@acemarke/diffloupe 0.5.0 → 0.5.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.
Files changed (3) hide show
  1. package/README.md +11 -7
  2. package/dist/index.js +214 -214
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,38 +1,38 @@
1
1
  #!/usr/bin/env -S bun --no-env-file
2
2
  // @bun
3
- var nR=Object.create;var{getPrototypeOf:rR,defineProperty:tc,getOwnPropertyNames:iR}=Object;var Zf=Object.prototype.hasOwnProperty;function sR(e){return this[e]}var oR,aR,ko=(e,t,n)=>{var r=e!=null&&typeof e==="object";if(r){var s=t?oR??=new WeakMap:aR??=new WeakMap,o=s.get(e);if(o)return o}n=e!=null?nR(rR(e)):{};let a=t||!e||!e.__esModule||!Zf.call(e,"default")?tc(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let l of iR(e))if(!Zf.call(a,l))tc(a,l,{get:sR.bind(e,l),enumerable:!0})}if(r)s.set(e,a);return a};var gr=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var qe=(e,t,n)=>()=>{if(e)try{t=e(e=0)}catch(r){n=[r]}if(n)throw n[0];return t};var lR=(e,t,n)=>{for(var r in t)tc(e,r,{get:t[r],set:n[r],enumerable:!0,configurable:!0})},Gi=import.meta.require;var Vi=gr(function(cR){class nc 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}}class Qf extends nc{constructor(e){super(1,"commander.invalidArgument",e);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}cR.CommanderError=nc;cR.InvalidArgumentError=Qf});var Eo=gr(function(hR){var{InvalidArgumentError:fR}=Vi();class ep{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}if(this._name.endsWith("..."))this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_collectValue(e,t){if(t===this.defaultValue||!Array.isArray(t))return[e];return t.push(e),t}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 fR(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(t,n);return t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function pR(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}hR.Argument=ep;hR.humanReadableArgName=pR});var rc=gr(function(wR){var{humanReadableArgName:_R}=Eo();class tp{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter((r)=>!r._hidden),n=e._getHelpCommand();if(n&&!n._hidden)t.push(n);if(this.sortSubcommands)t.sort((r,s)=>r.name().localeCompare(s.name()));return t}compareOptions(e,t){let n=(r)=>r.short?r.short.replace(/^-/,""):r.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter((r)=>!r.hidden),n=e._getHelpOption();if(n&&!n.hidden){let r=n.short&&e._findOption(n.short),s=n.long&&e._findOption(n.long);if(!r&&!s)t.push(n);else if(n.long&&!s)t.push(e.createOption(n.long,n.description));else if(n.short&&!r)t.push(e.createOption(n.short,n.description))}if(this.sortOptions)t.sort(this.compareOptions);return t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let r=n.options.filter((s)=>!s.hidden);t.push(...r)}if(this.sortOptions)t.sort(this.compareOptions);return t}visibleArguments(e){if(e._argsDescription)e.registeredArguments.forEach((t)=>{t.description=t.description||e._argsDescription[t.name()]||""});if(e.registeredArguments.find((t)=>t.description))return e.registeredArguments;return[]}subcommandTerm(e){let t=e.registeredArguments.map((n)=>_R(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,r)=>Math.max(n,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(r)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,r)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(r)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,r)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(r)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,r)=>Math.max(n,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(r)))),0)}commandUsage(e){let t=e._name;if(e._aliases[0])t=t+"|"+e._aliases[0];let n="";for(let r=e.parent;r;r=r.parent)n=r.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices)t.push(`choices: ${e.argChoices.map((n)=>JSON.stringify(n)).join(", ")}`);if(e.defaultValue!==void 0){if(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==="boolean")t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`)}if(e.presetArg!==void 0&&e.optional)t.push(`preset: ${JSON.stringify(e.presetArg)}`);if(e.envVar!==void 0)t.push(`env: ${e.envVar}`);if(t.length>0){let n=`(${t.join(", ")})`;if(e.description)return`${e.description} ${n}`;return n}return e.description}argumentDescription(e){let t=[];if(e.argChoices)t.push(`choices: ${e.argChoices.map((n)=>JSON.stringify(n)).join(", ")}`);if(e.defaultValue!==void 0)t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`);if(t.length>0){let n=`(${t.join(", ")})`;if(e.description)return`${e.description} ${n}`;return n}return e.description}formatItemList(e,t,n){if(t.length===0)return[];return[n.styleTitle(e),...t,""]}groupItems(e,t,n){let r=new Map;return e.forEach((s)=>{let o=n(s);if(!r.has(o))r.set(o,[])}),t.forEach((s)=>{let o=n(s);if(!r.has(o))r.set(o,[]);r.get(o).push(s)}),r}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth??80;function s(d,f){return t.formatItem(d,n,f,t)}let o=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],a=t.commandDescription(e);if(a.length>0)o=o.concat([t.boxWrap(t.styleCommandDescription(a),r),""]);let l=t.visibleArguments(e).map((d)=>s(t.styleArgumentTerm(t.argumentTerm(d)),t.styleArgumentDescription(t.argumentDescription(d))));if(o=o.concat(this.formatItemList("Arguments:",l,t)),this.groupItems(e.options,t.visibleOptions(e),(d)=>d.helpGroupHeading??"Options:").forEach((d,f)=>{let p=d.map((h)=>s(t.styleOptionTerm(t.optionTerm(h)),t.styleOptionDescription(t.optionDescription(h))));o=o.concat(this.formatItemList(f,p,t))}),t.showGlobalOptions){let d=t.visibleGlobalOptions(e).map((f)=>s(t.styleOptionTerm(t.optionTerm(f)),t.styleOptionDescription(t.optionDescription(f))));o=o.concat(this.formatItemList("Global Options:",d,t))}return this.groupItems(e.commands,t.visibleCommands(e),(d)=>d.helpGroup()||"Commands:").forEach((d,f)=>{let p=d.map((h)=>s(t.styleSubcommandTerm(t.subcommandTerm(h)),t.styleSubcommandDescription(t.subcommandDescription(h))));o=o.concat(this.formatItemList(f,p,t))}),o.join(`
4
- `)}displayWidth(e){return np(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map((t)=>{if(t==="[options]")return this.styleOptionText(t);if(t==="[command]")return this.styleSubcommandText(t);if(t[0]==="["||t[0]==="<")return this.styleArgumentText(t);return this.styleCommandText(t)}).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map((t)=>{if(t==="[options]")return this.styleOptionText(t);if(t[0]==="["||t[0]==="<")return this.styleArgumentText(t);return this.styleSubcommandText(t)}).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,r){let o=" ".repeat(2);if(!n)return o+e;let a=e.padEnd(t+e.length-r.displayWidth(e)),l=2,u=(this.helpWidth??80)-t-l-2,d;if(u<this.minWidthToWrap||r.preformatted(n))d=n;else d=r.boxWrap(n,u).replace(/\n/g,`
3
+ var $S=Object.create;var{getPrototypeOf:kS,defineProperty:dc,getOwnPropertyNames:ES}=Object;var dp=Object.prototype.hasOwnProperty;function CS(e){return this[e]}var AS,OS,Do=(e,t,n)=>{var r=e!=null&&typeof e==="object";if(r){var s=t?AS??=new WeakMap:OS??=new WeakMap,o=s.get(e);if(o)return o}n=e!=null?$S(kS(e)):{};let a=t||!e||!e.__esModule||!dp.call(e,"default")?dc(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let l of ES(e))if(!dp.call(a,l))dc(a,l,{get:CS.bind(e,l),enumerable:!0})}if(r)s.set(e,a);return a};var yr=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var He=(e,t,n)=>()=>{if(e)try{t=e(e=0)}catch(r){n=[r]}if(n)throw n[0];return t};var IS=(e,t,n)=>{for(var r in t)dc(e,r,{get:t[r],set:n[r],enumerable:!0,configurable:!0})},Yi=import.meta.require;var Zi=yr(function(PS){class fc 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}}class fp extends fc{constructor(e){super(1,"commander.invalidArgument",e);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}PS.CommanderError=fc;PS.InvalidArgumentError=fp});var No=yr(function(FS){var{InvalidArgumentError:DS}=Zi();class pp{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}if(this._name.endsWith("..."))this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_collectValue(e,t){if(t===this.defaultValue||!Array.isArray(t))return[e];return t.push(e),t}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 DS(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(t,n);return t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function NS(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}FS.Argument=pp;FS.humanReadableArgName=NS});var pc=yr(function(BS){var{humanReadableArgName:US}=No();class hp{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter((r)=>!r._hidden),n=e._getHelpCommand();if(n&&!n._hidden)t.push(n);if(this.sortSubcommands)t.sort((r,s)=>r.name().localeCompare(s.name()));return t}compareOptions(e,t){let n=(r)=>r.short?r.short.replace(/^-/,""):r.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter((r)=>!r.hidden),n=e._getHelpOption();if(n&&!n.hidden){let r=n.short&&e._findOption(n.short),s=n.long&&e._findOption(n.long);if(!r&&!s)t.push(n);else if(n.long&&!s)t.push(e.createOption(n.long,n.description));else if(n.short&&!r)t.push(e.createOption(n.short,n.description))}if(this.sortOptions)t.sort(this.compareOptions);return t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let r=n.options.filter((s)=>!s.hidden);t.push(...r)}if(this.sortOptions)t.sort(this.compareOptions);return t}visibleArguments(e){if(e._argsDescription)e.registeredArguments.forEach((t)=>{t.description=t.description||e._argsDescription[t.name()]||""});if(e.registeredArguments.find((t)=>t.description))return e.registeredArguments;return[]}subcommandTerm(e){let t=e.registeredArguments.map((n)=>US(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,r)=>Math.max(n,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(r)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,r)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(r)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,r)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(r)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,r)=>Math.max(n,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(r)))),0)}commandUsage(e){let t=e._name;if(e._aliases[0])t=t+"|"+e._aliases[0];let n="";for(let r=e.parent;r;r=r.parent)n=r.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices)t.push(`choices: ${e.argChoices.map((n)=>JSON.stringify(n)).join(", ")}`);if(e.defaultValue!==void 0){if(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==="boolean")t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`)}if(e.presetArg!==void 0&&e.optional)t.push(`preset: ${JSON.stringify(e.presetArg)}`);if(e.envVar!==void 0)t.push(`env: ${e.envVar}`);if(t.length>0){let n=`(${t.join(", ")})`;if(e.description)return`${e.description} ${n}`;return n}return e.description}argumentDescription(e){let t=[];if(e.argChoices)t.push(`choices: ${e.argChoices.map((n)=>JSON.stringify(n)).join(", ")}`);if(e.defaultValue!==void 0)t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`);if(t.length>0){let n=`(${t.join(", ")})`;if(e.description)return`${e.description} ${n}`;return n}return e.description}formatItemList(e,t,n){if(t.length===0)return[];return[n.styleTitle(e),...t,""]}groupItems(e,t,n){let r=new Map;return e.forEach((s)=>{let o=n(s);if(!r.has(o))r.set(o,[])}),t.forEach((s)=>{let o=n(s);if(!r.has(o))r.set(o,[]);r.get(o).push(s)}),r}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth??80;function s(d,f){return t.formatItem(d,n,f,t)}let o=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],a=t.commandDescription(e);if(a.length>0)o=o.concat([t.boxWrap(t.styleCommandDescription(a),r),""]);let l=t.visibleArguments(e).map((d)=>s(t.styleArgumentTerm(t.argumentTerm(d)),t.styleArgumentDescription(t.argumentDescription(d))));if(o=o.concat(this.formatItemList("Arguments:",l,t)),this.groupItems(e.options,t.visibleOptions(e),(d)=>d.helpGroupHeading??"Options:").forEach((d,f)=>{let p=d.map((h)=>s(t.styleOptionTerm(t.optionTerm(h)),t.styleOptionDescription(t.optionDescription(h))));o=o.concat(this.formatItemList(f,p,t))}),t.showGlobalOptions){let d=t.visibleGlobalOptions(e).map((f)=>s(t.styleOptionTerm(t.optionTerm(f)),t.styleOptionDescription(t.optionDescription(f))));o=o.concat(this.formatItemList("Global Options:",d,t))}return this.groupItems(e.commands,t.visibleCommands(e),(d)=>d.helpGroup()||"Commands:").forEach((d,f)=>{let p=d.map((h)=>s(t.styleSubcommandTerm(t.subcommandTerm(h)),t.styleSubcommandDescription(t.subcommandDescription(h))));o=o.concat(this.formatItemList(f,p,t))}),o.join(`
4
+ `)}displayWidth(e){return mp(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map((t)=>{if(t==="[options]")return this.styleOptionText(t);if(t==="[command]")return this.styleSubcommandText(t);if(t[0]==="["||t[0]==="<")return this.styleArgumentText(t);return this.styleCommandText(t)}).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map((t)=>{if(t==="[options]")return this.styleOptionText(t);if(t[0]==="["||t[0]==="<")return this.styleArgumentText(t);return this.styleSubcommandText(t)}).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,r){let o=" ".repeat(2);if(!n)return o+e;let a=e.padEnd(t+e.length-r.displayWidth(e)),l=2,u=(this.helpWidth??80)-t-l-2,d;if(u<this.minWidthToWrap||r.preformatted(n))d=n;else d=r.boxWrap(n,u).replace(/\n/g,`
5
5
  `+" ".repeat(t+l));return o+a+" ".repeat(l)+d.replace(/\n/g,`
6
6
  ${o}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),r=/[\s]*[^\s]+/g,s=[];return n.forEach((o)=>{let a=o.match(r);if(a===null){s.push("");return}let l=[a.shift()],c=this.displayWidth(l[0]);a.forEach((u)=>{let d=this.displayWidth(u);if(c+d<=t){l.push(u),c+=d;return}s.push(l.join(""));let f=u.trimStart();l=[f],c=this.displayWidth(f)}),s.push(l.join(""))}),s.join(`
7
- `)}}function np(e){let t=/\x1b\[\d*(;\d*)*m/g;return e.replace(t,"")}wR.Help=tp;wR.stripColor=np});var ic=gr(function(RR){var{InvalidArgumentError:vR}=Vi();class ip{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=xR(e);if(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,this.helpGroupHeading=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;if(typeof e==="string")t={[e]:!0};return 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}_collectValue(e,t){if(t===this.defaultValue||!Array.isArray(t))return[e];return t.push(e),t}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new vR(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(t,n);return t},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return rp(this.name().replace(/^no-/,""));return rp(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class sp{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach((t)=>{if(t.negate)this.negativeOptions.set(t.attributeName(),t);else this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,n)=>{if(this.positiveOptions.has(n))this.dualOptions.add(n)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let r=this.negativeOptions.get(n).presetArg,s=r!==void 0?r:!1;return t.negate===(s===e)}}function rp(e){return e.split("-").reduce((t,n)=>t+n[0].toUpperCase()+n.slice(1))}function xR(e){let t,n,r=/^-[^-]$/,s=/^--[^-]/,o=e.split(/[ |,]+/).concat("guard");if(r.test(o[0]))t=o.shift();if(s.test(o[0]))n=o.shift();if(!t&&r.test(o[0]))t=o.shift();if(!t&&s.test(o[0]))t=n,n=o.shift();if(o[0].startsWith("-")){let a=o[0],l=`option creation failed due to '${a}' in option flags '${e}'`;if(/^-[^-][^-]/.test(a))throw Error(`${l}
7
+ `)}}function mp(e){let t=/\x1b\[\d*(;\d*)*m/g;return e.replace(t,"")}BS.Help=hp;BS.stripColor=mp});var hc=yr(function(WS){var{InvalidArgumentError:KS}=Zi();class _p{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=GS(e);if(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,this.helpGroupHeading=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;if(typeof e==="string")t={[e]:!0};return 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}_collectValue(e,t){if(t===this.defaultValue||!Array.isArray(t))return[e];return t.push(e),t}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new KS(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(t,n);return t},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return gp(this.name().replace(/^no-/,""));return gp(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class wp{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach((t)=>{if(t.negate)this.negativeOptions.set(t.attributeName(),t);else this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,n)=>{if(this.positiveOptions.has(n))this.dualOptions.add(n)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let r=this.negativeOptions.get(n).presetArg,s=r!==void 0?r:!1;return t.negate===(s===e)}}function gp(e){return e.split("-").reduce((t,n)=>t+n[0].toUpperCase()+n.slice(1))}function GS(e){let t,n,r=/^-[^-]$/,s=/^--[^-]/,o=e.split(/[ |,]+/).concat("guard");if(r.test(o[0]))t=o.shift();if(s.test(o[0]))n=o.shift();if(!t&&r.test(o[0]))t=o.shift();if(!t&&s.test(o[0]))t=n,n=o.shift();if(o[0].startsWith("-")){let a=o[0],l=`option creation failed due to '${a}' in option flags '${e}'`;if(/^-[^-][^-]/.test(a))throw Error(`${l}
8
8
  - a short flag is a single dash and a single character
9
9
  - either use a single dash and a single character (for a short flag)
10
10
  - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(r.test(a))throw Error(`${l}
11
11
  - too many short flags`);if(s.test(a))throw Error(`${l}
12
12
  - too many long flags`);throw Error(`${l}
13
- - unrecognised flag format`)}if(t===void 0&&n===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}RR.Option=ip;RR.DualOptions=sp});var op=gr(function(AR){function kR(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let n=[];for(let r=0;r<=e.length;r++)n[r]=[r];for(let r=0;r<=t.length;r++)n[0][r]=r;for(let r=1;r<=t.length;r++)for(let s=1;s<=e.length;s++){let o=1;if(e[s-1]===t[r-1])o=0;else o=1;if(n[s][r]=Math.min(n[s-1][r]+1,n[s][r-1]+1,n[s-1][r-1]+o),s>1&&r>1&&e[s-1]===t[r-2]&&e[s-2]===t[r-1])n[s][r]=Math.min(n[s][r],n[s-2][r-2]+1)}return n[e.length][t.length]}function ER(e,t){if(!t||t.length===0)return"";t=Array.from(new Set(t));let n=e.startsWith("--");if(n)e=e.slice(2),t=t.map((a)=>a.slice(2));let r=[],s=3,o=0.4;if(t.forEach((a)=>{if(a.length<=1)return;let l=kR(e,a),c=Math.max(e.length,a.length);if((c-l)/c>o){if(l<s)s=l,r=[a];else if(l===s)r.push(a)}}),r.sort((a,l)=>a.localeCompare(l)),n)r=r.map((a)=>`--${a}`);if(r.length>1)return`
13
+ - unrecognised flag format`)}if(t===void 0&&n===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}WS.Option=_p;WS.DualOptions=wp});var yp=yr(function(YS){function JS(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let n=[];for(let r=0;r<=e.length;r++)n[r]=[r];for(let r=0;r<=t.length;r++)n[0][r]=r;for(let r=1;r<=t.length;r++)for(let s=1;s<=e.length;s++){let o=1;if(e[s-1]===t[r-1])o=0;else o=1;if(n[s][r]=Math.min(n[s-1][r]+1,n[s][r-1]+1,n[s-1][r-1]+o),s>1&&r>1&&e[s-1]===t[r-2]&&e[s-2]===t[r-1])n[s][r]=Math.min(n[s][r],n[s-2][r-2]+1)}return n[e.length][t.length]}function XS(e,t){if(!t||t.length===0)return"";t=Array.from(new Set(t));let n=e.startsWith("--");if(n)e=e.slice(2),t=t.map((a)=>a.slice(2));let r=[],s=3,o=0.4;if(t.forEach((a)=>{if(a.length<=1)return;let l=JS(e,a),c=Math.max(e.length,a.length);if((c-l)/c>o){if(l<s)s=l,r=[a];else if(l===s)r.push(a)}}),r.sort((a,l)=>a.localeCompare(l)),n)r=r.map((a)=>`--${a}`);if(r.length>1)return`
14
14
  (Did you mean one of ${r.join(", ")}?)`;if(r.length===1)return`
15
- (Did you mean ${r[0]}?)`;return""}AR.suggestSimilar=ER});var up=gr(function(NR){var OR=Gi("events").EventEmitter,Hr=Gi("child_process"),Ze=Gi("path"),Wn=Gi("fs"),J=Gi("process"),{Argument:IR,humanReadableArgName:PR}=Eo(),{CommanderError:sc}=Vi(),{Help:MR,stripColor:TR}=rc(),{Option:ap,DualOptions:FR}=ic(),{suggestSimilar:lp}=op();class ac extends OR{constructor(e){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,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._savedState=null,this._outputConfiguration={writeOut:(t)=>J.stdout.write(t),writeErr:(t)=>J.stderr.write(t),outputError:(t,n)=>n(t),getOutHelpWidth:()=>J.stdout.isTTY?J.stdout.columns:void 0,getErrHelpWidth:()=>J.stderr.isTTY?J.stderr.columns:void 0,getOutHasColors:()=>oc()??(J.stdout.isTTY&&J.stdout.hasColors?.()),getErrHasColors:()=>oc()??(J.stderr.isTTY&&J.stderr.hasColors?.()),stripColor:(t)=>TR(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}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 r=t,s=n;if(typeof r==="object"&&r!==null)s=r,r=null;s=s||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(o);if(r)l.description(r),l._executableHandler=!0;if(s.isDefault)this._defaultCommandName=l._name;if(l._hidden=!!(s.noHelp||s.hidden),l._executableFile=s.executableFile||null,a)l.arguments(a);if(this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),r)return this;return l}createCommand(e){return new ac(e)}createHelp(){return Object.assign(new MR,this.configureHelp())}configureHelp(e){if(e===void 0)return this._helpConfiguration;return this._helpConfiguration=e,this}configureOutput(e){if(e===void 0)return this._outputConfiguration;return this._outputConfiguration={...this._outputConfiguration,...e},this}showHelpAfterError(e=!0){if(typeof e!=="string")e=!!e;return this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw Error(`Command passed to .addCommand() must have a name
16
- - specify the name in Command constructor or using .name()`);if(t=t||{},t.isDefault)this._defaultCommandName=e._name;if(t.noHelp||t.hidden)e._hidden=!0;return this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new IR(e,t)}argument(e,t,n,r){let s=this.createArgument(e,t);if(typeof n==="function")s.default(r).argParser(n);else s.default(n);return this.addArgument(s),this}arguments(e){return e.trim().split(/ +/).forEach((t)=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t?.variadic)throw Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw 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"){if(this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup)this._initCommandGroup(this._getHelpCommand());return this}let n=e??"help [command]",[,r,s]=n.match(/([^ ]+) *(.*)/),o=t??"display help for command",a=this.createCommand(r);if(a.helpOption(!1),s)a.arguments(s);if(o)a.description(o);if(this._addImplicitHelpCommand=!0,this._helpCommand=a,e||t)this._initCommandGroup(a);return this}addHelpCommand(e,t){if(typeof e!=="object")return this.helpCommand(e,t),this;return this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook(e,t){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw Error(`Unexpected value for event passed to hook : '${e}'.
17
- Expecting one of '${n.join("', '")}'`);if(this._lifeCycleHooks[e])this._lifeCycleHooks[e].push(t);else this._lifeCycleHooks[e]=[t];return this}exitOverride(e){if(e)this._exitCallback=e;else this._exitCallback=(t)=>{if(t.code!=="commander.executeSubCommandAsync")throw t};return this}_exit(e,t,n){if(this._exitCallback)this._exitCallback(new sc(e,t,n));J.exit(e)}action(e){let t=(n)=>{let r=this.registeredArguments.length,s=n.slice(0,r);if(this._storeOptionsAsProperties)s[r]=this;else s[r]=this.opts();return s.push(this),e.apply(this,s)};return this._actionHandler=t,this}createOption(e,t){return new ap(e,t)}_callParseArg(e,t,n,r){try{return e.parseArg(t,n)}catch(s){if(s.code==="commander.invalidArgument"){let o=`${r} ${s.message}`;this.error(o,{exitCode:s.exitCode,code:s.code})}throw s}}_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 Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
18
- - already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=(r)=>[r.name()].concat(r.aliases()),n=t(e).find((r)=>this._findCommand(r));if(n){let r=t(this._findCommand(n)).join("|"),s=t(e).join("|");throw Error(`cannot add command '${s}' as already have command '${r}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let s=e.long.replace(/^--no-/,"--");if(!this._findOption(s))this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else if(e.defaultValue!==void 0)this.setOptionValueWithSource(n,e.defaultValue,"default");let r=(s,o,a)=>{if(s==null&&e.presetArg!==void 0)s=e.presetArg;let l=this.getOptionValue(n);if(s!==null&&e.parseArg)s=this._callParseArg(e,s,l,o);else if(s!==null&&e.variadic)s=e._collectValue(s,l);if(s==null)if(e.negate)s=!1;else if(e.isBoolean()||e.optional)s=!0;else s="";this.setOptionValueWithSource(n,s,a)};if(this.on("option:"+t,(s)=>{let o=`error: option '${e.flags}' argument '${s}' is invalid.`;r(s,o,"cli")}),e.envVar)this.on("optionEnv:"+t,(s)=>{let o=`error: option '${e.flags}' value '${s}' from env '${e.envVar}' is invalid.`;r(s,o,"env")});return this}_optionEx(e,t,n,r,s){if(typeof t==="object"&&t instanceof ap)throw 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 r==="function")o.default(s).argParser(r);else if(r instanceof RegExp){let a=r;r=(l,c)=>{let u=a.exec(l);return u?u[0]:c},o.default(s).argParser(r)}else o.default(r);return this.addOption(o)}option(e,t,n,r){return this._optionEx({},e,t,n,r)}requiredOption(e,t,n,r){return this._optionEx({mandatory:!0},e,t,n,r)}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 Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){if(this._storeOptionsAsProperties)return this[e];return this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){if(this._storeOptionsAsProperties)this[e]=t;else this._optionValues[e]=t;return this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach((n)=>{if(n.getOptionValueSource(e)!==void 0)t=n.getOptionValueSource(e)}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){if(J.versions?.electron)t.from="electron";let r=J.execArgv??[];if(r.includes("-e")||r.includes("--eval")||r.includes("-p")||r.includes("--print"))t.from="eval"}if(e===void 0)e=J.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":if(J.defaultApp)this._scriptPath=e[1],n=e.slice(2);else n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw Error(`unexpected parse option { from: '${t.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){if(this._savedState===null)this.saveStateBeforeParse();else this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
19
- - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,n){if(Wn.existsSync(e))return;let r=t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",s=`'${e}' does not exist
15
+ (Did you mean ${r[0]}?)`;return""}YS.suggestSimilar=XS});var Sp=yr(function(sR){var QS=Yi("events").EventEmitter,Vr=Yi("child_process"),Ze=Yi("path"),Vn=Yi("fs"),J=Yi("process"),{Argument:eR,humanReadableArgName:tR}=No(),{CommanderError:mc}=Zi(),{Help:nR,stripColor:rR}=pc(),{Option:bp,DualOptions:iR}=hc(),{suggestSimilar:vp}=yp();class _c extends QS{constructor(e){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,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._savedState=null,this._outputConfiguration={writeOut:(t)=>J.stdout.write(t),writeErr:(t)=>J.stderr.write(t),outputError:(t,n)=>n(t),getOutHelpWidth:()=>J.stdout.isTTY?J.stdout.columns:void 0,getErrHelpWidth:()=>J.stderr.isTTY?J.stderr.columns:void 0,getOutHasColors:()=>gc()??(J.stdout.isTTY&&J.stdout.hasColors?.()),getErrHasColors:()=>gc()??(J.stderr.isTTY&&J.stderr.hasColors?.()),stripColor:(t)=>rR(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}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 r=t,s=n;if(typeof r==="object"&&r!==null)s=r,r=null;s=s||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(o);if(r)l.description(r),l._executableHandler=!0;if(s.isDefault)this._defaultCommandName=l._name;if(l._hidden=!!(s.noHelp||s.hidden),l._executableFile=s.executableFile||null,a)l.arguments(a);if(this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),r)return this;return l}createCommand(e){return new _c(e)}createHelp(){return Object.assign(new nR,this.configureHelp())}configureHelp(e){if(e===void 0)return this._helpConfiguration;return this._helpConfiguration=e,this}configureOutput(e){if(e===void 0)return this._outputConfiguration;return this._outputConfiguration={...this._outputConfiguration,...e},this}showHelpAfterError(e=!0){if(typeof e!=="string")e=!!e;return this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw Error(`Command passed to .addCommand() must have a name
16
+ - specify the name in Command constructor or using .name()`);if(t=t||{},t.isDefault)this._defaultCommandName=e._name;if(t.noHelp||t.hidden)e._hidden=!0;return this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new eR(e,t)}argument(e,t,n,r){let s=this.createArgument(e,t);if(typeof n==="function")s.default(r).argParser(n);else s.default(n);return this.addArgument(s),this}arguments(e){return e.trim().split(/ +/).forEach((t)=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t?.variadic)throw Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw 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"){if(this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup)this._initCommandGroup(this._getHelpCommand());return this}let n=e??"help [command]",[,r,s]=n.match(/([^ ]+) *(.*)/),o=t??"display help for command",a=this.createCommand(r);if(a.helpOption(!1),s)a.arguments(s);if(o)a.description(o);if(this._addImplicitHelpCommand=!0,this._helpCommand=a,e||t)this._initCommandGroup(a);return this}addHelpCommand(e,t){if(typeof e!=="object")return this.helpCommand(e,t),this;return this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook(e,t){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw Error(`Unexpected value for event passed to hook : '${e}'.
17
+ Expecting one of '${n.join("', '")}'`);if(this._lifeCycleHooks[e])this._lifeCycleHooks[e].push(t);else this._lifeCycleHooks[e]=[t];return this}exitOverride(e){if(e)this._exitCallback=e;else this._exitCallback=(t)=>{if(t.code!=="commander.executeSubCommandAsync")throw t};return this}_exit(e,t,n){if(this._exitCallback)this._exitCallback(new mc(e,t,n));J.exit(e)}action(e){let t=(n)=>{let r=this.registeredArguments.length,s=n.slice(0,r);if(this._storeOptionsAsProperties)s[r]=this;else s[r]=this.opts();return s.push(this),e.apply(this,s)};return this._actionHandler=t,this}createOption(e,t){return new bp(e,t)}_callParseArg(e,t,n,r){try{return e.parseArg(t,n)}catch(s){if(s.code==="commander.invalidArgument"){let o=`${r} ${s.message}`;this.error(o,{exitCode:s.exitCode,code:s.code})}throw s}}_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 Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
18
+ - already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=(r)=>[r.name()].concat(r.aliases()),n=t(e).find((r)=>this._findCommand(r));if(n){let r=t(this._findCommand(n)).join("|"),s=t(e).join("|");throw Error(`cannot add command '${s}' as already have command '${r}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let s=e.long.replace(/^--no-/,"--");if(!this._findOption(s))this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else if(e.defaultValue!==void 0)this.setOptionValueWithSource(n,e.defaultValue,"default");let r=(s,o,a)=>{if(s==null&&e.presetArg!==void 0)s=e.presetArg;let l=this.getOptionValue(n);if(s!==null&&e.parseArg)s=this._callParseArg(e,s,l,o);else if(s!==null&&e.variadic)s=e._collectValue(s,l);if(s==null)if(e.negate)s=!1;else if(e.isBoolean()||e.optional)s=!0;else s="";this.setOptionValueWithSource(n,s,a)};if(this.on("option:"+t,(s)=>{let o=`error: option '${e.flags}' argument '${s}' is invalid.`;r(s,o,"cli")}),e.envVar)this.on("optionEnv:"+t,(s)=>{let o=`error: option '${e.flags}' value '${s}' from env '${e.envVar}' is invalid.`;r(s,o,"env")});return this}_optionEx(e,t,n,r,s){if(typeof t==="object"&&t instanceof bp)throw 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 r==="function")o.default(s).argParser(r);else if(r instanceof RegExp){let a=r;r=(l,c)=>{let u=a.exec(l);return u?u[0]:c},o.default(s).argParser(r)}else o.default(r);return this.addOption(o)}option(e,t,n,r){return this._optionEx({},e,t,n,r)}requiredOption(e,t,n,r){return this._optionEx({mandatory:!0},e,t,n,r)}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 Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){if(this._storeOptionsAsProperties)return this[e];return this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){if(this._storeOptionsAsProperties)this[e]=t;else this._optionValues[e]=t;return this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach((n)=>{if(n.getOptionValueSource(e)!==void 0)t=n.getOptionValueSource(e)}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){if(J.versions?.electron)t.from="electron";let r=J.execArgv??[];if(r.includes("-e")||r.includes("--eval")||r.includes("-p")||r.includes("--print"))t.from="eval"}if(e===void 0)e=J.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":if(J.defaultApp)this._scriptPath=e[1],n=e.slice(2);else n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw Error(`unexpected parse option { from: '${t.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){if(this._savedState===null)this.saveStateBeforeParse();else this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
19
+ - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,n){if(Vn.existsSync(e))return;let r=t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",s=`'${e}' does not exist
20
20
  - if '${n}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
21
21
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
22
- - ${r}`;throw Error(s)}_executeSubCommand(e,t){t=t.slice();let n=!1,r=[".js",".ts",".tsx",".mjs",".cjs"];function s(u,d){let f=Ze.resolve(u,d);if(Wn.existsSync(f))return f;if(r.includes(Ze.extname(d)))return;let p=r.find((h)=>Wn.existsSync(`${f}${h}`));if(p)return`${f}${p}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=Wn.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=Ze.resolve(Ze.dirname(u),a)}if(a){let u=s(a,o);if(!u&&!e._executableFile&&this._scriptPath){let d=Ze.basename(this._scriptPath,Ze.extname(this._scriptPath));if(d!==this._name)u=s(a,`${d}-${e._name}`)}o=u||o}n=r.includes(Ze.extname(o));let l;if(J.platform!=="win32")if(n)t.unshift(o),t=cp(J.execArgv).concat(t),l=Hr.spawn(J.argv[0],t,{stdio:"inherit"});else l=Hr.spawn(o,t,{stdio:"inherit"});else this._checkForMissingExecutable(o,a,e._name),t.unshift(o),t=cp(J.execArgv).concat(t),l=Hr.spawn(J.execPath,t,{stdio:"inherit"});if(!l.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((d)=>{J.on(d,()=>{if(l.killed===!1&&l.exitCode===null)l.kill(d)})});let c=this._exitCallback;l.on("close",(u)=>{if(u=u??1,!c)J.exit(u);else c(new sc(u,"commander.executeSubCommandAsync","(close)"))}),l.on("error",(u)=>{if(u.code==="ENOENT")this._checkForMissingExecutable(o,a,e._name);else if(u.code==="EACCES")throw Error(`'${o}' not executable`);if(!c)J.exit(1);else{let d=new sc(1,"commander.executeSubCommandAsync","(error)");d.nestedError=u,c(d)}}),this.runningCommand=l}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);if(!r)this.help({error:!0});r._prepareForParse();let s;return s=this._chainOrCallSubCommandHook(s,r,"preSubcommand"),s=this._chainOrCall(s,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),s}_dispatchHelpCommand(e){if(!e)this.help();let t=this._findCommand(e);if(t&&!t._executableHandler)t.help();return this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach((e,t)=>{if(e.required&&this.args[t]==null)this.missingArgument(e.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let e=(n,r,s)=>{let o=r;if(r!==null&&n.parseArg){let a=`error: command-argument value '${r}' is invalid for argument '${n.name()}'.`;o=this._callParseArg(n,r,s,a)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let s=n.defaultValue;if(n.variadic){if(r<this.args.length){if(s=this.args.slice(r),n.parseArg)s=s.reduce((o,a)=>e(n,a,o),n.defaultValue)}else if(s===void 0)s=[]}else if(r<this.args.length){if(s=this.args[r],n.parseArg)s=e(n,s,n.defaultValue)}t[r]=s}),this.processedArgs=t}_chainOrCall(e,t){if(e?.then&&typeof e.then==="function")return e.then(()=>t());return t()}_chainOrCallHooks(e,t){let n=e,r=[];if(this._getCommandAndAncestors().reverse().filter((s)=>s._lifeCycleHooks[t]!==void 0).forEach((s)=>{s._lifeCycleHooks[t].forEach((o)=>{r.push({hookedCommand:s,callback:o})})}),t==="postAction")r.reverse();return r.forEach((s)=>{n=this._chainOrCall(n,()=>s.callback(s.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;if(this._lifeCycleHooks[n]!==void 0)this._lifeCycleHooks[n].forEach((s)=>{r=this._chainOrCall(r,()=>s(this,t))});return r}_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);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{if(n.unknown.length>0)this.unknownOption(n.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let o;if(o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent)o=this._chainOrCall(o,()=>{this.parent.emit(s,e,t)});return o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent?.listenerCount(s))r(),this._processArguments(),this.parent.emit(s,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);if(this.listenerCount("command:*"))this.emit("command:*",e,t);else if(this.commands.length)this.unknownCommand();else r(),this._processArguments()}else if(this.commands.length)r(),this.help({error:!0});else r(),this._processArguments()}_findCommand(e){if(!e)return;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)=>{if(t.mandatory&&e.getOptionValue(t.attributeName())===void 0)e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter((n)=>{let r=n.attributeName();if(this.getOptionValue(r)===void 0)return!1;return this.getOptionValueSource(r)!=="default"});e.filter((n)=>n.conflictsWith.length>0).forEach((n)=>{let r=e.find((s)=>n.conflictsWith.includes(s.attributeName()));if(r)this._conflictingOption(n,r)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((e)=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t;function s(u){return u.length>1&&u[0]==="-"}let o=(u)=>{if(!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(u))return!1;return!this._getCommandAndAncestors().some((d)=>d.options.map((f)=>f.short).some((f)=>/^-\d$/.test(f)))},a=null,l=null,c=0;while(c<e.length||l){let u=l??e[c++];if(l=null,u==="--"){if(r===n)r.push(u);r.push(...e.slice(c));break}if(a&&(!s(u)||o(u))){this.emit(`option:${a.name()}`,u);continue}if(a=null,s(u)){let d=this._findOption(u);if(d){if(d.required){let f=e[c++];if(f===void 0)this.optionMissingArgument(d);this.emit(`option:${d.name()}`,f)}else if(d.optional){let f=null;if(c<e.length&&(!s(e[c])||o(e[c])))f=e[c++];this.emit(`option:${d.name()}`,f)}else this.emit(`option:${d.name()}`);a=d.variadic?d:null;continue}}if(u.length>2&&u[0]==="-"&&u[1]!=="-"){let d=this._findOption(`-${u[1]}`);if(d){if(d.required||d.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${d.name()}`,u.slice(2));else this.emit(`option:${d.name()}`),l=`-${u.slice(2)}`;continue}}if(/^--[^=]+=/.test(u)){let d=u.indexOf("="),f=this._findOption(u.slice(0,d));if(f&&(f.required||f.optional)){this.emit(`option:${f.name()}`,u.slice(d+1));continue}}if(r===t&&s(u)&&!(this.commands.length===0&&o(u)))r=n;if((this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(u)){t.push(u),n.push(...e.slice(c));break}else if(this._getHelpCommand()&&u===this._getHelpCommand().name()){t.push(u,...e.slice(c));break}else if(this._defaultCommandName){n.push(u,...e.slice(c));break}}if(this._passThroughOptions){r.push(u,...e.slice(c));break}r.push(u)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let r=this.options[n].attributeName();e[r]=r===this._versionOptionName?this._version:this[r]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){if(this._outputConfiguration.outputError(`${e}
22
+ - ${r}`;throw Error(s)}_executeSubCommand(e,t){t=t.slice();let n=!1,r=[".js",".ts",".tsx",".mjs",".cjs"];function s(u,d){let f=Ze.resolve(u,d);if(Vn.existsSync(f))return f;if(r.includes(Ze.extname(d)))return;let p=r.find((h)=>Vn.existsSync(`${f}${h}`));if(p)return`${f}${p}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=Vn.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=Ze.resolve(Ze.dirname(u),a)}if(a){let u=s(a,o);if(!u&&!e._executableFile&&this._scriptPath){let d=Ze.basename(this._scriptPath,Ze.extname(this._scriptPath));if(d!==this._name)u=s(a,`${d}-${e._name}`)}o=u||o}n=r.includes(Ze.extname(o));let l;if(J.platform!=="win32")if(n)t.unshift(o),t=xp(J.execArgv).concat(t),l=Vr.spawn(J.argv[0],t,{stdio:"inherit"});else l=Vr.spawn(o,t,{stdio:"inherit"});else this._checkForMissingExecutable(o,a,e._name),t.unshift(o),t=xp(J.execArgv).concat(t),l=Vr.spawn(J.execPath,t,{stdio:"inherit"});if(!l.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((d)=>{J.on(d,()=>{if(l.killed===!1&&l.exitCode===null)l.kill(d)})});let c=this._exitCallback;l.on("close",(u)=>{if(u=u??1,!c)J.exit(u);else c(new mc(u,"commander.executeSubCommandAsync","(close)"))}),l.on("error",(u)=>{if(u.code==="ENOENT")this._checkForMissingExecutable(o,a,e._name);else if(u.code==="EACCES")throw Error(`'${o}' not executable`);if(!c)J.exit(1);else{let d=new mc(1,"commander.executeSubCommandAsync","(error)");d.nestedError=u,c(d)}}),this.runningCommand=l}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);if(!r)this.help({error:!0});r._prepareForParse();let s;return s=this._chainOrCallSubCommandHook(s,r,"preSubcommand"),s=this._chainOrCall(s,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),s}_dispatchHelpCommand(e){if(!e)this.help();let t=this._findCommand(e);if(t&&!t._executableHandler)t.help();return this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach((e,t)=>{if(e.required&&this.args[t]==null)this.missingArgument(e.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let e=(n,r,s)=>{let o=r;if(r!==null&&n.parseArg){let a=`error: command-argument value '${r}' is invalid for argument '${n.name()}'.`;o=this._callParseArg(n,r,s,a)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let s=n.defaultValue;if(n.variadic){if(r<this.args.length){if(s=this.args.slice(r),n.parseArg)s=s.reduce((o,a)=>e(n,a,o),n.defaultValue)}else if(s===void 0)s=[]}else if(r<this.args.length){if(s=this.args[r],n.parseArg)s=e(n,s,n.defaultValue)}t[r]=s}),this.processedArgs=t}_chainOrCall(e,t){if(e?.then&&typeof e.then==="function")return e.then(()=>t());return t()}_chainOrCallHooks(e,t){let n=e,r=[];if(this._getCommandAndAncestors().reverse().filter((s)=>s._lifeCycleHooks[t]!==void 0).forEach((s)=>{s._lifeCycleHooks[t].forEach((o)=>{r.push({hookedCommand:s,callback:o})})}),t==="postAction")r.reverse();return r.forEach((s)=>{n=this._chainOrCall(n,()=>s.callback(s.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;if(this._lifeCycleHooks[n]!==void 0)this._lifeCycleHooks[n].forEach((s)=>{r=this._chainOrCall(r,()=>s(this,t))});return r}_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);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{if(n.unknown.length>0)this.unknownOption(n.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let o;if(o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent)o=this._chainOrCall(o,()=>{this.parent.emit(s,e,t)});return o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent?.listenerCount(s))r(),this._processArguments(),this.parent.emit(s,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);if(this.listenerCount("command:*"))this.emit("command:*",e,t);else if(this.commands.length)this.unknownCommand();else r(),this._processArguments()}else if(this.commands.length)r(),this.help({error:!0});else r(),this._processArguments()}_findCommand(e){if(!e)return;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)=>{if(t.mandatory&&e.getOptionValue(t.attributeName())===void 0)e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter((n)=>{let r=n.attributeName();if(this.getOptionValue(r)===void 0)return!1;return this.getOptionValueSource(r)!=="default"});e.filter((n)=>n.conflictsWith.length>0).forEach((n)=>{let r=e.find((s)=>n.conflictsWith.includes(s.attributeName()));if(r)this._conflictingOption(n,r)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((e)=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t;function s(u){return u.length>1&&u[0]==="-"}let o=(u)=>{if(!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(u))return!1;return!this._getCommandAndAncestors().some((d)=>d.options.map((f)=>f.short).some((f)=>/^-\d$/.test(f)))},a=null,l=null,c=0;while(c<e.length||l){let u=l??e[c++];if(l=null,u==="--"){if(r===n)r.push(u);r.push(...e.slice(c));break}if(a&&(!s(u)||o(u))){this.emit(`option:${a.name()}`,u);continue}if(a=null,s(u)){let d=this._findOption(u);if(d){if(d.required){let f=e[c++];if(f===void 0)this.optionMissingArgument(d);this.emit(`option:${d.name()}`,f)}else if(d.optional){let f=null;if(c<e.length&&(!s(e[c])||o(e[c])))f=e[c++];this.emit(`option:${d.name()}`,f)}else this.emit(`option:${d.name()}`);a=d.variadic?d:null;continue}}if(u.length>2&&u[0]==="-"&&u[1]!=="-"){let d=this._findOption(`-${u[1]}`);if(d){if(d.required||d.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${d.name()}`,u.slice(2));else this.emit(`option:${d.name()}`),l=`-${u.slice(2)}`;continue}}if(/^--[^=]+=/.test(u)){let d=u.indexOf("="),f=this._findOption(u.slice(0,d));if(f&&(f.required||f.optional)){this.emit(`option:${f.name()}`,u.slice(d+1));continue}}if(r===t&&s(u)&&!(this.commands.length===0&&o(u)))r=n;if((this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(u)){t.push(u),n.push(...e.slice(c));break}else if(this._getHelpCommand()&&u===this._getHelpCommand().name()){t.push(u,...e.slice(c));break}else if(this._defaultCommandName){n.push(u,...e.slice(c));break}}if(this._passThroughOptions){r.push(u,...e.slice(c));break}r.push(u)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let r=this.options[n].attributeName();e[r]=r===this._versionOptionName?this._version:this[r]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){if(this._outputConfiguration.outputError(`${e}
23
23
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
24
24
  `);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`
25
- `),this.outputHelp({error:!0});let n=t||{},r=n.exitCode||1,s=n.code||"commander.error";this._exit(r,s,e)}_parseOptionsEnv(){this.options.forEach((e)=>{if(e.envVar&&e.envVar in J.env){let t=e.attributeName();if(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))if(e.required||e.optional)this.emit(`optionEnv:${e.name()}`,J.env[e.envVar]);else this.emit(`optionEnv:${e.name()}`)}})}_parseOptionsImplied(){let e=new FR(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((r)=>!t(r)).forEach((r)=>{this.setOptionValueWithSource(r,n.implied[r],"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(),l=this.getOptionValue(a),c=this.options.find((d)=>d.negate&&a===d.attributeName()),u=this.options.find((d)=>!d.negate&&a===d.attributeName());if(c&&(c.presetArg===void 0&&l===!1||c.presetArg!==void 0&&l===c.presetArg))return c;return u||o},r=(o)=>{let a=n(o),l=a.attributeName();if(this.getOptionValueSource(l)==="env")return`environment variable '${a.envVar}'`;return`option '${a.flags}'`},s=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let r=[],s=this;do{let o=s.createHelp().visibleOptions(s).filter((a)=>a.long).map((a)=>a.long);r=r.concat(o),s=s.parent}while(s&&!s._enablePositionalOptions);t=lp(e,r)}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",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let r=[];this.createHelp().visibleCommands(this).forEach((s)=>{if(r.push(s.name()),s.alias())r.push(s.alias())}),t=lp(e,r)}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 r=this.createOption(t,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on("option:"+r.name(),()=>{this._outputConfiguration.writeOut(`${e}
26
- `),this._exit(0,"commander.version",e)}),this}description(e,t){if(e===void 0&&t===void 0)return this._description;if(this._description=e,t)this._argsDescription=t;return this}summary(e){if(e===void 0)return this._summary;return 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];if(e===t._name)throw Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let r=[n.name()].concat(n.aliases()).join("|");throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${r}'`)}return t._aliases.push(e),this}aliases(e){if(e===void 0)return this._aliases;return 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)=>PR(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){if(e===void 0)return this._name;return this._name=e,this}helpGroup(e){if(e===void 0)return this._helpGroupHeading??"";return this._helpGroupHeading=e,this}commandsGroup(e){if(e===void 0)return this._defaultCommandGroup??"";return this._defaultCommandGroup=e,this}optionsGroup(e){if(e===void 0)return this._defaultOptionGroup??"";return this._defaultOptionGroup=e,this}_initOptionGroup(e){if(this._defaultOptionGroup&&!e.helpGroupHeading)e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){if(this._defaultCommandGroup&&!e.helpGroup())e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=Ze.basename(e,Ze.extname(e)),this}executableDir(e){if(e===void 0)return this._executableDir;return this._executableDir=e,this}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let r=t.formatHelp(this,t);if(n.hasColors)return r;return this._outputConfiguration.stripColor(r)}_getOutputContext(e){e=e||{};let t=!!e.error,n,r,s;if(t)n=(a)=>this._outputConfiguration.writeErr(a),r=this._outputConfiguration.getErrHasColors(),s=this._outputConfiguration.getErrHelpWidth();else n=(a)=>this._outputConfiguration.writeOut(a),r=this._outputConfiguration.getOutHasColors(),s=this._outputConfiguration.getOutHelpWidth();return{error:t,write:(a)=>{if(!r)a=this._outputConfiguration.stripColor(a);return n(a)},hasColors:r,helpWidth:s}}outputHelp(e){let t;if(typeof e==="function")t=e,e=void 0;let n=this._getOutputContext(e),r={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach((o)=>o.emit("beforeAllHelp",r)),this.emit("beforeHelp",r);let s=this.helpInformation({error:n.error});if(t){if(s=t(s),typeof s!=="string"&&!Buffer.isBuffer(s))throw Error("outputHelp callback must return a string or a Buffer")}if(n.write(s),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",r),this._getCommandAndAncestors().forEach((o)=>o.emit("afterAllHelp",r))}helpOption(e,t){if(typeof e==="boolean"){if(e){if(this._helpOption===null)this._helpOption=void 0;if(this._defaultOptionGroup)this._initOptionGroup(this._getHelpOption())}else this._helpOption=null;return this}if(this._helpOption=this.createOption(e??"-h, --help",t??"display help for command"),e||t)this._initOptionGroup(this._helpOption);return this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(J.exitCode??0);if(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 Error(`Unexpected value for position to addHelpText.
25
+ `),this.outputHelp({error:!0});let n=t||{},r=n.exitCode||1,s=n.code||"commander.error";this._exit(r,s,e)}_parseOptionsEnv(){this.options.forEach((e)=>{if(e.envVar&&e.envVar in J.env){let t=e.attributeName();if(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))if(e.required||e.optional)this.emit(`optionEnv:${e.name()}`,J.env[e.envVar]);else this.emit(`optionEnv:${e.name()}`)}})}_parseOptionsImplied(){let e=new iR(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((r)=>!t(r)).forEach((r)=>{this.setOptionValueWithSource(r,n.implied[r],"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(),l=this.getOptionValue(a),c=this.options.find((d)=>d.negate&&a===d.attributeName()),u=this.options.find((d)=>!d.negate&&a===d.attributeName());if(c&&(c.presetArg===void 0&&l===!1||c.presetArg!==void 0&&l===c.presetArg))return c;return u||o},r=(o)=>{let a=n(o),l=a.attributeName();if(this.getOptionValueSource(l)==="env")return`environment variable '${a.envVar}'`;return`option '${a.flags}'`},s=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let r=[],s=this;do{let o=s.createHelp().visibleOptions(s).filter((a)=>a.long).map((a)=>a.long);r=r.concat(o),s=s.parent}while(s&&!s._enablePositionalOptions);t=vp(e,r)}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",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let r=[];this.createHelp().visibleCommands(this).forEach((s)=>{if(r.push(s.name()),s.alias())r.push(s.alias())}),t=vp(e,r)}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 r=this.createOption(t,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on("option:"+r.name(),()=>{this._outputConfiguration.writeOut(`${e}
26
+ `),this._exit(0,"commander.version",e)}),this}description(e,t){if(e===void 0&&t===void 0)return this._description;if(this._description=e,t)this._argsDescription=t;return this}summary(e){if(e===void 0)return this._summary;return 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];if(e===t._name)throw Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let r=[n.name()].concat(n.aliases()).join("|");throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${r}'`)}return t._aliases.push(e),this}aliases(e){if(e===void 0)return this._aliases;return 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)=>tR(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){if(e===void 0)return this._name;return this._name=e,this}helpGroup(e){if(e===void 0)return this._helpGroupHeading??"";return this._helpGroupHeading=e,this}commandsGroup(e){if(e===void 0)return this._defaultCommandGroup??"";return this._defaultCommandGroup=e,this}optionsGroup(e){if(e===void 0)return this._defaultOptionGroup??"";return this._defaultOptionGroup=e,this}_initOptionGroup(e){if(this._defaultOptionGroup&&!e.helpGroupHeading)e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){if(this._defaultCommandGroup&&!e.helpGroup())e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=Ze.basename(e,Ze.extname(e)),this}executableDir(e){if(e===void 0)return this._executableDir;return this._executableDir=e,this}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let r=t.formatHelp(this,t);if(n.hasColors)return r;return this._outputConfiguration.stripColor(r)}_getOutputContext(e){e=e||{};let t=!!e.error,n,r,s;if(t)n=(a)=>this._outputConfiguration.writeErr(a),r=this._outputConfiguration.getErrHasColors(),s=this._outputConfiguration.getErrHelpWidth();else n=(a)=>this._outputConfiguration.writeOut(a),r=this._outputConfiguration.getOutHasColors(),s=this._outputConfiguration.getOutHelpWidth();return{error:t,write:(a)=>{if(!r)a=this._outputConfiguration.stripColor(a);return n(a)},hasColors:r,helpWidth:s}}outputHelp(e){let t;if(typeof e==="function")t=e,e=void 0;let n=this._getOutputContext(e),r={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach((o)=>o.emit("beforeAllHelp",r)),this.emit("beforeHelp",r);let s=this.helpInformation({error:n.error});if(t){if(s=t(s),typeof s!=="string"&&!Buffer.isBuffer(s))throw Error("outputHelp callback must return a string or a Buffer")}if(n.write(s),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",r),this._getCommandAndAncestors().forEach((o)=>o.emit("afterAllHelp",r))}helpOption(e,t){if(typeof e==="boolean"){if(e){if(this._helpOption===null)this._helpOption=void 0;if(this._defaultOptionGroup)this._initOptionGroup(this._getHelpOption())}else this._helpOption=null;return this}if(this._helpOption=this.createOption(e??"-h, --help",t??"display help for command"),e||t)this._initOptionGroup(this._helpOption);return this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(J.exitCode??0);if(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 Error(`Unexpected value for position to addHelpText.
27
27
  Expecting one of '${n.join("', '")}'`);let r=`${e}Help`;return this.on(r,(s)=>{let o;if(typeof t==="function")o=t({error:s.error,command:s.command});else o=t;if(o)s.write(`${o}
28
- `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();if(t&&e.find((r)=>t.is(r)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function cp(e){return e.map((t)=>{if(!t.startsWith("--inspect"))return t;let n,r="127.0.0.1",s="9229",o;if((o=t.match(/^(--inspect(-brk)?)$/))!==null)n=o[1];else if((o=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(n=o[1],/^\d+$/.test(o[3]))s=o[3];else r=o[3];else if((o=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)n=o[1],r=o[3],s=o[4];if(n&&s!=="0")return`${n}=${r}:${parseInt(s)+1}`;return t})}function oc(){if(J.env.NO_COLOR||J.env.FORCE_COLOR==="0"||J.env.FORCE_COLOR==="false")return!1;if(J.env.FORCE_COLOR||J.env.CLICOLOR_FORCE!==void 0)return!0;return}NR.Command=ac;NR.useColor=oc});var zi=gr(function(zM,uc){var Oo=process||{},$p=Oo.argv||[],Co=Oo.env||{},qR=!(!!Co.NO_COLOR||$p.includes("--no-color"))&&(!!Co.FORCE_COLOR||$p.includes("--color")||Oo.platform==="win32"||(Oo.stdout||{}).isTTY&&Co.TERM!=="dumb"||!!Co.CI),HR=(e,t,n=e)=>(r)=>{let s=""+r,o=s.indexOf(t,e.length);return~o?e+KR(s,t,n,o)+t:e+s+t},KR=(e,t,n,r)=>{let s="",o=0;do s+=e.substring(o,r)+n,o=r+t.length,r=e.indexOf(t,o);while(~r);return s+e.substring(o)},kp=(e=qR)=>{let t=e?HR:()=>String;return{isColorSupported:e,reset:t("\x1B[0m","\x1B[0m"),bold:t("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:t("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:t("\x1B[3m","\x1B[23m"),underline:t("\x1B[4m","\x1B[24m"),inverse:t("\x1B[7m","\x1B[27m"),hidden:t("\x1B[8m","\x1B[28m"),strikethrough:t("\x1B[9m","\x1B[29m"),black:t("\x1B[30m","\x1B[39m"),red:t("\x1B[31m","\x1B[39m"),green:t("\x1B[32m","\x1B[39m"),yellow:t("\x1B[33m","\x1B[39m"),blue:t("\x1B[34m","\x1B[39m"),magenta:t("\x1B[35m","\x1B[39m"),cyan:t("\x1B[36m","\x1B[39m"),white:t("\x1B[37m","\x1B[39m"),gray:t("\x1B[90m","\x1B[39m"),bgBlack:t("\x1B[40m","\x1B[49m"),bgRed:t("\x1B[41m","\x1B[49m"),bgGreen:t("\x1B[42m","\x1B[49m"),bgYellow:t("\x1B[43m","\x1B[49m"),bgBlue:t("\x1B[44m","\x1B[49m"),bgMagenta:t("\x1B[45m","\x1B[49m"),bgCyan:t("\x1B[46m","\x1B[49m"),bgWhite:t("\x1B[47m","\x1B[49m"),blackBright:t("\x1B[90m","\x1B[39m"),redBright:t("\x1B[91m","\x1B[39m"),greenBright:t("\x1B[92m","\x1B[39m"),yellowBright:t("\x1B[93m","\x1B[39m"),blueBright:t("\x1B[94m","\x1B[39m"),magentaBright:t("\x1B[95m","\x1B[39m"),cyanBright:t("\x1B[96m","\x1B[39m"),whiteBright:t("\x1B[97m","\x1B[39m"),bgBlackBright:t("\x1B[100m","\x1B[49m"),bgRedBright:t("\x1B[101m","\x1B[49m"),bgGreenBright:t("\x1B[102m","\x1B[49m"),bgYellowBright:t("\x1B[103m","\x1B[49m"),bgBlueBright:t("\x1B[104m","\x1B[49m"),bgMagentaBright:t("\x1B[105m","\x1B[49m"),bgCyanBright:t("\x1B[106m","\x1B[49m"),bgWhiteBright:t("\x1B[107m","\x1B[49m")}};uc.exports=kp();uc.exports.createColors=kp});import{extname as eS}from"path";function Dt(e){return tS[eS(e).toLowerCase()]??null}var tS;var Ji=qe(()=>{tS={".ts":"typescript",".mts":"typescript",".cts":"typescript",".tsx":"tsx",".js":"tsx",".jsx":"tsx",".mjs":"tsx",".cjs":"tsx",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".c":"cpp",".h":"cpp",".hpp":"cpp",".hh":"cpp"}});import{existsSync as cS}from"fs";import uS from"os";import Fo from"path";function Qt(e,t){let n=process.env[e]?.trim();if(n===void 0||n==="")return t;let r=Number(n);if(!Number.isFinite(r)||r<=0)throw Error(`${e} must be a positive number, got "${process.env[e]}"`);return r}function Ho(e){if(e.provider!==void 0)fc=e.provider;if(e.model!==void 0){if($n=e.model,e.modelMerge===void 0&&process.env.REVIEW_MODEL_MERGE===void 0)yr=e.model}if(e.modelMerge!==void 0)yr=e.modelMerge;if(e.modelWalk!==void 0)kn=e.modelWalk;if(e.modelIntent!==void 0)Jr=e.modelIntent;if(e.effort!==void 0){if(zr=e.effort,e.effortAux===void 0&&process.env.REVIEW_EFFORT_AUX===void 0)Zt=e.effort}if(e.effortAux!==void 0)Zt=e.effortAux;if(e.sliceBudget!==void 0)gc=e.sliceBudget;if(e.mergeBudget!==void 0)_c=e.mergeBudget;if(e.walkBudget!==void 0)Yi=e.walkBudget;if(e.partBudget!==void 0)hc=e.partBudget;if(e.intentBudget!==void 0)mc=e.intentBudget;if(e.pool!==void 0)wc=e.pool;if(e.maxSlices!==void 0)br=e.maxSlices;if(e.maxSliceTokens!==void 0)Jn=e.maxSliceTokens;if(e.walkDiffTokens!==void 0)Zi=e.walkDiffTokens;if(e.maxSteps!==void 0)Do=e.maxSteps;if(e.deadlineMs!==void 0)pc=e.deadlineMs;if(e.grouping!==void 0)wr=e.grouping;if(e.artifacts!==void 0)ye=e.artifacts;if(e.out!==void 0)wt=e.out;if(e.extraExcludes!==void 0)Qi=e.extraExcludes;if(e.surfaces!==void 0)jo=e.surfaces;if(e.postMinSeverity!==void 0)Xr=e.postMinSeverity;if(e.dropQuestions!==void 0)Uo=e.dropQuestions;if(e.providers!==void 0)Bo=e.providers;if(e.childEnv!==void 0)yc=e.childEnv;if(e.authImport!==void 0)qo=e.authImport}function Zr(e){if(e.subject!==void 0)st=e.subject;if(e.releaseSubject!==void 0)No=e.releaseSubject;if(e.repoName!==void 0)yt=e.repoName;if(e.signal!==void 0)Yr=e.signal}function Ko(){st=process.cwd(),No=async()=>{},yt="this repository",Yr=void 0}var Vr,st,No=async()=>{},ye,Lp="opencode",fc,Do,pc,$n,zr,kn,yr,Jr,Zt,Yi,hc,mc,wr,gc,_c,wc,br,jp=2.4,Jn,Zi,Up,wt,yt="this repository",Lo,jo,Qi,Xr=null,Uo=!1,Bo,yc,qo="",Yr;var bt=qe(()=>{Vr=cS(Fo.join(import.meta.dir,"system.md"))?import.meta.dir:Fo.join(import.meta.dir,"review-core"),st=process.cwd(),ye=process.env.CODE_REVIEW_ARTIFACTS??Fo.join(process.cwd(),".code-review"),fc=process.env.REVIEW_PROVIDER??"anthropic",Do=Qt("REVIEW_MAX_STEPS",80),pc=Qt("REVIEW_DEADLINE_S",900)*1000,$n=process.env.REVIEW_MODEL??"claude-opus-5-5",zr=process.env.REVIEW_EFFORT??"medium",kn=process.env.REVIEW_MODEL_WALK??"claude-sonnet-5-5",yr=process.env.REVIEW_MODEL_MERGE??$n,Jr=process.env.REVIEW_MODEL_INTENT??"claude-haiku-5-5",Zt=process.env.REVIEW_EFFORT_AUX??zr;Yi=Qt("WALK_BUDGET_USD",2),hc=Qt("PART_BUDGET",0.6),mc=Qt("INTENT_BUDGET_USD",0.1),wr=process.env.REVIEW_GROUPING??"code";if(wr!=="code"&&wr!=="model")throw Error(`REVIEW_GROUPING must be "code" or "model", got "${wr}"`);gc=Qt("SLICE_BUDGET_USD",3),_c=Qt("MERGE_BUDGET_USD",3),wc=Qt("SLICE_POOL",6),br=Qt("MAX_SLICES",16),Jn=Qt("MAX_SLICE_TOKENS",42000),Zi=Qt("WALK_DIFF_TOKENS",1e5),Up=process.env.INLINE_MODE==="tier"?"tier":"none",wt=process.env.CODE_REVIEW_SCRATCH??Fo.join(uS.tmpdir(),"code-review-out"),Lo=Object.freeze({deploy:[],tooling:["^docs/","(^|/)[^/]*\\.config\\.[cm]?[jt]s$"]}),jo={...Lo},Qi=[],Bo={},yc={}});function Qr(e){if(e!==Zn)throw Error("Illegal constructor")}function ns(e){return!!e&&typeof e.row==="number"&&typeof e.column==="number"}function sh(e){m=e}function Mc(e,t,n,r){let s=n-t,o=e.textCallback(t,r);if(o){t+=o.length;while(t<n){let a=e.textCallback(t,r);if(a&&a.length>0)t+=a.length,o+=a;else break}if(t>n)o=o.slice(0,s)}return o??""}function Pc(e,t,n,r,s){for(let o=0,a=s.length;o<a;o++){let l=m.getValue(n,"i32");n+=Y;let c=Oe(t,n);n+=xt,s[o]={patternIndex:r,name:e.captureNames[l],node:c}}return n}function le(e,t=0){let n=V+t*xt;m.setValue(n,e.id,"i32"),n+=Y,m.setValue(n,e.startIndex,"i32"),n+=Y,m.setValue(n,e.startPosition.row,"i32"),n+=Y,m.setValue(n,e.startPosition.column,"i32"),n+=Y,m.setValue(n,e[0],"i32")}function Oe(e,t=V){let n=m.getValue(t,"i32");if(t+=Y,n===0)return null;let r=m.getValue(t,"i32");t+=Y;let s=m.getValue(t,"i32");t+=Y;let o=m.getValue(t,"i32");t+=Y;let a=m.getValue(t,"i32");return new QS(Zn,{id:n,tree:e,startIndex:r,startPosition:{row:s,column:o},other:a})}function xe(e,t=V){m.setValue(t+0*Y,e[0],"i32"),m.setValue(t+1*Y,e[1],"i32"),m.setValue(t+2*Y,e[2],"i32"),m.setValue(t+3*Y,e[3],"i32")}function Pt(e){e[0]=m.getValue(V+0*Y,"i32"),e[1]=m.getValue(V+1*Y,"i32"),e[2]=m.getValue(V+2*Y,"i32"),e[3]=m.getValue(V+3*Y,"i32")}function Lt(e,t){m.setValue(e,t.row,"i32"),m.setValue(e+Y,t.column,"i32")}function vr(e){return{row:m.getValue(e,"i32")>>>0,column:m.getValue(e+Y,"i32")>>>0}}function oh(e,t){Lt(e,t.startPosition),e+=mn,Lt(e,t.endPosition),e+=mn,m.setValue(e,t.startIndex,"i32"),e+=Y,m.setValue(e,t.endIndex,"i32"),e+=Y}function Jo(e){let t={};return t.startPosition=vr(e),e+=mn,t.endPosition=vr(e),e+=mn,t.startIndex=m.getValue(e,"i32")>>>0,e+=Y,t.endIndex=m.getValue(e,"i32")>>>0,t}function ah(e,t=V){Lt(t,e.startPosition),t+=mn,Lt(t,e.oldEndPosition),t+=mn,Lt(t,e.newEndPosition),t+=mn,m.setValue(t,e.startIndex,"i32"),t+=Y,m.setValue(t,e.oldEndIndex,"i32"),t+=Y,m.setValue(t,e.newEndIndex,"i32"),t+=Y}function lh(e){let t=m.getValue(e,"i32"),n=m.getValue(e+=Y,"i32"),r=m.getValue(e+=Y,"i32");return{major_version:t,minor_version:n,patch_version:r}}async function ch(moduleArg={}){var moduleRtn,Module=moduleArg,ENVIRONMENT_IS_WEB=typeof window=="object",ENVIRONMENT_IS_WORKER=typeof WorkerGlobalScope<"u",ENVIRONMENT_IS_NODE=typeof process=="object"&&process.versions?.node&&process.type!="renderer";if(ENVIRONMENT_IS_NODE){let{createRequire:e}=await import("module");var require=e(import.meta.url)}Module.currentQueryProgressCallback=null,Module.currentProgressCallback=null,Module.currentLogCallback=null,Module.currentParseCallback=null;var arguments_=[],thisProgram="./this.program",quit_=S((e,t)=>{throw t},"quit_"),_scriptName=import.meta.url,scriptDirectory="";function locateFile(e){if(Module.locateFile)return Module.locateFile(e,scriptDirectory);return scriptDirectory+e}S(locateFile,"locateFile");var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("fs");if(_scriptName.startsWith("file:"))scriptDirectory=require("path").dirname(require("url").fileURLToPath(_scriptName))+"/";if(readBinary=S((e)=>{e=isFileURI(e)?new URL(e):e;var t=fs.readFileSync(e);return t},"readBinary"),readAsync=S(async(e,t=!0)=>{e=isFileURI(e)?new URL(e):e;var n=fs.readFileSync(e,t?void 0:"utf8");return n},"readAsync"),process.argv.length>1)thisProgram=process.argv[1].replace(/\\/g,"/");arguments_=process.argv.slice(2),quit_=S((e,t)=>{throw process.exitCode=e,t},"quit_")}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER)readBinary=S((e)=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)},"readBinary");readAsync=S(async(e)=>{if(isFileURI(e))return new Promise((n,r)=>{var s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onload=()=>{if(s.status==200||s.status==0&&s.response){n(s.response);return}r(s.status)},s.onerror=r,s.send(null)});var t=await fetch(e,{credentials:"same-origin"});if(t.ok)return t.arrayBuffer();throw Error(t.status+" : "+t.url)},"readAsync")}}var out=console.log.bind(console),err=console.error.bind(console),dynamicLibraries=[],wasmBinary,ABORT=!1,EXITSTATUS,isFileURI=S((e)=>e.startsWith("file://"),"isFileURI"),readyPromiseResolve,readyPromiseReject,wasmMemory,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64,HEAP64,HEAPU64,HEAP_DATA_VIEW,runtimeInitialized=!1;function updateMemoryViews(){var e=wasmMemory.buffer;Module.HEAP8=HEAP8=new Int8Array(e),Module.HEAP16=HEAP16=new Int16Array(e),Module.HEAPU8=HEAPU8=new Uint8Array(e),Module.HEAPU16=HEAPU16=new Uint16Array(e),Module.HEAP32=HEAP32=new Int32Array(e),Module.HEAPU32=HEAPU32=new Uint32Array(e),Module.HEAPF32=HEAPF32=new Float32Array(e),Module.HEAPF64=HEAPF64=new Float64Array(e),Module.HEAP64=HEAP64=new BigInt64Array(e),Module.HEAPU64=HEAPU64=new BigUint64Array(e),Module.HEAP_DATA_VIEW=HEAP_DATA_VIEW=new DataView(e),LE_HEAP_UPDATE()}S(updateMemoryViews,"updateMemoryViews");function initMemory(){if(Module.wasmMemory)wasmMemory=Module.wasmMemory;else{var e=Module.INITIAL_MEMORY||33554432;wasmMemory=new WebAssembly.Memory({initial:e/65536,maximum:32768})}updateMemoryViews()}S(initMemory,"initMemory");var __RELOC_FUNCS__=[];function preRun(){if(Module.preRun){if(typeof Module.preRun=="function")Module.preRun=[Module.preRun];while(Module.preRun.length)addOnPreRun(Module.preRun.shift())}callRuntimeCallbacks(onPreRuns)}S(preRun,"preRun");function initRuntime(){runtimeInitialized=!0,callRuntimeCallbacks(__RELOC_FUNCS__),wasmExports.__wasm_call_ctors(),callRuntimeCallbacks(onPostCtors)}S(initRuntime,"initRuntime");function preMain(){}S(preMain,"preMain");function postRun(){if(Module.postRun){if(typeof Module.postRun=="function")Module.postRun=[Module.postRun];while(Module.postRun.length)addOnPostRun(Module.postRun.shift())}callRuntimeCallbacks(onPostRuns)}S(postRun,"postRun");function abort(e){Module.onAbort?.(e),e="Aborted("+e+")",err(e),ABORT=!0,e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);throw readyPromiseReject?.(t),t}S(abort,"abort");var wasmBinaryFile;function findWasmBinary(){if(Module.locateFile)return locateFile("web-tree-sitter.wasm");return new URL("web-tree-sitter.wasm",import.meta.url).href}S(findWasmBinary,"findWasmBinary");function getBinarySync(e){if(e==wasmBinaryFile&&wasmBinary)return new Uint8Array(wasmBinary);if(readBinary)return readBinary(e);throw"both async and sync fetching of the wasm failed"}S(getBinarySync,"getBinarySync");async function getWasmBinary(e){if(!wasmBinary)try{var t=await readAsync(e);return new Uint8Array(t)}catch{}return getBinarySync(e)}S(getWasmBinary,"getWasmBinary");async function instantiateArrayBuffer(e,t){try{var n=await getWasmBinary(e),r=await WebAssembly.instantiate(n,t);return r}catch(s){err(`failed to asynchronously prepare wasm: ${s}`),abort(s)}}S(instantiateArrayBuffer,"instantiateArrayBuffer");async function instantiateAsync(e,t,n){if(!e&&!isFileURI(t)&&!ENVIRONMENT_IS_NODE)try{var r=fetch(t,{credentials:"same-origin"}),s=await WebAssembly.instantiateStreaming(r,n);return s}catch(o){err(`wasm streaming compile failed: ${o}`),err("falling back to ArrayBuffer instantiation")}return instantiateArrayBuffer(t,n)}S(instantiateAsync,"instantiateAsync");function getWasmImports(){return{env:wasmImports,wasi_snapshot_preview1:wasmImports,"GOT.mem":new Proxy(wasmImports,GOTHandler),"GOT.func":new Proxy(wasmImports,GOTHandler)}}S(getWasmImports,"getWasmImports");async function createWasm(){function e(o,a){wasmExports=o.exports,wasmExports=relocateExports(wasmExports,1024);var l=getDylinkMetadata(a);if(l.neededDynlibs)dynamicLibraries=l.neededDynlibs.concat(dynamicLibraries);return mergeLibSymbols(wasmExports,"main"),LDSO.init(),loadDylibs(),__RELOC_FUNCS__.push(wasmExports.__wasm_apply_data_relocs),assignWasmExports(wasmExports),wasmExports}S(e,"receiveInstance");function t(o){return e(o.instance,o.module)}S(t,"receiveInstantiationResult");var n=getWasmImports();if(Module.instantiateWasm)return new Promise((o,a)=>{Module.instantiateWasm(n,(l,c)=>{o(e(l,c))})});wasmBinaryFile??=findWasmBinary();var r=await instantiateAsync(wasmBinary,wasmBinaryFile,n),s=t(r);return s}S(createWasm,"createWasm");class ExitStatus{static{S(this,"ExitStatus")}name="ExitStatus";constructor(e){this.message=`Program terminated with exit(${e})`,this.status=e}}var GOT={},currentModuleWeakSymbols=new Set([]),GOTHandler={get(e,t){var n=GOT[t];if(!n)n=GOT[t]=new WebAssembly.Global({value:"i32",mutable:!0});if(!currentModuleWeakSymbols.has(t))n.required=!0;return n}},LE_ATOMICS_NATIVE_BYTE_ORDER=[],LE_HEAP_LOAD_F32=S((e)=>HEAP_DATA_VIEW.getFloat32(e,!0),"LE_HEAP_LOAD_F32"),LE_HEAP_LOAD_F64=S((e)=>HEAP_DATA_VIEW.getFloat64(e,!0),"LE_HEAP_LOAD_F64"),LE_HEAP_LOAD_I16=S((e)=>HEAP_DATA_VIEW.getInt16(e,!0),"LE_HEAP_LOAD_I16"),LE_HEAP_LOAD_I32=S((e)=>HEAP_DATA_VIEW.getInt32(e,!0),"LE_HEAP_LOAD_I32"),LE_HEAP_LOAD_I64=S((e)=>HEAP_DATA_VIEW.getBigInt64(e,!0),"LE_HEAP_LOAD_I64"),LE_HEAP_LOAD_U32=S((e)=>HEAP_DATA_VIEW.getUint32(e,!0),"LE_HEAP_LOAD_U32"),LE_HEAP_STORE_F32=S((e,t)=>HEAP_DATA_VIEW.setFloat32(e,t,!0),"LE_HEAP_STORE_F32"),LE_HEAP_STORE_F64=S((e,t)=>HEAP_DATA_VIEW.setFloat64(e,t,!0),"LE_HEAP_STORE_F64"),LE_HEAP_STORE_I16=S((e,t)=>HEAP_DATA_VIEW.setInt16(e,t,!0),"LE_HEAP_STORE_I16"),LE_HEAP_STORE_I32=S((e,t)=>HEAP_DATA_VIEW.setInt32(e,t,!0),"LE_HEAP_STORE_I32"),LE_HEAP_STORE_I64=S((e,t)=>HEAP_DATA_VIEW.setBigInt64(e,t,!0),"LE_HEAP_STORE_I64"),LE_HEAP_STORE_U32=S((e,t)=>HEAP_DATA_VIEW.setUint32(e,t,!0),"LE_HEAP_STORE_U32"),callRuntimeCallbacks=S((e)=>{while(e.length>0)e.shift()(Module)},"callRuntimeCallbacks"),onPostRuns=[],addOnPostRun=S((e)=>onPostRuns.push(e),"addOnPostRun"),onPreRuns=[],addOnPreRun=S((e)=>onPreRuns.push(e),"addOnPreRun"),UTF8Decoder=typeof TextDecoder<"u"?new TextDecoder:void 0,findStringEnd=S((e,t,n,r)=>{var s=t+n;if(r)return s;while(e[t]&&!(t>=s))++t;return t},"findStringEnd"),UTF8ArrayToString=S((e,t=0,n,r)=>{var s=findStringEnd(e,t,n,r);if(s-t>16&&e.buffer&&UTF8Decoder)return UTF8Decoder.decode(e.subarray(t,s));var o="";while(t<s){var a=e[t++];if(!(a&128)){o+=String.fromCharCode(a);continue}var l=e[t++]&63;if((a&224)==192){o+=String.fromCharCode((a&31)<<6|l);continue}var c=e[t++]&63;if((a&240)==224)a=(a&15)<<12|l<<6|c;else a=(a&7)<<18|l<<12|c<<6|e[t++]&63;if(a<65536)o+=String.fromCharCode(a);else{var u=a-65536;o+=String.fromCharCode(55296|u>>10,56320|u&1023)}}return o},"UTF8ArrayToString"),getDylinkMetadata=S((e)=>{var t=0,n=0;function r(){return e[t++]}S(r,"getU8");function s(){var j=0,H=1;while(!0){var ve=e[t++];if(j+=(ve&127)*H,H*=128,!(ve&128))break}return j}S(s,"getLEB");function o(){var j=s();return t+=j,UTF8ArrayToString(e,t-j,j)}S(o,"getString");function a(){var j=s(),H=[];while(j--)H.push(o());return H}S(a,"getStringList");function l(j,H){if(j)throw Error(H)}if(S(l,"failIf"),e instanceof WebAssembly.Module){var c=WebAssembly.Module.customSections(e,"dylink.0");l(c.length===0,"need dylink section"),e=new Uint8Array(c[0]),n=e.length}else{var u=new Uint32Array(new Uint8Array(e.subarray(0,24)).buffer),d=u[0]==1836278016||u[0]==6386541;l(!d,"need to see wasm magic number"),l(e[8]!==0,"need the dylink section to be first"),t=9;var f=s();n=t+f;var p=o();l(p!=="dylink.0")}var h={neededDynlibs:[],tlsExports:new Set,weakImports:new Set,runtimePaths:[]},g=1,w=2,b=3,x=4,R=5,P=256,M=3,k=1;while(t<n){var E=r(),D=s();if(E===g)h.memorySize=s(),h.memoryAlign=s(),h.tableSize=s(),h.tableAlign=s();else if(E===w)h.neededDynlibs=a();else if(E===b){var L=s();while(L--){var O=o(),U=s();if(U&P)h.tlsExports.add(O)}}else if(E===x){var L=s();while(L--){var I=o(),O=o(),U=s();if((U&M)==k)h.weakImports.add(O)}}else if(E===R)h.runtimePaths=a();else t+=D}return h},"getDylinkMetadata");function getValue(e,t="i8"){if(t.endsWith("*"))t="*";switch(t){case"i1":return HEAP8[e];case"i8":return HEAP8[e];case"i16":return LE_HEAP_LOAD_I16((e>>1)*2);case"i32":return LE_HEAP_LOAD_I32((e>>2)*4);case"i64":return LE_HEAP_LOAD_I64((e>>3)*8);case"float":return LE_HEAP_LOAD_F32((e>>2)*4);case"double":return LE_HEAP_LOAD_F64((e>>3)*8);case"*":return LE_HEAP_LOAD_U32((e>>2)*4);default:abort(`invalid type for getValue: ${t}`)}}S(getValue,"getValue");var newDSO=S((e,t,n)=>{var r={refcount:1/0,name:e,exports:n,global:!0};if(LDSO.loadedLibsByName[e]=r,t!=null)LDSO.loadedLibsByHandle[t]=r;return r},"newDSO"),LDSO={loadedLibsByName:{},loadedLibsByHandle:{},init(){newDSO("__main__",0,wasmImports)}},___heap_base=78240,alignMemory=S((e,t)=>Math.ceil(e/t)*t,"alignMemory"),getMemory=S((e)=>{if(runtimeInitialized)return _calloc(e,1);var t=___heap_base,n=t+alignMemory(e,16);return ___heap_base=n,GOT.__heap_base.value=n,t},"getMemory"),isInternalSym=S((e)=>["__cpp_exception","__c_longjmp","__wasm_apply_data_relocs","__dso_handle","__tls_size","__tls_align","__set_stack_limits","_emscripten_tls_init","__wasm_init_tls","__wasm_call_ctors","__start_em_asm","__stop_em_asm","__start_em_js","__stop_em_js"].includes(e)||e.startsWith("__em_js__"),"isInternalSym"),uleb128EncodeWithLen=S((e)=>{let t=e.length;return[t%128|128,t>>7,...e]},"uleb128EncodeWithLen"),wasmTypeCodes={i:127,p:127,j:126,f:125,d:124,e:111},generateTypePack=S((e)=>uleb128EncodeWithLen(Array.from(e,(t)=>{var n=wasmTypeCodes[t];return n})),"generateTypePack"),convertJsFunctionToWasm=S((e,t)=>{var n=Uint8Array.of(0,97,115,109,1,0,0,0,1,...uleb128EncodeWithLen([1,96,...generateTypePack(t.slice(1)),...generateTypePack(t[0]==="v"?"":t[0])]),2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0),r=new WebAssembly.Module(n),s=new WebAssembly.Instance(r,{e:{f:e}}),o=s.exports.f;return o},"convertJsFunctionToWasm"),wasmTableMirror=[],wasmTable=new WebAssembly.Table({initial:31,element:"anyfunc"}),getWasmTableEntry=S((e)=>{var t=wasmTableMirror[e];if(!t)wasmTableMirror[e]=t=wasmTable.get(e);return t},"getWasmTableEntry"),updateTableMap=S((e,t)=>{if(functionsInTableMap)for(var n=e;n<e+t;n++){var r=getWasmTableEntry(n);if(r)functionsInTableMap.set(r,n)}},"updateTableMap"),functionsInTableMap,getFunctionAddress=S((e)=>{if(!functionsInTableMap)functionsInTableMap=new WeakMap,updateTableMap(0,wasmTable.length);return functionsInTableMap.get(e)||0},"getFunctionAddress"),freeTableIndexes=[],getEmptyTableSlot=S(()=>{if(freeTableIndexes.length)return freeTableIndexes.pop();return wasmTable.grow(1)},"getEmptyTableSlot"),setWasmTableEntry=S((e,t)=>{wasmTable.set(e,t),wasmTableMirror[e]=wasmTable.get(e)},"setWasmTableEntry"),addFunction=S((e,t)=>{var n=getFunctionAddress(e);if(n)return n;var r=getEmptyTableSlot();try{setWasmTableEntry(r,e)}catch(o){if(!(o instanceof TypeError))throw o;var s=convertJsFunctionToWasm(e,t);setWasmTableEntry(r,s)}return functionsInTableMap.set(e,r),r},"addFunction"),updateGOT=S((e,t)=>{for(var n in e){if(isInternalSym(n))continue;var r=e[n];if(GOT[n]||=new WebAssembly.Global({value:"i32",mutable:!0}),t||GOT[n].value==0)if(typeof r=="function")GOT[n].value=addFunction(r);else if(typeof r=="number")GOT[n].value=r;else err(`unhandled export type for '${n}': ${typeof r}`)}},"updateGOT"),relocateExports=S((e,t,n)=>{var r={};for(var s in e){var o=e[s];if(typeof o=="object")o=o.value;if(typeof o=="number")o+=t;r[s]=o}return updateGOT(r,n),r},"relocateExports"),isSymbolDefined=S((e)=>{var t=wasmImports[e];if(!t||t.stub)return!1;return!0},"isSymbolDefined"),dynCall=S((e,t,n=[],r=!1)=>{var s=getWasmTableEntry(t),o=s(...n);function a(l){return l}return S(a,"convert"),a(o)},"dynCall"),stackSave=S(()=>_emscripten_stack_get_current(),"stackSave"),stackRestore=S((e)=>__emscripten_stack_restore(e),"stackRestore"),createInvokeFunction=S((e)=>(t,...n)=>{var r=stackSave();try{return dynCall(e,t,n)}catch(s){if(stackRestore(r),s!==s+0)throw s;if(_setThrew(1,0),e[0]=="j")return 0n}},"createInvokeFunction"),resolveGlobalSymbol=S((e,t=!1)=>{var n;if(isSymbolDefined(e))n=wasmImports[e];else if(e.startsWith("invoke_"))n=wasmImports[e]=createInvokeFunction(e.split("_")[1]);return{sym:n,name:e}},"resolveGlobalSymbol"),onPostCtors=[],addOnPostCtor=S((e)=>onPostCtors.push(e),"addOnPostCtor"),UTF8ToString=S((e,t,n)=>e?UTF8ArrayToString(HEAPU8,e,t,n):"","UTF8ToString"),loadWebAssemblyModule=S((binary,flags,libName,localScope,handle)=>{var metadata=getDylinkMetadata(binary);function loadModule(){var memAlign=Math.pow(2,metadata.memoryAlign),memoryBase=metadata.memorySize?alignMemory(getMemory(metadata.memorySize+memAlign),memAlign):0,tableBase=metadata.tableSize?wasmTable.length:0;if(handle)HEAP8[handle+8]=1,LE_HEAP_STORE_U32((handle+12>>2)*4,memoryBase),LE_HEAP_STORE_I32((handle+16>>2)*4,metadata.memorySize),LE_HEAP_STORE_U32((handle+20>>2)*4,tableBase),LE_HEAP_STORE_I32((handle+24>>2)*4,metadata.tableSize);if(metadata.tableSize)wasmTable.grow(metadata.tableSize);var moduleExports;function resolveSymbol(e){var t=resolveGlobalSymbol(e).sym;if(!t&&localScope)t=localScope[e];if(!t)t=moduleExports[e];return t}S(resolveSymbol,"resolveSymbol");var proxyHandler={get(e,t){switch(t){case"__memory_base":return memoryBase;case"__table_base":return tableBase}if(t in wasmImports&&!wasmImports[t].stub){var n=wasmImports[t];return n}if(!(t in e)){var r;e[t]=(...s)=>(r||=resolveSymbol(t),r(...s))}return e[t]}},proxy=new Proxy({},proxyHandler);currentModuleWeakSymbols=metadata.weakImports;var info={"GOT.mem":new Proxy({},GOTHandler),"GOT.func":new Proxy({},GOTHandler),env:proxy,wasi_snapshot_preview1:proxy};function postInstantiation(module,instance){if(updateTableMap(tableBase,metadata.tableSize),moduleExports=relocateExports(instance.exports,memoryBase),!flags.allowUndefined)reportUndefinedSymbols();function addEmAsm(addr,body){var args=[],arity=0;for(;arity<16;arity++)if(body.indexOf("$"+arity)!=-1)args.push("$"+arity);else break;args=args.join(",");var func=`(${args}) => { ${body} };`;ASM_CONSTS[start]=eval(func)}if(S(addEmAsm,"addEmAsm"),"__start_em_asm"in moduleExports){var start=moduleExports.__start_em_asm,stop=moduleExports.__stop_em_asm;while(start<stop){var jsString=UTF8ToString(start);addEmAsm(start,jsString),start=HEAPU8.indexOf(0,start)+1}}function addEmJs(name,cSig,body){var jsArgs=[];if(cSig=cSig.slice(1,-1),cSig!="void"){cSig=cSig.split(",");for(var i in cSig){var jsArg=cSig[i].split(" ").pop();jsArgs.push(jsArg.replace("*",""))}}var func=`(${jsArgs}) => ${body};`;moduleExports[name]=eval(func)}S(addEmJs,"addEmJs");for(var name in moduleExports)if(name.startsWith("__em_js__")){var start=moduleExports[name],jsString=UTF8ToString(start),parts=jsString.split("<::>");addEmJs(name.replace("__em_js__",""),parts[0],parts[1]),delete moduleExports[name]}var applyRelocs=moduleExports.__wasm_apply_data_relocs;if(applyRelocs)if(runtimeInitialized)applyRelocs();else __RELOC_FUNCS__.push(applyRelocs);var init=moduleExports.__wasm_call_ctors;if(init)if(runtimeInitialized)init();else addOnPostCtor(init);return moduleExports}if(S(postInstantiation,"postInstantiation"),flags.loadAsync)return(async()=>{var e;if(binary instanceof WebAssembly.Module)e=new WebAssembly.Instance(binary,info);else({module:binary,instance:e}=await WebAssembly.instantiate(binary,info));return postInstantiation(binary,e)})();var module=binary instanceof WebAssembly.Module?binary:new WebAssembly.Module(binary),instance=new WebAssembly.Instance(module,info);return postInstantiation(module,instance)}if(S(loadModule,"loadModule"),flags={...flags,rpath:{parentLibPath:libName,paths:metadata.runtimePaths}},flags.loadAsync)return metadata.neededDynlibs.reduce((e,t)=>e.then(()=>loadDynamicLibrary(t,flags,localScope)),Promise.resolve()).then(loadModule);return metadata.neededDynlibs.forEach((e)=>loadDynamicLibrary(e,flags,localScope)),loadModule()},"loadWebAssemblyModule"),mergeLibSymbols=S((e,t)=>{for(var[n,r]of Object.entries(e)){let s=S((a)=>{if(!isSymbolDefined(a))wasmImports[a]=r},"setImport");s(n);let o="__main_argc_argv";if(n=="main")s(o);if(n==o)s("main")}},"mergeLibSymbols"),asyncLoad=S(async(e)=>{var t=await readAsync(e);return new Uint8Array(t)},"asyncLoad");function loadDynamicLibrary(e,t={global:!0,nodelete:!0},n,r){var s=LDSO.loadedLibsByName[e];if(s){if(!t.global){if(n)Object.assign(n,s.exports)}else if(!s.global)s.global=!0,mergeLibSymbols(s.exports,e);if(t.nodelete&&s.refcount!==1/0)s.refcount=1/0;if(s.refcount++,r)LDSO.loadedLibsByHandle[r]=s;return t.loadAsync?Promise.resolve(!0):!0}s=newDSO(e,r,"loading"),s.refcount=t.nodelete?1/0:1,s.global=t.global;function o(){if(r){var c=LE_HEAP_LOAD_U32((r+28>>2)*4),u=LE_HEAP_LOAD_U32((r+32>>2)*4);if(c&&u){var d=HEAP8.slice(c,c+u);return t.loadAsync?Promise.resolve(d):d}}var f=locateFile(e);if(t.loadAsync)return asyncLoad(f);if(!readBinary)throw Error(`${f}: file not found, and synchronous loading of external files is not available`);return readBinary(f)}S(o,"loadLibData");function a(){if(t.loadAsync)return o().then((c)=>loadWebAssemblyModule(c,t,e,n,r));return loadWebAssemblyModule(o(),t,e,n,r)}S(a,"getExports");function l(c){if(s.global)mergeLibSymbols(c,e);else if(n)Object.assign(n,c);s.exports=c}if(S(l,"moduleLoaded"),t.loadAsync)return a().then((c)=>(l(c),!0));return l(a()),!0}S(loadDynamicLibrary,"loadDynamicLibrary");var reportUndefinedSymbols=S(()=>{for(var[e,t]of Object.entries(GOT))if(t.value==0){var n=resolveGlobalSymbol(e,!0).sym;if(!n&&!t.required)continue;if(typeof n=="function")t.value=addFunction(n,n.sig);else if(typeof n=="number")t.value=n;else throw Error(`bad export type for '${e}': ${typeof n}`)}},"reportUndefinedSymbols"),runDependencies=0,dependenciesFulfilled=null,removeRunDependency=S((e)=>{if(runDependencies--,Module.monitorRunDependencies?.(runDependencies),runDependencies==0){if(dependenciesFulfilled){var t=dependenciesFulfilled;dependenciesFulfilled=null,t()}}},"removeRunDependency"),addRunDependency=S((e)=>{runDependencies++,Module.monitorRunDependencies?.(runDependencies)},"addRunDependency"),loadDylibs=S(async()=>{if(!dynamicLibraries.length){reportUndefinedSymbols();return}addRunDependency("loadDylibs");for(var e of dynamicLibraries)await loadDynamicLibrary(e,{loadAsync:!0,global:!0,nodelete:!0,allowUndefined:!0});reportUndefinedSymbols(),removeRunDependency("loadDylibs")},"loadDylibs"),noExitRuntime=!0;function setValue(e,t,n="i8"){if(n.endsWith("*"))n="*";switch(n){case"i1":HEAP8[e]=t;break;case"i8":HEAP8[e]=t;break;case"i16":LE_HEAP_STORE_I16((e>>1)*2,t);break;case"i32":LE_HEAP_STORE_I32((e>>2)*4,t);break;case"i64":LE_HEAP_STORE_I64((e>>3)*8,BigInt(t));break;case"float":LE_HEAP_STORE_F32((e>>2)*4,t);break;case"double":LE_HEAP_STORE_F64((e>>3)*8,t);break;case"*":LE_HEAP_STORE_U32((e>>2)*4,t);break;default:abort(`invalid type for setValue: ${n}`)}}S(setValue,"setValue");var ___memory_base=new WebAssembly.Global({value:"i32",mutable:!1},1024),___stack_high=78240,___stack_low=12704,___stack_pointer=new WebAssembly.Global({value:"i32",mutable:!0},78240),___table_base=new WebAssembly.Global({value:"i32",mutable:!1},1),__abort_js=S(()=>abort(""),"__abort_js");__abort_js.sig="v";var getHeapMax=S(()=>2147483648,"getHeapMax"),growMemory=S((e)=>{var t=wasmMemory.buffer.byteLength,n=(e-t+65535)/65536|0;try{return wasmMemory.grow(n),updateMemoryViews(),1}catch(r){}},"growMemory"),_emscripten_resize_heap=S((e)=>{var t=HEAPU8.length;e>>>=0;var n=getHeapMax();if(e>n)return!1;for(var r=1;r<=4;r*=2){var s=t*(1+0.2/r);s=Math.min(s,e+100663296);var o=Math.min(n,alignMemory(Math.max(e,s),65536)),a=growMemory(o);if(a)return!0}return!1},"_emscripten_resize_heap");_emscripten_resize_heap.sig="ip";var _fd_close=S((e)=>52,"_fd_close");_fd_close.sig="ii";var INT53_MAX=9007199254740992,INT53_MIN=-9007199254740992,bigintToI53Checked=S((e)=>e<INT53_MIN||e>INT53_MAX?NaN:Number(e),"bigintToI53Checked");function _fd_seek(e,t,n,r){return t=bigintToI53Checked(t),70}S(_fd_seek,"_fd_seek"),_fd_seek.sig="iijip";var printCharBuffers=[null,[],[]],printChar=S((e,t)=>{var n=printCharBuffers[e];if(t===0||t===10)(e===1?out:err)(UTF8ArrayToString(n)),n.length=0;else n.push(t)},"printChar"),_fd_write=S((e,t,n,r)=>{var s=0;for(var o=0;o<n;o++){var a=LE_HEAP_LOAD_U32((t>>2)*4),l=LE_HEAP_LOAD_U32((t+4>>2)*4);t+=8;for(var c=0;c<l;c++)printChar(e,HEAPU8[a+c]);s+=l}return LE_HEAP_STORE_U32((r>>2)*4,s),0},"_fd_write");_fd_write.sig="iippp";function _tree_sitter_log_callback(e,t){if(Module.currentLogCallback){let n=UTF8ToString(t);Module.currentLogCallback(n,e!==0)}}S(_tree_sitter_log_callback,"_tree_sitter_log_callback");function _tree_sitter_parse_callback(e,t,n,r,s){let a=Module.currentParseCallback(t,{row:n,column:r});if(typeof a==="string")setValue(s,a.length,"i32"),stringToUTF16(a,e,10240);else setValue(s,0,"i32")}S(_tree_sitter_parse_callback,"_tree_sitter_parse_callback");function _tree_sitter_progress_callback(e,t){if(Module.currentProgressCallback)return Module.currentProgressCallback({currentOffset:e,hasError:t});return!1}S(_tree_sitter_progress_callback,"_tree_sitter_progress_callback");function _tree_sitter_query_progress_callback(e){if(Module.currentQueryProgressCallback)return Module.currentQueryProgressCallback({currentOffset:e});return!1}S(_tree_sitter_query_progress_callback,"_tree_sitter_query_progress_callback");var runtimeKeepaliveCounter=0,keepRuntimeAlive=S(()=>noExitRuntime||runtimeKeepaliveCounter>0,"keepRuntimeAlive"),_proc_exit=S((e)=>{if(EXITSTATUS=e,!keepRuntimeAlive())Module.onExit?.(e),ABORT=!0;quit_(e,new ExitStatus(e))},"_proc_exit");_proc_exit.sig="vi";var exitJS=S((e,t)=>{EXITSTATUS=e,_proc_exit(e)},"exitJS"),handleException=S((e)=>{if(e instanceof ExitStatus||e=="unwind")return EXITSTATUS;quit_(1,e)},"handleException"),lengthBytesUTF8=S((e)=>{var t=0;for(var n=0;n<e.length;++n){var r=e.charCodeAt(n);if(r<=127)t++;else if(r<=2047)t+=2;else if(r>=55296&&r<=57343)t+=4,++n;else t+=3}return t},"lengthBytesUTF8"),stringToUTF8Array=S((e,t,n,r)=>{if(!(r>0))return 0;var s=n,o=n+r-1;for(var a=0;a<e.length;++a){var l=e.codePointAt(a);if(l<=127){if(n>=o)break;t[n++]=l}else if(l<=2047){if(n+1>=o)break;t[n++]=192|l>>6,t[n++]=128|l&63}else if(l<=65535){if(n+2>=o)break;t[n++]=224|l>>12,t[n++]=128|l>>6&63,t[n++]=128|l&63}else{if(n+3>=o)break;t[n++]=240|l>>18,t[n++]=128|l>>12&63,t[n++]=128|l>>6&63,t[n++]=128|l&63,a++}}return t[n]=0,n-s},"stringToUTF8Array"),stringToUTF8=S((e,t,n)=>stringToUTF8Array(e,HEAPU8,t,n),"stringToUTF8"),stackAlloc=S((e)=>__emscripten_stack_alloc(e),"stackAlloc"),stringToUTF8OnStack=S((e)=>{var t=lengthBytesUTF8(e)+1,n=stackAlloc(t);return stringToUTF8(e,n,t),n},"stringToUTF8OnStack"),AsciiToString=S((e)=>{var t="";while(!0){var n=HEAPU8[e++];if(!n)return t;t+=String.fromCharCode(n)}},"AsciiToString"),stringToUTF16=S((e,t,n)=>{if(n??=2147483647,n<2)return 0;n-=2;var r=t,s=n<e.length*2?n/2:e.length;for(var o=0;o<s;++o){var a=e.charCodeAt(o);LE_HEAP_STORE_I16((t>>1)*2,a),t+=2}return LE_HEAP_STORE_I16((t>>1)*2,0),t-r},"stringToUTF16");LE_ATOMICS_NATIVE_BYTE_ORDER=new Int8Array(new Int16Array([1]).buffer)[0]===1?[(e)=>e,(e)=>e,void 0,(e)=>e]:[(e)=>e,(e)=>((e&65280)<<8|(e&255)<<24)>>16,void 0,(e)=>e>>24&255|e>>8&65280|(e&65280)<<8|(e&255)<<24];function LE_HEAP_UPDATE(){HEAPU16.unsigned=(e)=>e&65535,HEAPU32.unsigned=(e)=>e>>>0}S(LE_HEAP_UPDATE,"LE_HEAP_UPDATE");{if(initMemory(),Module.noExitRuntime)noExitRuntime=Module.noExitRuntime;if(Module.print)out=Module.print;if(Module.printErr)err=Module.printErr;if(Module.dynamicLibraries)dynamicLibraries=Module.dynamicLibraries;if(Module.wasmBinary)wasmBinary=Module.wasmBinary;if(Module.arguments)arguments_=Module.arguments;if(Module.thisProgram)thisProgram=Module.thisProgram;if(Module.preInit){if(typeof Module.preInit=="function")Module.preInit=[Module.preInit];while(Module.preInit.length>0)Module.preInit.shift()()}}Module.setValue=setValue,Module.getValue=getValue,Module.UTF8ToString=UTF8ToString,Module.stringToUTF8=stringToUTF8,Module.lengthBytesUTF8=lengthBytesUTF8,Module.AsciiToString=AsciiToString,Module.stringToUTF16=stringToUTF16,Module.loadWebAssemblyModule=loadWebAssemblyModule,Module.LE_HEAP_STORE_I64=LE_HEAP_STORE_I64;var ASM_CONSTS={},_malloc,_calloc,_realloc,_free,_ts_range_edit,_memcmp,_ts_language_symbol_count,_ts_language_state_count,_ts_language_abi_version,_ts_language_name,_ts_language_field_count,_ts_language_next_state,_ts_language_symbol_name,_ts_language_symbol_for_name,_strncmp,_ts_language_symbol_type,_ts_language_field_name_for_id,_ts_lookahead_iterator_new,_ts_lookahead_iterator_delete,_ts_lookahead_iterator_reset_state,_ts_lookahead_iterator_reset,_ts_lookahead_iterator_next,_ts_lookahead_iterator_current_symbol,_ts_point_edit,_ts_parser_delete,_ts_parser_reset,_ts_parser_set_language,_ts_parser_set_included_ranges,_ts_query_new,_ts_query_delete,_iswspace,_iswalnum,_ts_query_pattern_count,_ts_query_capture_count,_ts_query_string_count,_ts_query_capture_name_for_id,_ts_query_capture_quantifier_for_id,_ts_query_string_value_for_id,_ts_query_predicates_for_pattern,_ts_query_start_byte_for_pattern,_ts_query_end_byte_for_pattern,_ts_query_is_pattern_rooted,_ts_query_is_pattern_non_local,_ts_query_is_pattern_guaranteed_at_step,_ts_query_disable_capture,_ts_query_disable_pattern,_ts_tree_copy,_ts_tree_delete,_ts_init,_ts_parser_new_wasm,_ts_parser_enable_logger_wasm,_ts_parser_parse_wasm,_ts_parser_included_ranges_wasm,_ts_language_type_is_named_wasm,_ts_language_type_is_visible_wasm,_ts_language_metadata_wasm,_ts_language_supertypes_wasm,_ts_language_subtypes_wasm,_ts_tree_root_node_wasm,_ts_tree_root_node_with_offset_wasm,_ts_tree_edit_wasm,_ts_tree_included_ranges_wasm,_ts_tree_get_changed_ranges_wasm,_ts_tree_cursor_new_wasm,_ts_tree_cursor_copy_wasm,_ts_tree_cursor_delete_wasm,_ts_tree_cursor_reset_wasm,_ts_tree_cursor_reset_to_wasm,_ts_tree_cursor_goto_first_child_wasm,_ts_tree_cursor_goto_last_child_wasm,_ts_tree_cursor_goto_first_child_for_index_wasm,_ts_tree_cursor_goto_first_child_for_position_wasm,_ts_tree_cursor_goto_next_sibling_wasm,_ts_tree_cursor_goto_previous_sibling_wasm,_ts_tree_cursor_goto_descendant_wasm,_ts_tree_cursor_goto_parent_wasm,_ts_tree_cursor_current_node_type_id_wasm,_ts_tree_cursor_current_node_state_id_wasm,_ts_tree_cursor_current_node_is_named_wasm,_ts_tree_cursor_current_node_is_missing_wasm,_ts_tree_cursor_current_node_id_wasm,_ts_tree_cursor_start_position_wasm,_ts_tree_cursor_end_position_wasm,_ts_tree_cursor_start_index_wasm,_ts_tree_cursor_end_index_wasm,_ts_tree_cursor_current_field_id_wasm,_ts_tree_cursor_current_depth_wasm,_ts_tree_cursor_current_descendant_index_wasm,_ts_tree_cursor_current_node_wasm,_ts_node_symbol_wasm,_ts_node_field_name_for_child_wasm,_ts_node_field_name_for_named_child_wasm,_ts_node_children_by_field_id_wasm,_ts_node_first_child_for_byte_wasm,_ts_node_first_named_child_for_byte_wasm,_ts_node_grammar_symbol_wasm,_ts_node_child_count_wasm,_ts_node_named_child_count_wasm,_ts_node_child_wasm,_ts_node_named_child_wasm,_ts_node_child_by_field_id_wasm,_ts_node_next_sibling_wasm,_ts_node_prev_sibling_wasm,_ts_node_next_named_sibling_wasm,_ts_node_prev_named_sibling_wasm,_ts_node_descendant_count_wasm,_ts_node_parent_wasm,_ts_node_child_with_descendant_wasm,_ts_node_descendant_for_index_wasm,_ts_node_named_descendant_for_index_wasm,_ts_node_descendant_for_position_wasm,_ts_node_named_descendant_for_position_wasm,_ts_node_start_point_wasm,_ts_node_end_point_wasm,_ts_node_start_index_wasm,_ts_node_end_index_wasm,_ts_node_to_string_wasm,_ts_node_children_wasm,_ts_node_named_children_wasm,_ts_node_descendants_of_type_wasm,_ts_node_is_named_wasm,_ts_node_has_changes_wasm,_ts_node_has_error_wasm,_ts_node_is_error_wasm,_ts_node_is_missing_wasm,_ts_node_is_extra_wasm,_ts_node_parse_state_wasm,_ts_node_next_parse_state_wasm,_ts_query_matches_wasm,_ts_query_captures_wasm,_memset,_memcpy,_memmove,_iswalpha,_iswblank,_iswdigit,_iswlower,_iswupper,_iswxdigit,_memchr,_strlen,_strcmp,_strncat,_strncpy,_towlower,_towupper,_setThrew,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,___wasm_apply_data_relocs;function assignWasmExports(e){Module._malloc=_malloc=e.malloc,Module._calloc=_calloc=e.calloc,Module._realloc=_realloc=e.realloc,Module._free=_free=e.free,Module._ts_range_edit=_ts_range_edit=e.ts_range_edit,Module._memcmp=_memcmp=e.memcmp,Module._ts_language_symbol_count=_ts_language_symbol_count=e.ts_language_symbol_count,Module._ts_language_state_count=_ts_language_state_count=e.ts_language_state_count,Module._ts_language_abi_version=_ts_language_abi_version=e.ts_language_abi_version,Module._ts_language_name=_ts_language_name=e.ts_language_name,Module._ts_language_field_count=_ts_language_field_count=e.ts_language_field_count,Module._ts_language_next_state=_ts_language_next_state=e.ts_language_next_state,Module._ts_language_symbol_name=_ts_language_symbol_name=e.ts_language_symbol_name,Module._ts_language_symbol_for_name=_ts_language_symbol_for_name=e.ts_language_symbol_for_name,Module._strncmp=_strncmp=e.strncmp,Module._ts_language_symbol_type=_ts_language_symbol_type=e.ts_language_symbol_type,Module._ts_language_field_name_for_id=_ts_language_field_name_for_id=e.ts_language_field_name_for_id,Module._ts_lookahead_iterator_new=_ts_lookahead_iterator_new=e.ts_lookahead_iterator_new,Module._ts_lookahead_iterator_delete=_ts_lookahead_iterator_delete=e.ts_lookahead_iterator_delete,Module._ts_lookahead_iterator_reset_state=_ts_lookahead_iterator_reset_state=e.ts_lookahead_iterator_reset_state,Module._ts_lookahead_iterator_reset=_ts_lookahead_iterator_reset=e.ts_lookahead_iterator_reset,Module._ts_lookahead_iterator_next=_ts_lookahead_iterator_next=e.ts_lookahead_iterator_next,Module._ts_lookahead_iterator_current_symbol=_ts_lookahead_iterator_current_symbol=e.ts_lookahead_iterator_current_symbol,Module._ts_point_edit=_ts_point_edit=e.ts_point_edit,Module._ts_parser_delete=_ts_parser_delete=e.ts_parser_delete,Module._ts_parser_reset=_ts_parser_reset=e.ts_parser_reset,Module._ts_parser_set_language=_ts_parser_set_language=e.ts_parser_set_language,Module._ts_parser_set_included_ranges=_ts_parser_set_included_ranges=e.ts_parser_set_included_ranges,Module._ts_query_new=_ts_query_new=e.ts_query_new,Module._ts_query_delete=_ts_query_delete=e.ts_query_delete,Module._iswspace=_iswspace=e.iswspace,Module._iswalnum=_iswalnum=e.iswalnum,Module._ts_query_pattern_count=_ts_query_pattern_count=e.ts_query_pattern_count,Module._ts_query_capture_count=_ts_query_capture_count=e.ts_query_capture_count,Module._ts_query_string_count=_ts_query_string_count=e.ts_query_string_count,Module._ts_query_capture_name_for_id=_ts_query_capture_name_for_id=e.ts_query_capture_name_for_id,Module._ts_query_capture_quantifier_for_id=_ts_query_capture_quantifier_for_id=e.ts_query_capture_quantifier_for_id,Module._ts_query_string_value_for_id=_ts_query_string_value_for_id=e.ts_query_string_value_for_id,Module._ts_query_predicates_for_pattern=_ts_query_predicates_for_pattern=e.ts_query_predicates_for_pattern,Module._ts_query_start_byte_for_pattern=_ts_query_start_byte_for_pattern=e.ts_query_start_byte_for_pattern,Module._ts_query_end_byte_for_pattern=_ts_query_end_byte_for_pattern=e.ts_query_end_byte_for_pattern,Module._ts_query_is_pattern_rooted=_ts_query_is_pattern_rooted=e.ts_query_is_pattern_rooted,Module._ts_query_is_pattern_non_local=_ts_query_is_pattern_non_local=e.ts_query_is_pattern_non_local,Module._ts_query_is_pattern_guaranteed_at_step=_ts_query_is_pattern_guaranteed_at_step=e.ts_query_is_pattern_guaranteed_at_step,Module._ts_query_disable_capture=_ts_query_disable_capture=e.ts_query_disable_capture,Module._ts_query_disable_pattern=_ts_query_disable_pattern=e.ts_query_disable_pattern,Module._ts_tree_copy=_ts_tree_copy=e.ts_tree_copy,Module._ts_tree_delete=_ts_tree_delete=e.ts_tree_delete,Module._ts_init=_ts_init=e.ts_init,Module._ts_parser_new_wasm=_ts_parser_new_wasm=e.ts_parser_new_wasm,Module._ts_parser_enable_logger_wasm=_ts_parser_enable_logger_wasm=e.ts_parser_enable_logger_wasm,Module._ts_parser_parse_wasm=_ts_parser_parse_wasm=e.ts_parser_parse_wasm,Module._ts_parser_included_ranges_wasm=_ts_parser_included_ranges_wasm=e.ts_parser_included_ranges_wasm,Module._ts_language_type_is_named_wasm=_ts_language_type_is_named_wasm=e.ts_language_type_is_named_wasm,Module._ts_language_type_is_visible_wasm=_ts_language_type_is_visible_wasm=e.ts_language_type_is_visible_wasm,Module._ts_language_metadata_wasm=_ts_language_metadata_wasm=e.ts_language_metadata_wasm,Module._ts_language_supertypes_wasm=_ts_language_supertypes_wasm=e.ts_language_supertypes_wasm,Module._ts_language_subtypes_wasm=_ts_language_subtypes_wasm=e.ts_language_subtypes_wasm,Module._ts_tree_root_node_wasm=_ts_tree_root_node_wasm=e.ts_tree_root_node_wasm,Module._ts_tree_root_node_with_offset_wasm=_ts_tree_root_node_with_offset_wasm=e.ts_tree_root_node_with_offset_wasm,Module._ts_tree_edit_wasm=_ts_tree_edit_wasm=e.ts_tree_edit_wasm,Module._ts_tree_included_ranges_wasm=_ts_tree_included_ranges_wasm=e.ts_tree_included_ranges_wasm,Module._ts_tree_get_changed_ranges_wasm=_ts_tree_get_changed_ranges_wasm=e.ts_tree_get_changed_ranges_wasm,Module._ts_tree_cursor_new_wasm=_ts_tree_cursor_new_wasm=e.ts_tree_cursor_new_wasm,Module._ts_tree_cursor_copy_wasm=_ts_tree_cursor_copy_wasm=e.ts_tree_cursor_copy_wasm,Module._ts_tree_cursor_delete_wasm=_ts_tree_cursor_delete_wasm=e.ts_tree_cursor_delete_wasm,Module._ts_tree_cursor_reset_wasm=_ts_tree_cursor_reset_wasm=e.ts_tree_cursor_reset_wasm,Module._ts_tree_cursor_reset_to_wasm=_ts_tree_cursor_reset_to_wasm=e.ts_tree_cursor_reset_to_wasm,Module._ts_tree_cursor_goto_first_child_wasm=_ts_tree_cursor_goto_first_child_wasm=e.ts_tree_cursor_goto_first_child_wasm,Module._ts_tree_cursor_goto_last_child_wasm=_ts_tree_cursor_goto_last_child_wasm=e.ts_tree_cursor_goto_last_child_wasm,Module._ts_tree_cursor_goto_first_child_for_index_wasm=_ts_tree_cursor_goto_first_child_for_index_wasm=e.ts_tree_cursor_goto_first_child_for_index_wasm,Module._ts_tree_cursor_goto_first_child_for_position_wasm=_ts_tree_cursor_goto_first_child_for_position_wasm=e.ts_tree_cursor_goto_first_child_for_position_wasm,Module._ts_tree_cursor_goto_next_sibling_wasm=_ts_tree_cursor_goto_next_sibling_wasm=e.ts_tree_cursor_goto_next_sibling_wasm,Module._ts_tree_cursor_goto_previous_sibling_wasm=_ts_tree_cursor_goto_previous_sibling_wasm=e.ts_tree_cursor_goto_previous_sibling_wasm,Module._ts_tree_cursor_goto_descendant_wasm=_ts_tree_cursor_goto_descendant_wasm=e.ts_tree_cursor_goto_descendant_wasm,Module._ts_tree_cursor_goto_parent_wasm=_ts_tree_cursor_goto_parent_wasm=e.ts_tree_cursor_goto_parent_wasm,Module._ts_tree_cursor_current_node_type_id_wasm=_ts_tree_cursor_current_node_type_id_wasm=e.ts_tree_cursor_current_node_type_id_wasm,Module._ts_tree_cursor_current_node_state_id_wasm=_ts_tree_cursor_current_node_state_id_wasm=e.ts_tree_cursor_current_node_state_id_wasm,Module._ts_tree_cursor_current_node_is_named_wasm=_ts_tree_cursor_current_node_is_named_wasm=e.ts_tree_cursor_current_node_is_named_wasm,Module._ts_tree_cursor_current_node_is_missing_wasm=_ts_tree_cursor_current_node_is_missing_wasm=e.ts_tree_cursor_current_node_is_missing_wasm,Module._ts_tree_cursor_current_node_id_wasm=_ts_tree_cursor_current_node_id_wasm=e.ts_tree_cursor_current_node_id_wasm,Module._ts_tree_cursor_start_position_wasm=_ts_tree_cursor_start_position_wasm=e.ts_tree_cursor_start_position_wasm,Module._ts_tree_cursor_end_position_wasm=_ts_tree_cursor_end_position_wasm=e.ts_tree_cursor_end_position_wasm,Module._ts_tree_cursor_start_index_wasm=_ts_tree_cursor_start_index_wasm=e.ts_tree_cursor_start_index_wasm,Module._ts_tree_cursor_end_index_wasm=_ts_tree_cursor_end_index_wasm=e.ts_tree_cursor_end_index_wasm,Module._ts_tree_cursor_current_field_id_wasm=_ts_tree_cursor_current_field_id_wasm=e.ts_tree_cursor_current_field_id_wasm,Module._ts_tree_cursor_current_depth_wasm=_ts_tree_cursor_current_depth_wasm=e.ts_tree_cursor_current_depth_wasm,Module._ts_tree_cursor_current_descendant_index_wasm=_ts_tree_cursor_current_descendant_index_wasm=e.ts_tree_cursor_current_descendant_index_wasm,Module._ts_tree_cursor_current_node_wasm=_ts_tree_cursor_current_node_wasm=e.ts_tree_cursor_current_node_wasm,Module._ts_node_symbol_wasm=_ts_node_symbol_wasm=e.ts_node_symbol_wasm,Module._ts_node_field_name_for_child_wasm=_ts_node_field_name_for_child_wasm=e.ts_node_field_name_for_child_wasm,Module._ts_node_field_name_for_named_child_wasm=_ts_node_field_name_for_named_child_wasm=e.ts_node_field_name_for_named_child_wasm,Module._ts_node_children_by_field_id_wasm=_ts_node_children_by_field_id_wasm=e.ts_node_children_by_field_id_wasm,Module._ts_node_first_child_for_byte_wasm=_ts_node_first_child_for_byte_wasm=e.ts_node_first_child_for_byte_wasm,Module._ts_node_first_named_child_for_byte_wasm=_ts_node_first_named_child_for_byte_wasm=e.ts_node_first_named_child_for_byte_wasm,Module._ts_node_grammar_symbol_wasm=_ts_node_grammar_symbol_wasm=e.ts_node_grammar_symbol_wasm,Module._ts_node_child_count_wasm=_ts_node_child_count_wasm=e.ts_node_child_count_wasm,Module._ts_node_named_child_count_wasm=_ts_node_named_child_count_wasm=e.ts_node_named_child_count_wasm,Module._ts_node_child_wasm=_ts_node_child_wasm=e.ts_node_child_wasm,Module._ts_node_named_child_wasm=_ts_node_named_child_wasm=e.ts_node_named_child_wasm,Module._ts_node_child_by_field_id_wasm=_ts_node_child_by_field_id_wasm=e.ts_node_child_by_field_id_wasm,Module._ts_node_next_sibling_wasm=_ts_node_next_sibling_wasm=e.ts_node_next_sibling_wasm,Module._ts_node_prev_sibling_wasm=_ts_node_prev_sibling_wasm=e.ts_node_prev_sibling_wasm,Module._ts_node_next_named_sibling_wasm=_ts_node_next_named_sibling_wasm=e.ts_node_next_named_sibling_wasm,Module._ts_node_prev_named_sibling_wasm=_ts_node_prev_named_sibling_wasm=e.ts_node_prev_named_sibling_wasm,Module._ts_node_descendant_count_wasm=_ts_node_descendant_count_wasm=e.ts_node_descendant_count_wasm,Module._ts_node_parent_wasm=_ts_node_parent_wasm=e.ts_node_parent_wasm,Module._ts_node_child_with_descendant_wasm=_ts_node_child_with_descendant_wasm=e.ts_node_child_with_descendant_wasm,Module._ts_node_descendant_for_index_wasm=_ts_node_descendant_for_index_wasm=e.ts_node_descendant_for_index_wasm,Module._ts_node_named_descendant_for_index_wasm=_ts_node_named_descendant_for_index_wasm=e.ts_node_named_descendant_for_index_wasm,Module._ts_node_descendant_for_position_wasm=_ts_node_descendant_for_position_wasm=e.ts_node_descendant_for_position_wasm,Module._ts_node_named_descendant_for_position_wasm=_ts_node_named_descendant_for_position_wasm=e.ts_node_named_descendant_for_position_wasm,Module._ts_node_start_point_wasm=_ts_node_start_point_wasm=e.ts_node_start_point_wasm,Module._ts_node_end_point_wasm=_ts_node_end_point_wasm=e.ts_node_end_point_wasm,Module._ts_node_start_index_wasm=_ts_node_start_index_wasm=e.ts_node_start_index_wasm,Module._ts_node_end_index_wasm=_ts_node_end_index_wasm=e.ts_node_end_index_wasm,Module._ts_node_to_string_wasm=_ts_node_to_string_wasm=e.ts_node_to_string_wasm,Module._ts_node_children_wasm=_ts_node_children_wasm=e.ts_node_children_wasm,Module._ts_node_named_children_wasm=_ts_node_named_children_wasm=e.ts_node_named_children_wasm,Module._ts_node_descendants_of_type_wasm=_ts_node_descendants_of_type_wasm=e.ts_node_descendants_of_type_wasm,Module._ts_node_is_named_wasm=_ts_node_is_named_wasm=e.ts_node_is_named_wasm,Module._ts_node_has_changes_wasm=_ts_node_has_changes_wasm=e.ts_node_has_changes_wasm,Module._ts_node_has_error_wasm=_ts_node_has_error_wasm=e.ts_node_has_error_wasm,Module._ts_node_is_error_wasm=_ts_node_is_error_wasm=e.ts_node_is_error_wasm,Module._ts_node_is_missing_wasm=_ts_node_is_missing_wasm=e.ts_node_is_missing_wasm,Module._ts_node_is_extra_wasm=_ts_node_is_extra_wasm=e.ts_node_is_extra_wasm,Module._ts_node_parse_state_wasm=_ts_node_parse_state_wasm=e.ts_node_parse_state_wasm,Module._ts_node_next_parse_state_wasm=_ts_node_next_parse_state_wasm=e.ts_node_next_parse_state_wasm,Module._ts_query_matches_wasm=_ts_query_matches_wasm=e.ts_query_matches_wasm,Module._ts_query_captures_wasm=_ts_query_captures_wasm=e.ts_query_captures_wasm,Module._memset=_memset=e.memset,Module._memcpy=_memcpy=e.memcpy,Module._memmove=_memmove=e.memmove,Module._iswalpha=_iswalpha=e.iswalpha,Module._iswblank=_iswblank=e.iswblank,Module._iswdigit=_iswdigit=e.iswdigit,Module._iswlower=_iswlower=e.iswlower,Module._iswupper=_iswupper=e.iswupper,Module._iswxdigit=_iswxdigit=e.iswxdigit,Module._memchr=_memchr=e.memchr,Module._strlen=_strlen=e.strlen,Module._strcmp=_strcmp=e.strcmp,Module._strncat=_strncat=e.strncat,Module._strncpy=_strncpy=e.strncpy,Module._towlower=_towlower=e.towlower,Module._towupper=_towupper=e.towupper,_setThrew=e.setThrew,__emscripten_stack_restore=e._emscripten_stack_restore,__emscripten_stack_alloc=e._emscripten_stack_alloc,_emscripten_stack_get_current=e.emscripten_stack_get_current,___wasm_apply_data_relocs=e.__wasm_apply_data_relocs}S(assignWasmExports,"assignWasmExports");var wasmImports={__heap_base:___heap_base,__indirect_function_table:wasmTable,__memory_base:___memory_base,__stack_high:___stack_high,__stack_low:___stack_low,__stack_pointer:___stack_pointer,__table_base:___table_base,_abort_js:__abort_js,emscripten_resize_heap:_emscripten_resize_heap,fd_close:_fd_close,fd_seek:_fd_seek,fd_write:_fd_write,memory:wasmMemory,tree_sitter_log_callback:_tree_sitter_log_callback,tree_sitter_parse_callback:_tree_sitter_parse_callback,tree_sitter_progress_callback:_tree_sitter_progress_callback,tree_sitter_query_progress_callback:_tree_sitter_query_progress_callback};function callMain(e=[]){var t=resolveGlobalSymbol("main").sym;if(!t)return;e.unshift(thisProgram);var n=e.length,r=stackAlloc((n+1)*4),s=r;e.forEach((a)=>{LE_HEAP_STORE_U32((s>>2)*4,stringToUTF8OnStack(a)),s+=4}),LE_HEAP_STORE_U32((s>>2)*4,0);try{var o=t(n,r);return exitJS(o,!0),o}catch(a){return handleException(a)}}S(callMain,"callMain");function run(e=arguments_){if(runDependencies>0){dependenciesFulfilled=run;return}if(preRun(),runDependencies>0){dependenciesFulfilled=run;return}function t(){if(Module.calledRun=!0,ABORT)return;initRuntime(),preMain(),readyPromiseResolve?.(Module),Module.onRuntimeInitialized?.();var n=Module.noInitialRun||!1;if(!n)callMain(e);postRun()}if(S(t,"doRun"),Module.setStatus)Module.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>Module.setStatus(""),1),t()},1);else t()}S(run,"run");var wasmExports=await createWasm();if(run(),runtimeInitialized)moduleRtn=Module;else moduleRtn=new Promise((e,t)=>{readyPromiseResolve=e,readyPromiseReject=t});return moduleRtn}async function dh(e){return uh??=await t$(e)}function fh(){return!!uh}function ph(e,t,n,r){if(e.length!==3)throw Error(`Wrong number of arguments to \`#${n}\` predicate. Expected 2, got ${e.length-1}`);if(!ih(e[1]))throw Error(`First argument of \`#${n}\` predicate must be a capture. Got "${e[1].value}"`);let s=n==="eq?"||n==="any-eq?",o=!n.startsWith("any-");if(ih(e[2])){let a=e[1].name,l=e[2].name;r[t].push((c)=>{let u=[],d=[];for(let p of c){if(p.name===a)u.push(p.node);if(p.name===l)d.push(p.node)}let f=S((p,h,g)=>g?p.text===h.text:p.text!==h.text,"compare");return o?u.every((p)=>d.some((h)=>f(p,h,s))):u.some((p)=>d.some((h)=>f(p,h,s)))})}else{let a=e[1].name,l=e[2].value,c=S((d)=>d.text===l,"matches"),u=S((d)=>d.text!==l,"doesNotMatch");r[t].push((d)=>{let f=[];for(let h of d)if(h.name===a)f.push(h.node);let p=s?c:u;return o?f.every(p):f.some(p)})}}function hh(e,t,n,r){if(e.length!==3)throw Error(`Wrong number of arguments to \`#${n}\` predicate. Expected 2, got ${e.length-1}.`);if(e[1].type!=="capture")throw Error(`First argument of \`#${n}\` predicate must be a capture. Got "${e[1].value}".`);if(e[2].type!=="string")throw Error(`Second argument of \`#${n}\` predicate must be a string. Got @${e[2].name}.`);let s=n==="match?"||n==="any-match?",o=!n.startsWith("any-"),a=e[1].name,l=new RegExp(e[2].value);r[t].push((c)=>{let u=[];for(let f of c)if(f.name===a)u.push(f.node.text);let d=S((f,p)=>p?l.test(f):!l.test(f),"test");if(u.length===0)return!s;return o?u.every((f)=>d(f,s)):u.some((f)=>d(f,s))})}function mh(e,t,n,r){if(e.length<2)throw Error(`Wrong number of arguments to \`#${n}\` predicate. Expected at least 1. Got ${e.length-1}.`);if(e[1].type!=="capture")throw Error(`First argument of \`#${n}\` predicate must be a capture. Got "${e[1].value}".`);let s=n==="any-of?",o=e[1].name,a=e.slice(2);if(!a.every(Nc))throw Error(`Arguments to \`#${n}\` predicate must be strings.".`);let l=a.map((c)=>c.value);r[t].push((c)=>{let u=[];for(let d of c)if(d.name===o)u.push(d.node.text);if(u.length===0)return!s;return u.every((d)=>l.includes(d))===s})}function gh(e,t,n,r,s){if(e.length<2||e.length>3)throw Error(`Wrong number of arguments to \`#${n}\` predicate. Expected 1 or 2. Got ${e.length-1}.`);if(!e.every(Nc))throw Error(`Arguments to \`#${n}\` predicate must be strings.".`);let o=n==="is?"?r:s;if(!o[t])o[t]={};o[t][e[1].value]=e[2]?.value??null}function _h(e,t,n){if(e.length<2||e.length>3)throw Error(`Wrong number of arguments to \`#set!\` predicate. Expected 1 or 2. Got ${e.length-1}.`);if(!e.every(Nc))throw Error('Arguments to `#set!` predicate must be strings.".');if(!n[t])n[t]={};n[t][e[1].value]=e[2]?.value??null}function wh(e,t,n,r,s,o,a,l,c,u,d){if(t===n$){let f=r[n];o.push({type:"capture",name:f})}else if(t===r$)o.push({type:"string",value:s[n]});else if(o.length>0){if(o[0].type!=="string")throw Error("Predicates must begin with a literal value");let f=o[0].value;switch(f){case"any-not-eq?":case"not-eq?":case"any-eq?":case"eq?":ph(o,e,f,a);break;case"any-not-match?":case"not-match?":case"any-match?":case"match?":hh(o,e,f,a);break;case"not-any-of?":case"any-of?":mh(o,e,f,a);break;case"is?":case"is-not?":gh(o,e,f,u,d);break;case"set!":_h(o,e,c);break;default:l[e].push({operator:f,operands:o.slice(1)})}o.length=0}}var JS,S=(e,t)=>JS(e,"name",{value:t,configurable:!0}),ET,rh=2,Y=4,Cc,xt,mn,rs,vt,Zn,m,XS,YS,ZS,QS,e$,Tc,t$,uh=null,V,Oc,Ic,Fc,n$=1,r$=2,i$,AT,ih,Nc,en,ts,Dc;var yh=qe(()=>{JS=Object.defineProperty,ET=class{static{S(this,"Edit")}startPosition;oldEndPosition;newEndPosition;startIndex;oldEndIndex;newEndIndex;constructor({startIndex:e,oldEndIndex:t,newEndIndex:n,startPosition:r,oldEndPosition:s,newEndPosition:o}){this.startIndex=e>>>0,this.oldEndIndex=t>>>0,this.newEndIndex=n>>>0,this.startPosition=r,this.oldEndPosition=s,this.newEndPosition=o}editPoint(e,t){let n=t,r={...e};if(t>=this.oldEndIndex){n=this.newEndIndex+(t-this.oldEndIndex);let s=e.row;r.row=this.newEndPosition.row+(e.row-this.oldEndPosition.row),r.column=s===this.oldEndPosition.row?this.newEndPosition.column+(e.column-this.oldEndPosition.column):e.column}else if(t>this.startIndex)n=this.newEndIndex,r.row=this.newEndPosition.row,r.column=this.newEndPosition.column;return{point:r,index:n}}editRange(e){let t={startIndex:e.startIndex,startPosition:{...e.startPosition},endIndex:e.endIndex,endPosition:{...e.endPosition}};if(e.endIndex>=this.oldEndIndex){if(e.endIndex!==Number.MAX_SAFE_INTEGER){if(t.endIndex=this.newEndIndex+(e.endIndex-this.oldEndIndex),t.endPosition={row:this.newEndPosition.row+(e.endPosition.row-this.oldEndPosition.row),column:e.endPosition.row===this.oldEndPosition.row?this.newEndPosition.column+(e.endPosition.column-this.oldEndPosition.column):e.endPosition.column},t.endIndex<this.newEndIndex)t.endIndex=Number.MAX_SAFE_INTEGER,t.endPosition={row:Number.MAX_SAFE_INTEGER,column:Number.MAX_SAFE_INTEGER}}}else if(e.endIndex>this.startIndex)t.endIndex=this.startIndex,t.endPosition={...this.startPosition};if(e.startIndex>=this.oldEndIndex){if(t.startIndex=this.newEndIndex+(e.startIndex-this.oldEndIndex),t.startPosition={row:this.newEndPosition.row+(e.startPosition.row-this.oldEndPosition.row),column:e.startPosition.row===this.oldEndPosition.row?this.newEndPosition.column+(e.startPosition.column-this.oldEndPosition.column):e.startPosition.column},t.startIndex<this.newEndIndex)t.startIndex=Number.MAX_SAFE_INTEGER,t.startPosition={row:Number.MAX_SAFE_INTEGER,column:Number.MAX_SAFE_INTEGER}}else if(e.startIndex>this.startIndex)t.startIndex=this.startIndex,t.startPosition={...this.startPosition};return t}},Cc=4*Y,xt=5*Y,mn=2*Y,rs=2*Y+2*mn,vt={row:0,column:0},Zn=Symbol("INTERNAL");S(Qr,"assertInternal");S(ns,"isPoint");S(sh,"setModule");XS=class{static{S(this,"LookaheadIterator")}[0]=0;language;constructor(e,t,n){Qr(e),this[0]=t,this.language=n}get currentTypeId(){return m._ts_lookahead_iterator_current_symbol(this[0])}get currentType(){return this.language.types[this.currentTypeId]||"ERROR"}delete(){m._ts_lookahead_iterator_delete(this[0]),this[0]=0}reset(e,t){if(m._ts_lookahead_iterator_reset(this[0],e[0],t))return this.language=e,!0;return!1}resetState(e){return Boolean(m._ts_lookahead_iterator_reset_state(this[0],e))}[Symbol.iterator](){return{next:S(()=>{if(m._ts_lookahead_iterator_next(this[0]))return{done:!1,value:this.currentType};return{done:!0,value:""}},"next")}}};S(Mc,"getText");YS=class e{static{S(this,"Tree")}[0]=0;textCallback;language;constructor(t,n,r,s){Qr(t),this[0]=n,this.language=r,this.textCallback=s}copy(){let t=m._ts_tree_copy(this[0]);return new e(Zn,t,this.language,this.textCallback)}delete(){m._ts_tree_delete(this[0]),this[0]=0}get rootNode(){return m._ts_tree_root_node_wasm(this[0]),Oe(this)}rootNodeWithOffset(t,n){let r=V+xt;return m.setValue(r,t,"i32"),Lt(r+Y,n),m._ts_tree_root_node_with_offset_wasm(this[0]),Oe(this)}edit(t){ah(t),m._ts_tree_edit_wasm(this[0])}walk(){return this.rootNode.walk()}getChangedRanges(t){if(!(t instanceof e))throw TypeError("Argument must be a Tree");m._ts_tree_get_changed_ranges_wasm(this[0],t[0]);let n=m.getValue(V,"i32"),r=m.getValue(V+Y,"i32"),s=Array(n);if(n>0){let o=r;for(let a=0;a<n;a++)s[a]=Jo(o),o+=rs;m._free(r)}return s}getIncludedRanges(){m._ts_tree_included_ranges_wasm(this[0]);let t=m.getValue(V,"i32"),n=m.getValue(V+Y,"i32"),r=Array(t);if(t>0){let s=n;for(let o=0;o<t;o++)r[o]=Jo(s),s+=rs;m._free(n)}return r}},ZS=class e{static{S(this,"TreeCursor")}[0]=0;[1]=0;[2]=0;[3]=0;tree;constructor(t,n){Qr(t),this.tree=n,Pt(this)}copy(){let t=new e(Zn,this.tree);return m._ts_tree_cursor_copy_wasm(this.tree[0]),Pt(t),t}delete(){xe(this),m._ts_tree_cursor_delete_wasm(this.tree[0]),this[0]=this[1]=this[2]=0}get currentNode(){return xe(this),m._ts_tree_cursor_current_node_wasm(this.tree[0]),Oe(this.tree)}get currentFieldId(){return xe(this),m._ts_tree_cursor_current_field_id_wasm(this.tree[0])}get currentFieldName(){return this.tree.language.fields[this.currentFieldId]}get currentDepth(){return xe(this),m._ts_tree_cursor_current_depth_wasm(this.tree[0])}get currentDescendantIndex(){return xe(this),m._ts_tree_cursor_current_descendant_index_wasm(this.tree[0])}get nodeType(){return this.tree.language.types[this.nodeTypeId]||"ERROR"}get nodeTypeId(){return xe(this),m._ts_tree_cursor_current_node_type_id_wasm(this.tree[0])}get nodeStateId(){return xe(this),m._ts_tree_cursor_current_node_state_id_wasm(this.tree[0])}get nodeId(){return xe(this),m._ts_tree_cursor_current_node_id_wasm(this.tree[0])}get nodeIsNamed(){return xe(this),m._ts_tree_cursor_current_node_is_named_wasm(this.tree[0])===1}get nodeIsMissing(){return xe(this),m._ts_tree_cursor_current_node_is_missing_wasm(this.tree[0])===1}get nodeText(){xe(this);let t=m._ts_tree_cursor_start_index_wasm(this.tree[0]),n=m._ts_tree_cursor_end_index_wasm(this.tree[0]);m._ts_tree_cursor_start_position_wasm(this.tree[0]);let r=vr(V);return Mc(this.tree,t,n,r)}get startPosition(){return xe(this),m._ts_tree_cursor_start_position_wasm(this.tree[0]),vr(V)}get endPosition(){return xe(this),m._ts_tree_cursor_end_position_wasm(this.tree[0]),vr(V)}get startIndex(){return xe(this),m._ts_tree_cursor_start_index_wasm(this.tree[0])}get endIndex(){return xe(this),m._ts_tree_cursor_end_index_wasm(this.tree[0])}gotoFirstChild(){xe(this);let t=m._ts_tree_cursor_goto_first_child_wasm(this.tree[0]);return Pt(this),t===1}gotoLastChild(){xe(this);let t=m._ts_tree_cursor_goto_last_child_wasm(this.tree[0]);return Pt(this),t===1}gotoParent(){xe(this);let t=m._ts_tree_cursor_goto_parent_wasm(this.tree[0]);return Pt(this),t===1}gotoNextSibling(){xe(this);let t=m._ts_tree_cursor_goto_next_sibling_wasm(this.tree[0]);return Pt(this),t===1}gotoPreviousSibling(){xe(this);let t=m._ts_tree_cursor_goto_previous_sibling_wasm(this.tree[0]);return Pt(this),t===1}gotoDescendant(t){xe(this),m._ts_tree_cursor_goto_descendant_wasm(this.tree[0],t),Pt(this)}gotoFirstChildForIndex(t){xe(this),m.setValue(V+Cc,t,"i32");let n=m._ts_tree_cursor_goto_first_child_for_index_wasm(this.tree[0]);return Pt(this),n===1}gotoFirstChildForPosition(t){xe(this),Lt(V+Cc,t);let n=m._ts_tree_cursor_goto_first_child_for_position_wasm(this.tree[0]);return Pt(this),n===1}reset(t){le(t),xe(this,V+xt),m._ts_tree_cursor_reset_wasm(this.tree[0]),Pt(this)}resetTo(t){xe(this,V),xe(t,V+Cc),m._ts_tree_cursor_reset_to_wasm(this.tree[0],t.tree[0]),Pt(this)}},QS=class{static{S(this,"Node")}[0]=0;_children;_namedChildren;constructor(e,{id:t,tree:n,startIndex:r,startPosition:s,other:o}){Qr(e),this[0]=o,this.id=t,this.tree=n,this.startIndex=r,this.startPosition=s}id;startIndex;startPosition;tree;get typeId(){return le(this),m._ts_node_symbol_wasm(this.tree[0])}get grammarId(){return le(this),m._ts_node_grammar_symbol_wasm(this.tree[0])}get type(){return this.tree.language.types[this.typeId]||"ERROR"}get grammarType(){return this.tree.language.types[this.grammarId]||"ERROR"}get isNamed(){return le(this),m._ts_node_is_named_wasm(this.tree[0])===1}get isExtra(){return le(this),m._ts_node_is_extra_wasm(this.tree[0])===1}get isError(){return le(this),m._ts_node_is_error_wasm(this.tree[0])===1}get isMissing(){return le(this),m._ts_node_is_missing_wasm(this.tree[0])===1}get hasChanges(){return le(this),m._ts_node_has_changes_wasm(this.tree[0])===1}get hasError(){return le(this),m._ts_node_has_error_wasm(this.tree[0])===1}get endIndex(){return le(this),m._ts_node_end_index_wasm(this.tree[0])}get endPosition(){return le(this),m._ts_node_end_point_wasm(this.tree[0]),vr(V)}get text(){return Mc(this.tree,this.startIndex,this.endIndex,this.startPosition)}get parseState(){return le(this),m._ts_node_parse_state_wasm(this.tree[0])}get nextParseState(){return le(this),m._ts_node_next_parse_state_wasm(this.tree[0])}equals(e){return this.tree===e.tree&&this.id===e.id}child(e){return le(this),m._ts_node_child_wasm(this.tree[0],e),Oe(this.tree)}namedChild(e){return le(this),m._ts_node_named_child_wasm(this.tree[0],e),Oe(this.tree)}childForFieldId(e){return le(this),m._ts_node_child_by_field_id_wasm(this.tree[0],e),Oe(this.tree)}childForFieldName(e){let t=this.tree.language.fields.indexOf(e);if(t!==-1)return this.childForFieldId(t);return null}fieldNameForChild(e){le(this);let t=m._ts_node_field_name_for_child_wasm(this.tree[0],e);if(!t)return null;return m.AsciiToString(t)}fieldNameForNamedChild(e){le(this);let t=m._ts_node_field_name_for_named_child_wasm(this.tree[0],e);if(!t)return null;return m.AsciiToString(t)}childrenForFieldName(e){let t=this.tree.language.fields.indexOf(e);if(t!==-1&&t!==0)return this.childrenForFieldId(t);return[]}childrenForFieldId(e){le(this),m._ts_node_children_by_field_id_wasm(this.tree[0],e);let t=m.getValue(V,"i32"),n=m.getValue(V+Y,"i32"),r=Array(t);if(t>0){let s=n;for(let o=0;o<t;o++)r[o]=Oe(this.tree,s),s+=xt;m._free(n)}return r}firstChildForIndex(e){le(this);let t=V+xt;return m.setValue(t,e,"i32"),m._ts_node_first_child_for_byte_wasm(this.tree[0]),Oe(this.tree)}firstNamedChildForIndex(e){le(this);let t=V+xt;return m.setValue(t,e,"i32"),m._ts_node_first_named_child_for_byte_wasm(this.tree[0]),Oe(this.tree)}get childCount(){return le(this),m._ts_node_child_count_wasm(this.tree[0])}get namedChildCount(){return le(this),m._ts_node_named_child_count_wasm(this.tree[0])}get firstChild(){return this.child(0)}get firstNamedChild(){return this.namedChild(0)}get lastChild(){return this.child(this.childCount-1)}get lastNamedChild(){return this.namedChild(this.namedChildCount-1)}get children(){if(!this._children){le(this),m._ts_node_children_wasm(this.tree[0]);let e=m.getValue(V,"i32"),t=m.getValue(V+Y,"i32");if(this._children=Array(e),e>0){let n=t;for(let r=0;r<e;r++)this._children[r]=Oe(this.tree,n),n+=xt;m._free(t)}}return this._children}get namedChildren(){if(!this._namedChildren){le(this),m._ts_node_named_children_wasm(this.tree[0]);let e=m.getValue(V,"i32"),t=m.getValue(V+Y,"i32");if(this._namedChildren=Array(e),e>0){let n=t;for(let r=0;r<e;r++)this._namedChildren[r]=Oe(this.tree,n),n+=xt;m._free(t)}}return this._namedChildren}descendantsOfType(e,t=vt,n=vt){if(!Array.isArray(e))e=[e];let r=[],s=this.tree.language.types;for(let u of e)if(u=="ERROR")r.push(65535);for(let u=0,d=s.length;u<d;u++)if(e.includes(s[u]))r.push(u);let o=m._malloc(Y*r.length);for(let u=0,d=r.length;u<d;u++)m.setValue(o+u*Y,r[u],"i32");le(this),m._ts_node_descendants_of_type_wasm(this.tree[0],o,r.length,t.row,t.column,n.row,n.column);let a=m.getValue(V,"i32"),l=m.getValue(V+Y,"i32"),c=Array(a);if(a>0){let u=l;for(let d=0;d<a;d++)c[d]=Oe(this.tree,u),u+=xt}return m._free(l),m._free(o),c}get nextSibling(){return le(this),m._ts_node_next_sibling_wasm(this.tree[0]),Oe(this.tree)}get previousSibling(){return le(this),m._ts_node_prev_sibling_wasm(this.tree[0]),Oe(this.tree)}get nextNamedSibling(){return le(this),m._ts_node_next_named_sibling_wasm(this.tree[0]),Oe(this.tree)}get previousNamedSibling(){return le(this),m._ts_node_prev_named_sibling_wasm(this.tree[0]),Oe(this.tree)}get descendantCount(){return le(this),m._ts_node_descendant_count_wasm(this.tree[0])}get parent(){return le(this),m._ts_node_parent_wasm(this.tree[0]),Oe(this.tree)}childWithDescendant(e){return le(this),le(e,1),m._ts_node_child_with_descendant_wasm(this.tree[0]),Oe(this.tree)}descendantForIndex(e,t=e){if(typeof e!=="number"||typeof t!=="number")throw Error("Arguments must be numbers");le(this);let n=V+xt;return m.setValue(n,e,"i32"),m.setValue(n+Y,t,"i32"),m._ts_node_descendant_for_index_wasm(this.tree[0]),Oe(this.tree)}namedDescendantForIndex(e,t=e){if(typeof e!=="number"||typeof t!=="number")throw Error("Arguments must be numbers");le(this);let n=V+xt;return m.setValue(n,e,"i32"),m.setValue(n+Y,t,"i32"),m._ts_node_named_descendant_for_index_wasm(this.tree[0]),Oe(this.tree)}descendantForPosition(e,t=e){if(!ns(e)||!ns(t))throw Error("Arguments must be {row, column} objects");le(this);let n=V+xt;return Lt(n,e),Lt(n+mn,t),m._ts_node_descendant_for_position_wasm(this.tree[0]),Oe(this.tree)}namedDescendantForPosition(e,t=e){if(!ns(e)||!ns(t))throw Error("Arguments must be {row, column} objects");le(this);let n=V+xt;return Lt(n,e),Lt(n+mn,t),m._ts_node_named_descendant_for_position_wasm(this.tree[0]),Oe(this.tree)}walk(){return le(this),m._ts_tree_cursor_new_wasm(this.tree[0]),new ZS(Zn,this.tree)}edit(e){if(this.startIndex>=e.oldEndIndex){this.startIndex=e.newEndIndex+(this.startIndex-e.oldEndIndex);let t,n;if(this.startPosition.row>e.oldEndPosition.row)t=this.startPosition.row-e.oldEndPosition.row,n=this.startPosition.column;else if(t=0,n=this.startPosition.column,this.startPosition.column>=e.oldEndPosition.column)n=this.startPosition.column-e.oldEndPosition.column;if(t>0)this.startPosition.row+=t,this.startPosition.column=n;else this.startPosition.column+=n}else if(this.startIndex>e.startIndex)this.startIndex=e.newEndIndex,this.startPosition.row=e.newEndPosition.row,this.startPosition.column=e.newEndPosition.column}toString(){le(this);let e=m._ts_node_to_string_wasm(this.tree[0]),t=m.AsciiToString(e);return m._free(e),t}};S(Pc,"unmarshalCaptures");S(le,"marshalNode");S(Oe,"unmarshalNode");S(xe,"marshalTreeCursor");S(Pt,"unmarshalTreeCursor");S(Lt,"marshalPoint");S(vr,"unmarshalPoint");S(oh,"marshalRange");S(Jo,"unmarshalRange");S(ah,"marshalEdit");S(lh,"unmarshalLanguageMetadata");e$=/^tree_sitter_\w+$/,Tc=class e{static{S(this,"Language")}[0]=0;types;fields;constructor(t,n){Qr(t),this[0]=n,this.types=Array(m._ts_language_symbol_count(this[0]));for(let r=0,s=this.types.length;r<s;r++)if(m._ts_language_symbol_type(this[0],r)<2)this.types[r]=m.UTF8ToString(m._ts_language_symbol_name(this[0],r));this.fields=Array(m._ts_language_field_count(this[0])+1);for(let r=0,s=this.fields.length;r<s;r++){let o=m._ts_language_field_name_for_id(this[0],r);if(o!==0)this.fields[r]=m.UTF8ToString(o);else this.fields[r]=null}}get name(){let t=m._ts_language_name(this[0]);if(t===0)return null;return m.UTF8ToString(t)}get abiVersion(){return m._ts_language_abi_version(this[0])}get metadata(){if(m._ts_language_metadata_wasm(this[0]),m.getValue(V,"i32")===0)return null;return lh(V+Y)}get fieldCount(){return this.fields.length-1}get stateCount(){return m._ts_language_state_count(this[0])}fieldIdForName(t){let n=this.fields.indexOf(t);return n!==-1?n:null}fieldNameForId(t){return this.fields[t]??null}idForNodeType(t,n){let r=m.lengthBytesUTF8(t),s=m._malloc(r+1);m.stringToUTF8(t,s,r+1);let o=m._ts_language_symbol_for_name(this[0],s,r,n?1:0);return m._free(s),o||null}get nodeTypeCount(){return m._ts_language_symbol_count(this[0])}nodeTypeForId(t){let n=m._ts_language_symbol_name(this[0],t);return n?m.UTF8ToString(n):null}nodeTypeIsNamed(t){return m._ts_language_type_is_named_wasm(this[0],t)?!0:!1}nodeTypeIsVisible(t){return m._ts_language_type_is_visible_wasm(this[0],t)?!0:!1}get supertypes(){m._ts_language_supertypes_wasm(this[0]);let t=m.getValue(V,"i32"),n=m.getValue(V+Y,"i32"),r=Array(t);if(t>0){let s=n;for(let o=0;o<t;o++)r[o]=m.getValue(s,"i16"),s+=rh}return r}subtypes(t){m._ts_language_subtypes_wasm(this[0],t);let n=m.getValue(V,"i32"),r=m.getValue(V+Y,"i32"),s=Array(n);if(n>0){let o=r;for(let a=0;a<n;a++)s[a]=m.getValue(o,"i16"),o+=rh}return s}nextState(t,n){return m._ts_language_next_state(this[0],t,n)}lookaheadIterator(t){let n=m._ts_lookahead_iterator_new(this[0],t);if(n)return new XS(Zn,n,this);return null}static async load(t){let n;if(t instanceof Uint8Array)n=t;else if(globalThis.process?.versions.node){let l=await import("fs/promises");n=await l.readFile(t)}else{let l=await fetch(t);if(!l.ok){let u=await l.text();throw Error(`Language.load failed with status ${l.status}.
28
+ `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();if(t&&e.find((r)=>t.is(r)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function xp(e){return e.map((t)=>{if(!t.startsWith("--inspect"))return t;let n,r="127.0.0.1",s="9229",o;if((o=t.match(/^(--inspect(-brk)?)$/))!==null)n=o[1];else if((o=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(n=o[1],/^\d+$/.test(o[3]))s=o[3];else r=o[3];else if((o=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)n=o[1],r=o[3],s=o[4];if(n&&s!=="0")return`${n}=${r}:${parseInt(s)+1}`;return t})}function gc(){if(J.env.NO_COLOR||J.env.FORCE_COLOR==="0"||J.env.FORCE_COLOR==="false")return!1;if(J.env.FORCE_COLOR||J.env.CLICOLOR_FORCE!==void 0)return!0;return}sR.Command=_c;sR.useColor=gc});var Qi=yr(function(TT,bc){var jo=process||{},Lp=jo.argv||[],Lo=jo.env||{},dR=!(!!Lo.NO_COLOR||Lp.includes("--no-color"))&&(!!Lo.FORCE_COLOR||Lp.includes("--color")||jo.platform==="win32"||(jo.stdout||{}).isTTY&&Lo.TERM!=="dumb"||!!Lo.CI),fR=(e,t,n=e)=>(r)=>{let s=""+r,o=s.indexOf(t,e.length);return~o?e+pR(s,t,n,o)+t:e+s+t},pR=(e,t,n,r)=>{let s="",o=0;do s+=e.substring(o,r)+n,o=r+t.length,r=e.indexOf(t,o);while(~r);return s+e.substring(o)},jp=(e=dR)=>{let t=e?fR:()=>String;return{isColorSupported:e,reset:t("\x1B[0m","\x1B[0m"),bold:t("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:t("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:t("\x1B[3m","\x1B[23m"),underline:t("\x1B[4m","\x1B[24m"),inverse:t("\x1B[7m","\x1B[27m"),hidden:t("\x1B[8m","\x1B[28m"),strikethrough:t("\x1B[9m","\x1B[29m"),black:t("\x1B[30m","\x1B[39m"),red:t("\x1B[31m","\x1B[39m"),green:t("\x1B[32m","\x1B[39m"),yellow:t("\x1B[33m","\x1B[39m"),blue:t("\x1B[34m","\x1B[39m"),magenta:t("\x1B[35m","\x1B[39m"),cyan:t("\x1B[36m","\x1B[39m"),white:t("\x1B[37m","\x1B[39m"),gray:t("\x1B[90m","\x1B[39m"),bgBlack:t("\x1B[40m","\x1B[49m"),bgRed:t("\x1B[41m","\x1B[49m"),bgGreen:t("\x1B[42m","\x1B[49m"),bgYellow:t("\x1B[43m","\x1B[49m"),bgBlue:t("\x1B[44m","\x1B[49m"),bgMagenta:t("\x1B[45m","\x1B[49m"),bgCyan:t("\x1B[46m","\x1B[49m"),bgWhite:t("\x1B[47m","\x1B[49m"),blackBright:t("\x1B[90m","\x1B[39m"),redBright:t("\x1B[91m","\x1B[39m"),greenBright:t("\x1B[92m","\x1B[39m"),yellowBright:t("\x1B[93m","\x1B[39m"),blueBright:t("\x1B[94m","\x1B[39m"),magentaBright:t("\x1B[95m","\x1B[39m"),cyanBright:t("\x1B[96m","\x1B[39m"),whiteBright:t("\x1B[97m","\x1B[39m"),bgBlackBright:t("\x1B[100m","\x1B[49m"),bgRedBright:t("\x1B[101m","\x1B[49m"),bgGreenBright:t("\x1B[102m","\x1B[49m"),bgYellowBright:t("\x1B[103m","\x1B[49m"),bgBlueBright:t("\x1B[104m","\x1B[49m"),bgMagentaBright:t("\x1B[105m","\x1B[49m"),bgCyanBright:t("\x1B[106m","\x1B[49m"),bgWhiteBright:t("\x1B[107m","\x1B[49m")}};bc.exports=jp();bc.exports.createColors=jp});import{extname as l$}from"path";function Lt(e){return c$[l$(e).toLowerCase()]??null}var c$;var rs=He(()=>{c$={".ts":"typescript",".mts":"typescript",".cts":"typescript",".tsx":"tsx",".js":"tsx",".jsx":"tsx",".mjs":"tsx",".cjs":"tsx",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".c":"cpp",".h":"cpp",".hpp":"cpp",".hh":"cpp"}});import{existsSync as _$}from"fs";import w$ from"os";import Vo from"path";function tn(e,t){let n=process.env[e]?.trim();if(n===void 0||n==="")return t;let r=Number(n);if(!Number.isFinite(r)||r<=0)throw Error(`${e} must be a positive number, got "${process.env[e]}"`);return r}function ta(e){if(e.provider!==void 0)Oc=e.provider;if(e.model!==void 0){if(An=e.model,e.modelMerge===void 0&&process.env.REVIEW_MODEL_MERGE===void 0)Sr=e.model}if(e.modelMerge!==void 0)Sr=e.modelMerge;if(e.modelWalk!==void 0)On=e.modelWalk;if(e.modelIntent!==void 0)ei=e.modelIntent;if(e.effort!==void 0){if(Qr=e.effort,e.effortAux===void 0&&process.env.REVIEW_EFFORT_AUX===void 0)en=e.effort}if(e.effortAux!==void 0)en=e.effortAux;if(e.sliceBudget!==void 0)Tc=e.sliceBudget;if(e.mergeBudget!==void 0)Dc=e.mergeBudget;if(e.walkBudget!==void 0)ss=e.walkBudget;if(e.partBudget!==void 0)Pc=e.partBudget;if(e.intentBudget!==void 0)Mc=e.intentBudget;if(e.pool!==void 0)Nc=e.pool;if(e.maxSlices!==void 0)Rr=e.maxSlices;if(e.maxSliceTokens!==void 0)Qn=e.maxSliceTokens;if(e.walkDiffTokens!==void 0)os=e.walkDiffTokens;if(e.maxSteps!==void 0)Jo=e.maxSteps;if(e.deadlineMs!==void 0)Ic=e.deadlineMs;if(e.grouping!==void 0)xr=e.grouping;if(e.artifacts!==void 0)ye=e.artifacts;if(e.out!==void 0)wt=e.out;if(e.extraExcludes!==void 0)as=e.extraExcludes;if(e.surfaces!==void 0)Yo=e.surfaces;if(e.postMinSeverity!==void 0)ti=e.postMinSeverity;if(e.dropQuestions!==void 0)Zo=e.dropQuestions;if(e.providers!==void 0)Qo=e.providers;if(e.childEnv!==void 0)Fc=e.childEnv;if(e.authImport!==void 0)ea=e.authImport;if(e.pluginStorage!==void 0)ls=e.pluginStorage}function ri(e){if(e.subject!==void 0)st=e.subject;if(e.releaseSubject!==void 0)zo=e.releaseSubject;if(e.repoName!==void 0)yt=e.repoName;if(e.signal!==void 0)ni=e.signal}function na(){st=process.cwd(),zo=async()=>{},yt="this repository",ni=void 0}var Zr,st,zo=async()=>{},ye,mh="opencode",Oc,Jo,Ic,An,Qr,On,Sr,ei,en,ss,Pc,Mc,xr,Tc,Dc,Nc,Rr,gh=2.4,Qn,os,_h,wt,yt="this repository",Xo,Yo,as,ti=null,Zo=!1,Qo,Fc,ea="",ls="",ni;var bt=He(()=>{Zr=_$(Vo.join(import.meta.dir,"system.md"))?import.meta.dir:Vo.join(import.meta.dir,"review-core"),st=process.cwd(),ye=process.env.CODE_REVIEW_ARTIFACTS??Vo.join(process.cwd(),".code-review"),Oc=process.env.REVIEW_PROVIDER??"anthropic",Jo=tn("REVIEW_MAX_STEPS",80),Ic=tn("REVIEW_DEADLINE_S",900)*1000,An=process.env.REVIEW_MODEL??"claude-opus-5-5",Qr=process.env.REVIEW_EFFORT??"medium",On=process.env.REVIEW_MODEL_WALK??"claude-sonnet-5-5",Sr=process.env.REVIEW_MODEL_MERGE??An,ei=process.env.REVIEW_MODEL_INTENT??"claude-haiku-5-5",en=process.env.REVIEW_EFFORT_AUX??Qr;ss=tn("WALK_BUDGET_USD",2),Pc=tn("PART_BUDGET",0.6),Mc=tn("INTENT_BUDGET_USD",0.1),xr=process.env.REVIEW_GROUPING??"code";if(xr!=="code"&&xr!=="model")throw Error(`REVIEW_GROUPING must be "code" or "model", got "${xr}"`);Tc=tn("SLICE_BUDGET_USD",3),Dc=tn("MERGE_BUDGET_USD",3),Nc=tn("SLICE_POOL",6),Rr=tn("MAX_SLICES",16),Qn=tn("MAX_SLICE_TOKENS",42000),os=tn("WALK_DIFF_TOKENS",1e5),_h=process.env.INLINE_MODE==="tier"?"tier":"none",wt=process.env.CODE_REVIEW_SCRATCH??Vo.join(w$.tmpdir(),"code-review-out"),Xo=Object.freeze({deploy:[],tooling:["^docs/","(^|/)[^/]*\\.config\\.[cm]?[jt]s$"]}),Yo={...Xo},as=[],Qo={},Fc={}});function ii(e){if(e!==tr)throw Error("Illegal constructor")}function us(e){return!!e&&typeof e.row==="number"&&typeof e.column==="number"}function Ah(e){m=e}function Wc(e,t,n,r){let s=n-t,o=e.textCallback(t,r);if(o){t+=o.length;while(t<n){let a=e.textCallback(t,r);if(a&&a.length>0)t+=a.length,o+=a;else break}if(t>n)o=o.slice(0,s)}return o??""}function Gc(e,t,n,r,s){for(let o=0,a=s.length;o<a;o++){let l=m.getValue(n,"i32");n+=Y;let c=Oe(t,n);n+=xt,s[o]={patternIndex:r,name:e.captureNames[l],node:c}}return n}function le(e,t=0){let n=V+t*xt;m.setValue(n,e.id,"i32"),n+=Y,m.setValue(n,e.startIndex,"i32"),n+=Y,m.setValue(n,e.startPosition.row,"i32"),n+=Y,m.setValue(n,e.startPosition.column,"i32"),n+=Y,m.setValue(n,e[0],"i32")}function Oe(e,t=V){let n=m.getValue(t,"i32");if(t+=Y,n===0)return null;let r=m.getValue(t,"i32");t+=Y;let s=m.getValue(t,"i32");t+=Y;let o=m.getValue(t,"i32");t+=Y;let a=m.getValue(t,"i32");return new U$(tr,{id:n,tree:e,startIndex:r,startPosition:{row:s,column:o},other:a})}function xe(e,t=V){m.setValue(t+0*Y,e[0],"i32"),m.setValue(t+1*Y,e[1],"i32"),m.setValue(t+2*Y,e[2],"i32"),m.setValue(t+3*Y,e[3],"i32")}function Mt(e){e[0]=m.getValue(V+0*Y,"i32"),e[1]=m.getValue(V+1*Y,"i32"),e[2]=m.getValue(V+2*Y,"i32"),e[3]=m.getValue(V+3*Y,"i32")}function jt(e,t){m.setValue(e,t.row,"i32"),m.setValue(e+Y,t.column,"i32")}function $r(e){return{row:m.getValue(e,"i32")>>>0,column:m.getValue(e+Y,"i32")>>>0}}function Oh(e,t){jt(e,t.startPosition),e+=_n,jt(e,t.endPosition),e+=_n,m.setValue(e,t.startIndex,"i32"),e+=Y,m.setValue(e,t.endIndex,"i32"),e+=Y}function ra(e){let t={};return t.startPosition=$r(e),e+=_n,t.endPosition=$r(e),e+=_n,t.startIndex=m.getValue(e,"i32")>>>0,e+=Y,t.endIndex=m.getValue(e,"i32")>>>0,t}function Ih(e,t=V){jt(t,e.startPosition),t+=_n,jt(t,e.oldEndPosition),t+=_n,jt(t,e.newEndPosition),t+=_n,m.setValue(t,e.startIndex,"i32"),t+=Y,m.setValue(t,e.oldEndIndex,"i32"),t+=Y,m.setValue(t,e.newEndIndex,"i32"),t+=Y}function Ph(e){let t=m.getValue(e,"i32"),n=m.getValue(e+=Y,"i32"),r=m.getValue(e+=Y,"i32");return{major_version:t,minor_version:n,patch_version:r}}async function Mh(moduleArg={}){var moduleRtn,Module=moduleArg,ENVIRONMENT_IS_WEB=typeof window=="object",ENVIRONMENT_IS_WORKER=typeof WorkerGlobalScope<"u",ENVIRONMENT_IS_NODE=typeof process=="object"&&process.versions?.node&&process.type!="renderer";if(ENVIRONMENT_IS_NODE){let{createRequire:e}=await import("module");var require=e(import.meta.url)}Module.currentQueryProgressCallback=null,Module.currentProgressCallback=null,Module.currentLogCallback=null,Module.currentParseCallback=null;var arguments_=[],thisProgram="./this.program",quit_=R((e,t)=>{throw t},"quit_"),_scriptName=import.meta.url,scriptDirectory="";function locateFile(e){if(Module.locateFile)return Module.locateFile(e,scriptDirectory);return scriptDirectory+e}R(locateFile,"locateFile");var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("fs");if(_scriptName.startsWith("file:"))scriptDirectory=require("path").dirname(require("url").fileURLToPath(_scriptName))+"/";if(readBinary=R((e)=>{e=isFileURI(e)?new URL(e):e;var t=fs.readFileSync(e);return t},"readBinary"),readAsync=R(async(e,t=!0)=>{e=isFileURI(e)?new URL(e):e;var n=fs.readFileSync(e,t?void 0:"utf8");return n},"readAsync"),process.argv.length>1)thisProgram=process.argv[1].replace(/\\/g,"/");arguments_=process.argv.slice(2),quit_=R((e,t)=>{throw process.exitCode=e,t},"quit_")}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER)readBinary=R((e)=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)},"readBinary");readAsync=R(async(e)=>{if(isFileURI(e))return new Promise((n,r)=>{var s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onload=()=>{if(s.status==200||s.status==0&&s.response){n(s.response);return}r(s.status)},s.onerror=r,s.send(null)});var t=await fetch(e,{credentials:"same-origin"});if(t.ok)return t.arrayBuffer();throw Error(t.status+" : "+t.url)},"readAsync")}}var out=console.log.bind(console),err=console.error.bind(console),dynamicLibraries=[],wasmBinary,ABORT=!1,EXITSTATUS,isFileURI=R((e)=>e.startsWith("file://"),"isFileURI"),readyPromiseResolve,readyPromiseReject,wasmMemory,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64,HEAP64,HEAPU64,HEAP_DATA_VIEW,runtimeInitialized=!1;function updateMemoryViews(){var e=wasmMemory.buffer;Module.HEAP8=HEAP8=new Int8Array(e),Module.HEAP16=HEAP16=new Int16Array(e),Module.HEAPU8=HEAPU8=new Uint8Array(e),Module.HEAPU16=HEAPU16=new Uint16Array(e),Module.HEAP32=HEAP32=new Int32Array(e),Module.HEAPU32=HEAPU32=new Uint32Array(e),Module.HEAPF32=HEAPF32=new Float32Array(e),Module.HEAPF64=HEAPF64=new Float64Array(e),Module.HEAP64=HEAP64=new BigInt64Array(e),Module.HEAPU64=HEAPU64=new BigUint64Array(e),Module.HEAP_DATA_VIEW=HEAP_DATA_VIEW=new DataView(e),LE_HEAP_UPDATE()}R(updateMemoryViews,"updateMemoryViews");function initMemory(){if(Module.wasmMemory)wasmMemory=Module.wasmMemory;else{var e=Module.INITIAL_MEMORY||33554432;wasmMemory=new WebAssembly.Memory({initial:e/65536,maximum:32768})}updateMemoryViews()}R(initMemory,"initMemory");var __RELOC_FUNCS__=[];function preRun(){if(Module.preRun){if(typeof Module.preRun=="function")Module.preRun=[Module.preRun];while(Module.preRun.length)addOnPreRun(Module.preRun.shift())}callRuntimeCallbacks(onPreRuns)}R(preRun,"preRun");function initRuntime(){runtimeInitialized=!0,callRuntimeCallbacks(__RELOC_FUNCS__),wasmExports.__wasm_call_ctors(),callRuntimeCallbacks(onPostCtors)}R(initRuntime,"initRuntime");function preMain(){}R(preMain,"preMain");function postRun(){if(Module.postRun){if(typeof Module.postRun=="function")Module.postRun=[Module.postRun];while(Module.postRun.length)addOnPostRun(Module.postRun.shift())}callRuntimeCallbacks(onPostRuns)}R(postRun,"postRun");function abort(e){Module.onAbort?.(e),e="Aborted("+e+")",err(e),ABORT=!0,e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);throw readyPromiseReject?.(t),t}R(abort,"abort");var wasmBinaryFile;function findWasmBinary(){if(Module.locateFile)return locateFile("web-tree-sitter.wasm");return new URL("web-tree-sitter.wasm",import.meta.url).href}R(findWasmBinary,"findWasmBinary");function getBinarySync(e){if(e==wasmBinaryFile&&wasmBinary)return new Uint8Array(wasmBinary);if(readBinary)return readBinary(e);throw"both async and sync fetching of the wasm failed"}R(getBinarySync,"getBinarySync");async function getWasmBinary(e){if(!wasmBinary)try{var t=await readAsync(e);return new Uint8Array(t)}catch{}return getBinarySync(e)}R(getWasmBinary,"getWasmBinary");async function instantiateArrayBuffer(e,t){try{var n=await getWasmBinary(e),r=await WebAssembly.instantiate(n,t);return r}catch(s){err(`failed to asynchronously prepare wasm: ${s}`),abort(s)}}R(instantiateArrayBuffer,"instantiateArrayBuffer");async function instantiateAsync(e,t,n){if(!e&&!isFileURI(t)&&!ENVIRONMENT_IS_NODE)try{var r=fetch(t,{credentials:"same-origin"}),s=await WebAssembly.instantiateStreaming(r,n);return s}catch(o){err(`wasm streaming compile failed: ${o}`),err("falling back to ArrayBuffer instantiation")}return instantiateArrayBuffer(t,n)}R(instantiateAsync,"instantiateAsync");function getWasmImports(){return{env:wasmImports,wasi_snapshot_preview1:wasmImports,"GOT.mem":new Proxy(wasmImports,GOTHandler),"GOT.func":new Proxy(wasmImports,GOTHandler)}}R(getWasmImports,"getWasmImports");async function createWasm(){function e(o,a){wasmExports=o.exports,wasmExports=relocateExports(wasmExports,1024);var l=getDylinkMetadata(a);if(l.neededDynlibs)dynamicLibraries=l.neededDynlibs.concat(dynamicLibraries);return mergeLibSymbols(wasmExports,"main"),LDSO.init(),loadDylibs(),__RELOC_FUNCS__.push(wasmExports.__wasm_apply_data_relocs),assignWasmExports(wasmExports),wasmExports}R(e,"receiveInstance");function t(o){return e(o.instance,o.module)}R(t,"receiveInstantiationResult");var n=getWasmImports();if(Module.instantiateWasm)return new Promise((o,a)=>{Module.instantiateWasm(n,(l,c)=>{o(e(l,c))})});wasmBinaryFile??=findWasmBinary();var r=await instantiateAsync(wasmBinary,wasmBinaryFile,n),s=t(r);return s}R(createWasm,"createWasm");class ExitStatus{static{R(this,"ExitStatus")}name="ExitStatus";constructor(e){this.message=`Program terminated with exit(${e})`,this.status=e}}var GOT={},currentModuleWeakSymbols=new Set([]),GOTHandler={get(e,t){var n=GOT[t];if(!n)n=GOT[t]=new WebAssembly.Global({value:"i32",mutable:!0});if(!currentModuleWeakSymbols.has(t))n.required=!0;return n}},LE_ATOMICS_NATIVE_BYTE_ORDER=[],LE_HEAP_LOAD_F32=R((e)=>HEAP_DATA_VIEW.getFloat32(e,!0),"LE_HEAP_LOAD_F32"),LE_HEAP_LOAD_F64=R((e)=>HEAP_DATA_VIEW.getFloat64(e,!0),"LE_HEAP_LOAD_F64"),LE_HEAP_LOAD_I16=R((e)=>HEAP_DATA_VIEW.getInt16(e,!0),"LE_HEAP_LOAD_I16"),LE_HEAP_LOAD_I32=R((e)=>HEAP_DATA_VIEW.getInt32(e,!0),"LE_HEAP_LOAD_I32"),LE_HEAP_LOAD_I64=R((e)=>HEAP_DATA_VIEW.getBigInt64(e,!0),"LE_HEAP_LOAD_I64"),LE_HEAP_LOAD_U32=R((e)=>HEAP_DATA_VIEW.getUint32(e,!0),"LE_HEAP_LOAD_U32"),LE_HEAP_STORE_F32=R((e,t)=>HEAP_DATA_VIEW.setFloat32(e,t,!0),"LE_HEAP_STORE_F32"),LE_HEAP_STORE_F64=R((e,t)=>HEAP_DATA_VIEW.setFloat64(e,t,!0),"LE_HEAP_STORE_F64"),LE_HEAP_STORE_I16=R((e,t)=>HEAP_DATA_VIEW.setInt16(e,t,!0),"LE_HEAP_STORE_I16"),LE_HEAP_STORE_I32=R((e,t)=>HEAP_DATA_VIEW.setInt32(e,t,!0),"LE_HEAP_STORE_I32"),LE_HEAP_STORE_I64=R((e,t)=>HEAP_DATA_VIEW.setBigInt64(e,t,!0),"LE_HEAP_STORE_I64"),LE_HEAP_STORE_U32=R((e,t)=>HEAP_DATA_VIEW.setUint32(e,t,!0),"LE_HEAP_STORE_U32"),callRuntimeCallbacks=R((e)=>{while(e.length>0)e.shift()(Module)},"callRuntimeCallbacks"),onPostRuns=[],addOnPostRun=R((e)=>onPostRuns.push(e),"addOnPostRun"),onPreRuns=[],addOnPreRun=R((e)=>onPreRuns.push(e),"addOnPreRun"),UTF8Decoder=typeof TextDecoder<"u"?new TextDecoder:void 0,findStringEnd=R((e,t,n,r)=>{var s=t+n;if(r)return s;while(e[t]&&!(t>=s))++t;return t},"findStringEnd"),UTF8ArrayToString=R((e,t=0,n,r)=>{var s=findStringEnd(e,t,n,r);if(s-t>16&&e.buffer&&UTF8Decoder)return UTF8Decoder.decode(e.subarray(t,s));var o="";while(t<s){var a=e[t++];if(!(a&128)){o+=String.fromCharCode(a);continue}var l=e[t++]&63;if((a&224)==192){o+=String.fromCharCode((a&31)<<6|l);continue}var c=e[t++]&63;if((a&240)==224)a=(a&15)<<12|l<<6|c;else a=(a&7)<<18|l<<12|c<<6|e[t++]&63;if(a<65536)o+=String.fromCharCode(a);else{var u=a-65536;o+=String.fromCharCode(55296|u>>10,56320|u&1023)}}return o},"UTF8ArrayToString"),getDylinkMetadata=R((e)=>{var t=0,n=0;function r(){return e[t++]}R(r,"getU8");function s(){var j=0,H=1;while(!0){var ve=e[t++];if(j+=(ve&127)*H,H*=128,!(ve&128))break}return j}R(s,"getLEB");function o(){var j=s();return t+=j,UTF8ArrayToString(e,t-j,j)}R(o,"getString");function a(){var j=s(),H=[];while(j--)H.push(o());return H}R(a,"getStringList");function l(j,H){if(j)throw Error(H)}if(R(l,"failIf"),e instanceof WebAssembly.Module){var c=WebAssembly.Module.customSections(e,"dylink.0");l(c.length===0,"need dylink section"),e=new Uint8Array(c[0]),n=e.length}else{var u=new Uint32Array(new Uint8Array(e.subarray(0,24)).buffer),d=u[0]==1836278016||u[0]==6386541;l(!d,"need to see wasm magic number"),l(e[8]!==0,"need the dylink section to be first"),t=9;var f=s();n=t+f;var p=o();l(p!=="dylink.0")}var h={neededDynlibs:[],tlsExports:new Set,weakImports:new Set,runtimePaths:[]},g=1,w=2,b=3,x=4,S=5,P=256,M=3,k=1;while(t<n){var E=r(),F=s();if(E===g)h.memorySize=s(),h.memoryAlign=s(),h.tableSize=s(),h.tableAlign=s();else if(E===w)h.neededDynlibs=a();else if(E===b){var L=s();while(L--){var O=o(),U=s();if(U&P)h.tlsExports.add(O)}}else if(E===x){var L=s();while(L--){var I=o(),O=o(),U=s();if((U&M)==k)h.weakImports.add(O)}}else if(E===S)h.runtimePaths=a();else t+=F}return h},"getDylinkMetadata");function getValue(e,t="i8"){if(t.endsWith("*"))t="*";switch(t){case"i1":return HEAP8[e];case"i8":return HEAP8[e];case"i16":return LE_HEAP_LOAD_I16((e>>1)*2);case"i32":return LE_HEAP_LOAD_I32((e>>2)*4);case"i64":return LE_HEAP_LOAD_I64((e>>3)*8);case"float":return LE_HEAP_LOAD_F32((e>>2)*4);case"double":return LE_HEAP_LOAD_F64((e>>3)*8);case"*":return LE_HEAP_LOAD_U32((e>>2)*4);default:abort(`invalid type for getValue: ${t}`)}}R(getValue,"getValue");var newDSO=R((e,t,n)=>{var r={refcount:1/0,name:e,exports:n,global:!0};if(LDSO.loadedLibsByName[e]=r,t!=null)LDSO.loadedLibsByHandle[t]=r;return r},"newDSO"),LDSO={loadedLibsByName:{},loadedLibsByHandle:{},init(){newDSO("__main__",0,wasmImports)}},___heap_base=78240,alignMemory=R((e,t)=>Math.ceil(e/t)*t,"alignMemory"),getMemory=R((e)=>{if(runtimeInitialized)return _calloc(e,1);var t=___heap_base,n=t+alignMemory(e,16);return ___heap_base=n,GOT.__heap_base.value=n,t},"getMemory"),isInternalSym=R((e)=>["__cpp_exception","__c_longjmp","__wasm_apply_data_relocs","__dso_handle","__tls_size","__tls_align","__set_stack_limits","_emscripten_tls_init","__wasm_init_tls","__wasm_call_ctors","__start_em_asm","__stop_em_asm","__start_em_js","__stop_em_js"].includes(e)||e.startsWith("__em_js__"),"isInternalSym"),uleb128EncodeWithLen=R((e)=>{let t=e.length;return[t%128|128,t>>7,...e]},"uleb128EncodeWithLen"),wasmTypeCodes={i:127,p:127,j:126,f:125,d:124,e:111},generateTypePack=R((e)=>uleb128EncodeWithLen(Array.from(e,(t)=>{var n=wasmTypeCodes[t];return n})),"generateTypePack"),convertJsFunctionToWasm=R((e,t)=>{var n=Uint8Array.of(0,97,115,109,1,0,0,0,1,...uleb128EncodeWithLen([1,96,...generateTypePack(t.slice(1)),...generateTypePack(t[0]==="v"?"":t[0])]),2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0),r=new WebAssembly.Module(n),s=new WebAssembly.Instance(r,{e:{f:e}}),o=s.exports.f;return o},"convertJsFunctionToWasm"),wasmTableMirror=[],wasmTable=new WebAssembly.Table({initial:31,element:"anyfunc"}),getWasmTableEntry=R((e)=>{var t=wasmTableMirror[e];if(!t)wasmTableMirror[e]=t=wasmTable.get(e);return t},"getWasmTableEntry"),updateTableMap=R((e,t)=>{if(functionsInTableMap)for(var n=e;n<e+t;n++){var r=getWasmTableEntry(n);if(r)functionsInTableMap.set(r,n)}},"updateTableMap"),functionsInTableMap,getFunctionAddress=R((e)=>{if(!functionsInTableMap)functionsInTableMap=new WeakMap,updateTableMap(0,wasmTable.length);return functionsInTableMap.get(e)||0},"getFunctionAddress"),freeTableIndexes=[],getEmptyTableSlot=R(()=>{if(freeTableIndexes.length)return freeTableIndexes.pop();return wasmTable.grow(1)},"getEmptyTableSlot"),setWasmTableEntry=R((e,t)=>{wasmTable.set(e,t),wasmTableMirror[e]=wasmTable.get(e)},"setWasmTableEntry"),addFunction=R((e,t)=>{var n=getFunctionAddress(e);if(n)return n;var r=getEmptyTableSlot();try{setWasmTableEntry(r,e)}catch(o){if(!(o instanceof TypeError))throw o;var s=convertJsFunctionToWasm(e,t);setWasmTableEntry(r,s)}return functionsInTableMap.set(e,r),r},"addFunction"),updateGOT=R((e,t)=>{for(var n in e){if(isInternalSym(n))continue;var r=e[n];if(GOT[n]||=new WebAssembly.Global({value:"i32",mutable:!0}),t||GOT[n].value==0)if(typeof r=="function")GOT[n].value=addFunction(r);else if(typeof r=="number")GOT[n].value=r;else err(`unhandled export type for '${n}': ${typeof r}`)}},"updateGOT"),relocateExports=R((e,t,n)=>{var r={};for(var s in e){var o=e[s];if(typeof o=="object")o=o.value;if(typeof o=="number")o+=t;r[s]=o}return updateGOT(r,n),r},"relocateExports"),isSymbolDefined=R((e)=>{var t=wasmImports[e];if(!t||t.stub)return!1;return!0},"isSymbolDefined"),dynCall=R((e,t,n=[],r=!1)=>{var s=getWasmTableEntry(t),o=s(...n);function a(l){return l}return R(a,"convert"),a(o)},"dynCall"),stackSave=R(()=>_emscripten_stack_get_current(),"stackSave"),stackRestore=R((e)=>__emscripten_stack_restore(e),"stackRestore"),createInvokeFunction=R((e)=>(t,...n)=>{var r=stackSave();try{return dynCall(e,t,n)}catch(s){if(stackRestore(r),s!==s+0)throw s;if(_setThrew(1,0),e[0]=="j")return 0n}},"createInvokeFunction"),resolveGlobalSymbol=R((e,t=!1)=>{var n;if(isSymbolDefined(e))n=wasmImports[e];else if(e.startsWith("invoke_"))n=wasmImports[e]=createInvokeFunction(e.split("_")[1]);return{sym:n,name:e}},"resolveGlobalSymbol"),onPostCtors=[],addOnPostCtor=R((e)=>onPostCtors.push(e),"addOnPostCtor"),UTF8ToString=R((e,t,n)=>e?UTF8ArrayToString(HEAPU8,e,t,n):"","UTF8ToString"),loadWebAssemblyModule=R((binary,flags,libName,localScope,handle)=>{var metadata=getDylinkMetadata(binary);function loadModule(){var memAlign=Math.pow(2,metadata.memoryAlign),memoryBase=metadata.memorySize?alignMemory(getMemory(metadata.memorySize+memAlign),memAlign):0,tableBase=metadata.tableSize?wasmTable.length:0;if(handle)HEAP8[handle+8]=1,LE_HEAP_STORE_U32((handle+12>>2)*4,memoryBase),LE_HEAP_STORE_I32((handle+16>>2)*4,metadata.memorySize),LE_HEAP_STORE_U32((handle+20>>2)*4,tableBase),LE_HEAP_STORE_I32((handle+24>>2)*4,metadata.tableSize);if(metadata.tableSize)wasmTable.grow(metadata.tableSize);var moduleExports;function resolveSymbol(e){var t=resolveGlobalSymbol(e).sym;if(!t&&localScope)t=localScope[e];if(!t)t=moduleExports[e];return t}R(resolveSymbol,"resolveSymbol");var proxyHandler={get(e,t){switch(t){case"__memory_base":return memoryBase;case"__table_base":return tableBase}if(t in wasmImports&&!wasmImports[t].stub){var n=wasmImports[t];return n}if(!(t in e)){var r;e[t]=(...s)=>(r||=resolveSymbol(t),r(...s))}return e[t]}},proxy=new Proxy({},proxyHandler);currentModuleWeakSymbols=metadata.weakImports;var info={"GOT.mem":new Proxy({},GOTHandler),"GOT.func":new Proxy({},GOTHandler),env:proxy,wasi_snapshot_preview1:proxy};function postInstantiation(module,instance){if(updateTableMap(tableBase,metadata.tableSize),moduleExports=relocateExports(instance.exports,memoryBase),!flags.allowUndefined)reportUndefinedSymbols();function addEmAsm(addr,body){var args=[],arity=0;for(;arity<16;arity++)if(body.indexOf("$"+arity)!=-1)args.push("$"+arity);else break;args=args.join(",");var func=`(${args}) => { ${body} };`;ASM_CONSTS[start]=eval(func)}if(R(addEmAsm,"addEmAsm"),"__start_em_asm"in moduleExports){var start=moduleExports.__start_em_asm,stop=moduleExports.__stop_em_asm;while(start<stop){var jsString=UTF8ToString(start);addEmAsm(start,jsString),start=HEAPU8.indexOf(0,start)+1}}function addEmJs(name,cSig,body){var jsArgs=[];if(cSig=cSig.slice(1,-1),cSig!="void"){cSig=cSig.split(",");for(var i in cSig){var jsArg=cSig[i].split(" ").pop();jsArgs.push(jsArg.replace("*",""))}}var func=`(${jsArgs}) => ${body};`;moduleExports[name]=eval(func)}R(addEmJs,"addEmJs");for(var name in moduleExports)if(name.startsWith("__em_js__")){var start=moduleExports[name],jsString=UTF8ToString(start),parts=jsString.split("<::>");addEmJs(name.replace("__em_js__",""),parts[0],parts[1]),delete moduleExports[name]}var applyRelocs=moduleExports.__wasm_apply_data_relocs;if(applyRelocs)if(runtimeInitialized)applyRelocs();else __RELOC_FUNCS__.push(applyRelocs);var init=moduleExports.__wasm_call_ctors;if(init)if(runtimeInitialized)init();else addOnPostCtor(init);return moduleExports}if(R(postInstantiation,"postInstantiation"),flags.loadAsync)return(async()=>{var e;if(binary instanceof WebAssembly.Module)e=new WebAssembly.Instance(binary,info);else({module:binary,instance:e}=await WebAssembly.instantiate(binary,info));return postInstantiation(binary,e)})();var module=binary instanceof WebAssembly.Module?binary:new WebAssembly.Module(binary),instance=new WebAssembly.Instance(module,info);return postInstantiation(module,instance)}if(R(loadModule,"loadModule"),flags={...flags,rpath:{parentLibPath:libName,paths:metadata.runtimePaths}},flags.loadAsync)return metadata.neededDynlibs.reduce((e,t)=>e.then(()=>loadDynamicLibrary(t,flags,localScope)),Promise.resolve()).then(loadModule);return metadata.neededDynlibs.forEach((e)=>loadDynamicLibrary(e,flags,localScope)),loadModule()},"loadWebAssemblyModule"),mergeLibSymbols=R((e,t)=>{for(var[n,r]of Object.entries(e)){let s=R((a)=>{if(!isSymbolDefined(a))wasmImports[a]=r},"setImport");s(n);let o="__main_argc_argv";if(n=="main")s(o);if(n==o)s("main")}},"mergeLibSymbols"),asyncLoad=R(async(e)=>{var t=await readAsync(e);return new Uint8Array(t)},"asyncLoad");function loadDynamicLibrary(e,t={global:!0,nodelete:!0},n,r){var s=LDSO.loadedLibsByName[e];if(s){if(!t.global){if(n)Object.assign(n,s.exports)}else if(!s.global)s.global=!0,mergeLibSymbols(s.exports,e);if(t.nodelete&&s.refcount!==1/0)s.refcount=1/0;if(s.refcount++,r)LDSO.loadedLibsByHandle[r]=s;return t.loadAsync?Promise.resolve(!0):!0}s=newDSO(e,r,"loading"),s.refcount=t.nodelete?1/0:1,s.global=t.global;function o(){if(r){var c=LE_HEAP_LOAD_U32((r+28>>2)*4),u=LE_HEAP_LOAD_U32((r+32>>2)*4);if(c&&u){var d=HEAP8.slice(c,c+u);return t.loadAsync?Promise.resolve(d):d}}var f=locateFile(e);if(t.loadAsync)return asyncLoad(f);if(!readBinary)throw Error(`${f}: file not found, and synchronous loading of external files is not available`);return readBinary(f)}R(o,"loadLibData");function a(){if(t.loadAsync)return o().then((c)=>loadWebAssemblyModule(c,t,e,n,r));return loadWebAssemblyModule(o(),t,e,n,r)}R(a,"getExports");function l(c){if(s.global)mergeLibSymbols(c,e);else if(n)Object.assign(n,c);s.exports=c}if(R(l,"moduleLoaded"),t.loadAsync)return a().then((c)=>(l(c),!0));return l(a()),!0}R(loadDynamicLibrary,"loadDynamicLibrary");var reportUndefinedSymbols=R(()=>{for(var[e,t]of Object.entries(GOT))if(t.value==0){var n=resolveGlobalSymbol(e,!0).sym;if(!n&&!t.required)continue;if(typeof n=="function")t.value=addFunction(n,n.sig);else if(typeof n=="number")t.value=n;else throw Error(`bad export type for '${e}': ${typeof n}`)}},"reportUndefinedSymbols"),runDependencies=0,dependenciesFulfilled=null,removeRunDependency=R((e)=>{if(runDependencies--,Module.monitorRunDependencies?.(runDependencies),runDependencies==0){if(dependenciesFulfilled){var t=dependenciesFulfilled;dependenciesFulfilled=null,t()}}},"removeRunDependency"),addRunDependency=R((e)=>{runDependencies++,Module.monitorRunDependencies?.(runDependencies)},"addRunDependency"),loadDylibs=R(async()=>{if(!dynamicLibraries.length){reportUndefinedSymbols();return}addRunDependency("loadDylibs");for(var e of dynamicLibraries)await loadDynamicLibrary(e,{loadAsync:!0,global:!0,nodelete:!0,allowUndefined:!0});reportUndefinedSymbols(),removeRunDependency("loadDylibs")},"loadDylibs"),noExitRuntime=!0;function setValue(e,t,n="i8"){if(n.endsWith("*"))n="*";switch(n){case"i1":HEAP8[e]=t;break;case"i8":HEAP8[e]=t;break;case"i16":LE_HEAP_STORE_I16((e>>1)*2,t);break;case"i32":LE_HEAP_STORE_I32((e>>2)*4,t);break;case"i64":LE_HEAP_STORE_I64((e>>3)*8,BigInt(t));break;case"float":LE_HEAP_STORE_F32((e>>2)*4,t);break;case"double":LE_HEAP_STORE_F64((e>>3)*8,t);break;case"*":LE_HEAP_STORE_U32((e>>2)*4,t);break;default:abort(`invalid type for setValue: ${n}`)}}R(setValue,"setValue");var ___memory_base=new WebAssembly.Global({value:"i32",mutable:!1},1024),___stack_high=78240,___stack_low=12704,___stack_pointer=new WebAssembly.Global({value:"i32",mutable:!0},78240),___table_base=new WebAssembly.Global({value:"i32",mutable:!1},1),__abort_js=R(()=>abort(""),"__abort_js");__abort_js.sig="v";var getHeapMax=R(()=>2147483648,"getHeapMax"),growMemory=R((e)=>{var t=wasmMemory.buffer.byteLength,n=(e-t+65535)/65536|0;try{return wasmMemory.grow(n),updateMemoryViews(),1}catch(r){}},"growMemory"),_emscripten_resize_heap=R((e)=>{var t=HEAPU8.length;e>>>=0;var n=getHeapMax();if(e>n)return!1;for(var r=1;r<=4;r*=2){var s=t*(1+0.2/r);s=Math.min(s,e+100663296);var o=Math.min(n,alignMemory(Math.max(e,s),65536)),a=growMemory(o);if(a)return!0}return!1},"_emscripten_resize_heap");_emscripten_resize_heap.sig="ip";var _fd_close=R((e)=>52,"_fd_close");_fd_close.sig="ii";var INT53_MAX=9007199254740992,INT53_MIN=-9007199254740992,bigintToI53Checked=R((e)=>e<INT53_MIN||e>INT53_MAX?NaN:Number(e),"bigintToI53Checked");function _fd_seek(e,t,n,r){return t=bigintToI53Checked(t),70}R(_fd_seek,"_fd_seek"),_fd_seek.sig="iijip";var printCharBuffers=[null,[],[]],printChar=R((e,t)=>{var n=printCharBuffers[e];if(t===0||t===10)(e===1?out:err)(UTF8ArrayToString(n)),n.length=0;else n.push(t)},"printChar"),_fd_write=R((e,t,n,r)=>{var s=0;for(var o=0;o<n;o++){var a=LE_HEAP_LOAD_U32((t>>2)*4),l=LE_HEAP_LOAD_U32((t+4>>2)*4);t+=8;for(var c=0;c<l;c++)printChar(e,HEAPU8[a+c]);s+=l}return LE_HEAP_STORE_U32((r>>2)*4,s),0},"_fd_write");_fd_write.sig="iippp";function _tree_sitter_log_callback(e,t){if(Module.currentLogCallback){let n=UTF8ToString(t);Module.currentLogCallback(n,e!==0)}}R(_tree_sitter_log_callback,"_tree_sitter_log_callback");function _tree_sitter_parse_callback(e,t,n,r,s){let a=Module.currentParseCallback(t,{row:n,column:r});if(typeof a==="string")setValue(s,a.length,"i32"),stringToUTF16(a,e,10240);else setValue(s,0,"i32")}R(_tree_sitter_parse_callback,"_tree_sitter_parse_callback");function _tree_sitter_progress_callback(e,t){if(Module.currentProgressCallback)return Module.currentProgressCallback({currentOffset:e,hasError:t});return!1}R(_tree_sitter_progress_callback,"_tree_sitter_progress_callback");function _tree_sitter_query_progress_callback(e){if(Module.currentQueryProgressCallback)return Module.currentQueryProgressCallback({currentOffset:e});return!1}R(_tree_sitter_query_progress_callback,"_tree_sitter_query_progress_callback");var runtimeKeepaliveCounter=0,keepRuntimeAlive=R(()=>noExitRuntime||runtimeKeepaliveCounter>0,"keepRuntimeAlive"),_proc_exit=R((e)=>{if(EXITSTATUS=e,!keepRuntimeAlive())Module.onExit?.(e),ABORT=!0;quit_(e,new ExitStatus(e))},"_proc_exit");_proc_exit.sig="vi";var exitJS=R((e,t)=>{EXITSTATUS=e,_proc_exit(e)},"exitJS"),handleException=R((e)=>{if(e instanceof ExitStatus||e=="unwind")return EXITSTATUS;quit_(1,e)},"handleException"),lengthBytesUTF8=R((e)=>{var t=0;for(var n=0;n<e.length;++n){var r=e.charCodeAt(n);if(r<=127)t++;else if(r<=2047)t+=2;else if(r>=55296&&r<=57343)t+=4,++n;else t+=3}return t},"lengthBytesUTF8"),stringToUTF8Array=R((e,t,n,r)=>{if(!(r>0))return 0;var s=n,o=n+r-1;for(var a=0;a<e.length;++a){var l=e.codePointAt(a);if(l<=127){if(n>=o)break;t[n++]=l}else if(l<=2047){if(n+1>=o)break;t[n++]=192|l>>6,t[n++]=128|l&63}else if(l<=65535){if(n+2>=o)break;t[n++]=224|l>>12,t[n++]=128|l>>6&63,t[n++]=128|l&63}else{if(n+3>=o)break;t[n++]=240|l>>18,t[n++]=128|l>>12&63,t[n++]=128|l>>6&63,t[n++]=128|l&63,a++}}return t[n]=0,n-s},"stringToUTF8Array"),stringToUTF8=R((e,t,n)=>stringToUTF8Array(e,HEAPU8,t,n),"stringToUTF8"),stackAlloc=R((e)=>__emscripten_stack_alloc(e),"stackAlloc"),stringToUTF8OnStack=R((e)=>{var t=lengthBytesUTF8(e)+1,n=stackAlloc(t);return stringToUTF8(e,n,t),n},"stringToUTF8OnStack"),AsciiToString=R((e)=>{var t="";while(!0){var n=HEAPU8[e++];if(!n)return t;t+=String.fromCharCode(n)}},"AsciiToString"),stringToUTF16=R((e,t,n)=>{if(n??=2147483647,n<2)return 0;n-=2;var r=t,s=n<e.length*2?n/2:e.length;for(var o=0;o<s;++o){var a=e.charCodeAt(o);LE_HEAP_STORE_I16((t>>1)*2,a),t+=2}return LE_HEAP_STORE_I16((t>>1)*2,0),t-r},"stringToUTF16");LE_ATOMICS_NATIVE_BYTE_ORDER=new Int8Array(new Int16Array([1]).buffer)[0]===1?[(e)=>e,(e)=>e,void 0,(e)=>e]:[(e)=>e,(e)=>((e&65280)<<8|(e&255)<<24)>>16,void 0,(e)=>e>>24&255|e>>8&65280|(e&65280)<<8|(e&255)<<24];function LE_HEAP_UPDATE(){HEAPU16.unsigned=(e)=>e&65535,HEAPU32.unsigned=(e)=>e>>>0}R(LE_HEAP_UPDATE,"LE_HEAP_UPDATE");{if(initMemory(),Module.noExitRuntime)noExitRuntime=Module.noExitRuntime;if(Module.print)out=Module.print;if(Module.printErr)err=Module.printErr;if(Module.dynamicLibraries)dynamicLibraries=Module.dynamicLibraries;if(Module.wasmBinary)wasmBinary=Module.wasmBinary;if(Module.arguments)arguments_=Module.arguments;if(Module.thisProgram)thisProgram=Module.thisProgram;if(Module.preInit){if(typeof Module.preInit=="function")Module.preInit=[Module.preInit];while(Module.preInit.length>0)Module.preInit.shift()()}}Module.setValue=setValue,Module.getValue=getValue,Module.UTF8ToString=UTF8ToString,Module.stringToUTF8=stringToUTF8,Module.lengthBytesUTF8=lengthBytesUTF8,Module.AsciiToString=AsciiToString,Module.stringToUTF16=stringToUTF16,Module.loadWebAssemblyModule=loadWebAssemblyModule,Module.LE_HEAP_STORE_I64=LE_HEAP_STORE_I64;var ASM_CONSTS={},_malloc,_calloc,_realloc,_free,_ts_range_edit,_memcmp,_ts_language_symbol_count,_ts_language_state_count,_ts_language_abi_version,_ts_language_name,_ts_language_field_count,_ts_language_next_state,_ts_language_symbol_name,_ts_language_symbol_for_name,_strncmp,_ts_language_symbol_type,_ts_language_field_name_for_id,_ts_lookahead_iterator_new,_ts_lookahead_iterator_delete,_ts_lookahead_iterator_reset_state,_ts_lookahead_iterator_reset,_ts_lookahead_iterator_next,_ts_lookahead_iterator_current_symbol,_ts_point_edit,_ts_parser_delete,_ts_parser_reset,_ts_parser_set_language,_ts_parser_set_included_ranges,_ts_query_new,_ts_query_delete,_iswspace,_iswalnum,_ts_query_pattern_count,_ts_query_capture_count,_ts_query_string_count,_ts_query_capture_name_for_id,_ts_query_capture_quantifier_for_id,_ts_query_string_value_for_id,_ts_query_predicates_for_pattern,_ts_query_start_byte_for_pattern,_ts_query_end_byte_for_pattern,_ts_query_is_pattern_rooted,_ts_query_is_pattern_non_local,_ts_query_is_pattern_guaranteed_at_step,_ts_query_disable_capture,_ts_query_disable_pattern,_ts_tree_copy,_ts_tree_delete,_ts_init,_ts_parser_new_wasm,_ts_parser_enable_logger_wasm,_ts_parser_parse_wasm,_ts_parser_included_ranges_wasm,_ts_language_type_is_named_wasm,_ts_language_type_is_visible_wasm,_ts_language_metadata_wasm,_ts_language_supertypes_wasm,_ts_language_subtypes_wasm,_ts_tree_root_node_wasm,_ts_tree_root_node_with_offset_wasm,_ts_tree_edit_wasm,_ts_tree_included_ranges_wasm,_ts_tree_get_changed_ranges_wasm,_ts_tree_cursor_new_wasm,_ts_tree_cursor_copy_wasm,_ts_tree_cursor_delete_wasm,_ts_tree_cursor_reset_wasm,_ts_tree_cursor_reset_to_wasm,_ts_tree_cursor_goto_first_child_wasm,_ts_tree_cursor_goto_last_child_wasm,_ts_tree_cursor_goto_first_child_for_index_wasm,_ts_tree_cursor_goto_first_child_for_position_wasm,_ts_tree_cursor_goto_next_sibling_wasm,_ts_tree_cursor_goto_previous_sibling_wasm,_ts_tree_cursor_goto_descendant_wasm,_ts_tree_cursor_goto_parent_wasm,_ts_tree_cursor_current_node_type_id_wasm,_ts_tree_cursor_current_node_state_id_wasm,_ts_tree_cursor_current_node_is_named_wasm,_ts_tree_cursor_current_node_is_missing_wasm,_ts_tree_cursor_current_node_id_wasm,_ts_tree_cursor_start_position_wasm,_ts_tree_cursor_end_position_wasm,_ts_tree_cursor_start_index_wasm,_ts_tree_cursor_end_index_wasm,_ts_tree_cursor_current_field_id_wasm,_ts_tree_cursor_current_depth_wasm,_ts_tree_cursor_current_descendant_index_wasm,_ts_tree_cursor_current_node_wasm,_ts_node_symbol_wasm,_ts_node_field_name_for_child_wasm,_ts_node_field_name_for_named_child_wasm,_ts_node_children_by_field_id_wasm,_ts_node_first_child_for_byte_wasm,_ts_node_first_named_child_for_byte_wasm,_ts_node_grammar_symbol_wasm,_ts_node_child_count_wasm,_ts_node_named_child_count_wasm,_ts_node_child_wasm,_ts_node_named_child_wasm,_ts_node_child_by_field_id_wasm,_ts_node_next_sibling_wasm,_ts_node_prev_sibling_wasm,_ts_node_next_named_sibling_wasm,_ts_node_prev_named_sibling_wasm,_ts_node_descendant_count_wasm,_ts_node_parent_wasm,_ts_node_child_with_descendant_wasm,_ts_node_descendant_for_index_wasm,_ts_node_named_descendant_for_index_wasm,_ts_node_descendant_for_position_wasm,_ts_node_named_descendant_for_position_wasm,_ts_node_start_point_wasm,_ts_node_end_point_wasm,_ts_node_start_index_wasm,_ts_node_end_index_wasm,_ts_node_to_string_wasm,_ts_node_children_wasm,_ts_node_named_children_wasm,_ts_node_descendants_of_type_wasm,_ts_node_is_named_wasm,_ts_node_has_changes_wasm,_ts_node_has_error_wasm,_ts_node_is_error_wasm,_ts_node_is_missing_wasm,_ts_node_is_extra_wasm,_ts_node_parse_state_wasm,_ts_node_next_parse_state_wasm,_ts_query_matches_wasm,_ts_query_captures_wasm,_memset,_memcpy,_memmove,_iswalpha,_iswblank,_iswdigit,_iswlower,_iswupper,_iswxdigit,_memchr,_strlen,_strcmp,_strncat,_strncpy,_towlower,_towupper,_setThrew,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,___wasm_apply_data_relocs;function assignWasmExports(e){Module._malloc=_malloc=e.malloc,Module._calloc=_calloc=e.calloc,Module._realloc=_realloc=e.realloc,Module._free=_free=e.free,Module._ts_range_edit=_ts_range_edit=e.ts_range_edit,Module._memcmp=_memcmp=e.memcmp,Module._ts_language_symbol_count=_ts_language_symbol_count=e.ts_language_symbol_count,Module._ts_language_state_count=_ts_language_state_count=e.ts_language_state_count,Module._ts_language_abi_version=_ts_language_abi_version=e.ts_language_abi_version,Module._ts_language_name=_ts_language_name=e.ts_language_name,Module._ts_language_field_count=_ts_language_field_count=e.ts_language_field_count,Module._ts_language_next_state=_ts_language_next_state=e.ts_language_next_state,Module._ts_language_symbol_name=_ts_language_symbol_name=e.ts_language_symbol_name,Module._ts_language_symbol_for_name=_ts_language_symbol_for_name=e.ts_language_symbol_for_name,Module._strncmp=_strncmp=e.strncmp,Module._ts_language_symbol_type=_ts_language_symbol_type=e.ts_language_symbol_type,Module._ts_language_field_name_for_id=_ts_language_field_name_for_id=e.ts_language_field_name_for_id,Module._ts_lookahead_iterator_new=_ts_lookahead_iterator_new=e.ts_lookahead_iterator_new,Module._ts_lookahead_iterator_delete=_ts_lookahead_iterator_delete=e.ts_lookahead_iterator_delete,Module._ts_lookahead_iterator_reset_state=_ts_lookahead_iterator_reset_state=e.ts_lookahead_iterator_reset_state,Module._ts_lookahead_iterator_reset=_ts_lookahead_iterator_reset=e.ts_lookahead_iterator_reset,Module._ts_lookahead_iterator_next=_ts_lookahead_iterator_next=e.ts_lookahead_iterator_next,Module._ts_lookahead_iterator_current_symbol=_ts_lookahead_iterator_current_symbol=e.ts_lookahead_iterator_current_symbol,Module._ts_point_edit=_ts_point_edit=e.ts_point_edit,Module._ts_parser_delete=_ts_parser_delete=e.ts_parser_delete,Module._ts_parser_reset=_ts_parser_reset=e.ts_parser_reset,Module._ts_parser_set_language=_ts_parser_set_language=e.ts_parser_set_language,Module._ts_parser_set_included_ranges=_ts_parser_set_included_ranges=e.ts_parser_set_included_ranges,Module._ts_query_new=_ts_query_new=e.ts_query_new,Module._ts_query_delete=_ts_query_delete=e.ts_query_delete,Module._iswspace=_iswspace=e.iswspace,Module._iswalnum=_iswalnum=e.iswalnum,Module._ts_query_pattern_count=_ts_query_pattern_count=e.ts_query_pattern_count,Module._ts_query_capture_count=_ts_query_capture_count=e.ts_query_capture_count,Module._ts_query_string_count=_ts_query_string_count=e.ts_query_string_count,Module._ts_query_capture_name_for_id=_ts_query_capture_name_for_id=e.ts_query_capture_name_for_id,Module._ts_query_capture_quantifier_for_id=_ts_query_capture_quantifier_for_id=e.ts_query_capture_quantifier_for_id,Module._ts_query_string_value_for_id=_ts_query_string_value_for_id=e.ts_query_string_value_for_id,Module._ts_query_predicates_for_pattern=_ts_query_predicates_for_pattern=e.ts_query_predicates_for_pattern,Module._ts_query_start_byte_for_pattern=_ts_query_start_byte_for_pattern=e.ts_query_start_byte_for_pattern,Module._ts_query_end_byte_for_pattern=_ts_query_end_byte_for_pattern=e.ts_query_end_byte_for_pattern,Module._ts_query_is_pattern_rooted=_ts_query_is_pattern_rooted=e.ts_query_is_pattern_rooted,Module._ts_query_is_pattern_non_local=_ts_query_is_pattern_non_local=e.ts_query_is_pattern_non_local,Module._ts_query_is_pattern_guaranteed_at_step=_ts_query_is_pattern_guaranteed_at_step=e.ts_query_is_pattern_guaranteed_at_step,Module._ts_query_disable_capture=_ts_query_disable_capture=e.ts_query_disable_capture,Module._ts_query_disable_pattern=_ts_query_disable_pattern=e.ts_query_disable_pattern,Module._ts_tree_copy=_ts_tree_copy=e.ts_tree_copy,Module._ts_tree_delete=_ts_tree_delete=e.ts_tree_delete,Module._ts_init=_ts_init=e.ts_init,Module._ts_parser_new_wasm=_ts_parser_new_wasm=e.ts_parser_new_wasm,Module._ts_parser_enable_logger_wasm=_ts_parser_enable_logger_wasm=e.ts_parser_enable_logger_wasm,Module._ts_parser_parse_wasm=_ts_parser_parse_wasm=e.ts_parser_parse_wasm,Module._ts_parser_included_ranges_wasm=_ts_parser_included_ranges_wasm=e.ts_parser_included_ranges_wasm,Module._ts_language_type_is_named_wasm=_ts_language_type_is_named_wasm=e.ts_language_type_is_named_wasm,Module._ts_language_type_is_visible_wasm=_ts_language_type_is_visible_wasm=e.ts_language_type_is_visible_wasm,Module._ts_language_metadata_wasm=_ts_language_metadata_wasm=e.ts_language_metadata_wasm,Module._ts_language_supertypes_wasm=_ts_language_supertypes_wasm=e.ts_language_supertypes_wasm,Module._ts_language_subtypes_wasm=_ts_language_subtypes_wasm=e.ts_language_subtypes_wasm,Module._ts_tree_root_node_wasm=_ts_tree_root_node_wasm=e.ts_tree_root_node_wasm,Module._ts_tree_root_node_with_offset_wasm=_ts_tree_root_node_with_offset_wasm=e.ts_tree_root_node_with_offset_wasm,Module._ts_tree_edit_wasm=_ts_tree_edit_wasm=e.ts_tree_edit_wasm,Module._ts_tree_included_ranges_wasm=_ts_tree_included_ranges_wasm=e.ts_tree_included_ranges_wasm,Module._ts_tree_get_changed_ranges_wasm=_ts_tree_get_changed_ranges_wasm=e.ts_tree_get_changed_ranges_wasm,Module._ts_tree_cursor_new_wasm=_ts_tree_cursor_new_wasm=e.ts_tree_cursor_new_wasm,Module._ts_tree_cursor_copy_wasm=_ts_tree_cursor_copy_wasm=e.ts_tree_cursor_copy_wasm,Module._ts_tree_cursor_delete_wasm=_ts_tree_cursor_delete_wasm=e.ts_tree_cursor_delete_wasm,Module._ts_tree_cursor_reset_wasm=_ts_tree_cursor_reset_wasm=e.ts_tree_cursor_reset_wasm,Module._ts_tree_cursor_reset_to_wasm=_ts_tree_cursor_reset_to_wasm=e.ts_tree_cursor_reset_to_wasm,Module._ts_tree_cursor_goto_first_child_wasm=_ts_tree_cursor_goto_first_child_wasm=e.ts_tree_cursor_goto_first_child_wasm,Module._ts_tree_cursor_goto_last_child_wasm=_ts_tree_cursor_goto_last_child_wasm=e.ts_tree_cursor_goto_last_child_wasm,Module._ts_tree_cursor_goto_first_child_for_index_wasm=_ts_tree_cursor_goto_first_child_for_index_wasm=e.ts_tree_cursor_goto_first_child_for_index_wasm,Module._ts_tree_cursor_goto_first_child_for_position_wasm=_ts_tree_cursor_goto_first_child_for_position_wasm=e.ts_tree_cursor_goto_first_child_for_position_wasm,Module._ts_tree_cursor_goto_next_sibling_wasm=_ts_tree_cursor_goto_next_sibling_wasm=e.ts_tree_cursor_goto_next_sibling_wasm,Module._ts_tree_cursor_goto_previous_sibling_wasm=_ts_tree_cursor_goto_previous_sibling_wasm=e.ts_tree_cursor_goto_previous_sibling_wasm,Module._ts_tree_cursor_goto_descendant_wasm=_ts_tree_cursor_goto_descendant_wasm=e.ts_tree_cursor_goto_descendant_wasm,Module._ts_tree_cursor_goto_parent_wasm=_ts_tree_cursor_goto_parent_wasm=e.ts_tree_cursor_goto_parent_wasm,Module._ts_tree_cursor_current_node_type_id_wasm=_ts_tree_cursor_current_node_type_id_wasm=e.ts_tree_cursor_current_node_type_id_wasm,Module._ts_tree_cursor_current_node_state_id_wasm=_ts_tree_cursor_current_node_state_id_wasm=e.ts_tree_cursor_current_node_state_id_wasm,Module._ts_tree_cursor_current_node_is_named_wasm=_ts_tree_cursor_current_node_is_named_wasm=e.ts_tree_cursor_current_node_is_named_wasm,Module._ts_tree_cursor_current_node_is_missing_wasm=_ts_tree_cursor_current_node_is_missing_wasm=e.ts_tree_cursor_current_node_is_missing_wasm,Module._ts_tree_cursor_current_node_id_wasm=_ts_tree_cursor_current_node_id_wasm=e.ts_tree_cursor_current_node_id_wasm,Module._ts_tree_cursor_start_position_wasm=_ts_tree_cursor_start_position_wasm=e.ts_tree_cursor_start_position_wasm,Module._ts_tree_cursor_end_position_wasm=_ts_tree_cursor_end_position_wasm=e.ts_tree_cursor_end_position_wasm,Module._ts_tree_cursor_start_index_wasm=_ts_tree_cursor_start_index_wasm=e.ts_tree_cursor_start_index_wasm,Module._ts_tree_cursor_end_index_wasm=_ts_tree_cursor_end_index_wasm=e.ts_tree_cursor_end_index_wasm,Module._ts_tree_cursor_current_field_id_wasm=_ts_tree_cursor_current_field_id_wasm=e.ts_tree_cursor_current_field_id_wasm,Module._ts_tree_cursor_current_depth_wasm=_ts_tree_cursor_current_depth_wasm=e.ts_tree_cursor_current_depth_wasm,Module._ts_tree_cursor_current_descendant_index_wasm=_ts_tree_cursor_current_descendant_index_wasm=e.ts_tree_cursor_current_descendant_index_wasm,Module._ts_tree_cursor_current_node_wasm=_ts_tree_cursor_current_node_wasm=e.ts_tree_cursor_current_node_wasm,Module._ts_node_symbol_wasm=_ts_node_symbol_wasm=e.ts_node_symbol_wasm,Module._ts_node_field_name_for_child_wasm=_ts_node_field_name_for_child_wasm=e.ts_node_field_name_for_child_wasm,Module._ts_node_field_name_for_named_child_wasm=_ts_node_field_name_for_named_child_wasm=e.ts_node_field_name_for_named_child_wasm,Module._ts_node_children_by_field_id_wasm=_ts_node_children_by_field_id_wasm=e.ts_node_children_by_field_id_wasm,Module._ts_node_first_child_for_byte_wasm=_ts_node_first_child_for_byte_wasm=e.ts_node_first_child_for_byte_wasm,Module._ts_node_first_named_child_for_byte_wasm=_ts_node_first_named_child_for_byte_wasm=e.ts_node_first_named_child_for_byte_wasm,Module._ts_node_grammar_symbol_wasm=_ts_node_grammar_symbol_wasm=e.ts_node_grammar_symbol_wasm,Module._ts_node_child_count_wasm=_ts_node_child_count_wasm=e.ts_node_child_count_wasm,Module._ts_node_named_child_count_wasm=_ts_node_named_child_count_wasm=e.ts_node_named_child_count_wasm,Module._ts_node_child_wasm=_ts_node_child_wasm=e.ts_node_child_wasm,Module._ts_node_named_child_wasm=_ts_node_named_child_wasm=e.ts_node_named_child_wasm,Module._ts_node_child_by_field_id_wasm=_ts_node_child_by_field_id_wasm=e.ts_node_child_by_field_id_wasm,Module._ts_node_next_sibling_wasm=_ts_node_next_sibling_wasm=e.ts_node_next_sibling_wasm,Module._ts_node_prev_sibling_wasm=_ts_node_prev_sibling_wasm=e.ts_node_prev_sibling_wasm,Module._ts_node_next_named_sibling_wasm=_ts_node_next_named_sibling_wasm=e.ts_node_next_named_sibling_wasm,Module._ts_node_prev_named_sibling_wasm=_ts_node_prev_named_sibling_wasm=e.ts_node_prev_named_sibling_wasm,Module._ts_node_descendant_count_wasm=_ts_node_descendant_count_wasm=e.ts_node_descendant_count_wasm,Module._ts_node_parent_wasm=_ts_node_parent_wasm=e.ts_node_parent_wasm,Module._ts_node_child_with_descendant_wasm=_ts_node_child_with_descendant_wasm=e.ts_node_child_with_descendant_wasm,Module._ts_node_descendant_for_index_wasm=_ts_node_descendant_for_index_wasm=e.ts_node_descendant_for_index_wasm,Module._ts_node_named_descendant_for_index_wasm=_ts_node_named_descendant_for_index_wasm=e.ts_node_named_descendant_for_index_wasm,Module._ts_node_descendant_for_position_wasm=_ts_node_descendant_for_position_wasm=e.ts_node_descendant_for_position_wasm,Module._ts_node_named_descendant_for_position_wasm=_ts_node_named_descendant_for_position_wasm=e.ts_node_named_descendant_for_position_wasm,Module._ts_node_start_point_wasm=_ts_node_start_point_wasm=e.ts_node_start_point_wasm,Module._ts_node_end_point_wasm=_ts_node_end_point_wasm=e.ts_node_end_point_wasm,Module._ts_node_start_index_wasm=_ts_node_start_index_wasm=e.ts_node_start_index_wasm,Module._ts_node_end_index_wasm=_ts_node_end_index_wasm=e.ts_node_end_index_wasm,Module._ts_node_to_string_wasm=_ts_node_to_string_wasm=e.ts_node_to_string_wasm,Module._ts_node_children_wasm=_ts_node_children_wasm=e.ts_node_children_wasm,Module._ts_node_named_children_wasm=_ts_node_named_children_wasm=e.ts_node_named_children_wasm,Module._ts_node_descendants_of_type_wasm=_ts_node_descendants_of_type_wasm=e.ts_node_descendants_of_type_wasm,Module._ts_node_is_named_wasm=_ts_node_is_named_wasm=e.ts_node_is_named_wasm,Module._ts_node_has_changes_wasm=_ts_node_has_changes_wasm=e.ts_node_has_changes_wasm,Module._ts_node_has_error_wasm=_ts_node_has_error_wasm=e.ts_node_has_error_wasm,Module._ts_node_is_error_wasm=_ts_node_is_error_wasm=e.ts_node_is_error_wasm,Module._ts_node_is_missing_wasm=_ts_node_is_missing_wasm=e.ts_node_is_missing_wasm,Module._ts_node_is_extra_wasm=_ts_node_is_extra_wasm=e.ts_node_is_extra_wasm,Module._ts_node_parse_state_wasm=_ts_node_parse_state_wasm=e.ts_node_parse_state_wasm,Module._ts_node_next_parse_state_wasm=_ts_node_next_parse_state_wasm=e.ts_node_next_parse_state_wasm,Module._ts_query_matches_wasm=_ts_query_matches_wasm=e.ts_query_matches_wasm,Module._ts_query_captures_wasm=_ts_query_captures_wasm=e.ts_query_captures_wasm,Module._memset=_memset=e.memset,Module._memcpy=_memcpy=e.memcpy,Module._memmove=_memmove=e.memmove,Module._iswalpha=_iswalpha=e.iswalpha,Module._iswblank=_iswblank=e.iswblank,Module._iswdigit=_iswdigit=e.iswdigit,Module._iswlower=_iswlower=e.iswlower,Module._iswupper=_iswupper=e.iswupper,Module._iswxdigit=_iswxdigit=e.iswxdigit,Module._memchr=_memchr=e.memchr,Module._strlen=_strlen=e.strlen,Module._strcmp=_strcmp=e.strcmp,Module._strncat=_strncat=e.strncat,Module._strncpy=_strncpy=e.strncpy,Module._towlower=_towlower=e.towlower,Module._towupper=_towupper=e.towupper,_setThrew=e.setThrew,__emscripten_stack_restore=e._emscripten_stack_restore,__emscripten_stack_alloc=e._emscripten_stack_alloc,_emscripten_stack_get_current=e.emscripten_stack_get_current,___wasm_apply_data_relocs=e.__wasm_apply_data_relocs}R(assignWasmExports,"assignWasmExports");var wasmImports={__heap_base:___heap_base,__indirect_function_table:wasmTable,__memory_base:___memory_base,__stack_high:___stack_high,__stack_low:___stack_low,__stack_pointer:___stack_pointer,__table_base:___table_base,_abort_js:__abort_js,emscripten_resize_heap:_emscripten_resize_heap,fd_close:_fd_close,fd_seek:_fd_seek,fd_write:_fd_write,memory:wasmMemory,tree_sitter_log_callback:_tree_sitter_log_callback,tree_sitter_parse_callback:_tree_sitter_parse_callback,tree_sitter_progress_callback:_tree_sitter_progress_callback,tree_sitter_query_progress_callback:_tree_sitter_query_progress_callback};function callMain(e=[]){var t=resolveGlobalSymbol("main").sym;if(!t)return;e.unshift(thisProgram);var n=e.length,r=stackAlloc((n+1)*4),s=r;e.forEach((a)=>{LE_HEAP_STORE_U32((s>>2)*4,stringToUTF8OnStack(a)),s+=4}),LE_HEAP_STORE_U32((s>>2)*4,0);try{var o=t(n,r);return exitJS(o,!0),o}catch(a){return handleException(a)}}R(callMain,"callMain");function run(e=arguments_){if(runDependencies>0){dependenciesFulfilled=run;return}if(preRun(),runDependencies>0){dependenciesFulfilled=run;return}function t(){if(Module.calledRun=!0,ABORT)return;initRuntime(),preMain(),readyPromiseResolve?.(Module),Module.onRuntimeInitialized?.();var n=Module.noInitialRun||!1;if(!n)callMain(e);postRun()}if(R(t,"doRun"),Module.setStatus)Module.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>Module.setStatus(""),1),t()},1);else t()}R(run,"run");var wasmExports=await createWasm();if(run(),runtimeInitialized)moduleRtn=Module;else moduleRtn=new Promise((e,t)=>{readyPromiseResolve=e,readyPromiseReject=t});return moduleRtn}async function Dh(e){return Th??=await q$(e)}function Nh(){return!!Th}function Fh(e,t,n,r){if(e.length!==3)throw Error(`Wrong number of arguments to \`#${n}\` predicate. Expected 2, got ${e.length-1}`);if(!Ch(e[1]))throw Error(`First argument of \`#${n}\` predicate must be a capture. Got "${e[1].value}"`);let s=n==="eq?"||n==="any-eq?",o=!n.startsWith("any-");if(Ch(e[2])){let a=e[1].name,l=e[2].name;r[t].push((c)=>{let u=[],d=[];for(let p of c){if(p.name===a)u.push(p.node);if(p.name===l)d.push(p.node)}let f=R((p,h,g)=>g?p.text===h.text:p.text!==h.text,"compare");return o?u.every((p)=>d.some((h)=>f(p,h,s))):u.some((p)=>d.some((h)=>f(p,h,s)))})}else{let a=e[1].name,l=e[2].value,c=R((d)=>d.text===l,"matches"),u=R((d)=>d.text!==l,"doesNotMatch");r[t].push((d)=>{let f=[];for(let h of d)if(h.name===a)f.push(h.node);let p=s?c:u;return o?f.every(p):f.some(p)})}}function Lh(e,t,n,r){if(e.length!==3)throw Error(`Wrong number of arguments to \`#${n}\` predicate. Expected 2, got ${e.length-1}.`);if(e[1].type!=="capture")throw Error(`First argument of \`#${n}\` predicate must be a capture. Got "${e[1].value}".`);if(e[2].type!=="string")throw Error(`Second argument of \`#${n}\` predicate must be a string. Got @${e[2].name}.`);let s=n==="match?"||n==="any-match?",o=!n.startsWith("any-"),a=e[1].name,l=new RegExp(e[2].value);r[t].push((c)=>{let u=[];for(let f of c)if(f.name===a)u.push(f.node.text);let d=R((f,p)=>p?l.test(f):!l.test(f),"test");if(u.length===0)return!s;return o?u.every((f)=>d(f,s)):u.some((f)=>d(f,s))})}function jh(e,t,n,r){if(e.length<2)throw Error(`Wrong number of arguments to \`#${n}\` predicate. Expected at least 1. Got ${e.length-1}.`);if(e[1].type!=="capture")throw Error(`First argument of \`#${n}\` predicate must be a capture. Got "${e[1].value}".`);let s=n==="any-of?",o=e[1].name,a=e.slice(2);if(!a.every(Jc))throw Error(`Arguments to \`#${n}\` predicate must be strings.".`);let l=a.map((c)=>c.value);r[t].push((c)=>{let u=[];for(let d of c)if(d.name===o)u.push(d.node.text);if(u.length===0)return!s;return u.every((d)=>l.includes(d))===s})}function Uh(e,t,n,r,s){if(e.length<2||e.length>3)throw Error(`Wrong number of arguments to \`#${n}\` predicate. Expected 1 or 2. Got ${e.length-1}.`);if(!e.every(Jc))throw Error(`Arguments to \`#${n}\` predicate must be strings.".`);let o=n==="is?"?r:s;if(!o[t])o[t]={};o[t][e[1].value]=e[2]?.value??null}function Bh(e,t,n){if(e.length<2||e.length>3)throw Error(`Wrong number of arguments to \`#set!\` predicate. Expected 1 or 2. Got ${e.length-1}.`);if(!e.every(Jc))throw Error('Arguments to `#set!` predicate must be strings.".');if(!n[t])n[t]={};n[t][e[1].value]=e[2]?.value??null}function qh(e,t,n,r,s,o,a,l,c,u,d){if(t===H$){let f=r[n];o.push({type:"capture",name:f})}else if(t===K$)o.push({type:"string",value:s[n]});else if(o.length>0){if(o[0].type!=="string")throw Error("Predicates must begin with a literal value");let f=o[0].value;switch(f){case"any-not-eq?":case"not-eq?":case"any-eq?":case"eq?":Fh(o,e,f,a);break;case"any-not-match?":case"not-match?":case"any-match?":case"match?":Lh(o,e,f,a);break;case"not-any-of?":case"any-of?":jh(o,e,f,a);break;case"is?":case"is-not?":Uh(o,e,f,u,d);break;case"set!":Bh(o,e,c);break;default:l[e].push({operator:f,operands:o.slice(1)})}o.length=0}}var N$,R=(e,t)=>N$(e,"name",{value:t,configurable:!0}),RD,Eh=2,Y=4,qc,xt,_n,ds,vt,tr,m,F$,L$,j$,U$,B$,Vc,q$,Th=null,V,Hc,Kc,zc,H$=1,K$=2,G$,$D,Ch,Jc,nn,cs,Xc;var Hh=He(()=>{N$=Object.defineProperty,RD=class{static{R(this,"Edit")}startPosition;oldEndPosition;newEndPosition;startIndex;oldEndIndex;newEndIndex;constructor({startIndex:e,oldEndIndex:t,newEndIndex:n,startPosition:r,oldEndPosition:s,newEndPosition:o}){this.startIndex=e>>>0,this.oldEndIndex=t>>>0,this.newEndIndex=n>>>0,this.startPosition=r,this.oldEndPosition=s,this.newEndPosition=o}editPoint(e,t){let n=t,r={...e};if(t>=this.oldEndIndex){n=this.newEndIndex+(t-this.oldEndIndex);let s=e.row;r.row=this.newEndPosition.row+(e.row-this.oldEndPosition.row),r.column=s===this.oldEndPosition.row?this.newEndPosition.column+(e.column-this.oldEndPosition.column):e.column}else if(t>this.startIndex)n=this.newEndIndex,r.row=this.newEndPosition.row,r.column=this.newEndPosition.column;return{point:r,index:n}}editRange(e){let t={startIndex:e.startIndex,startPosition:{...e.startPosition},endIndex:e.endIndex,endPosition:{...e.endPosition}};if(e.endIndex>=this.oldEndIndex){if(e.endIndex!==Number.MAX_SAFE_INTEGER){if(t.endIndex=this.newEndIndex+(e.endIndex-this.oldEndIndex),t.endPosition={row:this.newEndPosition.row+(e.endPosition.row-this.oldEndPosition.row),column:e.endPosition.row===this.oldEndPosition.row?this.newEndPosition.column+(e.endPosition.column-this.oldEndPosition.column):e.endPosition.column},t.endIndex<this.newEndIndex)t.endIndex=Number.MAX_SAFE_INTEGER,t.endPosition={row:Number.MAX_SAFE_INTEGER,column:Number.MAX_SAFE_INTEGER}}}else if(e.endIndex>this.startIndex)t.endIndex=this.startIndex,t.endPosition={...this.startPosition};if(e.startIndex>=this.oldEndIndex){if(t.startIndex=this.newEndIndex+(e.startIndex-this.oldEndIndex),t.startPosition={row:this.newEndPosition.row+(e.startPosition.row-this.oldEndPosition.row),column:e.startPosition.row===this.oldEndPosition.row?this.newEndPosition.column+(e.startPosition.column-this.oldEndPosition.column):e.startPosition.column},t.startIndex<this.newEndIndex)t.startIndex=Number.MAX_SAFE_INTEGER,t.startPosition={row:Number.MAX_SAFE_INTEGER,column:Number.MAX_SAFE_INTEGER}}else if(e.startIndex>this.startIndex)t.startIndex=this.startIndex,t.startPosition={...this.startPosition};return t}},qc=4*Y,xt=5*Y,_n=2*Y,ds=2*Y+2*_n,vt={row:0,column:0},tr=Symbol("INTERNAL");R(ii,"assertInternal");R(us,"isPoint");R(Ah,"setModule");F$=class{static{R(this,"LookaheadIterator")}[0]=0;language;constructor(e,t,n){ii(e),this[0]=t,this.language=n}get currentTypeId(){return m._ts_lookahead_iterator_current_symbol(this[0])}get currentType(){return this.language.types[this.currentTypeId]||"ERROR"}delete(){m._ts_lookahead_iterator_delete(this[0]),this[0]=0}reset(e,t){if(m._ts_lookahead_iterator_reset(this[0],e[0],t))return this.language=e,!0;return!1}resetState(e){return Boolean(m._ts_lookahead_iterator_reset_state(this[0],e))}[Symbol.iterator](){return{next:R(()=>{if(m._ts_lookahead_iterator_next(this[0]))return{done:!1,value:this.currentType};return{done:!0,value:""}},"next")}}};R(Wc,"getText");L$=class e{static{R(this,"Tree")}[0]=0;textCallback;language;constructor(t,n,r,s){ii(t),this[0]=n,this.language=r,this.textCallback=s}copy(){let t=m._ts_tree_copy(this[0]);return new e(tr,t,this.language,this.textCallback)}delete(){m._ts_tree_delete(this[0]),this[0]=0}get rootNode(){return m._ts_tree_root_node_wasm(this[0]),Oe(this)}rootNodeWithOffset(t,n){let r=V+xt;return m.setValue(r,t,"i32"),jt(r+Y,n),m._ts_tree_root_node_with_offset_wasm(this[0]),Oe(this)}edit(t){Ih(t),m._ts_tree_edit_wasm(this[0])}walk(){return this.rootNode.walk()}getChangedRanges(t){if(!(t instanceof e))throw TypeError("Argument must be a Tree");m._ts_tree_get_changed_ranges_wasm(this[0],t[0]);let n=m.getValue(V,"i32"),r=m.getValue(V+Y,"i32"),s=Array(n);if(n>0){let o=r;for(let a=0;a<n;a++)s[a]=ra(o),o+=ds;m._free(r)}return s}getIncludedRanges(){m._ts_tree_included_ranges_wasm(this[0]);let t=m.getValue(V,"i32"),n=m.getValue(V+Y,"i32"),r=Array(t);if(t>0){let s=n;for(let o=0;o<t;o++)r[o]=ra(s),s+=ds;m._free(n)}return r}},j$=class e{static{R(this,"TreeCursor")}[0]=0;[1]=0;[2]=0;[3]=0;tree;constructor(t,n){ii(t),this.tree=n,Mt(this)}copy(){let t=new e(tr,this.tree);return m._ts_tree_cursor_copy_wasm(this.tree[0]),Mt(t),t}delete(){xe(this),m._ts_tree_cursor_delete_wasm(this.tree[0]),this[0]=this[1]=this[2]=0}get currentNode(){return xe(this),m._ts_tree_cursor_current_node_wasm(this.tree[0]),Oe(this.tree)}get currentFieldId(){return xe(this),m._ts_tree_cursor_current_field_id_wasm(this.tree[0])}get currentFieldName(){return this.tree.language.fields[this.currentFieldId]}get currentDepth(){return xe(this),m._ts_tree_cursor_current_depth_wasm(this.tree[0])}get currentDescendantIndex(){return xe(this),m._ts_tree_cursor_current_descendant_index_wasm(this.tree[0])}get nodeType(){return this.tree.language.types[this.nodeTypeId]||"ERROR"}get nodeTypeId(){return xe(this),m._ts_tree_cursor_current_node_type_id_wasm(this.tree[0])}get nodeStateId(){return xe(this),m._ts_tree_cursor_current_node_state_id_wasm(this.tree[0])}get nodeId(){return xe(this),m._ts_tree_cursor_current_node_id_wasm(this.tree[0])}get nodeIsNamed(){return xe(this),m._ts_tree_cursor_current_node_is_named_wasm(this.tree[0])===1}get nodeIsMissing(){return xe(this),m._ts_tree_cursor_current_node_is_missing_wasm(this.tree[0])===1}get nodeText(){xe(this);let t=m._ts_tree_cursor_start_index_wasm(this.tree[0]),n=m._ts_tree_cursor_end_index_wasm(this.tree[0]);m._ts_tree_cursor_start_position_wasm(this.tree[0]);let r=$r(V);return Wc(this.tree,t,n,r)}get startPosition(){return xe(this),m._ts_tree_cursor_start_position_wasm(this.tree[0]),$r(V)}get endPosition(){return xe(this),m._ts_tree_cursor_end_position_wasm(this.tree[0]),$r(V)}get startIndex(){return xe(this),m._ts_tree_cursor_start_index_wasm(this.tree[0])}get endIndex(){return xe(this),m._ts_tree_cursor_end_index_wasm(this.tree[0])}gotoFirstChild(){xe(this);let t=m._ts_tree_cursor_goto_first_child_wasm(this.tree[0]);return Mt(this),t===1}gotoLastChild(){xe(this);let t=m._ts_tree_cursor_goto_last_child_wasm(this.tree[0]);return Mt(this),t===1}gotoParent(){xe(this);let t=m._ts_tree_cursor_goto_parent_wasm(this.tree[0]);return Mt(this),t===1}gotoNextSibling(){xe(this);let t=m._ts_tree_cursor_goto_next_sibling_wasm(this.tree[0]);return Mt(this),t===1}gotoPreviousSibling(){xe(this);let t=m._ts_tree_cursor_goto_previous_sibling_wasm(this.tree[0]);return Mt(this),t===1}gotoDescendant(t){xe(this),m._ts_tree_cursor_goto_descendant_wasm(this.tree[0],t),Mt(this)}gotoFirstChildForIndex(t){xe(this),m.setValue(V+qc,t,"i32");let n=m._ts_tree_cursor_goto_first_child_for_index_wasm(this.tree[0]);return Mt(this),n===1}gotoFirstChildForPosition(t){xe(this),jt(V+qc,t);let n=m._ts_tree_cursor_goto_first_child_for_position_wasm(this.tree[0]);return Mt(this),n===1}reset(t){le(t),xe(this,V+xt),m._ts_tree_cursor_reset_wasm(this.tree[0]),Mt(this)}resetTo(t){xe(this,V),xe(t,V+qc),m._ts_tree_cursor_reset_to_wasm(this.tree[0],t.tree[0]),Mt(this)}},U$=class{static{R(this,"Node")}[0]=0;_children;_namedChildren;constructor(e,{id:t,tree:n,startIndex:r,startPosition:s,other:o}){ii(e),this[0]=o,this.id=t,this.tree=n,this.startIndex=r,this.startPosition=s}id;startIndex;startPosition;tree;get typeId(){return le(this),m._ts_node_symbol_wasm(this.tree[0])}get grammarId(){return le(this),m._ts_node_grammar_symbol_wasm(this.tree[0])}get type(){return this.tree.language.types[this.typeId]||"ERROR"}get grammarType(){return this.tree.language.types[this.grammarId]||"ERROR"}get isNamed(){return le(this),m._ts_node_is_named_wasm(this.tree[0])===1}get isExtra(){return le(this),m._ts_node_is_extra_wasm(this.tree[0])===1}get isError(){return le(this),m._ts_node_is_error_wasm(this.tree[0])===1}get isMissing(){return le(this),m._ts_node_is_missing_wasm(this.tree[0])===1}get hasChanges(){return le(this),m._ts_node_has_changes_wasm(this.tree[0])===1}get hasError(){return le(this),m._ts_node_has_error_wasm(this.tree[0])===1}get endIndex(){return le(this),m._ts_node_end_index_wasm(this.tree[0])}get endPosition(){return le(this),m._ts_node_end_point_wasm(this.tree[0]),$r(V)}get text(){return Wc(this.tree,this.startIndex,this.endIndex,this.startPosition)}get parseState(){return le(this),m._ts_node_parse_state_wasm(this.tree[0])}get nextParseState(){return le(this),m._ts_node_next_parse_state_wasm(this.tree[0])}equals(e){return this.tree===e.tree&&this.id===e.id}child(e){return le(this),m._ts_node_child_wasm(this.tree[0],e),Oe(this.tree)}namedChild(e){return le(this),m._ts_node_named_child_wasm(this.tree[0],e),Oe(this.tree)}childForFieldId(e){return le(this),m._ts_node_child_by_field_id_wasm(this.tree[0],e),Oe(this.tree)}childForFieldName(e){let t=this.tree.language.fields.indexOf(e);if(t!==-1)return this.childForFieldId(t);return null}fieldNameForChild(e){le(this);let t=m._ts_node_field_name_for_child_wasm(this.tree[0],e);if(!t)return null;return m.AsciiToString(t)}fieldNameForNamedChild(e){le(this);let t=m._ts_node_field_name_for_named_child_wasm(this.tree[0],e);if(!t)return null;return m.AsciiToString(t)}childrenForFieldName(e){let t=this.tree.language.fields.indexOf(e);if(t!==-1&&t!==0)return this.childrenForFieldId(t);return[]}childrenForFieldId(e){le(this),m._ts_node_children_by_field_id_wasm(this.tree[0],e);let t=m.getValue(V,"i32"),n=m.getValue(V+Y,"i32"),r=Array(t);if(t>0){let s=n;for(let o=0;o<t;o++)r[o]=Oe(this.tree,s),s+=xt;m._free(n)}return r}firstChildForIndex(e){le(this);let t=V+xt;return m.setValue(t,e,"i32"),m._ts_node_first_child_for_byte_wasm(this.tree[0]),Oe(this.tree)}firstNamedChildForIndex(e){le(this);let t=V+xt;return m.setValue(t,e,"i32"),m._ts_node_first_named_child_for_byte_wasm(this.tree[0]),Oe(this.tree)}get childCount(){return le(this),m._ts_node_child_count_wasm(this.tree[0])}get namedChildCount(){return le(this),m._ts_node_named_child_count_wasm(this.tree[0])}get firstChild(){return this.child(0)}get firstNamedChild(){return this.namedChild(0)}get lastChild(){return this.child(this.childCount-1)}get lastNamedChild(){return this.namedChild(this.namedChildCount-1)}get children(){if(!this._children){le(this),m._ts_node_children_wasm(this.tree[0]);let e=m.getValue(V,"i32"),t=m.getValue(V+Y,"i32");if(this._children=Array(e),e>0){let n=t;for(let r=0;r<e;r++)this._children[r]=Oe(this.tree,n),n+=xt;m._free(t)}}return this._children}get namedChildren(){if(!this._namedChildren){le(this),m._ts_node_named_children_wasm(this.tree[0]);let e=m.getValue(V,"i32"),t=m.getValue(V+Y,"i32");if(this._namedChildren=Array(e),e>0){let n=t;for(let r=0;r<e;r++)this._namedChildren[r]=Oe(this.tree,n),n+=xt;m._free(t)}}return this._namedChildren}descendantsOfType(e,t=vt,n=vt){if(!Array.isArray(e))e=[e];let r=[],s=this.tree.language.types;for(let u of e)if(u=="ERROR")r.push(65535);for(let u=0,d=s.length;u<d;u++)if(e.includes(s[u]))r.push(u);let o=m._malloc(Y*r.length);for(let u=0,d=r.length;u<d;u++)m.setValue(o+u*Y,r[u],"i32");le(this),m._ts_node_descendants_of_type_wasm(this.tree[0],o,r.length,t.row,t.column,n.row,n.column);let a=m.getValue(V,"i32"),l=m.getValue(V+Y,"i32"),c=Array(a);if(a>0){let u=l;for(let d=0;d<a;d++)c[d]=Oe(this.tree,u),u+=xt}return m._free(l),m._free(o),c}get nextSibling(){return le(this),m._ts_node_next_sibling_wasm(this.tree[0]),Oe(this.tree)}get previousSibling(){return le(this),m._ts_node_prev_sibling_wasm(this.tree[0]),Oe(this.tree)}get nextNamedSibling(){return le(this),m._ts_node_next_named_sibling_wasm(this.tree[0]),Oe(this.tree)}get previousNamedSibling(){return le(this),m._ts_node_prev_named_sibling_wasm(this.tree[0]),Oe(this.tree)}get descendantCount(){return le(this),m._ts_node_descendant_count_wasm(this.tree[0])}get parent(){return le(this),m._ts_node_parent_wasm(this.tree[0]),Oe(this.tree)}childWithDescendant(e){return le(this),le(e,1),m._ts_node_child_with_descendant_wasm(this.tree[0]),Oe(this.tree)}descendantForIndex(e,t=e){if(typeof e!=="number"||typeof t!=="number")throw Error("Arguments must be numbers");le(this);let n=V+xt;return m.setValue(n,e,"i32"),m.setValue(n+Y,t,"i32"),m._ts_node_descendant_for_index_wasm(this.tree[0]),Oe(this.tree)}namedDescendantForIndex(e,t=e){if(typeof e!=="number"||typeof t!=="number")throw Error("Arguments must be numbers");le(this);let n=V+xt;return m.setValue(n,e,"i32"),m.setValue(n+Y,t,"i32"),m._ts_node_named_descendant_for_index_wasm(this.tree[0]),Oe(this.tree)}descendantForPosition(e,t=e){if(!us(e)||!us(t))throw Error("Arguments must be {row, column} objects");le(this);let n=V+xt;return jt(n,e),jt(n+_n,t),m._ts_node_descendant_for_position_wasm(this.tree[0]),Oe(this.tree)}namedDescendantForPosition(e,t=e){if(!us(e)||!us(t))throw Error("Arguments must be {row, column} objects");le(this);let n=V+xt;return jt(n,e),jt(n+_n,t),m._ts_node_named_descendant_for_position_wasm(this.tree[0]),Oe(this.tree)}walk(){return le(this),m._ts_tree_cursor_new_wasm(this.tree[0]),new j$(tr,this.tree)}edit(e){if(this.startIndex>=e.oldEndIndex){this.startIndex=e.newEndIndex+(this.startIndex-e.oldEndIndex);let t,n;if(this.startPosition.row>e.oldEndPosition.row)t=this.startPosition.row-e.oldEndPosition.row,n=this.startPosition.column;else if(t=0,n=this.startPosition.column,this.startPosition.column>=e.oldEndPosition.column)n=this.startPosition.column-e.oldEndPosition.column;if(t>0)this.startPosition.row+=t,this.startPosition.column=n;else this.startPosition.column+=n}else if(this.startIndex>e.startIndex)this.startIndex=e.newEndIndex,this.startPosition.row=e.newEndPosition.row,this.startPosition.column=e.newEndPosition.column}toString(){le(this);let e=m._ts_node_to_string_wasm(this.tree[0]),t=m.AsciiToString(e);return m._free(e),t}};R(Gc,"unmarshalCaptures");R(le,"marshalNode");R(Oe,"unmarshalNode");R(xe,"marshalTreeCursor");R(Mt,"unmarshalTreeCursor");R(jt,"marshalPoint");R($r,"unmarshalPoint");R(Oh,"marshalRange");R(ra,"unmarshalRange");R(Ih,"marshalEdit");R(Ph,"unmarshalLanguageMetadata");B$=/^tree_sitter_\w+$/,Vc=class e{static{R(this,"Language")}[0]=0;types;fields;constructor(t,n){ii(t),this[0]=n,this.types=Array(m._ts_language_symbol_count(this[0]));for(let r=0,s=this.types.length;r<s;r++)if(m._ts_language_symbol_type(this[0],r)<2)this.types[r]=m.UTF8ToString(m._ts_language_symbol_name(this[0],r));this.fields=Array(m._ts_language_field_count(this[0])+1);for(let r=0,s=this.fields.length;r<s;r++){let o=m._ts_language_field_name_for_id(this[0],r);if(o!==0)this.fields[r]=m.UTF8ToString(o);else this.fields[r]=null}}get name(){let t=m._ts_language_name(this[0]);if(t===0)return null;return m.UTF8ToString(t)}get abiVersion(){return m._ts_language_abi_version(this[0])}get metadata(){if(m._ts_language_metadata_wasm(this[0]),m.getValue(V,"i32")===0)return null;return Ph(V+Y)}get fieldCount(){return this.fields.length-1}get stateCount(){return m._ts_language_state_count(this[0])}fieldIdForName(t){let n=this.fields.indexOf(t);return n!==-1?n:null}fieldNameForId(t){return this.fields[t]??null}idForNodeType(t,n){let r=m.lengthBytesUTF8(t),s=m._malloc(r+1);m.stringToUTF8(t,s,r+1);let o=m._ts_language_symbol_for_name(this[0],s,r,n?1:0);return m._free(s),o||null}get nodeTypeCount(){return m._ts_language_symbol_count(this[0])}nodeTypeForId(t){let n=m._ts_language_symbol_name(this[0],t);return n?m.UTF8ToString(n):null}nodeTypeIsNamed(t){return m._ts_language_type_is_named_wasm(this[0],t)?!0:!1}nodeTypeIsVisible(t){return m._ts_language_type_is_visible_wasm(this[0],t)?!0:!1}get supertypes(){m._ts_language_supertypes_wasm(this[0]);let t=m.getValue(V,"i32"),n=m.getValue(V+Y,"i32"),r=Array(t);if(t>0){let s=n;for(let o=0;o<t;o++)r[o]=m.getValue(s,"i16"),s+=Eh}return r}subtypes(t){m._ts_language_subtypes_wasm(this[0],t);let n=m.getValue(V,"i32"),r=m.getValue(V+Y,"i32"),s=Array(n);if(n>0){let o=r;for(let a=0;a<n;a++)s[a]=m.getValue(o,"i16"),o+=Eh}return s}nextState(t,n){return m._ts_language_next_state(this[0],t,n)}lookaheadIterator(t){let n=m._ts_lookahead_iterator_new(this[0],t);if(n)return new F$(tr,n,this);return null}static async load(t){let n;if(t instanceof Uint8Array)n=t;else if(globalThis.process?.versions.node){let l=await import("fs/promises");n=await l.readFile(t)}else{let l=await fetch(t);if(!l.ok){let u=await l.text();throw Error(`Language.load failed with status ${l.status}.
29
29
 
30
- ${u}`)}let c=l.clone();try{n=await WebAssembly.compileStreaming(l)}catch(u){console.error("wasm streaming compile failed:",u),console.error("falling back to ArrayBuffer instantiation"),n=new Uint8Array(await c.arrayBuffer())}}let r=await m.loadWebAssemblyModule(n,{loadAsync:!0}),s=Object.keys(r),o=s.find((l)=>e$.test(l)&&!l.includes("external_scanner_"));if(!o)throw console.log(`Couldn't find language function in Wasm file. Symbols:
31
- ${JSON.stringify(s,null,2)}`),Error("Language.load failed: no language function found in Wasm file");let a=r[o]();return new e(Zn,a)}};S(ch,"Module");t$=ch;S(dh,"initializeBinding");S(fh,"checkModule");Fc=class{static{S(this,"Parser")}[0]=0;[1]=0;logCallback=null;language=null;static async init(e){sh(await dh(e)),V=m._ts_init(),Oc=m.getValue(V,"i32"),Ic=m.getValue(V+Y,"i32")}constructor(){this.initialize()}initialize(){if(!fh())throw Error("cannot construct a Parser before calling `init()`");m._ts_parser_new_wasm(),this[0]=m.getValue(V,"i32"),this[1]=m.getValue(V+Y,"i32")}delete(){m._ts_parser_delete(this[0]),m._free(this[1]),this[0]=0,this[1]=0}setLanguage(e){let t;if(!e)t=0,this.language=null;else if(e.constructor===Tc){t=e[0];let n=m._ts_language_abi_version(t);if(n<Ic||Oc<n)throw Error(`Incompatible language version ${n}. Compatibility range ${Ic} through ${Oc}.`);this.language=e}else throw Error("Argument must be a Language");return m._ts_parser_set_language(this[0],t),this}parse(e,t,n){if(typeof e==="string")m.currentParseCallback=(l)=>e.slice(l);else if(typeof e==="function")m.currentParseCallback=e;else throw Error("Argument must be a string or a function");if(n?.progressCallback)m.currentProgressCallback=n.progressCallback;else m.currentProgressCallback=null;if(this.logCallback)m.currentLogCallback=this.logCallback,m._ts_parser_enable_logger_wasm(this[0],1);else m.currentLogCallback=null,m._ts_parser_enable_logger_wasm(this[0],0);let r=0,s=0;if(n?.includedRanges){r=n.includedRanges.length,s=m._calloc(r,rs);let l=s;for(let c=0;c<r;c++)oh(l,n.includedRanges[c]),l+=rs}let o=m._ts_parser_parse_wasm(this[0],this[1],t?t[0]:0,s,r);if(!o)return m.currentParseCallback=null,m.currentLogCallback=null,m.currentProgressCallback=null,null;if(!this.language)throw Error("Parser must have a language to parse");let a=new YS(Zn,o,this.language,m.currentParseCallback);return m.currentParseCallback=null,m.currentLogCallback=null,m.currentProgressCallback=null,a}reset(){m._ts_parser_reset(this[0])}getIncludedRanges(){m._ts_parser_included_ranges_wasm(this[0]);let e=m.getValue(V,"i32"),t=m.getValue(V+Y,"i32"),n=Array(e);if(e>0){let r=t;for(let s=0;s<e;s++)n[s]=Jo(r),r+=rs;m._free(t)}return n}setLogger(e){if(!e)this.logCallback=null;else if(typeof e!=="function")throw Error("Logger callback must be a function");else this.logCallback=e;return this}getLogger(){return this.logCallback}},i$=/[\w-]+/g,AT={Zero:0,ZeroOrOne:1,ZeroOrMore:2,One:3,OneOrMore:4},ih=S((e)=>e.type==="capture","isCaptureStep"),Nc=S((e)=>e.type==="string","isStringStep"),en={Syntax:1,NodeName:2,FieldName:3,CaptureName:4,PatternStructure:5},ts=class e extends Error{constructor(t,n,r,s){super(e.formatMessage(t,n));this.kind=t,this.info=n,this.index=r,this.length=s,this.name="QueryError"}static{S(this,"QueryError")}static formatMessage(t,n){switch(t){case en.NodeName:return`Bad node name '${n.word}'`;case en.FieldName:return`Bad field name '${n.word}'`;case en.CaptureName:return`Bad capture name @${n.word}`;case en.PatternStructure:return`Bad pattern structure at offset ${n.suffix}`;case en.Syntax:return`Bad syntax at offset ${n.suffix}`}}};S(ph,"parseAnyPredicate");S(hh,"parseMatchPredicate");S(mh,"parseAnyOfPredicate");S(gh,"parseIsPredicate");S(_h,"parseSetDirective");S(wh,"parsePattern");Dc=class{static{S(this,"Query")}[0]=0;exceededMatchLimit;textPredicates;captureNames;captureQuantifiers;predicates;setProperties;assertedProperties;refutedProperties;matchLimit;constructor(e,t){let n=m.lengthBytesUTF8(t),r=m._malloc(n+1);m.stringToUTF8(t,r,n+1);let s=m._ts_query_new(e[0],r,n,V,V+Y);if(!s){let b=m.getValue(V+Y,"i32"),x=m.getValue(V,"i32"),R=m.UTF8ToString(r,x).length,P=t.slice(R,R+100).split(`
32
- `)[0],M=P.match(i$)?.[0]??"";switch(m._free(r),b){case en.Syntax:throw new ts(en.Syntax,{suffix:`${R}: '${P}'...`},R,0);case en.NodeName:throw new ts(b,{word:M},R,M.length);case en.FieldName:throw new ts(b,{word:M},R,M.length);case en.CaptureName:throw new ts(b,{word:M},R,M.length);case en.PatternStructure:throw new ts(b,{suffix:`${R}: '${P}'...`},R,0)}}let o=m._ts_query_string_count(s),a=m._ts_query_capture_count(s),l=m._ts_query_pattern_count(s),c=Array(a),u=Array(l),d=Array(o);for(let b=0;b<a;b++){let x=m._ts_query_capture_name_for_id(s,b,V),R=m.getValue(V,"i32");c[b]=m.UTF8ToString(x,R)}for(let b=0;b<l;b++){let x=Array(a);for(let R=0;R<a;R++){let P=m._ts_query_capture_quantifier_for_id(s,b,R);x[R]=P}u[b]=x}for(let b=0;b<o;b++){let x=m._ts_query_string_value_for_id(s,b,V),R=m.getValue(V,"i32");d[b]=m.UTF8ToString(x,R)}let f=Array(l),p=Array(l),h=Array(l),g=Array(l),w=Array(l);for(let b=0;b<l;b++){let x=m._ts_query_predicates_for_pattern(s,b,V),R=m.getValue(V,"i32");g[b]=[],w[b]=[];let P=[],M=x;for(let k=0;k<R;k++){let E=m.getValue(M,"i32");M+=Y;let D=m.getValue(M,"i32");M+=Y,wh(b,E,D,c,d,P,w,g,f,p,h)}Object.freeze(w[b]),Object.freeze(g[b]),Object.freeze(f[b]),Object.freeze(p[b]),Object.freeze(h[b])}m._free(r),this[0]=s,this.captureNames=c,this.captureQuantifiers=u,this.textPredicates=w,this.predicates=g,this.setProperties=f,this.assertedProperties=p,this.refutedProperties=h,this.exceededMatchLimit=!1}delete(){m._ts_query_delete(this[0]),this[0]=0}matches(e,t={}){let n=t.startPosition??vt,r=t.endPosition??vt,s=t.startIndex??0,o=t.endIndex??0,a=t.startContainingPosition??vt,l=t.endContainingPosition??vt,c=t.startContainingIndex??0,u=t.endContainingIndex??0,d=t.matchLimit??4294967295,f=t.maxStartDepth??4294967295,p=t.progressCallback;if(typeof d!=="number")throw Error("Arguments must be numbers");if(this.matchLimit=d,o!==0&&s>o)throw Error("`startIndex` cannot be greater than `endIndex`");if(r!==vt&&(n.row>r.row||n.row===r.row&&n.column>r.column))throw Error("`startPosition` cannot be greater than `endPosition`");if(u!==0&&c>u)throw Error("`startContainingIndex` cannot be greater than `endContainingIndex`");if(l!==vt&&(a.row>l.row||a.row===l.row&&a.column>l.column))throw Error("`startContainingPosition` cannot be greater than `endContainingPosition`");if(p)m.currentQueryProgressCallback=p;le(e),m._ts_query_matches_wasm(this[0],e.tree[0],n.row,n.column,r.row,r.column,s,o,a.row,a.column,l.row,l.column,c,u,d,f);let h=m.getValue(V,"i32"),g=m.getValue(V+Y,"i32"),w=m.getValue(V+2*Y,"i32"),b=Array(h);this.exceededMatchLimit=Boolean(w);let x=0,R=g;for(let P=0;P<h;P++){let M=m.getValue(R,"i32");R+=Y;let k=m.getValue(R,"i32");R+=Y;let E=Array(k);if(R=Pc(this,e.tree,R,M,E),this.textPredicates[M].every((D)=>D(E))){b[x]={patternIndex:M,captures:E};let D=this.setProperties[M];b[x].setProperties=D;let L=this.assertedProperties[M];b[x].assertedProperties=L;let O=this.refutedProperties[M];b[x].refutedProperties=O,x++}}return b.length=x,m._free(g),m.currentQueryProgressCallback=null,b}captures(e,t={}){let n=t.startPosition??vt,r=t.endPosition??vt,s=t.startIndex??0,o=t.endIndex??0,a=t.startContainingPosition??vt,l=t.endContainingPosition??vt,c=t.startContainingIndex??0,u=t.endContainingIndex??0,d=t.matchLimit??4294967295,f=t.maxStartDepth??4294967295,p=t.progressCallback;if(typeof d!=="number")throw Error("Arguments must be numbers");if(this.matchLimit=d,o!==0&&s>o)throw Error("`startIndex` cannot be greater than `endIndex`");if(r!==vt&&(n.row>r.row||n.row===r.row&&n.column>r.column))throw Error("`startPosition` cannot be greater than `endPosition`");if(u!==0&&c>u)throw Error("`startContainingIndex` cannot be greater than `endContainingIndex`");if(l!==vt&&(a.row>l.row||a.row===l.row&&a.column>l.column))throw Error("`startContainingPosition` cannot be greater than `endContainingPosition`");if(p)m.currentQueryProgressCallback=p;le(e),m._ts_query_captures_wasm(this[0],e.tree[0],n.row,n.column,r.row,r.column,s,o,a.row,a.column,l.row,l.column,c,u,d,f);let h=m.getValue(V,"i32"),g=m.getValue(V+Y,"i32"),w=m.getValue(V+2*Y,"i32"),b=[];this.exceededMatchLimit=Boolean(w);let x=[],R=g;for(let P=0;P<h;P++){let M=m.getValue(R,"i32");R+=Y;let k=m.getValue(R,"i32");R+=Y;let E=m.getValue(R,"i32");if(R+=Y,x.length=k,R=Pc(this,e.tree,R,M,x),this.textPredicates[M].every((D)=>D(x))){let D=x[E],L=this.setProperties[M];D.setProperties=L;let O=this.assertedProperties[M];D.assertedProperties=O;let U=this.refutedProperties[M];D.refutedProperties=U,b.push(D)}}return m._free(g),m.currentQueryProgressCallback=null,b}predicatesForPattern(e){return this.predicates[e]}disableCapture(e){let t=m.lengthBytesUTF8(e),n=m._malloc(t+1);m.stringToUTF8(e,n,t+1),m._ts_query_disable_capture(this[0],n,t),m._free(n)}disablePattern(e){if(e>=this.predicates.length)throw Error(`Pattern index is ${e} but the pattern count is ${this.predicates.length}`);m._ts_query_disable_pattern(this[0],e)}didExceedMatchLimit(){return this.exceededMatchLimit}startIndexForPattern(e){if(e>=this.predicates.length)throw Error(`Pattern index is ${e} but the pattern count is ${this.predicates.length}`);return m._ts_query_start_byte_for_pattern(this[0],e)}endIndexForPattern(e){if(e>=this.predicates.length)throw Error(`Pattern index is ${e} but the pattern count is ${this.predicates.length}`);return m._ts_query_end_byte_for_pattern(this[0],e)}patternCount(){return m._ts_query_pattern_count(this[0])}captureIndexForName(e){return this.captureNames.indexOf(e)}isPatternRooted(e){return m._ts_query_is_pattern_rooted(this[0],e)===1}isPatternNonLocal(e){return m._ts_query_is_pattern_non_local(this[0],e)===1}isPatternGuaranteedAtStep(e){return m._ts_query_is_pattern_guaranteed_at_step(this[0],e)===1}}});import{existsSync as bh,readFileSync as s$,statSync as o$}from"fs";import{dirname as a$,join as is,posix as ei}from"path";function vh(e,t){let n=import.meta.dir;for(let s of[process.env.DIFFLOUPE_WASM_DIR,is(n,"wasm")])if(s&&bh(is(s,t)))return is(s,t);let r=n;for(let s=0;s<8;s++){let o=is(r,"node_modules",e,t);if(bh(o))return o;let a=a$(r);if(a===r)break;r=a}throw Error(`Could not locate ${e}/${t} in any parent node_modules of ${n}`)}class ti{parser;loaded=new Map;constructor(e){this.parser=e}static async create(){return await Fc.init({locateFile:(e)=>vh("web-tree-sitter",e)}),new ti(new Fc)}async load(e){let t=this.loaded.get(e);if(t)return t;let[n,r]=f$[e],s=await Tc.load(vh(n,r)),o=e==="cpp",a={language:s,definitions:new Dc(s,o?u$:l$),imports:new Dc(s,o?d$:c$)};return this.loaded.set(e,a),a}async warmup(e){for(let t of e)await this.load(t)}async parseFile(e,t,n){let r=Dt(t);if(!r)return null;let s;try{s=s$(e,"utf-8")}catch{return null}return this.parseSource(s,t,n,r)}async parseSource(e,t,n,r){let s=await this.parseRaw(e,t,r);return s?jc(s,t,n):null}async parseRaw(e,t,n){let r=n??Dt(t);if(!r)return null;let{language:s,definitions:o,imports:a}=await this.load(r);this.parser.setLanguage(s);let l=this.parser.parse(e);if(!l)return null;try{let c=l.rootNode;return{language:r,lines:e.length===0?0:e.replace(/\n$/,"").split(`
33
- `).length,symbols:_$(c,e,o,r),importSpecs:S$(c,a),parseError:c.hasError}}finally{l.delete()}}}function _$(e,t,n,r){let s=n.matches(e),o=new Set,a=[];for(let u of s){let d=null,f=null,p=null;for(let x of u.captures){let R=x.node;if(x.name==="name")d=R;else if(x.name.startsWith("definition."))f=R,p=x.name.slice(11)}if(!d||!f||!p)continue;if(w$(f,r))continue;let h=d.text,g=f.startPosition.row+1,w=`${p}:${h}:${g}`;if(o.has(w))continue;o.add(w);let b=y$(f);a.push({name:h,kind:p,line:g,exported:v$(f,r),...b?{container:b}:{},signature:x$(f,t,r)})}let l=new Set(a.filter((u)=>u.kind!=="variable").map((u)=>`${u.name}:${u.line}`)),c=a.filter((u)=>u.kind!=="variable"||!l.has(`${u.name}:${u.line}`));return c.sort((u,d)=>u.line-d.line),c}function w$(e,t){if(t==="cpp")return!1;let n=e.parent;while(n){if(n.type==="object")return!0;if(m$.has(n.type))return!1;n=n.parent}return!1}function y$(e){let t=e.parent;while(t){if(p$.has(t.type)){let n=t.childForFieldName("name");if(n)return n.text}t=t.parent}return}function v$(e,t){let n=e;while(n){if(t==="cpp"){if(h$.has(n.type)&&n!==e)return!1}else{if(b$.has(n.type)&&n!==e)return!1;if(n.type==="export_statement")return!0}n=n.parent}return t==="cpp"}function x$(e,t,n){let r=e;if(n==="cpp"&&e.type==="function_declarator"){let l=e.parent;while(l){if(g$.has(l.type)){r=l;break}l=l.parent}}if(r.type==="variable_declarator"){let l=r.parent?.text.trimStart().split(/\s/)[0]??"const",u=r.childForFieldName("value")?.childForFieldName("body"),d=u&&u.startIndex>r.startIndex?u.startIndex:r.endIndex;return xh(`${l} ${t.slice(r.startIndex,d)}`)}let s=r.childForFieldName("body"),o=s&&s.startIndex>r.startIndex?s.startIndex:r.endIndex,a=t.slice(r.startIndex,o);return xh(a)}function xh(e,t=160){let n=e.replace(/\/\*[\s\S]*?\*\//g," ").split(`
30
+ ${u}`)}let c=l.clone();try{n=await WebAssembly.compileStreaming(l)}catch(u){console.error("wasm streaming compile failed:",u),console.error("falling back to ArrayBuffer instantiation"),n=new Uint8Array(await c.arrayBuffer())}}let r=await m.loadWebAssemblyModule(n,{loadAsync:!0}),s=Object.keys(r),o=s.find((l)=>B$.test(l)&&!l.includes("external_scanner_"));if(!o)throw console.log(`Couldn't find language function in Wasm file. Symbols:
31
+ ${JSON.stringify(s,null,2)}`),Error("Language.load failed: no language function found in Wasm file");let a=r[o]();return new e(tr,a)}};R(Mh,"Module");q$=Mh;R(Dh,"initializeBinding");R(Nh,"checkModule");zc=class{static{R(this,"Parser")}[0]=0;[1]=0;logCallback=null;language=null;static async init(e){Ah(await Dh(e)),V=m._ts_init(),Hc=m.getValue(V,"i32"),Kc=m.getValue(V+Y,"i32")}constructor(){this.initialize()}initialize(){if(!Nh())throw Error("cannot construct a Parser before calling `init()`");m._ts_parser_new_wasm(),this[0]=m.getValue(V,"i32"),this[1]=m.getValue(V+Y,"i32")}delete(){m._ts_parser_delete(this[0]),m._free(this[1]),this[0]=0,this[1]=0}setLanguage(e){let t;if(!e)t=0,this.language=null;else if(e.constructor===Vc){t=e[0];let n=m._ts_language_abi_version(t);if(n<Kc||Hc<n)throw Error(`Incompatible language version ${n}. Compatibility range ${Kc} through ${Hc}.`);this.language=e}else throw Error("Argument must be a Language");return m._ts_parser_set_language(this[0],t),this}parse(e,t,n){if(typeof e==="string")m.currentParseCallback=(l)=>e.slice(l);else if(typeof e==="function")m.currentParseCallback=e;else throw Error("Argument must be a string or a function");if(n?.progressCallback)m.currentProgressCallback=n.progressCallback;else m.currentProgressCallback=null;if(this.logCallback)m.currentLogCallback=this.logCallback,m._ts_parser_enable_logger_wasm(this[0],1);else m.currentLogCallback=null,m._ts_parser_enable_logger_wasm(this[0],0);let r=0,s=0;if(n?.includedRanges){r=n.includedRanges.length,s=m._calloc(r,ds);let l=s;for(let c=0;c<r;c++)Oh(l,n.includedRanges[c]),l+=ds}let o=m._ts_parser_parse_wasm(this[0],this[1],t?t[0]:0,s,r);if(!o)return m.currentParseCallback=null,m.currentLogCallback=null,m.currentProgressCallback=null,null;if(!this.language)throw Error("Parser must have a language to parse");let a=new L$(tr,o,this.language,m.currentParseCallback);return m.currentParseCallback=null,m.currentLogCallback=null,m.currentProgressCallback=null,a}reset(){m._ts_parser_reset(this[0])}getIncludedRanges(){m._ts_parser_included_ranges_wasm(this[0]);let e=m.getValue(V,"i32"),t=m.getValue(V+Y,"i32"),n=Array(e);if(e>0){let r=t;for(let s=0;s<e;s++)n[s]=ra(r),r+=ds;m._free(t)}return n}setLogger(e){if(!e)this.logCallback=null;else if(typeof e!=="function")throw Error("Logger callback must be a function");else this.logCallback=e;return this}getLogger(){return this.logCallback}},G$=/[\w-]+/g,$D={Zero:0,ZeroOrOne:1,ZeroOrMore:2,One:3,OneOrMore:4},Ch=R((e)=>e.type==="capture","isCaptureStep"),Jc=R((e)=>e.type==="string","isStringStep"),nn={Syntax:1,NodeName:2,FieldName:3,CaptureName:4,PatternStructure:5},cs=class e extends Error{constructor(t,n,r,s){super(e.formatMessage(t,n));this.kind=t,this.info=n,this.index=r,this.length=s,this.name="QueryError"}static{R(this,"QueryError")}static formatMessage(t,n){switch(t){case nn.NodeName:return`Bad node name '${n.word}'`;case nn.FieldName:return`Bad field name '${n.word}'`;case nn.CaptureName:return`Bad capture name @${n.word}`;case nn.PatternStructure:return`Bad pattern structure at offset ${n.suffix}`;case nn.Syntax:return`Bad syntax at offset ${n.suffix}`}}};R(Fh,"parseAnyPredicate");R(Lh,"parseMatchPredicate");R(jh,"parseAnyOfPredicate");R(Uh,"parseIsPredicate");R(Bh,"parseSetDirective");R(qh,"parsePattern");Xc=class{static{R(this,"Query")}[0]=0;exceededMatchLimit;textPredicates;captureNames;captureQuantifiers;predicates;setProperties;assertedProperties;refutedProperties;matchLimit;constructor(e,t){let n=m.lengthBytesUTF8(t),r=m._malloc(n+1);m.stringToUTF8(t,r,n+1);let s=m._ts_query_new(e[0],r,n,V,V+Y);if(!s){let b=m.getValue(V+Y,"i32"),x=m.getValue(V,"i32"),S=m.UTF8ToString(r,x).length,P=t.slice(S,S+100).split(`
32
+ `)[0],M=P.match(G$)?.[0]??"";switch(m._free(r),b){case nn.Syntax:throw new cs(nn.Syntax,{suffix:`${S}: '${P}'...`},S,0);case nn.NodeName:throw new cs(b,{word:M},S,M.length);case nn.FieldName:throw new cs(b,{word:M},S,M.length);case nn.CaptureName:throw new cs(b,{word:M},S,M.length);case nn.PatternStructure:throw new cs(b,{suffix:`${S}: '${P}'...`},S,0)}}let o=m._ts_query_string_count(s),a=m._ts_query_capture_count(s),l=m._ts_query_pattern_count(s),c=Array(a),u=Array(l),d=Array(o);for(let b=0;b<a;b++){let x=m._ts_query_capture_name_for_id(s,b,V),S=m.getValue(V,"i32");c[b]=m.UTF8ToString(x,S)}for(let b=0;b<l;b++){let x=Array(a);for(let S=0;S<a;S++){let P=m._ts_query_capture_quantifier_for_id(s,b,S);x[S]=P}u[b]=x}for(let b=0;b<o;b++){let x=m._ts_query_string_value_for_id(s,b,V),S=m.getValue(V,"i32");d[b]=m.UTF8ToString(x,S)}let f=Array(l),p=Array(l),h=Array(l),g=Array(l),w=Array(l);for(let b=0;b<l;b++){let x=m._ts_query_predicates_for_pattern(s,b,V),S=m.getValue(V,"i32");g[b]=[],w[b]=[];let P=[],M=x;for(let k=0;k<S;k++){let E=m.getValue(M,"i32");M+=Y;let F=m.getValue(M,"i32");M+=Y,qh(b,E,F,c,d,P,w,g,f,p,h)}Object.freeze(w[b]),Object.freeze(g[b]),Object.freeze(f[b]),Object.freeze(p[b]),Object.freeze(h[b])}m._free(r),this[0]=s,this.captureNames=c,this.captureQuantifiers=u,this.textPredicates=w,this.predicates=g,this.setProperties=f,this.assertedProperties=p,this.refutedProperties=h,this.exceededMatchLimit=!1}delete(){m._ts_query_delete(this[0]),this[0]=0}matches(e,t={}){let n=t.startPosition??vt,r=t.endPosition??vt,s=t.startIndex??0,o=t.endIndex??0,a=t.startContainingPosition??vt,l=t.endContainingPosition??vt,c=t.startContainingIndex??0,u=t.endContainingIndex??0,d=t.matchLimit??4294967295,f=t.maxStartDepth??4294967295,p=t.progressCallback;if(typeof d!=="number")throw Error("Arguments must be numbers");if(this.matchLimit=d,o!==0&&s>o)throw Error("`startIndex` cannot be greater than `endIndex`");if(r!==vt&&(n.row>r.row||n.row===r.row&&n.column>r.column))throw Error("`startPosition` cannot be greater than `endPosition`");if(u!==0&&c>u)throw Error("`startContainingIndex` cannot be greater than `endContainingIndex`");if(l!==vt&&(a.row>l.row||a.row===l.row&&a.column>l.column))throw Error("`startContainingPosition` cannot be greater than `endContainingPosition`");if(p)m.currentQueryProgressCallback=p;le(e),m._ts_query_matches_wasm(this[0],e.tree[0],n.row,n.column,r.row,r.column,s,o,a.row,a.column,l.row,l.column,c,u,d,f);let h=m.getValue(V,"i32"),g=m.getValue(V+Y,"i32"),w=m.getValue(V+2*Y,"i32"),b=Array(h);this.exceededMatchLimit=Boolean(w);let x=0,S=g;for(let P=0;P<h;P++){let M=m.getValue(S,"i32");S+=Y;let k=m.getValue(S,"i32");S+=Y;let E=Array(k);if(S=Gc(this,e.tree,S,M,E),this.textPredicates[M].every((F)=>F(E))){b[x]={patternIndex:M,captures:E};let F=this.setProperties[M];b[x].setProperties=F;let L=this.assertedProperties[M];b[x].assertedProperties=L;let O=this.refutedProperties[M];b[x].refutedProperties=O,x++}}return b.length=x,m._free(g),m.currentQueryProgressCallback=null,b}captures(e,t={}){let n=t.startPosition??vt,r=t.endPosition??vt,s=t.startIndex??0,o=t.endIndex??0,a=t.startContainingPosition??vt,l=t.endContainingPosition??vt,c=t.startContainingIndex??0,u=t.endContainingIndex??0,d=t.matchLimit??4294967295,f=t.maxStartDepth??4294967295,p=t.progressCallback;if(typeof d!=="number")throw Error("Arguments must be numbers");if(this.matchLimit=d,o!==0&&s>o)throw Error("`startIndex` cannot be greater than `endIndex`");if(r!==vt&&(n.row>r.row||n.row===r.row&&n.column>r.column))throw Error("`startPosition` cannot be greater than `endPosition`");if(u!==0&&c>u)throw Error("`startContainingIndex` cannot be greater than `endContainingIndex`");if(l!==vt&&(a.row>l.row||a.row===l.row&&a.column>l.column))throw Error("`startContainingPosition` cannot be greater than `endContainingPosition`");if(p)m.currentQueryProgressCallback=p;le(e),m._ts_query_captures_wasm(this[0],e.tree[0],n.row,n.column,r.row,r.column,s,o,a.row,a.column,l.row,l.column,c,u,d,f);let h=m.getValue(V,"i32"),g=m.getValue(V+Y,"i32"),w=m.getValue(V+2*Y,"i32"),b=[];this.exceededMatchLimit=Boolean(w);let x=[],S=g;for(let P=0;P<h;P++){let M=m.getValue(S,"i32");S+=Y;let k=m.getValue(S,"i32");S+=Y;let E=m.getValue(S,"i32");if(S+=Y,x.length=k,S=Gc(this,e.tree,S,M,x),this.textPredicates[M].every((F)=>F(x))){let F=x[E],L=this.setProperties[M];F.setProperties=L;let O=this.assertedProperties[M];F.assertedProperties=O;let U=this.refutedProperties[M];F.refutedProperties=U,b.push(F)}}return m._free(g),m.currentQueryProgressCallback=null,b}predicatesForPattern(e){return this.predicates[e]}disableCapture(e){let t=m.lengthBytesUTF8(e),n=m._malloc(t+1);m.stringToUTF8(e,n,t+1),m._ts_query_disable_capture(this[0],n,t),m._free(n)}disablePattern(e){if(e>=this.predicates.length)throw Error(`Pattern index is ${e} but the pattern count is ${this.predicates.length}`);m._ts_query_disable_pattern(this[0],e)}didExceedMatchLimit(){return this.exceededMatchLimit}startIndexForPattern(e){if(e>=this.predicates.length)throw Error(`Pattern index is ${e} but the pattern count is ${this.predicates.length}`);return m._ts_query_start_byte_for_pattern(this[0],e)}endIndexForPattern(e){if(e>=this.predicates.length)throw Error(`Pattern index is ${e} but the pattern count is ${this.predicates.length}`);return m._ts_query_end_byte_for_pattern(this[0],e)}patternCount(){return m._ts_query_pattern_count(this[0])}captureIndexForName(e){return this.captureNames.indexOf(e)}isPatternRooted(e){return m._ts_query_is_pattern_rooted(this[0],e)===1}isPatternNonLocal(e){return m._ts_query_is_pattern_non_local(this[0],e)===1}isPatternGuaranteedAtStep(e){return m._ts_query_is_pattern_guaranteed_at_step(this[0],e)===1}}});import{existsSync as Kh,readFileSync as W$,statSync as V$}from"fs";import{dirname as z$,join as ps,posix as si}from"path";function Gh(e,t){let n=import.meta.dir;for(let s of[process.env.DIFFLOUPE_WASM_DIR,ps(n,"wasm")])if(s&&Kh(ps(s,t)))return ps(s,t);let r=n;for(let s=0;s<8;s++){let o=ps(r,"node_modules",e,t);if(Kh(o))return o;let a=z$(r);if(a===r)break;r=a}throw Error(`Could not locate ${e}/${t} in any parent node_modules of ${n}`)}class oi{parser;loaded=new Map;constructor(e){this.parser=e}static async create(){return await zc.init({locateFile:(e)=>Gh("web-tree-sitter",e)}),new oi(new zc)}async load(e){let t=this.loaded.get(e);if(t)return t;let[n,r]=Q$[e],s=await Vc.load(Gh(n,r)),o=e==="cpp",a={language:s,definitions:new Xc(s,o?Y$:J$),imports:new Xc(s,o?Z$:X$)};return this.loaded.set(e,a),a}async warmup(e){for(let t of e)await this.load(t)}async parseFile(e,t,n){let r=Lt(t);if(!r)return null;let s;try{s=W$(e,"utf-8")}catch{return null}return this.parseSource(s,t,n,r)}async parseSource(e,t,n,r){let s=await this.parseRaw(e,t,r);return s?Zc(s,t,n):null}async parseRaw(e,t,n){let r=n??Lt(t);if(!r)return null;let{language:s,definitions:o,imports:a}=await this.load(r);this.parser.setLanguage(s);let l=this.parser.parse(e);if(!l)return null;try{let c=l.rootNode;return{language:r,lines:e.length===0?0:e.replace(/\n$/,"").split(`
33
+ `).length,symbols:ik(c,e,o,r),importSpecs:dk(c,a),parseError:c.hasError}}finally{l.delete()}}}function ik(e,t,n,r){let s=n.matches(e),o=new Set,a=[];for(let u of s){let d=null,f=null,p=null;for(let x of u.captures){let S=x.node;if(x.name==="name")d=S;else if(x.name.startsWith("definition."))f=S,p=x.name.slice(11)}if(!d||!f||!p)continue;if(sk(f,r))continue;let h=d.text,g=f.startPosition.row+1,w=`${p}:${h}:${g}`;if(o.has(w))continue;o.add(w);let b=ok(f);a.push({name:h,kind:p,line:g,exported:lk(f,r),...b?{container:b}:{},signature:ck(f,t,r)})}let l=new Set(a.filter((u)=>u.kind!=="variable").map((u)=>`${u.name}:${u.line}`)),c=a.filter((u)=>u.kind!=="variable"||!l.has(`${u.name}:${u.line}`));return c.sort((u,d)=>u.line-d.line),c}function sk(e,t){if(t==="cpp")return!1;let n=e.parent;while(n){if(n.type==="object")return!0;if(nk.has(n.type))return!1;n=n.parent}return!1}function ok(e){let t=e.parent;while(t){if(ek.has(t.type)){let n=t.childForFieldName("name");if(n)return n.text}t=t.parent}return}function lk(e,t){let n=e;while(n){if(t==="cpp"){if(tk.has(n.type)&&n!==e)return!1}else{if(ak.has(n.type)&&n!==e)return!1;if(n.type==="export_statement")return!0}n=n.parent}return t==="cpp"}function ck(e,t,n){let r=e;if(n==="cpp"&&e.type==="function_declarator"){let l=e.parent;while(l){if(rk.has(l.type)){r=l;break}l=l.parent}}if(r.type==="variable_declarator"){let l=r.parent?.text.trimStart().split(/\s/)[0]??"const",u=r.childForFieldName("value")?.childForFieldName("body"),d=u&&u.startIndex>r.startIndex?u.startIndex:r.endIndex;return Wh(`${l} ${t.slice(r.startIndex,d)}`)}let s=r.childForFieldName("body"),o=s&&s.startIndex>r.startIndex?s.startIndex:r.endIndex,a=t.slice(r.startIndex,o);return Wh(a)}function Wh(e,t=160){let n=e.replace(/\/\*[\s\S]*?\*\//g," ").split(`
34
34
  `).map((r)=>r.replace(/(^|[^:])\/\/.*$/,"$1")).join(`
35
- `).replace(/\s+/g," ").replace(/[{;,]\s*$/,"").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function S$(e,t){let n=new Set;for(let r of t.matches(e))for(let s of r.captures){if(s.name!=="path")continue;let o=s.node.text.replace(/^["'<]|["'>]$/g,"");if(o)n.add(o)}return[...n]}function jc(e,t,n){let r=new Set,s=new Set,o=ei.dirname(t.replace(/\\/g,"/"));for(let a of e.importSpecs){let l=e.language==="cpp"?E$(a,o,n):k$(a,o,n);if(l)r.add(l);else s.add(a)}return{path:t,language:e.language,lines:e.lines,symbols:e.symbols,imports:[...r].sort(),externalImports:[...s].sort(),parseError:e.parseError}}function $$(e){try{return o$(e).isFile()}catch{return!1}}function Lc(e,t){let n=ei.normalize(t.replace(/\\/g,"/"));if(n===".."||n.startsWith("../")||ei.isAbsolute(n))return null;if(typeof e==="string")return $$(is(e,n))?n:null;return e.has(n)?n:null}function k$(e,t,n){if(!e.startsWith("."))return null;let r=ei.join(t,e);for(let s of R$){let o=Lc(n,`${r}${s}`);if(o)return o}return null}function E$(e,t,n){if(e.startsWith("/"))return null;let r=t;for(;;){let s=Lc(n,ei.join(r,e));if(s)return s;let o=ei.dirname(r);if(o===r||r==="."||r==="")break;r=o}return Lc(n,e)}var l$=`
35
+ `).replace(/\s+/g," ").replace(/[{;,]\s*$/,"").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function dk(e,t){let n=new Set;for(let r of t.matches(e))for(let s of r.captures){if(s.name!=="path")continue;let o=s.node.text.replace(/^["'<]|["'>]$/g,"");if(o)n.add(o)}return[...n]}function Zc(e,t,n){let r=new Set,s=new Set,o=si.dirname(t.replace(/\\/g,"/"));for(let a of e.importSpecs){let l=e.language==="cpp"?hk(a,o,n):pk(a,o,n);if(l)r.add(l);else s.add(a)}return{path:t,language:e.language,lines:e.lines,symbols:e.symbols,imports:[...r].sort(),externalImports:[...s].sort(),parseError:e.parseError}}function fk(e){try{return V$(e).isFile()}catch{return!1}}function Yc(e,t){let n=si.normalize(t.replace(/\\/g,"/"));if(n===".."||n.startsWith("../")||si.isAbsolute(n))return null;if(typeof e==="string")return fk(ps(e,n))?n:null;return e.has(n)?n:null}function pk(e,t,n){if(!e.startsWith("."))return null;let r=si.join(t,e);for(let s of uk){let o=Yc(n,`${r}${s}`);if(o)return o}return null}function hk(e,t,n){if(e.startsWith("/"))return null;let r=t;for(;;){let s=Yc(n,si.join(r,e));if(s)return s;let o=si.dirname(r);if(o===r||r==="."||r==="")break;r=o}return Yc(n,e)}var J$=`
36
36
  (function_declaration name: (identifier) @name) @definition.function
37
37
  (generator_function_declaration name: (identifier) @name) @definition.function
38
38
  (function_signature name: (identifier) @name) @definition.function
@@ -59,10 +59,10 @@ ${JSON.stringify(s,null,2)}`),Error("Language.load failed: no language function
59
59
  ; reads. Declarators bound to a function match both patterns; collectSymbols
60
60
  ; keeps the function one.
61
61
  (variable_declarator name: (identifier) @name) @definition.variable
62
- `,c$=`
62
+ `,X$=`
63
63
  (import_statement source: (string) @path)
64
64
  (export_statement source: (string) @path)
65
- `,u$=`
65
+ `,Y$=`
66
66
  (struct_specifier name: (type_identifier) @name body: (_)) @definition.class
67
67
  ; A body is required for the same reason struct_specifier requires one: without
68
68
  ; it, a forward declaration indexes as a definition, and the symbol index then
@@ -80,52 +80,52 @@ ${JSON.stringify(s,null,2)}`),Error("Language.load failed: no language function
80
80
  (type_definition declarator: (type_identifier) @name) @definition.type
81
81
  (enum_specifier name: (type_identifier) @name) @definition.enum
82
82
  (namespace_definition name: (namespace_identifier) @name) @definition.module
83
- `,d$=`
83
+ `,Z$=`
84
84
  (preproc_include path: (string_literal) @path)
85
- `,f$,p$,h$,m$,g$,b$,R$;var Uc=qe(()=>{Ji();yh();f$={typescript:["tree-sitter-typescript","tree-sitter-typescript.wasm"],tsx:["tree-sitter-typescript","tree-sitter-tsx.wasm"],cpp:["tree-sitter-cpp","tree-sitter-cpp.wasm"]};p$=new Set(["class_declaration","abstract_class_declaration","interface_declaration","class_specifier","struct_specifier"]),h$=new Set(["compound_statement"]),m$=new Set(["class_body","interface_body","statement_block","program"]),g$=new Set(["field_declaration","declaration","function_definition","template_declaration"]);b$=new Set(["statement_block","arrow_function","function_expression"]);R$=["",".ts",".tsx",".d.ts",".js",".jsx","/index.ts","/index.tsx","/index.js"]});import{createHash as I$}from"crypto";function gn(e,t){let n=t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim();return I$("sha1").update(`${e}\x00${n}`).digest("hex").slice(0,10)}function P$(e){return String(e).replace(/\s+/g,"_").replace(/-{2,}/g,"-").replace(/>/g,"_")}function Mt(e,t={}){let n=[`kind=${e}`];for(let[r,s]of Object.entries(t))n.push(`${r}=${P$(s)}`);return`<!-- ${Bc} ${n.join(" ")} -->`}function jt(e){return e.replace(new RegExp(`[ \\t]*${kh.source}`,"g"),"").replace(/\n{3,}/g,`
85
+ `,Q$,ek,tk,nk,rk,ak,uk;var Qc=He(()=>{rs();Hh();Q$={typescript:["tree-sitter-typescript","tree-sitter-typescript.wasm"],tsx:["tree-sitter-typescript","tree-sitter-tsx.wasm"],cpp:["tree-sitter-cpp","tree-sitter-cpp.wasm"]};ek=new Set(["class_declaration","abstract_class_declaration","interface_declaration","class_specifier","struct_specifier"]),tk=new Set(["compound_statement"]),nk=new Set(["class_body","interface_body","statement_block","program"]),rk=new Set(["field_declaration","declaration","function_definition","template_declaration"]);ak=new Set(["statement_block","arrow_function","function_expression"]);uk=["",".ts",".tsx",".d.ts",".js",".jsx","/index.ts","/index.tsx","/index.js"]});import{createHash as wk}from"crypto";function wn(e,t){let n=t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim();return wk("sha1").update(`${e}\x00${n}`).digest("hex").slice(0,10)}function yk(e){return String(e).replace(/\s+/g,"_").replace(/-{2,}/g,"-").replace(/>/g,"_")}function Tt(e,t={}){let n=[`kind=${e}`];for(let[r,s]of Object.entries(t))n.push(`${r}=${yk(s)}`);return`<!-- ${eu} ${n.join(" ")} -->`}function Ut(e){return e.replace(new RegExp(`[ \\t]*${Xh.source}`,"g"),"").replace(/\n{3,}/g,`
86
86
 
87
- `).trimEnd()}function ni(e){let t=e.indexOf(Xo),n=e.lastIndexOf(os);if(t<0||n<t)return e;return`${e.slice(0,t).trimEnd()}
87
+ `).trimEnd()}function ai(e){let t=e.indexOf(ia),n=e.lastIndexOf(ms);if(t<0||n<t)return e;return`${e.slice(0,t).trimEnd()}
88
88
 
89
- ${e.slice(n+os.length).trimStart()}`.trim()}function T$(e){let t={};for(let r of e.split(/\s+/)){let s=r.indexOf("=");if(s>0)t[r.slice(0,s)]=r.slice(s+1)}let n=t.kind;if(!M$.includes(n))return null;return delete t.kind,{kind:n,fields:t}}function tn(e){let t=[];for(let n of e.matchAll(kh)){let r=T$(n[1]);if(r)t.push(r)}return t}function ri(e,t){return tn(e).find((n)=>n.kind===t)??null}function F$(e){return tn(e)[0]??null}function Cn(e,t,n){if(t!=null&&t!=="Bot")return!1;if(n!==void 0)return ri(e,n)!==null;return tn(e).length>0}function Yo(e){let t=new Set;for(let n of e){let r=n.body??"";if(!n.in_reply_to_id||!Cn(r,n.user?.type,"reply"))continue;let s=F$(r);if(s?.fields.addressed!=="1")continue;let o=Number(s.fields.of);t.add(Number.isFinite(o)&&o>0?o:n.in_reply_to_id)}return t}function Eh(e){let t=[...e.matchAll($h)],n=(l)=>jt(l).trim(),r=t.map((l,c)=>e.slice((l.index??0)+l[0].length,t[c+1]?.index??e.length)),s=e.slice(0,t[0]?.index??0),o=!!n(s)&&!n(r.at(-1)??""),a=[];return t.forEach((l,c)=>{let u={};for(let h of(l[1]??"").split(/\s+/)){let g=h.indexOf("=");if(g>0)u[h.slice(0,g)]=h.slice(g+1)}let d=u.verdict??u.action,f=u.fp;if(!f||!/^[0-9a-f]{6,40}$/i.test(f)||d!=="disputed"&&d!=="fixed")return;let p=t.length===1?n(e.replace($h,"")):o?n(c===0?s:r[c-1]??""):n((c===0?s:"")+(r[c]??""));a.push({fp:f.toLowerCase(),verdict:d,reason:p})}),a}var Bc="ai-review",kh,Xo="<!-- ai-review-copy -->",os="<!-- /ai-review-copy -->",M$,$h;var xr=qe(()=>{kh=new RegExp(`<!--\\s*${Bc}\\s+([^>]*?)\\s*-->`,"g");M$=["summary","summary-item","inline","reply","dispute","stopped"];$h=new RegExp(`<!--\\s*${Bc}-response\\s+([^>]*?)\\s*-->`,"g")});import{posix as zc}from"path";function Gh(e){let t=zc.dirname(e);return t==="."?void 0:zc.basename(t)}function X$(e){let t=zc.basename(e);if(!qh.test(t))return t;let n=t.replace(qh,"").replace(/\.d$/,""),r=Gh(e);return J$.has(n.toLowerCase())&&r?`${r}/${n}`:n}function Y$(e){return e.replace(/[._-](?:test|spec)(\.[^./]+)$/,"$1")}function Z$(e,t){let n=new Map;for(let r of e){let s=Y$(r),o=n.get(s)??{path:s,label:X$(s),weight:0};o.weight+=t(r),n.set(s,o)}return[...n.values()].sort((r,s)=>s.weight-r.weight)}function Hh(e){let t=Gh(e.path);if(!t||e.label.includes("/"))return e.label;let n=`${t}/${e.label}`;return n.length<=Wh?n:e.label}function Kh(e,t){let[n,r]=e;if(!n)return"Files";let s=t?Hh(n):n.label;if(e.length===1)return Hh(n);if(e.length===2&&r){let o=`${s}, ${r.label}`;if(o.length<=Wh)return o}return`${s} +${e.length-1}`}function si(e,t=()=>0){let n=e.map((c)=>Z$(c.files,t)),r=n.map((c)=>Kh(c,!1)),o=((c)=>{let u=new Map;for(let d of c)u.set(d,(u.get(d)??0)+1);return u})(r),a=r.map((c,u)=>(o.get(c)??0)>1?Kh(n[u]??[],!0):c),l=new Map;return a.map((c)=>{let u=(l.get(c)??0)+1;return l.set(c,u),u===1?c:`${c} (${u})`})}var Wh=24,qh,J$;var aa=qe(()=>{qh=/\.(?:c|cc|cpp|cs|css|cts|cjs|go|h|hpp|java|js|jsx|kt|less|mjs|mts|php|py|rb|rs|sass|scss|svelte|swift|ts|tsx|vue)$/i,J$=new Set(["__init__","common","constants","helpers","index","init","lib","main","mod","shared","types","util","utils"])});function ai(e){if(ik.some((t)=>e.includes(t)))return"skip";if(em.test(e)||em.test(e.split("/").pop()??""))return"docs";return"code"}var ik,em;var ls=qe(()=>{ik=["pnpm-lock.yaml","package-lock.json","bun.lock","yarn.lock","Cargo.lock","go.sum",".min.js",".min.css",".bundle.js",".map","__snapshots__/"],em=/\.(md|mdx|txt|rst)$|^LICENSE|^\.gitignore$|^\.gitattributes$/});function sm(e){let t=e.filter((s)=>!s.preexisting),n=t.filter((s)=>s.severity==="blocker").length,r=t.filter((s)=>s.severity==="should-fix").length;if(n)return{level:"high",label:"Merge risk: high",detail:`${n} ${n===1?"blocker":"blockers"} open.`};if(r)return{level:"moderate",label:"Merge risk: moderate",detail:`${r} should-fix ${r===1?"finding":"findings"} open.`};return{level:"low",label:"Merge risk: low",detail:"nothing found that should block this."}}function om(e){let t=e.filter((r)=>r.surface==="product"&&!r.preexisting),n=t.filter(Ck).length;if(t.length===0)return{level:"low",label:"Prod risk: none",detail:"everything found is in tooling, deploy or test code."};if(n)return{level:"high",label:`Prod risk: ${n}`,detail:`${n===1?"finding":"findings"} in production code worth acting on.`};return{level:"moderate",label:"Prod risk: low",detail:`${t.length} in production code, none above a question.`}}function am(e){let t=new Set(e);return rm.find((n)=>t.has(n))??"product"}var qt,rm,im,Ck=(e)=>e.severity==="blocker"||e.severity==="should-fix";var ca=qe(()=>{qt={product:0,deploy:1,tooling:2},rm=["product","deploy","tooling"],im={product:"Prod risk",deploy:"Deploy risk",tooling:"Main findings \u2014 tooling"}});function ot(e){if(/\.(test|spec)\.[cm]?[jt]sx?$/.test(e))return"tooling";if(jo.deploy.some((t)=>new RegExp(t).test(e)))return"deploy";if(/(^|\/)(Earthfile|[^/]*Dockerfile[^/]*)$/.test(e))return"deploy";if(/(^|\/)(scripts|test|tests|__tests__|e2e)\//.test(e))return"tooling";if(jo.tooling.some((t)=>new RegExp(t).test(e)))return"tooling";if(/^\./.test(e))return"tooling";if(!e.includes("/"))return"tooling";return"product"}function lm(e,t){let n=e.length?e:t.map((r)=>r.file);return am(n.map(ot))}function dm(e){let t=Math.min(e.line,e.end_line??e.line),n=Math.max(e.line,e.end_line??e.line);if(!e._anchor)return!0;if(e._anchor.kind!=="anchorable")return!1;return(e._anchor.start_line??e._anchor.line)===t&&e._anchor.line===n}function ua(e,t=280){let n=(e??"").trim();if(n.length<=t)return n;let r=n.split(/(?<=[.!?])\s+/),s="";for(let o of r){if(s&&`${s} ${o}`.length>t)break;s=s?`${s} ${o}`:o}return s.trim()}var cm,ci,tt,um,fm;var Sr=qe(()=>{bt();ca();ca();cm={product:"",deploy:"\uD83D\uDEA2 deploy",tooling:"\uD83D\uDD27 tooling"},ci=["high","medium","low"],tt={blocker:{badge:"\uD83D\uDD34 **Blocker**",rank:0},"should-fix":{badge:"\uD83D\uDFE0 **Should fix**",rank:1},question:{badge:"\uD83D\uDD35 **Question**",rank:2},"nice-to-have":{badge:"\u26AA **Nice to have**",rank:3}},um={quick:"\u26A1 Quick fix",moderate:"\uD83D\uDD28 Some work",involved:"\uD83C\uDFD7\uFE0F Involved"};fm={bug:"\uD83C\uDFAF Correctness",race:"\uD83E\uDE7A Concurrency","edge-case":"\uD83C\uDFAF Correctness","resource-leak":"\uD83E\uDE7A Stability",invariant:"\uD83D\uDDC4\uFE0F Data integrity",architecture:"\uD83D\uDCD0 Architecture",duplication:"\uD83D\uDCD0 Architecture",performance:"\uD83D\uDE80 Performance",security:"\uD83D\uDD12 Security",other:"\u26AA Other"}});function ga(e){let t=[...e.findings.map((o)=>o.anchor),...e.overCapFindings.map((o)=>o.anchor),...e.stops.flatMap((o)=>o.locations)],n=(o)=>t.filter((a)=>a.kind===o).length,r=[...new Set(t.flatMap((o)=>o.kind==="file"&&o.reason?[o.reason]:[]))],s=`${n("file")} file${r.length?` (${r.join(", ")})`:""}`;return`${n("line")} line, ${n("nearby")} nearby, ${s}`}function du(e,t){let n=[];for(let r of e.hunks){let s=t==="additions"?r.additionStart:r.deletionStart,o=t==="additions"?r.additionCount:r.deletionCount;if(o>0)n.push({start:s,end:s+o-1,hunk:r})}return n}function fu(e,t,n,r){let s=t==="additions"?e.additionLines:e.deletionLines,o=t==="additions"?n.hunk.additionLineIndex:n.hunk.deletionLineIndex;return s[o+(r-n.start)]?.replace(/\r?\n$/,"")}function ds(e,t,n){return{file:e,side:"additions",kind:"file",line:0,cited:t,...n?{reason:n}:{}}}function uu(e,t,n,r,s,o){let a=du(e,n).find((u)=>r>=u.start&&r<=u.end);if(!a)return null;let l=s!==void 0&&s>r?Math.min(s,a.end):void 0,c=fu(e,n,a,r);return{file:t,side:n,kind:"line",line:r,...l!==void 0&&l>r?{endLine:l}:{},cited:o,...c!==void 0?{text:c}:{}}}function _a(e,t,n,r,s={}){let o=n!==void 0&&Number.isFinite(n)&&n>0,a=o?r!==void 0&&r>0?Math.min(n,r):n:0,l=o&&r!==void 0&&r>0?Math.max(n,r):void 0,c={line:a,...l!==void 0&&l!==a?{endLine:l}:{}};if(!e)return ds(t,c,"not-in-diff");if(!o)return ds(t,c,"no-line");if(e.type==="deleted")return(s.deletionsFallback?uu(e,t,"deletions",a,l,c):null)??ds(t,c,"deleted-file");let u=du(e,"additions");if(!u.length)return ds(t,c,"no-hunks");let d=uu(e,t,"additions",a,l,c)??(s.deletionsFallback?uu(e,t,"deletions",a,l,c):null);if(d)return d;let f;for(let p of u){let h=a<p.start?p.start:p.end,g=Math.abs(h-a);if(!f||g<f.distance)f={line:h,range:p,distance:g}}if(f&&f.distance<=20){let p=fu(e,"additions",f.range,f.line);return{file:t,side:"additions",kind:"nearby",line:f.line,cited:c,...p!==void 0?{text:p}:{}}}return ds(t,c,"far-from-diff")}function Xm(e,t){for(let n of[e,t]){let r=n?.trim().replace(/\(\)$/,"");if(r&&/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(r))return r.slice(r.lastIndexOf(".")+1)}return}function Ym(e,t,n,r={}){if(!e||!n)return t;let s=new RegExp(`(?<![\\w$])${Jm(n)}(?![\\w$])`);if(t.kind!=="file"&&t.text!==void 0&&s.test(t.text))return t;let o=Jm(n),a=new RegExp([`\\b(?:function\\*?|class|interface|type|enum|namespace|def|fn|struct|trait|const|let|var)\\s+${o}(?![\\w$])`,`^\\s*(?:(?:export|default|public|private|protected|static|readonly|async|override|get|set|pub)\\s+)*\\*?${o}\\s*(?:<[^>]*>)?\\s*[(=:]`].join("|")),l=e.type==="deleted"?["deletions"]:r.deletionsFallback?["additions","deletions"]:["additions"],c=t.cited.line;for(let u of l){let d=[];for(let g of du(e,u))for(let w=g.start;w<=g.end;w++){let b=fu(e,u,g,w);if(b===void 0||!s.test(b))continue;d.push({line:w,text:b,definition:a.test(b),distance:c>0?Math.abs(w-c):w})}if(!d.length)continue;let f=(g,w)=>g.distance-w.distance,h=(c>0?d.filter((g)=>g.distance<=zk).sort(f)[0]:void 0)??d.filter((g)=>g.definition).sort(f)[0]??d.sort(f)[0];if(!h)continue;return{file:t.file,side:u,kind:"line",line:h.line,cited:t.cited,text:h.text}}return t}var zk=3,Jm=(e)=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function tl(e){if(typeof e!=="object"||e===null)return;let t=e;if(typeof t.input_tokens!=="number"&&typeof t.output_tokens!=="number")return;let n=t.first_step;return{input:xn(t.input_tokens),output:xn(t.output_tokens),reasoning:xn(t.reasoning_tokens),cacheRead:xn(t.cache_read_input_tokens),cacheWrite:xn(t.cache_creation_input_tokens),...typeof n==="object"&&n!==null?{firstStep:{input:xn(n.input_tokens),cacheRead:xn(n.cache_read_input_tokens),cacheWrite:xn(n.cache_creation_input_tokens)}}:{}}}function Md(e){if(typeof e!=="object"||e===null)return;let t=e;if(t.cached===!0)return;let n=tl(t.usage),r=xn(t.costUsd);if(!n&&r===0)return;return{costUsd:r,wallMs:xn(t.wallMs),...n?{usage:n}:{}}}function Fd(e){let t=Md(e?.merge),n=Md(e?.walk),r=Md(e?.intentDraft);if(!t&&!n&&!r)return;return{...t?{coordinator:t}:{},...n?{walkthrough:n}:{},...r?{intent:r}:{}}}function $y(e,t){if(typeof t!=="object"||t===null)return e;let n=t,r=Array.isArray(n.sliceRuns)?n.sliceRuns:[],s=e.meta.slices.map((a,l)=>{if(a.usage)return a;let c=r[l];if(!c||c.unit!==a.unit||c.part!==a.part)return a;let u=tl(c.usage);return u?{...a,usage:u}:a}),o=e.meta.stages??Fd(n);return{...e,meta:{...e.meta,slices:s,...o?{stages:o}:{}}}}function ky(e){return e.meta.slices.some((t)=>t.usage)||Object.values(e.meta.stages??{}).some((t)=>t?.usage)}function rl(e){let t=e.input+e.cacheRead+e.cacheWrite;return t>0?e.cacheRead/t:null}function Ry(e,t){e.input+=t.input,e.output+=t.output,e.reasoning+=t.reasoning,e.cacheRead+=t.cacheRead,e.cacheWrite+=t.cacheWrite,e.calls++}function Hs(e,t=nl()){for(let n of e.meta.slices){if(!n.usage)continue;Ry(t,n.usage);let r=n.usage.firstStep?rl(n.usage.firstStep):null;if(r!==null)t.firstStepShares.push(r)}for(let n of Object.values(e.meta.stages??{}))if(n?.usage)Ry(t,n.usage);return t}function iO(e){let t=[...e].sort((s,o)=>s-o),n=Math.floor(t.length/2),r=t[n];if(r===void 0)return null;return t.length%2?r:((t[n-1]??r)+r)/2}function Ks(e){if(!e.calls)return;let t=rl(e),n=iO(e.firstStepShares),r=e.input+e.cacheRead+e.cacheWrite;return`${Td(r)} prompt${t===null?"":` (${Sy(t)} from cache)`}, ${Td(e.output)} output`+(e.reasoning?`, ${Td(e.reasoning)} reasoning`:"")+(n===null?"":`; first requests ${Sy(n)} from cache (median of ${e.firstStepShares.length})`)}var xn=(e)=>typeof e==="number"&&Number.isFinite(e)?e:0,nl=()=>({input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,calls:0,firstStepShares:[]}),Td=(e)=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1000?`${Math.round(e/1000)}K`:String(e),Sy=(e)=>`${Math.round(e*100)}%`;function Dn(e){return e.replace(/-\d+$/,"")}function Uy(e){return e.findings.map((t,n)=>({id:n+1,file:t.file,...t.anchor.cited.line?{line:t.anchor.cited.line}:{},author:"diffloupe",body:`**${t.title}** ${t.impact??t.explanation}`,resolved:!1,mine:!0,fingerprint:Dn(t.id)}))}function By(e){let t=new Map,n,r;for(let s of e.split(`
90
- `)){let o=s.match(/^--- (?:a\/(.+)|\/dev\/null)$/);if(o){r=o[1];continue}let a=s.match(/^\+\+\+ (?:b\/(.+)|\/dev\/null)$/);if(a){let c=a[1]??r;if(n=c?[]:void 0,c&&n)t.set(c,n);continue}let l=s.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(l&&n)n.push({oldStart:Number(l[1]),oldCount:l[2]===void 0?1:Number(l[2]),newStart:Number(l[3]),newCount:l[4]===void 0?1:Number(l[4])})}return t}function Bd(e,t){let n=0;for(let r of e){if(r.oldCount===0){if(t<=r.oldStart)break;n+=r.newCount;continue}if(t<r.oldStart)break;if(t<r.oldStart+r.oldCount)return Math.max(1,r.newStart);n+=r.newCount-r.oldCount}return t+n}var nV,$b,tf,kb,Eb,ZO,rV,iV;var Ab=qe(()=>{nV=(()=>{try{return!0}catch{return!1}})(),$b=/(?=^From [a-f0-9]+ .+$)/m,tf=/(?=^diff --git)/gm,kb=/^(---|\+\+\+)\s+([^\t\r\n]+)/,Eb=/^index ([0-9a-f]+)\.\.([0-9a-f]+)(?: (\d+))?$/i,ZO={hunkLineCount:50,lineHeight:20,diffHeaderHeight:44,spacing:8},rV={...ZO,hunkLineCount:1},iV=Object.freeze({fromStart:0,fromEnd:0})});function Qs(e,t){return e-(t===0?0:1)}function nf(e,t){return Qs(e,t)+t}var Cb=()=>{};function rf(e,...t){return`ck1:${JSON.stringify([e,...t])}`}var Ob=()=>{};function sf(e){let t=e.length;if(e.charCodeAt(t-1)===10){if(t--,e.charCodeAt(t-1)===13)t--}return e.slice(0,t)}var Ib=()=>{};function Pb(){if(Ni.length!==1024)Ni=new Uint8Array(1024)}function Ue(e){if(e.length===0)return e;if(tI.test(e))return JSON.parse(JSON.stringify(e));let t=e.length*3;if(Ni.length<t)Ni=new Uint8Array(t);let{written:n}=QO.encodeInto(e,Ni);return eI.decode(Ni.subarray(0,n))}var QO,eI,tI,Ni;var Mb=qe(()=>{QO=new TextEncoder,eI=new TextDecoder("utf-8",{ignoreBOM:!0}),tI=/[\uD800-\uDFFF]/,Ni=new Uint8Array(1024)});function Tb(e){if(e[0]!=='"')return;let t="",n=1;while(n<e.length){let r=e[n];if(r==='"')return{fileName:t,rawLength:n+1};if(r!=="\\"){t+=r,n++;continue}let s=rI[e[n+1]];if(s!=null){t+=s,n+=2;continue}let o=[];do{let a=iI(e,n+1);if(a==null)return;o.push(a),n+=4}while(e[n]==="\\"&&e[n+1]>="0"&&e[n+1]<="7");t+=nI.decode(new Uint8Array(o))}}function iI(e,t){let n=e.charCodeAt(t)-48,r=e.charCodeAt(t+1)-48,s=e.charCodeAt(t+2)-48;if(n>=0&&n<=3&&r>=0&&r<=7&&s>=0&&s<=7)return n*64+r*8+s}var nI,rI;var Fb=qe(()=>{nI=new TextDecoder("utf-8",{ignoreBOM:!0}),rI={'"':'"',"\\":"\\",a:"\x07",b:"\b",t:"\t",n:`
91
- `,v:"\v",f:"\f",r:"\r"}});function Db(e){for(let t of e.hunks)for(let n=0;n<t.hunkContent.length;n++){let r=t.hunkContent[n];if(r.type!=="change")continue;let s=sI(e,r);if(s!=null)t.hunkContent.splice(n,1,...s),n+=s.length-1}}function sI(e,t){let{deletions:n,additions:r,deletionLineIndex:s,additionLineIndex:o}=t,a=Math.min(n,r),l=Math.abs(r-n);if(a===0||l===0||a*(l+1)>4096)return null;let c=[];for(let w=0;w<n;w++)c.push(Nb(e.deletionLines[s+w]??""));let u=[];for(let w=0;w<r;w++)u.push(Nb(e.additionLines[o+w]??""));let d=r>n,f=0,p=-1;for(let w=0;w<=l;w++){let b=0;for(let x=0;x<a;x++)b+=aI(c[x+(d?0:w)],u[x+(d?w:0)]);if(w===0)p=b+a*0.5;else if(b>p)p=b,f=w}if(f===0)return null;let h=[],g=(w,b,x,R)=>{if(w>0||b>0)h.push({type:"change",deletions:w,additions:b,deletionLineIndex:x,additionLineIndex:R})};if(d)g(0,f,s,o),g(a,a,s,o+f),g(0,r-a-f,s+a,o+f+a);else g(f,0,s,o),g(a,a,s+f,o),g(n-a-f,0,s+f+a,o+a);return h}function Nb(e){return e.replace(oI,"")}function aI(e,t){if(e===t)return 1;let n=Math.max(e.length,t.length),r=Math.min(e.length,t.length);if(r===0)return 0;let s=0;while(s<r&&e[s]===t[s])s++;let o=0;while(o<r-s&&e[e.length-1-o]===t[t.length-1-o])o++;return(s+o)/n}var oI;var Lb=qe(()=>{oI=/\s+/g});function cI(e,t,n=!1,r){let s=wI(e),o=s?fI(e):pI(e),a,l=[];for(let c of o){if(s&&!tf.test(c)){if(a==null)a=Ue(c);else if(n)throw Error("parsePatchContent: unknown file blob");else console.error("parsePatchContent: unknown file blob:",c);continue}else if(!s&&!hI(c)){if(a==null)a=Ue(c);else if(n)throw Error("parsePatchContent: unknown file blob");else console.error("parsePatchContent: unknown file blob:",c);continue}let u=uI(c,{cacheKey:t!=null?r==null?rf("patch-file",t,String(l.length)):rf("patch-file",t,String(r),String(l.length)):void 0,isGitDiff:s,throwOnError:n});if(u!=null)l.push(u)}return{patchMetadata:a,files:l}}function uI(e,{cacheKey:t,isGitDiff:n=tf.test(e),oldFile:r,newFile:s,throwOnError:o=!1}={}){let a=0,l=Gb(e,"@@ "),c,u=r==null||s==null,d=0,f=0;for(let p of l){let h=Hb(p),g=h[0];if(g==null){if(o)throw Error("parsePatchContent: invalid hunk");else console.error("parsePatchContent: invalid hunk",p);continue}let w=Wb(g),b=0,x=0;if(w==null||c==null){if(c!=null){if(o)throw Error("parsePatchContent: Invalid hunk");else console.error("parsePatchContent: Invalid hunk",p);continue}if(c={name:"",type:"change",hunks:[],splitLineCount:0,unifiedLineCount:0,isPartial:u,additionLines:!u&&r!=null&&s!=null?jb(s.contents):[],deletionLines:!u&&r!=null&&s!=null?jb(r.contents):[],cacheKey:qb(t)},c.additionLines.length===1&&s?.contents==="")c.additionLines.length=0;if(c.deletionLines.length===1&&r?.contents==="")c.deletionLines.length=0;for(let O of h){if(O.startsWith("diff --git")){let I=O.trim().match(lI);if(I==null){if(o)throw Error("parsePatchContent: invalid git diff header");else console.error("parsePatchContent: invalid git diff header",O);continue}let j=eo(I[1],!0),H=eo(I[2],!0);if(c.name=Ue(H),j!==H)c.prevName=Ue(j);continue}let U=O.startsWith("---")||O.startsWith("+++")?O.match(kb):null;if(U!=null){let[,I,j]=U,H=eo(j,n);if(I==="---"&&H!=="/dev/null"){let ve=Ue(H);c.prevName=ve,c.name=ve}else if(I==="+++"&&H!=="/dev/null")c.name=Ue(H)}else if(n){if(O.startsWith("new mode "))c.mode=Ue(O.slice(8).trim());if(O.startsWith("old mode "))c.prevMode=Ue(O.slice(8).trim());if(O.startsWith("new file mode"))c.type="new",c.mode=Ue(O.slice(13).trim());if(O.startsWith("deleted file mode"))c.type="deleted",c.mode=Ue(O.slice(17).trim());if(O.startsWith("similarity index"))if(O.startsWith("similarity index 100%"))c.type="rename-pure";else c.type="rename-changed";if(O.startsWith("index ")){let[,I,j,H]=O.trim().match(Eb)??[];if(I!=null)c.prevObjectId=Ue(I);if(j!=null)c.newObjectId=Ue(j);if(H!=null)c.mode=Ue(H)}if(O.startsWith("rename from ")||O.startsWith("copy from "))c.prevName=Ue(eo(O.slice(O.startsWith("rename")?12:10)));if(O.startsWith("rename to ")||O.startsWith("copy to "))c.name=Ue(eo(O.slice(O.startsWith("rename")?10:8)))}}continue}let R,P;while(h.length>0&&(h[h.length-1]===`
89
+ ${e.slice(n+ms.length).trimStart()}`.trim()}function vk(e){let t={};for(let r of e.split(/\s+/)){let s=r.indexOf("=");if(s>0)t[r.slice(0,s)]=r.slice(s+1)}let n=t.kind;if(!bk.includes(n))return null;return delete t.kind,{kind:n,fields:t}}function rn(e){let t=[];for(let n of e.matchAll(Xh)){let r=vk(n[1]);if(r)t.push(r)}return t}function li(e,t){return rn(e).find((n)=>n.kind===t)??null}function xk(e){return rn(e)[0]??null}function In(e,t,n){if(t!=null&&t!=="Bot")return!1;if(n!==void 0)return li(e,n)!==null;return rn(e).length>0}function sa(e){let t=new Set;for(let n of e){let r=n.body??"";if(!n.in_reply_to_id||!In(r,n.user?.type,"reply"))continue;let s=xk(r);if(s?.fields.addressed!=="1")continue;let o=Number(s.fields.of);t.add(Number.isFinite(o)&&o>0?o:n.in_reply_to_id)}return t}function Yh(e){let t=[...e.matchAll(Jh)],n=(l)=>Ut(l).trim(),r=t.map((l,c)=>e.slice((l.index??0)+l[0].length,t[c+1]?.index??e.length)),s=e.slice(0,t[0]?.index??0),o=!!n(s)&&!n(r.at(-1)??""),a=[];return t.forEach((l,c)=>{let u={};for(let h of(l[1]??"").split(/\s+/)){let g=h.indexOf("=");if(g>0)u[h.slice(0,g)]=h.slice(g+1)}let d=u.verdict??u.action,f=u.fp;if(!f||!/^[0-9a-f]{6,40}$/i.test(f)||d!=="disputed"&&d!=="fixed")return;let p=t.length===1?n(e.replace(Jh,"")):o?n(c===0?s:r[c-1]??""):n((c===0?s:"")+(r[c]??""));a.push({fp:f.toLowerCase(),verdict:d,reason:p})}),a}var eu="ai-review",Xh,ia="<!-- ai-review-copy -->",ms="<!-- /ai-review-copy -->",bk,Jh;var kr=He(()=>{Xh=new RegExp(`<!--\\s*${eu}\\s+([^>]*?)\\s*-->`,"g");bk=["summary","summary-item","inline","reply","dispute","stopped"];Jh=new RegExp(`<!--\\s*${eu}-response\\s+([^>]*?)\\s*-->`,"g")});import{posix as au}from"path";function gm(e){let t=au.dirname(e);return t==="."?void 0:au.basename(t)}function Fk(e){let t=au.basename(e);if(!fm.test(t))return t;let n=t.replace(fm,"").replace(/\.d$/,""),r=gm(e);return Nk.has(n.toLowerCase())&&r?`${r}/${n}`:n}function Lk(e){return e.replace(/[._-](?:test|spec)(\.[^./]+)$/,"$1")}function jk(e,t){let n=new Map;for(let r of e){let s=Lk(r),o=n.get(s)??{path:s,label:Fk(s),weight:0};o.weight+=t(r),n.set(s,o)}return[...n.values()].sort((r,s)=>s.weight-r.weight)}function pm(e){let t=gm(e.path);if(!t||e.label.includes("/"))return e.label;let n=`${t}/${e.label}`;return n.length<=mm?n:e.label}function hm(e,t){let[n,r]=e;if(!n)return"Files";let s=t?pm(n):n.label;if(e.length===1)return pm(n);if(e.length===2&&r){let o=`${s}, ${r.label}`;if(o.length<=mm)return o}return`${s} +${e.length-1}`}function ui(e,t=()=>0){let n=e.map((c)=>jk(c.files,t)),r=n.map((c)=>hm(c,!1)),o=((c)=>{let u=new Map;for(let d of c)u.set(d,(u.get(d)??0)+1);return u})(r),a=r.map((c,u)=>(o.get(c)??0)>1?hm(n[u]??[],!0):c),l=new Map;return a.map((c)=>{let u=(l.get(c)??0)+1;return l.set(c,u),u===1?c:`${c} (${u})`})}var mm=24,fm,Nk;var ma=He(()=>{fm=/\.(?:c|cc|cpp|cs|css|cts|cjs|go|h|hpp|java|js|jsx|kt|less|mjs|mts|php|py|rb|rs|sass|scss|svelte|swift|ts|tsx|vue)$/i,Nk=new Set(["__init__","common","constants","helpers","index","init","lib","main","mod","shared","types","util","utils"])});function fi(e){if(Gk.some((t)=>e.includes(t)))return"skip";if(Rm.test(e)||Rm.test(e.split("/").pop()??""))return"docs";return"code"}var Gk,Rm;var _s=He(()=>{Gk=["pnpm-lock.yaml","package-lock.json","bun.lock","yarn.lock","Cargo.lock","go.sum",".min.js",".min.css",".bundle.js",".map","__snapshots__/"],Rm=/\.(md|mdx|txt|rst)$|^LICENSE|^\.gitignore$|^\.gitattributes$/});function Om(e){let t=e.filter((s)=>!s.preexisting),n=t.filter((s)=>s.severity==="blocker").length,r=t.filter((s)=>s.severity==="should-fix").length;if(n)return{level:"high",label:"Merge risk: high",detail:`${n} ${n===1?"blocker":"blockers"} open.`};if(r)return{level:"moderate",label:"Merge risk: moderate",detail:`${r} should-fix ${r===1?"finding":"findings"} open.`};return{level:"low",label:"Merge risk: low",detail:"nothing found that should block this."}}function Im(e){let t=e.filter((r)=>r.surface==="product"&&!r.preexisting),n=t.filter(_E).length;if(t.length===0)return{level:"low",label:"Prod risk: none",detail:"everything found is in tooling, deploy or test code."};if(n)return{level:"high",label:`Prod risk: ${n}`,detail:`${n===1?"finding":"findings"} in production code worth acting on.`};return{level:"moderate",label:"Prod risk: low",detail:`${t.length} in production code, none above a question.`}}function Pm(e){let t=new Set(e);return Cm.find((n)=>t.has(n))??"product"}var Ht,Cm,Am,_E=(e)=>e.severity==="blocker"||e.severity==="should-fix";var _a=He(()=>{Ht={product:0,deploy:1,tooling:2},Cm=["product","deploy","tooling"],Am={product:"Prod risk",deploy:"Deploy risk",tooling:"Main findings \u2014 tooling"}});function ot(e){if(/\.(test|spec)\.[cm]?[jt]sx?$/.test(e))return"tooling";if(Yo.deploy.some((t)=>new RegExp(t).test(e)))return"deploy";if(/(^|\/)(Earthfile|[^/]*Dockerfile[^/]*)$/.test(e))return"deploy";if(/(^|\/)(scripts|test|tests|__tests__|e2e)\//.test(e))return"tooling";if(Yo.tooling.some((t)=>new RegExp(t).test(e)))return"tooling";if(/^\./.test(e))return"tooling";if(!e.includes("/"))return"tooling";return"product"}function Mm(e,t){let n=e.length?e:t.map((r)=>r.file);return Pm(n.map(ot))}function Nm(e){let t=Math.min(e.line,e.end_line??e.line),n=Math.max(e.line,e.end_line??e.line);if(!e._anchor)return!0;if(e._anchor.kind!=="anchorable")return!1;return(e._anchor.start_line??e._anchor.line)===t&&e._anchor.line===n}function wa(e,t=280){let n=(e??"").trim();if(n.length<=t)return n;let r=n.split(/(?<=[.!?])\s+/),s="";for(let o of r){if(s&&`${s} ${o}`.length>t)break;s=s?`${s} ${o}`:o}return s.trim()}var Tm,hi,tt,Dm,Fm;var Cr=He(()=>{bt();_a();_a();Tm={product:"",deploy:"\uD83D\uDEA2 deploy",tooling:"\uD83D\uDD27 tooling"},hi=["high","medium","low"],tt={blocker:{badge:"\uD83D\uDD34 **Blocker**",rank:0},"should-fix":{badge:"\uD83D\uDFE0 **Should fix**",rank:1},question:{badge:"\uD83D\uDD35 **Question**",rank:2},"nice-to-have":{badge:"\u26AA **Nice to have**",rank:3}},Dm={quick:"\u26A1 Quick fix",moderate:"\uD83D\uDD28 Some work",involved:"\uD83C\uDFD7\uFE0F Involved"};Fm={bug:"\uD83C\uDFAF Correctness",race:"\uD83E\uDE7A Concurrency","edge-case":"\uD83C\uDFAF Correctness","resource-leak":"\uD83E\uDE7A Stability",invariant:"\uD83D\uDDC4\uFE0F Data integrity",architecture:"\uD83D\uDCD0 Architecture",duplication:"\uD83D\uDCD0 Architecture",performance:"\uD83D\uDE80 Performance",security:"\uD83D\uDD12 Security",other:"\u26AA Other"}});function Ra(e){let t=[...e.findings.map((o)=>o.anchor),...e.overCapFindings.map((o)=>o.anchor),...e.stops.flatMap((o)=>o.locations)],n=(o)=>t.filter((a)=>a.kind===o).length,r=[...new Set(t.flatMap((o)=>o.kind==="file"&&o.reason?[o.reason]:[]))],s=`${n("file")} file${r.length?` (${r.join(", ")})`:""}`;return`${n("line")} line, ${n("nearby")} nearby, ${s}`}function Ru(e,t){let n=[];for(let r of e.hunks){let s=t==="additions"?r.additionStart:r.deletionStart,o=t==="additions"?r.additionCount:r.deletionCount;if(o>0)n.push({start:s,end:s+o-1,hunk:r})}return n}function $u(e,t,n,r){let s=t==="additions"?e.additionLines:e.deletionLines,o=t==="additions"?n.hunk.additionLineIndex:n.hunk.deletionLineIndex;return s[o+(r-n.start)]?.replace(/\r?\n$/,"")}function bs(e,t,n){return{file:e,side:"additions",kind:"file",line:0,cited:t,...n?{reason:n}:{}}}function Su(e,t,n,r,s,o){let a=Ru(e,n).find((u)=>r>=u.start&&r<=u.end);if(!a)return null;let l=s!==void 0&&s>r?Math.min(s,a.end):void 0,c=$u(e,n,a,r);return{file:t,side:n,kind:"line",line:r,...l!==void 0&&l>r?{endLine:l}:{},cited:o,...c!==void 0?{text:c}:{}}}function $a(e,t,n,r,s={}){let o=n!==void 0&&Number.isFinite(n)&&n>0,a=o?r!==void 0&&r>0?Math.min(n,r):n:0,l=o&&r!==void 0&&r>0?Math.max(n,r):void 0,c={line:a,...l!==void 0&&l!==a?{endLine:l}:{}};if(!e)return bs(t,c,"not-in-diff");if(!o)return bs(t,c,"no-line");if(e.type==="deleted")return(s.deletionsFallback?Su(e,t,"deletions",a,l,c):null)??bs(t,c,"deleted-file");let u=Ru(e,"additions");if(!u.length)return bs(t,c,"no-hunks");let d=Su(e,t,"additions",a,l,c)??(s.deletionsFallback?Su(e,t,"deletions",a,l,c):null);if(d)return d;let f;for(let p of u){let h=a<p.start?p.start:p.end,g=Math.abs(h-a);if(!f||g<f.distance)f={line:h,range:p,distance:g}}if(f&&f.distance<=20){let p=$u(e,"additions",f.range,f.line);return{file:t,side:"additions",kind:"nearby",line:f.line,cited:c,...p!==void 0?{text:p}:{}}}return bs(t,c,"far-from-diff")}function vg(e,t){for(let n of[e,t]){let r=n?.trim().replace(/\(\)$/,"");if(r&&/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(r))return r.slice(r.lastIndexOf(".")+1)}return}function xg(e,t,n,r={}){if(!e||!n)return t;let s=new RegExp(`(?<![\\w$])${bg(n)}(?![\\w$])`);if(t.kind!=="file"&&t.text!==void 0&&s.test(t.text))return t;let o=bg(n),a=new RegExp([`\\b(?:function\\*?|class|interface|type|enum|namespace|def|fn|struct|trait|const|let|var)\\s+${o}(?![\\w$])`,`^\\s*(?:(?:export|default|public|private|protected|static|readonly|async|override|get|set|pub)\\s+)*\\*?${o}\\s*(?:<[^>]*>)?\\s*[(=:]`].join("|")),l=e.type==="deleted"?["deletions"]:r.deletionsFallback?["additions","deletions"]:["additions"],c=t.cited.line;for(let u of l){let d=[];for(let g of Ru(e,u))for(let w=g.start;w<=g.end;w++){let b=$u(e,u,g,w);if(b===void 0||!s.test(b))continue;d.push({line:w,text:b,definition:a.test(b),distance:c>0?Math.abs(w-c):w})}if(!d.length)continue;let f=(g,w)=>g.distance-w.distance,h=(c>0?d.filter((g)=>g.distance<=NE).sort(f)[0]:void 0)??d.filter((g)=>g.definition).sort(f)[0]??d.sort(f)[0];if(!h)continue;return{file:t.file,side:u,kind:"line",line:h.line,cited:t.cited,text:h.text}}return t}var NE=3,bg=(e)=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function cl(e){if(typeof e!=="object"||e===null)return;let t=e;if(typeof t.input_tokens!=="number"&&typeof t.output_tokens!=="number")return;let n=t.first_step;return{input:Rn(t.input_tokens),output:Rn(t.output_tokens),reasoning:Rn(t.reasoning_tokens),cacheRead:Rn(t.cache_read_input_tokens),cacheWrite:Rn(t.cache_creation_input_tokens),...typeof n==="object"&&n!==null?{firstStep:{input:Rn(n.input_tokens),cacheRead:Rn(n.cache_read_input_tokens),cacheWrite:Rn(n.cache_creation_input_tokens)}}:{}}}function Wd(e){if(typeof e!=="object"||e===null)return;let t=e;if(t.cached===!0)return;let n=cl(t.usage),r=Rn(t.costUsd);if(!n&&r===0)return;return{costUsd:r,wallMs:Rn(t.wallMs),...n?{usage:n}:{}}}function zd(e){let t=Wd(e?.merge),n=Wd(e?.walk),r=Wd(e?.intentDraft);if(!t&&!n&&!r)return;return{...t?{coordinator:t}:{},...n?{walkthrough:n}:{},...r?{intent:r}:{}}}function Xy(e,t){if(typeof t!=="object"||t===null)return e;let n=t,r=Array.isArray(n.sliceRuns)?n.sliceRuns:[],s=e.meta.slices.map((a,l)=>{if(a.usage)return a;let c=r[l];if(!c||c.unit!==a.unit||c.part!==a.part)return a;let u=cl(c.usage);return u?{...a,usage:u}:a}),o=e.meta.stages??zd(n);return{...e,meta:{...e.meta,slices:s,...o?{stages:o}:{}}}}function Yy(e){return e.meta.slices.some((t)=>t.usage)||Object.values(e.meta.stages??{}).some((t)=>t?.usage)}function dl(e){let t=e.input+e.cacheRead+e.cacheWrite;return t>0?e.cacheRead/t:null}function zy(e,t){e.input+=t.input,e.output+=t.output,e.reasoning+=t.reasoning,e.cacheRead+=t.cacheRead,e.cacheWrite+=t.cacheWrite,e.calls++}function Ys(e,t=ul()){for(let n of e.meta.slices){if(!n.usage)continue;zy(t,n.usage);let r=n.usage.firstStep?dl(n.usage.firstStep):null;if(r!==null)t.firstStepShares.push(r)}for(let n of Object.values(e.meta.stages??{}))if(n?.usage)zy(t,n.usage);return t}function WO(e){let t=[...e].sort((s,o)=>s-o),n=Math.floor(t.length/2),r=t[n];if(r===void 0)return null;return t.length%2?r:((t[n-1]??r)+r)/2}function Zs(e){if(!e.calls)return;let t=dl(e),n=WO(e.firstStepShares),r=e.input+e.cacheRead+e.cacheWrite;return`${Vd(r)} prompt${t===null?"":` (${Jy(t)} from cache)`}, ${Vd(e.output)} output`+(e.reasoning?`, ${Vd(e.reasoning)} reasoning`:"")+(n===null?"":`; first requests ${Jy(n)} from cache (median of ${e.firstStepShares.length})`)}var Rn=(e)=>typeof e==="number"&&Number.isFinite(e)?e:0,ul=()=>({input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,calls:0,firstStepShares:[]}),Vd=(e)=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1000?`${Math.round(e/1000)}K`:String(e),Jy=(e)=>`${Math.round(e*100)}%`;function jn(e){return e.replace(/-\d+$/,"")}function db(e){return e.findings.map((t,n)=>({id:n+1,file:t.file,...t.anchor.cited.line?{line:t.anchor.cited.line}:{},author:"diffloupe",body:`**${t.title}** ${t.impact??t.explanation}`,resolved:!1,mine:!0,fingerprint:jn(t.id)}))}function fb(e){let t=new Map,n,r;for(let s of e.split(`
90
+ `)){let o=s.match(/^--- (?:a\/(.+)|\/dev\/null)$/);if(o){r=o[1];continue}let a=s.match(/^\+\+\+ (?:b\/(.+)|\/dev\/null)$/);if(a){let c=a[1]??r;if(n=c?[]:void 0,c&&n)t.set(c,n);continue}let l=s.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(l&&n)n.push({oldStart:Number(l[1]),oldCount:l[2]===void 0?1:Number(l[2]),newStart:Number(l[3]),newCount:l[4]===void 0?1:Number(l[4])})}return t}function ef(e,t){let n=0;for(let r of e){if(r.oldCount===0){if(t<=r.oldStart)break;n+=r.newCount;continue}if(t<r.oldStart)break;if(t<r.oldStart+r.oldCount)return Math.max(1,r.newStart);n+=r.newCount-r.oldCount}return t+n}var ZV,Jb,hf,Xb,Yb,LI,QV,e3;var Zb=He(()=>{ZV=(()=>{try{return!0}catch{return!1}})(),Jb=/(?=^From [a-f0-9]+ .+$)/m,hf=/(?=^diff --git)/gm,Xb=/^(---|\+\+\+)\s+([^\t\r\n]+)/,Yb=/^index ([0-9a-f]+)\.\.([0-9a-f]+)(?: (\d+))?$/i,LI={hunkLineCount:50,lineHeight:20,diffHeaderHeight:44,spacing:8},QV={...LI,hunkLineCount:1},e3=Object.freeze({fromStart:0,fromEnd:0})});function ao(e,t){return e-(t===0?0:1)}function mf(e,t){return ao(e,t)+t}var Qb=()=>{};function gf(e,...t){return`ck1:${JSON.stringify([e,...t])}`}var ev=()=>{};function _f(e){let t=e.length;if(e.charCodeAt(t-1)===10){if(t--,e.charCodeAt(t-1)===13)t--}return e.slice(0,t)}var tv=()=>{};function nv(){if(Bi.length!==1024)Bi=new Uint8Array(1024)}function Be(e){if(e.length===0)return e;if(BI.test(e))return JSON.parse(JSON.stringify(e));let t=e.length*3;if(Bi.length<t)Bi=new Uint8Array(t);let{written:n}=jI.encodeInto(e,Bi);return UI.decode(Bi.subarray(0,n))}var jI,UI,BI,Bi;var rv=He(()=>{jI=new TextEncoder,UI=new TextDecoder("utf-8",{ignoreBOM:!0}),BI=/[\uD800-\uDFFF]/,Bi=new Uint8Array(1024)});function iv(e){if(e[0]!=='"')return;let t="",n=1;while(n<e.length){let r=e[n];if(r==='"')return{fileName:t,rawLength:n+1};if(r!=="\\"){t+=r,n++;continue}let s=HI[e[n+1]];if(s!=null){t+=s,n+=2;continue}let o=[];do{let a=KI(e,n+1);if(a==null)return;o.push(a),n+=4}while(e[n]==="\\"&&e[n+1]>="0"&&e[n+1]<="7");t+=qI.decode(new Uint8Array(o))}}function KI(e,t){let n=e.charCodeAt(t)-48,r=e.charCodeAt(t+1)-48,s=e.charCodeAt(t+2)-48;if(n>=0&&n<=3&&r>=0&&r<=7&&s>=0&&s<=7)return n*64+r*8+s}var qI,HI;var sv=He(()=>{qI=new TextDecoder("utf-8",{ignoreBOM:!0}),HI={'"':'"',"\\":"\\",a:"\x07",b:"\b",t:"\t",n:`
91
+ `,v:"\v",f:"\f",r:"\r"}});function av(e){for(let t of e.hunks)for(let n=0;n<t.hunkContent.length;n++){let r=t.hunkContent[n];if(r.type!=="change")continue;let s=GI(e,r);if(s!=null)t.hunkContent.splice(n,1,...s),n+=s.length-1}}function GI(e,t){let{deletions:n,additions:r,deletionLineIndex:s,additionLineIndex:o}=t,a=Math.min(n,r),l=Math.abs(r-n);if(a===0||l===0||a*(l+1)>4096)return null;let c=[];for(let w=0;w<n;w++)c.push(ov(e.deletionLines[s+w]??""));let u=[];for(let w=0;w<r;w++)u.push(ov(e.additionLines[o+w]??""));let d=r>n,f=0,p=-1;for(let w=0;w<=l;w++){let b=0;for(let x=0;x<a;x++)b+=VI(c[x+(d?0:w)],u[x+(d?w:0)]);if(w===0)p=b+a*0.5;else if(b>p)p=b,f=w}if(f===0)return null;let h=[],g=(w,b,x,S)=>{if(w>0||b>0)h.push({type:"change",deletions:w,additions:b,deletionLineIndex:x,additionLineIndex:S})};if(d)g(0,f,s,o),g(a,a,s,o+f),g(0,r-a-f,s+a,o+f+a);else g(f,0,s,o),g(a,a,s+f,o),g(n-a-f,0,s+f+a,o+a);return h}function ov(e){return e.replace(WI,"")}function VI(e,t){if(e===t)return 1;let n=Math.max(e.length,t.length),r=Math.min(e.length,t.length);if(r===0)return 0;let s=0;while(s<r&&e[s]===t[s])s++;let o=0;while(o<r-s&&e[e.length-1-o]===t[t.length-1-o])o++;return(s+o)/n}var WI;var lv=He(()=>{WI=/\s+/g});function JI(e,t,n=!1,r){let s=iP(e),o=s?ZI(e):QI(e),a,l=[];for(let c of o){if(s&&!hf.test(c)){if(a==null)a=Be(c);else if(n)throw Error("parsePatchContent: unknown file blob");else console.error("parsePatchContent: unknown file blob:",c);continue}else if(!s&&!eP(c)){if(a==null)a=Be(c);else if(n)throw Error("parsePatchContent: unknown file blob");else console.error("parsePatchContent: unknown file blob:",c);continue}let u=XI(c,{cacheKey:t!=null?r==null?gf("patch-file",t,String(l.length)):gf("patch-file",t,String(r),String(l.length)):void 0,isGitDiff:s,throwOnError:n});if(u!=null)l.push(u)}return{patchMetadata:a,files:l}}function XI(e,{cacheKey:t,isGitDiff:n=hf.test(e),oldFile:r,newFile:s,throwOnError:o=!1}={}){let a=0,l=gv(e,"@@ "),c,u=r==null||s==null,d=0,f=0;for(let p of l){let h=pv(p),g=h[0];if(g==null){if(o)throw Error("parsePatchContent: invalid hunk");else console.error("parsePatchContent: invalid hunk",p);continue}let w=mv(g),b=0,x=0;if(w==null||c==null){if(c!=null){if(o)throw Error("parsePatchContent: Invalid hunk");else console.error("parsePatchContent: Invalid hunk",p);continue}if(c={name:"",type:"change",hunks:[],splitLineCount:0,unifiedLineCount:0,isPartial:u,additionLines:!u&&r!=null&&s!=null?cv(s.contents):[],deletionLines:!u&&r!=null&&s!=null?cv(r.contents):[],cacheKey:fv(t)},c.additionLines.length===1&&s?.contents==="")c.additionLines.length=0;if(c.deletionLines.length===1&&r?.contents==="")c.deletionLines.length=0;for(let O of h){if(O.startsWith("diff --git")){let I=O.trim().match(zI);if(I==null){if(o)throw Error("parsePatchContent: invalid git diff header");else console.error("parsePatchContent: invalid git diff header",O);continue}let j=lo(I[1],!0),H=lo(I[2],!0);if(c.name=Be(H),j!==H)c.prevName=Be(j);continue}let U=O.startsWith("---")||O.startsWith("+++")?O.match(Xb):null;if(U!=null){let[,I,j]=U,H=lo(j,n);if(I==="---"&&H!=="/dev/null"){let ve=Be(H);c.prevName=ve,c.name=ve}else if(I==="+++"&&H!=="/dev/null")c.name=Be(H)}else if(n){if(O.startsWith("new mode "))c.mode=Be(O.slice(8).trim());if(O.startsWith("old mode "))c.prevMode=Be(O.slice(8).trim());if(O.startsWith("new file mode"))c.type="new",c.mode=Be(O.slice(13).trim());if(O.startsWith("deleted file mode"))c.type="deleted",c.mode=Be(O.slice(17).trim());if(O.startsWith("similarity index"))if(O.startsWith("similarity index 100%"))c.type="rename-pure";else c.type="rename-changed";if(O.startsWith("index ")){let[,I,j,H]=O.trim().match(Yb)??[];if(I!=null)c.prevObjectId=Be(I);if(j!=null)c.newObjectId=Be(j);if(H!=null)c.mode=Be(H)}if(O.startsWith("rename from ")||O.startsWith("copy from "))c.prevName=Be(lo(O.slice(O.startsWith("rename")?12:10)));if(O.startsWith("rename to ")||O.startsWith("copy to "))c.name=Be(lo(O.slice(O.startsWith("rename")?10:8)))}}continue}let S,P;while(h.length>0&&(h[h.length-1]===`
92
92
  `||h[h.length-1]==="\r"||h[h.length-1]===`\r
93
- `||h[h.length-1]===""))h.pop();let{additionStart:M,deletionStart:k}=w;d=u?d:k-1,f=u?f:M-1;let E={collapsedBefore:0,splitLineCount:0,splitLineStart:0,unifiedLineCount:0,unifiedLineStart:0,additionCount:w.additionCount,additionStart:M,additionLines:b,deletionCount:w.deletionCount,deletionStart:k,deletionLines:x,deletionLineIndex:d,additionLineIndex:f,hunkContent:[],hunkContext:qb(w.hunkContext),hunkSpecs:Ue(g),noEOFCRAdditions:!1,noEOFCRDeletions:!1},D=0,L=0;for(let O=1;O<h.length;O++){let U=h[O];if(D>=E.additionCount&&L>=E.deletionCount&&!U.startsWith("\\")){if(!(mI(U)&&!gI(U)))break;if(o)throw Error("parsePatchContent: hunk has more lines than expected")}let I=U[0];if(I!=="+"&&I!=="-"&&I!==" "&&I!=="\\"){if(o)throw Error("parsePatchContent: invalid hunk line");console.error(`parseLineType: Invalid firstChar: "${I}", full line: "${U}"`),console.error("processFile: invalid rawLine:",U);continue}let j=yI(I);if(j==="addition"){if(o&&D>=E.additionCount)throw Error("parsePatchContent: hunk has too many addition lines");let H=of(U);if(R==null||R.type!=="change")R=af("change",d,f),E.hunkContent.push(R);if(f++,D++,u)c.additionLines.push(H);R.additions++,b++,P="addition"}else if(j==="deletion"){if(o&&L>=E.deletionCount)throw Error("parsePatchContent: hunk has too many deletion lines");let H=of(U);if(R==null||R.type!=="change")R=af("change",d,f),E.hunkContent.push(R);if(d++,L++,u)c.deletionLines.push(H);R.deletions++,x++,P="deletion"}else if(j==="context"){if(o&&(L>=E.deletionCount||D>=E.additionCount))throw Error("parsePatchContent: hunk has too many context lines");let H=of(U);if(R==null||R.type!=="context")R=af("context",d,f),E.hunkContent.push(R);if(f++,d++,D++,L++,u)c.deletionLines.push(H),c.additionLines.push(H);R.lines++,P="context"}else if(j==="metadata"&&R!=null){if(R.type==="context")E.noEOFCRAdditions=!0,E.noEOFCRDeletions=!0;else if(P==="deletion")E.noEOFCRDeletions=!0;else if(P==="addition")E.noEOFCRAdditions=!0;if(u&&(P==="addition"||P==="context")){let H=c.additionLines.length-1;if(H>=0)c.additionLines[H]=sf(c.additionLines[H])}if(u&&(P==="deletion"||P==="context")){let H=c.deletionLines.length-1;if(H>=0)c.deletionLines[H]=sf(c.deletionLines[H])}}}if(D!==E.additionCount||L!==E.deletionCount){if(o)throw Error("parsePatchContent: hunk line count mismatch");console.error(`parsePatchContent: hunk line count mismatch: "${g.trimEnd()}", declared old/new ${E.deletionCount}/${E.additionCount}, parsed old/new ${L}/${D}`);let O=Qs(E.additionStart,E.additionCount)+(D===0?0:1),U=Qs(E.deletionStart,E.deletionCount)+(L===0?0:1);if(!u){let I=O-E.additionStart,j=U-E.deletionStart;E.additionLineIndex+=I,E.deletionLineIndex+=j;for(let H of E.hunkContent)H.additionLineIndex+=I,H.deletionLineIndex+=j}E.additionStart=O,E.deletionStart=U,E.additionCount=D,E.deletionCount=L}E.additionLines=b,E.deletionLines=x,E.collapsedBefore=Math.max(Qs(E.additionStart,E.additionCount)-a,0),c.hunks.push(E),a=nf(E.additionStart,E.additionCount);for(let O of E.hunkContent)if(O.type==="context")E.splitLineCount+=O.lines,E.unifiedLineCount+=O.lines;else E.splitLineCount+=Math.max(O.additions,O.deletions),E.unifiedLineCount+=O.deletions+O.additions;E.splitLineStart=c.splitLineCount+E.collapsedBefore,E.unifiedLineStart=c.unifiedLineCount+E.collapsedBefore,c.splitLineCount+=E.collapsedBefore+E.splitLineCount,c.unifiedLineCount+=E.collapsedBefore+E.unifiedLineCount}if(c==null)return;if(o&&u&&!n&&c.hunks.length===0)throw Error("parsePatchContent: unified file has no hunks");if(c.hunks.length>0&&!u&&c.additionLines.length>0&&c.deletionLines.length>0){let p=c.hunks[c.hunks.length-1],h=nf(p.additionStart,p.additionCount),g=c.additionLines.length,w=Math.max(g-h,0);c.splitLineCount+=w,c.unifiedLineCount+=w}if(!n){if(c.prevName!=null&&c.name!==c.prevName)if(c.hunks.length>0)c.type="rename-changed";else c.type="rename-pure";else if((r==null||r.contents==="")&&s!=null&&s.contents!=="")c.type="new";else if(r!=null&&r.contents!==""&&(s==null||s.contents===""))c.type="deleted"}if(c.type!=="rename-pure"&&c.type!=="rename-changed")c.prevName=void 0;return Db(c),c}function cf(e,t,n=!1){let r=[],s=dI(e)?e.split($b):[e];for(let o of s)try{r.push(cI(o,t,n,t!=null?r.length:void 0))}catch(a){if(n)throw a;else console.error(a)}finally{Pb()}return r}function eo(e,t=!1){let n=e.trim(),r=n.startsWith('"')?Tb(n)?.fileName??n:n;return t&&(r.startsWith("a/")||r.startsWith("b/"))?r.slice(2):r}function dI(e){return e.startsWith("From ")||e.includes(`
94
- From `)}function jb(e){let t=Hb(e);for(let n=0;n<t.length;n++)t[n]=Ue(t[n]);return t}function Hb(e){if(e.length===0)return[""];let t=[],n=0;for(;;){let r=e.indexOf(`
95
- `,n);if(r===-1)break;t.push(e.slice(n,r+1)),n=r+1}if(n<e.length)t.push(e.slice(n));return t}function fI(e){return Gb(e,"diff --git")}function pI(e){if(e.length===0)return[""];let t=[],n=0,r=0,s=0,o=0,a=!1;while(r<e.length){let l=lf(e,r);if(s<=0&&o<=0){if(Kb(e,r)){if(r>n)t.push(e.slice(n,r));n=r,a=!0,r=lf(e,l);continue}if(a&&e.startsWith("@@ -",r)){let u=Wb(e.slice(r,l));if(u!=null)s=u.deletionCount,o=u.additionCount}r=l;continue}let c=e[r];if(c==="\\"){r=l;continue}if(c===" ")s=Math.max(s-1,0),o=Math.max(o-1,0);else if(c==="-")s=Math.max(s-1,0);else if(c==="+")o=Math.max(o-1,0);r=l}return t.push(e.slice(n)),t}function hI(e){return Kb(e,0)}function Kb(e,t){let n=lf(e,t);return Ub(e,t,"---")&&Ub(e,n,"+++")}function Ub(e,t,n){if(!e.startsWith(n,t))return!1;let r=e[t+n.length];if(r!==" "&&r!=="\t")return!1;for(let s=t+n.length+1;s<e.length;s++){let o=e[s];if(o===`
96
- `||o==="\r")break;if(o!==" "&&o!=="\t")return!0}return!1}function lf(e,t){let n=e.indexOf(`
97
- `,t);return n===-1?e.length:n+1}function mI(e){let t=e[0];return t==="+"||t==="-"||t===" "}function gI(e){if(!e.startsWith("--"))return!1;for(let t=2;t<e.length;t++){let n=e[t];if(n!==" "&&n!=="\t"&&n!==`
98
- `&&n!=="\r")return!1}return!0}function Wb(e){if(!e.startsWith("@@ -"))return;let t=4,n=dl(e,t);if(n==null)return;let r=n.value;t=n.endIndex;let s=1;if(e[t]===","){let d=dl(e,t+1);if(d==null)return;s=d.value,t=d.endIndex}if(e[t]!==" "||e[t+1]!=="+")return;t+=2;let o=dl(e,t);if(o==null)return;let a=o.value;t=o.endIndex;let l=1;if(e[t]===","){let d=dl(e,t+1);if(d==null)return;l=d.value,t=d.endIndex}if(e[t]!==" "||e[t+1]!=="@"||e[t+2]!=="@")return;let c,u=t+3;if(e[u]===" ")c=_I(e.slice(u+1));return{additionCount:l,additionStart:a,deletionCount:s,deletionStart:r,hunkContext:c}}function dl(e,t){let n=t,r=0;for(;n<e.length;n++){let s=e.charCodeAt(n)-48;if(s<0||s>9)break;r=r*10+s}if(n===t)return;return{value:r,endIndex:n}}function _I(e){if(e.endsWith(`\r
93
+ `||h[h.length-1]===""))h.pop();let{additionStart:M,deletionStart:k}=w;d=u?d:k-1,f=u?f:M-1;let E={collapsedBefore:0,splitLineCount:0,splitLineStart:0,unifiedLineCount:0,unifiedLineStart:0,additionCount:w.additionCount,additionStart:M,additionLines:b,deletionCount:w.deletionCount,deletionStart:k,deletionLines:x,deletionLineIndex:d,additionLineIndex:f,hunkContent:[],hunkContext:fv(w.hunkContext),hunkSpecs:Be(g),noEOFCRAdditions:!1,noEOFCRDeletions:!1},F=0,L=0;for(let O=1;O<h.length;O++){let U=h[O];if(F>=E.additionCount&&L>=E.deletionCount&&!U.startsWith("\\")){if(!(tP(U)&&!nP(U)))break;if(o)throw Error("parsePatchContent: hunk has more lines than expected")}let I=U[0];if(I!=="+"&&I!=="-"&&I!==" "&&I!=="\\"){if(o)throw Error("parsePatchContent: invalid hunk line");console.error(`parseLineType: Invalid firstChar: "${I}", full line: "${U}"`),console.error("processFile: invalid rawLine:",U);continue}let j=sP(I);if(j==="addition"){if(o&&F>=E.additionCount)throw Error("parsePatchContent: hunk has too many addition lines");let H=wf(U);if(S==null||S.type!=="change")S=yf("change",d,f),E.hunkContent.push(S);if(f++,F++,u)c.additionLines.push(H);S.additions++,b++,P="addition"}else if(j==="deletion"){if(o&&L>=E.deletionCount)throw Error("parsePatchContent: hunk has too many deletion lines");let H=wf(U);if(S==null||S.type!=="change")S=yf("change",d,f),E.hunkContent.push(S);if(d++,L++,u)c.deletionLines.push(H);S.deletions++,x++,P="deletion"}else if(j==="context"){if(o&&(L>=E.deletionCount||F>=E.additionCount))throw Error("parsePatchContent: hunk has too many context lines");let H=wf(U);if(S==null||S.type!=="context")S=yf("context",d,f),E.hunkContent.push(S);if(f++,d++,F++,L++,u)c.deletionLines.push(H),c.additionLines.push(H);S.lines++,P="context"}else if(j==="metadata"&&S!=null){if(S.type==="context")E.noEOFCRAdditions=!0,E.noEOFCRDeletions=!0;else if(P==="deletion")E.noEOFCRDeletions=!0;else if(P==="addition")E.noEOFCRAdditions=!0;if(u&&(P==="addition"||P==="context")){let H=c.additionLines.length-1;if(H>=0)c.additionLines[H]=_f(c.additionLines[H])}if(u&&(P==="deletion"||P==="context")){let H=c.deletionLines.length-1;if(H>=0)c.deletionLines[H]=_f(c.deletionLines[H])}}}if(F!==E.additionCount||L!==E.deletionCount){if(o)throw Error("parsePatchContent: hunk line count mismatch");console.error(`parsePatchContent: hunk line count mismatch: "${g.trimEnd()}", declared old/new ${E.deletionCount}/${E.additionCount}, parsed old/new ${L}/${F}`);let O=ao(E.additionStart,E.additionCount)+(F===0?0:1),U=ao(E.deletionStart,E.deletionCount)+(L===0?0:1);if(!u){let I=O-E.additionStart,j=U-E.deletionStart;E.additionLineIndex+=I,E.deletionLineIndex+=j;for(let H of E.hunkContent)H.additionLineIndex+=I,H.deletionLineIndex+=j}E.additionStart=O,E.deletionStart=U,E.additionCount=F,E.deletionCount=L}E.additionLines=b,E.deletionLines=x,E.collapsedBefore=Math.max(ao(E.additionStart,E.additionCount)-a,0),c.hunks.push(E),a=mf(E.additionStart,E.additionCount);for(let O of E.hunkContent)if(O.type==="context")E.splitLineCount+=O.lines,E.unifiedLineCount+=O.lines;else E.splitLineCount+=Math.max(O.additions,O.deletions),E.unifiedLineCount+=O.deletions+O.additions;E.splitLineStart=c.splitLineCount+E.collapsedBefore,E.unifiedLineStart=c.unifiedLineCount+E.collapsedBefore,c.splitLineCount+=E.collapsedBefore+E.splitLineCount,c.unifiedLineCount+=E.collapsedBefore+E.unifiedLineCount}if(c==null)return;if(o&&u&&!n&&c.hunks.length===0)throw Error("parsePatchContent: unified file has no hunks");if(c.hunks.length>0&&!u&&c.additionLines.length>0&&c.deletionLines.length>0){let p=c.hunks[c.hunks.length-1],h=mf(p.additionStart,p.additionCount),g=c.additionLines.length,w=Math.max(g-h,0);c.splitLineCount+=w,c.unifiedLineCount+=w}if(!n){if(c.prevName!=null&&c.name!==c.prevName)if(c.hunks.length>0)c.type="rename-changed";else c.type="rename-pure";else if((r==null||r.contents==="")&&s!=null&&s.contents!=="")c.type="new";else if(r!=null&&r.contents!==""&&(s==null||s.contents===""))c.type="deleted"}if(c.type!=="rename-pure"&&c.type!=="rename-changed")c.prevName=void 0;return av(c),c}function vf(e,t,n=!1){let r=[],s=YI(e)?e.split(Jb):[e];for(let o of s)try{r.push(JI(o,t,n,t!=null?r.length:void 0))}catch(a){if(n)throw a;else console.error(a)}finally{nv()}return r}function lo(e,t=!1){let n=e.trim(),r=n.startsWith('"')?iv(n)?.fileName??n:n;return t&&(r.startsWith("a/")||r.startsWith("b/"))?r.slice(2):r}function YI(e){return e.startsWith("From ")||e.includes(`
94
+ From `)}function cv(e){let t=pv(e);for(let n=0;n<t.length;n++)t[n]=Be(t[n]);return t}function pv(e){if(e.length===0)return[""];let t=[],n=0;for(;;){let r=e.indexOf(`
95
+ `,n);if(r===-1)break;t.push(e.slice(n,r+1)),n=r+1}if(n<e.length)t.push(e.slice(n));return t}function ZI(e){return gv(e,"diff --git")}function QI(e){if(e.length===0)return[""];let t=[],n=0,r=0,s=0,o=0,a=!1;while(r<e.length){let l=bf(e,r);if(s<=0&&o<=0){if(hv(e,r)){if(r>n)t.push(e.slice(n,r));n=r,a=!0,r=bf(e,l);continue}if(a&&e.startsWith("@@ -",r)){let u=mv(e.slice(r,l));if(u!=null)s=u.deletionCount,o=u.additionCount}r=l;continue}let c=e[r];if(c==="\\"){r=l;continue}if(c===" ")s=Math.max(s-1,0),o=Math.max(o-1,0);else if(c==="-")s=Math.max(s-1,0);else if(c==="+")o=Math.max(o-1,0);r=l}return t.push(e.slice(n)),t}function eP(e){return hv(e,0)}function hv(e,t){let n=bf(e,t);return uv(e,t,"---")&&uv(e,n,"+++")}function uv(e,t,n){if(!e.startsWith(n,t))return!1;let r=e[t+n.length];if(r!==" "&&r!=="\t")return!1;for(let s=t+n.length+1;s<e.length;s++){let o=e[s];if(o===`
96
+ `||o==="\r")break;if(o!==" "&&o!=="\t")return!0}return!1}function bf(e,t){let n=e.indexOf(`
97
+ `,t);return n===-1?e.length:n+1}function tP(e){let t=e[0];return t==="+"||t==="-"||t===" "}function nP(e){if(!e.startsWith("--"))return!1;for(let t=2;t<e.length;t++){let n=e[t];if(n!==" "&&n!=="\t"&&n!==`
98
+ `&&n!=="\r")return!1}return!0}function mv(e){if(!e.startsWith("@@ -"))return;let t=4,n=xl(e,t);if(n==null)return;let r=n.value;t=n.endIndex;let s=1;if(e[t]===","){let d=xl(e,t+1);if(d==null)return;s=d.value,t=d.endIndex}if(e[t]!==" "||e[t+1]!=="+")return;t+=2;let o=xl(e,t);if(o==null)return;let a=o.value;t=o.endIndex;let l=1;if(e[t]===","){let d=xl(e,t+1);if(d==null)return;l=d.value,t=d.endIndex}if(e[t]!==" "||e[t+1]!=="@"||e[t+2]!=="@")return;let c,u=t+3;if(e[u]===" ")c=rP(e.slice(u+1));return{additionCount:l,additionStart:a,deletionCount:s,deletionStart:r,hunkContext:c}}function xl(e,t){let n=t,r=0;for(;n<e.length;n++){let s=e.charCodeAt(n)-48;if(s<0||s>9)break;r=r*10+s}if(n===t)return;return{value:r,endIndex:n}}function rP(e){if(e.endsWith(`\r
99
99
  `))return e.slice(0,-2);if(e.endsWith(`
100
- `))return e.slice(0,-1);return e}function wI(e){return e.startsWith("diff --git")||e.includes(`
101
- diff --git`)}function Gb(e,t){if(e.length===0)return[""];let n=`
102
- ${t}`,r=e.startsWith(t)?0:Bb(e,n,0);if(r===-1)return[e];let s=[];if(r>0)s.push(e.slice(0,r));let o=r;for(;;){let a=Bb(e,n,o+1);if(a===-1)break;s.push(e.slice(o,a)),o=a}return s.push(e.slice(o)),s}function Bb(e,t,n){let r=e.indexOf(t,n);return r===-1?-1:r+1}function qb(e){return e==null?e:Ue(e)}function yI(e){return e===" "?"context":e==="\\"?"metadata":e==="+"?"addition":"deletion"}function of(e){let t=e.slice(1);return Ue(t===""?`
103
- `:t)}function af(e,t,n){if(e==="change")return{type:"change",additions:0,deletions:0,additionLineIndex:n,deletionLineIndex:t};return{type:"context",lines:0,additionLineIndex:n,deletionLineIndex:t}}var lI;var Vb=qe(()=>{Ab();Cb();Ob();Ib();Mb();Fb();Lb();lI=/^diff --git ("a\/(?:[^"\\]|\\.)*"|a\/.+?) ("b\/(?:[^"\\]|\\.)*"|b\/.+?)$/});var zb=qe(()=>{Vb()});function Jb(e,[t,n]){return e.some((r)=>{let s=r.oldStart+Math.max(r.oldCount,1)-1;return r.oldStart<=n&&t<=s})}function Xb(e,t){return e.flatMap((n)=>{let{line:r,endLine:s}=n.anchor.cited;if(n.anchor.side!=="additions"||r<1)return[];let o=[r,Math.max(s??r,r)],a=r>35?-35:35,l=t.get(n.file)??[];return[{id:n.id,acted:Jb(l,o),control:Jb(l,[o[0]+a,o[1]+a])}]})}function SI(e){let t=new Set;for(let n of e.matchAll(/^Binary files (?:a\/(.+?)|\/dev\/null) and (?:b\/(.+?)|\/dev\/null) differ$/gm)){let r=n[2]??n[1];if(r)t.add(r)}return t}function Qb(e){return cf(e).flatMap((t)=>t.files)}function ev(e,t,n){let r=SI(t),s=new Map;for(let o of["skip","docs","code"])for(let a of n[o])s.set(a,o);return e.map((o)=>{let a=0,l=0;for(let c of o.hunks)a+=c.additionLines,l+=c.deletionLines;return{path:o.name,...o.prevName&&o.prevName!==o.name?{previousPath:o.prevName}:{},status:RI[o.type],additions:a,deletions:l,isBinary:r.has(o.name),...o.newObjectId?{blob:o.newObjectId}:{},groupId:"",classification:s.get(o.name)??ai(o.name),surface:ot(o.name)}})}function Yb(e){let t=e.match(/^(.+?):(\d+)(?:-\d+)?$/);return t?.[1]&&t[2]?{file:t[1],line:Number(t[2])}:{file:e}}function Zb(e,t,n){return{id:t,file:e.file,anchor:_a(n,e.file,e.line,e.end_line),severity:e.severity,category:e.category,title:e.title,explanation:e.explanation,evidence:e.evidence,...e.impact?{impact:e.impact}:{},confidence:e.confidence,...e.effort?{effort:e.effort}:{},...e.suggestion?{suggestion:e.suggestion}:{},...e.suggested_code?{suggestedCode:e.suggested_code}:{},...e.cross_file_refs?.length?{crossFileRefs:e.cross_file_refs.map(Yb)}:{},...e.also_at?.length?{alsoAt:e.also_at.map(Yb)}:{},...e.repeat_of!==void 0?{repeatOf:e.repeat_of}:{},surface:ot(e.file),...e.preexisting?{preexisting:!0}:{}}}function to(e){return[...new Set(e)]}function $I(e,t){let n=e.split("/").slice(0,-1),r=t.split("/").slice(0,-1),s=0;while(s<n.length&&s<r.length&&n[s]===r[s])s++;return s}function kI(e,t){let n=new Map;for(let r of t){let s=Number(r.chapterId.slice(1))-1;for(let o of r.locations)if(!n.has(o.file))n.set(o.file,s)}return e.flatMap((r)=>{let s=r.files.flatMap((f)=>{let p=n.get(f);return p===void 0?[]:[{file:f,ci:p}]});if(!s.length)return[r];let o=new Map;for(let{ci:f}of s)o.set(f,(o.get(f)??0)+1);let a=0,l=0;for(let[f,p]of o)if(p>l||p===l&&f<a)a=f,l=p;let c=(f)=>{let p=f.replace(/\.(test|spec)(\.[^./]+)$/,"$2"),h=n.get(f)??n.get(p);if(h!==void 0)return h;if(p!==f){let w=p.slice(p.lastIndexOf("/")+1),b=[...n].find(([x])=>x.endsWith(`/${w}`)||x===w);if(b)return b[1]}let g;for(let w of s){let b=$I(f,w.file);if(b>0&&(!g||b>g.depth||b===g.depth&&w.ci<g.ci))g={depth:b,ci:w.ci}}return g?.ci??a},u=new Map;for(let f of r.files){let p=c(f);u.set(p,[...u.get(p)??[],f])}let d=u.size>1;return[...u].sort((f,p)=>f[0]-p[0]).map(([f,p])=>({id:d?`${r.id}-c${f+1}`:r.id,unit:r.unit,files:p,chapter:f}))})}function EI(e,t,n,r,s){let o=e.previous;if(!o)return{carried:[],resolved:t.map((h)=>({id:String(h.id),...h.note?{note:h.note}:{}}))};let a=o.run.findings,l=[],c=new Set;for(let h of t){let g=a[h.id-1];if(!g)continue;c.add(g.id),l.push({id:g.id,title:g.title,file:g.file,...h.note?{note:h.note}:{}})}let u=new Map(a.map((h)=>[Dn(h.id),h.carriedFrom??o.run.id]));for(let h of n){let g=u.get(Dn(h.id));if(g)h.carriedFrom=g}let d=new Set(n.map((h)=>Dn(h.id))),f=new Set(o.dismissed??[]),p=[];for(let h of a){if(c.has(h.id)||f.has(h.id)||d.has(Dn(h.id)))continue;let g=r.get(h.file);if(!g){s(` prior finding "${h.title}" dropped: ${h.file} is no longer in the diff`);continue}let w=o.lineMap?.get(h.file)??[],b=(R)=>R?Bd(w,R):void 0,x=h.alsoAt?.map((R)=>{let P=o.lineMap?.get(R.file)??[];return R.line?{...R,line:Bd(P,R.line)}:R});p.push({...h,anchor:_a(g,h.file,b(h.anchor.cited.line),b(h.anchor.cited.endLine)),...x?{alsoAt:x}:{},carriedFrom:h.carriedFrom??o.run.id})}return{carried:p,resolved:l}}function uf(e){let t=e.log??((_)=>console.error(_)),n=e.result.record,r=n?.walkthrough??null,s=Qb(e.patch),o=new Map(s.map((_)=>[_.name,_])),a=ev(s,e.patch,e.result.byClass),l=new Map(a.map((_)=>[_.path,_])),c=new Map,u=(_)=>{let F=gn(_.file,_.title),A=(c.get(F)??0)+1;return c.set(F,A),A===1?F:`${F}-${A}`},d=(n?.verifiedFindings??[]).map((_)=>Zb(_,u(_),o.get(_.file))),f=(n?.overCapFindings??[]).map((_)=>Zb(_,u(_),o.get(_.file))),{carried:p,resolved:h}=EI(e,n?.resolved??[],[...d,...f],o,t);d.push(...p);let g=(_)=>{let F=_.endsWith("/")?_:`${_}/`;return!o.has(_)&&s.some((A)=>A.name.startsWith(F))},w=[],b=r?.chapters??[];b.forEach((_,F)=>{(_.stops??[]).forEach((A,Q)=>{let fe=[];for(let Ce of A.locations??[]){if(g(Ce.file)){t(` walkthrough: dropped directory location ${Ce.file} in "${A.title}"`);continue}let Jt=o.get(Ce.file),pe={deletionsFallback:!0},ct=Ym(Jt,_a(Jt,Ce.file,Ce.line,void 0,pe),Xm(Ce.symbol,Ce.label),pe);fe.push({...ct,...Ce.label?{label:Ce.label}:{}})}w.push({id:`c${F+1}-s${Q+1}`,chapterId:`c${F+1}`,index:Q,title:A.title,...A.prose?{prose:A.prose}:{},importance:A.importance??"normal",locations:fe})})});let x=new Set,R=(_)=>{let F=[];for(let A of _){if(!l.has(A))continue;if(x.has(A))continue;x.add(A),F.push(A)}return F},P=new Set((r?.start_here??[]).map((_)=>_.file)),M=[...e.result.units].sort((_,F)=>(_.priority??99)-(F.priority??99)),k=new Set,E=(_)=>{let F=`u-${_.id}`;for(let Q=2;k.has(F);Q++)F=`u-${_.id}-${Q}`;k.add(F);let A=_.files.filter((Q)=>!l.has(Q));if(A.length)t(` unit "${_.title}": ${A.length} file(s) not in the patch: ${A.join(", ")}`);return{id:F,unit:_,files:R(_.files)}},D=kI(M.map(E).filter((_)=>_.files.length),w),L=new Map(D.flatMap((_)=>_.chapter===void 0?[]:[[_.id,_.chapter]])),O=(_)=>{let F=l.get(_);return F?F.additions+F.deletions:0},U=e.kind==="diff"?si(D,O):[],I=new Map(D.map((_,F)=>[_.id,U[F]??_.unit.title])),j=[],H=(_,F,A,Q={})=>({id:_,title:F,files:A,findingIds:[],stopIds:[],critical:!1,...Q}),ve=(_,F,A={})=>H(_,F,[],A),Se=(_,F)=>H(_.id,I.get(_.id)??_.unit.title,_.files,{...F?{parentId:F}:{},..._.unit.rationale?{summary:_.unit.rationale}:{}}),ne=(_)=>_.files.some((F)=>P.has(F));if(b.length){b.forEach((F,A)=>{let Q=`c${A+1}`,fe=F.icon;j.push(ve(Q,F.title,{...F.blurb?{summary:F.blurb}:{},...fe&&bI.has(fe)?{icon:fe}:{},stopIds:w.filter((pe)=>pe.chapterId===Q).map((pe)=>pe.id)}));let Ce=D.filter((pe)=>L.get(pe.id)===A),Jt=[...Ce.filter(ne),...Ce.filter((pe)=>!ne(pe))];for(let pe of Jt)j.push(Se(pe,Q))});let _=D.filter((F)=>!L.has(F.id));if(_.length){let F=to((r?.support??[]).map((A)=>A.reason).filter(Boolean));j.push(ve("supporting","Supporting changes",F.length?{summary:F.join(" ")}:{}));for(let A of _)j.push(Se(A,"supporting"))}}else for(let _ of D)j.push(Se(_));let ce=R(a.filter((_)=>_.classification==="docs").map((_)=>_.path)),Be=R(a.filter((_)=>_.classification==="skip").map((_)=>_.path)),ze=R(a.map((_)=>_.path));if(ze.length)t(` ${ze.length} file(s) in no review unit: ${ze.join(", ")}`);let Je=[...ze.length?[H("remaining","Remaining changes",ze)]:[],...ce.length?[H("docs","Docs",ce,{icon:"doc"})]:[],...Be.length?[H("skipped","Generated and skipped",Be,{icon:"gear"})]:[]],Xe=e.kind==="diff"?"Other changes":"Not reviewed in depth",[nt]=Je;if(Je.length===1&&nt)j.push(e.kind==="diff"?nt:{...nt,title:Xe});else if(Je.length){j.push(ve("other",Xe));for(let _ of Je)j.push({..._,parentId:"other"})}let be=new Map;for(let _ of j)for(let F of _.files)be.set(F,_);for(let _ of a)_.groupId=be.get(_.path)?.id??"";let Te=new Map(w.map((_)=>[_.id,_]));for(let _ of j){if(!_.files.length)continue;let F=new Set(_.files);_.findingIds=d.filter((A)=>F.has(A.file)).map((A)=>A.id),_.stopIds=w.filter((A)=>A.locations.some((Q)=>F.has(Q.file))).map((A)=>A.id)}let me=new Map(d.map((_)=>[_.id,_.severity])),W=(_)=>_.findingIds.some((F)=>xI.has(me.get(F)??"question"))||_.stopIds.some((F)=>Te.get(F)?.importance==="critical");for(let _ of j)if(_.files.length)_.critical=W(_);for(let _ of j){if(_.files.length)continue;let F=j.filter((A)=>A.parentId===_.id);_.findingIds=to(F.flatMap((A)=>A.findingIds)),_.critical=F.some((A)=>A.critical)||W(_)}let T=d.filter((_)=>!be.has(_.file));if(T.length)t(` ${T.length} finding(s) name files outside the patch`);let B=r?.intent,z=n?.intentAlignment??void 0,te=to([...B?.unstated??[],...z?.unstated??[]]),we=to([...B?.missing??[],...z?.missing??[]]),Ne=to([...z?.summary?[z.summary]:[],...B?.mismatches??[]]),Ye=B?.alignment==="aligned"&&z?.summary?"partial":B?.alignment,dr={...e.statedIntent?{stated:e.statedIntent}:{},...B?.inferred?{inferred:B.inferred}:{},...Ye?{alignment:Ye}:{},...B?.matches?.length?{matches:B.matches}:{},...Ne.length?{mismatches:Ne}:{},...te.length?{unstated:te}:{},...we.length?{missing:we}:{}},Ot=(n?.sliceRuns??[]).map((_)=>{let F=tl(_.usage);return{unit:_.unit,part:_.part,parts:_.parts,status:_.ok?"ok":"failed",costUsd:_.costUsd??0,wallMs:_.wallMs??0,...F?{usage:F}:{}}}),Un=Fd(e.result.record),Bn=n?.mergeMode,Nt=e.previous,y=Nt?.lineMap&&Nt.run.head!==e.head?Xb(Nt.run.findings,Nt.lineMap):void 0;return{schemaVersion:1,id:e.id,status:"complete",createdAt:e.createdAt,repo:e.repo,target:e.target,base:e.base,head:e.head,intent:dr,overview:{...r?.focus?{focus:r.focus}:{},...r?.change_type?{changeType:r.change_type}:{},startHere:r?.start_here??[]},files:a,groups:j,stops:w,findings:d,overCapFindings:f,resolved:h,...n?.disputes?.length?{disputes:n.disputes}:{},...n?.roundProgress?{roundProgress:n.roundProgress}:{},unreviewed:n?.unreviewed??{overCap:[],failed:[]},meta:{...n?.model?{model:n.model}:{},...n?.effort?{effort:n.effort}:{},...e.models?{models:e.models}:{},...e.kind==="diff"?{kind:"diff"}:{},wallMs:n?.wallMs??e.result.wallMs,costUsd:n?.totalCostUsd??e.result.costUsd,slices:Ot,...Un?{stages:Un}:{},rejectedCount:n?.rejected?.length??0,coreSource:e.coreSource,...Bn&&vI.has(Bn)?{mergeMode:Bn}:{},...n?.budgetStopped?{budgetStopped:!0}:{},...n?.postMinSeverity?{postMinSeverity:n.postMinSeverity}:{},...n?.reviewScope==="full"||n?.reviewScope==="incremental"?{reviewScope:n.reviewScope}:{},...typeof n?.reviewedFiles==="number"?{reviewedFiles:n.reviewedFiles}:{},...n?.scopeReason?{scopeReason:n.scopeReason}:{},...n?.promptVersion?{promptVersion:n.promptVersion}:{},...n?.instructionsHash?{instructionsHash:n.instructionsHash}:{}},untrackedSkipped:e.untrackedSkipped??[],...e.priorRunId?{priorRunId:e.priorRunId}:{},...e.round!==void 0?{round:e.round}:{},...y?{priorActedOn:y}:{}}}function tv(e,t,n){return{...uf({...e,result:{record:null,units:t,byClass:n,costUsd:0,wallMs:0},log:()=>{}}),status:"running"}}function nv(e){let t=ev(Qb(e.patch),e.patch,{skip:[],docs:[],code:[]});for(let n of t)n.groupId="all";return{schemaVersion:1,id:e.id,status:"running",createdAt:e.createdAt,repo:e.repo,target:e.target,base:e.base,head:e.head,intent:e.statedIntent?{stated:e.statedIntent}:{},overview:{startHere:[]},files:t,groups:[{id:"all",title:"All changes",files:t.map((n)=>n.path),findingIds:[],stopIds:[],critical:!1}],stops:[],findings:[],overCapFindings:[],resolved:[],unreviewed:{overCap:[],failed:[]},meta:{...e.models?{models:e.models}:{},...e.kind==="diff"?{kind:"diff"}:{},wallMs:0,costUsd:0,slices:[],rejectedCount:0,coreSource:e.coreSource},untrackedSkipped:e.untrackedSkipped??[],...e.priorRunId?{priorRunId:e.priorRunId}:{},...e.round!==void 0?{round:e.round}:{}}}var bI,vI,xI,RI;var df=qe(()=>{zb();ls();aa();xr();Sr();bI=new Set(["bug","wrench","path","flask","doc","gear"]),vI=new Set(["coordinator","nothing-to-merge","deterministic-fallback"]),xI=new Set(["blocker","should-fix"]),RI={new:"added",deleted:"removed",change:"modified","rename-pure":"renamed","rename-changed":"renamed"}});var cc={};lR(cc,{program:()=>hp,createCommand:()=>mp,createOption:()=>gp,createArgument:()=>_p,Command:()=>wp,Option:()=>yp,Argument:()=>bp,Help:()=>vp,CommanderError:()=>xp,InvalidArgumentError:()=>Rp,InvalidOptionArgumentError:()=>Sp},{program:(MM)=>hp=MM,createCommand:(MM)=>mp=MM,createOption:(MM)=>gp=MM,createArgument:(MM)=>_p=MM,Command:(MM)=>wp=MM,Option:(MM)=>yp=MM,Argument:(MM)=>bp=MM,Help:(MM)=>vp=MM,CommanderError:(MM)=>xp=MM,InvalidArgumentError:(MM)=>Rp=MM,InvalidOptionArgumentError:(MM)=>Sp=MM});var{Argument:dp}=Eo(),{Command:lc}=up(),{CommanderError:jR,InvalidArgumentError:fp}=Vi(),{Help:UR}=rc(),{Option:pp}=ic();var hp=new lc,mp=(e)=>new lc(e),gp=(e,t)=>new pp(e,t),_p=(e,t)=>new dp(e,t),wp=lc,yp=pp,bp=dp,vp=UR,xp=jR,Rp=fp,Sp=fp;var{program:FM,createCommand:NM,createArgument:DM,createOption:LM,CommanderError:jM,InvalidArgumentError:Gn,InvalidOptionArgumentError:UM,Command:It,Argument:BM,Option:qM,Help:HM}=cc;var Ao={name:"@acemarke/diffloupe",version:"0.5.0",type:"module",description:"Understand your diffs before you merge them",bin:{diffloupe:"dist/index.js"},exports:{".":"./dist/index.js"},files:["dist"],scripts:{start:"bun run src/index.ts",dev:"bun run --watch src/index.ts","dev:web":"vite --config src/web/vite.config.ts",prebuild:"rm -rf dist",build:"bun build src/index.ts --outdir=dist --target=bun --minify --banner '#!/usr/bin/env -S bun --no-env-file' && bun scripts/copy-assets.ts && bun run build:web","build:web":"vite build --config src/web/vite.config.ts",prepublishOnly:"bun run build && bun run typecheck",test:"bun test src",typecheck:"tsgo --noEmit && bun run typecheck:web","typecheck:web":"tsgo --noEmit -p src/web && tsgo --noEmit -p src/web/tsconfig.test.json",lint:"oxlint src/",release:"release-it"},engines:{bun:">=1.3.0"},repository:{type:"git",url:"git+https://github.com/markerikson/diffloupe.git"},keywords:["cli","diff","code-review","ai","git","llm"],author:"Mark Erikson",license:"MIT",devDependencies:{"@iconify-json/ph":"^1.2.2","@pierre/diffs":"1.5.2","@reduxjs/toolkit":"^2.11.2","@svgr/core":"^8.1.0","@svgr/plugin-jsx":"^8.1.0","@tanstack/react-router":"^1.170.41","@tanstack/react-router-devtools":"^1.167.2","@types/react":"^19.2.10","@types/react-dom":"^19.2.3","@typescript/native-preview":"^7.0.0-dev.20260127.1","@vitejs/plugin-react":"^5.1.2",arktype:"^2.1.29","bun-types":"^1.3.7",commander:"^14.0.2",hono:"^4.11.7",oxlint:"^1.42.0",picocolors:"^1.1.1",react:"^19","react-dom":"^19","react-redux":"^9.2.0","release-it":"^19.2.4",shiki:"^4.5.0","tree-sitter-cpp":"^0.23.4","tree-sitter-typescript":"^0.23.2","unplugin-icons":"^24.0.0",vite:"^8.3.4","web-tree-sitter":"^0.26.13"}};var Vn=Ao.version;import{readdir as KI,stat as WI}from"fs/promises";import uv from"path";var ro=ko(zi(),1);import{spawn as WR}from"child_process";function re(e,t,n={}){return new Promise((r,s)=>{let o=WR(e,t,{cwd:n.cwd,env:n.env??process.env,stdio:[n.input===void 0?"ignore":"pipe","pipe","pipe"]});if(n.input!==void 0)o.stdin?.on("error",()=>{}),o.stdin?.end(n.input);let a=n.timeoutMs?setTimeout(()=>o.kill("SIGKILL"),n.timeoutMs):void 0,l=[],c=[];o.stdout?.on("data",(u)=>l.push(u)),o.stderr?.on("data",(u)=>c.push(u)),o.on("error",(u)=>{clearTimeout(a),s(u)}),o.on("close",(u,d)=>{clearTimeout(a);let f={stdout:Buffer.concat(l).toString("utf8"),stderr:Buffer.concat(c).toString("utf8"),code:u??(d?128:0),...d?{signal:d}:{}};if(f.code!==0&&!n.allowFail){s(Error(`${e} ${t.join(" ")} ${d?`killed by ${d}`:`exited ${f.code}`}
104
- `+f.stderr.slice(0,2000)));return}r(f)})})}async function oe(e,t,n={}){return(await re(e,t,n)).stdout}var dn=["review","coordinator","walkthrough","intent"],GR={review:"anthropic/claude-opus-5-5",coordinator:"anthropic/claude-opus-5-5",walkthrough:"anthropic/claude-sonnet-5-5",intent:"anthropic/claude-haiku-5-5"},Io={review:"models.review",coordinator:"models.coordinator",walkthrough:"models.walkthrough",intent:"models.intent"};var VR={env:"REVIEW_* environment variable",cli:"--model",settings:"settings file",config:"~/.config/diffloupe/config.json",opencode:"OpenCode default model",default:"built-in default"};function Po(e){return VR[e]}function dt(e){let t=e?.trim();return t?t:void 0}function zR(e){let t=dt(e.REVIEW_MODEL),n=dt(e.REVIEW_MODEL_MERGE)??t,r=dt(e.REVIEW_MODEL_WALK),s=dt(e.REVIEW_MODEL_INTENT);return{...t?{review:t}:{},...n?{coordinator:n}:{},...r?{walkthrough:r}:{},...s?{intent:s}:{}}}function JR(e,t){let n=dt(e.REVIEW_EFFORT);return t==="review"?n:dt(e.REVIEW_EFFORT_AUX)??n}function XR(e,t){let n=e.indexOf("#"),r=n===-1?e:e.slice(0,n),s=n===-1?void 0:dt(e.slice(n+1)),o=r.indexOf("/"),a=o===-1?t:r.slice(0,o),l=o===-1?r:r.slice(o+1);return{provider:a,id:l,...s?{variant:s}:{}}}function dc(e){return dt(e.env?.REVIEW_PROVIDER)??dt(e.settings?.provider)??dt(e.config?.provider)??"anthropic"}function Ep(e){let t=e.env??{},n=dc(e),r=e.config?.opencode?.useDefaultModel!==!1,s=zR(t),o=r?dt(e.openCodeModel):void 0,a={};for(let l of dn){let c=[["env",s[l]],["cli",e.cli?.models?.[l]],["settings",e.settings?.models?.[l]],["config",e.config?.models?.[l]]];if(l!=="intent")c.push(["opencode",o]);let u="default",d=GR[l],f=!1;for(let[w,b]of c){let x=dt(b);if(x){u=w,d=x,f=!0;break}}if(l==="intent"&&!f&&a.walkthrough.provider!=="anthropic"){a.intent={...a.walkthrough};continue}let p=XR(d,n),h=JR(t,l)??dt(e.cli?.effort)??dt(e.settings?.effort)??dt(e.config?.effort)??(u==="default"?"medium":void 0),g=p.variant??h;a[l]={model:`${p.provider}/${p.id}${g?`#${g}`:""}`,provider:p.provider,id:p.id,...g?{variant:g}:{},source:u}}return a}function Ap(e,t=dn){let n=new Map;for(let r of t){let s=e[r].provider;n.set(s,[...n.get(s)??[],r])}return n}import et from"path";import{existsSync as AI}from"fs";import{copyFile as CI,readFile as pl,writeFile as Nr}from"fs/promises";import{join as Cp}from"path";import{homedir as YR}from"os";function ZR(){let e=process.env.XDG_CONFIG_HOME||Cp(YR(),".config");return Cp(e,"diffloupe","config.json")}var zn=null;async function Kr(){if(zn!==null)return zn;let e=Bun.file(ZR());if(!await e.exists())return zn={},zn;try{let t=await e.text();return zn=JSON.parse(t),zn}catch{return zn={},zn}}import Qe from"path";import dS from"path";import{promises as Wr}from"fs";import QR from"path";async function Gr(e){try{return await Wr.access(e),!0}catch{return!1}}function _t(e){return Wr.readFile(e,"utf8")}async function Mo(e){return JSON.parse(await _t(e))}async function De(e,t){await Wr.mkdir(QR.dirname(e),{recursive:!0}),await Wr.writeFile(e,t,"utf8")}async function fn(e,t){await De(e,JSON.stringify(t,null,2))}async function Yt(e){await Wr.rm(e,{force:!0})}async function Sn(e){await Wr.mkdir(e,{recursive:!0})}async function Op(e){try{let t=await _t(e);if(t==="")return 0;return t.replace(/\n$/,"").split(`
105
- `).length}catch{return null}}Ji();async function Tp(e,t,n){return Xi(await oe("git",["-C",e,"-c","diff.renames=true","diff","--unified=0",`${t}..${n}`]))}function*pn(e){let t,n=!1,r=0,s=0;for(let o of e.split(`
106
- `)){if(r>0||s>0){if(!o.startsWith("\\"))if(o.startsWith("-"))r--;else if(o.startsWith("+"))s--;else r--,s--;yield{file:t,line:o};continue}if(o.startsWith("diff --git ")){n=!1,t=void 0;continue}if(o.startsWith("--- ")){n=!0;continue}if(n&&o.startsWith("+++ ")){n=!1;let l=o.slice(4).trim();t=l==="/dev/null"?void 0:l.replace(/^b\//,""),yield{file:t,line:o};continue}n=!1;let a=/^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(o);if(a)r=a[1]===void 0?1:Number(a[1]),s=a[2]===void 0?1:Number(a[2]);yield{file:t,line:o}}}function Fp(e){let t=[],n=0,r=0,s=0,o=0;for(let a of e.split(`
100
+ `))return e.slice(0,-1);return e}function iP(e){return e.startsWith("diff --git")||e.includes(`
101
+ diff --git`)}function gv(e,t){if(e.length===0)return[""];let n=`
102
+ ${t}`,r=e.startsWith(t)?0:dv(e,n,0);if(r===-1)return[e];let s=[];if(r>0)s.push(e.slice(0,r));let o=r;for(;;){let a=dv(e,n,o+1);if(a===-1)break;s.push(e.slice(o,a)),o=a}return s.push(e.slice(o)),s}function dv(e,t,n){let r=e.indexOf(t,n);return r===-1?-1:r+1}function fv(e){return e==null?e:Be(e)}function sP(e){return e===" "?"context":e==="\\"?"metadata":e==="+"?"addition":"deletion"}function wf(e){let t=e.slice(1);return Be(t===""?`
103
+ `:t)}function yf(e,t,n){if(e==="change")return{type:"change",additions:0,deletions:0,additionLineIndex:n,deletionLineIndex:t};return{type:"context",lines:0,additionLineIndex:n,deletionLineIndex:t}}var zI;var _v=He(()=>{Zb();Qb();ev();tv();rv();sv();lv();zI=/^diff --git ("a\/(?:[^"\\]|\\.)*"|a\/.+?) ("b\/(?:[^"\\]|\\.)*"|b\/.+?)$/});var wv=He(()=>{_v()});function yv(e,[t,n]){return e.some((r)=>{let s=r.oldStart+Math.max(r.oldCount,1)-1;return r.oldStart<=n&&t<=s})}function bv(e,t){return e.flatMap((n)=>{let{line:r,endLine:s}=n.anchor.cited;if(n.anchor.side!=="additions"||r<1)return[];let o=[r,Math.max(s??r,r)],a=r>35?-35:35,l=t.get(n.file)??[];return[{id:n.id,acted:yv(l,o),control:yv(l,[o[0]+a,o[1]+a])}]})}function uP(e){let t=new Set;for(let n of e.matchAll(/^Binary files (?:a\/(.+?)|\/dev\/null) and (?:b\/(.+?)|\/dev\/null) differ$/gm)){let r=n[2]??n[1];if(r)t.add(r)}return t}function Sv(e){return vf(e).flatMap((t)=>t.files)}function Rv(e,t,n){let r=uP(t),s=new Map;for(let o of["skip","docs","code"])for(let a of n[o])s.set(a,o);return e.map((o)=>{let a=0,l=0;for(let c of o.hunks)a+=c.additionLines,l+=c.deletionLines;return{path:o.name,...o.prevName&&o.prevName!==o.name?{previousPath:o.prevName}:{},status:cP[o.type],additions:a,deletions:l,isBinary:r.has(o.name),...o.newObjectId?{blob:o.newObjectId}:{},groupId:"",classification:s.get(o.name)??fi(o.name),surface:ot(o.name)}})}function vv(e){let t=e.match(/^(.+?):(\d+)(?:-\d+)?$/);return t?.[1]&&t[2]?{file:t[1],line:Number(t[2])}:{file:e}}function xv(e,t,n){return{id:t,file:e.file,anchor:$a(n,e.file,e.line,e.end_line),severity:e.severity,category:e.category,title:e.title,explanation:e.explanation,evidence:e.evidence,...e.impact?{impact:e.impact}:{},confidence:e.confidence,...e.effort?{effort:e.effort}:{},...e.suggestion?{suggestion:e.suggestion}:{},...e.suggested_code?{suggestedCode:e.suggested_code}:{},...e.cross_file_refs?.length?{crossFileRefs:e.cross_file_refs.map(vv)}:{},...e.also_at?.length?{alsoAt:e.also_at.map(vv)}:{},...e.repeat_of!==void 0?{repeatOf:e.repeat_of}:{},surface:ot(e.file),...e.preexisting?{preexisting:!0}:{}}}function co(e){return[...new Set(e)]}function dP(e,t){let n=e.split("/").slice(0,-1),r=t.split("/").slice(0,-1),s=0;while(s<n.length&&s<r.length&&n[s]===r[s])s++;return s}function fP(e,t){let n=new Map;for(let r of t){let s=Number(r.chapterId.slice(1))-1;for(let o of r.locations)if(!n.has(o.file))n.set(o.file,s)}return e.flatMap((r)=>{let s=r.files.flatMap((f)=>{let p=n.get(f);return p===void 0?[]:[{file:f,ci:p}]});if(!s.length)return[r];let o=new Map;for(let{ci:f}of s)o.set(f,(o.get(f)??0)+1);let a=0,l=0;for(let[f,p]of o)if(p>l||p===l&&f<a)a=f,l=p;let c=(f)=>{let p=f.replace(/\.(test|spec)(\.[^./]+)$/,"$2"),h=n.get(f)??n.get(p);if(h!==void 0)return h;if(p!==f){let w=p.slice(p.lastIndexOf("/")+1),b=[...n].find(([x])=>x.endsWith(`/${w}`)||x===w);if(b)return b[1]}let g;for(let w of s){let b=dP(f,w.file);if(b>0&&(!g||b>g.depth||b===g.depth&&w.ci<g.ci))g={depth:b,ci:w.ci}}return g?.ci??a},u=new Map;for(let f of r.files){let p=c(f);u.set(p,[...u.get(p)??[],f])}let d=u.size>1;return[...u].sort((f,p)=>f[0]-p[0]).map(([f,p])=>({id:d?`${r.id}-c${f+1}`:r.id,unit:r.unit,files:p,chapter:f}))})}function pP(e,t,n,r,s){let o=e.previous;if(!o)return{carried:[],resolved:t.map((h)=>({id:String(h.id),...h.note?{note:h.note}:{}}))};let a=o.run.findings,l=[],c=new Set;for(let h of t){let g=a[h.id-1];if(!g)continue;c.add(g.id),l.push({id:g.id,title:g.title,file:g.file,...h.note?{note:h.note}:{}})}let u=new Map(a.map((h)=>[jn(h.id),h.carriedFrom??o.run.id]));for(let h of n){let g=u.get(jn(h.id));if(g)h.carriedFrom=g}let d=new Set(n.map((h)=>jn(h.id))),f=new Set(o.dismissed??[]),p=[];for(let h of a){if(c.has(h.id)||f.has(h.id)||d.has(jn(h.id)))continue;let g=r.get(h.file);if(!g){s(` prior finding "${h.title}" dropped: ${h.file} is no longer in the diff`);continue}let w=o.lineMap?.get(h.file)??[],b=(S)=>S?ef(w,S):void 0,x=h.alsoAt?.map((S)=>{let P=o.lineMap?.get(S.file)??[];return S.line?{...S,line:ef(P,S.line)}:S});p.push({...h,anchor:$a(g,h.file,b(h.anchor.cited.line),b(h.anchor.cited.endLine)),...x?{alsoAt:x}:{},carriedFrom:h.carriedFrom??o.run.id})}return{carried:p,resolved:l}}function xf(e){let t=e.log??((_)=>console.error(_)),n=e.result.record,r=n?.walkthrough??null,s=Sv(e.patch),o=new Map(s.map((_)=>[_.name,_])),a=Rv(s,e.patch,e.result.byClass),l=new Map(a.map((_)=>[_.path,_])),c=new Map,u=(_)=>{let D=wn(_.file,_.title),C=(c.get(D)??0)+1;return c.set(D,C),C===1?D:`${D}-${C}`},d=(n?.verifiedFindings??[]).map((_)=>xv(_,u(_),o.get(_.file))),f=(n?.overCapFindings??[]).map((_)=>xv(_,u(_),o.get(_.file))),{carried:p,resolved:h}=pP(e,n?.resolved??[],[...d,...f],o,t);d.push(...p);let g=(_)=>{let D=_.endsWith("/")?_:`${_}/`;return!o.has(_)&&s.some((C)=>C.name.startsWith(D))},w=[],b=r?.chapters??[];b.forEach((_,D)=>{(_.stops??[]).forEach((C,Q)=>{let fe=[];for(let Ae of C.locations??[]){if(g(Ae.file)){t(` walkthrough: dropped directory location ${Ae.file} in "${C.title}"`);continue}let Xt=o.get(Ae.file),pe={deletionsFallback:!0},ct=xg(Xt,$a(Xt,Ae.file,Ae.line,void 0,pe),vg(Ae.symbol,Ae.label),pe);fe.push({...ct,...Ae.label?{label:Ae.label}:{}})}w.push({id:`c${D+1}-s${Q+1}`,chapterId:`c${D+1}`,index:Q,title:C.title,...C.prose?{prose:C.prose}:{},importance:C.importance??"normal",locations:fe})})});let x=new Set,S=(_)=>{let D=[];for(let C of _){if(!l.has(C))continue;if(x.has(C))continue;x.add(C),D.push(C)}return D},P=new Set((r?.start_here??[]).map((_)=>_.file)),M=[...e.result.units].sort((_,D)=>(_.priority??99)-(D.priority??99)),k=new Set,E=(_)=>{let D=`u-${_.id}`;for(let Q=2;k.has(D);Q++)D=`u-${_.id}-${Q}`;k.add(D);let C=_.files.filter((Q)=>!l.has(Q));if(C.length)t(` unit "${_.title}": ${C.length} file(s) not in the patch: ${C.join(", ")}`);return{id:D,unit:_,files:S(_.files)}},F=fP(M.map(E).filter((_)=>_.files.length),w),L=new Map(F.flatMap((_)=>_.chapter===void 0?[]:[[_.id,_.chapter]])),O=(_)=>{let D=l.get(_);return D?D.additions+D.deletions:0},U=e.kind==="diff"?ui(F,O):[],I=new Map(F.map((_,D)=>[_.id,U[D]??_.unit.title])),j=[],H=(_,D,C,Q={})=>({id:_,title:D,files:C,findingIds:[],stopIds:[],critical:!1,...Q}),ve=(_,D,C={})=>H(_,D,[],C),Re=(_,D)=>H(_.id,I.get(_.id)??_.unit.title,_.files,{...D?{parentId:D}:{},..._.unit.rationale?{summary:_.unit.rationale}:{}}),ne=(_)=>_.files.some((D)=>P.has(D));if(b.length){b.forEach((D,C)=>{let Q=`c${C+1}`,fe=D.icon;j.push(ve(Q,D.title,{...D.blurb?{summary:D.blurb}:{},...fe&&oP.has(fe)?{icon:fe}:{},stopIds:w.filter((pe)=>pe.chapterId===Q).map((pe)=>pe.id)}));let Ae=F.filter((pe)=>L.get(pe.id)===C),Xt=[...Ae.filter(ne),...Ae.filter((pe)=>!ne(pe))];for(let pe of Xt)j.push(Re(pe,Q))});let _=F.filter((D)=>!L.has(D.id));if(_.length){let D=co((r?.support??[]).map((C)=>C.reason).filter(Boolean));j.push(ve("supporting","Supporting changes",D.length?{summary:D.join(" ")}:{}));for(let C of _)j.push(Re(C,"supporting"))}}else for(let _ of F)j.push(Re(_));let ce=S(a.filter((_)=>_.classification==="docs").map((_)=>_.path)),qe=S(a.filter((_)=>_.classification==="skip").map((_)=>_.path)),ze=S(a.map((_)=>_.path));if(ze.length)t(` ${ze.length} file(s) in no review unit: ${ze.join(", ")}`);let Je=[...ze.length?[H("remaining","Remaining changes",ze)]:[],...ce.length?[H("docs","Docs",ce,{icon:"doc"})]:[],...qe.length?[H("skipped","Generated and skipped",qe,{icon:"gear"})]:[]],Xe=e.kind==="diff"?"Other changes":"Not reviewed in depth",[nt]=Je;if(Je.length===1&&nt)j.push(e.kind==="diff"?nt:{...nt,title:Xe});else if(Je.length){j.push(ve("other",Xe));for(let _ of Je)j.push({..._,parentId:"other"})}let be=new Map;for(let _ of j)for(let D of _.files)be.set(D,_);for(let _ of a)_.groupId=be.get(_.path)?.id??"";let Te=new Map(w.map((_)=>[_.id,_]));for(let _ of j){if(!_.files.length)continue;let D=new Set(_.files);_.findingIds=d.filter((C)=>D.has(C.file)).map((C)=>C.id),_.stopIds=w.filter((C)=>C.locations.some((Q)=>D.has(Q.file))).map((C)=>C.id)}let me=new Map(d.map((_)=>[_.id,_.severity])),G=(_)=>_.findingIds.some((D)=>lP.has(me.get(D)??"question"))||_.stopIds.some((D)=>Te.get(D)?.importance==="critical");for(let _ of j)if(_.files.length)_.critical=G(_);for(let _ of j){if(_.files.length)continue;let D=j.filter((C)=>C.parentId===_.id);_.findingIds=co(D.flatMap((C)=>C.findingIds)),_.critical=D.some((C)=>C.critical)||G(_)}let T=d.filter((_)=>!be.has(_.file));if(T.length)t(` ${T.length} finding(s) name files outside the patch`);let B=r?.intent,z=n?.intentAlignment??void 0,te=co([...B?.unstated??[],...z?.unstated??[]]),we=co([...B?.missing??[],...z?.missing??[]]),Ne=co([...z?.summary?[z.summary]:[],...B?.mismatches??[]]),Ye=B?.alignment==="aligned"&&z?.summary?"partial":B?.alignment,hr={...e.statedIntent?{stated:e.statedIntent}:{},...B?.inferred?{inferred:B.inferred}:{},...Ye?{alignment:Ye}:{},...B?.matches?.length?{matches:B.matches}:{},...Ne.length?{mismatches:Ne}:{},...te.length?{unstated:te}:{},...we.length?{missing:we}:{}},Ot=(n?.sliceRuns??[]).map((_)=>{let D=cl(_.usage);return{unit:_.unit,part:_.part,parts:_.parts,status:_.ok?"ok":"failed",costUsd:_.costUsd??0,wallMs:_.wallMs??0,...D?{usage:D}:{}}}),qn=zd(e.result.record),Hn=n?.mergeMode,Ft=e.previous,y=Ft?.lineMap&&Ft.run.head!==e.head?bv(Ft.run.findings,Ft.lineMap):void 0;return{schemaVersion:1,id:e.id,status:"complete",createdAt:e.createdAt,repo:e.repo,target:e.target,base:e.base,head:e.head,intent:hr,overview:{...r?.focus?{focus:r.focus}:{},...r?.change_type?{changeType:r.change_type}:{},startHere:r?.start_here??[]},files:a,groups:j,stops:w,findings:d,overCapFindings:f,resolved:h,...n?.disputes?.length?{disputes:n.disputes}:{},...n?.roundProgress?{roundProgress:n.roundProgress}:{},unreviewed:n?.unreviewed??{overCap:[],failed:[]},meta:{...n?.model?{model:n.model}:{},...n?.effort?{effort:n.effort}:{},...e.models?{models:e.models}:{},...e.kind==="diff"?{kind:"diff"}:{},wallMs:n?.wallMs??e.result.wallMs,costUsd:n?.totalCostUsd??e.result.costUsd,slices:Ot,...qn?{stages:qn}:{},rejectedCount:n?.rejected?.length??0,coreSource:e.coreSource,...Hn&&aP.has(Hn)?{mergeMode:Hn}:{},...n?.budgetStopped?{budgetStopped:!0}:{},...n?.postMinSeverity?{postMinSeverity:n.postMinSeverity}:{},...n?.reviewScope==="full"||n?.reviewScope==="incremental"?{reviewScope:n.reviewScope}:{},...typeof n?.reviewedFiles==="number"?{reviewedFiles:n.reviewedFiles}:{},...n?.scopeReason?{scopeReason:n.scopeReason}:{},...n?.promptVersion?{promptVersion:n.promptVersion}:{},...n?.instructionsHash?{instructionsHash:n.instructionsHash}:{}},untrackedSkipped:e.untrackedSkipped??[],...e.priorRunId?{priorRunId:e.priorRunId}:{},...e.round!==void 0?{round:e.round}:{},...y?{priorActedOn:y}:{}}}function $v(e,t,n){return{...xf({...e,result:{record:null,units:t,byClass:n,costUsd:0,wallMs:0},log:()=>{}}),status:"running"}}function kv(e){let t=Rv(Sv(e.patch),e.patch,{skip:[],docs:[],code:[]});for(let n of t)n.groupId="all";return{schemaVersion:1,id:e.id,status:"running",createdAt:e.createdAt,repo:e.repo,target:e.target,base:e.base,head:e.head,intent:e.statedIntent?{stated:e.statedIntent}:{},overview:{startHere:[]},files:t,groups:[{id:"all",title:"All changes",files:t.map((n)=>n.path),findingIds:[],stopIds:[],critical:!1}],stops:[],findings:[],overCapFindings:[],resolved:[],unreviewed:{overCap:[],failed:[]},meta:{...e.models?{models:e.models}:{},...e.kind==="diff"?{kind:"diff"}:{},wallMs:0,costUsd:0,slices:[],rejectedCount:0,coreSource:e.coreSource},untrackedSkipped:e.untrackedSkipped??[],...e.priorRunId?{priorRunId:e.priorRunId}:{},...e.round!==void 0?{round:e.round}:{}}}var oP,aP,lP,cP;var Sf=He(()=>{wv();_s();ma();kr();Cr();oP=new Set(["bug","wrench","path","flask","doc","gear"]),aP=new Set(["coordinator","nothing-to-merge","deterministic-fallback"]),lP=new Set(["blocker","should-fix"]),cP={new:"added",deleted:"removed",change:"modified","rename-pure":"renamed","rename-changed":"renamed"}});var yc={};IS(yc,{program:()=>Ep,createCommand:()=>Cp,createOption:()=>Ap,createArgument:()=>Op,Command:()=>Ip,Option:()=>Pp,Argument:()=>Mp,Help:()=>Tp,CommanderError:()=>Dp,InvalidArgumentError:()=>Np,InvalidOptionArgumentError:()=>Fp},{program:(yT)=>Ep=yT,createCommand:(yT)=>Cp=yT,createOption:(yT)=>Ap=yT,createArgument:(yT)=>Op=yT,Command:(yT)=>Ip=yT,Option:(yT)=>Pp=yT,Argument:(yT)=>Mp=yT,Help:(yT)=>Tp=yT,CommanderError:(yT)=>Dp=yT,InvalidArgumentError:(yT)=>Np=yT,InvalidOptionArgumentError:(yT)=>Fp=yT});var{Argument:Rp}=No(),{Command:wc}=Sp(),{CommanderError:lR,InvalidArgumentError:$p}=Zi(),{Help:cR}=pc(),{Option:kp}=hc();var Ep=new wc,Cp=(e)=>new wc(e),Ap=(e,t)=>new kp(e,t),Op=(e,t)=>new Rp(e,t),Ip=wc,Pp=kp,Mp=Rp,Tp=cR,Dp=lR,Np=$p,Fp=$p;var{program:vT,createCommand:xT,createArgument:ST,createOption:RT,CommanderError:$T,InvalidArgumentError:zn,InvalidOptionArgumentError:kT,Command:It,Argument:ET,Option:CT,Help:AT}=yc;var Fo={name:"@acemarke/diffloupe",version:"0.5.1",type:"module",description:"Understand your diffs before you merge them",bin:{diffloupe:"dist/index.js"},exports:{".":"./dist/index.js"},files:["dist"],scripts:{start:"bun run src/index.ts",dev:"bun run --watch src/index.ts","dev:web":"vite --config src/web/vite.config.ts",prebuild:"rm -rf dist",build:"bun build src/index.ts --outdir=dist --target=bun --minify --banner '#!/usr/bin/env -S bun --no-env-file' && bun scripts/copy-assets.ts && bun run build:web","build:web":"vite build --config src/web/vite.config.ts",prepublishOnly:"bun run build && bun run typecheck",test:"bun test src",typecheck:"tsgo --noEmit && bun run typecheck:web","typecheck:web":"tsgo --noEmit -p src/web && tsgo --noEmit -p src/web/tsconfig.test.json",lint:"oxlint src/",release:"release-it"},engines:{bun:">=1.3.0"},repository:{type:"git",url:"git+https://github.com/markerikson/diffloupe.git"},keywords:["cli","diff","code-review","ai","git","llm"],author:"Mark Erikson",license:"MIT",devDependencies:{"@iconify-json/ph":"^1.2.2","@pierre/diffs":"1.5.2","@reduxjs/toolkit":"^2.11.2","@svgr/core":"^8.1.0","@svgr/plugin-jsx":"^8.1.0","@tanstack/react-router":"^1.170.41","@tanstack/react-router-devtools":"^1.167.2","@types/react":"^19.2.10","@types/react-dom":"^19.2.3","@typescript/native-preview":"^7.0.0-dev.20260127.1","@vitejs/plugin-react":"^5.1.2",arktype:"^2.1.29","bun-types":"^1.3.7",commander:"^14.0.2",hono:"^4.11.7",oxlint:"^1.42.0",picocolors:"^1.1.1",react:"^19","react-dom":"^19","react-redux":"^9.2.0","release-it":"^19.2.4",shiki:"^4.5.0","tree-sitter-cpp":"^0.23.4","tree-sitter-typescript":"^0.23.2","unplugin-icons":"^24.0.0",vite:"^8.3.4","web-tree-sitter":"^0.26.13"}};var Jn=Fo.version;import{readdir as OP,stat as IP}from"fs/promises";import Mv from"path";var po=Do(Qi(),1);import{spawn as hR}from"child_process";function re(e,t,n={}){return new Promise((r,s)=>{let o=hR(e,t,{cwd:n.cwd,env:n.env??process.env,stdio:[n.input===void 0?"ignore":"pipe","pipe","pipe"]});if(n.input!==void 0)o.stdin?.on("error",()=>{}),o.stdin?.end(n.input);let a=n.timeoutMs?setTimeout(()=>o.kill("SIGKILL"),n.timeoutMs):void 0,l=[],c=[];o.stdout?.on("data",(u)=>l.push(u)),o.stderr?.on("data",(u)=>c.push(u)),o.on("error",(u)=>{clearTimeout(a),s(u)}),o.on("close",(u,d)=>{clearTimeout(a);let f={stdout:Buffer.concat(l).toString("utf8"),stderr:Buffer.concat(c).toString("utf8"),code:u??(d?128:0),...d?{signal:d}:{}};if(f.code!==0&&!n.allowFail){s(Error(`${e} ${t.join(" ")} ${d?`killed by ${d}`:`exited ${f.code}`}
104
+ `+f.stderr.slice(0,2000)));return}r(f)})})}async function oe(e,t,n={}){return(await re(e,t,n)).stdout}import{Database as Kp}from"bun:sqlite";import{existsSync as bR}from"fs";import vR from"os";import xc from"path";var Zt=["review","coordinator","walkthrough","intent"],mR={review:"anthropic/claude-opus-5-5",coordinator:"anthropic/claude-opus-5-5",walkthrough:"anthropic/claude-sonnet-5-5",intent:"anthropic/claude-haiku-5-5"},Xn={review:"models.review",coordinator:"models.coordinator",walkthrough:"models.walkthrough",intent:"models.intent"};var gR={env:"REVIEW_* environment variable",cli:"--model",settings:"settings file",config:"~/.config/diffloupe/config.json",opencode:"OpenCode default model",default:"built-in default"};function Up(e){return gR[e]}function dt(e){let t=e?.trim();return t?t:void 0}function _R(e){let t=dt(e.REVIEW_MODEL),n=dt(e.REVIEW_MODEL_MERGE)??t,r=dt(e.REVIEW_MODEL_WALK),s=dt(e.REVIEW_MODEL_INTENT);return{...t?{review:t}:{},...n?{coordinator:n}:{},...r?{walkthrough:r}:{},...s?{intent:s}:{}}}function wR(e,t){let n=dt(e.REVIEW_EFFORT);return t==="review"?n:dt(e.REVIEW_EFFORT_AUX)??n}function yR(e,t){let n=e.indexOf("#"),r=n===-1?e:e.slice(0,n),s=n===-1?void 0:dt(e.slice(n+1)),o=r.indexOf("/"),a=o===-1?t:r.slice(0,o),l=o===-1?r:r.slice(o+1);return{provider:a,id:l,...s?{variant:s}:{}}}function vc(e){return dt(e.env?.REVIEW_PROVIDER)??dt(e.settings?.provider)??dt(e.config?.provider)??"anthropic"}function Bp(e){let t=e.env??{},n=vc(e),r=e.config?.opencode?.useDefaultModel!==!1,s=_R(t),o=r?dt(e.openCodeModel):void 0,a={};for(let l of Zt){let c=[["env",s[l]],["cli",e.cli?.models?.[l]],["settings",e.settings?.models?.[l]],["config",e.config?.models?.[l]]];if(l!=="intent")c.push(["opencode",o]);let u="default",d=mR[l],f=!1;for(let[w,b]of c){let x=dt(b);if(x){u=w,d=x,f=!0;break}}if(l==="intent"&&!f&&a.walkthrough.provider!=="anthropic"){a.intent={...a.walkthrough};continue}let p=yR(d,n),h=wR(t,l)??dt(e.cli?.effort)??dt(e.settings?.effort)??dt(e.config?.effort)??(u==="default"?"medium":void 0),g=p.variant??h;a[l]={model:`${p.provider}/${p.id}${g?`#${g}`:""}`,provider:p.provider,id:p.id,...g?{variant:g}:{},source:u}}return a}function qp(e,t=Zt){let n=new Map;for(let r of t){let s=e[r].provider;n.set(s,[...n.get(s)??[],r])}return n}function br(e,t,n){return n&&t.some((r)=>n.stages.includes(r))?`${e} ${n.hint}`:e}var pn="claude-agent",xR="opencode.provider.claude-agent",Gp="claude-login",Sc="2.1.248";function SR(e,t){return`plugin:${Array.from(e,(r)=>r.charCodeAt(0).toString(16).padStart(4,"0")).join("")}:${t}`}var RR=SR(xR,"models");function Rc(e=process.env,t=vR.homedir()){let n=e.XDG_DATA_HOME?e.XDG_DATA_HOME:xc.join(t,".local","share"),r=xc.join(n,"opencode");return xc.resolve(r,e.OPENCODE_DB||"opencode.db")}function Hp(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function $R(e){let t;try{t=JSON.parse(e.value)}catch{return}if(!Hp(t)||!Array.isArray(t.models))return;let n=[];for(let r of t.models){if(!Hp(r)||typeof r.id!=="string")continue;n.push({id:r.id,...typeof r.name==="string"?{name:r.name}:{},...Array.isArray(r.efforts)?{efforts:r.efforts.filter((s)=>typeof s==="string")}:{}})}return{...typeof t.priceSource==="string"?{priceSource:t.priceSource}:{},models:n,row:e}}function Wp(e=Rc()){if(!bR(e))return;let t;try{t=new Kp(e,{readonly:!0});let n=t.query("SELECT key, value FROM kv WHERE key = ?").get(RR);return n?$R({key:n.key,value:String(n.value)}):void 0}catch{return}finally{t?.close()}}function Vp(e,t,n,r,s){let o={errors:[],zeroCost:[],seed:[]},a=t.filter((c)=>e[c].provider===pn);if(!a.length)return o;let l=(c,u)=>o.errors.push(br(c,u,s));if(!n)return l(`OpenCode has no saved model list for \`${pn}\` in ${r}. Start OpenCode once and pick a ${pn} model so it lists Claude Code's models, then run DiffLoupe again.`,a),o;o.seed.push(n.row);for(let c of a){let u=e[c],d=n.models.find((p)=>p.id===u.id),f=`Set \`${Xn[c]}\` in ~/.config/diffloupe/config.json or pass --model ${c}=<provider/model>.`;if(!d){l(`Model \`${u.model}\` is not in Claude Code's model list (${n.models.map((p)=>p.id).join(", ")}). ${f}`,[c]);continue}if(u.variant&&d.efforts&&!d.efforts.includes(u.variant))l(`Model \`${u.model}\` has no effort \`${u.variant}\` (efforts: ${d.efforts.join(", ")||"none"}). ${f}`,[c]);if(!n.priceSource)o.zeroCost.push(c)}return o}function zp(e=process.env){if(e.OPENCODE_CLAUDE_PATH)return e.OPENCODE_CLAUDE_PATH;return Bun.which("claude",e.PATH?{PATH:e.PATH}:void 0)??void 0}function Jp(e,t,n=Date.now()){if(!t.length)return;let r=new Kp(e);try{let s=r.query("PRAGMA table_info(kv)").all(),o=new Set(s.map((l)=>l.name));for(let l of["key","value","time_created","time_updated"])if(!o.has(l))throw Error(`OpenCode's database at ${e} has no kv.${l} column; this OpenCode version stores plugin data differently than DiffLoupe expects.`);let a=r.query("INSERT INTO kv (key, value, time_created, time_updated) VALUES (?, ?, ?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value, time_updated = excluded.time_updated");r.transaction(()=>{for(let l of t)a.run(l.key,l.value,n,n)})()}finally{r.close()}}import{readFileSync as VR,realpathSync as zR,statSync as rh}from"fs";import JR from"os";import Pt from"path";import{execFileSync as kR}from"child_process";import{builtinModules as ER}from"module";import{existsSync as CR,readFileSync as AR}from"fs";import{join as OR,posix as kn}from"path";function IR(e,t){return{paths:new Set(t),read(n){let r=OR(e,n);try{return CR(r)?AR(r,"utf8"):void 0}catch{return}}}}function Bo(e){let t=kR("git",["-C",e,"ls-files"],{encoding:"utf8",maxBuffer:268435456});return IR(e,t.split(`
105
+ `).filter(Boolean))}var Xp=[".ts",".tsx",".d.ts",".js",".jsx",".mts",".cts",".mjs",".cjs"],PR={".js":[".ts",".tsx"],".jsx":[".tsx"],".mjs":[".mts"],".cjs":[".cts"]},es=/\.(?:d\.ts|tsx?|jsx?|mts|cts|mjs|cjs)$/;function hn(e,t){let n=kn.normalize(e).replace(/^\.\//,"");if(n.startsWith("../"))return;if(t.has(n))return n;let r=kn.extname(n);for(let s of PR[r]??[]){let o=n.slice(0,-r.length)+s;if(t.has(o))return o}for(let s of Xp)if(t.has(n+s))return n+s;for(let s of Xp)if(t.has(`${n}/index${s}`))return`${n}/index${s}`;return}function Cc(e){let t="",n=0;while(n<e.length){let r=e[n];if(r==='"'){let s=n++;while(n<e.length&&e[n]!=='"')n+=e[n]==="\\"?2:1;t+=e.slice(s,++n)}else if(r==="/"&&e[n+1]==="/")while(n<e.length&&e[n]!==`
106
+ `)n++;else if(r==="/"&&e[n+1]==="*"){let s=e.indexOf("*/",n+2);n=s===-1?e.length:s+2}else t+=r,n++}try{return JSON.parse(t.replace(/,(\s*[}\]])/g,"$1"))}catch{return}}function Yn(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var MR=/(^|\/)(tsconfig[^/]*|jsconfig[^/]*)\.json$/;function En(e){let t=kn.dirname(e);return t==="."?"":t}function ft(e,t){return kn.normalize(e?`${e}/${t}`:t).replace(/^\.\//,"").replace(/^\.$/,"")}function qo(e,t){let n=e.read(t);if(n===void 0)return;let r=Cc(n);return Yn(r)?r:void 0}function TR(e,t,n){if(e.startsWith(".")||e.startsWith("/")){let s=ft(t,e);return s.endsWith(".json")?s:`${s}.json`}return(e.endsWith(".json")?[`node_modules/${e}`]:[`node_modules/${e}/tsconfig.json`,`node_modules/${e}.json`]).find((s)=>n.read(s)!==void 0)}function kc(e,t,n=new Set){if(n.has(t))return{};n.add(t);let r=qo(e,t);if(!r)return{};let s=En(t),o={},a=r.extends;for(let c of typeof a==="string"?[a]:Array.isArray(a)?a:[]){if(typeof c!=="string")continue;let u=TR(c,s,e);if(u)o={...o,...kc(e,u,n)}}let l=Yn(r.compilerOptions)?r.compilerOptions:{};if(typeof l.baseUrl==="string")o.baseUrl=l.baseUrl,o.baseUrlFrom=s;if(Yn(l.paths)){let c={};for(let[u,d]of Object.entries(l.paths))if(Array.isArray(d))c[u]=d.filter((f)=>typeof f==="string");o.paths=c,o.pathsFrom=s}return o}function DR(e,t){let n=qo(e,t)?.references;if(!Array.isArray(n))return[];let r=En(t);return n.flatMap((s)=>{if(!Yn(s)||typeof s.path!=="string")return[];let o=ft(r,s.path);return[o.endsWith(".json")?o:`${o}/tsconfig.json`]})}function NR(e,t,n){let r=t.baseUrl!==void 0?ft(t.baseUrlFrom??e,t.baseUrl):void 0,s=[];for(let o of[t,...n]){if(!o.paths)continue;let a=o.baseUrl!==void 0?ft(o.baseUrlFrom??e,o.baseUrl):o.pathsFrom??e;for(let[l,c]of Object.entries(o.paths)){if(s.some((u)=>u.pattern===l))continue;s.push({pattern:l,targets:c.map((u)=>ft(a,u))})}}return{dir:e,...r!==void 0?{baseUrl:r}:{},paths:s}}function FR(e){let t=new Map,n=[...e.paths].filter((r)=>MR.test(r)&&!r.includes("node_modules/"));for(let r of["tsconfig.json","jsconfig.json"])for(let s of n){if(kn.basename(s)!==r)continue;let o=En(s);if(t.has(o))continue;let a=kc(e,s),l=a.paths?[]:DR(e,s).map((c)=>kc(e,c));t.set(o,NR(o,a,l))}return t}function Zp(e,t){let n=e.indexOf("*");if(n===-1)return e===t?"":void 0;let r=e.slice(0,n),s=e.slice(n+1);if(t.length<r.length+s.length)return;if(!t.startsWith(r)||!t.endsWith(s))return;return t.slice(r.length,t.length-s.length)}function Ec(e){let t=e.indexOf("*");return t===-1?1/0:t}function LR(e,t,n){let r;for(let s of e){let o=Zp(s.pattern,t);if(o===void 0)continue;if(!r||Ec(s.pattern)>Ec(r.rule.pattern))r={rule:s,capture:o}}if(!r)return;for(let s of r.rule.targets){let o=hn(s.replace("*",r.capture),n);if(o)return o}return}var jR=["source","development","import","module","node","require","browser","default","types"];function Uo(e){if(typeof e==="string")return e;if(Array.isArray(e)){for(let t of e){let n=Uo(t);if(n)return n}return}if(!Yn(e))return;for(let t of jR)if(t in e)return Uo(e[t]);for(let t of Object.values(e)){let n=Uo(t);if(n)return n}return}function Qp(e,t,n,r){let s;for(let[o,a]of Object.entries(e)){let l=Zp(o,t);if(l===void 0)continue;let c=Uo(a);if(!c)continue;let u=Ec(o);if(!s||u>s.len)s={target:c,capture:l,len:u}}if(!s)return;return eh(ft(n,s.target.replaceAll("*",s.capture)),n,r)}function eh(e,t,n){let r=hn(e,n);if(r)return r;let s=t?e.slice(t.length+1):e,o=/^(dist|lib|build|out|js)\/(.*)$/.exec(s);if(!o)return;for(let a of o[1]==="js"?["ts","src"]:["src"]){let l=hn(ft(t,`${a}/${o[2]}`).replace(es,""),n);if(l)return l}return}function UR(e){let t=new Map;for(let n of e.paths){if(kn.basename(n)!=="package.json"||n.includes("node_modules/"))continue;let r=qo(e,n);if(!r)continue;let s=[r.source,r.module,r.main,r.types,r.typings].filter((o)=>typeof o==="string");t.set(En(n),{dir:En(n),...typeof r.name==="string"?{name:r.name}:{},...Yn(r.imports)?{imports:r.imports}:{},...r.exports!==void 0?{exports:r.exports}:{},entry:s})}return t}function BR(e,t){let n=new Set;for(let r of t.keys()){let s=qo(e,ft(r,"package.json"));for(let o of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let a=s?.[o];if(Yn(a))for(let l of Object.keys(a))n.add(l)}}return n}function $c(e){let t=e.split("/");return e.startsWith("@")?t.slice(0,2).join("/"):t[0]}function qR(e,t,n){let r=t?`./${t}`:".";if(e.exports!==void 0){let s=Yn(e.exports)&&Object.keys(e.exports).some((a)=>a.startsWith("."))?e.exports:{".":e.exports},o=Qp(s,r,e.dir,n);if(o)return o}if(!t){for(let s of e.entry){let o=eh(ft(e.dir,s),e.dir,n);if(o)return o}return hn(ft(e.dir,"src/index"),n)??hn(ft(e.dir,"index"),n)}return hn(ft(e.dir,t),n)??hn(ft(e.dir,`src/${t}`),n)}var HR=new Set(ER);function KR(e){let t=e.indexOf("/");if(t<=0)return;let n=e.slice(0,t);return/^[@~#$]/.test(n)?`${n}/`:void 0}class th{byLast=new Map;constructor(e){for(let t of e){if(!es.test(t)||t.includes("node_modules/"))continue;let n=t.replace(es,"");if(this.add(n),kn.basename(n)==="index")this.add(En(n))}}add(e){if(!e)return;let t=kn.basename(e),n=this.byLast.get(t);if(n)n.push(e);else this.byLast.set(t,[e])}roots(e){let t=e.replace(es,"").replace(/\/$/,""),n=this.byLast.get(kn.basename(t))??[],r=new Set;for(let s of n)if(s===t)r.add("");else if(s.endsWith(`/${t}`))r.add(s.slice(0,s.length-t.length));return[...r]}}var GR=0.6,Yp=/^[@~#$]\/$/;function nh(e){let t=KR(e);if(t)return{prefix:t,bare:!1};let n=e.indexOf("/");return n>0?{prefix:e.slice(0,n+1),bare:!0}:void 0}function WR(e,t,n){let r=new Map;for(let{from:a,spec:l}of e){let c=nh(l);if(!c)continue;let u=n(a),d=`${u}\x00${c.prefix}`,f=r.get(d);if(!f)r.set(d,f={scope:u,...c,specs:new Set});f.specs.add(l)}let s=new th(t),o=[];for(let{scope:a,prefix:l,bare:c,specs:u}of r.values()){let d=new Map;for(let b of u)for(let x of s.roots(c?b:b.slice(l.length))){if(a&&x!==a&&!x.startsWith(`${a}/`))continue;d.set(x,(d.get(x)??0)+1)}let f=[...d].sort((b,x)=>x[1]-b[1]||b[0].length-x[0].length),[p,h]=f;if(!p)continue;let[g,w]=p;if(h&&h[1]===w)continue;if(w<GR*u.size)continue;if(w<2&&!Yp.test(l))continue;if(!c&&!Yp.test(l)&&g==="")continue;o.push({scope:a,prefix:l,root:c?g+l:g,hits:w,total:u.size})}return o.sort((a,l)=>a.scope.localeCompare(l.scope)||a.prefix.localeCompare(l.prefix))}class Ac{files;aliases;tsProjects;packages;workspaces=new Map;deps;nearestCache=new Map;constructor(e,t){this.files=e;this.tsProjects=FR(e),this.packages=UR(e);for(let r of this.packages.values())if(r.name)this.workspaces.set(r.name,r);this.deps=BR(e,this.packages);for(let r of e.paths)for(let s of r.matchAll(/(?:^|\/)node_modules\/((?:@[^/]+\/)?[^/]+)\//g))this.deps.add(s[1]);let n=[];if(t.infer){for(let r of t.infer)if(this.isCandidateAlias(r.spec)&&!this.resolveConfigured(r.spec,r.from))n.push(r)}this.aliases=WR(n,e.paths,(r)=>this.nearest(r).pkg?.dir??"")}static create(e,t={}){return new Ac(e,t)}isExternal(e){if(e.startsWith("node:")||HR.has($c(e)))return!0;return this.deps.has($c(e))}resolve(e,t){if(e.startsWith(".")){let r=hn(ft(En(t),e),this.files.paths);return r?{path:r,via:"relative"}:void 0}if(e.startsWith("/"))return;let n=this.resolveConfigured(e,t);if(n)return n;if(!this.isCandidateAlias(e))return;return this.resolveInferred(e,t)}isCandidateAlias(e){if(e.startsWith(".")||e.startsWith("/")||e.includes(":"))return!1;return!this.isExternal(e)}nearest(e){let t=En(e),n=this.nearestCache.get(t);if(n)return n;let r,s;for(let a=t;;a=En(a))if(r??=this.tsProjects.get(a),s??=this.packages.get(a),r&&s||a==="")break;let o={...r?{ts:r}:{},...s?{pkg:s}:{}};return this.nearestCache.set(t,o),o}resolveConfigured(e,t){let{ts:n,pkg:r}=this.nearest(t),s=this.files.paths;if(n){let l=LR(n.paths,e,s);if(l)return{path:l,via:"tsconfig"}}if(e.startsWith("#")&&r?.imports){let l=Qp(r.imports,e,r.dir,s);if(l)return{path:l,via:"package-imports"}}let o=$c(e),a=this.workspaces.get(o);if(a){let l=qR(a,e.slice(o.length+1),s);if(l)return{path:l,via:"workspace"}}if(n?.baseUrl!==void 0&&!this.isExternal(e)){let l=hn(ft(n.baseUrl,e),s);if(l)return{path:l,via:"base-url"}}return}resolveInferred(e,t){let n=this.nearest(t).pkg?.dir??"",r=nh(e)?.prefix;if(!r)return;let s=this.aliases.find((a)=>a.scope===n&&a.prefix===r)??this.aliases.find((a)=>a.scope===""&&a.prefix===r);if(!s)return;let o=hn(s.root+e.slice(r.length),this.files.paths);return o?{path:o,via:"inferred"}:void 0}}function Ho(e,t){let n=e.filter((o)=>es.test(o.path)),r=n.flatMap((o)=>o.externalImports.map((a)=>({from:o.path,spec:a}))),s=Ac.create(t,{infer:r});for(let o of n){let a=[],l=new Set(o.imports);for(let c of o.externalImports){let u=s.resolve(c,o.path);if(u&&u.path!==o.path)l.add(u.path);else if(!u)a.push(c)}o.imports=[...l].sort(),o.externalImports=a}return s}var ts=["opencode.json","opencode.jsonc"];function XR(e){let t=Bun.JSONC;if(t)try{return t.parse(e)}catch{return}return Cc(e)}function Ko(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function ih(e,t){let n={...e};for(let[r,s]of Object.entries(t)){let o=n[r];n[r]=Ko(o)&&Ko(s)?ih(o,s):s}return n}function YR(e,t){if(e.OPENCODE_CONFIG_DIR)return e.OPENCODE_CONFIG_DIR;let n=e.XDG_CONFIG_HOME?e.XDG_CONFIG_HOME:Pt.join(t,".config");return Pt.join(n,"opencode")}function ZR(e,t){if(t==="win32"){let n=e.ProgramData||e.PROGRAMDATA||e.ALLUSERSPROFILE||"C:\\ProgramData";return Pt.join(n,"opencode")}if(t==="darwin")return"/Library/Application Support/opencode";return"/etc/opencode"}function ns(e){try{return zR(e)}catch{return Pt.resolve(e)}}function QR(e){try{return rh(e).isFile()}catch{return!1}}function e$(e){try{return rh(e).isDirectory()}catch{return!1}}function t$(e){let t=[],n=Pt.resolve(e);for(;;){t.push(n);let r=Pt.dirname(n);if(r===n)return t;n=r}}function n$(e){let t=(n)=>n==="1"||n?.toLowerCase()==="true";return t(e.OPENCODE_CONFIG_PROJECT_DISABLE)||t(e.OPENCODE_DISABLE_PROJECT_CONFIG)}function r$(e={}){let t=e.env??process.env,n=e.home??JR.homedir(),r=e.platform??process.platform,s=YR(t,n),o=ZR(t,r),a=ts.map((u)=>({kind:"global",path:Pt.join(s,u)}));if(t.OPENCODE_CONFIG)a.push({kind:"explicit",path:Pt.resolve(t.OPENCODE_CONFIG)});let l=e.cwd??process.cwd(),c=[s,o].map(ns);if(!n$(t)&&!c.includes(ns(l))){let u=[s,o].flatMap((f)=>ts.map((p)=>ns(Pt.join(f,p)))),d=t$(l).reverse();for(let f of d)for(let p of ts){let h=Pt.join(f,p);if(!u.includes(ns(h)))a.push({kind:"project",path:h})}for(let f of d){let p=Pt.join(f,".opencode");if(c.includes(ns(p))||!e$(p))continue;for(let h of ts)a.push({kind:"project-dir",path:Pt.join(p,h)})}}if(t.OPENCODE_CONFIG_CONTENT)a.push({kind:"content",path:"OPENCODE_CONFIG_CONTENT"});for(let u of ts)a.push({kind:"system",path:Pt.join(o,u)});return a}function sh(e={}){let t=e.env??process.env,n=[],r={files:n};for(let s of r$(e)){let o;if(s.kind==="content")o=t.OPENCODE_CONFIG_CONTENT??"";else{if(!QR(s.path))continue;try{o=VR(s.path,"utf8")}catch{continue}}n.push(s);let a=XR(o);if(!Ko(a))continue;if(typeof a.model==="string"&&a.model.trim())r.model=a.model.trim(),r.modelFile=s;if(Ko(a.providers)&&!i$(s))r.providers=ih(r.providers??{},a.providers)}return r}function i$(e){return e.kind==="project"||e.kind==="project-dir"}function zr(e){if(e.kind==="content")return"the OPENCODE_CONFIG_CONTENT environment variable";if(e.kind==="system")return`${e.path} (OpenCode system config)`;return e.path}import et from"path";import{existsSync as hP}from"fs";import{copyFile as mP,readFile as Rl,writeFile as Ur}from"fs/promises";import{join as oh}from"path";import{homedir as s$}from"os";function o$(){let e=process.env.XDG_CONFIG_HOME||oh(s$(),".config");return oh(e,"diffloupe","config.json")}var Zn=null;async function Jr(){if(Zn!==null)return Zn;let e=Bun.file(o$());if(!await e.exists())return Zn={},Zn;try{let t=await e.text();return Zn=JSON.parse(t),Zn}catch{return Zn={},Zn}}import Qe from"path";import y$ from"path";import{promises as Xr}from"fs";import a$ from"path";async function Yr(e){try{return await Xr.access(e),!0}catch{return!1}}function _t(e){return Xr.readFile(e,"utf8")}async function Go(e){return JSON.parse(await _t(e))}async function Fe(e,t){await Xr.mkdir(a$.dirname(e),{recursive:!0}),await Xr.writeFile(e,t,"utf8")}async function mn(e,t){await Fe(e,JSON.stringify(t,null,2))}async function Qt(e){await Xr.rm(e,{force:!0})}async function Cn(e){await Xr.mkdir(e,{recursive:!0})}async function ah(e){try{let t=await _t(e);if(t==="")return 0;return t.replace(/\n$/,"").split(`
107
+ `).length}catch{return null}}rs();async function dh(e,t,n){return is(await oe("git",["-C",e,"-c","diff.renames=true","diff","--unified=0",`${t}..${n}`]))}function*gn(e){let t,n=!1,r=0,s=0;for(let o of e.split(`
108
+ `)){if(r>0||s>0){if(!o.startsWith("\\"))if(o.startsWith("-"))r--;else if(o.startsWith("+"))s--;else r--,s--;yield{file:t,line:o};continue}if(o.startsWith("diff --git ")){n=!1,t=void 0;continue}if(o.startsWith("--- ")){n=!0;continue}if(n&&o.startsWith("+++ ")){n=!1;let l=o.slice(4).trim();t=l==="/dev/null"?void 0:l.replace(/^b\//,""),yield{file:t,line:o};continue}n=!1;let a=/^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(o);if(a)r=a[1]===void 0?1:Number(a[1]),s=a[2]===void 0?1:Number(a[2]);yield{file:t,line:o}}}function fh(e){let t=[],n=0,r=0,s=0,o=0;for(let a of e.split(`
107
109
  `)){if(n>0||r>0){if(a.startsWith("\\")||a.startsWith("-")){if(a.startsWith("-"))n--;t.push(`${" ".repeat(o)} ${a}`);continue}if(a.startsWith("+"))r--;else n--,r--;t.push(`${String(s++).padStart(o)} ${a}`);continue}let l=/^@@ -\d+(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(a);if(l)n=l[1]===void 0?1:Number(l[1]),s=Number(l[2]),r=l[3]===void 0?1:Number(l[3]),o=String(Math.max(s+r-1,1)).length;t.push(a)}return t.join(`
108
- `)}function Np(e){let t=new Map,n,r;for(let s of e.split(`
109
- `)){if(s.startsWith("diff --git "))n=void 0,r=void 0;else if(s.startsWith("--- ")){let o=s.slice(4).trim();r=o==="/dev/null"?void 0:o.replace(/^a\//,"")}else if(s.startsWith("+++ ")){let o=s.slice(4).trim();n=o==="/dev/null"?r:o.replace(/^b\//,"")}if(n)t.set(n,(t.get(n)??0)+s.length+1)}return t}var nS=40,rS=30,iS=/^(?:export\s|declare\s|async\s|function[\s*]|class\s|interface\s|type\s|enum\s|const\s|let\s|var\s|abstract\s|namespace\s|module\.exports|exports\.|struct\s|template\s*<|typedef\s|using\s|#define\s|[A-Za-z_][\w:<>,*&\s]*\s[*&]?[\w:~]+\()/;function _r(e,t){return e.split(/^(?=diff --git )/m).map((r)=>{if(!/^\+\+\+ \/dev\/null$/m.test(r))return r;let s=r.split(`
110
- `),o=s.findIndex((d)=>d.startsWith("@@ "));if(o<0)return r;let a=s.slice(o+1).filter((d)=>d.startsWith("-"));if(a.length<=nS)return r;let l=/^--- (?:a\/)?(.+)$/m.exec(r)?.[1]??"",c=a.filter((d)=>iS.test(d.slice(1))).slice(0,rS),u=r.endsWith(`
110
+ `)}function ph(e){let t=new Map,n,r;for(let s of e.split(`
111
+ `)){if(s.startsWith("diff --git "))n=void 0,r=void 0;else if(s.startsWith("--- ")){let o=s.slice(4).trim();r=o==="/dev/null"?void 0:o.replace(/^a\//,"")}else if(s.startsWith("+++ ")){let o=s.slice(4).trim();n=o==="/dev/null"?r:o.replace(/^b\//,"")}if(n)t.set(n,(t.get(n)??0)+s.length+1)}return t}var u$=40,d$=30,f$=/^(?:export\s|declare\s|async\s|function[\s*]|class\s|interface\s|type\s|enum\s|const\s|let\s|var\s|abstract\s|namespace\s|module\.exports|exports\.|struct\s|template\s*<|typedef\s|using\s|#define\s|[A-Za-z_][\w:<>,*&\s]*\s[*&]?[\w:~]+\()/;function vr(e,t){return e.split(/^(?=diff --git )/m).map((r)=>{if(!/^\+\+\+ \/dev\/null$/m.test(r))return r;let s=r.split(`
112
+ `),o=s.findIndex((d)=>d.startsWith("@@ "));if(o<0)return r;let a=s.slice(o+1).filter((d)=>d.startsWith("-"));if(a.length<=u$)return r;let l=/^--- (?:a\/)?(.+)$/m.exec(r)?.[1]??"",c=a.filter((d)=>f$.test(d.slice(1))).slice(0,d$),u=r.endsWith(`
111
113
  `)?`
112
114
  `:"";return[...s.slice(0,o),...c.length?[`@@ -1,${c.length} +0,0 @@`,...c]:[],`# Deleted file, ${a.length} lines. Only its top-level declarations are shown; read the rest with \`git show ${t.slice(0,12)}:${l}\`.`].join(`
113
- `)+u}).join("")}var Ip=" [rest of line cut]",sS=80,oS=36;function Dp(e,t){if(e.length<=t)return e;let n=e.split(/^(?=diff --git )/m).filter((a)=>a.length>0),r=new Map,s=n.map((a,l)=>({i:l,size:a.length})).sort((a,l)=>a.size-l.size),o=t;for(let[a,{i:l,size:c}]of s.entries()){let u=Math.floor(o/(s.length-a)),d=Math.min(c,u);r.set(l,d),o-=d}return n.map((a,l)=>{if(a.length<=(r.get(l)??0))return a;let c=(r.get(l)??0)-oS,u=a.replace(/\n$/,"").split(`
114
- `),d=u.findIndex((R)=>R.startsWith("@@")),f=d<0?u.length:d,p=u.slice(0,Math.min(f+1,u.length)),h=p.reduce((R,P)=>R+P.length+1,0),g=p.length;for(let R of u.slice(g)){if(h+R.length+1>c)break;p.push(R),h+=R.length+1,g++}let w=c-h-Ip.length,b=u[g];if(b!==void 0&&w>=sS)p.push(`${b.slice(0,w)}${Ip}`),g++;let x=u.length-g;if(x>0)p.push(`[${x} more lines in this file]`);return`${p.join(`
115
+ `)+u}).join("")}var lh=" [rest of line cut]",p$=80,h$=36;function hh(e,t){if(e.length<=t)return e;let n=e.split(/^(?=diff --git )/m).filter((a)=>a.length>0),r=new Map,s=n.map((a,l)=>({i:l,size:a.length})).sort((a,l)=>a.size-l.size),o=t;for(let[a,{i:l,size:c}]of s.entries()){let u=Math.floor(o/(s.length-a)),d=Math.min(c,u);r.set(l,d),o-=d}return n.map((a,l)=>{if(a.length<=(r.get(l)??0))return a;let c=(r.get(l)??0)-h$,u=a.replace(/\n$/,"").split(`
116
+ `),d=u.findIndex((S)=>S.startsWith("@@")),f=d<0?u.length:d,p=u.slice(0,Math.min(f+1,u.length)),h=p.reduce((S,P)=>S+P.length+1,0),g=p.length;for(let S of u.slice(g)){if(h+S.length+1>c)break;p.push(S),h+=S.length+1,g++}let w=c-h-lh.length,b=u[g];if(b!==void 0&&w>=p$)p.push(`${b.slice(0,w)}${lh}`),g++;let x=u.length-g;if(x>0)p.push(`[${x} more lines in this file]`);return`${p.join(`
115
117
  `)}
116
- `}).join("")}function Xi(e){let t=new Map;for(let{file:n,line:r}of pn(e)){if(n&&!t.has(n))t.set(n,[]);if(!n||!r.startsWith("@@"))continue;let s=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(r);if(!s)continue;let o=Number(s[1]),a=s[2]===void 0?1:Number(s[2]);if(a<=0)continue;t.get(n).push({start:o,end:o+a-1})}return t}var aS=20,Pp=(e,t)=>e.some((n)=>t>=n.start&&t<=n.end),lS=(e,t,n)=>e.some((r)=>t>=r.start&&t<=r.end&&n>=r.start&&n<=r.end);function Mp(e,t){let n;for(let r of e){let s=t<r.start?r.start:t>r.end?r.end:t,o=Math.abs(s-t);if(!n||o<n.distance)n={line:s,distance:o}}return n}function To(e,t,n,r){let s=r??void 0,o=e.get(t);if(!o||o.length===0)return{kind:"off-diff"};if(!Number.isFinite(n)||s!==void 0&&!Number.isFinite(s))return{kind:"off-diff"};let a=s!==void 0?Math.min(n,s):n,l=s!==void 0?Math.max(n,s):n,c=l!==a;if(c&&lS(o,a,l))return{kind:"anchorable",line:l,start_line:a};if(Pp(o,l))return{kind:"anchorable",line:l};if(c&&Pp(o,a))return{kind:"anchorable",line:a};let u=c&&o.find((h)=>h.start>=a&&h.end<=l);if(u)return{kind:"off-hunk",line:u.start};let d=Mp(o,a),f=c?Mp(o,l):d,p=!d?f:!f?d:f.distance<d.distance?f:d;if(!p||p.distance>aS)return{kind:"off-diff"};return{kind:"off-hunk",line:p.line}}bt();var fS=["node_modules/","/dist/","/build/","/.next/","/__snapshots__/",".min.js",".d.ts",".js.map","third-party/"],pS=new Set(["string","number","boolean","object","symbol","unknown","never","void","Record","Promise","Array","Object","String","Number","Boolean","Error","Partial","Required","Readonly","Pick","Omit","Map","Set","Date","JSON","Math","length","name","value","data","result","options","config","context","index","count","total","logger","console","process","buffer","return","export","import","default","function","typeof","instanceof","public","private","static","struct","class","const","enum","true","false","null"]),hS=(e)=>[...fS,...Qi].some((t)=>e.includes(t)),mS=new Set([".yml",".yaml",".json",".jsonc",".toml",".ini",".env",".py",".rb",".go",".rs",".java",".kt",".sh",".bash",".tf",".tfvars",".sql",".proto",".graphql",".gql"]),gS=new Set(["Dockerfile","Makefile","Procfile"]);function _S(e){if(Dt(e))return!0;let t=e.slice(e.lastIndexOf("/")+1);if(gS.has(t))return!0;let n=t.lastIndexOf(".");return n>0&&mS.has(t.slice(n))}var wS=(e)=>e.replace(/[.*+?^${}()|[\]\\-]/g,"\\$&");function yS(e){let t=e.trim();return/^import\b/.test(t)||/^export\s+.*\bfrom\b/.test(t)||/^#include\b/.test(t)||/\brequire\s*\(/.test(t)||/^from\b/.test(t)}function Bp(e){let t=new Set;for(let n of e.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let r=n[0];if(r.length<6)continue;if(pS.has(r))continue;if(!/^[A-Z]/.test(r))continue;t.add(r)}for(let n of e.matchAll(/["'`]([A-Za-z0-9_.-]{6,})["'`]/g)){if(n[1].includes("/")||n[1].startsWith("."))continue;t.add(n[1])}return[...t]}var qp=25;function Hp(e){return e.trim().replace(/["'`][^"'`]*["'`]/g,"~").replace(/[A-Za-z_$][A-Za-z0-9_$]*/g,"X").replace(/\d+/g,"#").replace(/\s+/g,"")}function bS(e){let t=[],n=null,r=0;for(let{file:s,line:o}of pn(e)){if(n&&s!==n.file)n=null;let a=/^@@ -\d+(?:,\d+)? \+(\d+)/.exec(o);if(a){if(!s)continue;r=Number(a[1]),n={file:s,lines:[]},t.push(n);continue}if(!n)continue;if(o.startsWith("+"))n.lines.push({kind:"add",text:o.slice(1),newLine:r++});else if(o.startsWith("-"))n.lines.push({kind:"del",text:o.slice(1),newLine:r});else if(o.startsWith(" "))n.lines.push({kind:"ctx",text:o.slice(1),newLine:r++})}return t}async function Kp(e){try{return await vS(e)}catch(t){let n=t instanceof Error?t.message:String(t);return console.error(`registry check unavailable, continuing without it: ${n}`),{findings:[],meta:{unavailable:n}}}}async function vS(e){let{repo:t,base:n,head:r}=e,s=t,o=await oe("git",["-C",s,"-c","diff.renames=true","diff","-U5",`${n}..${r}`]),a=bS(o),l=new Set(a.map((x)=>x.file)),c=new Map;for(let x of a)for(let R=0;R<x.lines.length;R++){let P=x.lines[R];if(P.kind!=="add")continue;let M=P.text.trim();if(M.length<8)continue;if(yS(M))continue;if(!/[,;]$/.test(M)&&!/^case\b/.test(M)&&!/:\s*\S+$/.test(M))continue;let k=Hp(P.text);if(k.length<4)continue;let E=Bp(P.text);if(E.length===0)continue;let D=new Set,L=0;for(let O=Math.max(0,R-5);O<=Math.min(x.lines.length-1,R+5);O++){if(O===R)continue;let U=x.lines[O];if(U.kind!=="ctx")continue;if(Hp(U.text)!==k)continue;L++;for(let I of Bp(U.text))if(!E.includes(I))D.add(I)}if(L<2||D.size<2)continue;for(let O of E){let U=`${O}@${x.file}`,I=c.get(U);if(I)for(let j of D)I.siblings.add(j);else c.set(U,{newEntry:O,file:x.file,line:P.newLine,siblings:new Set(D)})}}if(c.size===0)return{findings:[],meta:{hunks:a.length,candidates:0}};let d=(await oe("git",["-C",s,"ls-files"])).trim().split(`
117
- `).filter((x)=>x&&!hS(x)&&_S(x)),f=new Set;for(let x of c.values()){f.add(x.newEntry);for(let R of x.siblings)f.add(R)}let p=new Map;for(let x of f)p.set(x,new Set);let h=new Map,g=new Map;for(let x of f){let R=/^[A-Za-z0-9_$]+$/.test(x);if(h.set(x,R),!R)g.set(x,new RegExp(`(?<![A-Za-z0-9_$-])${wS(x)}(?![A-Za-z0-9_$-])`))}let w=0;for(let x of d){let R;try{R=await _t(dS.join(s,x))}catch{continue}if(R.length>2000000)continue;w++;let P=new Set(R.match(/[A-Za-z0-9_$]+/g)??[]);for(let M of f)if(h.get(M)?P.has(M):g.get(M).test(R))p.get(M).add(x)}let b=[];for(let x of c.values()){let R=[...x.siblings].filter((D)=>{let L=(p.get(D)??new Set).size;return L>0&&L<=qp});if(R.length<2)continue;if((p.get(x.newEntry)??new Set).size>qp)continue;let P=new Map;for(let D of R)for(let L of p.get(D)??[]){if(!P.has(L))P.set(L,[]);P.get(L).push(D)}let M=p.get(x.newEntry)??new Set,k=[],E=[];for(let[D,L]of P){if(L.length<2)continue;if(D===x.file)continue;if(M.has(D))E.push({file:D,siblingsPresent:L.sort()});else k.push({file:D,siblingsPresent:L.sort()})}if(k.length===0)continue;k.sort((D,L)=>L.siblingsPresent.length-D.siblingsPresent.length),E.sort((D,L)=>L.siblingsPresent.length-D.siblingsPresent.length),b.push({newEntry:x.newEntry,addedIn:x.file,addedAtLine:x.line,siblings:R.sort(),missingIn:k.slice(0,6),presentIn:E.slice(0,6)})}return b.sort((x,R)=>R.missingIn.length-x.missingIn.length),{findings:b,meta:{hunks:a.length,candidates:c.size,filesScanned:w,changedFiles:l.size}}}function Wp(e){if(e.length===0)return"";let t=["## Registry-completeness signals (computed, unverified)","","This diff adds entries to lists that look like registries. For each new entry, these are","files that already carry several of its sibling entries but do NOT mention the new one.","This is a mechanical text signal, not a finding. Open the files and decide whether the","omission matters. If precedent is mixed, that is itself worth asking the author about.",""];for(let n of e){t.push(`### \`${n.newEntry}\` added in \`${n.addedIn}:${n.addedAtLine}\``),t.push(`Siblings used for comparison: ${n.siblings.map((r)=>`\`${r}\``).join(", ")}`),t.push(""),t.push("Carries siblings but NOT this entry:");for(let r of n.missingIn)t.push(`- \`${r.file}\` \u2014 has ${r.siblingsPresent.map((s)=>`\`${s}\``).join(", ")}`);if(n.presentIn.length){t.push(""),t.push("Carries siblings AND this entry (convention followed here):");for(let r of n.presentIn)t.push(`- \`${r.file}\` \u2014 has ${r.siblingsPresent.map((s)=>`\`${s}\``).join(", ")}`)}t.push("")}return t.join(`
118
- `)}import Rh from"path";import{mkdirSync as Gp,readdirSync as xS,readFileSync as RS,renameSync as SS,rmSync as Vp,statSync as bc,utimesSync as $S,writeFileSync as zp}from"fs";import Xn from"path";var kS=1,vc=86400000,ES=30;class Rc{dir;hits=0;misses=0;constructor(e){this.dir=Xn.join(e,`v${kS}`)}file(e,t){return Xn.join(this.dir,e.slice(0,2),`${e}.${t}.json`)}get(e,t){let n=this.file(e,t),r;try{r=JSON.parse(RS(n,"utf8"))}catch{return this.misses++,null}this.hits++;try{if(Date.now()-bc(n).mtimeMs>vc){let s=new Date;$S(n,s,s)}}catch{}return r}set(e,t,n){let r=this.file(e,t);try{Gp(Xn.dirname(r),{recursive:!0});let s=`${r}.${process.pid}.tmp`;zp(s,JSON.stringify(n)),SS(s,r)}catch{}}prune(e=Date.now()){let t=Xn.dirname(this.dir),n=Xn.join(t,".last-prune");try{if(e-bc(n).mtimeMs<vc)return 0}catch{}try{Gp(t,{recursive:!0}),zp(n,new Date(e).toISOString())}catch{return 0}let r=0;for(let s of xc(t)){let o=Xn.join(t,s);if(s.startsWith("."))continue;if(o!==this.dir){Vp(o,{recursive:!0,force:!0});continue}for(let a of xc(o)){let l=Xn.join(o,a);for(let c of xc(l)){let u=Xn.join(l,c);try{if(e-bc(u).mtimeMs>ES*vc)Vp(u,{force:!0}),r++}catch{}}}}return r}}function xc(e){try{return xS(e)}catch{return[]}}function Jp(e,t){let n=new Set(t.split(`
118
+ `}).join("")}function is(e){let t=new Map;for(let{file:n,line:r}of gn(e)){if(n&&!t.has(n))t.set(n,[]);if(!n||!r.startsWith("@@"))continue;let s=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(r);if(!s)continue;let o=Number(s[1]),a=s[2]===void 0?1:Number(s[2]);if(a<=0)continue;t.get(n).push({start:o,end:o+a-1})}return t}var m$=20,ch=(e,t)=>e.some((n)=>t>=n.start&&t<=n.end),g$=(e,t,n)=>e.some((r)=>t>=r.start&&t<=r.end&&n>=r.start&&n<=r.end);function uh(e,t){let n;for(let r of e){let s=t<r.start?r.start:t>r.end?r.end:t,o=Math.abs(s-t);if(!n||o<n.distance)n={line:s,distance:o}}return n}function Wo(e,t,n,r){let s=r??void 0,o=e.get(t);if(!o||o.length===0)return{kind:"off-diff"};if(!Number.isFinite(n)||s!==void 0&&!Number.isFinite(s))return{kind:"off-diff"};let a=s!==void 0?Math.min(n,s):n,l=s!==void 0?Math.max(n,s):n,c=l!==a;if(c&&g$(o,a,l))return{kind:"anchorable",line:l,start_line:a};if(ch(o,l))return{kind:"anchorable",line:l};if(c&&ch(o,a))return{kind:"anchorable",line:a};let u=c&&o.find((h)=>h.start>=a&&h.end<=l);if(u)return{kind:"off-hunk",line:u.start};let d=uh(o,a),f=c?uh(o,l):d,p=!d?f:!f?d:f.distance<d.distance?f:d;if(!p||p.distance>m$)return{kind:"off-diff"};return{kind:"off-hunk",line:p.line}}bt();var b$=["node_modules/","/dist/","/build/","/.next/","/__snapshots__/",".min.js",".d.ts",".js.map","third-party/"],v$=new Set(["string","number","boolean","object","symbol","unknown","never","void","Record","Promise","Array","Object","String","Number","Boolean","Error","Partial","Required","Readonly","Pick","Omit","Map","Set","Date","JSON","Math","length","name","value","data","result","options","config","context","index","count","total","logger","console","process","buffer","return","export","import","default","function","typeof","instanceof","public","private","static","struct","class","const","enum","true","false","null"]),x$=(e)=>[...b$,...as].some((t)=>e.includes(t)),S$=new Set([".yml",".yaml",".json",".jsonc",".toml",".ini",".env",".py",".rb",".go",".rs",".java",".kt",".sh",".bash",".tf",".tfvars",".sql",".proto",".graphql",".gql"]),R$=new Set(["Dockerfile","Makefile","Procfile"]);function $$(e){if(Lt(e))return!0;let t=e.slice(e.lastIndexOf("/")+1);if(R$.has(t))return!0;let n=t.lastIndexOf(".");return n>0&&S$.has(t.slice(n))}var k$=(e)=>e.replace(/[.*+?^${}()|[\]\\-]/g,"\\$&");function E$(e){let t=e.trim();return/^import\b/.test(t)||/^export\s+.*\bfrom\b/.test(t)||/^#include\b/.test(t)||/\brequire\s*\(/.test(t)||/^from\b/.test(t)}function wh(e){let t=new Set;for(let n of e.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let r=n[0];if(r.length<6)continue;if(v$.has(r))continue;if(!/^[A-Z]/.test(r))continue;t.add(r)}for(let n of e.matchAll(/["'`]([A-Za-z0-9_.-]{6,})["'`]/g)){if(n[1].includes("/")||n[1].startsWith("."))continue;t.add(n[1])}return[...t]}var yh=25;function bh(e){return e.trim().replace(/["'`][^"'`]*["'`]/g,"~").replace(/[A-Za-z_$][A-Za-z0-9_$]*/g,"X").replace(/\d+/g,"#").replace(/\s+/g,"")}function C$(e){let t=[],n=null,r=0;for(let{file:s,line:o}of gn(e)){if(n&&s!==n.file)n=null;let a=/^@@ -\d+(?:,\d+)? \+(\d+)/.exec(o);if(a){if(!s)continue;r=Number(a[1]),n={file:s,lines:[]},t.push(n);continue}if(!n)continue;if(o.startsWith("+"))n.lines.push({kind:"add",text:o.slice(1),newLine:r++});else if(o.startsWith("-"))n.lines.push({kind:"del",text:o.slice(1),newLine:r});else if(o.startsWith(" "))n.lines.push({kind:"ctx",text:o.slice(1),newLine:r++})}return t}async function vh(e){try{return await A$(e)}catch(t){let n=t instanceof Error?t.message:String(t);return console.error(`registry check unavailable, continuing without it: ${n}`),{findings:[],meta:{unavailable:n}}}}async function A$(e){let{repo:t,base:n,head:r}=e,s=t,o=await oe("git",["-C",s,"-c","diff.renames=true","diff","-U5",`${n}..${r}`]),a=C$(o),l=new Set(a.map((x)=>x.file)),c=new Map;for(let x of a)for(let S=0;S<x.lines.length;S++){let P=x.lines[S];if(P.kind!=="add")continue;let M=P.text.trim();if(M.length<8)continue;if(E$(M))continue;if(!/[,;]$/.test(M)&&!/^case\b/.test(M)&&!/:\s*\S+$/.test(M))continue;let k=bh(P.text);if(k.length<4)continue;let E=wh(P.text);if(E.length===0)continue;let F=new Set,L=0;for(let O=Math.max(0,S-5);O<=Math.min(x.lines.length-1,S+5);O++){if(O===S)continue;let U=x.lines[O];if(U.kind!=="ctx")continue;if(bh(U.text)!==k)continue;L++;for(let I of wh(U.text))if(!E.includes(I))F.add(I)}if(L<2||F.size<2)continue;for(let O of E){let U=`${O}@${x.file}`,I=c.get(U);if(I)for(let j of F)I.siblings.add(j);else c.set(U,{newEntry:O,file:x.file,line:P.newLine,siblings:new Set(F)})}}if(c.size===0)return{findings:[],meta:{hunks:a.length,candidates:0}};let d=(await oe("git",["-C",s,"ls-files"])).trim().split(`
119
+ `).filter((x)=>x&&!x$(x)&&$$(x)),f=new Set;for(let x of c.values()){f.add(x.newEntry);for(let S of x.siblings)f.add(S)}let p=new Map;for(let x of f)p.set(x,new Set);let h=new Map,g=new Map;for(let x of f){let S=/^[A-Za-z0-9_$]+$/.test(x);if(h.set(x,S),!S)g.set(x,new RegExp(`(?<![A-Za-z0-9_$-])${k$(x)}(?![A-Za-z0-9_$-])`))}let w=0;for(let x of d){let S;try{S=await _t(y$.join(s,x))}catch{continue}if(S.length>2000000)continue;w++;let P=new Set(S.match(/[A-Za-z0-9_$]+/g)??[]);for(let M of f)if(h.get(M)?P.has(M):g.get(M).test(S))p.get(M).add(x)}let b=[];for(let x of c.values()){let S=[...x.siblings].filter((F)=>{let L=(p.get(F)??new Set).size;return L>0&&L<=yh});if(S.length<2)continue;if((p.get(x.newEntry)??new Set).size>yh)continue;let P=new Map;for(let F of S)for(let L of p.get(F)??[]){if(!P.has(L))P.set(L,[]);P.get(L).push(F)}let M=p.get(x.newEntry)??new Set,k=[],E=[];for(let[F,L]of P){if(L.length<2)continue;if(F===x.file)continue;if(M.has(F))E.push({file:F,siblingsPresent:L.sort()});else k.push({file:F,siblingsPresent:L.sort()})}if(k.length===0)continue;k.sort((F,L)=>L.siblingsPresent.length-F.siblingsPresent.length),E.sort((F,L)=>L.siblingsPresent.length-F.siblingsPresent.length),b.push({newEntry:x.newEntry,addedIn:x.file,addedAtLine:x.line,siblings:S.sort(),missingIn:k.slice(0,6),presentIn:E.slice(0,6)})}return b.sort((x,S)=>S.missingIn.length-x.missingIn.length),{findings:b,meta:{hunks:a.length,candidates:c.size,filesScanned:w,changedFiles:l.size}}}function xh(e){if(e.length===0)return"";let t=["## Registry-completeness signals (computed, unverified)","","This diff adds entries to lists that look like registries. For each new entry, these are","files that already carry several of its sibling entries but do NOT mention the new one.","This is a mechanical text signal, not a finding. Open the files and decide whether the","omission matters. If precedent is mixed, that is itself worth asking the author about.",""];for(let n of e){t.push(`### \`${n.newEntry}\` added in \`${n.addedIn}:${n.addedAtLine}\``),t.push(`Siblings used for comparison: ${n.siblings.map((r)=>`\`${r}\``).join(", ")}`),t.push(""),t.push("Carries siblings but NOT this entry:");for(let r of n.missingIn)t.push(`- \`${r.file}\` \u2014 has ${r.siblingsPresent.map((s)=>`\`${s}\``).join(", ")}`);if(n.presentIn.length){t.push(""),t.push("Carries siblings AND this entry (convention followed here):");for(let r of n.presentIn)t.push(`- \`${r.file}\` \u2014 has ${r.siblingsPresent.map((s)=>`\`${s}\``).join(", ")}`)}t.push("")}return t.join(`
120
+ `)}import Vh from"path";import{mkdirSync as Sh,readdirSync as O$,readFileSync as I$,renameSync as P$,rmSync as Rh,statSync as Lc,utimesSync as M$,writeFileSync as $h}from"fs";import er from"path";var T$=1,jc=86400000,D$=30;class Bc{dir;hits=0;misses=0;constructor(e){this.dir=er.join(e,`v${T$}`)}file(e,t){return er.join(this.dir,e.slice(0,2),`${e}.${t}.json`)}get(e,t){let n=this.file(e,t),r;try{r=JSON.parse(I$(n,"utf8"))}catch{return this.misses++,null}this.hits++;try{if(Date.now()-Lc(n).mtimeMs>jc){let s=new Date;M$(n,s,s)}}catch{}return r}set(e,t,n){let r=this.file(e,t);try{Sh(er.dirname(r),{recursive:!0});let s=`${r}.${process.pid}.tmp`;$h(s,JSON.stringify(n)),P$(s,r)}catch{}}prune(e=Date.now()){let t=er.dirname(this.dir),n=er.join(t,".last-prune");try{if(e-Lc(n).mtimeMs<jc)return 0}catch{}try{Sh(t,{recursive:!0}),$h(n,new Date(e).toISOString())}catch{return 0}let r=0;for(let s of Uc(t)){let o=er.join(t,s);if(s.startsWith("."))continue;if(o!==this.dir){Rh(o,{recursive:!0,force:!0});continue}for(let a of Uc(o)){let l=er.join(o,a);for(let c of Uc(l)){let u=er.join(l,c);try{if(e-Lc(u).mtimeMs>D$*jc)Rh(u,{force:!0}),r++}catch{}}}}return r}}function Uc(e){try{return O$(e)}catch{return[]}}function kh(e,t){let n=new Set(t.split(`
119
121
  `).map((s)=>s.trim()).filter(Boolean)),r=new Map;for(let s of e.split(`
120
- `)){let o=s.indexOf("\t");if(o<0)continue;let[a,l,c]=s.slice(0,o).split(" "),u=s.slice(o+1);if(!l||a==="160000"||c!=="0"||n.has(u))continue;r.set(u,l)}return r}Ji();import{execFileSync as AS}from"child_process";import{builtinModules as CS}from"module";import{existsSync as OS,readFileSync as IS}from"fs";import{join as PS,posix as En}from"path";function MS(e,t){return{paths:new Set(t),read(n){let r=PS(e,n);try{return OS(r)?IS(r,"utf8"):void 0}catch{return}}}}function Go(e){let t=AS("git",["-C",e,"ls-files"],{encoding:"utf8",maxBuffer:268435456});return MS(e,t.split(`
121
- `).filter(Boolean))}var Xp=[".ts",".tsx",".d.ts",".js",".jsx",".mts",".cts",".mjs",".cjs"],TS={".js":[".ts",".tsx"],".jsx":[".tsx"],".mjs":[".mts"],".cjs":[".cts"]},es=/\.(?:d\.ts|tsx?|jsx?|mts|cts|mjs|cjs)$/;function hn(e,t){let n=En.normalize(e).replace(/^\.\//,"");if(n.startsWith("../"))return;if(t.has(n))return n;let r=En.extname(n);for(let s of TS[r]??[]){let o=n.slice(0,-r.length)+s;if(t.has(o))return o}for(let s of Xp)if(t.has(n+s))return n+s;for(let s of Xp)if(t.has(`${n}/index${s}`))return`${n}/index${s}`;return}function Ec(e){let t="",n=0;while(n<e.length){let r=e[n];if(r==='"'){let s=n++;while(n<e.length&&e[n]!=='"')n+=e[n]==="\\"?2:1;t+=e.slice(s,++n)}else if(r==="/"&&e[n+1]==="/")while(n<e.length&&e[n]!==`
122
- `)n++;else if(r==="/"&&e[n+1]==="*"){let s=e.indexOf("*/",n+2);n=s===-1?e.length:s+2}else t+=r,n++}try{return JSON.parse(t.replace(/,(\s*[}\]])/g,"$1"))}catch{return}}function Yn(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var FS=/(^|\/)(tsconfig[^/]*|jsconfig[^/]*)\.json$/;function An(e){let t=En.dirname(e);return t==="."?"":t}function ft(e,t){return En.normalize(e?`${e}/${t}`:t).replace(/^\.\//,"").replace(/^\.$/,"")}function Vo(e,t){let n=e.read(t);if(n===void 0)return;let r=Ec(n);return Yn(r)?r:void 0}function NS(e,t,n){if(e.startsWith(".")||e.startsWith("/")){let s=ft(t,e);return s.endsWith(".json")?s:`${s}.json`}return(e.endsWith(".json")?[`node_modules/${e}`]:[`node_modules/${e}/tsconfig.json`,`node_modules/${e}.json`]).find((s)=>n.read(s)!==void 0)}function $c(e,t,n=new Set){if(n.has(t))return{};n.add(t);let r=Vo(e,t);if(!r)return{};let s=An(t),o={},a=r.extends;for(let c of typeof a==="string"?[a]:Array.isArray(a)?a:[]){if(typeof c!=="string")continue;let u=NS(c,s,e);if(u)o={...o,...$c(e,u,n)}}let l=Yn(r.compilerOptions)?r.compilerOptions:{};if(typeof l.baseUrl==="string")o.baseUrl=l.baseUrl,o.baseUrlFrom=s;if(Yn(l.paths)){let c={};for(let[u,d]of Object.entries(l.paths))if(Array.isArray(d))c[u]=d.filter((f)=>typeof f==="string");o.paths=c,o.pathsFrom=s}return o}function DS(e,t){let n=Vo(e,t)?.references;if(!Array.isArray(n))return[];let r=An(t);return n.flatMap((s)=>{if(!Yn(s)||typeof s.path!=="string")return[];let o=ft(r,s.path);return[o.endsWith(".json")?o:`${o}/tsconfig.json`]})}function LS(e,t,n){let r=t.baseUrl!==void 0?ft(t.baseUrlFrom??e,t.baseUrl):void 0,s=[];for(let o of[t,...n]){if(!o.paths)continue;let a=o.baseUrl!==void 0?ft(o.baseUrlFrom??e,o.baseUrl):o.pathsFrom??e;for(let[l,c]of Object.entries(o.paths)){if(s.some((u)=>u.pattern===l))continue;s.push({pattern:l,targets:c.map((u)=>ft(a,u))})}}return{dir:e,...r!==void 0?{baseUrl:r}:{},paths:s}}function jS(e){let t=new Map,n=[...e.paths].filter((r)=>FS.test(r)&&!r.includes("node_modules/"));for(let r of["tsconfig.json","jsconfig.json"])for(let s of n){if(En.basename(s)!==r)continue;let o=An(s);if(t.has(o))continue;let a=$c(e,s),l=a.paths?[]:DS(e,s).map((c)=>$c(e,c));t.set(o,LS(o,a,l))}return t}function Zp(e,t){let n=e.indexOf("*");if(n===-1)return e===t?"":void 0;let r=e.slice(0,n),s=e.slice(n+1);if(t.length<r.length+s.length)return;if(!t.startsWith(r)||!t.endsWith(s))return;return t.slice(r.length,t.length-s.length)}function kc(e){let t=e.indexOf("*");return t===-1?1/0:t}function US(e,t,n){let r;for(let s of e){let o=Zp(s.pattern,t);if(o===void 0)continue;if(!r||kc(s.pattern)>kc(r.rule.pattern))r={rule:s,capture:o}}if(!r)return;for(let s of r.rule.targets){let o=hn(s.replace("*",r.capture),n);if(o)return o}return}var BS=["source","development","import","module","node","require","browser","default","types"];function Wo(e){if(typeof e==="string")return e;if(Array.isArray(e)){for(let t of e){let n=Wo(t);if(n)return n}return}if(!Yn(e))return;for(let t of BS)if(t in e)return Wo(e[t]);for(let t of Object.values(e)){let n=Wo(t);if(n)return n}return}function Qp(e,t,n,r){let s;for(let[o,a]of Object.entries(e)){let l=Zp(o,t);if(l===void 0)continue;let c=Wo(a);if(!c)continue;let u=kc(o);if(!s||u>s.len)s={target:c,capture:l,len:u}}if(!s)return;return eh(ft(n,s.target.replaceAll("*",s.capture)),n,r)}function eh(e,t,n){let r=hn(e,n);if(r)return r;let s=t?e.slice(t.length+1):e,o=/^(dist|lib|build|out|js)\/(.*)$/.exec(s);if(!o)return;for(let a of o[1]==="js"?["ts","src"]:["src"]){let l=hn(ft(t,`${a}/${o[2]}`).replace(es,""),n);if(l)return l}return}function qS(e){let t=new Map;for(let n of e.paths){if(En.basename(n)!=="package.json"||n.includes("node_modules/"))continue;let r=Vo(e,n);if(!r)continue;let s=[r.source,r.module,r.main,r.types,r.typings].filter((o)=>typeof o==="string");t.set(An(n),{dir:An(n),...typeof r.name==="string"?{name:r.name}:{},...Yn(r.imports)?{imports:r.imports}:{},...r.exports!==void 0?{exports:r.exports}:{},entry:s})}return t}function HS(e,t){let n=new Set;for(let r of t.keys()){let s=Vo(e,ft(r,"package.json"));for(let o of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let a=s?.[o];if(Yn(a))for(let l of Object.keys(a))n.add(l)}}return n}function Sc(e){let t=e.split("/");return e.startsWith("@")?t.slice(0,2).join("/"):t[0]}function KS(e,t,n){let r=t?`./${t}`:".";if(e.exports!==void 0){let s=Yn(e.exports)&&Object.keys(e.exports).some((a)=>a.startsWith("."))?e.exports:{".":e.exports},o=Qp(s,r,e.dir,n);if(o)return o}if(!t){for(let s of e.entry){let o=eh(ft(e.dir,s),e.dir,n);if(o)return o}return hn(ft(e.dir,"src/index"),n)??hn(ft(e.dir,"index"),n)}return hn(ft(e.dir,t),n)??hn(ft(e.dir,`src/${t}`),n)}var WS=new Set(CS);function GS(e){let t=e.indexOf("/");if(t<=0)return;let n=e.slice(0,t);return/^[@~#$]/.test(n)?`${n}/`:void 0}class th{byLast=new Map;constructor(e){for(let t of e){if(!es.test(t)||t.includes("node_modules/"))continue;let n=t.replace(es,"");if(this.add(n),En.basename(n)==="index")this.add(An(n))}}add(e){if(!e)return;let t=En.basename(e),n=this.byLast.get(t);if(n)n.push(e);else this.byLast.set(t,[e])}roots(e){let t=e.replace(es,"").replace(/\/$/,""),n=this.byLast.get(En.basename(t))??[],r=new Set;for(let s of n)if(s===t)r.add("");else if(s.endsWith(`/${t}`))r.add(s.slice(0,s.length-t.length));return[...r]}}var VS=0.6,Yp=/^[@~#$]\/$/;function nh(e){let t=GS(e);if(t)return{prefix:t,bare:!1};let n=e.indexOf("/");return n>0?{prefix:e.slice(0,n+1),bare:!0}:void 0}function zS(e,t,n){let r=new Map;for(let{from:a,spec:l}of e){let c=nh(l);if(!c)continue;let u=n(a),d=`${u}\x00${c.prefix}`,f=r.get(d);if(!f)r.set(d,f={scope:u,...c,specs:new Set});f.specs.add(l)}let s=new th(t),o=[];for(let{scope:a,prefix:l,bare:c,specs:u}of r.values()){let d=new Map;for(let b of u)for(let x of s.roots(c?b:b.slice(l.length))){if(a&&x!==a&&!x.startsWith(`${a}/`))continue;d.set(x,(d.get(x)??0)+1)}let f=[...d].sort((b,x)=>x[1]-b[1]||b[0].length-x[0].length),[p,h]=f;if(!p)continue;let[g,w]=p;if(h&&h[1]===w)continue;if(w<VS*u.size)continue;if(w<2&&!Yp.test(l))continue;if(!c&&!Yp.test(l)&&g==="")continue;o.push({scope:a,prefix:l,root:c?g+l:g,hits:w,total:u.size})}return o.sort((a,l)=>a.scope.localeCompare(l.scope)||a.prefix.localeCompare(l.prefix))}class Ac{files;aliases;tsProjects;packages;workspaces=new Map;deps;nearestCache=new Map;constructor(e,t){this.files=e;this.tsProjects=jS(e),this.packages=qS(e);for(let r of this.packages.values())if(r.name)this.workspaces.set(r.name,r);this.deps=HS(e,this.packages);for(let r of e.paths)for(let s of r.matchAll(/(?:^|\/)node_modules\/((?:@[^/]+\/)?[^/]+)\//g))this.deps.add(s[1]);let n=[];if(t.infer){for(let r of t.infer)if(this.isCandidateAlias(r.spec)&&!this.resolveConfigured(r.spec,r.from))n.push(r)}this.aliases=zS(n,e.paths,(r)=>this.nearest(r).pkg?.dir??"")}static create(e,t={}){return new Ac(e,t)}isExternal(e){if(e.startsWith("node:")||WS.has(Sc(e)))return!0;return this.deps.has(Sc(e))}resolve(e,t){if(e.startsWith(".")){let r=hn(ft(An(t),e),this.files.paths);return r?{path:r,via:"relative"}:void 0}if(e.startsWith("/"))return;let n=this.resolveConfigured(e,t);if(n)return n;if(!this.isCandidateAlias(e))return;return this.resolveInferred(e,t)}isCandidateAlias(e){if(e.startsWith(".")||e.startsWith("/")||e.includes(":"))return!1;return!this.isExternal(e)}nearest(e){let t=An(e),n=this.nearestCache.get(t);if(n)return n;let r,s;for(let a=t;;a=An(a))if(r??=this.tsProjects.get(a),s??=this.packages.get(a),r&&s||a==="")break;let o={...r?{ts:r}:{},...s?{pkg:s}:{}};return this.nearestCache.set(t,o),o}resolveConfigured(e,t){let{ts:n,pkg:r}=this.nearest(t),s=this.files.paths;if(n){let l=US(n.paths,e,s);if(l)return{path:l,via:"tsconfig"}}if(e.startsWith("#")&&r?.imports){let l=Qp(r.imports,e,r.dir,s);if(l)return{path:l,via:"package-imports"}}let o=Sc(e),a=this.workspaces.get(o);if(a){let l=KS(a,e.slice(o.length+1),s);if(l)return{path:l,via:"workspace"}}if(n?.baseUrl!==void 0&&!this.isExternal(e)){let l=hn(ft(n.baseUrl,e),s);if(l)return{path:l,via:"base-url"}}return}resolveInferred(e,t){let n=this.nearest(t).pkg?.dir??"",r=nh(e)?.prefix;if(!r)return;let s=this.aliases.find((a)=>a.scope===n&&a.prefix===r)??this.aliases.find((a)=>a.scope===""&&a.prefix===r);if(!s)return;let o=hn(s.root+e.slice(r.length),this.files.paths);return o?{path:o,via:"inferred"}:void 0}}function zo(e,t){let n=e.filter((o)=>es.test(o.path)),r=n.flatMap((o)=>o.externalImports.map((a)=>({from:o.path,spec:a}))),s=Ac.create(t,{infer:r});for(let o of n){let a=[],l=new Set(o.imports);for(let c of o.externalImports){let u=s.resolve(c,o.path);if(u&&u.path!==o.path)l.add(u.path);else if(!u)a.push(c)}o.imports=[...l].sort(),o.externalImports=a}return s}bt();var A$=["node_modules/","/dist/","/build/","/.next/","/__snapshots__/",".min.js",".d.ts",".js.map","third-party/"],ss=new Set(["length","name","data","value","values","result","results","error","index","sort","update","commit","title","stringify","parse","resume","first","last","evaluate","process","context","options","config","state","status","start","stop","close","open","read","write","size","count","type","kind","path","file","line","text","message","handler","callback","toString","constructor","entries","keys","items","list","item","node","root","child","children","params","args","props","info","detail","details","target","source","output","input","buffer","offset","reset","clear","flush","init","create","destroy"]);function C$(e){return[...A$,...Qi].some((t)=>e.includes(t)||!t.startsWith("/")&&e.startsWith(t))}var O$=(e)=>Math.ceil(e.length/3.6);async function Sh(e){let{repo:t,base:n,head:r}=e,s=e.budgetTokens??14000,o=Date.now(),a=(await oe("git",["-C",t,"-c","diff.renames=true","diff","--name-only",`${n}..${r}`])).split(`
122
+ `)){let o=s.indexOf("\t");if(o<0)continue;let[a,l,c]=s.slice(0,o).split(" "),u=s.slice(o+1);if(!l||a==="160000"||c!=="0"||n.has(u))continue;r.set(u,l)}return r}rs();bt();var mk=["node_modules/","/dist/","/build/","/.next/","/__snapshots__/",".min.js",".d.ts",".js.map","third-party/"],hs=new Set(["length","name","data","value","values","result","results","error","index","sort","update","commit","title","stringify","parse","resume","first","last","evaluate","process","context","options","config","state","status","start","stop","close","open","read","write","size","count","type","kind","path","file","line","text","message","handler","callback","toString","constructor","entries","keys","items","list","item","node","root","child","children","params","args","props","info","detail","details","target","source","output","input","buffer","offset","reset","clear","flush","init","create","destroy"]);function gk(e){return[...mk,...as].some((t)=>e.includes(t)||!t.startsWith("/")&&e.startsWith(t))}var _k=(e)=>Math.ceil(e.length/3.6);async function zh(e){let{repo:t,base:n,head:r}=e,s=e.budgetTokens??14000,o=Date.now(),a=(await oe("git",["-C",t,"-c","diff.renames=true","diff","--name-only",`${n}..${r}`])).split(`
123
123
  `).map((T)=>T.trim()).filter(Boolean),l=new Set(a),c=await oe("git",["-C",t,"ls-files","-s"]),u=c.split(`
124
- `).map((T)=>T.slice(T.indexOf("\t")+1).trim()).filter((T)=>T&&!C$(T)&&Dt(T)!==null),d=e.cacheDir?new Rc(e.cacheDir):null,f=d?Jp(c,await oe("git",["-C",t,"diff","--name-only"])):new Map;await Promise.resolve().then(() => Uc());let g,w=()=>g??=ti.create().then(async(T)=>(await T.warmup(["typescript","tsx","cpp"]),T)),b=async(T,B)=>{let z=await _t(Rh.join(t,T)).catch(()=>null);return z===null?null:(await w()).parseRaw(z,T,B)},x=new Map,R=Date.now();for(let T of u){let B=Dt(T);if(!B)continue;try{let z=f.get(T),te=z?d?.get(z,B)??null:null;if(!te){if(te=await b(T,B),te&&z)d?.set(z,B,te)}if(te)x.set(T,jc(te,T,t))}catch{}}let P=Date.now()-R;d?.prune();let M=zo([...x.values()],Go(t)),k=new Map;for(let[T,B]of x)for(let z of B.imports??[]){if(!k.has(z))k.set(z,new Set);k.get(z).add(T)}let E=new Map;for(let[T,B]of x)for(let z of B.symbols??[]){if(z.kind==="variable"&&!z.exported)continue;let te=E.get(z.name);if(te){if(te.length<8)te.push(T)}else E.set(z.name,[T])}let D=await oe("git",["-C",t,"-c","diff.renames=true","diff","-U0",`${n}..${r}`]),L=new Set;for(let{file:T,line:B}of pn(D)){if(!T||!Dt(T))continue;if(B.startsWith("+++ "))continue;if(!/^[+-]/.test(B))continue;for(let z of B.matchAll(/[A-Za-z_][A-Za-z0-9_]{3,}/g))L.add(z[0])}let O=await oe("git",["-C",t,"-c","diff.renames=true","diff","-U4",`${n}..${r}`]),U=new Set;{let T=[...pn(O)];for(let B=0;B<T.length;B++){if(!T[B].line.startsWith("+")||T[B].line.startsWith("+++"))continue;if(!T[B].file||!Dt(T[B].file))continue;for(let z=Math.max(0,B-4);z<=Math.min(T.length-1,B+4);z++){if(T[z].file!==T[B].file)continue;let te=T[z].line;if(!te.startsWith(" "))continue;for(let we of te.matchAll(/[A-Za-z_][A-Za-z0-9_]{7,}/g)){let Ne=we[0];if(ss.has(Ne.toLowerCase()))continue;if(!/[A-Z_]/.test(Ne))continue;if(l.size&&E.has(Ne))U.add(Ne)}}}}let I=new Map,j=new Map,H=(T,B,z)=>{if(!x.has(T)||l.has(T))return;if(I.set(T,(I.get(T)??0)+B),!j.has(T))j.set(T,new Set);j.get(T).add(z)};for(let T of a){for(let B of x.get(T)?.imports??[])H(B,6,"imported by a changed file");for(let B of k.get(T)??[])H(B,5,"imports a changed file")}let ve=new Set;for(let T of a)for(let B of x.get(T)?.symbols??[])ve.add(B.name);let Se=new Map;if(U.size){let T=[...U];for(let[B]of x){if(l.has(B))continue;let z;try{z=await _t(Rh.join(t,B))}catch{continue}if(z.length>2000000)continue;let te=new Set(z.match(/[A-Za-z0-9_$]+/g)??[]);for(let we of T)if(te.has(we)){if(!Se.has(B))Se.set(B,new Set);Se.get(B).add(we)}}}for(let[T,B]of Se)for(let z of B){let te=[...Se.values()].filter((we)=>we.has(z)).length;if(te>12)continue;H(T,te<=4?8:4,`also references \`${z}\``)}for(let T of L){if(T.length<6)continue;if(ss.has(T)||ss.has(T.toLowerCase()))continue;if(!/[A-Z_]/.test(T))continue;if(ve.has(T))continue;let B=E.get(T);if(!B||B.length>3)continue;let z=B.length===1?4:2;for(let te of B)H(te,z,`defines \`${T}\``)}let ne=[...I.entries()].sort((T,B)=>B[1]-T[1]),ce=ne.map(([T])=>T);if(process.env.MAP_DEBUG)for(let[T,B]of ne.slice(0,30))console.error(String(B).padStart(4),T,"|",[...j.get(T)??[]].slice(0,4).join("; "));let Be=(T,B)=>{let z=x.get(T);if(!z)return"";let te=(z.symbols??[]).filter((Ye)=>Ye.exported||z.language==="cpp"||Ye.kind!=="variable"),we=te.slice(0,40).map((Ye)=>` ${Ye.line} ${Ye.kind} ${Ye.signature||Ye.name}`),Ne=te.length>40?` \u2026 ${te.length-40} more
124
+ `).map((T)=>T.slice(T.indexOf("\t")+1).trim()).filter((T)=>T&&!gk(T)&&Lt(T)!==null),d=e.cacheDir?new Bc(e.cacheDir):null,f=d?kh(c,await oe("git",["-C",t,"diff","--name-only"])):new Map;await Promise.resolve().then(() => Qc());let g,w=()=>g??=oi.create().then(async(T)=>(await T.warmup(["typescript","tsx","cpp"]),T)),b=async(T,B)=>{let z=await _t(Vh.join(t,T)).catch(()=>null);return z===null?null:(await w()).parseRaw(z,T,B)},x=new Map,S=Date.now();for(let T of u){let B=Lt(T);if(!B)continue;try{let z=f.get(T),te=z?d?.get(z,B)??null:null;if(!te){if(te=await b(T,B),te&&z)d?.set(z,B,te)}if(te)x.set(T,Zc(te,T,t))}catch{}}let P=Date.now()-S;d?.prune();let M=Ho([...x.values()],Bo(t)),k=new Map;for(let[T,B]of x)for(let z of B.imports??[]){if(!k.has(z))k.set(z,new Set);k.get(z).add(T)}let E=new Map;for(let[T,B]of x)for(let z of B.symbols??[]){if(z.kind==="variable"&&!z.exported)continue;let te=E.get(z.name);if(te){if(te.length<8)te.push(T)}else E.set(z.name,[T])}let F=await oe("git",["-C",t,"-c","diff.renames=true","diff","-U0",`${n}..${r}`]),L=new Set;for(let{file:T,line:B}of gn(F)){if(!T||!Lt(T))continue;if(B.startsWith("+++ "))continue;if(!/^[+-]/.test(B))continue;for(let z of B.matchAll(/[A-Za-z_][A-Za-z0-9_]{3,}/g))L.add(z[0])}let O=await oe("git",["-C",t,"-c","diff.renames=true","diff","-U4",`${n}..${r}`]),U=new Set;{let T=[...gn(O)];for(let B=0;B<T.length;B++){if(!T[B].line.startsWith("+")||T[B].line.startsWith("+++"))continue;if(!T[B].file||!Lt(T[B].file))continue;for(let z=Math.max(0,B-4);z<=Math.min(T.length-1,B+4);z++){if(T[z].file!==T[B].file)continue;let te=T[z].line;if(!te.startsWith(" "))continue;for(let we of te.matchAll(/[A-Za-z_][A-Za-z0-9_]{7,}/g)){let Ne=we[0];if(hs.has(Ne.toLowerCase()))continue;if(!/[A-Z_]/.test(Ne))continue;if(l.size&&E.has(Ne))U.add(Ne)}}}}let I=new Map,j=new Map,H=(T,B,z)=>{if(!x.has(T)||l.has(T))return;if(I.set(T,(I.get(T)??0)+B),!j.has(T))j.set(T,new Set);j.get(T).add(z)};for(let T of a){for(let B of x.get(T)?.imports??[])H(B,6,"imported by a changed file");for(let B of k.get(T)??[])H(B,5,"imports a changed file")}let ve=new Set;for(let T of a)for(let B of x.get(T)?.symbols??[])ve.add(B.name);let Re=new Map;if(U.size){let T=[...U];for(let[B]of x){if(l.has(B))continue;let z;try{z=await _t(Vh.join(t,B))}catch{continue}if(z.length>2000000)continue;let te=new Set(z.match(/[A-Za-z0-9_$]+/g)??[]);for(let we of T)if(te.has(we)){if(!Re.has(B))Re.set(B,new Set);Re.get(B).add(we)}}}for(let[T,B]of Re)for(let z of B){let te=[...Re.values()].filter((we)=>we.has(z)).length;if(te>12)continue;H(T,te<=4?8:4,`also references \`${z}\``)}for(let T of L){if(T.length<6)continue;if(hs.has(T)||hs.has(T.toLowerCase()))continue;if(!/[A-Z_]/.test(T))continue;if(ve.has(T))continue;let B=E.get(T);if(!B||B.length>3)continue;let z=B.length===1?4:2;for(let te of B)H(te,z,`defines \`${T}\``)}let ne=[...I.entries()].sort((T,B)=>B[1]-T[1]),ce=ne.map(([T])=>T);if(process.env.MAP_DEBUG)for(let[T,B]of ne.slice(0,30))console.error(String(B).padStart(4),T,"|",[...j.get(T)??[]].slice(0,4).join("; "));let qe=(T,B)=>{let z=x.get(T);if(!z)return"";let te=(z.symbols??[]).filter((Ye)=>Ye.exported||z.language==="cpp"||Ye.kind!=="variable"),we=te.slice(0,40).map((Ye)=>` ${Ye.line} ${Ye.kind} ${Ye.signature||Ye.name}`),Ne=te.length>40?` \u2026 ${te.length-40} more
125
125
  `:"";return`### ${T} (${z.lines} lines)${B}
126
126
  ${we.join(`
127
127
  `)}
128
- ${Ne}`},ze=[],Je=0,Xe=(T,B=s)=>{let z=O$(T);if(Je+z>B)return!1;return ze.push(T),Je+=z,!0},nt=new Map;for(let[T,B]of x){let z=T.split("/"),te=z.slice(0,Math.min(3,z.length-1)).join("/")||".",we=nt.get(te)??{files:0,symbols:0};we.files++,we.symbols+=(B.symbols??[]).length,nt.set(te,we)}let be=[...nt.entries()].sort((T,B)=>B[1].files-T[1].files).slice(0,45).map(([T,B])=>` ${T}/ ${B.files} files, ${B.symbols} symbols`).join(`
128
+ ${Ne}`},ze=[],Je=0,Xe=(T,B=s)=>{let z=_k(T);if(Je+z>B)return!1;return ze.push(T),Je+=z,!0},nt=new Map;for(let[T,B]of x){let z=T.split("/"),te=z.slice(0,Math.min(3,z.length-1)).join("/")||".",we=nt.get(te)??{files:0,symbols:0};we.files++,we.symbols+=(B.symbols??[]).length,nt.set(te,we)}let be=[...nt.entries()].sort((T,B)=>B[1].files-T[1].files).slice(0,45).map(([T,B])=>` ${T}/ ${B.files} files, ${B.symbols} symbols`).join(`
129
129
  `);Xe(`# Repo map for this change
130
130
 
131
131
  Orientation for reviewing this diff, so you do not have to discover the codebase from scratch. Outlines list exported symbols with signatures; use your file-read tool for bodies. This map is incomplete by construction \u2014 the file that confirms or disproves a finding may not appear here. Search for what it does not contain.
@@ -135,16 +135,16 @@ Orientation for reviewing this diff, so you do not have to discover the codebase
135
135
  ${be}
136
136
  \`\`\`
137
137
  `);let Te=Math.floor(s*0.5);Xe(`## Changed files
138
- `,Te);let me=0;for(let T of a)if(x.has(T)&&Xe(Be(T,""),Te))me++;Xe(`
138
+ `,Te);let me=0;for(let T of a)if(x.has(T)&&Xe(qe(T,""),Te))me++;Xe(`
139
139
  ## Related files (not changed by this PR)
140
- `);let W=0;for(let T of ce){let B=` \u2014 ${[...j.get(T)??[]].slice(0,3).join("; ")}`;if(!Xe(Be(T,B)))break;W++}return{markdown:ze.join(`
141
- `),meta:{base:n,head:r,changedFiles:a.length,trackedParsed:x.size,symbolsIndexed:E.size,diffIdentifiers:L.size,candidatesScored:I.size,changedRendered:me,relatedRendered:W,approxTokens:Je,parseMs:P,totalMs:Date.now()-o,...d?{outlineCache:{hits:d.hits,misses:d.misses}}:{},inferredAliases:M.aliases.map((T)=>`${T.scope||"."}: ${T.prefix} -> ${T.root||"."}`)}}}bt();xr();bt();async function pt(e){return await oe("git",["-C",st,"-c","diff.renames=true",...e])}var Zo=(e)=>oe("gh",e);function qc(e){return e instanceof Error?e.message:String(e)}async function Ch(e,t,n){return(await pt(["diff","--unified=0",`${e}..${t}`,"--",...n])).split(`
140
+ `);let G=0;for(let T of ce){let B=` \u2014 ${[...j.get(T)??[]].slice(0,3).join("; ")}`;if(!Xe(qe(T,B)))break;G++}return{markdown:ze.join(`
141
+ `),meta:{base:n,head:r,changedFiles:a.length,trackedParsed:x.size,symbolsIndexed:E.size,diffIdentifiers:L.size,candidatesScored:I.size,changedRendered:me,relatedRendered:G,approxTokens:Je,parseMs:P,totalMs:Date.now()-o,...d?{outlineCache:{hits:d.hits,misses:d.misses}}:{},inferredAliases:M.aliases.map((T)=>`${T.scope||"."}: ${T.prefix} -> ${T.root||"."}`)}}}bt();kr();bt();async function pt(e){return await oe("git",["-C",st,"-c","diff.renames=true",...e])}var oa=(e)=>oe("gh",e);function tu(e){return e instanceof Error?e.message:String(e)}async function Qh(e,t,n){return(await pt(["diff","--unified=0",`${e}..${t}`,"--",...n])).split(`
142
142
  `).filter((s)=>s.startsWith("diff --git ")||s.startsWith("@@")).join(`
143
- `)}async function Qo(e,t,n,r,s,o={}){let a=o.gh??Zo,l="",c="";if(t)try{let d=JSON.parse(await a(["api",`repos/${e}/pulls/${t}`]));l=d.title??"",c=d.body??""}catch(d){if(o.strict)throw Error(`reading the pull request description: ${qc(d)}`,{cause:d})}let u=await pt(["log","--format=%s%n%b%n---",`${n}..${r}`]);return{title:l,body:c,commits:u.trim(),...s?.trim()?{stated:s.trim()}:{}}}function Hc(e){let t=[];for(let n of e.split(`
144
- `))for(let r of tn(n)){let{fp:s,outcome:o}=r.fields;if(r.kind!=="dispute"||!s||o!=="withdrawn"&&o!=="upheld")continue;t.push({fp:s,outcome:o,label:jt(n).replace(/^\s*[-*]\s*/,"").trim()})}return t}function Ah(e){let t=Eh(e);return t.length?{responses:t}:{}}async function as(e,t=Zo){return JSON.parse(await t(["api","--paginate",e]))}async function Oh(e,t,n={}){return(await as(`repos/${e}/issues/${t}/comments`,n.gh)).filter((o)=>Cn(o.body??"",o.user?.type,"summary")).reduce((o,a)=>o&&o.id>a.id?o:a,void 0)?.body??null}function N$(e){return ni(e).replace(/<!--[\s\S]*?-->/g,"").replace(/\n{3,}/g,`
143
+ `)}async function aa(e,t,n,r,s,o={}){let a=o.gh??oa,l="",c="";if(t)try{let d=JSON.parse(await a(["api",`repos/${e}/pulls/${t}`]));l=d.title??"",c=d.body??""}catch(d){if(o.strict)throw Error(`reading the pull request description: ${tu(d)}`,{cause:d})}let u=await pt(["log","--format=%s%n%b%n---",`${n}..${r}`]);return{title:l,body:c,commits:u.trim(),...s?.trim()?{stated:s.trim()}:{}}}function nu(e){let t=[];for(let n of e.split(`
144
+ `))for(let r of rn(n)){let{fp:s,outcome:o}=r.fields;if(r.kind!=="dispute"||!s||o!=="withdrawn"&&o!=="upheld")continue;t.push({fp:s,outcome:o,label:Ut(n).replace(/^\s*[-*]\s*/,"").trim()})}return t}function Zh(e){let t=Yh(e);return t.length?{responses:t}:{}}async function gs(e,t=oa){return JSON.parse(await t(["api","--paginate",e]))}async function em(e,t,n={}){return(await gs(`repos/${e}/issues/${t}/comments`,n.gh)).filter((o)=>In(o.body??"",o.user?.type,"summary")).reduce((o,a)=>o&&o.id>a.id?o:a,void 0)?.body??null}function Sk(e){return ai(e).replace(/<!--[\s\S]*?-->/g,"").replace(/\n{3,}/g,`
145
145
 
146
- `).trim()}async function Ih(e,t,n={}){let r=process.env.PRIOR_FIXTURE;if(r)return await Mo(r);if(!t)return[];let s=n.gh??Zo,o=[];try{let a=await as(`repos/${e}/pulls/${t}/comments`,s),l=Yo(a);for(let c of a){let u=Cn(c.body??"",c.user?.type);o.push({id:c.id,file:c.path,line:c.line??c.original_line,author:c.user?.login??"?",body:c.body??"",resolved:!1,commit:c.original_commit_id,url:c.html_url,...c.created_at?{createdAt:c.created_at}:{},mine:u,...u?{fingerprint:tn(c.body??"").find((d)=>d.fields.fp)?.fields.fp}:{},...l.has(c.id)?{addressed:!0}:{},...c.in_reply_to_id?{inReplyTo:c.in_reply_to_id}:{},...u?{}:Ah(c.body??"")})}}catch(a){if(n.strict)throw Error(`reading the pull request's review comments: ${qc(a)}`,{cause:a})}try{for(let a of await as(`repos/${e}/issues/${t}/comments`,s)){let l=Cn(a.body??"",a.user?.type,"summary"),c=l?{}:Ah(a.body??"");if(!l&&a.user?.type==="Bot"&&!c.responses)continue;let u=l?ri(a.body??"","summary"):void 0,d=l?Number(u?.fields.runs??0):void 0,f=u?.fields.head,p=l?(a.body??"").split(`
147
- `).flatMap((g)=>tn(g).filter((w)=>w.kind==="summary-item"&&w.fields.fp).map((w)=>{let b={fp:w.fields.fp,file:w.fields.file??"?",line:w.fields.line??"?",text:jt(g).replace(/^\s*[-*]\s*/,"").trim()};if(w.fields.sev)b.sev=w.fields.sev;if(w.fields.pre==="1")b.pre=!0;return b})):[],h=l?Hc(a.body??""):[];o.push({id:a.id,author:a.user?.login??"?",body:l?N$(a.body??""):a.body??"",resolved:!1,url:a.html_url,...a.created_at?{createdAt:a.created_at}:{},mine:l,...a.author_association?{association:a.author_association}:{},...d?{runs:d}:{},...f&&/^[0-9a-f]{40}$/i.test(f)?{head:f.toLowerCase()}:{},...p.length?{summaryClaims:p}:{},...h.length?{rulings:h}:{},...c})}}catch(a){if(n.strict)throw Error(`reading the pull request's comments: ${qc(a)}`,{cause:a})}return o}var D$=`query($owner: String!, $name: String!, $number: Int!, $endCursor: String) {
146
+ `).trim()}async function tm(e,t,n={}){let r=process.env.PRIOR_FIXTURE;if(r)return await Go(r);if(!t)return[];let s=n.gh??oa,o=[];try{let a=await gs(`repos/${e}/pulls/${t}/comments`,s),l=sa(a);for(let c of a){let u=In(c.body??"",c.user?.type);o.push({id:c.id,file:c.path,line:c.line??c.original_line,author:c.user?.login??"?",body:c.body??"",resolved:!1,commit:c.original_commit_id,url:c.html_url,...c.created_at?{createdAt:c.created_at}:{},mine:u,...u?{fingerprint:rn(c.body??"").find((d)=>d.fields.fp)?.fields.fp}:{},...l.has(c.id)?{addressed:!0}:{},...c.in_reply_to_id?{inReplyTo:c.in_reply_to_id}:{},...u?{}:Zh(c.body??"")})}}catch(a){if(n.strict)throw Error(`reading the pull request's review comments: ${tu(a)}`,{cause:a})}try{for(let a of await gs(`repos/${e}/issues/${t}/comments`,s)){let l=In(a.body??"",a.user?.type,"summary"),c=l?{}:Zh(a.body??"");if(!l&&a.user?.type==="Bot"&&!c.responses)continue;let u=l?li(a.body??"","summary"):void 0,d=l?Number(u?.fields.runs??0):void 0,f=u?.fields.head,p=l?(a.body??"").split(`
147
+ `).flatMap((g)=>rn(g).filter((w)=>w.kind==="summary-item"&&w.fields.fp).map((w)=>{let b={fp:w.fields.fp,file:w.fields.file??"?",line:w.fields.line??"?",text:Ut(g).replace(/^\s*[-*]\s*/,"").trim()};if(w.fields.sev)b.sev=w.fields.sev;if(w.fields.pre==="1")b.pre=!0;return b})):[],h=l?nu(a.body??""):[];o.push({id:a.id,author:a.user?.login??"?",body:l?Sk(a.body??""):a.body??"",resolved:!1,url:a.html_url,...a.created_at?{createdAt:a.created_at}:{},mine:l,...a.author_association?{association:a.author_association}:{},...d?{runs:d}:{},...f&&/^[0-9a-f]{40}$/i.test(f)?{head:f.toLowerCase()}:{},...p.length?{summaryClaims:p}:{},...h.length?{rulings:h}:{},...c})}}catch(a){if(n.strict)throw Error(`reading the pull request's comments: ${tu(a)}`,{cause:a})}return o}var Rk=`query($owner: String!, $name: String!, $number: Int!, $endCursor: String) {
148
148
  repository(owner: $owner, name: $name) {
149
149
  pullRequest(number: $number) {
150
150
  number url headRefOid
@@ -162,24 +162,24 @@ ${be}
162
162
  }
163
163
  }
164
164
  }
165
- }`;async function Ph(e,t,n={}){let r=n.gh??Zo,[s,o]=e.split("/");if(!s||!o)throw Error(`not an owner/name repository: ${e}`);let a=[],l=null,c=null;do{let u=["api","graphql","-f",`query=${D$}`,"-f",`owner=${s}`,"-f",`name=${o}`];if(u.push("-F",`number=${t}`),l)u.push("-f",`endCursor=${l}`);let d=JSON.parse(await r(u));if(d.errors?.length)throw Error(d.errors.map((p)=>p.message).join("; "));let f=d.data?.repository?.pullRequest;if(!f)throw Error(`no pull request #${t} in ${e}`);c??={number:f.number,url:f.url,author:f.author?.login??"?",headSha:f.headRefOid,labels:(f.labels?.nodes??[]).map((p)=>p.name)};for(let p of f.reviewThreads.nodes){let h=p.line??p.originalLine;a.push({id:p.id,resolved:p.isResolved,outdated:p.isOutdated,...p.resolvedBy?.login?{resolvedBy:p.resolvedBy.login}:{},...p.path?{file:p.path}:{},...h?{line:h}:{},comments:p.comments.nodes.map((g)=>{let w={id:g.databaseId,body:g.body,author:g.author?.login??"?",authorType:g.author?.__typename??"",url:g.url};if(g.replyTo?.databaseId)w.replyTo=g.replyTo.databaseId;return w})})}l=f.reviewThreads.pageInfo.hasNextPage?f.reviewThreads.pageInfo.endCursor:null}while(l);if(!c)throw Error(`no pull request #${t} in ${e}`);return{...c,threads:a}}function L$(e,t){let n=e.trim();if(!n)return!0;if(/^@[\w-]+(\[bot\])?(\s+[\w-]+){1,2}$/.test(n))return!0;let r=n.slice(0,200).replace(/\s+/g," ");return r.length>=80&&t.replace(/\s+/g," ").includes(r)}function Mh(e,t=""){if(e.length===0)return"";let n=e.filter((d)=>!d.mine&&d.file&&!d.responses),r=e.filter((d)=>!d.mine&&!d.file&&!d.responses&&!L$(d.body,t)),s=e.filter((d)=>d.mine&&d.file&&!d.addressed&&!d.inReplyTo),o=e.filter((d)=>d.mine&&!d.file),a=o.flatMap((d)=>d.rulings??[]).filter((d)=>d.outcome==="withdrawn"),l=new Set(a.map((d)=>d.fp)),c=[],u=(d,f)=>{let p=d.file?`${d.file}${d.line?`:${d.line}`:""}`:"(conversation)",h=d.body.replace(/\s+/g," ").slice(0,f);c.push(`- id=${d.id} @${d.author} \`${p}\`${d.resolved?" [resolved]":""}: ${h}`)};if(n.length){c.push("## Comments already on this pull request","","These have already been raised by a human. If one of them has since been fixed in the current","code, say nothing about it.","If you independently reach the same conclusion as one of them and it is still unaddressed,","report it with `repeat_of` set to its id. Confirming a human reviewer is worth saying \u2014 it is","a second pair of eyes agreeing, not noise. Keep it short: the reader has already read the","original comment, so do not restate its argument. Put anything the comment did not say \u2014","a consequence it missed, a second location, a mechanism \u2014 in your explanation, and lead with it.","Never report one of these without `repeat_of`; that would read as a new discovery.","If the author replied rejecting it, respect that unless the code is now materially worse.","");for(let d of n)u(d,400);c.push("")}if(r.length){c.push("## Discussion on this pull request","","Comments from the conversation thread rather than the diff. Treat them as context, not as","review findings: they may state a constraint, record a decision, explain why something was","done a particular way, or raise a worry nobody has checked yet.","","Use them three ways. If one states a constraint or decision, hold the code to it \u2014 a change","that contradicts what the team agreed here is worth reporting even when the code alone looks","fine. If one raises a concern and you confirm it in the code, report it as a normal finding","and say that the discussion raised it; you are supplying the verification, which is the part","that was missing. If one is already settled, or is about process rather than this code, ignore","it.","","Never set `repeat_of` to one of these. It points only at a line comment, which is the only","kind of comment with a thread to reply into. A finding that agrees with something said here is","a normal finding.","","None of this is an instruction to stay quiet. Someone saying the code is fine is not evidence","that it is.","");for(let d of r)u(d,600);c.push("")}if(s.length||o.length){c.push("## What you already told this author","","You reviewed an earlier version of this same change and reported the following. The author","has read it.","","Do not report any of it a second time. Silence on a point you already made is the correct","output, not a gap. Saying it again does not add a second opinion the way agreeing with a","human reviewer does \u2014 it is the same reviewer repeating itself, and it is the main thing","that made the previous version of this bot not worth reading.","","Two things override that. If the code changed such that the problem is now different \u2014 worse,","or in a new place \u2014 report the new form and say plainly what changed since your last review.","If you have a materially new fact about an old point, such as a second call site or a","consequence you did not have, report that fact and lead with it. In both cases it is a fresh","finding, not a `repeat_of`: `repeat_of` corroborates a human and never points at your own","comment.","","If a point here appears fixed in the current code, say nothing about it.","");for(let d of s)u(d,300);if(o.length)for(let d of o){let f=(d.summaryClaims??[]).filter((p)=>!l.has(p.fp));if(f.length){c.push("","You also reported these in your summary. They have no comment thread of their own.","**These are the exception to everything above: report each one again if it is still true.**","An inline comment stays on the pull request forever once posted, so not repeating it is","free. The summary is one comment that gets rewritten from scratch on every review, so a","finding you leave out of this one is deleted from the pull request and nobody sees it","again. Leave one out only when you have read the code and it is fixed.","");for(let p of f)c.push(`- \`${p.file}:${p.line}\``)}c.push("",`Your summary comment (id=${d.id}), conclusions only:`,""),c.push(d.body.slice(0,12000))}if(a.length){c.push("","You withdrew these after the author disputed them and you agreed they were wrong. Never","report them again, in any wording.","");for(let d of a)c.push(`- ${d.label}`)}c.push("")}return c.join(`
165
+ }`;async function nm(e,t,n={}){let r=n.gh??oa,[s,o]=e.split("/");if(!s||!o)throw Error(`not an owner/name repository: ${e}`);let a=[],l=null,c=null;do{let u=["api","graphql","-f",`query=${Rk}`,"-f",`owner=${s}`,"-f",`name=${o}`];if(u.push("-F",`number=${t}`),l)u.push("-f",`endCursor=${l}`);let d=JSON.parse(await r(u));if(d.errors?.length)throw Error(d.errors.map((p)=>p.message).join("; "));let f=d.data?.repository?.pullRequest;if(!f)throw Error(`no pull request #${t} in ${e}`);c??={number:f.number,url:f.url,author:f.author?.login??"?",headSha:f.headRefOid,labels:(f.labels?.nodes??[]).map((p)=>p.name)};for(let p of f.reviewThreads.nodes){let h=p.line??p.originalLine;a.push({id:p.id,resolved:p.isResolved,outdated:p.isOutdated,...p.resolvedBy?.login?{resolvedBy:p.resolvedBy.login}:{},...p.path?{file:p.path}:{},...h?{line:h}:{},comments:p.comments.nodes.map((g)=>{let w={id:g.databaseId,body:g.body,author:g.author?.login??"?",authorType:g.author?.__typename??"",url:g.url};if(g.replyTo?.databaseId)w.replyTo=g.replyTo.databaseId;return w})})}l=f.reviewThreads.pageInfo.hasNextPage?f.reviewThreads.pageInfo.endCursor:null}while(l);if(!c)throw Error(`no pull request #${t} in ${e}`);return{...c,threads:a}}function $k(e,t){let n=e.trim();if(!n)return!0;if(/^@[\w-]+(\[bot\])?(\s+[\w-]+){1,2}$/.test(n))return!0;let r=n.slice(0,200).replace(/\s+/g," ");return r.length>=80&&t.replace(/\s+/g," ").includes(r)}function rm(e,t=""){if(e.length===0)return"";let n=e.filter((d)=>!d.mine&&d.file&&!d.responses),r=e.filter((d)=>!d.mine&&!d.file&&!d.responses&&!$k(d.body,t)),s=e.filter((d)=>d.mine&&d.file&&!d.addressed&&!d.inReplyTo),o=e.filter((d)=>d.mine&&!d.file),a=o.flatMap((d)=>d.rulings??[]).filter((d)=>d.outcome==="withdrawn"),l=new Set(a.map((d)=>d.fp)),c=[],u=(d,f)=>{let p=d.file?`${d.file}${d.line?`:${d.line}`:""}`:"(conversation)",h=d.body.replace(/\s+/g," ").slice(0,f);c.push(`- id=${d.id} @${d.author} \`${p}\`${d.resolved?" [resolved]":""}: ${h}`)};if(n.length){c.push("## Comments already on this pull request","","These have already been raised by a human. If one of them has since been fixed in the current","code, say nothing about it.","If you independently reach the same conclusion as one of them and it is still unaddressed,","report it with `repeat_of` set to its id. Confirming a human reviewer is worth saying \u2014 it is","a second pair of eyes agreeing, not noise. Keep it short: the reader has already read the","original comment, so do not restate its argument. Put anything the comment did not say \u2014","a consequence it missed, a second location, a mechanism \u2014 in your explanation, and lead with it.","Never report one of these without `repeat_of`; that would read as a new discovery.","If the author replied rejecting it, respect that unless the code is now materially worse.","");for(let d of n)u(d,400);c.push("")}if(r.length){c.push("## Discussion on this pull request","","Comments from the conversation thread rather than the diff. Treat them as context, not as","review findings: they may state a constraint, record a decision, explain why something was","done a particular way, or raise a worry nobody has checked yet.","","Use them three ways. If one states a constraint or decision, hold the code to it \u2014 a change","that contradicts what the team agreed here is worth reporting even when the code alone looks","fine. If one raises a concern and you confirm it in the code, report it as a normal finding","and say that the discussion raised it; you are supplying the verification, which is the part","that was missing. If one is already settled, or is about process rather than this code, ignore","it.","","Never set `repeat_of` to one of these. It points only at a line comment, which is the only","kind of comment with a thread to reply into. A finding that agrees with something said here is","a normal finding.","","None of this is an instruction to stay quiet. Someone saying the code is fine is not evidence","that it is.","");for(let d of r)u(d,600);c.push("")}if(s.length||o.length){c.push("## What you already told this author","","You reviewed an earlier version of this same change and reported the following. The author","has read it.","","Do not report any of it a second time. Silence on a point you already made is the correct","output, not a gap. Saying it again does not add a second opinion the way agreeing with a","human reviewer does \u2014 it is the same reviewer repeating itself, and it is the main thing","that made the previous version of this bot not worth reading.","","Two things override that. If the code changed such that the problem is now different \u2014 worse,","or in a new place \u2014 report the new form and say plainly what changed since your last review.","If you have a materially new fact about an old point, such as a second call site or a","consequence you did not have, report that fact and lead with it. In both cases it is a fresh","finding, not a `repeat_of`: `repeat_of` corroborates a human and never points at your own","comment.","","If a point here appears fixed in the current code, say nothing about it.","");for(let d of s)u(d,300);if(o.length)for(let d of o){let f=(d.summaryClaims??[]).filter((p)=>!l.has(p.fp));if(f.length){c.push("","You also reported these in your summary. They have no comment thread of their own.","**These are the exception to everything above: report each one again if it is still true.**","An inline comment stays on the pull request forever once posted, so not repeating it is","free. The summary is one comment that gets rewritten from scratch on every review, so a","finding you leave out of this one is deleted from the pull request and nobody sees it","again. Leave one out only when you have read the code and it is fixed.","");for(let p of f)c.push(`- \`${p.file}:${p.line}\``)}c.push("",`Your summary comment (id=${d.id}), conclusions only:`,""),c.push(d.body.slice(0,12000))}if(a.length){c.push("","You withdrew these after the author disputed them and you agreed they were wrong. Never","report them again, in any wording.","");for(let d of a)c.push(`- ${d.label}`)}c.push("")}return c.join(`
166
166
  `)+`
167
- `}Ji();async function Th(e){let t=Xi(e.diffU0),n=new Map;for(let{file:a,line:l}of pn(e.diffU0)){if(!a||!l.startsWith("+")||l.startsWith("+++ "))continue;let c=n.get(a)??new Set;for(let u of l.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g))c.add(u[0]);n.set(a,c)}await Promise.resolve().then(() => Uc());let s=await ti.create(),o=[];for(let a of e.files){let l={path:a,imports:[],externalImports:[]},c=[];if(Dt(a))try{let u=e.source.read(a),d=u===void 0?null:await s.parseSource(u,a,e.source.paths);if(d){let f=t.get(a)??[];l.imports=d.imports,l.externalImports=d.externalImports,c=d.symbols.filter((p)=>f.some((h)=>p.line>=h.start&&p.line<=h.end)).map((p)=>p.name)}}catch{}o.push({file:a,imports:l,defined:c})}return zo(o.map((a)=>a.imports),e.source),o.map(({file:a,imports:l,defined:c})=>({file:a,tokens:e.fileTokens.get(a)??0,imports:l.imports,defined:[...new Set(c)],used:[...n.get(a)??[]]}))}var Kc=/\.(test|spec)(\.[cm]?[jt]sx?)$/,Wc=/\.(h|hh|hpp)$/,Gc=/\.(c|cc|cpp|cxx)$/;function Ut(e){let t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}function Vc(e){return e.slice(e.lastIndexOf("/")+1).replace(Kc,"").replace(/\.[^.]+$/,"")}function j$(e,t=new Set){if(e.length<6)return!1;if(t.has(e)||t.has(e.toLowerCase()))return!1;return/[A-Z_]/.test(e)}function U$(e,t){if(Vc(e)!==Vc(t))return!1;let[n,r]=[Ut(e),Ut(t)];if(!(n===r||Ut(n)===r||Ut(r)===n))return!1;if(Kc.test(e)!==Kc.test(t))return!0;return Wc.test(e)&&Gc.test(t)||Wc.test(t)&&Gc.test(e)}function Dh(e,t=new Set){let n=new Set(e.map((d)=>d.file)),r=new Map;for(let d of e)for(let f of new Set(d.defined)){if(!j$(f,t))continue;let p=r.get(f)??[];p.push(d.file),r.set(f,p)}let s=new Map;for(let d of e)for(let f of new Set(d.used))if(r.has(f))s.set(f,(s.get(f)??0)+1);let o=new Map;for(let d of e)for(let f of new Set(d.imports))if(n.has(f)&&f!==d.file)o.set(f,(o.get(f)??0)+1);let a={symbol:0,pair:1,import:2,dir:3},l=new Map,c=(d,f,p,h,g)=>{if(d===f)return;let w=d<f?`${d}\x00${f}`:`${f}\x00${d}`,b=l.get(w);if(!b){l.set(w,{from:d,to:f,kind:p,weight:h,...g?{names:[g]}:{}});return}if(b.weight+=h,a[p]<a[b.kind])b.kind=p,b.from=d,b.to=f;if(g&&!b.names?.includes(g))b.names=[...b.names??[],g]};for(let d of e){for(let f of new Set(d.used)){let p=r.get(f);if(!p||p.length>2||p.includes(d.file))continue;let h=s.get(f)??1;for(let g of p)c(d.file,g,"symbol",4/h,f)}for(let f of new Set(d.imports)){if(!n.has(f))continue;c(d.file,f,"import",2/Math.max(1,(o.get(f)??1)-1))}}let u=[...n].sort();for(let d=0;d<u.length;d++)for(let f=d+1;f<u.length;f++){let[p,h]=[u[d],u[f]];if(U$(p,h))c(p,h,"pair",3);else if(Ut(p)===Ut(h))c(p,h,"dir",0.25)}return B$([...l.values()])}function B$(e){return e.sort((t,n)=>n.weight-t.weight||t.from.localeCompare(n.from)||t.to.localeCompare(n.to))}function q$(e){if(!e.length)return"";let t=Ut(e[0]).split("/");for(let n of e.slice(1)){let r=Ut(n).split("/"),s=0;while(s<t.length&&s<r.length&&t[s]===r[s])s++;t=t.slice(0,s)}return t.filter(Boolean).join("/")}function Fh(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function H$(e,t){let n=q$(e).split("/").filter(Boolean);if(e.length>1&&n.length>=3)return Fh(n.slice(-2).join("-"));let r=[...e].sort((s,o)=>(t.get(o)??0)-(t.get(s)??0))[0];return Fh(Vc(r))||"files"}function Nh(e,t){let[n,r]=[e.split("/"),t.split("/")],s=0;while(s<n.length&&s<r.length&&n[s]===r[s])s++;return s}var Lh=new Set(["symbol","pair"]);function jh(e,t,n){let r=n.maxFiles??8,s=n.maxDirFiles??6,o=new Map(e.map((k)=>[k.file,k.tokens])),a=new Map(e.map((k,E)=>[k.file,E])),l=new Map(e.map((k,E)=>[E,new Set([k.file])])),c=new Map(e.map((k,E)=>[E,k.tokens])),u=(k,E)=>{let[D,L]=l.get(k).size>=l.get(E).size?[k,E]:[E,k];for(let O of l.get(L))a.set(O,D),l.get(D).add(O);c.set(D,c.get(D)+c.get(L)),l.delete(L),c.delete(L)},d=n.target??Math.round(n.budget*0.7),f=(k,E,D)=>c.get(k)+c.get(E)<=d&&l.get(k).size+l.get(E).size<=D,p=[[(k)=>Lh.has(k.kind),r],[(k)=>k.kind==="import",r],[(k)=>k.kind==="dir",s]];for(let[k,E]of p)for(let D of t){if(!k(D))continue;let[L,O]=[a.get(D.from),a.get(D.to)];if(L===void 0||O===void 0||L===O||!f(L,O,E))continue;u(L,O)}let h=d/4,g=()=>[...l.keys()].sort((k,E)=>c.get(k)-c.get(E)||k-E);for(let k of g()){if(!l.has(k)||c.get(k)>h||l.get(k).size>2)continue;let E;for(let D of l.keys()){if(D===k||!f(k,D,s))continue;let L=0;for(let O of l.get(k))for(let U of l.get(D))L=Math.max(L,Nh(Ut(O),Ut(U)));if(L>0&&(!E||L>E.depth))E={group:D,depth:L}}if(E)u(E.group,k)}K$(t,a,l,c,o,n.budget,r*2),G$(a,l,c,o);let w=(k,E=!1)=>{let D=new Map;for(let U of t){let[I,j]=[a.get(U.from),a.get(U.to)];if(I===j||I!==k&&j!==k)continue;let H=I===k?j:I;D.set(H,(D.get(H)??0)+U.weight)}let L=new Set([...l.get(k)].map(ea)),O;for(let U of l.keys()){if(U===k||c.get(k)+c.get(U)>n.budget)continue;let I=0;for(let Se of l.get(k))for(let ne of l.get(U))I=Math.max(I,Nh(Ut(Se),Ut(ne)));let j=D.get(U)??0,H=[...l.get(U)].some((Se)=>L.has(ea(Se)));if(E&&!H)continue;if(!O||j>O.weight||j===O.weight&&H&&!O.sameLanguage||j===O.weight&&H===O.sameLanguage&&I>O.depth||j===O.weight&&H===O.sameLanguage&&I===O.depth&&c.get(U)<c.get(O.group))O={group:U,weight:j,sameLanguage:H,depth:I}}return O?.group};while(n.maxGroups&&l.size>n.maxGroups){let k=g()[0],E=w(k);if(E===void 0)break;u(E,k)}if(n.foldSmall!==!1)for(let k of g()){if(l.size<2)break;if(!l.has(k)||c.get(k)>h||l.get(k).size>2)continue;let E=w(k,!0);if(E!==void 0)u(E,k)}let b=[...l.values()].map((k)=>[...k].sort()).sort((k,E)=>ii(E,o)-ii(k,o)||k[0].localeCompare(E[0])),x=new Map,R=new Map,P=b.map((k,E)=>{for(let O of k)R.set(O,E);let D=H$(k,o),L=(x.get(D)??0)+1;return x.set(D,L),{id:L>1?`${D}-${L}`:D,files:k,tokens:ii(k,o),links:[]}}),M=[];for(let k of t){let[E,D]=[R.get(k.from),R.get(k.to)];if(E===void 0||D===void 0)continue;if(E===D)P[E].links.push(k);else if(k.kind!=="dir")M.push(k)}return{groups:P,cut:M}}function K$(e,t,n,r,s,o,a){let l=new Map;for(let u of e){if(!Lh.has(u.kind))continue;for(let d of[u.from,u.to])l.set(d,[...l.get(d)??[],u])}let c=[...l.keys()].sort((u,d)=>s.get(u)-s.get(d)||u.localeCompare(d));for(let u=0;u<3;u++){let d=!1;for(let f of c){let p=t.get(f),h=new Map;for(let b of l.get(f)){let x=b.from===f?b.to:b.from,R=t.get(x);h.set(R,(h.get(R)??0)+b.weight)}let g=h.get(p)??0,w;for(let[b,x]of h){if(b===p||x<=g||w&&x<=w.weight)continue;if(r.get(b)+s.get(f)>o||n.get(b).size+1>a)continue;w={group:b,weight:x}}if(!w)continue;if(n.get(p).delete(f),r.set(p,r.get(p)-s.get(f)),!n.get(p).size)n.delete(p),r.delete(p);n.get(w.group).add(f),r.set(w.group,r.get(w.group)+s.get(f)),t.set(f,w.group),d=!0}if(!d)break}}var W$=4;function ea(e){if(Wc.test(e)||Gc.test(e))return"cpp";if(/\.[cm]?[jt]sx?$/.test(e))return"js";return e.slice(e.lastIndexOf(".")+1)}function G$(e,t,n,r){let s=Math.max(-1,...t.keys())+1,o=(a,l)=>{let c=s++;t.set(c,new Set(l)),n.set(c,ii(l,r));for(let u of l)t.get(a).delete(u),e.set(u,c);return n.set(a,n.get(a)-n.get(c)),c};for(let a of[...t.keys()]){let l=[...t.get(a)].sort();if(l.length<W$)continue;let c=new Map;for(let d of l)c.set(ea(d),[...c.get(ea(d))??[],d]);if(c.size<2||[...c.values()].some((d)=>d.length<2))continue;let[,...u]=[...c.values()].sort((d,f)=>ii(f,r)-ii(d,r));for(let d of u)o(a,d)}}function ii(e,t){return e.reduce((n,r)=>n+(t.get(r)??0),0)}function Rr(e){switch(e.kind){case"symbol":{let t=(e.names??[]).slice(0,3).map((n)=>`\`${n}\``).join(", ");return`\`${e.from}\` uses ${t}, added in \`${e.to}\``}case"pair":return`\`${e.from}\` and \`${e.to}\` are a test/source or header/source pair`;case"import":return`\`${e.from}\` imports \`${e.to}\``;case"dir":return`\`${e.from}\` and \`${e.to}\` share a directory`}}function Uh(e,t,n=8){let r=new Set(e),s={symbol:0,pair:1,import:2,dir:3};return t.filter((o)=>o.kind!=="dir"&&r.has(o.from)!==r.has(o.to)).sort((o,a)=>s[o.kind]-s[a.kind]||a.weight-o.weight).slice(0,n).map(Rr)}function Bh(e,t,n,r){let s=e.map((c)=>({id:c.id,files:[...c.files],tokens:c.tokens})),o=new Map(s.map((c)=>[c.id,c])),a=new Map;for(let c of t?.groups??[]){if(typeof c?.id!=="string"||!o.has(c.id))continue;a.set(c.id,{title:typeof c.title==="string"&&c.title.trim()?c.title.trim():void 0,rationale:typeof c.rationale==="string"&&c.rationale.trim()?c.rationale.trim():void 0,priority:typeof c.priority==="number"&&Number.isFinite(c.priority)?c.priority:void 0})}let l=[];for(let c of t?.moves??[]){if(typeof c?.file!=="string"||typeof c.to!=="string")continue;let u=s.find((p)=>p.files.includes(c.file)),d=o.get(c.to);if(!u||!d||u===d||u.files.length===1)continue;let f=r.get(c.file)??0;if(d.tokens+f>n)continue;u.files=u.files.filter((p)=>p!==c.file),u.tokens-=f,d.files=[...d.files,c.file].sort(),d.tokens+=f,l.push({file:c.file,from:u.id,to:d.id,reason:typeof c.reason==="string"?c.reason:""})}return{moves:l,units:s.map((c)=>{let u=a.get(c.id);return{id:c.id,title:u?.title??c.id,...u?.rationale?{rationale:u.rationale}:{},files:c.files,...u?.priority!==void 0?{priority:u.priority}:{}}})}}async function ta(e){let t=`${e.base}..${e.head}`,n=_r(await pt(["diff",t,"--",...e.files]),e.base),r=await pt(["diff","--stat",t]),s=new Map([...Np(n)].map(([u,d])=>[u,Math.ceil(d/jp)])),o=await pt(["diff","--unified=0",t,"--",...e.files]),a=await Th({source:await e.source(e.files),diffU0:o,files:e.files,fileTokens:s}),l=Dh(a,ss),c=jh(a,l,{budget:Jn,maxGroups:br});return{wholeDiff:n,diffstat:r,diffU0:o,fileTokens:s,facts:a,links:l,grouping:c}}var V$=new Set(["if","for","while","switch","return","catch","function","new","await","typeof","sizeof"]);function z$(e){for(let n of e.matchAll(/([A-Za-z_$~][\w$]*(?:::~?[A-Za-z_$][\w$]*)*)\s*(?:[(<]|=\s*(?:async\s*)?\()/g))if(!V$.has(n[1]))return n[1];return/\b(?:class|interface|type|enum|struct|namespace|const|let|var)\s+([A-Za-z_$][\w$]*)/.exec(e)?.[1]}function na(e,t){let n=new Map,r=(s)=>{let o=n.get(s);if(!o)o={file:s,added:0,removed:0,defines:[],touches:[]},n.set(s,o);return o};for(let{file:s,line:o}of pn(e)){if(!s||o.startsWith("+++ "))continue;let a=r(s),l=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@ ?(.*)$/.exec(o);if(l){let c=z$(l[2]);if(c&&!a.touches.some((u)=>u.name===c))a.touches.push({name:c,line:Number(l[1])})}else if(o.startsWith("+"))a.added++;else if(o.startsWith("-"))a.removed++}for(let s of t){let o=r(s.file);o.defines=s.defined,o.touches=o.touches.filter((a)=>!s.defined.includes(a.name))}return n}function ra(e,t=6){let n=[],r=(s)=>s.slice(0,t).map((o)=>`\`${o}\``).join(", ")+(s.length>t?`, +${s.length-t} more`:"");if(e.defines.length)n.push(`adds ${r(e.defines)}`);if(e.touches.length)n.push(`edits in ${r(e.touches.map((s)=>`${s.name}@${s.line}`))}`);return`- \`${e.file}\` (+${e.added} \u2212${e.removed})${n.length?`: ${n.join("; ")}`:""}`}function ia(e,t,n,r=Math.floor(n/4)){let s=e.flatMap((d)=>d.files),o=(d)=>t.get(d)??0;if(s.reduce((d,f)=>d+o(f),0)<=n)return{shown:s,sketched:[]};let l=new Set,c=0,u=Math.floor(n/Math.max(1,e.length));for(let d of e){let f=0;for(let p of[...d.files].sort((h,g)=>o(g)-o(h))){let h=o(p);if(h>r||f+h>u||c+h>n)continue;l.add(p),f+=h,c+=h}}for(let d of s.filter((f)=>!l.has(f)).sort((f,p)=>o(f)-o(p))){let f=o(d);if(f>r||c+f>n)continue;l.add(d),c+=f}return{shown:s.filter((d)=>l.has(d)),sketched:s.filter((d)=>!l.has(d))}}function sa(e,t,n=3){let r=new Set(e);return t.filter((s)=>s.kind!=="dir"&&r.has(s.from)&&r.has(s.to)).slice(0,n).map(Rr)}function oa(e,t,n=20){let r=new Map;for(let o of e)for(let a of o.files)r.set(a,o.id);let s=[];for(let o of t){if(o.kind==="dir")continue;let a=r.get(o.from),l=r.get(o.to);if(!a||!l||a===l)continue;if(s.push(`${Rr(o)} (${a} \u2192 ${l})`),s.length>=n)break}return s}aa();import{randomBytes as Q$}from"crypto";import{existsSync as ek,realpathSync as tk}from"fs";import nk from"os";import Xh from"path";function Vh(e){try{return tk(e)}catch{return Xh.resolve(e)}}function zh(e,t){return Vh(e)===Vh(t)}async function rk(e,t){await re("git",["-C",e,"worktree","remove","--force",t],{allowFail:!0}),await re("git",["-C",e,"worktree","prune"],{allowFail:!0})}async function Jh(e,t,n){if((await re("git",["-C",e,"cat-file","-e",`${n}^{commit}`],{allowFail:!0})).code===0)return;if(t===void 0)throw Error(`commit ${n} is not in this clone`);if(await re("git",["-C",e,"fetch","-q","origin",`refs/pull/${t}/head`],{allowFail:!0}),(await re("git",["-C",e,"cat-file","-e",`${n}^{commit}`],{allowFail:!0})).code!==0)throw Error(`commit ${n} is not in this clone and could not be fetched from refs/pull/${t}/head`)}async function Yh(e,t,n){if(process.env.CODE_REVIEW_NO_CHECKOUT==="1")return{dir:e,release:async()=>{}};let r=process.env.CODE_REVIEW_SUBJECT_DIR;if(!r){let u=Xh.join(nk.tmpdir(),`code-review-subject-${n.slice(0,12)}-${process.pid}-${Q$(3).toString("hex")}`);return await Jh(e,t,n),await oe("git",["-C",e,"worktree","add","--detach","-q",u,n]),{dir:u,release:()=>rk(e,u)}}let s=r,o=async()=>{},a=await re("git",["-C",s,"rev-parse","--show-toplevel"],{allowFail:!0}),c=a.code===0&&zh(a.stdout.trim(),s)?await re("git",["-C",s,"rev-parse","HEAD"],{allowFail:!0}):{code:1,stdout:"",stderr:""};if(c.code===0&&c.stdout.trim().startsWith(n))return{dir:s,release:o};if(await Jh(e,t,n),c.code===0){let u=await re("git",["-C",s,"status","--porcelain","--untracked-files=no"],{allowFail:!0});if(u.code!==0||u.stdout.trim()!=="")throw Error(`CODE_REVIEW_SUBJECT_DIR ${s} has uncommitted changes to tracked files, so it was not moved to ${n.slice(0,12)}. Commit, stash or discard them, or point it somewhere else.`);if(zh(s,e))throw Error(`CODE_REVIEW_SUBJECT_DIR ${s} is the checkout this review is running from, and it is not at ${n.slice(0,12)}. Point it somewhere else, or set CODE_REVIEW_NO_CHECKOUT=1 when the checkout is already at the head commit.`);let d=await re("git",["-C",s,"checkout","--detach","-q",n],{allowFail:!0});if(d.code!==0)throw Error(`CODE_REVIEW_SUBJECT_DIR ${s} could not be moved to ${n.slice(0,12)}: ${d.stderr.trim()||"checkout failed"}`);return{dir:s,release:o}}if(ek(s))throw Error(`CODE_REVIEW_SUBJECT_DIR ${s} exists but is not the root of its own git working tree`+(a.code===0?` \u2014 it sits inside ${a.stdout.trim()}`:""));return await oe("git",["-C",e,"worktree","add","--detach","-q",s,n]),{dir:s,release:o}}import Zh from"path";function Qh(e){return e.pr?`pr-${e.pr}-${e.head.slice(0,12)}`:`range-${e.base.slice(0,12)}-${e.head.slice(0,12)}`}async function oi(e){if(process.env.GH_REPO)return process.env.GH_REPO;let t=await re("git",["-C",e,"remote","get-url","origin"],{allowFail:!0}),r=(t.code===0?t.stdout.trim():"").match(/github\.com[:/]+([^/]+)\/(.+?)(?:\.git)?$/);if(!r)return`local/${Zh.basename(Zh.resolve(e))}`;return`${r[1]}/${r[2]}`}xr();bt();ls();import He from"path";import{spawn as sk}from"child_process";import{readFileSync as ok}from"fs";import{chmod as ak,mkdir as lk,rm as ck}from"fs/promises";bt();class Bt extends Error{name="CancelledError";constructor(){super("review cancelled")}}var cs=new Map,tm=!1;function Jc(e,t){if(e.pid===void 0)return;try{process.kill(-e.pid,t)}catch{}}function uk(){for(let e of cs.keys())Jc(e,"SIGKILL")}async function li(e=5000){let t=[...cs];if(!t.length)return;for(let[r]of t)Jc(r,"SIGTERM");let n=setTimeout(()=>{for(let[r]of t)if(cs.has(r))Jc(r,"SIGKILL")},e);await Promise.all(t.map(([,r])=>r)),clearTimeout(n)}function dk(e){let t=0,n=0,r={input_tokens:0,output_tokens:0,reasoning_tokens:0,cache_read_input_tokens:0,cache_creation_input_tokens:0};for(let s of e.split(`
168
- `)){let o=s.trim();if(!o.startsWith("{"))continue;let a;try{a=JSON.parse(o)}catch{continue}let l=a.part;if(!(l?.type==="step-finish"||l?.type==="step_finish"||a.type==="step_finish")||!l)continue;if(n+=1,n===1)r.first_step={input_tokens:l.tokens?.input??0,cache_read_input_tokens:l.tokens?.cache?.read??0,cache_creation_input_tokens:l.tokens?.cache?.write??0};t+=l.cost??0,r.input_tokens+=l.tokens?.input??0,r.output_tokens+=l.tokens?.output??0,r.reasoning_tokens+=l.tokens?.reasoning??0,r.cache_read_input_tokens+=l.tokens?.cache?.read??0,r.cache_creation_input_tokens+=l.tokens?.cache?.write??0}return{costUsd:t,numTurns:n,usage:r}}var fk=new Set(["read","tilth_tilth_read"]),pk=new Set(["grep","glob","tilth_tilth_search","tilth_tilth_files"]),hk=60;function mk(e,t=""){let n={},r=0,s=new Set,o=new Set,a=t?`${t.replace(/\/$/,"")}/`:"",l=(u)=>a&&u.startsWith(a)?u.slice(a.length):u,c=(u,d)=>{if(u.size<hk)u.add(d)};for(let u of e.split(`
169
- `)){let d=u.trim();if(!d.startsWith("{"))continue;let f;try{f=JSON.parse(d)}catch{continue}let p=f.part;if(f.type!=="tool_use"||p?.type!=="tool"||typeof p.tool!=="string")continue;if(n[p.tool]=(n[p.tool]??0)+1,p.state?.status==="error")r+=1;let h=p.state?.input??{};if(fk.has(p.tool)){let g=Array.isArray(h.paths)?h.paths:[h.path??h.filePath],w=typeof h.section==="string"?`:${h.section}`:"";for(let b of g)if(typeof b==="string")c(s,l(b)+w)}else if(pk.has(p.tool)){let g=h.query??h.pattern;if(typeof g==="string")c(o,g)}}return{calls:n,failed:r,read:[...s],searched:[...o]}}var Xc=new Map;function gk(e,t,n="repo",r){let s=`${e}\x00${t}`,o=`${n==="repo"?"shared":"no-tools"}${r?`-${r}`:""}`,a=Xc.get(o);if(a&&a.key!==s)throw Error("openCodeConfig called with a different prompt after the config was written");if(a)return a.home;let l=(async()=>{let c=He.join(wt,"oc",o),u=He.join(c,"config");return await fn(He.join(u,"opencode.json"),wk(e,t,n)),await De(He.join(u,"plugin","governor.ts"),await _t(He.join(Vr,"opencode","governor.ts"))),c})();return Xc.set(o,{home:l,key:s}),l}function la(){Xc.clear()}function _k(e){return e.includes("/")?e:`${fc}/${e}`}function wk(e,t,n="repo"){let r=n==="repo"?["read","glob","grep","shell","tilth_*"]:[];return{$schema:"https://opencode.ai/config.json",formatter:!1,snapshots:!1,share:"disabled",compaction:{auto:!1},...Object.keys(Bo).length?{providers:Bo}:{},mcp:{servers:n==="none"?{}:{tilth:{type:"local",command:["tilth","--mcp"],codemode:!1,timeout:{catalog:60000,execution:60000}}}},agents:{reviewer:{description:"code review pipeline",mode:"primary",steps:Do,system:t?`${e}
167
+ `}rs();async function im(e){let t=is(e.diffU0),n=new Map;for(let{file:a,line:l}of gn(e.diffU0)){if(!a||!l.startsWith("+")||l.startsWith("+++ "))continue;let c=n.get(a)??new Set;for(let u of l.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g))c.add(u[0]);n.set(a,c)}await Promise.resolve().then(() => Qc());let s=await oi.create(),o=[];for(let a of e.files){let l={path:a,imports:[],externalImports:[]},c=[];if(Lt(a))try{let u=e.source.read(a),d=u===void 0?null:await s.parseSource(u,a,e.source.paths);if(d){let f=t.get(a)??[];l.imports=d.imports,l.externalImports=d.externalImports,c=d.symbols.filter((p)=>f.some((h)=>p.line>=h.start&&p.line<=h.end)).map((p)=>p.name)}}catch{}o.push({file:a,imports:l,defined:c})}return Ho(o.map((a)=>a.imports),e.source),o.map(({file:a,imports:l,defined:c})=>({file:a,tokens:e.fileTokens.get(a)??0,imports:l.imports,defined:[...new Set(c)],used:[...n.get(a)??[]]}))}var ru=/\.(test|spec)(\.[cm]?[jt]sx?)$/,iu=/\.(h|hh|hpp)$/,su=/\.(c|cc|cpp|cxx)$/;function Bt(e){let t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}function ou(e){return e.slice(e.lastIndexOf("/")+1).replace(ru,"").replace(/\.[^.]+$/,"")}function kk(e,t=new Set){if(e.length<6)return!1;if(t.has(e)||t.has(e.toLowerCase()))return!1;return/[A-Z_]/.test(e)}function Ek(e,t){if(ou(e)!==ou(t))return!1;let[n,r]=[Bt(e),Bt(t)];if(!(n===r||Bt(n)===r||Bt(r)===n))return!1;if(ru.test(e)!==ru.test(t))return!0;return iu.test(e)&&su.test(t)||iu.test(t)&&su.test(e)}function am(e,t=new Set){let n=new Set(e.map((d)=>d.file)),r=new Map;for(let d of e)for(let f of new Set(d.defined)){if(!kk(f,t))continue;let p=r.get(f)??[];p.push(d.file),r.set(f,p)}let s=new Map;for(let d of e)for(let f of new Set(d.used))if(r.has(f))s.set(f,(s.get(f)??0)+1);let o=new Map;for(let d of e)for(let f of new Set(d.imports))if(n.has(f)&&f!==d.file)o.set(f,(o.get(f)??0)+1);let a={symbol:0,pair:1,import:2,dir:3},l=new Map,c=(d,f,p,h,g)=>{if(d===f)return;let w=d<f?`${d}\x00${f}`:`${f}\x00${d}`,b=l.get(w);if(!b){l.set(w,{from:d,to:f,kind:p,weight:h,...g?{names:[g]}:{}});return}if(b.weight+=h,a[p]<a[b.kind])b.kind=p,b.from=d,b.to=f;if(g&&!b.names?.includes(g))b.names=[...b.names??[],g]};for(let d of e){for(let f of new Set(d.used)){let p=r.get(f);if(!p||p.length>2||p.includes(d.file))continue;let h=s.get(f)??1;for(let g of p)c(d.file,g,"symbol",4/h,f)}for(let f of new Set(d.imports)){if(!n.has(f))continue;c(d.file,f,"import",2/Math.max(1,(o.get(f)??1)-1))}}let u=[...n].sort();for(let d=0;d<u.length;d++)for(let f=d+1;f<u.length;f++){let[p,h]=[u[d],u[f]];if(Ek(p,h))c(p,h,"pair",3);else if(Bt(p)===Bt(h))c(p,h,"dir",0.25)}return Ck([...l.values()])}function Ck(e){return e.sort((t,n)=>n.weight-t.weight||t.from.localeCompare(n.from)||t.to.localeCompare(n.to))}function Ak(e){if(!e.length)return"";let t=Bt(e[0]).split("/");for(let n of e.slice(1)){let r=Bt(n).split("/"),s=0;while(s<t.length&&s<r.length&&t[s]===r[s])s++;t=t.slice(0,s)}return t.filter(Boolean).join("/")}function sm(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function Ok(e,t){let n=Ak(e).split("/").filter(Boolean);if(e.length>1&&n.length>=3)return sm(n.slice(-2).join("-"));let r=[...e].sort((s,o)=>(t.get(o)??0)-(t.get(s)??0))[0];return sm(ou(r))||"files"}function om(e,t){let[n,r]=[e.split("/"),t.split("/")],s=0;while(s<n.length&&s<r.length&&n[s]===r[s])s++;return s}var lm=new Set(["symbol","pair"]);function cm(e,t,n){let r=n.maxFiles??8,s=n.maxDirFiles??6,o=new Map(e.map((k)=>[k.file,k.tokens])),a=new Map(e.map((k,E)=>[k.file,E])),l=new Map(e.map((k,E)=>[E,new Set([k.file])])),c=new Map(e.map((k,E)=>[E,k.tokens])),u=(k,E)=>{let[F,L]=l.get(k).size>=l.get(E).size?[k,E]:[E,k];for(let O of l.get(L))a.set(O,F),l.get(F).add(O);c.set(F,c.get(F)+c.get(L)),l.delete(L),c.delete(L)},d=n.target??Math.round(n.budget*0.7),f=(k,E,F)=>c.get(k)+c.get(E)<=d&&l.get(k).size+l.get(E).size<=F,p=[[(k)=>lm.has(k.kind),r],[(k)=>k.kind==="import",r],[(k)=>k.kind==="dir",s]];for(let[k,E]of p)for(let F of t){if(!k(F))continue;let[L,O]=[a.get(F.from),a.get(F.to)];if(L===void 0||O===void 0||L===O||!f(L,O,E))continue;u(L,O)}let h=d/4,g=()=>[...l.keys()].sort((k,E)=>c.get(k)-c.get(E)||k-E);for(let k of g()){if(!l.has(k)||c.get(k)>h||l.get(k).size>2)continue;let E;for(let F of l.keys()){if(F===k||!f(k,F,s))continue;let L=0;for(let O of l.get(k))for(let U of l.get(F))L=Math.max(L,om(Bt(O),Bt(U)));if(L>0&&(!E||L>E.depth))E={group:F,depth:L}}if(E)u(E.group,k)}Ik(t,a,l,c,o,n.budget,r*2),Mk(a,l,c,o);let w=(k,E=!1)=>{let F=new Map;for(let U of t){let[I,j]=[a.get(U.from),a.get(U.to)];if(I===j||I!==k&&j!==k)continue;let H=I===k?j:I;F.set(H,(F.get(H)??0)+U.weight)}let L=new Set([...l.get(k)].map(la)),O;for(let U of l.keys()){if(U===k||c.get(k)+c.get(U)>n.budget)continue;let I=0;for(let Re of l.get(k))for(let ne of l.get(U))I=Math.max(I,om(Bt(Re),Bt(ne)));let j=F.get(U)??0,H=[...l.get(U)].some((Re)=>L.has(la(Re)));if(E&&!H)continue;if(!O||j>O.weight||j===O.weight&&H&&!O.sameLanguage||j===O.weight&&H===O.sameLanguage&&I>O.depth||j===O.weight&&H===O.sameLanguage&&I===O.depth&&c.get(U)<c.get(O.group))O={group:U,weight:j,sameLanguage:H,depth:I}}return O?.group};while(n.maxGroups&&l.size>n.maxGroups){let k=g()[0],E=w(k);if(E===void 0)break;u(E,k)}if(n.foldSmall!==!1)for(let k of g()){if(l.size<2)break;if(!l.has(k)||c.get(k)>h||l.get(k).size>2)continue;let E=w(k,!0);if(E!==void 0)u(E,k)}let b=[...l.values()].map((k)=>[...k].sort()).sort((k,E)=>ci(E,o)-ci(k,o)||k[0].localeCompare(E[0])),x=new Map,S=new Map,P=b.map((k,E)=>{for(let O of k)S.set(O,E);let F=Ok(k,o),L=(x.get(F)??0)+1;return x.set(F,L),{id:L>1?`${F}-${L}`:F,files:k,tokens:ci(k,o),links:[]}}),M=[];for(let k of t){let[E,F]=[S.get(k.from),S.get(k.to)];if(E===void 0||F===void 0)continue;if(E===F)P[E].links.push(k);else if(k.kind!=="dir")M.push(k)}return{groups:P,cut:M}}function Ik(e,t,n,r,s,o,a){let l=new Map;for(let u of e){if(!lm.has(u.kind))continue;for(let d of[u.from,u.to])l.set(d,[...l.get(d)??[],u])}let c=[...l.keys()].sort((u,d)=>s.get(u)-s.get(d)||u.localeCompare(d));for(let u=0;u<3;u++){let d=!1;for(let f of c){let p=t.get(f),h=new Map;for(let b of l.get(f)){let x=b.from===f?b.to:b.from,S=t.get(x);h.set(S,(h.get(S)??0)+b.weight)}let g=h.get(p)??0,w;for(let[b,x]of h){if(b===p||x<=g||w&&x<=w.weight)continue;if(r.get(b)+s.get(f)>o||n.get(b).size+1>a)continue;w={group:b,weight:x}}if(!w)continue;if(n.get(p).delete(f),r.set(p,r.get(p)-s.get(f)),!n.get(p).size)n.delete(p),r.delete(p);n.get(w.group).add(f),r.set(w.group,r.get(w.group)+s.get(f)),t.set(f,w.group),d=!0}if(!d)break}}var Pk=4;function la(e){if(iu.test(e)||su.test(e))return"cpp";if(/\.[cm]?[jt]sx?$/.test(e))return"js";return e.slice(e.lastIndexOf(".")+1)}function Mk(e,t,n,r){let s=Math.max(-1,...t.keys())+1,o=(a,l)=>{let c=s++;t.set(c,new Set(l)),n.set(c,ci(l,r));for(let u of l)t.get(a).delete(u),e.set(u,c);return n.set(a,n.get(a)-n.get(c)),c};for(let a of[...t.keys()]){let l=[...t.get(a)].sort();if(l.length<Pk)continue;let c=new Map;for(let d of l)c.set(la(d),[...c.get(la(d))??[],d]);if(c.size<2||[...c.values()].some((d)=>d.length<2))continue;let[,...u]=[...c.values()].sort((d,f)=>ci(f,r)-ci(d,r));for(let d of u)o(a,d)}}function ci(e,t){return e.reduce((n,r)=>n+(t.get(r)??0),0)}function Er(e){switch(e.kind){case"symbol":{let t=(e.names??[]).slice(0,3).map((n)=>`\`${n}\``).join(", ");return`\`${e.from}\` uses ${t}, added in \`${e.to}\``}case"pair":return`\`${e.from}\` and \`${e.to}\` are a test/source or header/source pair`;case"import":return`\`${e.from}\` imports \`${e.to}\``;case"dir":return`\`${e.from}\` and \`${e.to}\` share a directory`}}function um(e,t,n=8){let r=new Set(e),s={symbol:0,pair:1,import:2,dir:3};return t.filter((o)=>o.kind!=="dir"&&r.has(o.from)!==r.has(o.to)).sort((o,a)=>s[o.kind]-s[a.kind]||a.weight-o.weight).slice(0,n).map(Er)}function dm(e,t,n,r){let s=e.map((c)=>({id:c.id,files:[...c.files],tokens:c.tokens})),o=new Map(s.map((c)=>[c.id,c])),a=new Map;for(let c of t?.groups??[]){if(typeof c?.id!=="string"||!o.has(c.id))continue;a.set(c.id,{title:typeof c.title==="string"&&c.title.trim()?c.title.trim():void 0,rationale:typeof c.rationale==="string"&&c.rationale.trim()?c.rationale.trim():void 0,priority:typeof c.priority==="number"&&Number.isFinite(c.priority)?c.priority:void 0})}let l=[];for(let c of t?.moves??[]){if(typeof c?.file!=="string"||typeof c.to!=="string")continue;let u=s.find((p)=>p.files.includes(c.file)),d=o.get(c.to);if(!u||!d||u===d||u.files.length===1)continue;let f=r.get(c.file)??0;if(d.tokens+f>n)continue;u.files=u.files.filter((p)=>p!==c.file),u.tokens-=f,d.files=[...d.files,c.file].sort(),d.tokens+=f,l.push({file:c.file,from:u.id,to:d.id,reason:typeof c.reason==="string"?c.reason:""})}return{moves:l,units:s.map((c)=>{let u=a.get(c.id);return{id:c.id,title:u?.title??c.id,...u?.rationale?{rationale:u.rationale}:{},files:c.files,...u?.priority!==void 0?{priority:u.priority}:{}}})}}async function ca(e){let t=`${e.base}..${e.head}`,n=vr(await pt(["diff",t,"--",...e.files]),e.base),r=await pt(["diff","--stat",t]),s=new Map([...ph(n)].map(([u,d])=>[u,Math.ceil(d/gh)])),o=await pt(["diff","--unified=0",t,"--",...e.files]),a=await im({source:await e.source(e.files),diffU0:o,files:e.files,fileTokens:s}),l=am(a,hs),c=cm(a,l,{budget:Qn,maxGroups:Rr});return{wholeDiff:n,diffstat:r,diffU0:o,fileTokens:s,facts:a,links:l,grouping:c}}var Tk=new Set(["if","for","while","switch","return","catch","function","new","await","typeof","sizeof"]);function Dk(e){for(let n of e.matchAll(/([A-Za-z_$~][\w$]*(?:::~?[A-Za-z_$][\w$]*)*)\s*(?:[(<]|=\s*(?:async\s*)?\()/g))if(!Tk.has(n[1]))return n[1];return/\b(?:class|interface|type|enum|struct|namespace|const|let|var)\s+([A-Za-z_$][\w$]*)/.exec(e)?.[1]}function ua(e,t){let n=new Map,r=(s)=>{let o=n.get(s);if(!o)o={file:s,added:0,removed:0,defines:[],touches:[]},n.set(s,o);return o};for(let{file:s,line:o}of gn(e)){if(!s||o.startsWith("+++ "))continue;let a=r(s),l=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@ ?(.*)$/.exec(o);if(l){let c=Dk(l[2]);if(c&&!a.touches.some((u)=>u.name===c))a.touches.push({name:c,line:Number(l[1])})}else if(o.startsWith("+"))a.added++;else if(o.startsWith("-"))a.removed++}for(let s of t){let o=r(s.file);o.defines=s.defined,o.touches=o.touches.filter((a)=>!s.defined.includes(a.name))}return n}function da(e,t=6){let n=[],r=(s)=>s.slice(0,t).map((o)=>`\`${o}\``).join(", ")+(s.length>t?`, +${s.length-t} more`:"");if(e.defines.length)n.push(`adds ${r(e.defines)}`);if(e.touches.length)n.push(`edits in ${r(e.touches.map((s)=>`${s.name}@${s.line}`))}`);return`- \`${e.file}\` (+${e.added} \u2212${e.removed})${n.length?`: ${n.join("; ")}`:""}`}function fa(e,t,n,r=Math.floor(n/4)){let s=e.flatMap((d)=>d.files),o=(d)=>t.get(d)??0;if(s.reduce((d,f)=>d+o(f),0)<=n)return{shown:s,sketched:[]};let l=new Set,c=0,u=Math.floor(n/Math.max(1,e.length));for(let d of e){let f=0;for(let p of[...d.files].sort((h,g)=>o(g)-o(h))){let h=o(p);if(h>r||f+h>u||c+h>n)continue;l.add(p),f+=h,c+=h}}for(let d of s.filter((f)=>!l.has(f)).sort((f,p)=>o(f)-o(p))){let f=o(d);if(f>r||c+f>n)continue;l.add(d),c+=f}return{shown:s.filter((d)=>l.has(d)),sketched:s.filter((d)=>!l.has(d))}}function pa(e,t,n=3){let r=new Set(e);return t.filter((s)=>s.kind!=="dir"&&r.has(s.from)&&r.has(s.to)).slice(0,n).map(Er)}function ha(e,t,n=20){let r=new Map;for(let o of e)for(let a of o.files)r.set(a,o.id);let s=[];for(let o of t){if(o.kind==="dir")continue;let a=r.get(o.from),l=r.get(o.to);if(!a||!l||a===l)continue;if(s.push(`${Er(o)} (${a} \u2192 ${l})`),s.length>=n)break}return s}ma();import{randomBytes as Uk}from"crypto";import{existsSync as Bk,realpathSync as qk}from"fs";import Hk from"os";import bm from"path";function _m(e){try{return qk.native(e)}catch{return bm.resolve(e)}}function wm(e,t){return _m(e)===_m(t)}async function Kk(e,t){await re("git",["-C",e,"worktree","remove","--force",t],{allowFail:!0}),await re("git",["-C",e,"worktree","prune"],{allowFail:!0})}async function ym(e,t,n){if((await re("git",["-C",e,"cat-file","-e",`${n}^{commit}`],{allowFail:!0})).code===0)return;if(t===void 0)throw Error(`commit ${n} is not in this clone`);if(await re("git",["-C",e,"fetch","-q","origin",`refs/pull/${t}/head`],{allowFail:!0}),(await re("git",["-C",e,"cat-file","-e",`${n}^{commit}`],{allowFail:!0})).code!==0)throw Error(`commit ${n} is not in this clone and could not be fetched from refs/pull/${t}/head`)}async function vm(e,t,n){if(process.env.CODE_REVIEW_NO_CHECKOUT==="1")return{dir:e,release:async()=>{}};let r=process.env.CODE_REVIEW_SUBJECT_DIR;if(!r){let u=bm.join(Hk.tmpdir(),`code-review-subject-${n.slice(0,12)}-${process.pid}-${Uk(3).toString("hex")}`);return await ym(e,t,n),await oe("git",["-C",e,"worktree","add","--detach","-q",u,n]),{dir:u,release:()=>Kk(e,u)}}let s=r,o=async()=>{},a=await re("git",["-C",s,"rev-parse","--show-toplevel"],{allowFail:!0}),c=a.code===0&&wm(a.stdout.trim(),s)?await re("git",["-C",s,"rev-parse","HEAD"],{allowFail:!0}):{code:1,stdout:"",stderr:""};if(c.code===0&&c.stdout.trim().startsWith(n))return{dir:s,release:o};if(await ym(e,t,n),c.code===0){let u=await re("git",["-C",s,"status","--porcelain","--untracked-files=no"],{allowFail:!0});if(u.code!==0||u.stdout.trim()!=="")throw Error(`CODE_REVIEW_SUBJECT_DIR ${s} has uncommitted changes to tracked files, so it was not moved to ${n.slice(0,12)}. Commit, stash or discard them, or point it somewhere else.`);if(wm(s,e))throw Error(`CODE_REVIEW_SUBJECT_DIR ${s} is the checkout this review is running from, and it is not at ${n.slice(0,12)}. Point it somewhere else, or set CODE_REVIEW_NO_CHECKOUT=1 when the checkout is already at the head commit.`);let d=await re("git",["-C",s,"checkout","--detach","-q",n],{allowFail:!0});if(d.code!==0)throw Error(`CODE_REVIEW_SUBJECT_DIR ${s} could not be moved to ${n.slice(0,12)}: ${d.stderr.trim()||"checkout failed"}`);return{dir:s,release:o}}if(Bk(s))throw Error(`CODE_REVIEW_SUBJECT_DIR ${s} exists but is not the root of its own git working tree`+(a.code===0?` \u2014 it sits inside ${a.stdout.trim()}`:""));return await oe("git",["-C",e,"worktree","add","--detach","-q",s,n]),{dir:s,release:o}}import xm from"path";function Sm(e){return e.pr?`pr-${e.pr}-${e.head.slice(0,12)}`:`range-${e.base.slice(0,12)}-${e.head.slice(0,12)}`}async function di(e){if(process.env.GH_REPO)return process.env.GH_REPO;let t=await re("git",["-C",e,"remote","get-url","origin"],{allowFail:!0}),r=(t.code===0?t.stdout.trim():"").match(/github\.com[:/]+([^/]+)\/(.+?)(?:\.git)?$/);if(!r)return`local/${xm.basename(xm.resolve(e))}`;return`${r[1]}/${r[2]}`}kr();bt();_s();import Le from"path";import{spawn as Wk,spawnSync as Vk}from"child_process";import{readFileSync as zk}from"fs";import{chmod as Jk,mkdir as Xk,rm as Yk}from"fs/promises";bt();class qt extends Error{name="CancelledError";constructor(){super("review cancelled")}}var ws=new Map,$m=!1,km=process.platform==="win32";function lu(e,t){if(e.pid===void 0)return;if(km){Vk("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore",windowsHide:!0});return}try{process.kill(-e.pid,t)}catch{}}function Zk(){for(let e of ws.keys())lu(e,"SIGKILL")}async function pi(e=5000){let t=[...ws];if(!t.length)return;for(let[r]of t)lu(r,"SIGTERM");let n=setTimeout(()=>{for(let[r]of t)if(ws.has(r))lu(r,"SIGKILL")},e);await Promise.all(t.map(([,r])=>r)),clearTimeout(n)}function Qk(e){let t=0,n=0,r={input_tokens:0,output_tokens:0,reasoning_tokens:0,cache_read_input_tokens:0,cache_creation_input_tokens:0};for(let s of e.split(`
168
+ `)){let o=s.trim();if(!o.startsWith("{"))continue;let a;try{a=JSON.parse(o)}catch{continue}let l=a.part;if(!(l?.type==="step-finish"||l?.type==="step_finish"||a.type==="step_finish")||!l)continue;if(n+=1,n===1)r.first_step={input_tokens:l.tokens?.input??0,cache_read_input_tokens:l.tokens?.cache?.read??0,cache_creation_input_tokens:l.tokens?.cache?.write??0};t+=l.cost??0,r.input_tokens+=l.tokens?.input??0,r.output_tokens+=l.tokens?.output??0,r.reasoning_tokens+=l.tokens?.reasoning??0,r.cache_read_input_tokens+=l.tokens?.cache?.read??0,r.cache_creation_input_tokens+=l.tokens?.cache?.write??0}return{costUsd:t,numTurns:n,usage:r}}var eE=new Set(["read","tilth_tilth_read"]),tE=new Set(["grep","glob","tilth_tilth_search","tilth_tilth_files"]),nE=60;function rE(e,t=""){let n={},r=0,s=new Set,o=new Set,a=t?`${t.replace(/\/$/,"")}/`:"",l=(u)=>a&&u.startsWith(a)?u.slice(a.length):u,c=(u,d)=>{if(u.size<nE)u.add(d)};for(let u of e.split(`
169
+ `)){let d=u.trim();if(!d.startsWith("{"))continue;let f;try{f=JSON.parse(d)}catch{continue}let p=f.part;if(f.type!=="tool_use"||p?.type!=="tool"||typeof p.tool!=="string")continue;if(n[p.tool]=(n[p.tool]??0)+1,p.state?.status==="error")r+=1;let h=p.state?.input??{};if(eE.has(p.tool)){let g=Array.isArray(h.paths)?h.paths:[h.path??h.filePath],w=typeof h.section==="string"?`:${h.section}`:"";for(let b of g)if(typeof b==="string")c(s,l(b)+w)}else if(tE.has(p.tool)){let g=h.query??h.pattern;if(typeof g==="string")c(o,g)}}return{calls:n,failed:r,read:[...s],searched:[...o]}}var cu=new Map;function iE(e,t,n="repo",r){let s=`${e}\x00${t}`,o=`${n==="repo"?"shared":"no-tools"}${r?`-${r}`:""}`,a=cu.get(o);if(a&&a.key!==s)throw Error("openCodeConfig called with a different prompt after the config was written");if(a)return a.home;let l=(async()=>{let c=Le.join(wt,"oc",o),u=Le.join(c,"config");return await mn(Le.join(u,"opencode.json"),oE(e,t,n)),await Fe(Le.join(u,"plugin","governor.ts"),await _t(Le.join(Zr,"opencode","governor.ts"))),c})();return cu.set(o,{home:l,key:s}),l}function ga(){cu.clear()}function sE(e){return e.includes("/")?e:`${Oc}/${e}`}function oE(e,t,n="repo"){let r=n==="repo"?["read","glob","grep","shell","tilth_*"]:[];return{$schema:"https://opencode.ai/config.json",formatter:!1,snapshots:!1,share:"disabled",compaction:{auto:!1},...Object.keys(Qo).length?{providers:Qo}:{},mcp:{servers:n==="none"?{}:{tilth:{type:"local",command:["tilth","--mcp"],codemode:!1,timeout:{catalog:60000,execution:60000}}}},agents:{reviewer:{description:"code review pipeline",mode:"primary",steps:Jo,system:t?`${e}
170
170
 
171
- ${t}`:e,permissions:[{action:"*",resource:"*",effect:"deny"},...r.map((s)=>({action:s,resource:"*",effect:"allow"})),{action:"edit",resource:"*",effect:"allow"},{action:"external_directory",resource:"*",effect:"allow"}]}}}}async function yk(e,t){let n=t.tools??"repo",r=n==="repo"?await _t(He.join(Vr,"opencode","tools.md")):"",s=await gk(e,r,n,t.systemName),o=He.join(s,"config"),a=He.join(ye,"logs",`${t.tag}.usage.json`);await Sn(He.dirname(a)),await Yt(a);let l=t.effort,c=_k(t.model);return{command:"opencode",args:["run","--standalone","--format","json","--agent","reviewer","--model",l&&!c.includes("#")?`${c}#${l}`:c,"--title",t.tag],cwd:st,env:{PWD:st,XDG_CONFIG_HOME:He.join(s,"xdg"),XDG_DATA_HOME:He.join(s,"data",t.tag),XDG_STATE_HOME:He.join(s,"state",t.tag),XDG_CACHE_HOME:He.join(s,"cache"),OPENCODE_CONFIG_DIR:o,OPENCODE_DISABLE_PROJECT_CONFIG:"1",OPENCODE_DISABLE_AUTOUPDATE:"1",REVIEW_GOVERNOR_BUDGET_USD:String(t.budget),REVIEW_GOVERNOR_DEADLINE_MS:String(pc),REVIEW_GOVERNOR_MAX_STEPS:String(Do),REVIEW_GOVERNOR_OUT_FILE:t.outFile,REVIEW_GOVERNOR_LOG:He.join(ye,"logs",`${t.tag}.governor.jsonl`),REVIEW_GOVERNOR_USAGE_FILE:a,REVIEW_GOVERNOR_WAIT_FOR_TOOLS:n==="repo"?"tilth_":"",REVIEW_GOVERNOR_EXPECT_TOOLS:[...new Set(r.match(/\btilth_tilth_\w+/g)??[])].join(",")},unsetEnv:["OPENCODE_CONFIG","OPENCODE_CONFIG_CONTENT","OPENCODE_CLI_CONFIG_CONTENT"],rawExt:"stdout.ndjson",parse:(d)=>bk(a)??dk(d),tools:(d)=>mk(d,st)}}function bk(e){try{return JSON.parse(ok(e,"utf8"))}catch{return}}var vk=new Set(["write","edit","multiedit"]),xk={"\n":"\\n","\r":"\\r","\t":"\\t","\b":"\\b","\f":"\\f"};function Rk(e,t){for(let n=t+1;n<e.length;n++){let r=e.charAt(n);if(!/\s/.test(r))return",:}]".includes(r)}return!0}function nm(e){try{return JSON.parse(e)}catch(t){let n="",r=!1,s=!1,o=!1;for(let a=0;a<e.length;a++){let l=e.charAt(a);if(r){if(s)s=!1;else if(l==="\\")s=!0;else if(l==='"')if(Rk(e,a))r=!1;else{n+="\\\"",o=!0;continue}else if(l<" "){n+=xk[l]??`\\u${l.charCodeAt(0).toString(16).padStart(4,"0")}`,o=!0;continue}}else if(l==='"')r=!0;n+=l}if(!o)throw t;try{return JSON.parse(n)}catch{throw t}}}function Sk(e){if(e.parseError!==void 0)return{kind:"invalid-json",message:`wrote ${e.outFile}, but it is not valid JSON (${e.parseError})`};let t=[],n=[];for(let s of e.stdout.split(`
172
- `)){let o=s.trim();if(!o.startsWith("{"))continue;let a;try{a=JSON.parse(o)}catch{continue}if(a.type==="error"&&a.error){let u=a.error,d=u.type??u.name??"error",f=u.message??u.data?.message;t.push(f?`${d}: ${f}`:d);continue}let l=a.part;if(a.type!=="tool_use"||l?.type!=="tool"||!vk.has(l.tool??""))continue;if(l.state?.status!=="completed")continue;let c=l.state.input?.path??l.state.input?.filePath;if(typeof c==="string")n.push(c)}if(t.length)return{kind:"provider",message:`the model provider returned an error (${t[0]})`};let r=n.filter((s)=>He.resolve(e.cwd,s)!==He.resolve(e.cwd,e.outFile));if(r.length)return{kind:"wrong-path",message:`wrote its output to ${r.at(-1)} instead of ${e.outFile}`};if(e.exitCode!==0){let s=e.stderr.trim().split(`
173
- `).at(-1)?.slice(0,300);return{kind:"exit",message:`exited with code ${e.exitCode} without writing its output${s?`: ${s}`:""}`}}return{kind:"no-output",message:"finished without writing its output file"}}function $k(e){let t;for(let n of e.split(`
174
- `)){let r=n.trim();if(!r.startsWith("{"))continue;let s;try{s=JSON.parse(r)}catch{continue}let o=s.part?.type==="text"?s.part.text:void 0;if(typeof o==="string"&&o.trim())t=o}return t}function kk(e,t){let n=[...e.matchAll(/```[a-zA-Z]*\s*\n([\s\S]*?)```/g)].map((o)=>o[1]??"").reverse(),r=e.indexOf("{"),s=e.lastIndexOf("}");if(r!==-1&&s>r)n.push(e.slice(r,s+1));for(let o of n){let a;try{a=nm(o.trim())}catch{continue}if(typeof a!=="object"||a===null||Array.isArray(a))continue;if(t.length===0||t.some((l)=>(l in a)))return a}return}async function On(e,t){if(Yr?.aborted)throw new Bt;let n=t.system?.text??(await _t(He.join(Vr,"system.md"))).replaceAll("{{repo}}",yt),r=t.model??$n,s=t.effort??zr,o=await yk(n,{...t,model:r,effort:s,systemName:t.system?.name}),a={...process.env,...yc,...o.env};for(let c of o.unsetEnv)delete a[c];let l=[o.env.XDG_DATA_HOME,o.env.XDG_STATE_HOME].filter((c)=>c!==void 0);try{return await Ak(e,t,o,a)}finally{if(process.env.DIFFLOUPE_KEEP_SCRATCH!=="1")await Promise.all(l.map((c)=>ck(c,{recursive:!0,force:!0}).catch(()=>{})))}}async function Ek(e,t){if(!qo||!t)return;await lk(t,{recursive:!0,mode:448}),await ak(t,448);let n=await re("opencode",["auth","import","--standalone"],{env:e,cwd:st,input:qo,allowFail:!0,timeoutMs:60000});if(n.code!==0)throw Error(`opencode auth import failed (exit ${n.code}): ${n.stderr.trim().slice(0,500)}`)}async function Ak(e,t,n,r){if(Yr?.aborted)throw new Bt;if(await Ek(r,n.env.XDG_DATA_HOME),Yr?.aborted)throw new Bt;if(!tm)tm=!0,process.on("exit",uk);let s=Date.now(),{stdout:o,stderr:a,exitCode:l}=await new Promise((g,w)=>{let b=sk(n.command,n.args,{cwd:n.cwd,env:r,stdio:["pipe","pipe","pipe"],detached:!0}),x=()=>{};cs.set(b,new Promise((k)=>x=k));let R=()=>{cs.delete(b),x()};b.stdin.on("error",w),b.stdin.end(e);let P=[],M=[];b.stdout.on("data",(k)=>P.push(k)),b.stderr.on("data",(k)=>M.push(k)),b.on("error",(k)=>{R(),w(k)}),b.on("close",(k,E)=>{R(),g({stdout:Buffer.concat(P).toString("utf8"),stderr:Buffer.concat(M).toString("utf8"),exitCode:k??(E?128:0)})})}),c=Date.now()-s;await De(He.join(ye,"logs",`${t.tag}.stderr.log`),a),await De(He.join(ye,"raw",`${t.tag}.${n.rawExt}`),o);let u=n.parse(o),d=n.tools?.(o),f=null,p;try{f=nm(await _t(t.outFile))}catch(g){let w=await Gr(t.outFile)?g instanceof Error?g.message:String(g):void 0;p=Sk({outFile:t.outFile,stdout:o,stderr:a,exitCode:l,cwd:n.cwd,parseError:w})}let h;if(p?.kind==="no-output"){let g=$k(o),w=g===void 0||!t.answerKeys?.length?void 0:kk(g,t.answerKeys);if(w!==void 0)f=w,p=void 0,h="text",await De(t.outFile,`${JSON.stringify(w,null,2)}
175
- `),console.error(` ${t.tag}: no output file; read the answer from the final reply`)}return{wallMs:c,exitCode:l,...u,tools:d,payload:f,failure:p,...h?{deliveredAs:h}:{}}}import{createHash as Pk}from"crypto";bt();Sr();function hm(e,t){let n=e.filter((s)=>s.mine&&!s.file).reduce((s,o)=>s&&s.id>o.id?s:o,void 0),r=new Set;return(n?.summaryClaims??[]).filter((s)=>{if(r.has(s.fp)||t.rendered.has(s.fp)||t.withdrawn.has(s.fp))return!1;if(!t.unread(s.file)&&!t.refound.has(s.fp))return!1;if(t.dropQuestions&&s.sev==="question")return!1;return r.add(s.fp),!0})}function mm(e){return new Map(e.filter((t)=>t.mine&&t.fingerprint&&!t.addressed).map((t)=>[t.fingerprint,t]))}var Ok=4,pm=300;function gm(e){if(typeof e!=="object"||e===null||Array.isArray(e))return[];let t=e.checked;if(!Array.isArray(t))return[];return t.filter((n)=>typeof n==="string").map((n)=>n.replace(/\s+/g," ").trim()).filter(Boolean).slice(0,Ok).map((n)=>n.length>pm?`${n.slice(0,pm-1)}\u2026`:n)}function _m(e,t){return Math.min(9,Math.max(t,0.22*e))}function wm(e){let t=new Set;return e.filter((n)=>{let r=`${n.file}:${n.line}`;if(t.has(r))return!1;return t.add(r),n.severity!=="nice-to-have"||n.confidence==="high"}).sort((n,r)=>(tt[n.severity]?.rank??9)-(tt[r.severity]?.rank??9)||qt[ot(n.file)]-qt[ot(r.file)])}function ym(e,t){return e.length>0||t.some((n)=>n.mine&&n.file&&!n.addressed)}var Qn=10,Yc=5,da=3,Ik=/^\s*(cut for the )?cap\b/i;function Zc(e,t){let n=[],r=[],s={fresh:0,preexisting:0};for(let o of e){if(o.repeat_of){n.push(o);continue}let a=o.preexisting?"preexisting":"fresh",l=o.preexisting?t.maxPreexisting:t.maxNew;(s[a]<l?n:r).push(o),s[a]+=1}return{posted:n,overCap:r}}function Qc(e,t){if(!Array.isArray(t))return;let n=`${e.file}:${e.line}`,r=new Set;for(let s of t){if(typeof s!=="string")continue;let o=s.trim().replace(/^`|`$/g,"");if(o&&o!==n&&o!==e.file)r.add(o)}return r.size?[...r]:void 0}function bm(e,t,n){let r=[],s=[],o=[],a=new Set,l=new Map(n.map((c)=>[c.id,c]));for(let c of e.keep??[]){let u=t[c.id];if(!u)continue;if(a.has(c.id))continue;a.add(c.id);let d=new Set(u.cross_file_refs??[]),f=[...u.also_at??[]];for(let[w,b]of[[c.repeats,!0],[c.merge_with,!1]])for(let x of w??[]){let R=t[x];if(!R||a.has(x))continue;a.add(x);let P=[`${R.file}:${R.line}`,...R.also_at??[]];if(b)f.push(...P);else for(let M of P)d.add(M);for(let M of R.cross_file_refs??[])d.add(M)}d.delete(`${u.file}:${u.line}`);let p=Qc(u,f),h=c.repeat_of?l.get(c.repeat_of):void 0,g=h&&!h.mine&&h.file?c.repeat_of:void 0;if(c.repeat_of&&!g){let w=!h?"no such comment on this PR":h.mine?"the bot's own comment":"not a review comment, so it has no thread to reply into";console.error(` repeat_of ${c.repeat_of} on "${u.title}" ignored: ${w}`)}r.push({...u,severity:c.severity??u.severity,explanation:c.note?`${u.explanation}
171
+ ${t}`:e,permissions:[{action:"*",resource:"*",effect:"deny"},...r.map((s)=>({action:s,resource:"*",effect:"allow"})),{action:"edit",resource:"*",effect:"allow"},{action:"external_directory",resource:"*",effect:"allow"}]}}}}async function aE(e,t){let n=t.tools??"repo",r=n==="repo"?await _t(Le.join(Zr,"opencode","tools.md")):"",s=await iE(e,r,n,t.systemName),o=Le.join(s,"config"),a=Le.join(ye,"logs",`${t.tag}.usage.json`);await Cn(Le.dirname(a)),await Qt(a);let l=t.effort,c=sE(t.model);return{command:"opencode",args:["run","--standalone","--format","json","--agent","reviewer","--model",l&&!c.includes("#")?`${c}#${l}`:c,"--title",t.tag],cwd:st,env:{PWD:st,XDG_CONFIG_HOME:Le.join(s,"xdg"),XDG_DATA_HOME:Le.join(s,"data",t.tag),XDG_STATE_HOME:Le.join(s,"state",t.tag),XDG_CACHE_HOME:Le.join(s,"cache"),OPENCODE_CONFIG_DIR:o,OPENCODE_DISABLE_PROJECT_CONFIG:"1",OPENCODE_DISABLE_AUTOUPDATE:"1",REVIEW_GOVERNOR_BUDGET_USD:String(t.budget),REVIEW_GOVERNOR_DEADLINE_MS:String(Ic),REVIEW_GOVERNOR_MAX_STEPS:String(Jo),REVIEW_GOVERNOR_OUT_FILE:t.outFile,REVIEW_GOVERNOR_LOG:Le.join(ye,"logs",`${t.tag}.governor.jsonl`),REVIEW_GOVERNOR_USAGE_FILE:a,REVIEW_GOVERNOR_WAIT_FOR_TOOLS:n==="repo"?"tilth_":"",REVIEW_GOVERNOR_EXPECT_TOOLS:[...new Set(r.match(/\btilth_tilth_\w+/g)??[])].join(",")},unsetEnv:["OPENCODE_CONFIG","OPENCODE_CONFIG_CONTENT","OPENCODE_CLI_CONFIG_CONTENT","OPENCODE_DB"],rawExt:"stdout.ndjson",parse:(d)=>lE(a)??Qk(d),tools:(d)=>rE(d,st)}}function lE(e){try{return JSON.parse(zk(e,"utf8"))}catch{return}}var cE=new Set(["write","edit","multiedit"]),uE={"\n":"\\n","\r":"\\r","\t":"\\t","\b":"\\b","\f":"\\f"};function dE(e,t){for(let n=t+1;n<e.length;n++){let r=e.charAt(n);if(!/\s/.test(r))return",:}]".includes(r)}return!0}function Em(e){try{return JSON.parse(e)}catch(t){let n="",r=!1,s=!1,o=!1;for(let a=0;a<e.length;a++){let l=e.charAt(a);if(r){if(s)s=!1;else if(l==="\\")s=!0;else if(l==='"')if(dE(e,a))r=!1;else{n+="\\\"",o=!0;continue}else if(l<" "){n+=uE[l]??`\\u${l.charCodeAt(0).toString(16).padStart(4,"0")}`,o=!0;continue}}else if(l==='"')r=!0;n+=l}if(!o)throw t;try{return JSON.parse(n)}catch{throw t}}}function fE(e){if(e.parseError!==void 0)return{kind:"invalid-json",message:`wrote ${e.outFile}, but it is not valid JSON (${e.parseError})`};let t=[],n=[];for(let s of e.stdout.split(`
172
+ `)){let o=s.trim();if(!o.startsWith("{"))continue;let a;try{a=JSON.parse(o)}catch{continue}if(a.type==="error"&&a.error){let u=a.error,d=u.type??u.name??"error",f=u.message??u.data?.message;t.push(f?`${d}: ${f}`:d);continue}let l=a.part;if(a.type!=="tool_use"||l?.type!=="tool"||!cE.has(l.tool??""))continue;if(l.state?.status!=="completed")continue;let c=l.state.input?.path??l.state.input?.filePath;if(typeof c==="string")n.push(c)}if(t.length)return{kind:"provider",message:`the model provider returned an error (${t[0]})`};let r=n.filter((s)=>Le.resolve(e.cwd,s)!==Le.resolve(e.cwd,e.outFile));if(r.length)return{kind:"wrong-path",message:`wrote its output to ${r.at(-1)} instead of ${e.outFile}`};if(e.exitCode!==0){let s=e.stderr.trim().split(`
173
+ `).at(-1)?.slice(0,300);return{kind:"exit",message:`exited with code ${e.exitCode} without writing its output${s?`: ${s}`:""}`}}return{kind:"no-output",message:"finished without writing its output file"}}function pE(e){let t;for(let n of e.split(`
174
+ `)){let r=n.trim();if(!r.startsWith("{"))continue;let s;try{s=JSON.parse(r)}catch{continue}let o=s.part?.type==="text"?s.part.text:void 0;if(typeof o==="string"&&o.trim())t=o}return t}function hE(e,t){let n=[...e.matchAll(/```[a-zA-Z]*\s*\n([\s\S]*?)```/g)].map((o)=>o[1]??"").reverse(),r=e.indexOf("{"),s=e.lastIndexOf("}");if(r!==-1&&s>r)n.push(e.slice(r,s+1));for(let o of n){let a;try{a=Em(o.trim())}catch{continue}if(typeof a!=="object"||a===null||Array.isArray(a))continue;if(t.length===0||t.some((l)=>(l in a)))return a}return}async function Pn(e,t){if(ni?.aborted)throw new qt;let n=t.system?.text??(await _t(Le.join(Zr,"system.md"))).replaceAll("{{repo}}",yt),r=t.model??An,s=t.effort??Qr,o=await aE(n,{...t,model:r,effort:s,systemName:t.system?.name}),a={...process.env,...Fc,...o.env};for(let c of o.unsetEnv)delete a[c];let l=[o.env.XDG_DATA_HOME,o.env.XDG_STATE_HOME].filter((c)=>c!==void 0);try{return await gE(e,t,o,a)}finally{if(process.env.DIFFLOUPE_KEEP_SCRATCH!=="1")await Promise.all(l.map((c)=>Yk(c,{recursive:!0,force:!0}).catch(()=>{})))}}async function mE(e,t){if(!ea&&!ls||!t)return;await Xk(t,{recursive:!0,mode:448}),await Jk(t,448);let n=await re("opencode",["auth","import","--standalone"],{env:e,cwd:st,input:ea||"[]",allowFail:!0,timeoutMs:60000});if(n.code!==0)throw Error(`opencode auth import failed (exit ${n.code}): ${n.stderr.trim().slice(0,500)}`);if(ls)Jp(Le.join(t,"opencode","opencode.db"),JSON.parse(ls))}async function gE(e,t,n,r){if(ni?.aborted)throw new qt;if(await mE(r,n.env.XDG_DATA_HOME),ni?.aborted)throw new qt;if(!$m)$m=!0,process.on("exit",Zk);let s=Date.now(),{stdout:o,stderr:a,exitCode:l}=await new Promise((g,w)=>{let b=Wk(n.command,n.args,{cwd:n.cwd,env:r,stdio:["pipe","pipe","pipe"],detached:!km,windowsHide:!0}),x=()=>{};ws.set(b,new Promise((k)=>x=k));let S=()=>{ws.delete(b),x()};b.stdin.on("error",w),b.stdin.end(e);let P=[],M=[];b.stdout.on("data",(k)=>P.push(k)),b.stderr.on("data",(k)=>M.push(k)),b.on("error",(k)=>{S(),w(k)}),b.on("close",(k,E)=>{S(),g({stdout:Buffer.concat(P).toString("utf8"),stderr:Buffer.concat(M).toString("utf8"),exitCode:k??(E?128:0)})})}),c=Date.now()-s;await Fe(Le.join(ye,"logs",`${t.tag}.stderr.log`),a),await Fe(Le.join(ye,"raw",`${t.tag}.${n.rawExt}`),o);let u=n.parse(o),d=n.tools?.(o),f=null,p;try{f=Em(await _t(t.outFile))}catch(g){let w=await Yr(t.outFile)?g instanceof Error?g.message:String(g):void 0;p=fE({outFile:t.outFile,stdout:o,stderr:a,exitCode:l,cwd:n.cwd,parseError:w})}let h;if(p?.kind==="no-output"){let g=pE(o),w=g===void 0||!t.answerKeys?.length?void 0:hE(g,t.answerKeys);if(w!==void 0)f=w,p=void 0,h="text",await Fe(t.outFile,`${JSON.stringify(w,null,2)}
175
+ `),console.error(` ${t.tag}: no output file; read the answer from the final reply`)}return{wallMs:c,exitCode:l,...u,tools:d,payload:f,failure:p,...h?{deliveredAs:h}:{}}}import{createHash as bE}from"crypto";bt();Cr();function jm(e,t){let n=e.filter((s)=>s.mine&&!s.file).reduce((s,o)=>s&&s.id>o.id?s:o,void 0),r=new Set;return(n?.summaryClaims??[]).filter((s)=>{if(r.has(s.fp)||t.rendered.has(s.fp)||t.withdrawn.has(s.fp))return!1;if(!t.unread(s.file)&&!t.refound.has(s.fp))return!1;if(t.dropQuestions&&s.sev==="question")return!1;return r.add(s.fp),!0})}function Um(e){return new Map(e.filter((t)=>t.mine&&t.fingerprint&&!t.addressed).map((t)=>[t.fingerprint,t]))}var wE=4,Lm=300;function Bm(e){if(typeof e!=="object"||e===null||Array.isArray(e))return[];let t=e.checked;if(!Array.isArray(t))return[];return t.filter((n)=>typeof n==="string").map((n)=>n.replace(/\s+/g," ").trim()).filter(Boolean).slice(0,wE).map((n)=>n.length>Lm?`${n.slice(0,Lm-1)}\u2026`:n)}function qm(e,t){return Math.min(9,Math.max(t,0.22*e))}function Hm(e){let t=new Set;return e.filter((n)=>{let r=`${n.file}:${n.line}`;if(t.has(r))return!1;return t.add(r),n.severity!=="nice-to-have"||n.confidence==="high"}).sort((n,r)=>(tt[n.severity]?.rank??9)-(tt[r.severity]?.rank??9)||Ht[ot(n.file)]-Ht[ot(r.file)])}function Km(e,t){return e.length>0||t.some((n)=>n.mine&&n.file&&!n.addressed)}var nr=10,uu=5,ya=3,yE=/^\s*(cut for the )?cap\b/i;function du(e,t){let n=[],r=[],s={fresh:0,preexisting:0};for(let o of e){if(o.repeat_of){n.push(o);continue}let a=o.preexisting?"preexisting":"fresh",l=o.preexisting?t.maxPreexisting:t.maxNew;(s[a]<l?n:r).push(o),s[a]+=1}return{posted:n,overCap:r}}function fu(e,t){if(!Array.isArray(t))return;let n=`${e.file}:${e.line}`,r=new Set;for(let s of t){if(typeof s!=="string")continue;let o=s.trim().replace(/^`|`$/g,"");if(o&&o!==n&&o!==e.file)r.add(o)}return r.size?[...r]:void 0}function Gm(e,t,n){let r=[],s=[],o=[],a=new Set,l=new Map(n.map((c)=>[c.id,c]));for(let c of e.keep??[]){let u=t[c.id];if(!u)continue;if(a.has(c.id))continue;a.add(c.id);let d=new Set(u.cross_file_refs??[]),f=[...u.also_at??[]];for(let[w,b]of[[c.repeats,!0],[c.merge_with,!1]])for(let x of w??[]){let S=t[x];if(!S||a.has(x))continue;a.add(x);let P=[`${S.file}:${S.line}`,...S.also_at??[]];if(b)f.push(...P);else for(let M of P)d.add(M);for(let M of S.cross_file_refs??[])d.add(M)}d.delete(`${u.file}:${u.line}`);let p=fu(u,f),h=c.repeat_of?l.get(c.repeat_of):void 0,g=h&&!h.mine&&h.file?c.repeat_of:void 0;if(c.repeat_of&&!g){let w=!h?"no such comment on this PR":h.mine?"the bot's own comment":"not a review comment, so it has no thread to reply into";console.error(` repeat_of ${c.repeat_of} on "${u.title}" ignored: ${w}`)}r.push({...u,severity:c.severity??u.severity,explanation:c.note?`${u.explanation}
176
176
 
177
- ${c.note}`:u.explanation,cross_file_refs:d.size?[...d]:void 0,also_at:p,repeat_of:g,preexisting:typeof c.preexisting==="boolean"?c.preexisting:u.preexisting})}for(let c of e.drop??[]){let u=t[c.id];if(u&&!a.has(c.id))if(a.add(c.id),Ik.test(c.reason??""))o.push({...u,repeat_of:void 0});else s.push({title:u.title,reason:c.reason})}return t.forEach((c,u)=>{if(!a.has(u))s.push({title:c.title,reason:"coordinator did not rule on this finding"})}),{kept:r,dropped:s,capped:o}}var vm="cited line is outside the changed hunks",Rm="Focus on the lines that changed since the last review. Report problems elsewhere in the file only if the new changes caused them or made them reachable.",Mk=`
177
+ ${c.note}`:u.explanation,cross_file_refs:d.size?[...d]:void 0,also_at:p,repeat_of:g,preexisting:typeof c.preexisting==="boolean"?c.preexisting:u.preexisting})}for(let c of e.drop??[]){let u=t[c.id];if(u&&!a.has(c.id))if(a.add(c.id),yE.test(c.reason??""))o.push({...u,repeat_of:void 0});else s.push({title:u.title,reason:c.reason})}return t.forEach((c,u)=>{if(!a.has(u))s.push({title:c.title,reason:"coordinator did not rule on this finding"})}),{kept:r,dropped:s,capped:o}}var Wm="cited line is outside the changed hunks",zm="Focus on the lines that changed since the last review. Report problems elsewhere in the file only if the new changes caused them or made them reachable.",vE=`
178
178
  Calibrated uncertainty \u2014 this matters as much as finding bugs:
179
179
  - If you notice a discrepancy that you investigated and could argue either way, do NOT silently drop it. Report it with severity "question" and state both sides: what looks inconsistent, and the evidence that suggests it may be intentional. The author knows the intent and can answer in one word; you cannot.
180
180
  - This applies especially when a change is added to one of several parallel lists, registries, or spec files and not the others, and the existing entries are themselves inconsistent. Inconsistent precedent is not proof that the omission is correct.
181
181
  - Use "question" only where you have concrete evidence of the discrepancy and cite both the place it was added and the places it was not. Do not use it to hedge vague concerns.
182
- `.trim(),Tk=`
182
+ `.trim(),xE=`
183
183
  Your goal is to find real problems a reviewer would want to know about before merging: logic errors, race conditions, unhandled edge cases, resource leaks, violated invariants, and architectural problems (code in the wrong layer, a concept duplicated instead of reused, a design that will not survive the next change).
184
184
 
185
185
  Scope and priorities:
@@ -201,15 +201,15 @@ Do not report:
201
201
  - Missing defense in depth when the input is already validated or the case is already handled elsewhere.
202
202
  - Unchanged code that this change does not affect, unless the problem is serious enough that the author would want to know while they are in this code. Then report it with \`preexisting: true\`; those are listed apart from the findings on the change.
203
203
  - Generic advice with no concrete defect behind it: "consider using library X", "consider adding error handling", "this could be refactored".
204
- `.trim();function Sm(e){let t=e?.trim();return t?`
204
+ `.trim();function Jm(e){let t=e?.trim();return t?`
205
205
 
206
206
  ## Instructions for reviewing this repository
207
207
  The maintainers wrote these for this repository. Follow them; where they conflict with the general guidance above, they win.
208
208
 
209
- ${t}`:""}function eu(e,t){let n=e.body?.slice(0,t);if(n)return n;if(e.stated)return"(No description was written. Treat the requester's statement below as the statement of intent, and do not report the missing description as a gap.)";return e.commits?"(No description was written. Treat the commit messages below as the statement of intent, and do not report the missing description as a gap.)":"(No description and no commit messages: infer the intent from the diff alone, and do not report the missing description as a gap.)"}function ui(e,t){let n=e.stated?.trim().slice(0,t);return n?`
209
+ ${t}`:""}function pu(e,t){let n=e.body?.slice(0,t);if(n)return n;if(e.stated)return"(No description was written. Treat the requester's statement below as the statement of intent, and do not report the missing description as a gap.)";return e.commits?"(No description was written. Treat the commit messages below as the statement of intent, and do not report the missing description as a gap.)":"(No description and no commit messages: infer the intent from the diff alone, and do not report the missing description as a gap.)"}function mi(e,t){let n=e.stated?.trim().slice(0,t);return n?`
210
210
 
211
211
  Stated by the requester:
212
- ${n}`:""}var xm={title:"t",goal:"g",expected_changes:["e"]};function tu(e){if(!e)return"";let t=e.expected_changes.map((n)=>`- ${n}`).join(`
212
+ ${n}`:""}var Vm={title:"t",goal:"g",expected_changes:["e"]};function hu(e){if(!e)return"";let t=e.expected_changes.map((n)=>`- ${n}`).join(`
213
213
  `);return`## Inferred intent (drafted by a smaller model from the whole diff; it may be wrong, so check it against the code)
214
214
  Title: ${e.title}
215
215
  ${e.goal}${t?`
@@ -217,9 +217,9 @@ ${e.goal}${t?`
217
217
  Expected changes:
218
218
  ${t}`:""}
219
219
 
220
- `}var fa=`You infer the intent of a code change for a code review bot, before any reviewer reads the code. Reviewers each see one part of the change, and will use your output to judge whether their part does what the change set out to do. Be concrete and specific to this change. Do not praise or critique the code, and do not look for bugs.
220
+ `}var ba=`You infer the intent of a code change for a code review bot, before any reviewer reads the code. Reviewers each see one part of the change, and will use your output to judge whether their part does what the change set out to do. Be concrete and specific to this change. Do not praise or critique the code, and do not look for bugs.
221
221
 
222
- You have no tools except writing your answer. Everything you need is in the message.`;function pa(e){let t=e.branch?`Branch: ${e.branch}
222
+ You have no tools except writing your answer. Everything you need is in the message.`;function va(e){let t=e.branch?`Branch: ${e.branch}
223
223
 
224
224
  `:"",n=e.otherFiles.length?`
225
225
 
@@ -228,7 +228,7 @@ ${e.otherFiles.map((r)=>`- ${r}`).join(`
228
228
  `)}`:"";return`${t}## Pull request description
229
229
  Title: ${e.intent.title||"(none)"}
230
230
 
231
- ${e.intent.body.slice(0,4000)||"(none)"}${ui(e.intent,4000)}
231
+ ${e.intent.body.slice(0,4000)||"(none)"}${mi(e.intent,4000)}
232
232
 
233
233
  ## Commit messages (oldest last)
234
234
  ${e.intent.commits.slice(0,6000)||"(none)"}
@@ -249,9 +249,9 @@ Write a single JSON object to \`${e.outFile}\` with the write tool, and do nothi
249
249
  "goal": "2-4 sentences: what the change is for and the main approach",
250
250
  "expected_changes": ["each distinct piece of work the change contains"]
251
251
  }
252
- \`\`\``}function nu(e){let t=e.unit.files.map((s)=>`\`${s}\``).join(", "),n=e.sinceLast?`
252
+ \`\`\``}function mu(e){let t=e.unit.files.map((s)=>`\`${s}\``).join(", "),n=e.sinceLast?`
253
253
  ## Changes since the last review
254
- This change was reviewed before, and the earlier findings are listed above. ${Rm}
254
+ This change was reviewed before, and the earlier findings are listed above. ${zm}
255
255
  \`\`\`diff
256
256
  ${e.sinceLast}
257
257
  \`\`\`
@@ -261,9 +261,9 @@ These changed files are linked to files that another reviewer has. That reviewer
261
261
  ${e.crossLinks.map((s)=>`- ${s}`).join(`
262
262
  `)}`:"";return`You are reviewing one coherent part of a pull request in the ${yt} repository.
263
263
 
264
- ${Tk}${Sm(e.instructions)}
264
+ ${xE}${Jm(e.instructions)}
265
265
 
266
- ${Mk}
266
+ ${vE}
267
267
 
268
268
  This is ONE SLICE of a larger pull request: **${e.unit.title}**. ${e.unit.rationale??""}
269
269
 
@@ -274,12 +274,12 @@ Other changed files in this pull request are being reviewed separately; do not c
274
274
  ## Pull request intent (as stated by the author)
275
275
  Title: ${e.intent.title}
276
276
 
277
- ${eu(e.intent,4000)}${ui(e.intent,4000)}
277
+ ${pu(e.intent,4000)}${mi(e.intent,4000)}
278
278
 
279
279
  Commit messages:
280
280
  ${e.intent.commits.slice(0,3000)||"(none)"}
281
281
 
282
- ${tu(e.draft)}${e.mapNote}${e.registry?`
282
+ ${hu(e.draft)}${e.mapNote}${e.registry?`
283
283
  ${e.registry}
284
284
  `:""}${e.prior?`
285
285
  ${e.prior}
@@ -289,10 +289,10 @@ ${e.prior}
289
289
  ${e.diff}
290
290
  \`\`\`
291
291
  ${n}
292
- Write your findings as JSON to \`${e.outFile}\`. Write the file even if you have no findings (use an empty array).`}function ru(e){let t=Boolean(e.disputes?.includes("## Findings the author disputes")),n=e.sinceLast?`
292
+ Write your findings as JSON to \`${e.outFile}\`. Write the file even if you have no findings (use an empty array).`}function gu(e){let t=Boolean(e.disputes?.includes("## Findings the author disputes")),n=e.sinceLast?`
293
293
  ## This is a re-review
294
- This change was reviewed before. Only these files changed since then, and only they were reviewed again: ${e.sinceLast.map((s)=>`\`${s}\``).join(", ")}. ${Rm} Earlier findings in files that did not change stay open on their own; do not close them out as resolved.
295
- `:"",r=e.findings.map((s,o)=>{let a=e.changedLines&&To(e.changedLines,s.file,s.line,s.end_line).kind!=="anchorable";return{...s,id:o,...a?{hint:vm}:{}}});return`You are the coordinator for a code review of a pull request in ${yt}. Independent reviewers each looked at one changed file. Your job is to turn their raw findings into the review that actually gets posted.${Sm(e.instructions)}
294
+ This change was reviewed before. Only these files changed since then, and only they were reviewed again: ${e.sinceLast.map((s)=>`\`${s}\``).join(", ")}. ${zm} Earlier findings in files that did not change stay open on their own; do not close them out as resolved.
295
+ `:"",r=e.findings.map((s,o)=>{let a=e.changedLines&&Wo(e.changedLines,s.file,s.line,s.end_line).kind!=="anchorable";return{...s,id:o,...a?{hint:Wm}:{}}});return`You are the coordinator for a code review of a pull request in ${yt}. Independent reviewers each looked at one changed file. Your job is to turn their raw findings into the review that actually gets posted.${Jm(e.instructions)}
296
296
 
297
297
  ## Changed files
298
298
  ${e.files.map((s)=>`- ${s}`).join(`
@@ -301,12 +301,12 @@ ${e.files.map((s)=>`- ${s}`).join(`
301
301
  ## Pull request intent (as stated by the author)
302
302
  Title: ${e.intent.title}
303
303
 
304
- ${eu(e.intent,4000)}${ui(e.intent,4000)}
304
+ ${pu(e.intent,4000)}${mi(e.intent,4000)}
305
305
 
306
306
  Commit messages:
307
307
  ${e.intent.commits.slice(0,3000)||"(none)"}
308
308
  ${e.draft?`
309
- ${tu(e.draft).trimEnd()}
309
+ ${hu(e.draft).trimEnd()}
310
310
  `:""}${e.prior?`
311
311
  ${e.prior}
312
312
  `:""}${e.disputes?`
@@ -342,9 +342,9 @@ Do all of the following:
342
342
 
343
343
  6. **Judge intent alignment.** Compare what the author said this PR does against what the diff actually does. Report only substantive divergences: behavior changed that the description does not mention, a stated goal the diff does not accomplish, or scope that looks unrelated to the stated purpose. Say nothing if it lines up.${e.draft?" Judge against the author's statement, not the inferred intent: the draft was written from the diff, so it cannot show the diff missing a goal.":""}
344
344
 
345
- 7. **Separate what was already there.** A finding is pre-existing when the problem is in code this change did not add or modify, and the change does not make it worse or newly reachable. Reviewers mark these with \`preexisting: true\`, and a finding whose cited line falls outside the lines this change added carries \`"hint": "${vm}"\`. The hint is only a hint: a changed caller can make an untouched line newly reachable, and then the finding belongs to the change. Set \`preexisting\` on a kept finding to correct the reviewer either way. Keep the severity as it is; the flag already says the change did not introduce it.
345
+ 7. **Separate what was already there.** A finding is pre-existing when the problem is in code this change did not add or modify, and the change does not make it worse or newly reachable. Reviewers mark these with \`preexisting: true\`, and a finding whose cited line falls outside the lines this change added carries \`"hint": "${Wm}"\`. The hint is only a hint: a changed caller can make an untouched line newly reachable, and then the finding belongs to the change. Set \`preexisting\` on a kept finding to correct the reviewer either way. Keep the severity as it is; the flag already says the change did not introduce it.
346
346
 
347
- 8. **Cap.** Keep at most ${e.maxNew??Qn} new findings on the change, and at most ${da} pre-existing ones, which are capped separately. Anything carrying \`repeat_of\` is shown in a separate section and does not count against either limit. Production impact decides what survives the cut: a finding in shipped \`src/\` code or in deployment config outranks one in \`scripts/\` or a test harness at the same severity. Keep a tooling finding only when the tooling is actually broken \u2014 sloppiness there is not worth a comment. Cut low-confidence and nice-to-have items first. Sorting is handled for you. A finding that is sound but did not make the cut goes in \`drop\` with the reason \`cap\` and nothing else; those are listed separately for the author, so do not use \`cap\` for anything you rejected on its merits.
347
+ 8. **Cap.** Keep at most ${e.maxNew??nr} new findings on the change, and at most ${ya} pre-existing ones, which are capped separately. Anything carrying \`repeat_of\` is shown in a separate section and does not count against either limit. Production impact decides what survives the cut: a finding in shipped \`src/\` code or in deployment config outranks one in \`scripts/\` or a test harness at the same severity. Keep a tooling finding only when the tooling is actually broken \u2014 sloppiness there is not worth a comment. Cut low-confidence and nice-to-have items first. Sorting is handled for you. A finding that is sound but did not make the cut goes in \`drop\` with the reason \`cap\` and nothing else; those are listed separately for the author, so do not use \`cap\` for anything you rejected on its merits.
348
348
 
349
349
  Your output is a set of decisions, not a rewritten review. The reviewers' own wording is kept verbatim, so do not restate it \u2014 every finding you keep must be listed by number, and every finding you do not keep must appear in \`drop\` with a reason. Correct a finding only through \`severity\`, which overrides theirs, or \`note\`, one sentence appended to their explanation when they got the reasoning slightly wrong but the finding stands.
350
350
 
@@ -363,14 +363,14 @@ Write a single JSON object to \`${e.outFile}\`:
363
363
  }
364
364
  }
365
365
  \`\`\`
366
- \`severity\`, \`repeats\`, \`merge_with\`, \`repeat_of\`, \`preexisting\` and \`note\` are all optional, and \`resolved\` is an empty array when nothing you previously raised has been fixed. Ids in \`resolved\` are comment ids from the "what you already told this author" section, not finding numbers.${t?" `disputes` has one entry per disputed finding, keyed by the `fp` it was listed with.":""} Write the file even if \`keep\` is empty.`}function $m(e){return Pk("sha256").update(e).digest("hex").slice(0,12)}function km(e){let t={title:"t",body:"b",commits:"c",stated:"s"},r=[e,nu({unit:{id:"u",title:"u",files:["f"]},diff:"d",intent:t,draft:xm,registry:"",prior:"",mapNote:"",outFile:"o"}),ru({findings:[],intent:t,draft:xm,files:["f"],prior:"",outFile:"o"}),fa,pa({intent:t,diffstat:"s",diff:"d",otherFiles:[],outFile:"o"})].map((s)=>s.replaceAll(yt,"{{repo}}"));return $m(r.join("\x00"))}function Em(e){let t=e?.trim();return t?$m(t):void 0}function iu(e,t){let n=new Set,r=[];for(let o of e){let a=(o.files??[]).filter((l)=>t.includes(l)&&!n.has(l));for(let l of a)n.add(l);if(a.length)r.push({...o,files:a})}let s=t.filter((o)=>!n.has(o));if(s.length)r.push({id:"unassigned",title:"Remaining changes",rationale:"These files were not grouped with any flow; review them on their own terms.",files:s,priority:9});return r}function Am(e,t,n){let r=[];for(let s of e){let o=[...s.files].sort((l,c)=>(t.get(c)??0)-(t.get(l)??0)||l.localeCompare(c)),a=[];for(let l of o){let c=t.get(l)??0,u=a.find((d)=>d.tokens+c<=n);if(u)u.files.push(l),u.tokens+=c;else a.push({files:[l],tokens:c})}a.forEach((l,c)=>{r.push({unitId:s.id,title:a.length>1?`${s.title} (part ${c+1} of ${a.length})`:s.title,rationale:s.rationale,priority:s.priority,files:[...l.files].sort(),part:c+1,parts:a.length,tokens:l.tokens})})}return r}function Cm(e){return`You are planning how to split up the review of a pull request in ${yt}. You are not reviewing anything and you are not looking for bugs. You are deciding which changed files each reviewer should see together.
366
+ \`severity\`, \`repeats\`, \`merge_with\`, \`repeat_of\`, \`preexisting\` and \`note\` are all optional, and \`resolved\` is an empty array when nothing you previously raised has been fixed. Ids in \`resolved\` are comment ids from the "what you already told this author" section, not finding numbers.${t?" `disputes` has one entry per disputed finding, keyed by the `fp` it was listed with.":""} Write the file even if \`keep\` is empty.`}function Xm(e){return bE("sha256").update(e).digest("hex").slice(0,12)}function Ym(e){let t={title:"t",body:"b",commits:"c",stated:"s"},r=[e,mu({unit:{id:"u",title:"u",files:["f"]},diff:"d",intent:t,draft:Vm,registry:"",prior:"",mapNote:"",outFile:"o"}),gu({findings:[],intent:t,draft:Vm,files:["f"],prior:"",outFile:"o"}),ba,va({intent:t,diffstat:"s",diff:"d",otherFiles:[],outFile:"o"})].map((s)=>s.replaceAll(yt,"{{repo}}"));return Xm(r.join("\x00"))}function Zm(e){let t=e?.trim();return t?Xm(t):void 0}function _u(e,t){let n=new Set,r=[];for(let o of e){let a=(o.files??[]).filter((l)=>t.includes(l)&&!n.has(l));for(let l of a)n.add(l);if(a.length)r.push({...o,files:a})}let s=t.filter((o)=>!n.has(o));if(s.length)r.push({id:"unassigned",title:"Remaining changes",rationale:"These files were not grouped with any flow; review them on their own terms.",files:s,priority:9});return r}function Qm(e,t,n){let r=[];for(let s of e){let o=[...s.files].sort((l,c)=>(t.get(c)??0)-(t.get(l)??0)||l.localeCompare(c)),a=[];for(let l of o){let c=t.get(l)??0,u=a.find((d)=>d.tokens+c<=n);if(u)u.files.push(l),u.tokens+=c;else a.push({files:[l],tokens:c})}a.forEach((l,c)=>{r.push({unitId:s.id,title:a.length>1?`${s.title} (part ${c+1} of ${a.length})`:s.title,rationale:s.rationale,priority:s.priority,files:[...l.files].sort(),part:c+1,parts:a.length,tokens:l.tokens})})}return r}function eg(e){return`You are planning how to split up the review of a pull request in ${yt}. You are not reviewing anything and you are not looking for bugs. You are deciding which changed files each reviewer should see together.
367
367
 
368
368
  Work from the outline below. **Do not read files from the repository** \u2014 you do not need them for this decision, and the reviewers who follow you will do that work.
369
369
 
370
370
  ## Stated intent
371
371
  Title: ${e.intent.title}
372
372
 
373
- ${e.intent.body?.slice(0,2000)||"(no description)"}${ui(e.intent,2000)}
373
+ ${e.intent.body?.slice(0,2000)||"(no description)"}${mi(e.intent,2000)}
374
374
 
375
375
  ## Files changed
376
376
  ${e.diffstat}
@@ -398,15 +398,15 @@ Write only this JSON to \`${e.outFile}\`:
398
398
  { "review_units": [ { "id": "short-slug", "title": "a few words naming the mechanism, not the paths",
399
399
  "rationale": "one sentence the reviewer will read as their brief: what this group does and what would break",
400
400
  "files": ["..."], "priority": 1 } ] }
401
- \`\`\``}function Om(e){let t=new Map(e.groups.flatMap((s)=>s.files.map((o)=>[o,s.id]))),n=e.groups.map((s)=>{let o=s.links.filter((a)=>a.kind!=="dir").slice(0,6).map((a)=>` - ${Rr(a)}`);return[`### ${s.id} (${s.tokens} diff tokens)`,...s.files.map((a)=>`- ${a}`),...o.length?["Linked by:",...o]:[]].join(`
402
- `)}),r=e.links.filter((s)=>s.kind!=="dir"&&t.get(s.from)!==t.get(s.to)).slice(0,20).map((s)=>`- ${Rr(s)} (${t.get(s.from)} \u2192 ${t.get(s.to)})`);return`You are preparing the review of a pull request in ${yt}. The changed files have already been grouped, from links found in the diff: a name used on added lines of one file and defined on added lines of another, a test and the file it tests, an import. Each group goes to its own reviewer, in parallel. You are not reviewing anything and you are not looking for bugs.
401
+ \`\`\``}function tg(e){let t=new Map(e.groups.flatMap((s)=>s.files.map((o)=>[o,s.id]))),n=e.groups.map((s)=>{let o=s.links.filter((a)=>a.kind!=="dir").slice(0,6).map((a)=>` - ${Er(a)}`);return[`### ${s.id} (${s.tokens} diff tokens)`,...s.files.map((a)=>`- ${a}`),...o.length?["Linked by:",...o]:[]].join(`
402
+ `)}),r=e.links.filter((s)=>s.kind!=="dir"&&t.get(s.from)!==t.get(s.to)).slice(0,20).map((s)=>`- ${Er(s)} (${t.get(s.from)} \u2192 ${t.get(s.to)})`);return`You are preparing the review of a pull request in ${yt}. The changed files have already been grouped, from links found in the diff: a name used on added lines of one file and defined on added lines of another, a test and the file it tests, an import. Each group goes to its own reviewer, in parallel. You are not reviewing anything and you are not looking for bugs.
403
403
 
404
404
  Work from what is below. **Do not read files from the repository.**
405
405
 
406
406
  ## Stated intent
407
407
  Title: ${e.intent.title}
408
408
 
409
- ${e.intent.body?.slice(0,2000)||"(no description)"}${ui(e.intent,2000)}
409
+ ${e.intent.body?.slice(0,2000)||"(no description)"}${mi(e.intent,2000)}
410
410
  ${e.registry?`
411
411
  ${e.registry}
412
412
  `:""}
@@ -436,18 +436,18 @@ Write only this JSON to \`${e.outFile}\`:
436
436
  \`\`\`json
437
437
  { "groups": [ { "id": "group id from above", "title": "...", "rationale": "...", "priority": 1 } ],
438
438
  "moves": [ { "file": "path", "to": "group id", "reason": "one sentence" } ] }
439
- \`\`\``}function Fk(e){let t=new Map;for(let n of e){let r=n.lastIndexOf("/"),s=r===-1?"./":n.slice(0,r+1),o=t.get(s);if(o)o.push(n);else t.set(s,[n])}return[...t].sort((n,r)=>r[1].length-n[1].length||n[0].localeCompare(r[0])).map(([n,r])=>r.length===1?`- ${r[0]}`:`- ${n} (${r.length} files)`).join(`
440
- `)}function ha(e){let t=e.findingIndex!==void 0;return`${t?`You are writing the reviewer's guide for a pull request in ${yt}: what the change actually does, and the order a human should read it in. You are NOT looking for bugs \u2014 specialist reviewers have already done that, and their findings are listed below to tell you where the risk turned out to be.`:`You are writing the reader's guide for a change in ${yt}: what the change actually does, and the order a human should read it in. You are NOT looking for bugs. You have no tools for reading the repository: everything you can know about the change is in this prompt, so do not try to open files.`}
439
+ \`\`\``}function SE(e){let t=new Map;for(let n of e){let r=n.lastIndexOf("/"),s=r===-1?"./":n.slice(0,r+1),o=t.get(s);if(o)o.push(n);else t.set(s,[n])}return[...t].sort((n,r)=>r[1].length-n[1].length||n[0].localeCompare(r[0])).map(([n,r])=>r.length===1?`- ${r[0]}`:`- ${n} (${r.length} files)`).join(`
440
+ `)}function xa(e){let t=e.findingIndex!==void 0;return`${t?`You are writing the reviewer's guide for a pull request in ${yt}: what the change actually does, and the order a human should read it in. You are NOT looking for bugs \u2014 specialist reviewers have already done that, and their findings are listed below to tell you where the risk turned out to be.`:`You are writing the reader's guide for a change in ${yt}: what the change actually does, and the order a human should read it in. You are NOT looking for bugs. You have no tools for reading the repository: everything you can know about the change is in this prompt, so do not try to open files.`}
441
441
 
442
442
  ## Stated description (what the author says it does)
443
443
  Title: ${e.intent.title}
444
444
 
445
- ${eu(e.intent,4000)}${ui(e.intent,4000)}
445
+ ${pu(e.intent,4000)}${mi(e.intent,4000)}
446
446
 
447
447
  Commit messages:
448
448
  ${e.intent.commits.slice(0,3000)||"(none)"}
449
449
 
450
- ${tu(e.draft)}## Files changed
450
+ ${hu(e.draft)}## Files changed
451
451
  ${e.diffstat}
452
452
 
453
453
  ## ${t?"How the review was split up":"How the files are grouped"}
@@ -464,14 +464,14 @@ ${t?`## What the reviewers found
464
464
  ${e.findingIndex||"(nothing)"}
465
465
 
466
466
  `:""}${e.docsFiles.length?`## Documentation-only files (${t?"already excluded from review; ":""}cover them with one \`support\` group)
467
- ${Fk(e.docsFiles)}
467
+ ${SE(e.docsFiles)}
468
468
  `:""}${e.registry?`
469
469
  ${e.registry}
470
470
  `:""}
471
471
  ## Diff
472
472
  Each line inside a hunk starts with its line number in the new version of the file, then the usual diff marker. Removed lines have no number. Cite these numbers; do not count lines from the \`@@\` headers.
473
473
  \`\`\`diff
474
- ${Fp(e.diff)}
474
+ ${fh(e.diff)}
475
475
  \`\`\`
476
476
  ${e.sketches.length?`
477
477
  ## Changed files whose diff is not shown above (${e.sketches.length})
@@ -505,179 +505,179 @@ Write a single JSON object to \`${e.outFile}\`:
505
505
  }
506
506
  \`\`\`
507
507
 
508
- Write the object once, in one \`write\` call, and nothing else. Everything above bounds it: at most 14 stops, at most 8 support groups, prose of 1-3 sentences. A guide that runs past those limits is a worse guide, not a more thorough one, and one long enough to exhaust your output budget is not delivered at all.`}Sr();import $r from"path";xr();function di(e,t=""){let n=e.match(/`+/g)??[],r=Math.max(3,...n.map((o)=>o.length+1)),s="`".repeat(r);return`${s}${t}
508
+ Write the object once, in one \`write\` call, and nothing else. Everything above bounds it: at most 14 stops, at most 8 support groups, prose of 1-3 sentences. A guide that runs past those limits is a worse guide, not a more thorough one, and one long enough to exhaust your output budget is not delivered at all.`}Cr();import Ar from"path";kr();function gi(e,t=""){let n=e.match(/`+/g)??[],r=Math.max(3,...n.map((o)=>o.length+1)),s="`".repeat(r);return`${s}${t}
509
509
  ${e.replace(/\n$/,"")}
510
- ${s}`}function _n(e){let t=e.match(/`+/g)??[],n=Math.max(1,...t.map((o)=>o.length+1)),r="`".repeat(n),s=e.startsWith("`")||e.endsWith("`")?" ":"";return`${r}${s}${e}${s}${r}`}bt();Sr();ca();var Nk={high:"\uD83D\uDD34",moderate:"\uD83D\uDFE1",low:"\uD83D\uDFE2"},Im=["blocker","should-fix","nice-to-have","question"];function ou(e){if(!e)return()=>!1;let t=Im.indexOf(e);return(n)=>Im.indexOf(n.severity)>t}function su(e){return{file:e.file,line:e.line,fp:gn(e.file,e.title),sev:e.severity,...e.preexisting?{pre:1}:{}}}function Dk(e){let t=e.repo??yt,n=(y,_)=>`https://github.com/${t}/blob/${e.head}/${y}${_?`#L${_}`:""}`,r=(y,_,F)=>{let A=F??`${y.split("/").pop()}${_?`:${_}`:""}`;if(!e.pr)return A.includes("`")?A:`\`${A}\``;return`[${A}](${n(y,_)})`},s=(y)=>{let _=y.match(/^(.+?):(\d+)(?:-\d+)?$/);return _?.[1]&&_[2]?r(_[1],Number(_[2]),y):r(y,void 0,y)},o=[...e.findings].sort((y,_)=>(tt[y.severity]?.rank??9)-(tt[_.severity]?.rank??9)||qt[ot(y.file)]-qt[ot(_.file)]||ci.indexOf(y.confidence)-ci.indexOf(_.confidence)),a=o.filter((y)=>y.repeat_of),l=o.filter((y)=>!y.repeat_of),c=l.filter((y)=>y._anchor?.kind!=="off-diff"),u=new Map((e.prior??[]).map((y)=>[y.id,y])),d=e.rulings??[],f=()=>{let y=new Set(d.map((F)=>F.fp)),_=[...(e.earlierRulings??[]).filter((F)=>!y.has(F.fp)).map((F)=>`- ${F.label} ${Mt("dispute",{fp:F.fp,outcome:F.outcome})}`),...d.map((F)=>{let A=F.outcome==="withdrawn"?"\u21A9\uFE0F Withdrawn":"Upheld, for a human reviewer",Q=F.note?` \u2014 ${F.note}`:"";return`- ${A}: \`${F.file}:${F.line}\` ${F.claim} (disputed by @${F.author})${Q} `+Mt("dispute",{fp:F.fp,outcome:F.outcome})})];if(!_.length)return"";return[`<details><summary>Disputed findings (${_.length})</summary>`,"",..._,"","</details>"].join(`
511
- `)},p=Mt("summary",{...e.pr?{pr:e.pr}:{},...e.runs?{runs:e.runs}:{},head:e.head}),h=l.reduce((y,_)=>(y[_.severity]=(y[_.severity]??0)+1,y),{}),g=(y,_,F)=>{let A=[],Q=tt[y.severity]?.badge??y.severity,fe=fm[y.category]??y.category,Ce=y.end_line&&y.end_line!==y.line?`-${y.end_line}`:"",Jt=_==="summary"?r(y.file,y.line,`${y.file}:${y.line}${Ce}`):`\`${y.file}:${y.line}${Ce}\``;if(A.push(`${_==="summary"?"#####":"####"} ${F??y.title}`),A.push(""),A.push([Q,fe,um[y.effort??""],`confidence: ${y.confidence}`,Jt,cm[ot(y.file)],y.preexisting?"pre-existing":""].filter(Boolean).join(" \xB7 ")),_==="inline"&&y._anchor?.kind==="off-hunk")A.push(""),A.push(`> Posted here because GitHub only accepts comments on changed lines. The code this is about is at \`${y.file}:${y.line}${Ce}\`.`);if(A.push(""),A.push(y.impact?.trim()||ua(y.explanation)),y.also_at?.length)A.push(""),A.push(`Same problem at: ${y.also_at.map(s).join(", ")}`);if(y.explanation)A.push(""),A.push("<details><summary>Why this is a problem</summary>"),A.push(""),A.push(y.explanation),A.push(""),A.push("</details>");if(y.evidence||y.cross_file_refs?.length){if(A.push(""),A.push("<details><summary>Evidence</summary>"),A.push(""),y.evidence)A.push(y.evidence);if(y.cross_file_refs?.length){A.push(""),A.push("Also read:");for(let pe of y.cross_file_refs)A.push(`- \`${pe}\``)}A.push(""),A.push("</details>")}if(y.suggested_code){if(y._original!==void 0){let ct=y._original.replace(/\n$/,"").split(`
512
- `).map((cn)=>`-${cn}`),ho=y.suggested_code.replace(/\n$/,"").split(`
513
- `).map((cn)=>`+${cn}`);A.push(""),A.push("<details><summary>What this changes</summary>"),A.push(""),A.push(di([...ct,...ho].join(`
514
- `),"diff")),A.push(""),A.push("</details>")}A.push("");let pe=_==="inline"&&dm(y);if(pe)A.push("_Applying this commits it as written \u2014 read it first._"),A.push("");else if(_==="inline"){let ct=y.end_line&&y.end_line!==y.line?`${y.line}-${y.end_line}`:`${y.line}`;A.push(`_Replaces ${_n(`${y.file}:${ct}`)}. Not offered as a committable suggestion because this comment is anchored elsewhere._`),A.push("")}A.push(di(y.suggested_code,pe?"suggestion":""))}else if(y.suggestion)A.push(""),A.push(`_Suggested fix:_ ${y.suggestion}`);return A.push(""),A.push(_==="inline"?Mt("inline",su(y)):Mt("summary-item",su(y))),A.join(`
515
- `)},w=(y)=>y.replace(/\s+/g," ").trim(),b=lm(e.changedFiles??[],l),x=(y)=>qt[ot(y.file)]<=qt[b],R=ou(e.minSeverity),P=l.filter((y)=>!R(y)),M=P.filter(x),k=P.filter((y)=>!x(y)),E=l.filter(R),D=(e.inlineMode??"none")==="none"?[]:c.filter((y)=>x(y)&&!R(y)),L=new Set(D),O=[...M,...k,...E],U=new Map;for(let y of O)U.set(y,U.size+1);let I=[];I.push(`### Review of \`${e.head.slice(0,12)}\``),I.push("");let j=e.unreviewed?.overCap??[],H=e.unreviewed?.failed??[],ve=e.unreviewed?.budget??[],Se=j.length+H.length+ve.length>0;if(Se){let y=[j.length?`${j.length} over the slice cap`:"",H.length?`${H.length} in a reviewer that failed`:"",ve.length?`${ve.length} skipped at the cost limit`:""].filter(Boolean),_=[...H,...ve,...j],F=_.slice(0,5).map((Q)=>`\`${Q}\``).join(", "),A=_.length>5?`, and ${_.length-5} more`:"";I.push(`\u26A0\uFE0F **Partial review:** ${_.length} changed code ${_.length===1?"file was":"files were"} not reviewed (${y.join(", ")}): ${F}${A}.`),I.push("")}if(l.length===0)I.push(e.noReviewers?"No reviewer ran on this change. What follows is the reading guide only \u2014 it is not a statement that the code is clean.":Se?"No new issues found in the reviewed files.":"No new issues found in the changed files.");else{let y=(_)=>`${Nk[_.level]} **${_.label}** \u2014 ${_.detail}`;I.push(y(sm(l))),I.push(""),I.push(y(om(l.map((_)=>({severity:_.severity,preexisting:_.preexisting,surface:ot(_.file)}))))),I.push(""),I.push(Object.entries(tt).filter(([_])=>h[_]).map(([_,F])=>`${F.badge}: ${h[_]}`).join(" \xB7 "))}I.push("");let ne=e.walkthrough,ce=ne?.intent,Be=e.intentAlignment,ze={aligned:"\u2705 Matches the description",partial:"\u26A0\uFE0F Partly matches the description",misaligned:"\u274C Does not match the description"},Je=[...ce?.unstated??[],...Be?.unstated??[]],Xe=[...ce?.missing??[],...Be?.missing??[]],nt=ce?.alignment==="aligned"&&Be?.summary?"partial":ce?.alignment,be=nt?ze[nt]:void 0,Te=Be?.summary??ce?.mismatches?.[0],me=[],W=[];if(W.push(`# Review of \`${e.head.slice(0,12)}\`${e.pr?` \u2014 PR #${e.pr}`:""}`),W.push(""),W.push("Everything the summary comment links to rather than carries."),W.push(""),be||Te||ce?.inferred||Je.length||Xe.length){if(me.push(`**Intent:** ${be??"\u2139\uFE0F Not assessed"}${Te?` \u2014 ${Te}`:""}`),ce?.inferred)me.push("",`**What it does:** ${ua(ce.inferred,320)}`);if(me.push(""),W.push("## What the change actually does, read from the code"),W.push(""),ce?.inferred)W.push(ce.inferred,"");if(ce?.matches?.length){W.push("Description holds up on:");for(let y of ce.matches)W.push(`- ${y}`);W.push("")}if(ce?.mismatches?.length){W.push("Description does not hold up on:");for(let y of ce.mismatches)W.push(`- ${y}`);W.push("")}if(Je.length){W.push("In the diff but not in the description:");for(let y of Je)W.push(`- ${y}`);W.push("")}if(Xe.length){W.push("Described but not accomplished:");for(let y of Xe)W.push(`- ${y}`);W.push("")}}if(ne?.focus)me.push(`**What to focus on:** ${ne.focus}`,"");let T=ne?.chapters??[],B=T.reduce((y,_)=>y+(_.stops?.length??0),0);if(ne?.start_here?.length||B){let y={bug:"\uD83D\uDC1B",wrench:"\uD83D\uDD27",path:"\uD83D\uDEE4\uFE0F",flask:"\uD83E\uDDEA",doc:"\uD83D\uDCC4",gear:"\u2699\uFE0F"},_={critical:" \uD83D\uDD34",normal:"",context:" _(context)_"};if(ne?.start_here?.length){me.push("**Start here**"),me.push("");for(let A of ne.start_here)me.push(`1. ${r(A.file,void 0,`\`${A.file}\``)} \u2014 ${A.why}`);me.push("")}if(B||ne?.support?.length)W.push(`## Guided walkthrough \u2014 ${T.length} ${T.length===1?"part":"parts"}, ${B} ${B===1?"stop":"stops"}`),W.push("");let F=0;for(let A of T){if(W.push(`### ${y[A.icon??""]??"\u25B8"} ${A.title}`),A.blurb)W.push("",`_${A.blurb}_`);W.push("");for(let Q of A.stops??[]){if(F++,W.push(`**${F}. ${Q.title}**${_[Q.importance??"normal"]??""}`),Q.prose)W.push("",Q.prose);if(Q.locations?.length)W.push("",`\u21B3 ${Q.locations.map((fe)=>r(fe.file,fe.line,fe.label)).join(" \xB7 ")}`);W.push("")}}if(ne?.support?.length){W.push("### Safe to skim"),W.push("");for(let A of ne.support){let Q=A.files.map((fe)=>`\`${fe}\``).join(", ");W.push(`- ${Q} \u2014 ${A.reason}`)}W.push("")}}let z=(y)=>{let _=new Map;for(let A of y){let Q=_.get(A.file);if(Q)Q.push(A);else _.set(A.file,[A])}let F=[];for(let[A,Q]of _){F.push(`- \`${A}\``);for(let fe of Q){let Ce=tt[fe.severity]?.badge??fe.severity,Jt=fe._anchor?.kind==="off-diff"?`${r(fe.file,fe.line,`L${fe.line}`)} \uD83D\uDCCE outside the diff`:r(fe.file,fe.line,`L${fe.line}`),pe=L.has(fe)?"":` ${Mt("summary-item",su(fe))}`,ct=fe.also_at?.length?` \xB7 also ${fe.also_at.map(s).join(", ")}`:"";F.push(` - ${Ce} ${w(fe.title)} \u2014 ${Jt}${ct} \xB7 _[${U.get(fe)}]_${pe}`)}}return F};if(M.length)I.push(`#### ${im[b]} (${M.length})`),I.push(""),I.push(...z(M)),I.push("");if(k.length)I.push(`<details><summary>Everything else (${k.length}) \u2014 lower-risk surfaces</summary>`),I.push(""),I.push(...z(k)),I.push(""),I.push("</details>"),I.push("");if(E.length&&e.minSeverity)I.push(`<details><summary>Minor findings (${E.length}) \u2014 below ${e.minSeverity}</summary>`),I.push(""),I.push(...z(E)),I.push(""),I.push("</details>"),I.push("");let te=e.carried??[];if(te.length){I.push(`<details><summary>Still open from earlier reviews (${te.length}) \u2014 not posted again this review</summary>`),I.push("");for(let y of te){let _={file:y.file,line:y.line,fp:y.fp,...y.sev?{sev:y.sev}:{},...y.pre?{pre:1}:{}};I.push(`- ${y.text||`\`${y.file}:${y.line}\``} ${Mt("summary-item",_)}`)}I.push(""),I.push("</details>"),I.push("")}let we=e.overCap??[];if(we.length)I.push(`\u2795 ${we.length} more ${we.length===1?"finding":"findings"} past the ${Qn}-finding cap,`+" listed under \u201CPast the cap\u201D in the detail file."),I.push("");let Ne=e.checked??[];if(I.push(...me),a.length){I.push(`<details><summary>Agreeing with ${a.length} existing review ${a.length===1?"comment":"comments"}</summary>`),I.push("");for(let y of a){let _=u.get(y.repeat_of),F=_?`@${_.author}`:"an earlier review comment",A=_?.url?`[${F}](${_.url})`:F,Q=tt[y.severity]?.badge??y.severity;I.push(`- ${Q} ${w(y.title)} \u2014 \`${y.file}:${y.line}\` _\u2014 agrees with ${A}_`)}I.push(""),I.push("</details>"),I.push("")}if(O.length){W.push("## Evidence and reasoning"),W.push(""),W.push("Numbered to match the bullets in the summary comment."),W.push("");for(let y of O)W.push(g(y,"summary",`[${U.get(y)}] ${w(y.title)}`)),W.push("")}if(we.length){W.push("## Past the cap"),W.push(""),W.push(`Findings the review kept but did not post, because a review posts at most ${Qn}. Ranked below the posted ones by severity, surface and confidence.`),W.push("");for(let y of we)W.push(g(y,"summary",w(y.title))),W.push("")}if(Ne.length){W.push("## What the reviewers checked"),W.push(""),W.push("Claims each reviewer verified against the code and found correct."),W.push("");for(let y of Ne)W.push(`- ${y}`);W.push("")}let Ye=process.env.GITHUB_RUN_ID,dr=process.env.GITHUB_SERVER_URL??"https://github.com",Ot=e.detailFile??"review-detail.md";if(O.length||B||we.length||Ne.length>8)I.push(Ye?`\uD83D\uDCC4 **[Full review detail](${dr}/${t}/actions/runs/${Ye})** \u2014 download the`+` \`${us(e.pr??"",e.head)}\` artifact and open \`${Ot}\` for the walkthrough and the evidence behind each finding. Artifacts expire 90 days after the run.`:`\uD83D\uDCC4 Full walkthrough and evidence: \`${e.detailPath??Ot}\`.`),I.push("");if(Ne.length&&l.length<=2&&!e.noReviewers){I.push(`<details><summary>What the reviewers checked (${Ne.length})</summary>`),I.push("");for(let y of Ne.slice(0,8))I.push(`- ${y}`);if(Ne.length>8)I.push(`- \u2026and ${Ne.length-8} more in the detail file`);I.push(""),I.push("</details>"),I.push("")}if(e.dropped?.length){I.push("<details><summary>Findings considered and dropped during verification</summary>"),I.push("");for(let y of e.dropped)I.push(`- **${y.title}** \u2014 ${y.reason}`);I.push(""),I.push("</details>"),I.push("")}I.push("<details><summary>Review details</summary>"),I.push("");for(let[y,_]of Object.entries(e.stats))I.push(`- ${y}: ${_}`);I.push(""),I.push("</details>");let Un=[f(),p].filter(Boolean).join(`
516
-
517
- `);I.push(""),I.push(Un);let Bn=D.map((y)=>g(y,"inline")),Nt=a.map((y)=>{let _=y.repeat_of,F=u.get(_),A=[];A.push(`Checked this against \`${e.head.slice(0,12)}\` \u2014 still open. ${tt[y.severity]?.badge??y.severity}`);let Q=y.impact?.trim()||ua(y.explanation,240);if(Q)A.push("",Q);if(y.also_at?.length)A.push("",`Same problem at: ${y.also_at.map(s).join(", ")}`);let fe=[y.explanation,y.evidence].filter(Boolean).join(`
518
-
519
- `);if(fe)A.push("","<details><summary>What I found</summary>","",fe,"","</details>");return A.push("",Mt("reply",{of:_,fp:gn(y.file,y.title)})),{comment_id:_,author:F?.author,url:F?.url,finding:y,body:A.join(`
520
- `)}});for(let y of e.resolved??[]){let _=u.get(y.id);if(!_?.mine||!_.file)continue;let F=y.note?.trim();Nt.push({comment_id:y.id,author:_.author,url:_.url,body:[`\u2705 Fixed as of \`${e.head.slice(0,12)}\`.${F?` ${F}`:""}`,"",Mt("reply",{of:y.id,addressed:1})].join(`
521
- `)})}for(let y of d){if(!y.commentId)continue;let _=u.get(y.commentId),F=y.note?` ${y.note}`:"";Nt.push({comment_id:y.commentId,author:_?.author,url:_?.url,about:`${y.outcome} after a dispute`,body:y.outcome==="withdrawn"?[`\u21A9\uFE0F Withdrawn after @${y.author}'s reply.${F}`,"",Mt("reply",{of:y.commentId,addressed:1,fp:y.fp,dispute:"withdrawn"})].join(`
522
- `):[`Checked @${y.author}'s reply against \`${e.head.slice(0,12)}\` \u2014 this still stands.${F}`,"","Leaving it for a human reviewer to decide.","",Mt("reply",{of:y.commentId,fp:y.fp,dispute:"upheld"})].join(`
523
- `)})}return{summary:jk(I.join(`
524
- `),Un),detail:W.join(`
525
- `),inline:Bn,ordered:D,replies:Nt}}async function Lk(e,t,n){if(n.filter((a)=>a.suggested_code).length===0)return n;let s=new Map,o=[];for(let a of n){if(!a.suggested_code){o.push(a);continue}if(!s.has(a.file))try{s.set(a.file,(await oe("git",["-C",e,"show",`${t}:${a.file}`])).split(`
510
+ ${s}`}function yn(e){let t=e.match(/`+/g)??[],n=Math.max(1,...t.map((o)=>o.length+1)),r="`".repeat(n),s=e.startsWith("`")||e.endsWith("`")?" ":"";return`${r}${s}${e}${s}${r}`}bt();Cr();_a();var RE={high:"\uD83D\uDD34",moderate:"\uD83D\uDFE1",low:"\uD83D\uDFE2"},ng=["blocker","should-fix","nice-to-have","question"];function yu(e){if(!e)return()=>!1;let t=ng.indexOf(e);return(n)=>ng.indexOf(n.severity)>t}function wu(e){return{file:e.file,line:e.line,fp:wn(e.file,e.title),sev:e.severity,...e.preexisting?{pre:1}:{}}}function $E(e){let t=e.repo??yt,n=(y,_)=>`https://github.com/${t}/blob/${e.head}/${y}${_?`#L${_}`:""}`,r=(y,_,D)=>{let C=D??`${y.split("/").pop()}${_?`:${_}`:""}`;if(!e.pr)return C.includes("`")?C:`\`${C}\``;return`[${C}](${n(y,_)})`},s=(y)=>{let _=y.match(/^(.+?):(\d+)(?:-\d+)?$/);return _?.[1]&&_[2]?r(_[1],Number(_[2]),y):r(y,void 0,y)},o=[...e.findings].sort((y,_)=>(tt[y.severity]?.rank??9)-(tt[_.severity]?.rank??9)||Ht[ot(y.file)]-Ht[ot(_.file)]||hi.indexOf(y.confidence)-hi.indexOf(_.confidence)),a=o.filter((y)=>y.repeat_of),l=o.filter((y)=>!y.repeat_of),c=l.filter((y)=>y._anchor?.kind!=="off-diff"),u=new Map((e.prior??[]).map((y)=>[y.id,y])),d=e.rulings??[],f=()=>{let y=new Set(d.map((D)=>D.fp)),_=[...(e.earlierRulings??[]).filter((D)=>!y.has(D.fp)).map((D)=>`- ${D.label} ${Tt("dispute",{fp:D.fp,outcome:D.outcome})}`),...d.map((D)=>{let C=D.outcome==="withdrawn"?"\u21A9\uFE0F Withdrawn":"Upheld, for a human reviewer",Q=D.note?` \u2014 ${D.note}`:"";return`- ${C}: \`${D.file}:${D.line}\` ${D.claim} (disputed by @${D.author})${Q} `+Tt("dispute",{fp:D.fp,outcome:D.outcome})})];if(!_.length)return"";return[`<details><summary>Disputed findings (${_.length})</summary>`,"",..._,"","</details>"].join(`
511
+ `)},p=Tt("summary",{...e.pr?{pr:e.pr}:{},...e.runs?{runs:e.runs}:{},head:e.head}),h=l.reduce((y,_)=>(y[_.severity]=(y[_.severity]??0)+1,y),{}),g=(y,_,D)=>{let C=[],Q=tt[y.severity]?.badge??y.severity,fe=Fm[y.category]??y.category,Ae=y.end_line&&y.end_line!==y.line?`-${y.end_line}`:"",Xt=_==="summary"?r(y.file,y.line,`${y.file}:${y.line}${Ae}`):`\`${y.file}:${y.line}${Ae}\``;if(C.push(`${_==="summary"?"#####":"####"} ${D??y.title}`),C.push(""),C.push([Q,fe,Dm[y.effort??""],`confidence: ${y.confidence}`,Xt,Tm[ot(y.file)],y.preexisting?"pre-existing":""].filter(Boolean).join(" \xB7 ")),_==="inline"&&y._anchor?.kind==="off-hunk")C.push(""),C.push(`> Posted here because GitHub only accepts comments on changed lines. The code this is about is at \`${y.file}:${y.line}${Ae}\`.`);if(C.push(""),C.push(y.impact?.trim()||wa(y.explanation)),y.also_at?.length)C.push(""),C.push(`Same problem at: ${y.also_at.map(s).join(", ")}`);if(y.explanation)C.push(""),C.push("<details><summary>Why this is a problem</summary>"),C.push(""),C.push(y.explanation),C.push(""),C.push("</details>");if(y.evidence||y.cross_file_refs?.length){if(C.push(""),C.push("<details><summary>Evidence</summary>"),C.push(""),y.evidence)C.push(y.evidence);if(y.cross_file_refs?.length){C.push(""),C.push("Also read:");for(let pe of y.cross_file_refs)C.push(`- \`${pe}\``)}C.push(""),C.push("</details>")}if(y.suggested_code){if(y._original!==void 0){let ct=y._original.replace(/\n$/,"").split(`
512
+ `).map((dn)=>`-${dn}`),So=y.suggested_code.replace(/\n$/,"").split(`
513
+ `).map((dn)=>`+${dn}`);C.push(""),C.push("<details><summary>What this changes</summary>"),C.push(""),C.push(gi([...ct,...So].join(`
514
+ `),"diff")),C.push(""),C.push("</details>")}C.push("");let pe=_==="inline"&&Nm(y);if(pe)C.push("_Applying this commits it as written \u2014 read it first._"),C.push("");else if(_==="inline"){let ct=y.end_line&&y.end_line!==y.line?`${y.line}-${y.end_line}`:`${y.line}`;C.push(`_Replaces ${yn(`${y.file}:${ct}`)}. Not offered as a committable suggestion because this comment is anchored elsewhere._`),C.push("")}C.push(gi(y.suggested_code,pe?"suggestion":""))}else if(y.suggestion)C.push(""),C.push(`_Suggested fix:_ ${y.suggestion}`);return C.push(""),C.push(_==="inline"?Tt("inline",wu(y)):Tt("summary-item",wu(y))),C.join(`
515
+ `)},w=(y)=>y.replace(/\s+/g," ").trim(),b=Mm(e.changedFiles??[],l),x=(y)=>Ht[ot(y.file)]<=Ht[b],S=yu(e.minSeverity),P=l.filter((y)=>!S(y)),M=P.filter(x),k=P.filter((y)=>!x(y)),E=l.filter(S),F=(e.inlineMode??"none")==="none"?[]:c.filter((y)=>x(y)&&!S(y)),L=new Set(F),O=[...M,...k,...E],U=new Map;for(let y of O)U.set(y,U.size+1);let I=[];I.push(`### Review of \`${e.head.slice(0,12)}\``),I.push("");let j=e.unreviewed?.overCap??[],H=e.unreviewed?.failed??[],ve=e.unreviewed?.budget??[],Re=j.length+H.length+ve.length>0;if(Re){let y=[j.length?`${j.length} over the slice cap`:"",H.length?`${H.length} in a reviewer that failed`:"",ve.length?`${ve.length} skipped at the cost limit`:""].filter(Boolean),_=[...H,...ve,...j],D=_.slice(0,5).map((Q)=>`\`${Q}\``).join(", "),C=_.length>5?`, and ${_.length-5} more`:"";I.push(`\u26A0\uFE0F **Partial review:** ${_.length} changed code ${_.length===1?"file was":"files were"} not reviewed (${y.join(", ")}): ${D}${C}.`),I.push("")}if(l.length===0)I.push(e.noReviewers?"No reviewer ran on this change. What follows is the reading guide only \u2014 it is not a statement that the code is clean.":Re?"No new issues found in the reviewed files.":"No new issues found in the changed files.");else{let y=(_)=>`${RE[_.level]} **${_.label}** \u2014 ${_.detail}`;I.push(y(Om(l))),I.push(""),I.push(y(Im(l.map((_)=>({severity:_.severity,preexisting:_.preexisting,surface:ot(_.file)}))))),I.push(""),I.push(Object.entries(tt).filter(([_])=>h[_]).map(([_,D])=>`${D.badge}: ${h[_]}`).join(" \xB7 "))}I.push("");let ne=e.walkthrough,ce=ne?.intent,qe=e.intentAlignment,ze={aligned:"\u2705 Matches the description",partial:"\u26A0\uFE0F Partly matches the description",misaligned:"\u274C Does not match the description"},Je=[...ce?.unstated??[],...qe?.unstated??[]],Xe=[...ce?.missing??[],...qe?.missing??[]],nt=ce?.alignment==="aligned"&&qe?.summary?"partial":ce?.alignment,be=nt?ze[nt]:void 0,Te=qe?.summary??ce?.mismatches?.[0],me=[],G=[];if(G.push(`# Review of \`${e.head.slice(0,12)}\`${e.pr?` \u2014 PR #${e.pr}`:""}`),G.push(""),G.push("Everything the summary comment links to rather than carries."),G.push(""),be||Te||ce?.inferred||Je.length||Xe.length){if(me.push(`**Intent:** ${be??"\u2139\uFE0F Not assessed"}${Te?` \u2014 ${Te}`:""}`),ce?.inferred)me.push("",`**What it does:** ${wa(ce.inferred,320)}`);if(me.push(""),G.push("## What the change actually does, read from the code"),G.push(""),ce?.inferred)G.push(ce.inferred,"");if(ce?.matches?.length){G.push("Description holds up on:");for(let y of ce.matches)G.push(`- ${y}`);G.push("")}if(ce?.mismatches?.length){G.push("Description does not hold up on:");for(let y of ce.mismatches)G.push(`- ${y}`);G.push("")}if(Je.length){G.push("In the diff but not in the description:");for(let y of Je)G.push(`- ${y}`);G.push("")}if(Xe.length){G.push("Described but not accomplished:");for(let y of Xe)G.push(`- ${y}`);G.push("")}}if(ne?.focus)me.push(`**What to focus on:** ${ne.focus}`,"");let T=ne?.chapters??[],B=T.reduce((y,_)=>y+(_.stops?.length??0),0);if(ne?.start_here?.length||B){let y={bug:"\uD83D\uDC1B",wrench:"\uD83D\uDD27",path:"\uD83D\uDEE4\uFE0F",flask:"\uD83E\uDDEA",doc:"\uD83D\uDCC4",gear:"\u2699\uFE0F"},_={critical:" \uD83D\uDD34",normal:"",context:" _(context)_"};if(ne?.start_here?.length){me.push("**Start here**"),me.push("");for(let C of ne.start_here)me.push(`1. ${r(C.file,void 0,`\`${C.file}\``)} \u2014 ${C.why}`);me.push("")}if(B||ne?.support?.length)G.push(`## Guided walkthrough \u2014 ${T.length} ${T.length===1?"part":"parts"}, ${B} ${B===1?"stop":"stops"}`),G.push("");let D=0;for(let C of T){if(G.push(`### ${y[C.icon??""]??"\u25B8"} ${C.title}`),C.blurb)G.push("",`_${C.blurb}_`);G.push("");for(let Q of C.stops??[]){if(D++,G.push(`**${D}. ${Q.title}**${_[Q.importance??"normal"]??""}`),Q.prose)G.push("",Q.prose);if(Q.locations?.length)G.push("",`\u21B3 ${Q.locations.map((fe)=>r(fe.file,fe.line,fe.label)).join(" \xB7 ")}`);G.push("")}}if(ne?.support?.length){G.push("### Safe to skim"),G.push("");for(let C of ne.support){let Q=C.files.map((fe)=>`\`${fe}\``).join(", ");G.push(`- ${Q} \u2014 ${C.reason}`)}G.push("")}}let z=(y)=>{let _=new Map;for(let C of y){let Q=_.get(C.file);if(Q)Q.push(C);else _.set(C.file,[C])}let D=[];for(let[C,Q]of _){D.push(`- \`${C}\``);for(let fe of Q){let Ae=tt[fe.severity]?.badge??fe.severity,Xt=fe._anchor?.kind==="off-diff"?`${r(fe.file,fe.line,`L${fe.line}`)} \uD83D\uDCCE outside the diff`:r(fe.file,fe.line,`L${fe.line}`),pe=L.has(fe)?"":` ${Tt("summary-item",wu(fe))}`,ct=fe.also_at?.length?` \xB7 also ${fe.also_at.map(s).join(", ")}`:"";D.push(` - ${Ae} ${w(fe.title)} \u2014 ${Xt}${ct} \xB7 _[${U.get(fe)}]_${pe}`)}}return D};if(M.length)I.push(`#### ${Am[b]} (${M.length})`),I.push(""),I.push(...z(M)),I.push("");if(k.length)I.push(`<details><summary>Everything else (${k.length}) \u2014 lower-risk surfaces</summary>`),I.push(""),I.push(...z(k)),I.push(""),I.push("</details>"),I.push("");if(E.length&&e.minSeverity)I.push(`<details><summary>Minor findings (${E.length}) \u2014 below ${e.minSeverity}</summary>`),I.push(""),I.push(...z(E)),I.push(""),I.push("</details>"),I.push("");let te=e.carried??[];if(te.length){I.push(`<details><summary>Still open from earlier reviews (${te.length}) \u2014 not posted again this review</summary>`),I.push("");for(let y of te){let _={file:y.file,line:y.line,fp:y.fp,...y.sev?{sev:y.sev}:{},...y.pre?{pre:1}:{}};I.push(`- ${y.text||`\`${y.file}:${y.line}\``} ${Tt("summary-item",_)}`)}I.push(""),I.push("</details>"),I.push("")}let we=e.overCap??[];if(we.length)I.push(`\u2795 ${we.length} more ${we.length===1?"finding":"findings"} past the ${nr}-finding cap,`+" listed under \u201CPast the cap\u201D in the detail file."),I.push("");let Ne=e.checked??[];if(I.push(...me),a.length){I.push(`<details><summary>Agreeing with ${a.length} existing review ${a.length===1?"comment":"comments"}</summary>`),I.push("");for(let y of a){let _=u.get(y.repeat_of),D=_?`@${_.author}`:"an earlier review comment",C=_?.url?`[${D}](${_.url})`:D,Q=tt[y.severity]?.badge??y.severity;I.push(`- ${Q} ${w(y.title)} \u2014 \`${y.file}:${y.line}\` _\u2014 agrees with ${C}_`)}I.push(""),I.push("</details>"),I.push("")}if(O.length){G.push("## Evidence and reasoning"),G.push(""),G.push("Numbered to match the bullets in the summary comment."),G.push("");for(let y of O)G.push(g(y,"summary",`[${U.get(y)}] ${w(y.title)}`)),G.push("")}if(we.length){G.push("## Past the cap"),G.push(""),G.push(`Findings the review kept but did not post, because a review posts at most ${nr}. Ranked below the posted ones by severity, surface and confidence.`),G.push("");for(let y of we)G.push(g(y,"summary",w(y.title))),G.push("")}if(Ne.length){G.push("## What the reviewers checked"),G.push(""),G.push("Claims each reviewer verified against the code and found correct."),G.push("");for(let y of Ne)G.push(`- ${y}`);G.push("")}let Ye=process.env.GITHUB_RUN_ID,hr=process.env.GITHUB_SERVER_URL??"https://github.com",Ot=e.detailFile??"review-detail.md";if(O.length||B||we.length||Ne.length>8)I.push(Ye?`\uD83D\uDCC4 **[Full review detail](${hr}/${t}/actions/runs/${Ye})** \u2014 download the`+` \`${ys(e.pr??"",e.head)}\` artifact and open \`${Ot}\` for the walkthrough and the evidence behind each finding. Artifacts expire 90 days after the run.`:`\uD83D\uDCC4 Full walkthrough and evidence: \`${e.detailPath??Ot}\`.`),I.push("");if(Ne.length&&l.length<=2&&!e.noReviewers){I.push(`<details><summary>What the reviewers checked (${Ne.length})</summary>`),I.push("");for(let y of Ne.slice(0,8))I.push(`- ${y}`);if(Ne.length>8)I.push(`- \u2026and ${Ne.length-8} more in the detail file`);I.push(""),I.push("</details>"),I.push("")}if(e.dropped?.length){I.push("<details><summary>Findings considered and dropped during verification</summary>"),I.push("");for(let y of e.dropped)I.push(`- **${y.title}** \u2014 ${y.reason}`);I.push(""),I.push("</details>"),I.push("")}I.push("<details><summary>Review details</summary>"),I.push("");for(let[y,_]of Object.entries(e.stats))I.push(`- ${y}: ${_}`);I.push(""),I.push("</details>");let qn=[f(),p].filter(Boolean).join(`
516
+
517
+ `);I.push(""),I.push(qn);let Hn=F.map((y)=>g(y,"inline")),Ft=a.map((y)=>{let _=y.repeat_of,D=u.get(_),C=[];C.push(`Checked this against \`${e.head.slice(0,12)}\` \u2014 still open. ${tt[y.severity]?.badge??y.severity}`);let Q=y.impact?.trim()||wa(y.explanation,240);if(Q)C.push("",Q);if(y.also_at?.length)C.push("",`Same problem at: ${y.also_at.map(s).join(", ")}`);let fe=[y.explanation,y.evidence].filter(Boolean).join(`
518
+
519
+ `);if(fe)C.push("","<details><summary>What I found</summary>","",fe,"","</details>");return C.push("",Tt("reply",{of:_,fp:wn(y.file,y.title)})),{comment_id:_,author:D?.author,url:D?.url,finding:y,body:C.join(`
520
+ `)}});for(let y of e.resolved??[]){let _=u.get(y.id);if(!_?.mine||!_.file)continue;let D=y.note?.trim();Ft.push({comment_id:y.id,author:_.author,url:_.url,body:[`\u2705 Fixed as of \`${e.head.slice(0,12)}\`.${D?` ${D}`:""}`,"",Tt("reply",{of:y.id,addressed:1})].join(`
521
+ `)})}for(let y of d){if(!y.commentId)continue;let _=u.get(y.commentId),D=y.note?` ${y.note}`:"";Ft.push({comment_id:y.commentId,author:_?.author,url:_?.url,about:`${y.outcome} after a dispute`,body:y.outcome==="withdrawn"?[`\u21A9\uFE0F Withdrawn after @${y.author}'s reply.${D}`,"",Tt("reply",{of:y.commentId,addressed:1,fp:y.fp,dispute:"withdrawn"})].join(`
522
+ `):[`Checked @${y.author}'s reply against \`${e.head.slice(0,12)}\` \u2014 this still stands.${D}`,"","Leaving it for a human reviewer to decide.","",Tt("reply",{of:y.commentId,fp:y.fp,dispute:"upheld"})].join(`
523
+ `)})}return{summary:EE(I.join(`
524
+ `),qn),detail:G.join(`
525
+ `),inline:Hn,ordered:F,replies:Ft}}async function kE(e,t,n){if(n.filter((a)=>a.suggested_code).length===0)return n;let s=new Map,o=[];for(let a of n){if(!a.suggested_code){o.push(a);continue}if(!s.has(a.file))try{s.set(a.file,(await oe("git",["-C",e,"show",`${t}:${a.file}`])).split(`
526
526
  `))}catch{s.set(a.file,null)}let l=s.get(a.file),c=a.end_line!==void 0?Math.max(a.line,a.end_line):a.line,u=a.end_line!==void 0?Math.min(a.line,a.end_line):a.line;if(!l||u<1||c>l.length){o.push(a);continue}o.push({...a,_original:l.slice(u-1,c).join(`
527
- `)})}return o}var ma=65536;function jk(e,t){if(e.length<=ma)return e;let n=`
527
+ `)})}return o}var Sa=65536;function EE(e,t){if(e.length<=Sa)return e;let n=`
528
528
 
529
529
  ---
530
530
 
531
531
  _Truncated to fit GitHub's comment size limit. The full review is in the run artifact._
532
532
 
533
533
  `,r=`
534
- </details>`,s=((e.match(/<details/g)??[]).length+1)*r.length,o=ma-n.length-t.length-s-1,a=e.slice(0,o),l=a.lastIndexOf(`
534
+ </details>`,s=((e.match(/<details/g)??[]).length+1)*r.length,o=Sa-n.length-t.length-s-1,a=e.slice(0,o),l=a.lastIndexOf(`
535
535
 
536
536
  `),c=a.slice(0,l>o/2?l:a.length),u=(c.match(/<details/g)??[]).length-(c.match(/<\/details>/g)??[]).length,d=u>0?`
537
- ${r.repeat(u)}`:"";return`${c}${d}${n}${t}`}function Mm(e,t){let n=e.split(`
538
- `).filter((o)=>!tn(o).some((a)=>a.kind==="stopped")).join(`
539
- `).trimStart(),r=t.round-1,s=`> \u23F8\uFE0F **Reviews stopped.** Commit \`${t.head.slice(0,10)}\` was not reviewed: this pull request already had ${r} round${r===1?"":"s"} of review, and the limit is ${t.maxRounds} (\`--max-rounds\`). The findings below are from the last review and are left for a human reviewer. `+Mt("stopped",{round:t.round,max:t.maxRounds,head:t.head});for(let o of[n,ni(n)]){let a=`${s}
537
+ ${r.repeat(u)}`:"";return`${c}${d}${n}${t}`}function ig(e,t){let n=e.split(`
538
+ `).filter((o)=>!rn(o).some((a)=>a.kind==="stopped")).join(`
539
+ `).trimStart(),r=t.round-1,s=`> \u23F8\uFE0F **Reviews stopped.** Commit \`${t.head.slice(0,10)}\` was not reviewed: this pull request already had ${r} round${r===1?"":"s"} of review, and the limit is ${t.maxRounds} (\`--max-rounds\`). The findings below are from the last review and are left for a human reviewer. `+Tt("stopped",{round:t.round,max:t.maxRounds,head:t.head});for(let o of[n,ai(n)]){let a=`${s}
540
540
 
541
- ${o}`;if(a.length<=ma)return a}return n}async function Tm(e){await De($r.join(e.dir,`${e.tag}.md`),`<!-- summary comment: replaces the existing one; no inline comments or replies -->
541
+ ${o}`;if(a.length<=Sa)return a}return n}async function sg(e){await Fe(Ar.join(e.dir,`${e.tag}.md`),`<!-- summary comment: replaces the existing one; no inline comments or replies -->
542
542
 
543
543
  ${e.summary}
544
- `),await fn($r.join(e.dir,`${e.tag}.payloads.json`),{summary:{method:"POST",endpoint:`repos/${e.slug}/issues/${e.pr}/comments`,body:{body:e.summary}},review:{method:"POST",endpoint:`repos/${e.slug}/pulls/${e.pr}/reviews`,body:{commit_id:e.head,event:"COMMENT",comments:[]}},replies:[]})}function us(e,t){return`ai-code-review-${e}-${t.slice(0,9)}`}var kr="findings.md",Uk="<details><summary>Review details</summary>";function Fm(e){return e?`download the \`${e}\` artifact and open \`${kr}\``:`see \`${kr}\` in the run artifact`}function Nm(e,t){return`_${e===1?"The last finding is":`The last ${e} findings are`} shortened to fit this comment. For the full text, ${Fm(t)}._`}function Dm(e,t,n={}){let r=n.limit??ma,s=typeof t==="string"?[t]:t;for(let l of s){let c=[Xo,"<details><summary>Copy all findings as Markdown</summary>","",di(l,"markdown"),"","</details>",os].join(`
545
- `),u=Pm(e,c);if(u.length<=r)return u}let o=[Xo,`_All findings as Markdown are too long for this comment: ${Fm(n.artifact)}._`,os].join(`
546
- `),a=Pm(e,o);return a.length<=r?a:e}function Pm(e,t){let n=e.lastIndexOf(Uk);if(n<0){let o=e.lastIndexOf("<!-- ai-review kind=summary");n=o<0?e.length:o}let r=e.slice(0,n).replace(/\n*$/,""),s=e.slice(n);return s?`${r}
544
+ `),await mn(Ar.join(e.dir,`${e.tag}.payloads.json`),{summary:{method:"POST",endpoint:`repos/${e.slug}/issues/${e.pr}/comments`,body:{body:e.summary}},review:{method:"POST",endpoint:`repos/${e.slug}/pulls/${e.pr}/reviews`,body:{commit_id:e.head,event:"COMMENT",comments:[]}},replies:[]})}function ys(e,t){return`ai-code-review-${e}-${t.slice(0,9)}`}var Or="findings.md",CE="<details><summary>Review details</summary>";function og(e){return e?`download the \`${e}\` artifact and open \`${Or}\``:`see \`${Or}\` in the run artifact`}function ag(e,t){return`_${e===1?"The last finding is":`The last ${e} findings are`} shortened to fit this comment. For the full text, ${og(t)}._`}function lg(e,t,n={}){let r=n.limit??Sa,s=typeof t==="string"?[t]:t;for(let l of s){let c=[ia,"<details><summary>Copy all findings as Markdown</summary>","",gi(l,"markdown"),"","</details>",ms].join(`
545
+ `),u=rg(e,c);if(u.length<=r)return u}let o=[ia,`_All findings as Markdown are too long for this comment: ${og(n.artifact)}._`,ms].join(`
546
+ `),a=rg(e,o);return a.length<=r?a:e}function rg(e,t){let n=e.lastIndexOf(CE);if(n<0){let o=e.lastIndexOf("<!-- ai-review kind=summary");n=o<0?e.length:o}let r=e.slice(0,n).replace(/\n*$/,""),s=e.slice(n);return s?`${r}
547
547
 
548
548
  ${t}
549
549
 
550
550
  ${s}`:`${r}
551
551
 
552
- ${t}`}async function au(e){let t=e.findings,n=[];if(e.repoDir){t=await Lk(e.repoDir,e.head,t);try{let f=await Tp(e.repoDir,e.base,e.head);n=[...f.keys()],t=t.map((h)=>({...h,_anchor:To(f,h.file,h.line,h.end_line)}));let p=t.filter((h)=>h._anchor?.kind!=="anchorable");for(let h of p)console.error(` anchor: ${h.file}:${h.line} is ${h._anchor?.kind}`+(h._anchor?.line?` \u2192 line ${h._anchor.line}`:" \u2192 summary comment"))}catch(f){console.warn(` could not read diff for anchoring, using model line numbers: ${f}`)}}let r=`${e.tag}.detail.md`,{summary:s,detail:o,inline:a,ordered:l,replies:c}=Dk({pr:e.pr,detailFile:r,detailPath:$r.join(e.dir,r),head:e.head,findings:t,intentAlignment:e.intentAlignment,dropped:e.dropped,stats:e.stats,walkthrough:e.walkthrough,repo:e.slug,prior:e.prior,resolved:e.resolved,rulings:e.rulings,earlierRulings:e.earlierRulings,carried:e.carried,runs:e.runs,noReviewers:e.noReviewers,unreviewed:e.unreviewed,checked:e.checked,overCap:e.overCap,changedFiles:n,inlineMode:Up,minSeverity:e.minSeverity===void 0?Xr:e.minSeverity}),u=e.local?jt([s,...a.length?["","## Line comments","",...a.flatMap((f)=>[f,"","---",""])]:[]].join(`
552
+ ${t}`}async function bu(e){let t=e.findings,n=[];if(e.repoDir){t=await kE(e.repoDir,e.head,t);try{let f=await dh(e.repoDir,e.base,e.head);n=[...f.keys()],t=t.map((h)=>({...h,_anchor:Wo(f,h.file,h.line,h.end_line)}));let p=t.filter((h)=>h._anchor?.kind!=="anchorable");for(let h of p)console.error(` anchor: ${h.file}:${h.line} is ${h._anchor?.kind}`+(h._anchor?.line?` \u2192 line ${h._anchor.line}`:" \u2192 summary comment"))}catch(f){console.warn(` could not read diff for anchoring, using model line numbers: ${f}`)}}let r=`${e.tag}.detail.md`,{summary:s,detail:o,inline:a,ordered:l,replies:c}=$E({pr:e.pr,detailFile:r,detailPath:Ar.join(e.dir,r),head:e.head,findings:t,intentAlignment:e.intentAlignment,dropped:e.dropped,stats:e.stats,walkthrough:e.walkthrough,repo:e.slug,prior:e.prior,resolved:e.resolved,rulings:e.rulings,earlierRulings:e.earlierRulings,carried:e.carried,runs:e.runs,noReviewers:e.noReviewers,unreviewed:e.unreviewed,checked:e.checked,overCap:e.overCap,changedFiles:n,inlineMode:_h,minSeverity:e.minSeverity===void 0?ti:e.minSeverity}),u=e.local?Ut([s,...a.length?["","## Line comments","",...a.flatMap((f)=>[f,"","---",""])]:[]].join(`
553
553
  `))+`
554
554
  `:["# Summary comment","",s,"","---","","# Inline comments","",...l.map((f,p)=>[`<!-- inline ${p+1} of ${l.length} \u2014 ${f.file}:${f.line}${f._anchor&&f._anchor.line!==f.line?` (anchored at line ${f._anchor.line})`:""} -->`,"",a[p],"","---",""].join(`
555
555
  `)),...c.length?["# Replies to existing review comments","",...c.map((f,p)=>[`<!-- reply ${p+1} of ${c.length} \u2014 to ${f.author?`@${f.author}`:"comment"} ${f.comment_id}${f.finding?` on ${f.finding.file}:${f.finding.line}`:` \u2014 ${f.about??"closing it out as fixed"}`} -->`,"",...f.url?[`In reply to ${f.url}`,""]:[],f.body,"","---",""].join(`
556
556
  `))]:[]].join(`
557
- `);if(await De($r.join(e.dir,`${e.tag}.md`),u),await De($r.join(e.dir,r),e.local?`${jt(o)}
558
- `:o),!e.pr||e.local){if(await Yt($r.join(e.dir,`${e.tag}.payloads.json`)),!e.local)console.error(" local review: no pull request, so no API payloads written");return{summary:s,inline:a,ordered:l}}let d={summary:{method:"POST",endpoint:`repos/${e.slug}/issues/${e.pr}/comments`,body:{body:s}},review:{method:"POST",endpoint:`repos/${e.slug}/pulls/${e.pr}/reviews`,body:{commit_id:e.head,event:"COMMENT",comments:l.map((f,p)=>{let h=f._anchor,g=f.end_line!==void 0?Math.min(f.line,f.end_line):f.line,w=f.end_line!==void 0?Math.max(f.line,f.end_line):f.line,b=w!==g;return{path:f.file,line:h?.line??w,...h?h.start_line!==void 0?{start_line:h.start_line}:{}:b?{start_line:g}:{},side:"RIGHT",body:a[p]}})}},replies:c.map((f)=>({method:"POST",endpoint:`repos/${e.slug}/pulls/${e.pr}/comments/${f.comment_id}/replies`,body:{body:f.body}}))};return await fn($r.join(e.dir,`${e.tag}.payloads.json`),d),{summary:s,inline:a,ordered:l}}bt();import{createHash as Bk}from"crypto";import Lm from"path";var qk=160000;function lu(e){return typeof e==="string"&&e.trim()?e.trim():void 0}function jm(e){if(typeof e!=="object"||e===null||Array.isArray(e))return;let t=e,n=lu(t.title),r=lu(t.goal);if(!n||!r)return;let s=Array.isArray(t.expected_changes)?t.expected_changes.map(lu).filter((o)=>o!==void 0):[];return{title:n,goal:r,expected_changes:s}}async function Um(e){let t=Jr,n=Dp(e.diff,qk),r=Lm.join(wt,`${e.tag}-intent.json`),s={branch:e.branch,intent:e.intent,diffstat:e.diffstat,diff:n,otherFiles:e.otherFiles},o=Bk("sha256").update(fa).update(pa({...s,outFile:""})).digest("hex").slice(0,16),a=Lm.join(ye,"intents",`${e.cacheKey}.json`),l={model:t,diffChars:n.length};if(await Gr(a))try{let f=await Mo(a),p=jm(f.draft);if(p&&f.model===t&&f.inputHash===o)return{...l,draft:p,costUsd:0,wallMs:0,cached:!0}}catch{}let c=await On(pa({...s,outFile:r}),{budget:mc,outFile:r,tag:`${e.tag}-intent`,model:t,effort:Zt,tools:"none",system:{name:"intent",text:fa},answerKeys:["title","goal"]}),u={costUsd:c.costUsd,wallMs:c.wallMs,cached:!1,...c.usage?{usage:c.usage}:{},...c.deliveredAs?{deliveredAs:c.deliveredAs}:{}},d=jm(c.payload);if(!d){let f=c.failure?.message??"the draft has no title or goal";return{...l,...u,failure:f}}return await fn(a,{draft:d,model:t,inputHash:o}),{...l,...u,draft:d}}xr();function cu(e){let t=new Set,n=[];for(let r of e){if(!r.mine||r.file)continue;for(let s of r.rulings??[]){if(t.has(s.fp))continue;t.add(s.fp),n.push(s)}}return n}function Hk(e){return(jt(e).split(`
559
- `).find((n)=>n.trim())??"").replace(/^#+\s*/,"").replace(/\s+/g," ").trim().slice(0,200)}function Bm(e){let t=new Set(cu(e).map((o)=>o.fp)),n=new Map;for(let o of e){if(!o.mine)continue;if(o.file&&o.fingerprint&&!o.inReplyTo){if(o.addressed)continue;n.set(o.fingerprint,{fp:o.fingerprint,commentId:o.id,file:o.file,line:o.line===void 0?"?":String(o.line),claim:Hk(o.body)})}for(let a of o.summaryClaims??[])if(!n.has(a.fp))n.set(a.fp,{fp:a.fp,file:a.file,line:a.line,claim:a.text??""})}let r=new Map,s=(o,a)=>(o.createdAt??"").localeCompare(a.createdAt??"")||o.id-a.id;for(let o of[...e].sort(s)){if(o.mine)continue;for(let a of o.responses??[]){let l=n.get(a.fp);if(!l||t.has(a.fp))continue;r.set(a.fp,{...l,verdict:a.verdict,reason:a.reason,author:o.author,responseId:o.id})}}return[...r.values()]}function qm(e){return e.some((t)=>t.verdict==="disputed")}function Hm(e){if(!e.length)return"";let t=e.filter((o)=>o.verdict==="disputed"),n=e.filter((o)=>o.verdict==="fixed"),r=(o)=>{let a=o.reason.replace(/\s+/g," ").slice(0,1200)||"(no reason given)",l=o.commentId?` (your comment id=${o.commentId})`:" (in your summary)";return`- fp=${o.fp} \`${o.file}:${o.line}\`${l}: ${o.claim}
557
+ `);if(await Fe(Ar.join(e.dir,`${e.tag}.md`),u),await Fe(Ar.join(e.dir,r),e.local?`${Ut(o)}
558
+ `:o),!e.pr||e.local){if(await Qt(Ar.join(e.dir,`${e.tag}.payloads.json`)),!e.local)console.error(" local review: no pull request, so no API payloads written");return{summary:s,inline:a,ordered:l}}let d={summary:{method:"POST",endpoint:`repos/${e.slug}/issues/${e.pr}/comments`,body:{body:s}},review:{method:"POST",endpoint:`repos/${e.slug}/pulls/${e.pr}/reviews`,body:{commit_id:e.head,event:"COMMENT",comments:l.map((f,p)=>{let h=f._anchor,g=f.end_line!==void 0?Math.min(f.line,f.end_line):f.line,w=f.end_line!==void 0?Math.max(f.line,f.end_line):f.line,b=w!==g;return{path:f.file,line:h?.line??w,...h?h.start_line!==void 0?{start_line:h.start_line}:{}:b?{start_line:g}:{},side:"RIGHT",body:a[p]}})}},replies:c.map((f)=>({method:"POST",endpoint:`repos/${e.slug}/pulls/${e.pr}/comments/${f.comment_id}/replies`,body:{body:f.body}}))};return await mn(Ar.join(e.dir,`${e.tag}.payloads.json`),d),{summary:s,inline:a,ordered:l}}bt();import{createHash as AE}from"crypto";import cg from"path";var OE=160000;function vu(e){return typeof e==="string"&&e.trim()?e.trim():void 0}function ug(e){if(typeof e!=="object"||e===null||Array.isArray(e))return;let t=e,n=vu(t.title),r=vu(t.goal);if(!n||!r)return;let s=Array.isArray(t.expected_changes)?t.expected_changes.map(vu).filter((o)=>o!==void 0):[];return{title:n,goal:r,expected_changes:s}}async function dg(e){let t=ei,n=hh(e.diff,OE),r=cg.join(wt,`${e.tag}-intent.json`),s={branch:e.branch,intent:e.intent,diffstat:e.diffstat,diff:n,otherFiles:e.otherFiles},o=AE("sha256").update(ba).update(va({...s,outFile:""})).digest("hex").slice(0,16),a=cg.join(ye,"intents",`${e.cacheKey}.json`),l={model:t,diffChars:n.length};if(await Yr(a))try{let f=await Go(a),p=ug(f.draft);if(p&&f.model===t&&f.inputHash===o)return{...l,draft:p,costUsd:0,wallMs:0,cached:!0}}catch{}let c=await Pn(va({...s,outFile:r}),{budget:Mc,outFile:r,tag:`${e.tag}-intent`,model:t,effort:en,tools:"none",system:{name:"intent",text:ba},answerKeys:["title","goal"]}),u={costUsd:c.costUsd,wallMs:c.wallMs,cached:!1,...c.usage?{usage:c.usage}:{},...c.deliveredAs?{deliveredAs:c.deliveredAs}:{}},d=ug(c.payload);if(!d){let f=c.failure?.message??"the draft has no title or goal";return{...l,...u,failure:f}}return await mn(a,{draft:d,model:t,inputHash:o}),{...l,...u,draft:d}}kr();function xu(e){let t=new Set,n=[];for(let r of e){if(!r.mine||r.file)continue;for(let s of r.rulings??[]){if(t.has(s.fp))continue;t.add(s.fp),n.push(s)}}return n}function IE(e){return(Ut(e).split(`
559
+ `).find((n)=>n.trim())??"").replace(/^#+\s*/,"").replace(/\s+/g," ").trim().slice(0,200)}function fg(e){let t=new Set(xu(e).map((o)=>o.fp)),n=new Map;for(let o of e){if(!o.mine)continue;if(o.file&&o.fingerprint&&!o.inReplyTo){if(o.addressed)continue;n.set(o.fingerprint,{fp:o.fingerprint,commentId:o.id,file:o.file,line:o.line===void 0?"?":String(o.line),claim:IE(o.body)})}for(let a of o.summaryClaims??[])if(!n.has(a.fp))n.set(a.fp,{fp:a.fp,file:a.file,line:a.line,claim:a.text??""})}let r=new Map,s=(o,a)=>(o.createdAt??"").localeCompare(a.createdAt??"")||o.id-a.id;for(let o of[...e].sort(s)){if(o.mine)continue;for(let a of o.responses??[]){let l=n.get(a.fp);if(!l||t.has(a.fp))continue;r.set(a.fp,{...l,verdict:a.verdict,reason:a.reason,author:o.author,responseId:o.id})}}return[...r.values()]}function pg(e){return e.some((t)=>t.verdict==="disputed")}function hg(e){if(!e.length)return"";let t=e.filter((o)=>o.verdict==="disputed"),n=e.filter((o)=>o.verdict==="fixed"),r=(o)=>{let a=o.reason.replace(/\s+/g," ").slice(0,1200)||"(no reason given)",l=o.commentId?` (your comment id=${o.commentId})`:" (in your summary)";return`- fp=${o.fp} \`${o.file}:${o.line}\`${l}: ${o.claim}
560
560
  @${o.author} replied: ${a}`},s=[];if(t.length){s.push("## Findings the author disputes","","The author, or an agent working for them, says these findings of yours are wrong. Rule on","each one in `disputes`, by its `fp`. Open the code and weigh the reason against it.","","- `withdrawn` when the reason holds: the finding misreads the code, the behavior is"," intended and the reply shows why that is safe, or the case cannot happen. The finding is"," never raised on this pull request again, so do not report it in any other form.","- `upheld` when the code still has the problem the finding describes. A reply that only"," disagrees, or promises a later fix, does not change the code. A human reviewer decides"," what happens next.","","Every dispute gets a `note`: one sentence the author will read, saying what in the code","decided it. You rule once; no later review reopens it.","");for(let o of t)s.push(r(o));s.push("")}if(n.length){s.push("## Findings the author says are fixed","","Check each against the current code. A finding with a comment of its own goes in `resolved`","when it is fixed, as in step 5. A finding in your summary is simply not reported again.","Neither goes in `disputes`.","");for(let o of n)s.push(r(o));s.push("")}return s.join(`
561
- `)}function Km(e,t,n){let r=new Set(t.map((s)=>s.fp));return[...e.map((s)=>({fp:s.fp,outcome:s.outcome,earlier:!0,claim:s.label})),...t.map(({fp:s,outcome:o,file:a,line:l,claim:c,note:u})=>({fp:s,outcome:o,file:a,line:l,claim:c,...u?{note:u}:{}})),...n.filter((s)=>s.verdict==="disputed"&&!r.has(s.fp)).map(({fp:s,file:o,line:a,claim:l})=>({fp:s,outcome:"unjudged",file:o,line:a,claim:l}))]}function Wm(e,t){let n=new Map(t.filter((s)=>s.verdict==="disputed").map((s)=>[s.fp,s])),r=[];for(let s of e??[]){let o=typeof s.fp==="string"?n.get(s.fp.toLowerCase()):void 0;if(!o||s.outcome!=="withdrawn"&&s.outcome!=="upheld")continue;n.delete(o.fp);let a=typeof s.note==="string"?s.note.replace(/\s+/g," ").trim():"";r.push({fp:o.fp,outcome:s.outcome,file:o.file,line:o.line,claim:o.claim,author:o.author,...a?{note:a}:{},...o.commentId?{commentId:o.commentId}:{}})}return r}function Gm(e){let{prior:t,earlierRulings:n,rulings:r}=e,s=(p)=>new Set([...n,...r].filter((h)=>h.outcome===p).map((h)=>h.fp)),o=s("withdrawn"),a=s("upheld"),l=new Set(e.resolvedIds),c=new Map;for(let p of t){if(!p.mine||!p.file||!p.fingerprint||p.inReplyTo)continue;let h=c.get(p.fingerprint);c.set(p.fingerprint,{addressed:(h?.addressed??!1)||p.addressed===!0,resolvedNow:(h?.resolvedNow??!1)||l.has(p.id)})}let u=0,d=0,f=0;for(let[p,h]of c){if(o.has(p))continue;if(h.resolvedNow)f++;if(h.addressed||h.resolvedNow)d++;else u++}return{open:u,fixed:d,withdrawn:o.size,upheld:[...a].filter((p)=>!o.has(p)).length,fixedThisRound:f,withdrawnThisRound:r.filter((p)=>p.outcome==="withdrawn").length,new:e.newFindings}}bt();ls();Sr();var Kk=4;function Wk(e,t){if(!t)return{kind:"full",files:e,reason:"the previous head is not available"};let n=new Set(t),r=e.filter((s)=>n.has(s));if(e.length>=Kk&&r.length>e.length/2)return{kind:"full",files:e,reason:`${r.length} of ${e.length} files changed since the last review`};return{kind:"incremental",files:r}}function Vm(e,t){return e.map((n)=>{let r=String(n.tag??""),s=r.startsWith(`${t}-`)?r.slice(t.length+1):r,o=n.failure;return`${s}: ${o?.message??`exited with code ${String(n.exitCode)}`}`})}function Gk(e,t,n){let r=new Set(e.map((a)=>a.failure?.kind)),s=r.has("provider")||r.has("spawn")||r.has("exit")||r.has(void 0);return[`all ${n} review slices failed \u2014 no review was produced.`,...Vm(e,t).map((a)=>` ${a}`),s?"Run `diffloupe doctor` to check credentials and tools.":"The agents ran normally, so this is not a credentials problem.",`Agent output: ${Qe.join(ye,"raw",`${t}-sNN.stdout.ndjson`)}, logs in ${Qe.join(ye,"logs")}`].join(`
562
- `)}async function zm(e){if(e.config)Ho(e.config);let{signal:t}=e;if(t?.aborted)throw new Bt;let n=()=>void li();if(t?.addEventListener("abort",n,{once:!0}),t)Zr({signal:t});try{return await Vk(e)}finally{t?.removeEventListener("abort",n),await li(),await No(),Ko(),la()}}async function Vk(e){let t=(v)=>e.onProgress?.(v),{signal:n,maxCostUsd:r}=e,s=()=>{if(n?.aborted)throw new Bt},o=0,a=(v)=>{o+=v,t({type:"cost",totalUsd:o})};t({type:"stage",stage:"resolving_target"});let l=e.repo,{pr:c,base:u,head:d,slug:f}=e.target,p=Qh({pr:c,base:u,head:d}),h=e.tag,g=Qe.join(ye,"reviews",`${h}.md`);await Sn(wt);for(let v of["runs","raw","logs","prompts","reviews","maps"])await Sn(Qe.join(ye,v));await De(Qe.join(ye,".gitignore"),`*
563
- `);let w=await Yh(l,c,d);Zr({subject:w.dir,releaseSubject:w.release});let b=Date.now();Zr({repoName:f});let x=!e.local,R=await Qo(f,c,u,d,e.intent,{strict:x}),P=[...await Ih(f,c,{strict:x}),...e.prior??[]],M=Mh(P,R.body),k=Bm(P),E=cu(P);if(k.length){let v=k.filter((K)=>K.verdict==="disputed").length;console.error(` ${v} disputed and ${k.length-v} reported-fixed answers to earlier findings`)}let D=Math.max(0,...P.filter((v)=>v.mine).map((v)=>v.runs??0));s();let L=(await pt(["diff","--name-only",`${u}..${d}`])).trim().split(`
564
- `).filter(Boolean),O={skip:[],docs:[],code:[]};for(let v of L)O[ai(v)].push(v);let U=O.code,I=e.local?e.round??1:D+1;if(e.maxRounds!==void 0&&I>e.maxRounds){if(console.error(` not reviewing: this would be round ${I}, and --max-rounds is ${e.maxRounds}`),c&&!e.local){let v=await Oh(f,c);if(v)await Tm({dir:Qe.join(ye,"reviews"),tag:h,slug:f,pr:c,head:d,summary:Mm(v,{round:I,maxRounds:e.maxRounds,head:d})});else console.error(" no summary comment from an earlier review to add the notice to")}return{record:null,roundLimit:{maxRounds:e.maxRounds,round:I},units:[],byClass:O,findings:[],costUsd:0,wallMs:Date.now()-b,markdownPath:g}}if(U.length===0)return console.error(` ${L.length} changed files, none reviewable \u2014 no review`),await au({dir:Qe.join(ye,"reviews"),tag:h,slug:f,pr:c,base:u,head:d,findings:[],stats:{"changed files":String(L.length),reviewed:"nothing: no code files in this change"},repoDir:st,local:e.local}),{record:null,units:[],byClass:O,findings:[],costUsd:0,wallMs:Date.now()-b,markdownPath:g};let j={kind:"full",files:U};if(e.priorHead){let v=e.priorHead===d?[]:await pt(["diff","--name-only",e.priorHead,d]).then((K)=>K.trim().split(`
565
- `).filter(Boolean),()=>null);j=Wk(U,v),console.error(j.kind==="incremental"?` re-review: ${j.files.length} of ${U.length} code files changed since ${e.priorHead.slice(0,12)}`:` re-review in full: ${j.reason}`)}let H=j.kind==="incremental";t({type:"stage",stage:"grouping"});let{wholeDiff:ve,diffstat:Se,diffU0:ne,fileTokens:ce,facts:Be,links:ze,grouping:Je}=await ta({base:u,head:d,files:U,source:()=>Go(st)}),Xe=Um({tag:h,cacheKey:p,intent:R,diffstat:Se,diff:ve,otherFiles:O.docs}).catch((v)=>({model:Jr,costUsd:0,wallMs:0,cached:!1,diffChars:0,failure:v instanceof Error?v.message:String(v)})),nt=await Ch(u,d,U),be=wr==="code"?Je:void 0,Te=be?.groups.length===1;if(be){let v=si(be.groups,(G)=>ce.get(G)??0),K=be.groups.map((G,rt)=>({id:G.id,title:Te?R.title||G.id:v[rt]??G.id,files:G.files,priority:rt+1}));t({type:"units",units:K,byClass:O})}s(),t({type:"stage",stage:"checking_registry"});let me=await Kp({repo:st,base:u,head:d}),W=Wp(me.findings),T=Qe.join(ye,"maps",`${p}.md`),B="",z=await Gr(T);if(t({type:"stage",stage:"building_map"}),!z)try{let v=await Sh({repo:st,base:u,head:d,cacheDir:Qe.join(ye,"outlines")});await De(T,v.markdown),await fn(Qe.join(ye,"maps",`${p}.meta.json`),v.meta),z=!0}catch(v){console.error(`repo map unavailable, continuing without it: ${v}`)}if(z)B=`A repository orientation map for this change is at \`${T}\`. Read it first (use tilth_read if available) to get your bearings before exploring \u2014 it lists the codebase layout, the symbols in each changed file, and the files that import or are imported by them.
566
- `;if(s(),!Te)t({type:"stage",stage:"grouping"});let te=`${h}-part`,we=`${wt}/${te}.json`;await Yt(we);let Ne=be?Om({groups:be.groups,links:ze,outline:nt,intent:R,registry:W,outFile:we}):Cm({diffstat:Se,outline:nt,intent:R,codeFiles:U,registry:W,outFile:we});await De(Qe.join(ye,"prompts",`${te}.txt`),Ne);let Ye={wallMs:0,costUsd:0,numTurns:0,payload:void 0};if(!Te)Ye=await On(Ne,{budget:hc,outFile:we,tag:te,model:kn,effort:Zt,answerKeys:["groups","review_units"]}),a(Ye.costUsd);s();let dr=[],Ot;if(be&&Te)Ot=[{id:be.groups[0].id,title:R.title||be.groups[0].id,files:be.groups[0].files,priority:1}];else if(be){let v=Bh(be.groups,Ye.payload,Jn,ce);dr=v.moves,Ot=iu(v.units,U);for(let K of dr)console.error(` moved ${K.file}: ${K.from} -> ${K.to} (${K.reason})`)}else{let v=Ye.payload??void 0;Ot=iu(v?.review_units??[],U)}let Un=new Set(me.findings.map((v)=>v.addedIn)),Bn=new Map(Ot.map((v)=>[v.id,v.files.reduce((K,G)=>K+(ce.get(G)??0),0)])),Nt=[...Ot].sort((v,K)=>{let G=Number(v.files.some((Ki)=>Un.has(Ki))),rt=Number(K.files.some((Ki)=>Un.has(Ki)));if(G!==rt)return rt-G;let ut=v.priority??5,Kn=K.priority??5;if(ut!==Kn)return ut-Kn;return(Bn.get(K.id)??0)-(Bn.get(v.id)??0)}),y=new Map(Nt.map((v,K)=>[v.id,K])),_=Am(Nt,ce,Jn).sort((v,K)=>v.part-K.part||(y.get(v.unitId)??0)-(y.get(K.unitId)??0)),F=new Set(j.files),A=H?_.map((v)=>{let K=v.files.filter((G)=>F.has(G));return{...v,files:K,tokens:K.reduce((G,rt)=>G+(ce.get(rt)??0),0)}}).filter((v)=>v.files.length>0):_,Q=A.slice(0,br),fe=_.slice(0,br),Ce=A.slice(br).flatMap((v)=>v.files),Jt=Q.filter((v)=>v.tokens>Jn);console.error(`${c?`PR ${c} `:""}${u.slice(0,12)}..${d.slice(0,12)} \u2014 ${L.length} changed (${U.length} code, ${O.docs.length} docs, ${O.skip.length} skipped) -> ${Ot.length} units, ${Q.length} slices${Ce.length?`, ${Ce.length} files over cap`:""}${Jt.length?`, ${Jt.length} over ${Jn} tokens`:""}, registry signals: ${me.findings.length}, prior comments: ${P.length}`);for(let v of Q)console.error(` slice ${v.unitId}${v.parts>1?` ${v.part}/${v.parts}`:""} (${v.tokens} tokens): ${v.files.join(", ")}`);let pe=[],ct=[],ho=[],cn=await Xe;s(),a(cn.costUsd);let ji=cn.draft;t({type:"log",message:ji?` intent draft${cn.cached?" (cached)":""}: ${ji.title}`:` warning: no intent draft (${cn.failure??"unknown error"}); reviewing without it`}),t({type:"units",units:Ot,byClass:O}),t({type:"stage",stage:"reviewing"});let mo=0,Ll=!1,jl=[];async function Gx(v){while(!0){if(n?.aborted)return;if(r!==void 0&&o>=r&&mo<Q.length){let it=Q.slice(mo);mo=Q.length,Ll=!0,jl=it.flatMap(($o)=>$o.files),console.error(` cost $${o.toFixed(2)} reached --max-cost $${r.toFixed(2)}: ${it.length} slice(s) not started`),t({type:"budget",totalUsd:o,limitUsd:r,skippedSlices:it.length});return}let K=mo++;if(K>=Q.length)return;let G=Q[K],rt={id:G.unitId,title:G.title,rationale:G.rationale,files:G.files,priority:G.priority},ut=`${h}-s${String(K).padStart(2,"0")}`,[Kn,Ki]=await Promise.all([pt(["diff",`${u}..${d}`,"--",...G.files]),H&&e.priorHead?pt(["diff",e.priorHead,d,"--",...G.files]):void 0]),Jf=_r(Kn,u);if(!Jf.trim())continue;let Zl=`${wt}/${ut}.json`;await Yt(Zl);let Xf=nu({unit:rt,diff:Jf,intent:R,draft:ji,registry:W,prior:M,mapNote:B,outFile:Zl,crossLinks:Uh(G.files,ze),instructions:e.instructions,sinceLast:Ki});await De(Qe.join(ye,"prompts",`${ut}.txt`),Xf);let Ql={type:"slice",index:K,total:Q.length,title:G.title};t({...Ql,status:"started"});let Pe;try{Pe=await On(Xf,{budget:gc,outFile:Zl,tag:ut,answerKeys:["findings"]}),a(Pe.costUsd)}catch(it){let $o=it instanceof Error?it.message:String(it);console.error(` [w${v}] ${G.unitId} \u2014 failed to run: ${$o}`);let tR={kind:"spawn",message:`failed to run: ${$o}`};pe.push({unit:G.unitId,part:G.part,parts:G.parts,tokens:G.tokens,files:G.files,tag:ut,wallMs:0,costUsd:0,numTurns:0,exitCode:-1,findingCount:0,ok:!1,failure:tR}),t({...Ql,status:"failed"});continue}let ec=Pe.payload,So=Array.isArray(ec)?ec:ec?.findings??[],Wi=(Array.isArray(So)?So:[]).filter((it)=>typeof it==="object"&&it!==null);if(Wi.length!==(Array.isArray(So)?So.length:0))console.error(` [w${v}] ${G.unitId} \u2014 discarded malformed entries from the findings file`);for(let it of Wi)it._slice=G.unitId,it.also_at=Qc(it,it.also_at),ct.push(it);let Yf=gm(Pe.payload);ho[K]=Yf,pe.push({unit:G.unitId,part:G.part,parts:G.parts,tokens:G.tokens,files:G.files,tag:ut,wallMs:Pe.wallMs,costUsd:Pe.costUsd,numTurns:Pe.numTurns,usage:Pe.usage,tools:Pe.tools,checked:Yf,exitCode:Pe.exitCode,findingCount:Wi.length,ok:Pe.payload!==null,...Pe.failure?{failure:Pe.failure}:{},...Pe.deliveredAs?{deliveredAs:Pe.deliveredAs}:{}}),console.error(` [w${v}] ${G.unitId}${G.parts>1?` ${G.part}/${G.parts}`:""} (${G.files.length}f ${G.tokens}t) \u2014 ${(Pe.wallMs/1000).toFixed(0)}s $${Pe.costUsd.toFixed(2)} ${Pe.numTurns}t ${Wi.length} findings${Pe.failure?` \u2014 failed: ${Pe.failure.message}`:""}`),t({...Ql,status:Pe.payload!==null?"ok":"failed",costUsd:Pe.costUsd,wallMs:Pe.wallMs,findings:Wi.length})}}await Promise.all(Array.from({length:Math.min(wc,Q.length)},(v,K)=>Gx(K))),s();let go=pe.filter((v)=>v.ok??v.exitCode===0),_o=pe.filter((v)=>!go.includes(v));if(pe.length>0&&go.length===0)throw Error(Gk(_o,h,pe.length));if(_o.length){console.error(` warning: ${_o.length} of ${pe.length} slices failed`);for(let v of Vm(_o,h))console.error(` ${v}`)}let qn=ct;if(ct.length>20)qn=ct.filter((v)=>!(v.severity==="nice-to-have"&&v.confidence!=="high"));let Ul=ct.length-qn.length,Bl=`${h}-merge`,ql=`${wt}/${Bl}.json`;await Yt(ql);let Df=ru({findings:qn,intent:R,draft:ji,files:U,prior:M,outFile:ql,instructions:e.instructions,disputes:Hm(k),changedLines:Xi(ne),maxNew:H?Yc:Qn,sinceLast:H?j.files:void 0});await De(Qe.join(ye,"prompts",`${Bl}.txt`),Df);let Vx=_m(qn.length,_c),Hl=`${h}-walk`,Kl=`${wt}/${Hl}.json`;await Yt(Kl);let wo=Nt.filter((v)=>fe.some((K)=>K.unitId===v.id)),zx=new Set(wo.flatMap((v)=>v.files)),Lf=_.flatMap((v)=>v.files).filter((v)=>!zx.has(v)),Jx=[...wo,...Lf.length?[{files:[...new Set(Lf)]}]:[]],{shown:Wl,sketched:qr}=ia(Jx,ce,Zi),Xx=Wl.reduce((v,K)=>v+(ce.get(K)??0),0),Yx=qr.length?_r(await pt(["diff",`${u}..${d}`,"--",...Wl]),u):ve;if(qr.length)console.error(` walkthrough sees ${Wl.length} of ${U.length} files (${Xx} tokens), ${qr.length} given as sketches`);let Zx=na(ne,Be),jf=ha({diffstat:Se,diff:Yx,sketches:qr.map((v)=>ra(Zx.get(v)??{file:v,added:0,removed:0,defines:[],touches:[]})),crossLinks:oa(wo,ze),intent:R,draft:ji,findingIndex:qn.map((v)=>`- [${v.severity}] ${v.file}:${v.line} \u2014 ${v.title}`).join(`
567
- `),unitSummary:wo.map((v)=>{let K=sa(v.files,ze);return`**${v.title}** (${v.id})
568
- ${v.files.map((G)=>` - ${G}`).join(`
561
+ `)}function mg(e,t,n){let r=new Set(t.map((s)=>s.fp));return[...e.map((s)=>({fp:s.fp,outcome:s.outcome,earlier:!0,claim:s.label})),...t.map(({fp:s,outcome:o,file:a,line:l,claim:c,note:u})=>({fp:s,outcome:o,file:a,line:l,claim:c,...u?{note:u}:{}})),...n.filter((s)=>s.verdict==="disputed"&&!r.has(s.fp)).map(({fp:s,file:o,line:a,claim:l})=>({fp:s,outcome:"unjudged",file:o,line:a,claim:l}))]}function gg(e,t){let n=new Map(t.filter((s)=>s.verdict==="disputed").map((s)=>[s.fp,s])),r=[];for(let s of e??[]){let o=typeof s.fp==="string"?n.get(s.fp.toLowerCase()):void 0;if(!o||s.outcome!=="withdrawn"&&s.outcome!=="upheld")continue;n.delete(o.fp);let a=typeof s.note==="string"?s.note.replace(/\s+/g," ").trim():"";r.push({fp:o.fp,outcome:s.outcome,file:o.file,line:o.line,claim:o.claim,author:o.author,...a?{note:a}:{},...o.commentId?{commentId:o.commentId}:{}})}return r}function _g(e){let{prior:t,earlierRulings:n,rulings:r}=e,s=(p)=>new Set([...n,...r].filter((h)=>h.outcome===p).map((h)=>h.fp)),o=s("withdrawn"),a=s("upheld"),l=new Set(e.resolvedIds),c=new Map;for(let p of t){if(!p.mine||!p.file||!p.fingerprint||p.inReplyTo)continue;let h=c.get(p.fingerprint);c.set(p.fingerprint,{addressed:(h?.addressed??!1)||p.addressed===!0,resolvedNow:(h?.resolvedNow??!1)||l.has(p.id)})}let u=0,d=0,f=0;for(let[p,h]of c){if(o.has(p))continue;if(h.resolvedNow)f++;if(h.addressed||h.resolvedNow)d++;else u++}return{open:u,fixed:d,withdrawn:o.size,upheld:[...a].filter((p)=>!o.has(p)).length,fixedThisRound:f,withdrawnThisRound:r.filter((p)=>p.outcome==="withdrawn").length,new:e.newFindings}}bt();_s();Cr();var PE=4;function ME(e,t){if(!t)return{kind:"full",files:e,reason:"the previous head is not available"};let n=new Set(t),r=e.filter((s)=>n.has(s));if(e.length>=PE&&r.length>e.length/2)return{kind:"full",files:e,reason:`${r.length} of ${e.length} files changed since the last review`};return{kind:"incremental",files:r}}function wg(e,t){return e.map((n)=>{let r=String(n.tag??""),s=r.startsWith(`${t}-`)?r.slice(t.length+1):r,o=n.failure;return`${s}: ${o?.message??`exited with code ${String(n.exitCode)}`}`})}function TE(e,t,n){let r=new Set(e.map((a)=>a.failure?.kind)),s=r.has("provider")||r.has("spawn")||r.has("exit")||r.has(void 0);return[`all ${n} review slices failed \u2014 no review was produced.`,...wg(e,t).map((a)=>` ${a}`),s?"Run `diffloupe doctor` to check credentials and tools.":"The agents ran normally, so this is not a credentials problem.",`Agent output: ${Qe.join(ye,"raw",`${t}-sNN.stdout.ndjson`)}, logs in ${Qe.join(ye,"logs")}`].join(`
562
+ `)}async function yg(e){if(e.config)ta(e.config);let{signal:t}=e;if(t?.aborted)throw new qt;let n=()=>void pi();if(t?.addEventListener("abort",n,{once:!0}),t)ri({signal:t});try{return await DE(e)}finally{t?.removeEventListener("abort",n),await pi(),await zo(),na(),ga()}}async function DE(e){let t=(v)=>e.onProgress?.(v),{signal:n,maxCostUsd:r}=e,s=()=>{if(n?.aborted)throw new qt},o=0,a=(v)=>{o+=v,t({type:"cost",totalUsd:o})};t({type:"stage",stage:"resolving_target"});let l=e.repo,{pr:c,base:u,head:d,slug:f}=e.target,p=Sm({pr:c,base:u,head:d}),h=e.tag,g=Qe.join(ye,"reviews",`${h}.md`);await Cn(wt);for(let v of["runs","raw","logs","prompts","reviews","maps"])await Cn(Qe.join(ye,v));await Fe(Qe.join(ye,".gitignore"),`*
563
+ `);let w=await vm(l,c,d);ri({subject:w.dir,releaseSubject:w.release});let b=Date.now();ri({repoName:f});let x=!e.local,S=await aa(f,c,u,d,e.intent,{strict:x}),P=[...await tm(f,c,{strict:x}),...e.prior??[]],M=rm(P,S.body),k=fg(P),E=xu(P);if(k.length){let v=k.filter((K)=>K.verdict==="disputed").length;console.error(` ${v} disputed and ${k.length-v} reported-fixed answers to earlier findings`)}let F=Math.max(0,...P.filter((v)=>v.mine).map((v)=>v.runs??0));s();let L=(await pt(["diff","--name-only",`${u}..${d}`])).trim().split(`
564
+ `).filter(Boolean),O={skip:[],docs:[],code:[]};for(let v of L)O[fi(v)].push(v);let U=O.code,I=e.local?e.round??1:F+1;if(e.maxRounds!==void 0&&I>e.maxRounds){if(console.error(` not reviewing: this would be round ${I}, and --max-rounds is ${e.maxRounds}`),c&&!e.local){let v=await em(f,c);if(v)await sg({dir:Qe.join(ye,"reviews"),tag:h,slug:f,pr:c,head:d,summary:ig(v,{round:I,maxRounds:e.maxRounds,head:d})});else console.error(" no summary comment from an earlier review to add the notice to")}return{record:null,roundLimit:{maxRounds:e.maxRounds,round:I},units:[],byClass:O,findings:[],costUsd:0,wallMs:Date.now()-b,markdownPath:g}}if(U.length===0)return console.error(` ${L.length} changed files, none reviewable \u2014 no review`),await bu({dir:Qe.join(ye,"reviews"),tag:h,slug:f,pr:c,base:u,head:d,findings:[],stats:{"changed files":String(L.length),reviewed:"nothing: no code files in this change"},repoDir:st,local:e.local}),{record:null,units:[],byClass:O,findings:[],costUsd:0,wallMs:Date.now()-b,markdownPath:g};let j={kind:"full",files:U};if(e.priorHead){let v=e.priorHead===d?[]:await pt(["diff","--name-only",e.priorHead,d]).then((K)=>K.trim().split(`
565
+ `).filter(Boolean),()=>null);j=ME(U,v),console.error(j.kind==="incremental"?` re-review: ${j.files.length} of ${U.length} code files changed since ${e.priorHead.slice(0,12)}`:` re-review in full: ${j.reason}`)}let H=j.kind==="incremental";t({type:"stage",stage:"grouping"});let{wholeDiff:ve,diffstat:Re,diffU0:ne,fileTokens:ce,facts:qe,links:ze,grouping:Je}=await ca({base:u,head:d,files:U,source:()=>Bo(st)}),Xe=dg({tag:h,cacheKey:p,intent:S,diffstat:Re,diff:ve,otherFiles:O.docs}).catch((v)=>({model:ei,costUsd:0,wallMs:0,cached:!1,diffChars:0,failure:v instanceof Error?v.message:String(v)})),nt=await Qh(u,d,U),be=xr==="code"?Je:void 0,Te=be?.groups.length===1;if(be){let v=ui(be.groups,(W)=>ce.get(W)??0),K=be.groups.map((W,rt)=>({id:W.id,title:Te?S.title||W.id:v[rt]??W.id,files:W.files,priority:rt+1}));t({type:"units",units:K,byClass:O})}s(),t({type:"stage",stage:"checking_registry"});let me=await vh({repo:st,base:u,head:d}),G=xh(me.findings),T=Qe.join(ye,"maps",`${p}.md`),B="",z=await Yr(T);if(t({type:"stage",stage:"building_map"}),!z)try{let v=await zh({repo:st,base:u,head:d,cacheDir:Qe.join(ye,"outlines")});await Fe(T,v.markdown),await mn(Qe.join(ye,"maps",`${p}.meta.json`),v.meta),z=!0}catch(v){console.error(`repo map unavailable, continuing without it: ${v}`)}if(z)B=`A repository orientation map for this change is at \`${T}\`. Read it first (use tilth_read if available) to get your bearings before exploring \u2014 it lists the codebase layout, the symbols in each changed file, and the files that import or are imported by them.
566
+ `;if(s(),!Te)t({type:"stage",stage:"grouping"});let te=`${h}-part`,we=`${wt}/${te}.json`;await Qt(we);let Ne=be?tg({groups:be.groups,links:ze,outline:nt,intent:S,registry:G,outFile:we}):eg({diffstat:Re,outline:nt,intent:S,codeFiles:U,registry:G,outFile:we});await Fe(Qe.join(ye,"prompts",`${te}.txt`),Ne);let Ye={wallMs:0,costUsd:0,numTurns:0,payload:void 0};if(!Te)Ye=await Pn(Ne,{budget:Pc,outFile:we,tag:te,model:On,effort:en,answerKeys:["groups","review_units"]}),a(Ye.costUsd);s();let hr=[],Ot;if(be&&Te)Ot=[{id:be.groups[0].id,title:S.title||be.groups[0].id,files:be.groups[0].files,priority:1}];else if(be){let v=dm(be.groups,Ye.payload,Qn,ce);hr=v.moves,Ot=_u(v.units,U);for(let K of hr)console.error(` moved ${K.file}: ${K.from} -> ${K.to} (${K.reason})`)}else{let v=Ye.payload??void 0;Ot=_u(v?.review_units??[],U)}let qn=new Set(me.findings.map((v)=>v.addedIn)),Hn=new Map(Ot.map((v)=>[v.id,v.files.reduce((K,W)=>K+(ce.get(W)??0),0)])),Ft=[...Ot].sort((v,K)=>{let W=Number(v.files.some((Ji)=>qn.has(Ji))),rt=Number(K.files.some((Ji)=>qn.has(Ji)));if(W!==rt)return rt-W;let ut=v.priority??5,Wn=K.priority??5;if(ut!==Wn)return ut-Wn;return(Hn.get(K.id)??0)-(Hn.get(v.id)??0)}),y=new Map(Ft.map((v,K)=>[v.id,K])),_=Qm(Ft,ce,Qn).sort((v,K)=>v.part-K.part||(y.get(v.unitId)??0)-(y.get(K.unitId)??0)),D=new Set(j.files),C=H?_.map((v)=>{let K=v.files.filter((W)=>D.has(W));return{...v,files:K,tokens:K.reduce((W,rt)=>W+(ce.get(rt)??0),0)}}).filter((v)=>v.files.length>0):_,Q=C.slice(0,Rr),fe=_.slice(0,Rr),Ae=C.slice(Rr).flatMap((v)=>v.files),Xt=Q.filter((v)=>v.tokens>Qn);console.error(`${c?`PR ${c} `:""}${u.slice(0,12)}..${d.slice(0,12)} \u2014 ${L.length} changed (${U.length} code, ${O.docs.length} docs, ${O.skip.length} skipped) -> ${Ot.length} units, ${Q.length} slices${Ae.length?`, ${Ae.length} files over cap`:""}${Xt.length?`, ${Xt.length} over ${Qn} tokens`:""}, registry signals: ${me.findings.length}, prior comments: ${P.length}`);for(let v of Q)console.error(` slice ${v.unitId}${v.parts>1?` ${v.part}/${v.parts}`:""} (${v.tokens} tokens): ${v.files.join(", ")}`);let pe=[],ct=[],So=[],dn=await Xe;s(),a(dn.costUsd);let Ki=dn.draft;t({type:"log",message:Ki?` intent draft${dn.cached?" (cached)":""}: ${Ki.title}`:` warning: no intent draft (${dn.failure??"unknown error"}); reviewing without it`}),t({type:"units",units:Ot,byClass:O}),t({type:"stage",stage:"reviewing"});let Ro=0,zl=!1,Jl=[];async function mS(v){while(!0){if(n?.aborted)return;if(r!==void 0&&o>=r&&Ro<Q.length){let it=Q.slice(Ro);Ro=Q.length,zl=!0,Jl=it.flatMap((To)=>To.files),console.error(` cost $${o.toFixed(2)} reached --max-cost $${r.toFixed(2)}: ${it.length} slice(s) not started`),t({type:"budget",totalUsd:o,limitUsd:r,skippedSlices:it.length});return}let K=Ro++;if(K>=Q.length)return;let W=Q[K],rt={id:W.unitId,title:W.title,rationale:W.rationale,files:W.files,priority:W.priority},ut=`${h}-s${String(K).padStart(2,"0")}`,[Wn,Ji]=await Promise.all([pt(["diff",`${u}..${d}`,"--",...W.files]),H&&e.priorHead?pt(["diff",e.priorHead,d,"--",...W.files]):void 0]),lp=vr(Wn,u);if(!lp.trim())continue;let lc=`${wt}/${ut}.json`;await Qt(lc);let cp=mu({unit:rt,diff:lp,intent:S,draft:Ki,registry:G,prior:M,mapNote:B,outFile:lc,crossLinks:um(W.files,ze),instructions:e.instructions,sinceLast:Ji});await Fe(Qe.join(ye,"prompts",`${ut}.txt`),cp);let cc={type:"slice",index:K,total:Q.length,title:W.title};t({...cc,status:"started"});let Pe;try{Pe=await Pn(cp,{budget:Tc,outFile:lc,tag:ut,answerKeys:["findings"]}),a(Pe.costUsd)}catch(it){let To=it instanceof Error?it.message:String(it);console.error(` [w${v}] ${W.unitId} \u2014 failed to run: ${To}`);let RS={kind:"spawn",message:`failed to run: ${To}`};pe.push({unit:W.unitId,part:W.part,parts:W.parts,tokens:W.tokens,files:W.files,tag:ut,wallMs:0,costUsd:0,numTurns:0,exitCode:-1,findingCount:0,ok:!1,failure:RS}),t({...cc,status:"failed"});continue}let uc=Pe.payload,Mo=Array.isArray(uc)?uc:uc?.findings??[],Xi=(Array.isArray(Mo)?Mo:[]).filter((it)=>typeof it==="object"&&it!==null);if(Xi.length!==(Array.isArray(Mo)?Mo.length:0))console.error(` [w${v}] ${W.unitId} \u2014 discarded malformed entries from the findings file`);for(let it of Xi)it._slice=W.unitId,it.also_at=fu(it,it.also_at),ct.push(it);let up=Bm(Pe.payload);So[K]=up,pe.push({unit:W.unitId,part:W.part,parts:W.parts,tokens:W.tokens,files:W.files,tag:ut,wallMs:Pe.wallMs,costUsd:Pe.costUsd,numTurns:Pe.numTurns,usage:Pe.usage,tools:Pe.tools,checked:up,exitCode:Pe.exitCode,findingCount:Xi.length,ok:Pe.payload!==null,...Pe.failure?{failure:Pe.failure}:{},...Pe.deliveredAs?{deliveredAs:Pe.deliveredAs}:{}}),console.error(` [w${v}] ${W.unitId}${W.parts>1?` ${W.part}/${W.parts}`:""} (${W.files.length}f ${W.tokens}t) \u2014 ${(Pe.wallMs/1000).toFixed(0)}s $${Pe.costUsd.toFixed(2)} ${Pe.numTurns}t ${Xi.length} findings${Pe.failure?` \u2014 failed: ${Pe.failure.message}`:""}`),t({...cc,status:Pe.payload!==null?"ok":"failed",costUsd:Pe.costUsd,wallMs:Pe.wallMs,findings:Xi.length})}}await Promise.all(Array.from({length:Math.min(Nc,Q.length)},(v,K)=>mS(K))),s();let $o=pe.filter((v)=>v.ok??v.exitCode===0),ko=pe.filter((v)=>!$o.includes(v));if(pe.length>0&&$o.length===0)throw Error(TE(ko,h,pe.length));if(ko.length){console.error(` warning: ${ko.length} of ${pe.length} slices failed`);for(let v of wg(ko,h))console.error(` ${v}`)}let Kn=ct;if(ct.length>20)Kn=ct.filter((v)=>!(v.severity==="nice-to-have"&&v.confidence!=="high"));let Xl=ct.length-Kn.length,Yl=`${h}-merge`,Zl=`${wt}/${Yl}.json`;await Qt(Zl);let Xf=gu({findings:Kn,intent:S,draft:Ki,files:U,prior:M,outFile:Zl,instructions:e.instructions,disputes:hg(k),changedLines:is(ne),maxNew:H?uu:nr,sinceLast:H?j.files:void 0});await Fe(Qe.join(ye,"prompts",`${Yl}.txt`),Xf);let gS=qm(Kn.length,Dc),Ql=`${h}-walk`,ec=`${wt}/${Ql}.json`;await Qt(ec);let Eo=Ft.filter((v)=>fe.some((K)=>K.unitId===v.id)),_S=new Set(Eo.flatMap((v)=>v.files)),Yf=_.flatMap((v)=>v.files).filter((v)=>!_S.has(v)),wS=[...Eo,...Yf.length?[{files:[...new Set(Yf)]}]:[]],{shown:tc,sketched:Wr}=fa(wS,ce,os),yS=tc.reduce((v,K)=>v+(ce.get(K)??0),0),bS=Wr.length?vr(await pt(["diff",`${u}..${d}`,"--",...tc]),u):ve;if(Wr.length)console.error(` walkthrough sees ${tc.length} of ${U.length} files (${yS} tokens), ${Wr.length} given as sketches`);let vS=ua(ne,qe),Zf=xa({diffstat:Re,diff:bS,sketches:Wr.map((v)=>da(vS.get(v)??{file:v,added:0,removed:0,defines:[],touches:[]})),crossLinks:ha(Eo,ze),intent:S,draft:Ki,findingIndex:Kn.map((v)=>`- [${v.severity}] ${v.file}:${v.line} \u2014 ${v.title}`).join(`
567
+ `),unitSummary:Eo.map((v)=>{let K=pa(v.files,ze);return`**${v.title}** (${v.id})
568
+ ${v.files.map((W)=>` - ${W}`).join(`
569
569
  `)}`+(K.length?`
570
570
  Links: ${K.join("; ")}`:"")}).join(`
571
571
 
572
- `),docsFiles:O.docs,registry:W,outFile:Kl});await De(Qe.join(ye,"prompts",`${Hl}.txt`),jf);let Uf=(v)=>(K)=>(console.error(` ${v} failed to run: ${K instanceof Error?K.message:String(K)}`),{wallMs:0,exitCode:-1,costUsd:0,numTurns:0,usage:null,payload:null}),Qx={wallMs:0,exitCode:0,costUsd:0,numTurns:0,usage:null,payload:null},Bf=qm(k),qf=H&&j.files.length===0&&!Bf,Gl=qf||!Bf&&!ym(qn,P);if(qf)console.error(" coordinator skipped: no code changed since the last review");else if(Gl)console.error(" coordinator skipped: no findings and no earlier comments to close out");t({type:"stage",stage:"coordinating"}),t({type:"stage",stage:"walkthrough"});let[un,Hn]=await Promise.all([Gl?Promise.resolve({...Qx,payload:{keep:[]}}):On(Df,{budget:Vx,outFile:ql,tag:Bl,model:yr,effort:Zt,answerKeys:["keep"]}).then((v)=>(a(v.costUsd),v)).catch(Uf("coordinator")),On(jf,{budget:Yi,outFile:Kl,tag:Hl,model:kn,effort:Zt,answerKeys:["chapters"]}).then((v)=>(a(v.costUsd),v)).catch(Uf("walkthrough"))]);s();let yo=Hn.payload??void 0,fr=un.payload??{},Ui=[],bo=[],Bi=Gl?"nothing-to-merge":"coordinator",Xt=Wm(fr.disputes,k);for(let v of Xt)console.error(` ${v.outcome} "${v.claim}" after @${v.author} disputed it`);let Vl=new Set([...E,...Xt].filter((v)=>v.outcome==="withdrawn").map((v)=>v.fp)),Hf=mm(P),zl=(v)=>{if(!Hf.size&&!Vl.size)return v;return v.filter((K)=>{let G=gn(K.file,K.title);if(Vl.has(G))return bo.push({title:K.title,reason:"withdrawn after the author disputed it"}),console.error(` suppressed "${K.title}" \u2014 withdrawn after a dispute`),!1;let rt=Hf.get(G);if(!rt)return!0;return bo.push({title:K.title,reason:`already posted on an earlier push (comment ${rt.id})`}),console.error(` suppressed "${K.title}" \u2014 same claim as comment ${rt.id}`),!1})},pr=[],Jl=(v)=>{if(!Uo)return v;return v.filter((K)=>{if(K.severity!=="question")return!0;return pr.push(K),!1})},vo=new Set,xo=[],Kf={maxNew:H?Yc:Qn,maxPreexisting:da};if(fr.keep){let v=bm(fr,qn,P);bo=v.dropped;let K=(ut,Kn)=>(tt[ut.severity]?.rank??9)-(tt[Kn.severity]?.rank??9)||qt[ot(ut.file)]-qt[ot(Kn.file)]||ci.indexOf(ut.confidence)-ci.indexOf(Kn.confidence),G=v.kept.sort(K);vo=new Set([...G,...v.capped].map((ut)=>gn(ut.file,ut.title)));let rt=Zc(Jl(zl(G)),Kf);xo=[...rt.overCap,...Jl(zl(v.capped.sort(K)))],Ui=rt.posted}if(!fr.keep){Bi="deterministic-fallback";let v=wm(qn);vo=new Set(v.map((G)=>gn(G.file,G.title)));let K=Zc(Jl(zl(v)).map((G)=>({...G,repeat_of:void 0})),Kf);Ui=K.posted,xo=K.overCap}let qi=(fr.resolved??[]).filter((v)=>{let K=P.find((G)=>G.id===v.id);if(!K?.mine)return!1;if(!K.file)return!1;if(K.fingerprint&&Xt.some((G)=>G.fp===K.fingerprint))return!1;return!(K.fingerprint&&vo.has(K.fingerprint))});if(qi.length)console.error(` closing out ${qi.length} earlier comments as fixed`);if(pr.length)console.error(` left ${pr.length} question(s) out of the posted review`);t({type:"stage",stage:"verifying"});let hr=[],Ro=[...bo];for(let v of Ui){let K=Qe.join(st,v.file),G=await Op(K);if(G===null){Ro.push({title:v.title,reason:`cited file does not exist: ${v.file}`});continue}if(v.line<1||v.line>G){Ro.push({title:v.title,reason:`cited line ${v.line} outside ${v.file} (${G} lines)`});continue}hr.push(v)}let Hi={overCap:Ce,failed:pe.filter((v)=>!(v.ok??v.exitCode===0)).flatMap((v)=>v.files??[]),budget:jl},Wf=new Set([...Hi.overCap,...Hi.failed,...Hi.budget]),eR=new Set(Q.flatMap((v)=>v.files).filter((v)=>!Wf.has(v))),mr=hm(P,{unread:H?(v)=>!eR.has(v):(v)=>Wf.has(v),refound:vo,rendered:new Set(hr.map((v)=>gn(v.file,v.title))),withdrawn:Vl,dropQuestions:Uo});if(mr.length)console.error(` carrying forward ${mr.length} earlier summary finding(s) this review did not post again`);let Gf=ho.flat().filter(Boolean),Xl=pe.reduce((v,K)=>v+K.costUsd,0)+un.costUsd+Hn.costUsd+cn.costUsd,Yl=Date.now()-b,Vf={"review units":Q.length,"code files reviewed":Q.reduce((v,K)=>v+K.files.length,0),"docs files not reviewed":O.docs.length,"generated files skipped":O.skip.length,"raw findings":ct.length,"after merge":Ui.length,"after verification":hr.length,...pr.length?{"questions not posted (settings)":pr.length}:{},"registry signals":me.findings.length,"prior comments considered":P.length,...mr.length?{"carried forward unread":mr.length}:{},...Xt.length?{"disputes ruled":`${Xt.filter((v)=>v.outcome==="withdrawn").length} withdrawn, ${Xt.filter((v)=>v.outcome==="upheld").length} upheld`}:{},...H?{"review scope":`${j.files.length} of ${U.length} code files changed since the last review`}:j.reason?{"review scope":`full: ${j.reason}`}:{},"wall time":`${(Yl/60000).toFixed(1)} min`,cost:`$${Xl.toFixed(2)}`,model:$n,...yr!==$n?{"coordinator model":yr}:{},"walkthrough model":kn,"walkthrough stops":yo?(yo.chapters??[]).reduce((v,K)=>v+(K.stops?.length??0),0):"none \u2014 the walkthrough produced no guide",...qr.length?{"walkthrough did not read":`${qr.length} of ${U.length} files`}:{},...Ce.length?{"not reviewed (over cap)":Ce.join(", ")}:{},...Ll?{"not reviewed (cost limit)":jl.join(", ")}:{},...Ul?{"trimmed before merge":`${Ul} low-confidence nice-to-have`}:{},...go.length<pe.length?{"slices that failed":`${pe.length-go.length} of ${pe.length} \u2014 this review is incomplete`}:{},...Bi!=="coordinator"&&Bi!=="nothing-to-merge"?{merging:`${Bi} \u2014 findings are unverified`}:{}};t({type:"stage",stage:"writing"}),await au({dir:Qe.join(ye,"reviews"),tag:h,slug:f,pr:c,base:u,head:d,findings:hr,intentAlignment:fr.intent_alignment,dropped:Ro,stats:Vf,walkthrough:yo,prior:P,resolved:qi,rulings:Xt,earlierRulings:E,carried:mr,runs:D+1,noReviewers:pe.length===0,unreviewed:Hi,checked:Gf,overCap:xo,repoDir:st,local:e.local});let zf={pr:c,base:u,head:d,runner:Lp,model:$n,effort:zr,effortAux:Zt,models:{review:$n,coordinator:yr,walkthrough:kn,intent:Jr},tag:h,wallMs:Yl,totalCostUsd:Xl,mergeMode:Bi,preTrimmed:Ul,budgetStopped:Ll,sliceRuns:pe,merge:{wallMs:un.wallMs,costUsd:un.costUsd,numTurns:un.numTurns,usage:un.usage,tools:"tools"in un?un.tools:void 0,..."deliveredAs"in un?{deliveredAs:un.deliveredAs}:{}},walk:{model:kn,wallMs:Hn.wallMs,costUsd:Hn.costUsd,numTurns:Hn.numTurns,usage:Hn.usage,..."deliveredAs"in Hn?{deliveredAs:Hn.deliveredAs}:{}},walkthrough:yo??null,intentDraft:cn,grouping:wr,groupMoves:dr,reviewUnits:Q,reviewScope:j.kind,reviewedFiles:Q.reduce((v,K)=>v+K.files.length,0),...j.reason?{scopeReason:j.reason}:{},promptVersion:km(await _t(Qe.join(Vr,"system.md"))),...e.instructions?.trim()?{instructionsHash:Em(e.instructions)}:{},registry:{meta:me.meta,findings:me.findings},priorComments:P.length,prior:P,rawFindings:ct,mergedFindings:Ui,verifiedFindings:hr,overCapFindings:xo,...pr.length?{droppedQuestions:pr}:{},...Xr?{postMinSeverity:Xr}:{},checked:Gf,unreviewed:Hi,resolved:qi,...mr.length?{carried:mr}:{},...k.length||E.length?{disputes:Km(E,Xt,k)}:{},...Xt.length?{rulings:Xt}:{},roundProgress:Gm({prior:P,resolvedIds:qi.map((v)=>v.id),earlierRulings:E,rulings:Xt,newFindings:hr.length}),runs:D+1,rejected:Ro,intentAlignment:fr.intent_alignment??null,stats:Vf};return await fn(Qe.join(ye,"runs",`${h}.json`),zf),{record:zf,units:Ot,byClass:O,findings:hr,costUsd:Xl,wallMs:Yl,markdownPath:g}}var er=(e)=>Array.isArray(e)?e:[e],Zm=(e,t)=>{let n=[[],[]];for(let r of e)if(t(r))n[0].push(r);else n[1].push(r);return n},wa=Array,Ht=(e,t)=>e.includes(t),Qm=(e,t=0)=>[...Array(e)].map((n,r)=>r+t),de=(e,t,n)=>{if(e===void 0)return t===void 0?[]:Array.isArray(t)?t:[t];if(n?.prepend)if(Array.isArray(t))e.unshift(...t);else e.unshift(t);else if(Array.isArray(t))e.push(...t);else e.push(t);return e},In=(e,t)=>{if(t===void 0||t===null)return e??[];if(e===void 0||e===null)return er(t);return e.concat(t)},eg=(...e)=>e.reduce(In,[]),wn=(e,t,n)=>{if(e===void 0)return Array.isArray(t)?t:[t];let r=n?.isEqual??((s,o)=>s===o);for(let s of er(t))if(!e.some((o)=>r(o,s)))e.push(s);return e},tg=(e,t)=>e.reduce((n,r)=>{let s=r[t];return n[s]=de(n[s],r),n},{}),Pn=(e,t,n)=>e.length===t.length&&e.every(n?.isEqual?(r,s)=>n.isEqual(r,t[s]):(r,s)=>r===t[s]);var Rt=(e,t)=>Ke(e)===t,Ke=(e)=>{let t=typeof e;return t==="object"?e===null?"null":"object":t==="function"?"object":t},St={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},ng={...St,function:"a function"};class rg extends Error{}var he=(e)=>Ar(e,rg),Ar=(e,t=Error)=>{throw new t(e)};class ps extends Error{name="ParseError"}var C=(e)=>Ar(e,ps),nn=(e)=>` ${e}`,ig="\u200B";var ie=(e,t)=>{let n={},r=Array.isArray(e),s=!1;for(let[o,a]of Object.entries(e).entries()){let l=r?t(o,a[1]):t(...a,o);s||=typeof l[0]==="number";let c=Array.isArray(l[0])||l.length===0?l:[l];for(let[u,d]of c)if(typeof u==="object")n[u.group]=de(n[u.group],d);else n[u]=d}return s?Object.values(n):n};var pu=Object.entries;var We=(e,t)=>(e in t),fi=(e,t)=>(t in e);class hu{constructor(e){Object.assign(this,e)}}var sg=class{};class hs extends sg{}var Jk=(e,t)=>{let n={},r={},s;for(s in e)if(s in t)n[s]=e[s];else r[s]=e[s];return[n,r]};var ya=(e,t)=>Jk(e,t)[1],yn=(e)=>Object.keys(e).length===0,Cr=(e)=>[...Object.entries(e),...Object.getOwnPropertySymbols(e).map((t)=>[t,e[t]])],og=(e,t)=>Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)),ag=(e)=>{let t=Object.keys(e).sort(),n={};for(let r=0;r<t.length;r++)n[t[r]]=e[t[r]];return n};var $t=nn(`unset${ig}`),lg=(e)=>Object.values(e).filter((t)=>{if(typeof t==="number")return!0;return typeof e[t]!=="number"});var mu={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},gu=globalThis.File??Blob,_u={ArrayBuffer,Blob,File:gu,FormData,Headers,Request,Response,URL},Xk={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},Or={...mu,..._u,...Xk,String,Number,Boolean},ms=(e)=>{let t=Object.getPrototypeOf(e);while(t?.constructor&&(!We(t.constructor.name,Or)||!(e instanceof Or[t.constructor.name])))t=Object.getPrototypeOf(t);let n=t?.constructor?.name;if(n===void 0||n==="Object")return;return n},gs=(e)=>typeof e==="object"&&e!==null?ms(e)??"object":Ke(e);var Re=Array.isArray,Yk={Array:"an array",Function:"a function",Date:"a Date",RegExp:"a RegExp",Error:"an Error",Map:"a Map",Set:"a Set",String:"a String object",Number:"a Number object",Boolean:"a Boolean object",Promise:"a Promise",WeakMap:"a WeakMap",WeakSet:"a WeakSet"},Zk={ArrayBuffer:"an ArrayBuffer instance",Blob:"a Blob instance",File:"a File instance",FormData:"a FormData instance",Headers:"a Headers instance",Request:"a Request instance",Response:"a Response instance",URL:"a URL instance"},Qk={Int8Array:"an Int8Array",Uint8Array:"a Uint8Array",Uint8ClampedArray:"a Uint8ClampedArray",Int16Array:"an Int16Array",Uint16Array:"a Uint16Array",Int32Array:"an Int32Array",Uint32Array:"a Uint32Array",Float32Array:"a Float32Array",Float64Array:"a Float64Array",BigInt64Array:"a BigInt64Array",BigUint64Array:"a BigUint64Array"},cg={...Yk,...Zk,...Qk},_s=(e)=>{let t=Object(e).name??null;return t&&We(t,Or)&&Or[t]===e?t:null};var wu=(e,t)=>{let n=e.prototype;while(n!==null){if(n===t.prototype)return!0;n=Object.getPrototypeOf(n)}return!1};var ug=(e)=>dg(e,new Map),dg=(e,t)=>{if(typeof e!=="object"||e===null)return e;if(t?.has(e))return t.get(e);let n=_s(e.constructor);if(n==="Date")return new Date(e.getTime());if(n&&n!=="Array")return e;let r=Array.isArray(e)?e.slice():Object.create(Object.getPrototypeOf(e)),s=Object.getOwnPropertyDescriptors(e);if(t){t.set(e,r);for(let o in s){let a=s[o];if("get"in a||"set"in a)continue;a.value=dg(a.value,t)}}return Object.defineProperties(r,s),r};var eE=(e)=>{let t=$t;return()=>t===$t?t=e():t},tr=(e)=>typeof e==="function"&&e.length===0;var fg=class extends Function{constructor(...e){let t=e.slice(0,-1),n=e[e.length-1];try{super(...t,n)}catch(r){return he(`Encountered an unexpected error while compiling your definition:
572
+ `),docsFiles:O.docs,registry:G,outFile:ec});await Fe(Qe.join(ye,"prompts",`${Ql}.txt`),Zf);let Qf=(v)=>(K)=>(console.error(` ${v} failed to run: ${K instanceof Error?K.message:String(K)}`),{wallMs:0,exitCode:-1,costUsd:0,numTurns:0,usage:null,payload:null}),xS={wallMs:0,exitCode:0,costUsd:0,numTurns:0,usage:null,payload:null},ep=pg(k),tp=H&&j.files.length===0&&!ep,nc=tp||!ep&&!Km(Kn,P);if(tp)console.error(" coordinator skipped: no code changed since the last review");else if(nc)console.error(" coordinator skipped: no findings and no earlier comments to close out");t({type:"stage",stage:"coordinating"}),t({type:"stage",stage:"walkthrough"});let[fn,Gn]=await Promise.all([nc?Promise.resolve({...xS,payload:{keep:[]}}):Pn(Xf,{budget:gS,outFile:Zl,tag:Yl,model:Sr,effort:en,answerKeys:["keep"]}).then((v)=>(a(v.costUsd),v)).catch(Qf("coordinator")),Pn(Zf,{budget:ss,outFile:ec,tag:Ql,model:On,effort:en,answerKeys:["chapters"]}).then((v)=>(a(v.costUsd),v)).catch(Qf("walkthrough"))]);s();let Co=Gn.payload??void 0,mr=fn.payload??{},Gi=[],Ao=[],Wi=nc?"nothing-to-merge":"coordinator",Yt=gg(mr.disputes,k);for(let v of Yt)console.error(` ${v.outcome} "${v.claim}" after @${v.author} disputed it`);let rc=new Set([...E,...Yt].filter((v)=>v.outcome==="withdrawn").map((v)=>v.fp)),np=Um(P),ic=(v)=>{if(!np.size&&!rc.size)return v;return v.filter((K)=>{let W=wn(K.file,K.title);if(rc.has(W))return Ao.push({title:K.title,reason:"withdrawn after the author disputed it"}),console.error(` suppressed "${K.title}" \u2014 withdrawn after a dispute`),!1;let rt=np.get(W);if(!rt)return!0;return Ao.push({title:K.title,reason:`already posted on an earlier push (comment ${rt.id})`}),console.error(` suppressed "${K.title}" \u2014 same claim as comment ${rt.id}`),!1})},gr=[],sc=(v)=>{if(!Zo)return v;return v.filter((K)=>{if(K.severity!=="question")return!0;return gr.push(K),!1})},Oo=new Set,Io=[],rp={maxNew:H?uu:nr,maxPreexisting:ya};if(mr.keep){let v=Gm(mr,Kn,P);Ao=v.dropped;let K=(ut,Wn)=>(tt[ut.severity]?.rank??9)-(tt[Wn.severity]?.rank??9)||Ht[ot(ut.file)]-Ht[ot(Wn.file)]||hi.indexOf(ut.confidence)-hi.indexOf(Wn.confidence),W=v.kept.sort(K);Oo=new Set([...W,...v.capped].map((ut)=>wn(ut.file,ut.title)));let rt=du(sc(ic(W)),rp);Io=[...rt.overCap,...sc(ic(v.capped.sort(K)))],Gi=rt.posted}if(!mr.keep){Wi="deterministic-fallback";let v=Hm(Kn);Oo=new Set(v.map((W)=>wn(W.file,W.title)));let K=du(sc(ic(v)).map((W)=>({...W,repeat_of:void 0})),rp);Gi=K.posted,Io=K.overCap}let Vi=(mr.resolved??[]).filter((v)=>{let K=P.find((W)=>W.id===v.id);if(!K?.mine)return!1;if(!K.file)return!1;if(K.fingerprint&&Yt.some((W)=>W.fp===K.fingerprint))return!1;return!(K.fingerprint&&Oo.has(K.fingerprint))});if(Vi.length)console.error(` closing out ${Vi.length} earlier comments as fixed`);if(gr.length)console.error(` left ${gr.length} question(s) out of the posted review`);t({type:"stage",stage:"verifying"});let _r=[],Po=[...Ao];for(let v of Gi){let K=Qe.join(st,v.file),W=await ah(K);if(W===null){Po.push({title:v.title,reason:`cited file does not exist: ${v.file}`});continue}if(v.line<1||v.line>W){Po.push({title:v.title,reason:`cited line ${v.line} outside ${v.file} (${W} lines)`});continue}_r.push(v)}let zi={overCap:Ae,failed:pe.filter((v)=>!(v.ok??v.exitCode===0)).flatMap((v)=>v.files??[]),budget:Jl},ip=new Set([...zi.overCap,...zi.failed,...zi.budget]),SS=new Set(Q.flatMap((v)=>v.files).filter((v)=>!ip.has(v))),wr=jm(P,{unread:H?(v)=>!SS.has(v):(v)=>ip.has(v),refound:Oo,rendered:new Set(_r.map((v)=>wn(v.file,v.title))),withdrawn:rc,dropQuestions:Zo});if(wr.length)console.error(` carrying forward ${wr.length} earlier summary finding(s) this review did not post again`);let sp=So.flat().filter(Boolean),oc=pe.reduce((v,K)=>v+K.costUsd,0)+fn.costUsd+Gn.costUsd+dn.costUsd,ac=Date.now()-b,op={"review units":Q.length,"code files reviewed":Q.reduce((v,K)=>v+K.files.length,0),"docs files not reviewed":O.docs.length,"generated files skipped":O.skip.length,"raw findings":ct.length,"after merge":Gi.length,"after verification":_r.length,...gr.length?{"questions not posted (settings)":gr.length}:{},"registry signals":me.findings.length,"prior comments considered":P.length,...wr.length?{"carried forward unread":wr.length}:{},...Yt.length?{"disputes ruled":`${Yt.filter((v)=>v.outcome==="withdrawn").length} withdrawn, ${Yt.filter((v)=>v.outcome==="upheld").length} upheld`}:{},...H?{"review scope":`${j.files.length} of ${U.length} code files changed since the last review`}:j.reason?{"review scope":`full: ${j.reason}`}:{},"wall time":`${(ac/60000).toFixed(1)} min`,cost:`$${oc.toFixed(2)}`,model:An,...Sr!==An?{"coordinator model":Sr}:{},"walkthrough model":On,"walkthrough stops":Co?(Co.chapters??[]).reduce((v,K)=>v+(K.stops?.length??0),0):"none \u2014 the walkthrough produced no guide",...Wr.length?{"walkthrough did not read":`${Wr.length} of ${U.length} files`}:{},...Ae.length?{"not reviewed (over cap)":Ae.join(", ")}:{},...zl?{"not reviewed (cost limit)":Jl.join(", ")}:{},...Xl?{"trimmed before merge":`${Xl} low-confidence nice-to-have`}:{},...$o.length<pe.length?{"slices that failed":`${pe.length-$o.length} of ${pe.length} \u2014 this review is incomplete`}:{},...Wi!=="coordinator"&&Wi!=="nothing-to-merge"?{merging:`${Wi} \u2014 findings are unverified`}:{}};t({type:"stage",stage:"writing"}),await bu({dir:Qe.join(ye,"reviews"),tag:h,slug:f,pr:c,base:u,head:d,findings:_r,intentAlignment:mr.intent_alignment,dropped:Po,stats:op,walkthrough:Co,prior:P,resolved:Vi,rulings:Yt,earlierRulings:E,carried:wr,runs:F+1,noReviewers:pe.length===0,unreviewed:zi,checked:sp,overCap:Io,repoDir:st,local:e.local});let ap={pr:c,base:u,head:d,runner:mh,model:An,effort:Qr,effortAux:en,models:{review:An,coordinator:Sr,walkthrough:On,intent:ei},tag:h,wallMs:ac,totalCostUsd:oc,mergeMode:Wi,preTrimmed:Xl,budgetStopped:zl,sliceRuns:pe,merge:{wallMs:fn.wallMs,costUsd:fn.costUsd,numTurns:fn.numTurns,usage:fn.usage,tools:"tools"in fn?fn.tools:void 0,..."deliveredAs"in fn?{deliveredAs:fn.deliveredAs}:{}},walk:{model:On,wallMs:Gn.wallMs,costUsd:Gn.costUsd,numTurns:Gn.numTurns,usage:Gn.usage,..."deliveredAs"in Gn?{deliveredAs:Gn.deliveredAs}:{}},walkthrough:Co??null,intentDraft:dn,grouping:xr,groupMoves:hr,reviewUnits:Q,reviewScope:j.kind,reviewedFiles:Q.reduce((v,K)=>v+K.files.length,0),...j.reason?{scopeReason:j.reason}:{},promptVersion:Ym(await _t(Qe.join(Zr,"system.md"))),...e.instructions?.trim()?{instructionsHash:Zm(e.instructions)}:{},registry:{meta:me.meta,findings:me.findings},priorComments:P.length,prior:P,rawFindings:ct,mergedFindings:Gi,verifiedFindings:_r,overCapFindings:Io,...gr.length?{droppedQuestions:gr}:{},...ti?{postMinSeverity:ti}:{},checked:sp,unreviewed:zi,resolved:Vi,...wr.length?{carried:wr}:{},...k.length||E.length?{disputes:mg(E,Yt,k)}:{},...Yt.length?{rulings:Yt}:{},roundProgress:_g({prior:P,resolvedIds:Vi.map((v)=>v.id),earlierRulings:E,rulings:Yt,newFindings:_r.length}),runs:F+1,rejected:Po,intentAlignment:mr.intent_alignment??null,stats:op};return await mn(Qe.join(ye,"runs",`${h}.json`),ap),{record:ap,units:Ot,byClass:O,findings:_r,costUsd:oc,wallMs:ac,markdownPath:g}}var rr=(e)=>Array.isArray(e)?e:[e],Sg=(e,t)=>{let n=[[],[]];for(let r of e)if(t(r))n[0].push(r);else n[1].push(r);return n},ka=Array,Kt=(e,t)=>e.includes(t),Rg=(e,t=0)=>[...Array(e)].map((n,r)=>r+t),de=(e,t,n)=>{if(e===void 0)return t===void 0?[]:Array.isArray(t)?t:[t];if(n?.prepend)if(Array.isArray(t))e.unshift(...t);else e.unshift(t);else if(Array.isArray(t))e.push(...t);else e.push(t);return e},Mn=(e,t)=>{if(t===void 0||t===null)return e??[];if(e===void 0||e===null)return rr(t);return e.concat(t)},$g=(...e)=>e.reduce(Mn,[]),bn=(e,t,n)=>{if(e===void 0)return Array.isArray(t)?t:[t];let r=n?.isEqual??((s,o)=>s===o);for(let s of rr(t))if(!e.some((o)=>r(o,s)))e.push(s);return e},kg=(e,t)=>e.reduce((n,r)=>{let s=r[t];return n[s]=de(n[s],r),n},{}),Tn=(e,t,n)=>e.length===t.length&&e.every(n?.isEqual?(r,s)=>n.isEqual(r,t[s]):(r,s)=>r===t[s]);var St=(e,t)=>Ke(e)===t,Ke=(e)=>{let t=typeof e;return t==="object"?e===null?"null":"object":t==="function"?"object":t},Rt={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},Eg={...Rt,function:"a function"};class Cg extends Error{}var he=(e)=>Pr(e,Cg),Pr=(e,t=Error)=>{throw new t(e)};class vs extends Error{name="ParseError"}var A=(e)=>Pr(e,vs),sn=(e)=>` ${e}`,Ag="\u200B";var ie=(e,t)=>{let n={},r=Array.isArray(e),s=!1;for(let[o,a]of Object.entries(e).entries()){let l=r?t(o,a[1]):t(...a,o);s||=typeof l[0]==="number";let c=Array.isArray(l[0])||l.length===0?l:[l];for(let[u,d]of c)if(typeof u==="object")n[u.group]=de(n[u.group],d);else n[u]=d}return s?Object.values(n):n};var ku=Object.entries;var Ge=(e,t)=>(e in t),_i=(e,t)=>(t in e);class Eu{constructor(e){Object.assign(this,e)}}var Og=class{};class xs extends Og{}var FE=(e,t)=>{let n={},r={},s;for(s in e)if(s in t)n[s]=e[s];else r[s]=e[s];return[n,r]};var Ea=(e,t)=>FE(e,t)[1],vn=(e)=>Object.keys(e).length===0,Mr=(e)=>[...Object.entries(e),...Object.getOwnPropertySymbols(e).map((t)=>[t,e[t]])],Ig=(e,t)=>Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)),Pg=(e)=>{let t=Object.keys(e).sort(),n={};for(let r=0;r<t.length;r++)n[t[r]]=e[t[r]];return n};var $t=sn(`unset${Ag}`),Mg=(e)=>Object.values(e).filter((t)=>{if(typeof t==="number")return!0;return typeof e[t]!=="number"});var Cu={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},Au=globalThis.File??Blob,Ou={ArrayBuffer,Blob,File:Au,FormData,Headers,Request,Response,URL},LE={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},Tr={...Cu,...Ou,...LE,String,Number,Boolean},Ss=(e)=>{let t=Object.getPrototypeOf(e);while(t?.constructor&&(!Ge(t.constructor.name,Tr)||!(e instanceof Tr[t.constructor.name])))t=Object.getPrototypeOf(t);let n=t?.constructor?.name;if(n===void 0||n==="Object")return;return n},Rs=(e)=>typeof e==="object"&&e!==null?Ss(e)??"object":Ke(e);var Se=Array.isArray,jE={Array:"an array",Function:"a function",Date:"a Date",RegExp:"a RegExp",Error:"an Error",Map:"a Map",Set:"a Set",String:"a String object",Number:"a Number object",Boolean:"a Boolean object",Promise:"a Promise",WeakMap:"a WeakMap",WeakSet:"a WeakSet"},UE={ArrayBuffer:"an ArrayBuffer instance",Blob:"a Blob instance",File:"a File instance",FormData:"a FormData instance",Headers:"a Headers instance",Request:"a Request instance",Response:"a Response instance",URL:"a URL instance"},BE={Int8Array:"an Int8Array",Uint8Array:"a Uint8Array",Uint8ClampedArray:"a Uint8ClampedArray",Int16Array:"an Int16Array",Uint16Array:"a Uint16Array",Int32Array:"an Int32Array",Uint32Array:"a Uint32Array",Float32Array:"a Float32Array",Float64Array:"a Float64Array",BigInt64Array:"a BigInt64Array",BigUint64Array:"a BigUint64Array"},Tg={...jE,...UE,...BE},$s=(e)=>{let t=Object(e).name??null;return t&&Ge(t,Tr)&&Tr[t]===e?t:null};var Iu=(e,t)=>{let n=e.prototype;while(n!==null){if(n===t.prototype)return!0;n=Object.getPrototypeOf(n)}return!1};var Dg=(e)=>Ng(e,new Map),Ng=(e,t)=>{if(typeof e!=="object"||e===null)return e;if(t?.has(e))return t.get(e);let n=$s(e.constructor);if(n==="Date")return new Date(e.getTime());if(n&&n!=="Array")return e;let r=Array.isArray(e)?e.slice():Object.create(Object.getPrototypeOf(e)),s=Object.getOwnPropertyDescriptors(e);if(t){t.set(e,r);for(let o in s){let a=s[o];if("get"in a||"set"in a)continue;a.value=Ng(a.value,t)}}return Object.defineProperties(r,s),r};var qE=(e)=>{let t=$t;return()=>t===$t?t=e():t},ir=(e)=>typeof e==="function"&&e.length===0;var Fg=class extends Function{constructor(...e){let t=e.slice(0,-1),n=e[e.length-1];try{super(...t,n)}catch(r){return he(`Encountered an unexpected error while compiling your definition:
573
573
  Message: ${r}
574
574
  Source: (${e.slice(0,-1)}) => {
575
575
  ${e[e.length-1]}
576
- }`)}}};class kt{constructor(e,...[t]){return Object.assign(Object.setPrototypeOf(e.bind(t?.bind??this),this.constructor.prototype),t?.attach)}}var pg=eE(()=>{try{return Function("return false")()}catch{return!0}});var wD=nn("brand");var hg=nn("arkInferred");var vD=nn("args");class at{constructor(){}}var tE=()=>{try{return((Error().stack?.split(`
577
- `)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},nE=globalThis.process?.env??{},mg={fileName:tE,env:nE};var gg=(e)=>e[0].toUpperCase()+e.slice(1),_g=(e)=>e[0].toLowerCase()+e.slice(1),yu=(e)=>new RegExp(rE(e),typeof e==="string"?"":e.flags);var rE=(e)=>`^(?:${typeof e==="string"?e:e.source})$`;var Mn={negativeLookahead:(e)=>`(?!${e})`,nonCapturingGroup:(e)=>`(?:${e})`},Ir="\\",nr={" ":1,"\n":1,"\t":1};var iE=/^-0\.?0*$/.source,yg=/[1-9]\d*/.source,sE=/\.\d+/.source,oE=/\.\d*[1-9]/.source,bg=(e)=>yu(Mn.negativeLookahead(iE)+Mn.nonCapturingGroup("-?"+Mn.nonCapturingGroup(Mn.nonCapturingGroup("0|"+yg)+Mn.nonCapturingGroup(e.decimalPattern)+"?")+(e.allowDecimalOnly?"|"+e.decimalPattern:"")+"?")),wg=bg({decimalPattern:oE,allowDecimalOnly:!1}),aE=wg.test.bind(wg),ba=bg({decimalPattern:sE,allowDecimalOnly:!0}),AD=ba.test.bind(ba),lE=/^-?\d*\.?\d*$/,cE=(e)=>e.length!==0&&lE.test(e),ws=yu(Mn.negativeLookahead("^-0$")+"-?"+Mn.nonCapturingGroup(Mn.nonCapturingGroup("0|"+yg))),uE=ws.test.bind(ws),bu=/^-?\d+$/,dE=bu.test.bind(bu),vg={number:"a number",bigint:"a bigint",integer:"an integer"},xg=(e,t)=>`'${e}' was parsed as ${vg[t]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,fE=(e,t)=>t==="number"?aE(e):uE(e),pE=(e,t)=>t==="number"?Number(e):Number.parseInt(e),hE=(e,t)=>t==="number"?cE(e):dE(e),Rg=(e,t)=>vu(e,"number",t),Sg=(e,t)=>vu(e,"number",{...t,strict:!0}),$g=(e,t)=>vu(e,"integer",t),vu=(e,t,n)=>{let r=pE(e,t);if(!Number.isNaN(r)){if(hE(e,t)){if(n?.strict)return fE(e,t)?r:C(xg(e,t));return r}}return n?.errorOnFail?C(n?.errorOnFail===!0?`Failed to parse ${vg[t]} from '${e}'`:n?.errorOnFail):void 0},kg=(e)=>{if(e[e.length-1]!=="n")return;let t=e.slice(0,-1),n;try{n=BigInt(t)}catch{return}if(ws.test(t))return n;if(bu.test(t))return C(xg(e,"bigint"))};var mE="0.56.0",gE={version:mE,filename:mg.fileName(),FileConstructor:gu},Pr=gE,Eg=new Map,xu=Object.create(null),ys=(e)=>{let t=Eg.get(e);if(t)return t;let n=_E(e);if(xu[n])n=`${n}${xu[n]++}`;else xu[n]=1;return Pr[n]=e,Eg.set(e,n),n},rr=(e)=>/^[$A-Z_a-z][\w$]*$/.test(e),_E=(e)=>{switch(typeof e){case"object":{if(e===null)break;let t=ms(e)??"object";return t[0].toLowerCase()+t.slice(1)}case"function":return rr(e.name)?e.name:"fn";case"symbol":return e.description&&rr(e.description)?e.description:"symbol"}return he(`Unexpected attempt to register serializable value of type ${Ke(e)}`)};var bs=(e)=>typeof e==="string"?JSON.stringify(e):typeof e==="bigint"?`${e}n`:`${e}`;var Ag=(e,t={})=>vs(e,{onUndefined:"$ark.undefined",onBigInt:(n)=>`$ark.bigint-${n}`,...t},[]);var se=(e,t)=>{switch(Ke(e)){case"object":let n=e,r=n.constructor?.name??"Object";return r==="Object"||r==="Array"?t?.quoteKeys===!1?va(n,t?.indent??0,""):JSON.stringify(vs(n,pi,[]),null,t?.indent):va(n,t?.indent??0,"");case"symbol":return pi.onSymbol(e);default:return bs(e)}},va=(e,t,n)=>{if(typeof e==="function")return pi.onFunction(e);if(typeof e!=="object"||e===null)return bs(e);let r=n+" ".repeat(t);if(Array.isArray(e)){if(e.length===0)return"[]";let o=e.map((a)=>va(a,t,r)).join(`,
576
+ }`)}}};class kt{constructor(e,...[t]){return Object.assign(Object.setPrototypeOf(e.bind(t?.bind??this),this.constructor.prototype),t?.attach)}}var Lg=qE(()=>{try{return Function("return false")()}catch{return!0}});var g1=sn("brand");var jg=sn("arkInferred");var y1=sn("args");class at{constructor(){}}var HE=()=>{try{return((Error().stack?.split(`
577
+ `)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},KE=globalThis.process?.env??{},Ug={fileName:HE,env:KE};var Bg=(e)=>e[0].toUpperCase()+e.slice(1),qg=(e)=>e[0].toLowerCase()+e.slice(1),Pu=(e)=>new RegExp(GE(e),typeof e==="string"?"":e.flags);var GE=(e)=>`^(?:${typeof e==="string"?e:e.source})$`;var Dn={negativeLookahead:(e)=>`(?!${e})`,nonCapturingGroup:(e)=>`(?:${e})`},Dr="\\",sr={" ":1,"\n":1,"\t":1};var WE=/^-0\.?0*$/.source,Kg=/[1-9]\d*/.source,VE=/\.\d+/.source,zE=/\.\d*[1-9]/.source,Gg=(e)=>Pu(Dn.negativeLookahead(WE)+Dn.nonCapturingGroup("-?"+Dn.nonCapturingGroup(Dn.nonCapturingGroup("0|"+Kg)+Dn.nonCapturingGroup(e.decimalPattern)+"?")+(e.allowDecimalOnly?"|"+e.decimalPattern:"")+"?")),Hg=Gg({decimalPattern:zE,allowDecimalOnly:!1}),JE=Hg.test.bind(Hg),Ca=Gg({decimalPattern:VE,allowDecimalOnly:!0}),k1=Ca.test.bind(Ca),XE=/^-?\d*\.?\d*$/,YE=(e)=>e.length!==0&&XE.test(e),ks=Pu(Dn.negativeLookahead("^-0$")+"-?"+Dn.nonCapturingGroup(Dn.nonCapturingGroup("0|"+Kg))),ZE=ks.test.bind(ks),Mu=/^-?\d+$/,QE=Mu.test.bind(Mu),Wg={number:"a number",bigint:"a bigint",integer:"an integer"},Vg=(e,t)=>`'${e}' was parsed as ${Wg[t]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,eC=(e,t)=>t==="number"?JE(e):ZE(e),tC=(e,t)=>t==="number"?Number(e):Number.parseInt(e),nC=(e,t)=>t==="number"?YE(e):QE(e),zg=(e,t)=>Tu(e,"number",t),Jg=(e,t)=>Tu(e,"number",{...t,strict:!0}),Xg=(e,t)=>Tu(e,"integer",t),Tu=(e,t,n)=>{let r=tC(e,t);if(!Number.isNaN(r)){if(nC(e,t)){if(n?.strict)return eC(e,t)?r:A(Vg(e,t));return r}}return n?.errorOnFail?A(n?.errorOnFail===!0?`Failed to parse ${Wg[t]} from '${e}'`:n?.errorOnFail):void 0},Yg=(e)=>{if(e[e.length-1]!=="n")return;let t=e.slice(0,-1),n;try{n=BigInt(t)}catch{return}if(ks.test(t))return n;if(Mu.test(t))return A(Vg(e,"bigint"))};var rC="0.56.0",iC={version:rC,filename:Ug.fileName(),FileConstructor:Au},Nr=iC,Zg=new Map,Du=Object.create(null),Es=(e)=>{let t=Zg.get(e);if(t)return t;let n=sC(e);if(Du[n])n=`${n}${Du[n]++}`;else Du[n]=1;return Nr[n]=e,Zg.set(e,n),n},or=(e)=>/^[$A-Z_a-z][\w$]*$/.test(e),sC=(e)=>{switch(typeof e){case"object":{if(e===null)break;let t=Ss(e)??"object";return t[0].toLowerCase()+t.slice(1)}case"function":return or(e.name)?e.name:"fn";case"symbol":return e.description&&or(e.description)?e.description:"symbol"}return he(`Unexpected attempt to register serializable value of type ${Ke(e)}`)};var Cs=(e)=>typeof e==="string"?JSON.stringify(e):typeof e==="bigint"?`${e}n`:`${e}`;var Qg=(e,t={})=>As(e,{onUndefined:"$ark.undefined",onBigInt:(n)=>`$ark.bigint-${n}`,...t},[]);var se=(e,t)=>{switch(Ke(e)){case"object":let n=e,r=n.constructor?.name??"Object";return r==="Object"||r==="Array"?t?.quoteKeys===!1?Aa(n,t?.indent??0,""):JSON.stringify(As(n,wi,[]),null,t?.indent):Aa(n,t?.indent??0,"");case"symbol":return wi.onSymbol(e);default:return Cs(e)}},Aa=(e,t,n)=>{if(typeof e==="function")return wi.onFunction(e);if(typeof e!=="object"||e===null)return Cs(e);let r=n+" ".repeat(t);if(Array.isArray(e)){if(e.length===0)return"[]";let o=e.map((a)=>Aa(a,t,r)).join(`,
578
578
  `+r);return t?`[
579
579
  ${r}${o}
580
- ${n}]`:`[${o}]`}let s=e.constructor?.name??"Object";if(s==="Object"){let o=Cr(e).map(([a,l])=>{let c=typeof a==="symbol"?pi.onSymbol(a):rr(a)?a:JSON.stringify(a),u=va(l,t,r);return`${r}${c}: ${u}`});if(o.length===0)return"{}";return t?`{
580
+ ${n}]`:`[${o}]`}let s=e.constructor?.name??"Object";if(s==="Object"){let o=Mr(e).map(([a,l])=>{let c=typeof a==="symbol"?wi.onSymbol(a):or(a)?a:JSON.stringify(a),u=Aa(l,t,r);return`${r}${c}: ${u}`});if(o.length===0)return"{}";return t?`{
581
581
  ${o.join(`,
582
582
  `)}
583
- ${n}}`:`{${o.join(", ")}}`}if(e instanceof Date)return Mr(e);if("expression"in e&&typeof e.expression==="string")return e.expression;return s},pi={onCycle:()=>"(cycle)",onSymbol:(e)=>`Symbol(${ys(e)})`,onFunction:(e)=>`Function(${ys(e)})`},vs=(e,t,n)=>{switch(Ke(e)){case"object":{let r=e;if("toJSON"in r&&typeof r.toJSON==="function")return r.toJSON();if(typeof r==="function")return pi.onFunction(r);if(n.includes(r))return"(cycle)";let s=[...n,r];if(Array.isArray(r))return r.map((a)=>vs(a,t,s));if(r instanceof Date)return r.toDateString();let o={};for(let a in r)o[a]=vs(r[a],t,s);for(let a of Object.getOwnPropertySymbols(r))o[t.onSymbol?.(a)??a.toString()]=vs(r[a],t,s);return o}case"symbol":return pi.onSymbol(e);case"bigint":return t.onBigInt?.(e)??`${e}n`;case"undefined":return t.onUndefined??"undefined";case"string":return e.replace(/\\/g,"\\\\");default:return e}},Mr=(e)=>{let t=e.getFullYear(),n=e.getMonth(),r=e.getDate(),s=e.getHours(),o=e.getMinutes(),a=e.getSeconds(),l=e.getMilliseconds();if(n===0&&r===1&&s===0&&o===0&&a===0&&l===0)return`${t}`;let c=`${wE[n]} ${r}, ${t}`;if(s===0&&o===0&&a===0&&l===0)return c;let u=e.toLocaleTimeString(),d=u.endsWith(" AM")||u.endsWith(" PM")?u.slice(-3):"";if(d)u=u.slice(0,-d.length);if(l)u+=`.${bE(l,3)}`;else if(yE.test(u))u=u.slice(0,-3);return`${u+d}, ${c}`},wE=["January","February","March","April","May","June","July","August","September","October","November","December"],yE=/:\d\d:00$/,bE=(e,t)=>String(e).padStart(t,"0");var Cg=(e,t,...[n])=>{let r=n?.stringifySymbol??se,s=e;switch(typeof t){case"string":s=rr(t)?e===""?t:`${e}.${t}`:`${e}[${JSON.stringify(t)}]`;break;case"number":s=`${e}[${t}]`;break;case"symbol":s=`${e}[${r(t)}]`;break;default:if(n?.stringifyNonKey)s=`${e}[${n.stringifyNonKey(t)}]`;else C(`${se(t)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return s},Tn=(e,...t)=>e.reduce((n,r)=>Cg(n,r,...t),"");class xs extends wa{cache={};constructor(...e){super();this.push(...e)}toJSON(){if(this.cache.json)return this.cache.json;this.cache.json=[];for(let e=0;e<this.length;e++)this.cache.json.push(typeof this[e]==="symbol"?se(this[e]):this[e]);return this.cache.json}stringify(){if(this.cache.stringify)return this.cache.stringify;return this.cache.stringify=Tn(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let e="",t=[e];for(let n of this)e=Cg(e,n),t.push(e);return this.cache.stringifyAncestors=t}}class Rs{chars;i;def;constructor(e){this.def=e,this.chars=[...e],this.i=0}shift(){return this.chars[this.i++]??""}get lookahead(){return this.chars[this.i]??""}get nextLookahead(){return this.chars[this.i+1]??""}get length(){return this.chars.length}shiftUntil(e){let t="";while(this.lookahead)if(e(this,t))break;else t+=this.shift();return t}shiftUntilEscapable(e){let t="";while(this.lookahead)if(this.lookahead===Ir)if(this.shift(),e(this,t))t+=this.shift();else if(this.lookahead===Ir)t+=this.shift();else t+=`${Ir}${this.shift()}`;else if(e(this,t))break;else t+=this.shift();return t}shiftUntilLookahead(e){return typeof e==="string"?this.shiftUntil((t)=>t.lookahead===e):this.shiftUntil((t)=>(t.lookahead in e))}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in nr))}jumpToIndex(e){this.i=e<0?this.length+e:e}jumpForward(e){this.i+=e}get location(){return this.i}get unscanned(){return this.chars.slice(this.i,this.length).join("")}get scanned(){return this.chars.slice(0,this.i).join("")}sliceChars(e,t){return this.chars.slice(e,t).join("")}lookaheadIs(e){return this.lookahead===e}lookaheadIsIn(e){return this.lookahead in e}}var Og=(e,t)=>`Unmatched ${e}${t===""?"":` before ${t}`}`,xa=(e)=>`Missing ${e}`;var QD=nn("implementedTraits");var Ru="$ark",vE=2;while(Ru in globalThis)Ru=`$ark${vE++}`;var Ig=Ru;globalThis[Ig]=Pr;var N=Pr,xE=(e)=>`${Ig}.${e}`,Me=(e)=>xE(ys(e));class Ra extends hs{argNames;body="";constructor(...e){super();this.argNames=e;for(let t of e){if(t in this)throw Error(`Arg name '${t}' would overwrite an existing property on FunctionBody`);this[t]=t}}indentation=0;indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop(e,t=!1){return Su(e,t)}index(e,t=!1){return Pg(`${e}`,t)}line(e){return this.body+=`${" ".repeat(this.indentation)}${e}
583
+ ${n}}`:`{${o.join(", ")}}`}if(e instanceof Date)return Fr(e);if("expression"in e&&typeof e.expression==="string")return e.expression;return s},wi={onCycle:()=>"(cycle)",onSymbol:(e)=>`Symbol(${Es(e)})`,onFunction:(e)=>`Function(${Es(e)})`},As=(e,t,n)=>{switch(Ke(e)){case"object":{let r=e;if("toJSON"in r&&typeof r.toJSON==="function")return r.toJSON();if(typeof r==="function")return wi.onFunction(r);if(n.includes(r))return"(cycle)";let s=[...n,r];if(Array.isArray(r))return r.map((a)=>As(a,t,s));if(r instanceof Date)return r.toDateString();let o={};for(let a in r)o[a]=As(r[a],t,s);for(let a of Object.getOwnPropertySymbols(r))o[t.onSymbol?.(a)??a.toString()]=As(r[a],t,s);return o}case"symbol":return wi.onSymbol(e);case"bigint":return t.onBigInt?.(e)??`${e}n`;case"undefined":return t.onUndefined??"undefined";case"string":return e.replace(/\\/g,"\\\\");default:return e}},Fr=(e)=>{let t=e.getFullYear(),n=e.getMonth(),r=e.getDate(),s=e.getHours(),o=e.getMinutes(),a=e.getSeconds(),l=e.getMilliseconds();if(n===0&&r===1&&s===0&&o===0&&a===0&&l===0)return`${t}`;let c=`${oC[n]} ${r}, ${t}`;if(s===0&&o===0&&a===0&&l===0)return c;let u=e.toLocaleTimeString(),d=u.endsWith(" AM")||u.endsWith(" PM")?u.slice(-3):"";if(d)u=u.slice(0,-d.length);if(l)u+=`.${lC(l,3)}`;else if(aC.test(u))u=u.slice(0,-3);return`${u+d}, ${c}`},oC=["January","February","March","April","May","June","July","August","September","October","November","December"],aC=/:\d\d:00$/,lC=(e,t)=>String(e).padStart(t,"0");var e_=(e,t,...[n])=>{let r=n?.stringifySymbol??se,s=e;switch(typeof t){case"string":s=or(t)?e===""?t:`${e}.${t}`:`${e}[${JSON.stringify(t)}]`;break;case"number":s=`${e}[${t}]`;break;case"symbol":s=`${e}[${r(t)}]`;break;default:if(n?.stringifyNonKey)s=`${e}[${n.stringifyNonKey(t)}]`;else A(`${se(t)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return s},Nn=(e,...t)=>e.reduce((n,r)=>e_(n,r,...t),"");class Os extends ka{cache={};constructor(...e){super();this.push(...e)}toJSON(){if(this.cache.json)return this.cache.json;this.cache.json=[];for(let e=0;e<this.length;e++)this.cache.json.push(typeof this[e]==="symbol"?se(this[e]):this[e]);return this.cache.json}stringify(){if(this.cache.stringify)return this.cache.stringify;return this.cache.stringify=Nn(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let e="",t=[e];for(let n of this)e=e_(e,n),t.push(e);return this.cache.stringifyAncestors=t}}class Is{chars;i;def;constructor(e){this.def=e,this.chars=[...e],this.i=0}shift(){return this.chars[this.i++]??""}get lookahead(){return this.chars[this.i]??""}get nextLookahead(){return this.chars[this.i+1]??""}get length(){return this.chars.length}shiftUntil(e){let t="";while(this.lookahead)if(e(this,t))break;else t+=this.shift();return t}shiftUntilEscapable(e){let t="";while(this.lookahead)if(this.lookahead===Dr)if(this.shift(),e(this,t))t+=this.shift();else if(this.lookahead===Dr)t+=this.shift();else t+=`${Dr}${this.shift()}`;else if(e(this,t))break;else t+=this.shift();return t}shiftUntilLookahead(e){return typeof e==="string"?this.shiftUntil((t)=>t.lookahead===e):this.shiftUntil((t)=>(t.lookahead in e))}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in sr))}jumpToIndex(e){this.i=e<0?this.length+e:e}jumpForward(e){this.i+=e}get location(){return this.i}get unscanned(){return this.chars.slice(this.i,this.length).join("")}get scanned(){return this.chars.slice(0,this.i).join("")}sliceChars(e,t){return this.chars.slice(e,t).join("")}lookaheadIs(e){return this.lookahead===e}lookaheadIsIn(e){return this.lookahead in e}}var t_=(e,t)=>`Unmatched ${e}${t===""?"":` before ${t}`}`,Oa=(e)=>`Missing ${e}`;var Y1=sn("implementedTraits");var Nu="$ark",cC=2;while(Nu in globalThis)Nu=`$ark${cC++}`;var n_=Nu;globalThis[n_]=Nr;var N=Nr,uC=(e)=>`${n_}.${e}`,Me=(e)=>uC(Es(e));class Ia extends xs{argNames;body="";constructor(...e){super();this.argNames=e;for(let t of e){if(t in this)throw Error(`Arg name '${t}' would overwrite an existing property on FunctionBody`);this[t]=t}}indentation=0;indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop(e,t=!1){return Fu(e,t)}index(e,t=!1){return r_(`${e}`,t)}line(e){return this.body+=`${" ".repeat(this.indentation)}${e}
584
584
  `,this}const(e,t){return this.line(`const ${e} = ${t}`),this}let(e,t){return this.line(`let ${e} = ${t}`)}set(e,t){return this.line(`${e} = ${t}`)}if(e,t){return this.block(`if (${e})`,t)}elseIf(e,t){return this.block(`else if (${e})`,t)}else(e){return this.block("else",e)}for(e,t,n=0){return this.block(`for (let i = ${n}; ${e}; i++)`,t)}forIn(e,t){return this.block(`for (const k in ${e})`,t)}block(e,t,n=""){return this.line(`${e} {`),this.indent(),t(this),this.dedent(),this.line(`}${n}`)}return(e=""){return this.line(`return ${e}`)}write(e="anonymous",t=0){return`${e}(${this.argNames.join(", ")}) { ${t?this.body.split(`
585
585
  `).map((n)=>" ".repeat(t)+`${n}`).join(`
586
- `):this.body} }`}compile(){return new fg(...this.argNames,this.body)}}var rn=(e)=>Rt(e,"object")||typeof e==="symbol"?Me(e):bs(e),Su=(e,t=!1)=>{if(typeof e==="string"&&rr(e))return`${t?"?":""}.${e}`;return Pg(RE(e),t)},RE=(e)=>typeof e==="symbol"?Me(e):JSON.stringify(e),Pg=(e,t=!1)=>`${t?"?.":""}[${e}]`;class Ss extends Ra{traversalKind;optimistic;constructor(e){super("data","ctx");this.traversalKind=e.kind,this.optimistic=e.optimistic===!0}invoke(e,t){let n=t?.arg??this.data,r=typeof e==="string"?!0:this.requiresContextFor(e),s=typeof e==="string"?e:e.id;if(r)return`${this.referenceToId(s,t)}(${n}, ${this.ctx})`;return`${this.referenceToId(s,t)}(${n})`}referenceToId(e,t){let n=t?.kind??this.traversalKind,r=`this.${e}${n}`;return t?.bind?`${r}.bind(${t?.bind})`:r}requiresContextFor(e){return this.traversalKind==="Apply"||e.allowsRequiresContext}initializeErrorCount(){return this.const("errorCount","ctx.currentErrorCount")}returnIfFail(){return this.if("ctx.currentErrorCount > errorCount",()=>this.return())}returnIfFailFast(){return this.if("ctx.failFast && ctx.currentErrorCount > errorCount",()=>this.return())}traverseKey(e,t,n){let r=this.requiresContextFor(n);if(r)this.line(`${this.ctx}.path.push(${e})`);if(this.check(n,{arg:t}),r)this.line(`${this.ctx}.path.pop()`);return this}check(e,t){return this.traversalKind==="Allows"?this.if(`!${this.invoke(e,t)}`,()=>this.return(!1)):this.line(this.invoke(e,t))}}var Sa=(e)=>ie(e,(t,n)=>[t,Re(n)?[...n]:n]),ht=nn("arkKind"),X=(e,t)=>e?.[ht]===t,$e=(e)=>X(e,"root")||X(e,"constraint");var Mg=["unit","proto","domain"],hi=["required","optional","index","sequence"],$u=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],ku=[...$u,"structure","predicate"],$a=[...ku,...hi],mi=["alias","union","morph","unit","intersection","proto","domain"],SE=[...mi,...$a],ka=ie($a,(e,t)=>[t,1]),Tg=ie([...hi,"undeclared"],(e,t)=>[t,1]),Fg=ie(SE,(e,t)=>[t,e]),gi=(e)=>typeof e==="string"&&(e in Fg);var _i=(e)=>Fg[e],Ea=(e)=>mi.slice(_i(e)+1),N1=[...Ea("union"),"alias"],D1=[...Ea("morph"),"alias"],Kt=(e)=>{if(typeof e==="string"||typeof e==="boolean"||e===null)return e;if(typeof e==="number"){if(Number.isNaN(e))return"NaN";if(e===Number.POSITIVE_INFINITY)return"Infinity";if(e===Number.NEGATIVE_INFINITY)return"-Infinity";return e}return rn(e)},ir=(e)=>{let t="{ ";for(let[n,r]of Object.entries(e))t+=`${n}: ${rn(r)}, `;return t+" }"},ae=(e)=>{let t=e;if(t.hasAssociatedError)t.defaults.expected??=(n)=>("description"in n)?n.description:t.defaults.description(n),t.defaults.actual??=(n)=>se(n),t.defaults.problem??=(n)=>`must be ${n.expected}${n.actual?` (was ${n.actual})`:""}`,t.defaults.message??=(n)=>{if(n.path.length===0)return n.problem;let r=`${n.propString} ${n.problem}`;if(r[0]==="[")return`value at ${r}`;return r};return t};class Ng extends Error{name="ToJsonSchemaError";code;context;constructor(e,t){super(se(t,{quoteKeys:!1,indent:4}));this.code=e,this.context=t}hasCode(e){return this.code===e}}var $E={target:"draft-2020-12",dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:(e)=>Ee.throw("arrayObject",e),arrayPostfix:(e)=>Ee.throw("arrayPostfix",e),defaultValue:(e)=>Ee.throw("defaultValue",e),domain:(e)=>Ee.throw("domain",e),morph:(e)=>Ee.throw("morph",e),patternIntersection:(e)=>Ee.throw("patternIntersection",e),predicate:(e)=>Ee.throw("predicate",e),proto:(e)=>Ee.throw("proto",e),symbolKey:(e)=>Ee.throw("symbolKey",e),unit:(e)=>Ee.throw("unit",e),date:(e)=>Ee.throw("date",e)}},Ee={Error:Ng,throw:(...e)=>{throw new Ee.Error(...e)},throwInternalOperandError:(e,t)=>he(`Unexpected JSON Schema input for ${e}: ${se(t)}`),defaultConfig:$E};N.config??={};var $s=(e,t)=>{if(!t)return e;let n={...e},r;for(r in t){let s={...e.keywords};if(r==="keywords"){for(let o in t[r]){let a=t.keywords[o];if(a===void 0)continue;s[o]=typeof a==="string"?{description:a}:a}n.keywords=s}else if(r==="toJsonSchema")n[r]=Eu(e.toJsonSchema,t.toJsonSchema);else if(gi(r))n[r]={...e[r],...t[r]};else n[r]=t[r]}return n},kE={"draft-2020-12":"https://json-schema.org/draft/2020-12/schema","draft-07":"http://json-schema.org/draft-07/schema#"},Eu=(e,t)=>{if(!e)return Dg(t??{},void 0);if(!t)return e;let n={...e},r;for(r in t)if(r==="fallback")n.fallback=EE(e.fallback,t.fallback);else n[r]=t[r];return Dg(n,t)},Dg=(e,t)=>{if(t?.dialect!==void 0)return e;if(t?.target!==void 0)return{...e,dialect:kE[t.target]};return e},EE=(e,t)=>{e=Lg(e),t=Lg(t);let n={},r;for(r in Ee.defaultConfig.fallback)n[r]=t[r]??t.default??e[r]??e.default??Ee.defaultConfig.fallback[r];return n},Lg=(e)=>typeof e==="function"?{default:e}:e??{};class sr extends hs{[ht]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:e,relativePath:t,...n},r){super();this.input=n,this.ctx=r,og(this,n);let s=r.data;if(n.code==="union")n.errors=n.errors.flatMap((a)=>{let l=a.hasCode("union")?a.errors:[a];if(!e&&!t)return l;return l.map((c)=>c.transform((u)=>({...u,path:eg(e,u.path,t)})))});this.nodeConfig=r.config[this.code];let o=[...n.path??r.path];if(t)o.push(...t);if(e)o.unshift(...e);this.path=new xs(...o),this.data="data"in n?n.data:s}transform(e){return new sr(e({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(e){return this.code===e}get propString(){return Tn(this.path)}get expected(){if(this.input.expected)return this.input.expected;let e=this.meta?.expected??this.nodeConfig.expected;return typeof e==="function"?e(this.input):e}get actual(){if(this.input.actual)return this.input.actual;let e=this.meta?.actual??this.nodeConfig.actual;return typeof e==="function"?e(this.data):e}get problem(){if(this.input.problem)return this.input.problem;let e=this.meta?.problem??this.nodeConfig.problem;return typeof e==="function"?e(this):e}get message(){if(this.input.message)return this.input.message;let e=this.meta?.message??this.nodeConfig.message;return typeof e==="function"?e(this):e}get flat(){return this.hasCode("intersection")?[...this.errors]:[this]}toJSON(){return{data:this.data,path:this.path,...this.input,expected:this.expected,actual:this.actual,problem:this.problem,message:this.message}}toString(){return this.message}throw(){throw this}}class Et extends wa{[ht]="errors";ctx;constructor(e){super();this.ctx=e}byPath=Object.create(null);get flatByPath(){return ie(this.byPath,(e,t)=>[e,t.flat])}get flatProblemsByPath(){return ie(this.byPath,(e,t)=>[e,t.flat.map((n)=>n.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new Au(this)}add(e){let t=this.byPath[e.propString];if(t){if(e===t)return;if(t.hasCode("union")&&t.errors.length===0)return;let n=e.hasCode("union")&&e.errors.length===0?e:new sr({code:"intersection",errors:t.hasCode("intersection")?[...t.errors,e]:[t,e]},this.ctx),r=this.indexOf(t);this.mutable[r===-1?this.length:r]=n,this.byPath[e.propString]=n,this.addAncestorPaths(e)}else this.byPath[e.propString]=e,this.addAncestorPaths(e),this.mutable.push(e);this.count++}transform(e){let t=new Et(this.ctx);for(let n of this)t.add(e(n));return t}merge(e){for(let t of e)this.add(new sr({...t,path:[...this.ctx.path,...t.path]},this.ctx))}affectsPath(e){if(this.length===0)return!1;return e.stringifyAncestors().some((t)=>(t in this.byPath))||e.stringify()in this.byAncestorPath}get summary(){return this.toString()}get issues(){return this}toJSON(){return[...this.map((e)=>e.toJSON())]}toString(){return this.join(`
587
- `)}addAncestorPaths(e){for(let t of e.path.stringifyAncestors())this.byAncestorPath[t]=de(this.byAncestorPath[t],e)}}class Au extends Error{name="TraversalError";constructor(e){if(e.length===1)super(e.summary);else super(`
588
- `+e.map((t)=>` \u2022 ${AE(t)}`).join(`
589
- `));Object.defineProperty(this,"arkErrors",{value:e,enumerable:!1})}}var AE=(e)=>e.toString().split(`
586
+ `):this.body} }`}compile(){return new Fg(...this.argNames,this.body)}}var on=(e)=>St(e,"object")||typeof e==="symbol"?Me(e):Cs(e),Fu=(e,t=!1)=>{if(typeof e==="string"&&or(e))return`${t?"?":""}.${e}`;return r_(dC(e),t)},dC=(e)=>typeof e==="symbol"?Me(e):JSON.stringify(e),r_=(e,t=!1)=>`${t?"?.":""}[${e}]`;class Ps extends Ia{traversalKind;optimistic;constructor(e){super("data","ctx");this.traversalKind=e.kind,this.optimistic=e.optimistic===!0}invoke(e,t){let n=t?.arg??this.data,r=typeof e==="string"?!0:this.requiresContextFor(e),s=typeof e==="string"?e:e.id;if(r)return`${this.referenceToId(s,t)}(${n}, ${this.ctx})`;return`${this.referenceToId(s,t)}(${n})`}referenceToId(e,t){let n=t?.kind??this.traversalKind,r=`this.${e}${n}`;return t?.bind?`${r}.bind(${t?.bind})`:r}requiresContextFor(e){return this.traversalKind==="Apply"||e.allowsRequiresContext}initializeErrorCount(){return this.const("errorCount","ctx.currentErrorCount")}returnIfFail(){return this.if("ctx.currentErrorCount > errorCount",()=>this.return())}returnIfFailFast(){return this.if("ctx.failFast && ctx.currentErrorCount > errorCount",()=>this.return())}traverseKey(e,t,n){let r=this.requiresContextFor(n);if(r)this.line(`${this.ctx}.path.push(${e})`);if(this.check(n,{arg:t}),r)this.line(`${this.ctx}.path.pop()`);return this}check(e,t){return this.traversalKind==="Allows"?this.if(`!${this.invoke(e,t)}`,()=>this.return(!1)):this.line(this.invoke(e,t))}}var Pa=(e)=>ie(e,(t,n)=>[t,Se(n)?[...n]:n]),ht=sn("arkKind"),X=(e,t)=>e?.[ht]===t,$e=(e)=>X(e,"root")||X(e,"constraint");var i_=["unit","proto","domain"],yi=["required","optional","index","sequence"],Lu=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],ju=[...Lu,"structure","predicate"],Ma=[...ju,...yi],bi=["alias","union","morph","unit","intersection","proto","domain"],fC=[...bi,...Ma],Ta=ie(Ma,(e,t)=>[t,1]),s_=ie([...yi,"undeclared"],(e,t)=>[t,1]),o_=ie(fC,(e,t)=>[t,e]),vi=(e)=>typeof e==="string"&&(e in o_);var xi=(e)=>o_[e],Da=(e)=>bi.slice(xi(e)+1),TL=[...Da("union"),"alias"],DL=[...Da("morph"),"alias"],Gt=(e)=>{if(typeof e==="string"||typeof e==="boolean"||e===null)return e;if(typeof e==="number"){if(Number.isNaN(e))return"NaN";if(e===Number.POSITIVE_INFINITY)return"Infinity";if(e===Number.NEGATIVE_INFINITY)return"-Infinity";return e}return on(e)},ar=(e)=>{let t="{ ";for(let[n,r]of Object.entries(e))t+=`${n}: ${on(r)}, `;return t+" }"},ae=(e)=>{let t=e;if(t.hasAssociatedError)t.defaults.expected??=(n)=>("description"in n)?n.description:t.defaults.description(n),t.defaults.actual??=(n)=>se(n),t.defaults.problem??=(n)=>`must be ${n.expected}${n.actual?` (was ${n.actual})`:""}`,t.defaults.message??=(n)=>{if(n.path.length===0)return n.problem;let r=`${n.propString} ${n.problem}`;if(r[0]==="[")return`value at ${r}`;return r};return t};class a_ extends Error{name="ToJsonSchemaError";code;context;constructor(e,t){super(se(t,{quoteKeys:!1,indent:4}));this.code=e,this.context=t}hasCode(e){return this.code===e}}var pC={target:"draft-2020-12",dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:(e)=>Ee.throw("arrayObject",e),arrayPostfix:(e)=>Ee.throw("arrayPostfix",e),defaultValue:(e)=>Ee.throw("defaultValue",e),domain:(e)=>Ee.throw("domain",e),morph:(e)=>Ee.throw("morph",e),patternIntersection:(e)=>Ee.throw("patternIntersection",e),predicate:(e)=>Ee.throw("predicate",e),proto:(e)=>Ee.throw("proto",e),symbolKey:(e)=>Ee.throw("symbolKey",e),unit:(e)=>Ee.throw("unit",e),date:(e)=>Ee.throw("date",e)}},Ee={Error:a_,throw:(...e)=>{throw new Ee.Error(...e)},throwInternalOperandError:(e,t)=>he(`Unexpected JSON Schema input for ${e}: ${se(t)}`),defaultConfig:pC};N.config??={};var Ms=(e,t)=>{if(!t)return e;let n={...e},r;for(r in t){let s={...e.keywords};if(r==="keywords"){for(let o in t[r]){let a=t.keywords[o];if(a===void 0)continue;s[o]=typeof a==="string"?{description:a}:a}n.keywords=s}else if(r==="toJsonSchema")n[r]=Uu(e.toJsonSchema,t.toJsonSchema);else if(vi(r))n[r]={...e[r],...t[r]};else n[r]=t[r]}return n},hC={"draft-2020-12":"https://json-schema.org/draft/2020-12/schema","draft-07":"http://json-schema.org/draft-07/schema#"},Uu=(e,t)=>{if(!e)return l_(t??{},void 0);if(!t)return e;let n={...e},r;for(r in t)if(r==="fallback")n.fallback=mC(e.fallback,t.fallback);else n[r]=t[r];return l_(n,t)},l_=(e,t)=>{if(t?.dialect!==void 0)return e;if(t?.target!==void 0)return{...e,dialect:hC[t.target]};return e},mC=(e,t)=>{e=c_(e),t=c_(t);let n={},r;for(r in Ee.defaultConfig.fallback)n[r]=t[r]??t.default??e[r]??e.default??Ee.defaultConfig.fallback[r];return n},c_=(e)=>typeof e==="function"?{default:e}:e??{};class lr extends xs{[ht]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:e,relativePath:t,...n},r){super();this.input=n,this.ctx=r,Ig(this,n);let s=r.data;if(n.code==="union")n.errors=n.errors.flatMap((a)=>{let l=a.hasCode("union")?a.errors:[a];if(!e&&!t)return l;return l.map((c)=>c.transform((u)=>({...u,path:$g(e,u.path,t)})))});this.nodeConfig=r.config[this.code];let o=[...n.path??r.path];if(t)o.push(...t);if(e)o.unshift(...e);this.path=new Os(...o),this.data="data"in n?n.data:s}transform(e){return new lr(e({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(e){return this.code===e}get propString(){return Nn(this.path)}get expected(){if(this.input.expected)return this.input.expected;let e=this.meta?.expected??this.nodeConfig.expected;return typeof e==="function"?e(this.input):e}get actual(){if(this.input.actual)return this.input.actual;let e=this.meta?.actual??this.nodeConfig.actual;return typeof e==="function"?e(this.data):e}get problem(){if(this.input.problem)return this.input.problem;let e=this.meta?.problem??this.nodeConfig.problem;return typeof e==="function"?e(this):e}get message(){if(this.input.message)return this.input.message;let e=this.meta?.message??this.nodeConfig.message;return typeof e==="function"?e(this):e}get flat(){return this.hasCode("intersection")?[...this.errors]:[this]}toJSON(){return{data:this.data,path:this.path,...this.input,expected:this.expected,actual:this.actual,problem:this.problem,message:this.message}}toString(){return this.message}throw(){throw this}}class Et extends ka{[ht]="errors";ctx;constructor(e){super();this.ctx=e}byPath=Object.create(null);get flatByPath(){return ie(this.byPath,(e,t)=>[e,t.flat])}get flatProblemsByPath(){return ie(this.byPath,(e,t)=>[e,t.flat.map((n)=>n.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new Bu(this)}add(e){let t=this.byPath[e.propString];if(t){if(e===t)return;if(t.hasCode("union")&&t.errors.length===0)return;let n=e.hasCode("union")&&e.errors.length===0?e:new lr({code:"intersection",errors:t.hasCode("intersection")?[...t.errors,e]:[t,e]},this.ctx),r=this.indexOf(t);this.mutable[r===-1?this.length:r]=n,this.byPath[e.propString]=n,this.addAncestorPaths(e)}else this.byPath[e.propString]=e,this.addAncestorPaths(e),this.mutable.push(e);this.count++}transform(e){let t=new Et(this.ctx);for(let n of this)t.add(e(n));return t}merge(e){for(let t of e)this.add(new lr({...t,path:[...this.ctx.path,...t.path]},this.ctx))}affectsPath(e){if(this.length===0)return!1;return e.stringifyAncestors().some((t)=>(t in this.byPath))||e.stringify()in this.byAncestorPath}get summary(){return this.toString()}get issues(){return this}toJSON(){return[...this.map((e)=>e.toJSON())]}toString(){return this.join(`
587
+ `)}addAncestorPaths(e){for(let t of e.path.stringifyAncestors())this.byAncestorPath[t]=de(this.byAncestorPath[t],e)}}class Bu extends Error{name="TraversalError";constructor(e){if(e.length===1)super(e.summary);else super(`
588
+ `+e.map((t)=>` \u2022 ${gC(t)}`).join(`
589
+ `));Object.defineProperty(this,"arkErrors",{value:e,enumerable:!1})}}var gC=(e)=>e.toString().split(`
590
590
  `).join(`
591
- `);class sn{path=[];errors=new Et(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(e,t){this.root=e,this.config=t}get data(){let e=this.root;for(let t of this.path)e=e?.[t];return e}get propString(){return Tn(this.path)}reject(e){return this.error(e),!1}mustBe(e){return this.error(e),!1}error(e){let t=typeof e==="object"?e.code?e:{...e,code:"predicate"}:{code:"predicate",expected:e};return this.errorFromContext(t)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches[this.branches.length-1]}queueMorphs(e){let t={path:new xs(...this.path),morphs:e};if(this.currentBranch)this.currentBranch.queuedMorphs.push(t);else this.queuedMorphs.push(t)}finalize(e){if(this.queuedMorphs.length){if(typeof this.root==="object"&&this.root!==null&&this.config.clone)this.root=this.config.clone(this.root);this.applyQueuedMorphs()}if(this.hasError())return e?e(this.errors):this.errors;return this.root}get currentErrorCount(){return this.currentBranch?this.currentBranch.error?1:0:this.errors.count}get failFast(){return this.branches.length!==0}pushBranch(){this.branches.push({error:void 0,queuedMorphs:[]})}popBranch(){return this.branches.pop()}get external(){return this}errorFromNodeContext(e){return this.errorFromContext(e)}errorFromContext(e){let t=new sr(e,this);if(this.currentBranch)this.currentBranch.error=t;else this.errors.add(t);return t}applyQueuedMorphs(){while(this.queuedMorphs.length){let e=this.queuedMorphs;this.queuedMorphs=[];for(let{path:t,morphs:n}of e){if(this.errors.affectsPath(t))continue;this.applyMorphsAtPath(t,n)}}}applyMorphsAtPath(e,t){let n=e[e.length-1],r;if(n!==void 0){r=this.root;for(let s=0;s<e.length-1;s++)r=r[e[s]]}for(let s of t){this.path=[...e];let o=$e(s),a=s(r===void 0?this.root:r[n],this);if(a instanceof sr){if(!this.errors.includes(a))this.errors.add(a);break}if(a instanceof Et){if(!o)this.errors.merge(a);this.queuedMorphs=[];break}if(r===void 0)this.root=a;else r[n]=a;this.applyQueuedMorphs()}}}var At=(e,t,n)=>{if(!n)return t();n.path.push(e);let r=t();return n.path.pop(),r};class Es extends kt{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(e,t){super((r,s,o=this.onFail)=>{if(s)return this.traverseApply(r,s),s.hasError()?s.errors:s.data;return this.rootApply(r,o)},{attach:e});this.attachments=e,this.$=t,this.onFail=this.meta.onFail??this.$.resolvedConfig.onFail,this.includesTransform=this.hasKind("morph")||this.hasKind("structure")&&this.structuralMorph!==void 0||this.hasKind("sequence")&&this.inner.defaultables!==void 0,this.includesContextualPredicate=this.hasKind("predicate")&&this.inner.predicate.length!==1,this.isCyclic=this.kind==="alias",this.referencesById={[this.id]:this},this.shallowReferences=this.hasKind("structure")?[this,...this.children]:this.children.reduce((r,s)=>PE(r,s.shallowReferences),[this]);let n=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let r=0;r<this.children.length;r++){if(this.includesTransform||=this.children[r].includesTransform,this.includesContextualPredicate||=this.children[r].includesContextualPredicate,this.isCyclic||=this.children[r].isCyclic,!n){let s=this.children[r].flatRefs;for(let o=0;o<s.length;o++){let a=s[o];if(!this.flatRefs.some((l)=>Ug(l,a))){this.flatRefs.push(a);for(let l of a.node.branches)if(l.hasKind("morph")||l.hasKind("intersection")&&l.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:a.path,propString:a.propString,node:l})}}}Object.assign(this.referencesById,this.children[r].referencesById)}this.flatRefs.sort((r,s)=>r.path.length>s.path.length?1:r.path.length<s.path.length?-1:r.propString>s.propString?1:r.propString<s.propString?-1:r.node.expression<s.node.expression?-1:1),this.allowsRequiresContext=this.includesContextualPredicate||this.isCyclic,this.rootApplyStrategy=!this.allowsRequiresContext&&this.flatMorphs.length===0?this.shallowMorphs.length===0?"allows":this.shallowMorphs.every((r)=>r.length===1||r.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((r)=>r.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(r)=>this.traverseAllows(r,new sn(r,this.$.resolvedConfig)):(r)=>this.traverseAllows(r)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(t,n)=>{if(this.allows(t))return t;let r=new sn(t,this.$.resolvedConfig);return this.traverseApply(t,r),r.finalize(n)};case"contextual":return(t,n)=>{let r=new sn(t,this.$.resolvedConfig);return this.traverseApply(t,r),r.finalize(n)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let e=this.$.resolvedConfig.clone;return(t,n)=>{if(this.allows(t))return this.contextFreeMorph(e&&(typeof t==="object"&&t!==null||typeof t==="function")?e(t):t);let r=new sn(t,this.$.resolvedConfig);return this.traverseApply(t,r),r.finalize(n)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,he(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=IE(this.metaJson);cacheGetter(e,t){return Object.defineProperty(this,e,{value:t}),t}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=_i(this.kind);precompilation;assert=(e,t)=>this(e,t,(n)=>n.throw());traverse(e,t){return this(e,t,null)}get in(){return this.cacheGetter("in",this.rawIn.isRoot()?this.$.finalize(this.rawIn):this.rawIn)}get rawIn(){return this.cacheGetter("rawIn",this.getIo("in"))}get out(){return this.cacheGetter("out",this.rawOut.isRoot()?this.$.finalize(this.rawOut):this.rawOut)}get rawOut(){return this.cacheGetter("rawOut",this.getIo("out"))}getIo(e){if(!this.includesTransform)return this;let t={};for(let[n,r]of this.innerEntries){let s=this.impl.keys[n];if(s.reduceIo)s.reduceIo(e,t,r);else if(s.child){let o=r;t[n]=Re(o)?o.map((a)=>e==="in"?a.rawIn:a.rawOut):e==="in"?o.rawIn:o.rawOut}else t[n]=r}return this.$.node(this.kind,t)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(e){let t=$e(e)?e:this.$.parseDefinition(e);return this.innerHash===t.innerHash}ifEquals(e){return this.equals(e)?this:void 0}hasKind(e){return this.kind===e}assertHasKind(e){if(this.kind!==e)Ar(`${this.kind} node was not of asserted kind ${e}`);return this}hasKindIn(...e){return e.includes(this.kind)}assertHasKindIn(...e){if(!Ht(e,this.kind))Ar(`${this.kind} node was not one of asserted kinds ${e}`);return this}isBasis(){return Ht(Mg,this.kind)}isConstraint(){return Ht($a,this.kind)}isStructural(){return Ht(hi,this.kind)}isRefinement(){return Ht(ku,this.kind)}isRoot(){return Ht(mi,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(e){return this.hasKind("unit")&&this.allows(e)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(e){let t=ks.normalize(e);return this._select(t)}_select(e){let t=ks.applyBoundary[e.boundary??"references"](this);if(e.kind)t=t.filter((n)=>n.kind===e.kind);if(e.where)t=t.filter(e.where);return ks.applyMethod[e.method??"filter"](t,this,e)}transform(e,t){return this._transform(e,this._createTransformContext(t))}_createTransformContext(e){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:e?.prereduced??!1},undeclaredKeyHandling:void 0,...e}}_transform(e,t){let n=t.bindScope??this.$;if(t.seen[this.id])return this.$.lazilyResolve(t.seen[this.id]);if(t.shouldTransform?.(this,t)===!1)return this;let r;if(t.seen[this.id]=()=>r,this.hasKind("structure")&&this.undeclared!==t.undeclaredKeyHandling)t={...t,undeclaredKeyHandling:this.undeclared};let s=ie(this.inner,(u,d)=>{if(!this.impl.keys[u].child)return[u,d];let f=d;if(!Re(f)){let h=f._transform(e,t);return h?[u,h]:[]}if(f.length===0)return[u,d];let p=f.flatMap((h)=>h._transform(e,t)??[]);return p.length?[u,p]:[]});delete t.seen[this.id];let o=Object.assign(s,{meta:this.meta}),a=t.selected&&!t.selected.includes(this)?o:e(this.kind,o,t);if(a===null)return null;if($e(a))return r=a;let l=Object.keys(a);if((l.length===0||l.length===1&&l[0]==="meta")&&!yn(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in a))return t.undeclaredKeyHandling?{...a,value:N.intrinsic.unknown}:null;if(this.kind==="morph")a.in??=N.intrinsic.unknown;return r=n.node(this.kind,a,t.parseOptions)}configureReferences(e,t="references"){let n=ks.normalize(t),r=typeof e==="string"?(l,c)=>({...c,meta:{...c.meta,description:e}}):typeof e==="function"?(l,c)=>({...c,meta:e(c.meta)}):(l,c)=>({...c,meta:{...c.meta,...e}});if(n.boundary==="self")return this.$.node(this.kind,r(this.kind,{...this.inner,meta:this.meta}));let s=this._select(n),o=s&&er(s),a=n.boundary==="child"?(l,c)=>c.root.children.includes(l):n.boundary==="shallow"?(l)=>l.kind!=="structure":()=>!0;return this.$.finalize(this.transform(r,{shouldTransform:a,selected:o}))}}var ks={applyBoundary:{self:(e)=>[e],child:(e)=>[...e.children],shallow:(e)=>[...e.shallowReferences],references:(e)=>[...e.references]},applyMethod:{filter:(e)=>e,assertFilter:(e,t,n)=>{if(e.length===0)Ar(jg(t,n));return e},find:(e)=>e[0],assertFind:(e,t,n)=>{if(e.length===0)Ar(jg(t,n));return e[0]}},normalize:(e)=>typeof e==="function"?{boundary:"references",method:"filter",where:e}:typeof e==="string"?We(e,ks.applyBoundary)?{method:"filter",boundary:e}:{boundary:"references",method:"filter",kind:e}:{boundary:"references",method:"filter",...e}},jg=(e,t)=>`${e} had no references matching ${se(t)}.`,CE=(e)=>Tn(e,{stringifyNonKey:(t)=>t.expression}),OE=/"(\$ark\.[^"]+)"/g,IE=(e)=>JSON.stringify(e).replace(OE,"$1"),on=(e,t)=>({path:e,node:t,propString:CE(e)}),Ug=(e,t)=>e.propString===t.propString&&e.node.equals(t.node),Cu=(e,t)=>wn(e,t,{isEqual:Ug}),PE=(e,t)=>wn(e,t,{isEqual:(n,r)=>n.equals(r)});class q extends Array{static init(e,t,n,r){return new q({kind:e,l:t,r:n,path:r?.path??[],optional:r?.optional??!1})}add(e,t,n,r){return this.push({kind:e,l:t,r:n,path:r?.path??[],optional:r?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:e,l:t,r:n}=this[0],r=Tn(e);return Iu(`Intersection${r&&` at ${r}`} of ${Bg(t,n)}`)}return`The following intersections result in unsatisfiable types:
592
- \u2022 ${this.map(({path:e,l:t,r:n})=>`${e}: ${Bg(t,n)}`).join(`
593
- \u2022 `)}`}throw(){return C(this.describeReasons())}invert(){let e=this.map((t)=>({...t,l:t.r,r:t.l}));if(!(e instanceof q))return new q(...e);return e}withPrefixKey(e,t){return this.map((n)=>({...n,path:[e,...n.path],optional:n.optional||t==="optional"}))}toNeverIfDisjoint(){return N.intrinsic.never}}var Bg=(e,t)=>`${Ou(e)} and ${Ou(t)}`,Ou=(e)=>$e(e)?e.expression:Re(e)?e.map(Ou).join(" | ")||"never":String(e),Iu=(e)=>`${e} results in an unsatisfiable type`;var wi={},Ct=(e,t,n)=>ke(e,t,{$:n,invert:!1,pipe:!1}),As=(e,t,n)=>ke(e,t,{$:n,invert:!1,pipe:!0}),ke=(e,t,n)=>{let r=n.pipe?"|>":"&",s=`${e.hash}${r}${t.hash}`;if(wi[s]!==void 0)return wi[s];if(!n.pipe){let l=`${t.hash}${r}${e.hash}`;if(wi[l]!==void 0){let c=wi[l],u=c instanceof q?c.invert():c;return wi[s]=u,u}}let o=!n.pipe||!e.includesTransform&&!t.includesTransform;if(o&&e.equals(t))return e;let a=o?Pu(e,t,n):e.hasKindIn(...mi)?ME(e,t,n):Pu(e,t,n);if($e(a)){if(e.equals(a))a=e;else if(t.equals(a))a=t}return wi[s]=a,a},Pu=(e,t,n)=>{let r=e.precedence<t.precedence?e.kind:t.kind,s=e.impl.intersections[t.kind]??t.impl.intersections[e.kind];if(s===void 0)return null;else if(r===e.kind)return s(e,t,n);else{let o=s(t,e,{...n,invert:!n.invert});if(o instanceof q)o=o.invert();return o}},ME=(e,t,n)=>e.includesTransform||t.includesTransform?n.invert?qg(t,e,n):qg(e,t,n):Pu(e,t,n),qg=(e,t,n)=>e.distribute((r)=>TE(r,t,n),(r)=>{let s=r.filter($e);if(s.length===0)return q.init("union",e.branches,t.branches);if(s.length<e.branches.length||!e.branches.every((l,c)=>l.rawIn.equals(s[c].rawIn)))return n.$.parseSchema(s);let o;if(s.length===1){let l=s[0];if(!o)return l;return n.$.node("morph",{...l.inner,in:l.rawIn.configure(o,"self")})}let a={branches:s};if(o)a.meta=o;return n.$.parseSchema(a)}),TE=(e,t,n)=>{if(e.hasKind("morph")){let s=[...e.morphs];if(e.lastMorphIfNode){let o=ke(e.lastMorphIfNode,t,n);if(o instanceof q)return o;s[s.length-1]=o}else s.push(t);return n.$.node("morph",{morphs:s,in:e.inner.in})}if(t.hasKind("morph")){let s=ke(e,t.rawIn,n);if(s instanceof q)return s;return n.$.node("morph",{morphs:[t],in:s})}return n.$.node("morph",{morphs:[t],in:e})};class Wt extends Es{constructor(e,t){super(e,t);Object.defineProperty(this,ht,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(e){return Ct(this,e,this.$)}}class Fn extends Wt{traverseApply=(e,t)=>{if(!this.traverseAllows(e,t))t.errorFromNodeContext(this.errorContext)};compile(e){if(e.traversalKind==="Allows")e.return(this.compiledCondition);else e.if(this.compiledNegation,()=>e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return ir(this.errorContext)}}var lt=(e)=>(t,n)=>{if(Re(t)){if(t.length===0)return;let s=t.map((o)=>n.$.node(e,o));if(e==="predicate")return s;return s.sort((o,a)=>o.hash<a.hash?-1:1)}let r=n.$.node(e,t);return r.hasOpenIntersection()?[r]:r},yi=(e)=>{let t=e.r.shift();if(!t){let r=e.l.length===0&&e.kind==="structure"?N.intrinsic.unknown.internal:e.ctx.$.node(e.kind,Object.assign(e.baseInner,FE(e.l)),{prereduced:!0});for(let s of e.roots){if(r instanceof q)return r;r=ke(s,r,e.ctx)}return r}let n=!1;for(let r=0;r<e.l.length;r++){let s=ke(e.l[r],t,e.ctx);if(s===null)continue;if(s instanceof q)return s;if(s.isRoot())return e.roots.push(s),e.l.splice(r),yi(e);if(!n)e.l[r]=s,n=!0;else if(!e.l.includes(s))return he(`Unexpectedly encountered multiple distinct intersection results for refinement ${t}`)}if(!n)e.l.push(t);if(e.kind==="intersection"){if(t.impliedSiblings)for(let r of t.impliedSiblings)wn(e.r,r)}return yi(e)},bi=(e)=>Object.entries(e).flatMap(([n,r])=>(n in ka)?r:[]).sort((n,r)=>n.precedence<r.precedence?-1:n.precedence>r.precedence?1:n.kind==="predicate"&&r.kind==="predicate"?0:n.hash<r.hash?-1:1),FE=(e)=>{let t={};for(let n of e)if(n.hasOpenIntersection())t[n.kind]=de(t[n.kind],n);else{if(t[n.kind])return he(`Unexpected intersection of closed refinements of kind ${n.kind}`);t[n.kind]=n}return t},Hg=(...e)=>C(Kg(...e)),Kg=(e,t,n)=>{let r=n.hasKind("morph")?"a morph":n.isUnknown()?"unknown":n.exclude(t).defaultShortDescription;return`${gg(e)} operand must be ${t.description} (was ${r})`};var Wg=(e,t,n)=>new or(e,t,n,n,null);class Aa extends kt{}class or extends kt{[ht]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(e,t,n,r,s){super((...o)=>{let a=ie(this.names,(l,c)=>{let u=this.arg$.parse(o[l]);if(!u.extends(this.constraints[l]))C(NE(c,this.constraints[l].expression,u.expression));return[c,u]});if(this.defIsLazy()){let l=this.bodyDef(a);return this.$.parse(l)}return this.$.parse(t,{args:a})});this.paramDefs=e,this.bodyDef=t,this.$=n,this.arg$=r,this.hkt=s,this.description=s?new s().description??`a generic type for ${s.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof Aa}cacheGetter(e,t){return Object.defineProperty(this,e,{value:t}),t}get json(){return this.cacheGetter("json",{params:this.params.map((e)=>e[1].isUnknown()?e[0]:[e[0],e[1].json]),body:Ag(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((e)=>typeof e==="string"?[e,N.intrinsic.unknown]:[e[0],this.$.parse(e[1])]))}get names(){return this.cacheGetter("names",this.params.map((e)=>e[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map((e)=>e[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}var NE=(e,t,n)=>`${e} must be assignable to ${t} (was ${n})`;var DE=ae({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:(e)=>typeof e==="function"?{predicate:e}:e,defaults:{description:(e)=>`valid according to ${e.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class Gg extends Wt{serializedPredicate=Me(this.predicate);compiledCondition=`${this.serializedPredicate}(data, ctx)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=null;expression=this.serializedPredicate;traverseAllows=this.predicate;errorContext={code:"predicate",description:this.description,meta:this.meta};compiledErrorContext=ir(this.errorContext);traverseApply=(e,t)=>{let n=t.currentErrorCount;if(!this.predicate(e,t.external)&&t.currentErrorCount===n)t.errorFromNodeContext(this.errorContext)};compile(e){if(e.traversalKind==="Allows"){e.return(this.compiledCondition);return}e.initializeErrorCount(),e.if(`${this.compiledNegation} && ctx.currentErrorCount === errorCount`,()=>e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(e,t){return t.fallback.predicate({code:"predicate",base:e,predicate:this.predicate})}}var Mu={implementation:DE,Node:Gg};var LE=ae({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(e)=>Number.isInteger(e)?e:C(jE(e))}},normalize:(e)=>typeof e==="number"?{rule:e}:e,hasAssociatedError:!0,defaults:{description:(e)=>e.rule===1?"an integer":e.rule===2?"even":`a multiple of ${e.rule}`},intersections:{divisor:(e,t,n)=>n.$.node("divisor",{rule:Math.abs(e.rule*t.rule/UE(e.rule,t.rule))})},obviatesBasisDescription:!0});class Vg extends Fn{traverseAllows=(e)=>e%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=N.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(e){if(e.type="integer",this.rule===1)return e;return e.multipleOf=this.rule,e}}var Tu={implementation:LE,Node:Vg};var jE=(e)=>`divisor must be an integer (was ${e})`,UE=(e,t)=>{let n,r=e,s=t;while(s!==0)n=s,s=r%s,r=n;return r};class Tt extends Fn{boundOperandKind=KE[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=WE(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${BE[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?GE(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator["0"]==="<"?"upper":"lower";isStricterThan(e){return(this.limitKind==="upper"?this.numericLimit<e.numericLimit:this.numericLimit>e.numericLimit)||this.numericLimit===e.numericLimit&&this.exclusive===!0&&!e.exclusive}overlapsRange(e){if(this.isStricterThan(e))return!1;if(this.numericLimit===e.numericLimit&&(this.exclusive||e.exclusive))return!1;return!0}overlapIsUnit(e){return this.numericLimit===e.numericLimit&&!this.exclusive&&!e.exclusive}}var BE={"<":">=","<=":">",">":"<=",">=":"<"},qE={min:"max",minLength:"maxLength",after:"before"},Ca={parse:(e)=>e||void 0},Oa=(e)=>(t)=>{if(typeof t==="number")return{rule:t};let{exclusive:n,...r}=t;return n?{...r,rule:e==="minLength"?r.rule+1:r.rule-1}:r},Ia=(e)=>(t)=>{if(typeof t==="number"||typeof t==="string"||t instanceof Date)return{rule:t};let{exclusive:n,...r}=t;if(!n)return r;let s=typeof r.rule==="number"?r.rule:typeof r.rule==="string"?new Date(r.rule).valueOf():r.rule.valueOf();return n?{...r,rule:e==="after"?s+1:s-1}:r},Pa=(e)=>typeof e==="string"||typeof e==="number"?new Date(e):e,HE=(e,t)=>`${e} bound must be a positive integer (was ${t})`,vi=(e)=>(t)=>{if(!Number.isInteger(t)||t<0)C(HE(e,t));return t},KE={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},WE=(e,t)=>`${We(e,qE)?">":"<"}${t?"":"="}`,GE=(e)=>typeof e==="string"?e:new Date(e).toLocaleString(),zg=(e)=>`Bounded expression ${e} must be exactly one of number, string, Array, or Date`;var VE=ae({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Pa,serialize:(e)=>e.toISOString()}},normalize:Ia("after"),defaults:{description:(e)=>`${e.collapsibleLimitString} or later`,actual:Mr},intersections:{after:(e,t)=>e.isStricterThan(t)?e:t}});class Jg extends Tt{impliedBasis=N.intrinsic.Date.internal;collapsibleLimitString=Mr(this.rule);traverseAllows=(e)=>e>=this.rule;reduceJsonSchema(e,t){return t.fallback.date({code:"date",base:e,after:this.rule})}}var Fu={implementation:VE,Node:Jg};var zE=ae({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Pa,serialize:(e)=>e.toISOString()}},normalize:Ia("before"),defaults:{description:(e)=>`${e.collapsibleLimitString} or earlier`,actual:Mr},intersections:{before:(e,t)=>e.isStricterThan(t)?e:t,after:(e,t,n)=>e.overlapsRange(t)?e.overlapIsUnit(t)?n.$.node("unit",{unit:e.rule}):null:q.init("range",e,t)}});class Xg extends Tt{collapsibleLimitString=Mr(this.rule);traverseAllows=(e)=>e<=this.rule;impliedBasis=N.intrinsic.Date.internal;reduceJsonSchema(e,t){return t.fallback.date({code:"date",base:e,before:this.rule})}}var Nu={implementation:zE,Node:Xg};var JE=ae({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:vi("exactLength")}},normalize:(e)=>typeof e==="number"?{rule:e}:e,hasAssociatedError:!0,defaults:{description:(e)=>`exactly length ${e.rule}`,actual:(e)=>`${e.length}`},intersections:{exactLength:(e,t,n)=>q.init("unit",n.$.node("unit",{unit:e.rule}),n.$.node("unit",{unit:t.rule}),{path:["length"]}),minLength:(e,t)=>e.rule>=t.rule?e:q.init("range",e,t),maxLength:(e,t)=>e.rule<=t.rule?e:q.init("range",e,t)}});class Yg extends Fn{traverseAllows=(e)=>e.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=N.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(e){switch(e.type){case"string":return e.minLength=this.rule,e.maxLength=this.rule,e;case"array":return e.minItems=this.rule,e.maxItems=this.rule,e;default:return Ee.throwInternalOperandError("exactLength",e)}}}var Du={implementation:JE,Node:Yg};var XE=ae({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:Ca},normalize:(e)=>typeof e==="number"?{rule:e}:e,defaults:{description:(e)=>{if(e.rule===0)return e.exclusive?"negative":"non-positive";return`${e.exclusive?"less than":"at most"} ${e.rule}`}},intersections:{max:(e,t)=>e.isStricterThan(t)?e:t,min:(e,t,n)=>e.overlapsRange(t)?e.overlapIsUnit(t)?n.$.node("unit",{unit:e.rule}):null:q.init("range",e,t)},obviatesBasisDescription:!0});class Zg extends Tt{impliedBasis=N.intrinsic.number.internal;traverseAllows=this.exclusive?(e)=>e<this.rule:(e)=>e<=this.rule;reduceJsonSchema(e){if(this.exclusive)e.exclusiveMaximum=this.rule;else e.maximum=this.rule;return e}}var Lu={implementation:XE,Node:Zg};var YE=ae({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:vi("maxLength")}},reduce:(e,t)=>e.rule===0?t.node("exactLength",e):void 0,normalize:Oa("maxLength"),defaults:{description:(e)=>`at most length ${e.rule}`,actual:(e)=>`${e.length}`},intersections:{maxLength:(e,t)=>e.isStricterThan(t)?e:t,minLength:(e,t,n)=>e.overlapsRange(t)?e.overlapIsUnit(t)?n.$.node("exactLength",{rule:e.rule}):null:q.init("range",e,t)}});class Qg extends Tt{impliedBasis=N.intrinsic.lengthBoundable.internal;traverseAllows=(e)=>e.length<=this.rule;reduceJsonSchema(e){switch(e.type){case"string":return e.maxLength=this.rule,e;case"array":return e.maxItems=this.rule,e;default:return Ee.throwInternalOperandError("maxLength",e)}}}var ju={implementation:YE,Node:Qg};var ZE=ae({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:Ca},normalize:(e)=>typeof e==="number"?{rule:e}:e,defaults:{description:(e)=>{if(e.rule===0)return e.exclusive?"positive":"non-negative";return`${e.exclusive?"more than":"at least"} ${e.rule}`}},intersections:{min:(e,t)=>e.isStricterThan(t)?e:t},obviatesBasisDescription:!0});class e_ extends Tt{impliedBasis=N.intrinsic.number.internal;traverseAllows=this.exclusive?(e)=>e>this.rule:(e)=>e>=this.rule;reduceJsonSchema(e){if(this.exclusive)e.exclusiveMinimum=this.rule;else e.minimum=this.rule;return e}}var Uu={implementation:ZE,Node:e_};var QE=ae({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:vi("minLength")}},reduce:(e)=>e.rule===0?N.intrinsic.unknown:void 0,normalize:Oa("minLength"),defaults:{description:(e)=>e.rule===1?"non-empty":`at least length ${e.rule}`,actual:(e)=>e.length===0?"":`${e.length}`},intersections:{minLength:(e,t)=>e.isStricterThan(t)?e:t}});class t_ extends Tt{impliedBasis=N.intrinsic.lengthBoundable.internal;traverseAllows=(e)=>e.length>=this.rule;reduceJsonSchema(e){switch(e.type){case"string":return e.minLength=this.rule,e;case"array":return e.minItems=this.rule,e;default:return Ee.throwInternalOperandError("minLength",e)}}}var Bu={implementation:QE,Node:t_};var n_={min:Uu.implementation,max:Lu.implementation,minLength:Bu.implementation,maxLength:ju.implementation,exactLength:Du.implementation,after:Fu.implementation,before:Nu.implementation},r_={min:Uu.Node,max:Lu.Node,minLength:Bu.Node,maxLength:ju.Node,exactLength:Du.Node,after:Fu.Node,before:Nu.Node};var e0=ae({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:(e)=>typeof e==="string"?{rule:e}:e instanceof RegExp?e.flags?{rule:e.source,flags:e.flags}:{rule:e.source}:e,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:(e)=>`matched by ${e.rule}`},intersections:{pattern:()=>null}});class i_ extends Fn{instance=new RegExp(this.rule,this.flags);expression=`${this.instance}`;traverseAllows=this.instance.test.bind(this.instance);compiledCondition=`${this.expression}.test(data)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=N.intrinsic.string.internal;reduceJsonSchema(e,t){if(e.pattern)return t.fallback.patternIntersection({code:"patternIntersection",base:e,pattern:this.rule});return e.pattern=this.rule,e}}var qu={implementation:e0,Node:i_};var Cs=(e,t)=>{let n=t0(e);if(t&&!t.includes(n))return C(`Root of kind ${n} should be one of ${t}`);return n},t0=(e)=>{if(X(e,"root"))return e.kind;if(typeof e==="string")return e[0]==="$"?"alias":(e in St)?"domain":"proto";if(typeof e==="function")return"proto";if(typeof e!=="object"||e===null)return C(s_(e));if("morphs"in e)return"morph";if("branches"in e||Re(e))return"union";if("unit"in e)return"unit";if("reference"in e)return"alias";let t=Object.keys(e);if(t.length===0||t.some((n)=>(n in ka)))return"intersection";if("proto"in e)return"proto";if("domain"in e)return"domain";return C(s_(e))},s_=(e)=>`${se(e)} is not a valid type schema`,o_={},n0=(e)=>Re(e)?e.map((t)=>t.collapsibleJson):e.collapsibleJson,mt={};N.nodesByRegisteredId=mt;var Hu=(e)=>(o_[e]??=0,`${e}${++o_[e]}`),Ku=(e)=>{let t=xi[e.kind],n=t.applyConfig?.(e.def,e.$.resolvedConfig)??e.def,r={},{meta:s,...o}=n,a=s===void 0?{}:typeof s==="string"?{description:s}:s,l=pu(o).sort(([u],[d])=>gi(u)?gi(d)?_i(u)-_i(d):1:gi(d)?-1:u<d?-1:1).filter(([u,d])=>{if(u.startsWith("meta.")){let f=u.slice(5);return a[f]=d,!1}return!0});for(let u of l){let d=u[0],f=t.keys[d];if(!f)return C(`Key ${d} is not valid on ${e.kind} schema`);let p=f.parse?f.parse(u[1],e):u[1];if(p!==$t&&(p!==void 0||f.preserveUndefined))r[d]=p}if(t.reduce&&!e.prereduced){let u=t.reduce(r,e.$);if(u){if(u instanceof q)return u.throw();return r0(u,a)}}return Wu({id:e.id,kind:e.kind,inner:r,meta:a,$:e.$})},Wu=({id:e,kind:t,inner:n,meta:r,$:s,ignoreCache:o})=>{let a=xi[t],l=pu(n),c=[],u={};for(let[x,R]of l){let P=a.keys[x],M=P.serialize??(P.child?n0:Kt);if(u[x]=M(R),P.child===!0){let k=R;if(Re(k))c.push(...k);else c.push(k)}else if(typeof P.child==="function")c.push(...P.child(R))}if(a.finalizeInnerJson)u=a.finalizeInnerJson(u);let d={...u},f={};if(!yn(r))f=ie(r,(x,R)=>[x,x==="examples"?R:Kt(R)]),d.meta=Ma(f,"description",!0);u=Ma(u,a.collapsibleKey,!1);let p=JSON.stringify({kind:t,...u});d=Ma(d,a.collapsibleKey,!1);let h=Ma(d,a.collapsibleKey,!0),g=JSON.stringify({kind:t,...d});if(s.nodesByHash[g]&&!o)return s.nodesByHash[g];let w={id:e,kind:t,impl:a,inner:n,innerEntries:l,innerJson:u,innerHash:p,meta:r,metaJson:f,json:d,hash:g,collapsibleJson:h,children:c};if(t!=="intersection"){for(let x in n)if(x!=="in"&&x!=="out")w[x]=n[x]}let b=new l_[t](w,s);return s.nodesByHash[g]=b},a_=(e,t)=>{if(e.id===t)return e;if($e(mt[t]))he(`Unexpected attempt to overwrite node id ${t}`);return Wu({id:t,kind:e.kind,inner:e.inner,meta:e.meta,$:e.$,ignoreCache:!0})},r0=(e,t,n)=>{if(n&&$e(mt[n]))he(`Unexpected attempt to overwrite node id ${n}`);return Wu({id:n??Hu(t.alias??e.kind),kind:e.kind,inner:e.inner,meta:t,$:e.$})},Ma=(e,t,n)=>{let r=Object.keys(e);if(r.length===1&&r[0]===t){let s=e[t];if(n)return s;if(Rt(s,"object")&&(Object.keys(s).length===1||Array.isArray(s)))return s}return e};var Os=(e,t,n)=>{if(e.key!==t.key)return null;let r=e.key,s=ke(e.value,t.value,n),o=e.required||t.required?"required":"optional";if(s instanceof q)if(o==="optional")s=N.intrinsic.never.internal;else return s.withPrefixKey(e.key,e.required&&t.required?"required":"optional");if(o==="required")return n.$.node("required",{key:r,value:s});let a=e.hasDefault()?t.hasDefault()?e.default===t.default?e.default:C(Gu(e.default,t.default)):e.default:t.hasDefault()?t.default:$t;return n.$.node("optional",{key:r,value:s,default:a})};class Is extends Wt{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=N.intrinsic.object.internal;serializedKey=rn(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=de(this.value.flatRefs.map((e)=>on([this.key,...e.path],e.node)),on([this.key],this.value));_transform(e,t){t.path.push(this.key);let n=super._transform(e,t);return t.path.pop(),n}hasDefault(){return"default"in this.inner}traverseAllows=(e,t)=>{if(this.key in e)return At(this.key,()=>this.value.traverseAllows(e[this.key],t),t);return this.optional};traverseApply=(e,t)=>{if(this.key in e)At(this.key,()=>this.value.traverseApply(e[this.key],t),t);else if(this.hasKind("required"))t.errorFromNodeContext(this.errorContext)};compile(e){if(e.if(`${this.serializedKey} in data`,()=>e.traverseKey(this.serializedKey,`data${e.prop(this.key)}`,this.value)),this.hasKind("required"))e.else(()=>e.traversalKind==="Apply"?e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):e.return(!1));if(e.traversalKind==="Allows")e.return(!0)}}var Gu=(e,t)=>`Invalid intersection of default values ${se(e)} & ${se(t)}`;var i0=ae({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(e,t)=>t.$.parseSchema(e)},default:{preserveUndefined:!0}},normalize:(e)=>e,reduce:(e,t)=>{if(t.resolvedConfig.exactOptionalPropertyTypes===!1){if(!e.value.allows(void 0))return t.node("optional",{...e,value:e.value.or(ee.undefined)},{prereduced:!0})}},defaults:{description:(e)=>`${e.compiledKey}?: ${e.value.description}`},intersections:{optional:Os}});class c_ extends Is{constructor(...e){super(...e);if("default"in this.inner)Ms(this.value,this.inner.default,this.key)}get rawIn(){let e=super.rawIn;if(!this.hasDefault())return e;return this.$.node("optional",ya(e.inner,{default:!0}),{prereduced:!0})}get outProp(){if(!this.hasDefault())return this;let{default:e,...t}=this.inner;return this.cacheGetter("outProp",this.$.node("required",t,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${se(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=o0(this);defaultValueMorphRef=this.defaultValueMorph&&Me(this.defaultValueMorph)}var Ps={implementation:i0,Node:c_},s0={},o0=(e)=>{if(!e.hasDefault())return;let t=`{${e.compiledKey}: ${e.value.id} = ${Kt(e.default)}}`;return s0[t]??=Vu(e.key,e.value,e.default)},Vu=(e,t,n)=>{if(typeof n==="function")return t.includesTransform?(s,o)=>(At(e,()=>t(s[e]=n(),o),o),s):(s)=>(s[e]=n(),s);let r=t.includesTransform?t.assert(n):n;return Rt(r,"object")?(s,o)=>(At(e,()=>t(s[e]=n,o),o),s):(s)=>(s[e]=r,s)},Ms=(e,t,n)=>{let r=tr(t);if(Rt(t,"object")&&!r)C(a0(n));let s=e.in(r?t():t);if(s instanceof Et){if(n===null)C(`Default ${s.summary}`);let o=s.transform((a)=>a.transform((l)=>({...l,prefixPath:[n]})));C(`Default for ${o.summary}`)}return t},a0=(e)=>`Non-primitive default ${e===null?"":typeof e==="number"?`for value at [${e}] `:`for ${rn(e)} `}must be specified as a function like () => ({my: 'object'})`;class Gt extends Es{constructor(e,t){super(e,t);Object.defineProperty(this,ht,{value:"root",enumerable:!1})}get rawIn(){return super.rawIn}get rawOut(){return super.rawOut}get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:(e)=>{let t=this(e);if(t instanceof Et)return t;return{value:t}},jsonSchema:{input:(e)=>this.rawIn.toJsonSchema({target:u_(e.target),...e.libraryOptions}),output:(e)=>this.rawOut.toJsonSchema({target:u_(e.target),...e.libraryOptions})}}}as(){return this}brand(e){if(e==="")return C(l0);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(e,t){let n=this.branches.map(e);return t?.(n)??n}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(e={}){let t=Eu(this.$.resolvedConfig.toJsonSchema,e);t.useRefs||=this.isCyclic;let n=typeof t.dialect==="string"?{$schema:t.dialect}:{};if(Object.assign(n,this.toJsonSchemaRecurse(t)),t.useRefs){let r=ie(this.references,(s,o)=>o.isRoot()&&!o.alwaysExpandJsonSchema?[o.id,o.toResolvedJsonSchema(t)]:[]);if(t.target==="draft-07")Object.assign(n,{definitions:r});else n.$defs=r}return n}toJsonSchemaRecurse(e){if(e.useRefs&&!this.alwaysExpandJsonSchema)return{$ref:`#/${e.target==="draft-07"?"definitions":"$defs"}/${this.id}`};return this.toResolvedJsonSchema(e)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(e){let t=this.innerToJsonSchema(e);return Object.assign(t,this.metaJson)}intersect(e){let t=this.$.parseDefinition(e),n=this.rawIntersect(t);if(n instanceof q)return n;return this.$.finalize(n)}rawIntersect(e){return Ct(this,e,this.$)}toNeverIfDisjoint(){return this}and(e){let t=this.intersect(e);return t instanceof q?t.throw():t}rawAnd(e){let t=this.rawIntersect(e);return t instanceof q?t.throw():t}or(e){let t=this.$.parseDefinition(e);return this.$.finalize(this.rawOr(t))}rawOr(e){let t=[...this.branches,...e.branches];return this.$.node("union",t)}map(e){return this.$.schema(this.applyStructuralOperation("map",[e]))}pick(...e){return this.$.schema(this.applyStructuralOperation("pick",e))}omit(...e){return this.$.schema(this.applyStructuralOperation("omit",e))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let e=this.applyStructuralOperation("keyof",[]).reduce((t,n)=>t.intersect(n).toNeverIfDisjoint(),N.intrinsic.unknown.internal);if(e.branches.length===0)C(Iu(`keyof ${this.expression}`));return this._keyof=this.$.finalize(e)}get props(){if(this.branches.length!==1)return C(u0(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(e){let t=this.$.parseDefinition(e);return this.$.schema(t.distribute((n)=>this.applyStructuralOperation("merge",[d_(n)??C(f_("merge",n.expression))])))}applyStructuralOperation(e,t){return this.distribute((n)=>{if(n.equals(N.intrinsic.object)&&e!=="merge")return n;let r=d_(n);if(!r)C(f_(e,n.expression));if(e==="keyof")return r.keyof();if(e==="get")return r.get(...t);if(e==="props")return r.props;let s=e==="required"?"require":e==="partial"?"optionalize":e;return this.$.node("intersection",{domain:"object",structure:r[s](...t)})})}get(...e){if(e[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",e))}extract(e){let t=this.$.parseDefinition(e);return this.$.schema(this.branches.filter((n)=>n.extends(t)))}exclude(e){let t=this.$.parseDefinition(e);return this.$.schema(this.branches.filter((n)=>!n.extends(t)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(e){return!(this.intersect(e)instanceof q)}extends(e){if(this.isNever())return!0;let t=this.intersect(e);return!(t instanceof q)&&this.equals(t)}ifExtends(e){return this.extends(e)?this:void 0}subsumes(e){return this.$.parseDefinition(e).extends(this)}configure(e,t="shallow"){return this.configureReferences(e,t)}describe(e,t="shallow"){return this.configure({description:e},t)}optional(){return[this,"?"]}default(e){return Ms(this,e,null),[this,"=",e]}from(e){return this.assert(e)}_pipe(...e){let t=e.reduce((n,r)=>n.rawPipeOnce(r),this);return this.$.finalize(t)}tryPipe(...e){let t=e.reduce((n,r)=>n.rawPipeOnce(X(r,"root")?r:(s,o)=>{try{return r(s,o)}catch(a){return o.error({code:"predicate",predicate:r,actual:`aborted due to error:
591
+ `);class an{path=[];errors=new Et(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(e,t){this.root=e,this.config=t}get data(){let e=this.root;for(let t of this.path)e=e?.[t];return e}get propString(){return Nn(this.path)}reject(e){return this.error(e),!1}mustBe(e){return this.error(e),!1}error(e){let t=typeof e==="object"?e.code?e:{...e,code:"predicate"}:{code:"predicate",expected:e};return this.errorFromContext(t)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches[this.branches.length-1]}queueMorphs(e){let t={path:new Os(...this.path),morphs:e};if(this.currentBranch)this.currentBranch.queuedMorphs.push(t);else this.queuedMorphs.push(t)}finalize(e){if(this.queuedMorphs.length){if(typeof this.root==="object"&&this.root!==null&&this.config.clone)this.root=this.config.clone(this.root);this.applyQueuedMorphs()}if(this.hasError())return e?e(this.errors):this.errors;return this.root}get currentErrorCount(){return this.currentBranch?this.currentBranch.error?1:0:this.errors.count}get failFast(){return this.branches.length!==0}pushBranch(){this.branches.push({error:void 0,queuedMorphs:[]})}popBranch(){return this.branches.pop()}get external(){return this}errorFromNodeContext(e){return this.errorFromContext(e)}errorFromContext(e){let t=new lr(e,this);if(this.currentBranch)this.currentBranch.error=t;else this.errors.add(t);return t}applyQueuedMorphs(){while(this.queuedMorphs.length){let e=this.queuedMorphs;this.queuedMorphs=[];for(let{path:t,morphs:n}of e){if(this.errors.affectsPath(t))continue;this.applyMorphsAtPath(t,n)}}}applyMorphsAtPath(e,t){let n=e[e.length-1],r;if(n!==void 0){r=this.root;for(let s=0;s<e.length-1;s++)r=r[e[s]]}for(let s of t){this.path=[...e];let o=$e(s),a=s(r===void 0?this.root:r[n],this);if(a instanceof lr){if(!this.errors.includes(a))this.errors.add(a);break}if(a instanceof Et){if(!o)this.errors.merge(a);this.queuedMorphs=[];break}if(r===void 0)this.root=a;else r[n]=a;this.applyQueuedMorphs()}}}var Ct=(e,t,n)=>{if(!n)return t();n.path.push(e);let r=t();return n.path.pop(),r};class Ds extends kt{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(e,t){super((r,s,o=this.onFail)=>{if(s)return this.traverseApply(r,s),s.hasError()?s.errors:s.data;return this.rootApply(r,o)},{attach:e});this.attachments=e,this.$=t,this.onFail=this.meta.onFail??this.$.resolvedConfig.onFail,this.includesTransform=this.hasKind("morph")||this.hasKind("structure")&&this.structuralMorph!==void 0||this.hasKind("sequence")&&this.inner.defaultables!==void 0,this.includesContextualPredicate=this.hasKind("predicate")&&this.inner.predicate.length!==1,this.isCyclic=this.kind==="alias",this.referencesById={[this.id]:this},this.shallowReferences=this.hasKind("structure")?[this,...this.children]:this.children.reduce((r,s)=>bC(r,s.shallowReferences),[this]);let n=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let r=0;r<this.children.length;r++){if(this.includesTransform||=this.children[r].includesTransform,this.includesContextualPredicate||=this.children[r].includesContextualPredicate,this.isCyclic||=this.children[r].isCyclic,!n){let s=this.children[r].flatRefs;for(let o=0;o<s.length;o++){let a=s[o];if(!this.flatRefs.some((l)=>d_(l,a))){this.flatRefs.push(a);for(let l of a.node.branches)if(l.hasKind("morph")||l.hasKind("intersection")&&l.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:a.path,propString:a.propString,node:l})}}}Object.assign(this.referencesById,this.children[r].referencesById)}this.flatRefs.sort((r,s)=>r.path.length>s.path.length?1:r.path.length<s.path.length?-1:r.propString>s.propString?1:r.propString<s.propString?-1:r.node.expression<s.node.expression?-1:1),this.allowsRequiresContext=this.includesContextualPredicate||this.isCyclic,this.rootApplyStrategy=!this.allowsRequiresContext&&this.flatMorphs.length===0?this.shallowMorphs.length===0?"allows":this.shallowMorphs.every((r)=>r.length===1||r.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((r)=>r.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(r)=>this.traverseAllows(r,new an(r,this.$.resolvedConfig)):(r)=>this.traverseAllows(r)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(t,n)=>{if(this.allows(t))return t;let r=new an(t,this.$.resolvedConfig);return this.traverseApply(t,r),r.finalize(n)};case"contextual":return(t,n)=>{let r=new an(t,this.$.resolvedConfig);return this.traverseApply(t,r),r.finalize(n)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let e=this.$.resolvedConfig.clone;return(t,n)=>{if(this.allows(t))return this.contextFreeMorph(e&&(typeof t==="object"&&t!==null||typeof t==="function")?e(t):t);let r=new an(t,this.$.resolvedConfig);return this.traverseApply(t,r),r.finalize(n)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,he(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=yC(this.metaJson);cacheGetter(e,t){return Object.defineProperty(this,e,{value:t}),t}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=xi(this.kind);precompilation;assert=(e,t)=>this(e,t,(n)=>n.throw());traverse(e,t){return this(e,t,null)}get in(){return this.cacheGetter("in",this.rawIn.isRoot()?this.$.finalize(this.rawIn):this.rawIn)}get rawIn(){return this.cacheGetter("rawIn",this.getIo("in"))}get out(){return this.cacheGetter("out",this.rawOut.isRoot()?this.$.finalize(this.rawOut):this.rawOut)}get rawOut(){return this.cacheGetter("rawOut",this.getIo("out"))}getIo(e){if(!this.includesTransform)return this;let t={};for(let[n,r]of this.innerEntries){let s=this.impl.keys[n];if(s.reduceIo)s.reduceIo(e,t,r);else if(s.child){let o=r;t[n]=Se(o)?o.map((a)=>e==="in"?a.rawIn:a.rawOut):e==="in"?o.rawIn:o.rawOut}else t[n]=r}return this.$.node(this.kind,t)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(e){let t=$e(e)?e:this.$.parseDefinition(e);return this.innerHash===t.innerHash}ifEquals(e){return this.equals(e)?this:void 0}hasKind(e){return this.kind===e}assertHasKind(e){if(this.kind!==e)Pr(`${this.kind} node was not of asserted kind ${e}`);return this}hasKindIn(...e){return e.includes(this.kind)}assertHasKindIn(...e){if(!Kt(e,this.kind))Pr(`${this.kind} node was not one of asserted kinds ${e}`);return this}isBasis(){return Kt(i_,this.kind)}isConstraint(){return Kt(Ma,this.kind)}isStructural(){return Kt(yi,this.kind)}isRefinement(){return Kt(ju,this.kind)}isRoot(){return Kt(bi,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(e){return this.hasKind("unit")&&this.allows(e)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(e){let t=Ts.normalize(e);return this._select(t)}_select(e){let t=Ts.applyBoundary[e.boundary??"references"](this);if(e.kind)t=t.filter((n)=>n.kind===e.kind);if(e.where)t=t.filter(e.where);return Ts.applyMethod[e.method??"filter"](t,this,e)}transform(e,t){return this._transform(e,this._createTransformContext(t))}_createTransformContext(e){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:e?.prereduced??!1},undeclaredKeyHandling:void 0,...e}}_transform(e,t){let n=t.bindScope??this.$;if(t.seen[this.id])return this.$.lazilyResolve(t.seen[this.id]);if(t.shouldTransform?.(this,t)===!1)return this;let r;if(t.seen[this.id]=()=>r,this.hasKind("structure")&&this.undeclared!==t.undeclaredKeyHandling)t={...t,undeclaredKeyHandling:this.undeclared};let s=ie(this.inner,(u,d)=>{if(!this.impl.keys[u].child)return[u,d];let f=d;if(!Se(f)){let h=f._transform(e,t);return h?[u,h]:[]}if(f.length===0)return[u,d];let p=f.flatMap((h)=>h._transform(e,t)??[]);return p.length?[u,p]:[]});delete t.seen[this.id];let o=Object.assign(s,{meta:this.meta}),a=t.selected&&!t.selected.includes(this)?o:e(this.kind,o,t);if(a===null)return null;if($e(a))return r=a;let l=Object.keys(a);if((l.length===0||l.length===1&&l[0]==="meta")&&!vn(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in a))return t.undeclaredKeyHandling?{...a,value:N.intrinsic.unknown}:null;if(this.kind==="morph")a.in??=N.intrinsic.unknown;return r=n.node(this.kind,a,t.parseOptions)}configureReferences(e,t="references"){let n=Ts.normalize(t),r=typeof e==="string"?(l,c)=>({...c,meta:{...c.meta,description:e}}):typeof e==="function"?(l,c)=>({...c,meta:e(c.meta)}):(l,c)=>({...c,meta:{...c.meta,...e}});if(n.boundary==="self")return this.$.node(this.kind,r(this.kind,{...this.inner,meta:this.meta}));let s=this._select(n),o=s&&rr(s),a=n.boundary==="child"?(l,c)=>c.root.children.includes(l):n.boundary==="shallow"?(l)=>l.kind!=="structure":()=>!0;return this.$.finalize(this.transform(r,{shouldTransform:a,selected:o}))}}var Ts={applyBoundary:{self:(e)=>[e],child:(e)=>[...e.children],shallow:(e)=>[...e.shallowReferences],references:(e)=>[...e.references]},applyMethod:{filter:(e)=>e,assertFilter:(e,t,n)=>{if(e.length===0)Pr(u_(t,n));return e},find:(e)=>e[0],assertFind:(e,t,n)=>{if(e.length===0)Pr(u_(t,n));return e[0]}},normalize:(e)=>typeof e==="function"?{boundary:"references",method:"filter",where:e}:typeof e==="string"?Ge(e,Ts.applyBoundary)?{method:"filter",boundary:e}:{boundary:"references",method:"filter",kind:e}:{boundary:"references",method:"filter",...e}},u_=(e,t)=>`${e} had no references matching ${se(t)}.`,_C=(e)=>Nn(e,{stringifyNonKey:(t)=>t.expression}),wC=/"(\$ark\.[^"]+)"/g,yC=(e)=>JSON.stringify(e).replace(wC,"$1"),ln=(e,t)=>({path:e,node:t,propString:_C(e)}),d_=(e,t)=>e.propString===t.propString&&e.node.equals(t.node),qu=(e,t)=>bn(e,t,{isEqual:d_}),bC=(e,t)=>bn(e,t,{isEqual:(n,r)=>n.equals(r)});class q extends Array{static init(e,t,n,r){return new q({kind:e,l:t,r:n,path:r?.path??[],optional:r?.optional??!1})}add(e,t,n,r){return this.push({kind:e,l:t,r:n,path:r?.path??[],optional:r?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:e,l:t,r:n}=this[0],r=Nn(e);return Ku(`Intersection${r&&` at ${r}`} of ${f_(t,n)}`)}return`The following intersections result in unsatisfiable types:
592
+ \u2022 ${this.map(({path:e,l:t,r:n})=>`${e}: ${f_(t,n)}`).join(`
593
+ \u2022 `)}`}throw(){return A(this.describeReasons())}invert(){let e=this.map((t)=>({...t,l:t.r,r:t.l}));if(!(e instanceof q))return new q(...e);return e}withPrefixKey(e,t){return this.map((n)=>({...n,path:[e,...n.path],optional:n.optional||t==="optional"}))}toNeverIfDisjoint(){return N.intrinsic.never}}var f_=(e,t)=>`${Hu(e)} and ${Hu(t)}`,Hu=(e)=>$e(e)?e.expression:Se(e)?e.map(Hu).join(" | ")||"never":String(e),Ku=(e)=>`${e} results in an unsatisfiable type`;var Si={},At=(e,t,n)=>ke(e,t,{$:n,invert:!1,pipe:!1}),Ns=(e,t,n)=>ke(e,t,{$:n,invert:!1,pipe:!0}),ke=(e,t,n)=>{let r=n.pipe?"|>":"&",s=`${e.hash}${r}${t.hash}`;if(Si[s]!==void 0)return Si[s];if(!n.pipe){let l=`${t.hash}${r}${e.hash}`;if(Si[l]!==void 0){let c=Si[l],u=c instanceof q?c.invert():c;return Si[s]=u,u}}let o=!n.pipe||!e.includesTransform&&!t.includesTransform;if(o&&e.equals(t))return e;let a=o?Gu(e,t,n):e.hasKindIn(...bi)?vC(e,t,n):Gu(e,t,n);if($e(a)){if(e.equals(a))a=e;else if(t.equals(a))a=t}return Si[s]=a,a},Gu=(e,t,n)=>{let r=e.precedence<t.precedence?e.kind:t.kind,s=e.impl.intersections[t.kind]??t.impl.intersections[e.kind];if(s===void 0)return null;else if(r===e.kind)return s(e,t,n);else{let o=s(t,e,{...n,invert:!n.invert});if(o instanceof q)o=o.invert();return o}},vC=(e,t,n)=>e.includesTransform||t.includesTransform?n.invert?p_(t,e,n):p_(e,t,n):Gu(e,t,n),p_=(e,t,n)=>e.distribute((r)=>xC(r,t,n),(r)=>{let s=r.filter($e);if(s.length===0)return q.init("union",e.branches,t.branches);if(s.length<e.branches.length||!e.branches.every((l,c)=>l.rawIn.equals(s[c].rawIn)))return n.$.parseSchema(s);let o;if(s.length===1){let l=s[0];if(!o)return l;return n.$.node("morph",{...l.inner,in:l.rawIn.configure(o,"self")})}let a={branches:s};if(o)a.meta=o;return n.$.parseSchema(a)}),xC=(e,t,n)=>{if(e.hasKind("morph")){let s=[...e.morphs];if(e.lastMorphIfNode){let o=ke(e.lastMorphIfNode,t,n);if(o instanceof q)return o;s[s.length-1]=o}else s.push(t);return n.$.node("morph",{morphs:s,in:e.inner.in})}if(t.hasKind("morph")){let s=ke(e,t.rawIn,n);if(s instanceof q)return s;return n.$.node("morph",{morphs:[t],in:s})}return n.$.node("morph",{morphs:[t],in:e})};class Wt extends Ds{constructor(e,t){super(e,t);Object.defineProperty(this,ht,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(e){return At(this,e,this.$)}}class Fn extends Wt{traverseApply=(e,t)=>{if(!this.traverseAllows(e,t))t.errorFromNodeContext(this.errorContext)};compile(e){if(e.traversalKind==="Allows")e.return(this.compiledCondition);else e.if(this.compiledNegation,()=>e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return ar(this.errorContext)}}var lt=(e)=>(t,n)=>{if(Se(t)){if(t.length===0)return;let s=t.map((o)=>n.$.node(e,o));if(e==="predicate")return s;return s.sort((o,a)=>o.hash<a.hash?-1:1)}let r=n.$.node(e,t);return r.hasOpenIntersection()?[r]:r},Ri=(e)=>{let t=e.r.shift();if(!t){let r=e.l.length===0&&e.kind==="structure"?N.intrinsic.unknown.internal:e.ctx.$.node(e.kind,Object.assign(e.baseInner,SC(e.l)),{prereduced:!0});for(let s of e.roots){if(r instanceof q)return r;r=ke(s,r,e.ctx)}return r}let n=!1;for(let r=0;r<e.l.length;r++){let s=ke(e.l[r],t,e.ctx);if(s===null)continue;if(s instanceof q)return s;if(s.isRoot())return e.roots.push(s),e.l.splice(r),Ri(e);if(!n)e.l[r]=s,n=!0;else if(!e.l.includes(s))return he(`Unexpectedly encountered multiple distinct intersection results for refinement ${t}`)}if(!n)e.l.push(t);if(e.kind==="intersection"){if(t.impliedSiblings)for(let r of t.impliedSiblings)bn(e.r,r)}return Ri(e)},$i=(e)=>Object.entries(e).flatMap(([n,r])=>(n in Ta)?r:[]).sort((n,r)=>n.precedence<r.precedence?-1:n.precedence>r.precedence?1:n.kind==="predicate"&&r.kind==="predicate"?0:n.hash<r.hash?-1:1),SC=(e)=>{let t={};for(let n of e)if(n.hasOpenIntersection())t[n.kind]=de(t[n.kind],n);else{if(t[n.kind])return he(`Unexpected intersection of closed refinements of kind ${n.kind}`);t[n.kind]=n}return t},h_=(...e)=>A(m_(...e)),m_=(e,t,n)=>{let r=n.hasKind("morph")?"a morph":n.isUnknown()?"unknown":n.exclude(t).defaultShortDescription;return`${Bg(e)} operand must be ${t.description} (was ${r})`};var g_=(e,t,n)=>new cr(e,t,n,n,null);class Na extends kt{}class cr extends kt{[ht]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(e,t,n,r,s){super((...o)=>{let a=ie(this.names,(l,c)=>{let u=this.arg$.parse(o[l]);if(!u.extends(this.constraints[l]))A(RC(c,this.constraints[l].expression,u.expression));return[c,u]});if(this.defIsLazy()){let l=this.bodyDef(a);return this.$.parse(l)}return this.$.parse(t,{args:a})});this.paramDefs=e,this.bodyDef=t,this.$=n,this.arg$=r,this.hkt=s,this.description=s?new s().description??`a generic type for ${s.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof Na}cacheGetter(e,t){return Object.defineProperty(this,e,{value:t}),t}get json(){return this.cacheGetter("json",{params:this.params.map((e)=>e[1].isUnknown()?e[0]:[e[0],e[1].json]),body:Qg(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((e)=>typeof e==="string"?[e,N.intrinsic.unknown]:[e[0],this.$.parse(e[1])]))}get names(){return this.cacheGetter("names",this.params.map((e)=>e[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map((e)=>e[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}var RC=(e,t,n)=>`${e} must be assignable to ${t} (was ${n})`;var $C=ae({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:(e)=>typeof e==="function"?{predicate:e}:e,defaults:{description:(e)=>`valid according to ${e.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class __ extends Wt{serializedPredicate=Me(this.predicate);compiledCondition=`${this.serializedPredicate}(data, ctx)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=null;expression=this.serializedPredicate;traverseAllows=this.predicate;errorContext={code:"predicate",description:this.description,meta:this.meta};compiledErrorContext=ar(this.errorContext);traverseApply=(e,t)=>{let n=t.currentErrorCount;if(!this.predicate(e,t.external)&&t.currentErrorCount===n)t.errorFromNodeContext(this.errorContext)};compile(e){if(e.traversalKind==="Allows"){e.return(this.compiledCondition);return}e.initializeErrorCount(),e.if(`${this.compiledNegation} && ctx.currentErrorCount === errorCount`,()=>e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(e,t){return t.fallback.predicate({code:"predicate",base:e,predicate:this.predicate})}}var Wu={implementation:$C,Node:__};var kC=ae({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(e)=>Number.isInteger(e)?e:A(EC(e))}},normalize:(e)=>typeof e==="number"?{rule:e}:e,hasAssociatedError:!0,defaults:{description:(e)=>e.rule===1?"an integer":e.rule===2?"even":`a multiple of ${e.rule}`},intersections:{divisor:(e,t,n)=>n.$.node("divisor",{rule:Math.abs(e.rule*t.rule/CC(e.rule,t.rule))})},obviatesBasisDescription:!0});class w_ extends Fn{traverseAllows=(e)=>e%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=N.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(e){if(e.type="integer",this.rule===1)return e;return e.multipleOf=this.rule,e}}var Vu={implementation:kC,Node:w_};var EC=(e)=>`divisor must be an integer (was ${e})`,CC=(e,t)=>{let n,r=e,s=t;while(s!==0)n=s,s=r%s,r=n;return r};class Dt extends Fn{boundOperandKind=PC[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=MC(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${AC[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?TC(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator["0"]==="<"?"upper":"lower";isStricterThan(e){return(this.limitKind==="upper"?this.numericLimit<e.numericLimit:this.numericLimit>e.numericLimit)||this.numericLimit===e.numericLimit&&this.exclusive===!0&&!e.exclusive}overlapsRange(e){if(this.isStricterThan(e))return!1;if(this.numericLimit===e.numericLimit&&(this.exclusive||e.exclusive))return!1;return!0}overlapIsUnit(e){return this.numericLimit===e.numericLimit&&!this.exclusive&&!e.exclusive}}var AC={"<":">=","<=":">",">":"<=",">=":"<"},OC={min:"max",minLength:"maxLength",after:"before"},Fa={parse:(e)=>e||void 0},La=(e)=>(t)=>{if(typeof t==="number")return{rule:t};let{exclusive:n,...r}=t;return n?{...r,rule:e==="minLength"?r.rule+1:r.rule-1}:r},ja=(e)=>(t)=>{if(typeof t==="number"||typeof t==="string"||t instanceof Date)return{rule:t};let{exclusive:n,...r}=t;if(!n)return r;let s=typeof r.rule==="number"?r.rule:typeof r.rule==="string"?new Date(r.rule).valueOf():r.rule.valueOf();return n?{...r,rule:e==="after"?s+1:s-1}:r},Ua=(e)=>typeof e==="string"||typeof e==="number"?new Date(e):e,IC=(e,t)=>`${e} bound must be a positive integer (was ${t})`,ki=(e)=>(t)=>{if(!Number.isInteger(t)||t<0)A(IC(e,t));return t},PC={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},MC=(e,t)=>`${Ge(e,OC)?">":"<"}${t?"":"="}`,TC=(e)=>typeof e==="string"?e:new Date(e).toLocaleString(),y_=(e)=>`Bounded expression ${e} must be exactly one of number, string, Array, or Date`;var DC=ae({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Ua,serialize:(e)=>e.toISOString()}},normalize:ja("after"),defaults:{description:(e)=>`${e.collapsibleLimitString} or later`,actual:Fr},intersections:{after:(e,t)=>e.isStricterThan(t)?e:t}});class b_ extends Dt{impliedBasis=N.intrinsic.Date.internal;collapsibleLimitString=Fr(this.rule);traverseAllows=(e)=>e>=this.rule;reduceJsonSchema(e,t){return t.fallback.date({code:"date",base:e,after:this.rule})}}var zu={implementation:DC,Node:b_};var NC=ae({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Ua,serialize:(e)=>e.toISOString()}},normalize:ja("before"),defaults:{description:(e)=>`${e.collapsibleLimitString} or earlier`,actual:Fr},intersections:{before:(e,t)=>e.isStricterThan(t)?e:t,after:(e,t,n)=>e.overlapsRange(t)?e.overlapIsUnit(t)?n.$.node("unit",{unit:e.rule}):null:q.init("range",e,t)}});class v_ extends Dt{collapsibleLimitString=Fr(this.rule);traverseAllows=(e)=>e<=this.rule;impliedBasis=N.intrinsic.Date.internal;reduceJsonSchema(e,t){return t.fallback.date({code:"date",base:e,before:this.rule})}}var Ju={implementation:NC,Node:v_};var FC=ae({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:ki("exactLength")}},normalize:(e)=>typeof e==="number"?{rule:e}:e,hasAssociatedError:!0,defaults:{description:(e)=>`exactly length ${e.rule}`,actual:(e)=>`${e.length}`},intersections:{exactLength:(e,t,n)=>q.init("unit",n.$.node("unit",{unit:e.rule}),n.$.node("unit",{unit:t.rule}),{path:["length"]}),minLength:(e,t)=>e.rule>=t.rule?e:q.init("range",e,t),maxLength:(e,t)=>e.rule<=t.rule?e:q.init("range",e,t)}});class x_ extends Fn{traverseAllows=(e)=>e.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=N.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(e){switch(e.type){case"string":return e.minLength=this.rule,e.maxLength=this.rule,e;case"array":return e.minItems=this.rule,e.maxItems=this.rule,e;default:return Ee.throwInternalOperandError("exactLength",e)}}}var Xu={implementation:FC,Node:x_};var LC=ae({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:Fa},normalize:(e)=>typeof e==="number"?{rule:e}:e,defaults:{description:(e)=>{if(e.rule===0)return e.exclusive?"negative":"non-positive";return`${e.exclusive?"less than":"at most"} ${e.rule}`}},intersections:{max:(e,t)=>e.isStricterThan(t)?e:t,min:(e,t,n)=>e.overlapsRange(t)?e.overlapIsUnit(t)?n.$.node("unit",{unit:e.rule}):null:q.init("range",e,t)},obviatesBasisDescription:!0});class S_ extends Dt{impliedBasis=N.intrinsic.number.internal;traverseAllows=this.exclusive?(e)=>e<this.rule:(e)=>e<=this.rule;reduceJsonSchema(e){if(this.exclusive)e.exclusiveMaximum=this.rule;else e.maximum=this.rule;return e}}var Yu={implementation:LC,Node:S_};var jC=ae({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:ki("maxLength")}},reduce:(e,t)=>e.rule===0?t.node("exactLength",e):void 0,normalize:La("maxLength"),defaults:{description:(e)=>`at most length ${e.rule}`,actual:(e)=>`${e.length}`},intersections:{maxLength:(e,t)=>e.isStricterThan(t)?e:t,minLength:(e,t,n)=>e.overlapsRange(t)?e.overlapIsUnit(t)?n.$.node("exactLength",{rule:e.rule}):null:q.init("range",e,t)}});class R_ extends Dt{impliedBasis=N.intrinsic.lengthBoundable.internal;traverseAllows=(e)=>e.length<=this.rule;reduceJsonSchema(e){switch(e.type){case"string":return e.maxLength=this.rule,e;case"array":return e.maxItems=this.rule,e;default:return Ee.throwInternalOperandError("maxLength",e)}}}var Zu={implementation:jC,Node:R_};var UC=ae({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:Fa},normalize:(e)=>typeof e==="number"?{rule:e}:e,defaults:{description:(e)=>{if(e.rule===0)return e.exclusive?"positive":"non-negative";return`${e.exclusive?"more than":"at least"} ${e.rule}`}},intersections:{min:(e,t)=>e.isStricterThan(t)?e:t},obviatesBasisDescription:!0});class $_ extends Dt{impliedBasis=N.intrinsic.number.internal;traverseAllows=this.exclusive?(e)=>e>this.rule:(e)=>e>=this.rule;reduceJsonSchema(e){if(this.exclusive)e.exclusiveMinimum=this.rule;else e.minimum=this.rule;return e}}var Qu={implementation:UC,Node:$_};var BC=ae({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:ki("minLength")}},reduce:(e)=>e.rule===0?N.intrinsic.unknown:void 0,normalize:La("minLength"),defaults:{description:(e)=>e.rule===1?"non-empty":`at least length ${e.rule}`,actual:(e)=>e.length===0?"":`${e.length}`},intersections:{minLength:(e,t)=>e.isStricterThan(t)?e:t}});class k_ extends Dt{impliedBasis=N.intrinsic.lengthBoundable.internal;traverseAllows=(e)=>e.length>=this.rule;reduceJsonSchema(e){switch(e.type){case"string":return e.minLength=this.rule,e;case"array":return e.minItems=this.rule,e;default:return Ee.throwInternalOperandError("minLength",e)}}}var ed={implementation:BC,Node:k_};var E_={min:Qu.implementation,max:Yu.implementation,minLength:ed.implementation,maxLength:Zu.implementation,exactLength:Xu.implementation,after:zu.implementation,before:Ju.implementation},C_={min:Qu.Node,max:Yu.Node,minLength:ed.Node,maxLength:Zu.Node,exactLength:Xu.Node,after:zu.Node,before:Ju.Node};var qC=ae({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:(e)=>typeof e==="string"?{rule:e}:e instanceof RegExp?e.flags?{rule:e.source,flags:e.flags}:{rule:e.source}:e,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:(e)=>`matched by ${e.rule}`},intersections:{pattern:()=>null}});class A_ extends Fn{instance=new RegExp(this.rule,this.flags);expression=`${this.instance}`;traverseAllows=this.instance.test.bind(this.instance);compiledCondition=`${this.expression}.test(data)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=N.intrinsic.string.internal;reduceJsonSchema(e,t){if(e.pattern)return t.fallback.patternIntersection({code:"patternIntersection",base:e,pattern:this.rule});return e.pattern=this.rule,e}}var td={implementation:qC,Node:A_};var Fs=(e,t)=>{let n=HC(e);if(t&&!t.includes(n))return A(`Root of kind ${n} should be one of ${t}`);return n},HC=(e)=>{if(X(e,"root"))return e.kind;if(typeof e==="string")return e[0]==="$"?"alias":(e in Rt)?"domain":"proto";if(typeof e==="function")return"proto";if(typeof e!=="object"||e===null)return A(O_(e));if("morphs"in e)return"morph";if("branches"in e||Se(e))return"union";if("unit"in e)return"unit";if("reference"in e)return"alias";let t=Object.keys(e);if(t.length===0||t.some((n)=>(n in Ta)))return"intersection";if("proto"in e)return"proto";if("domain"in e)return"domain";return A(O_(e))},O_=(e)=>`${se(e)} is not a valid type schema`,I_={},KC=(e)=>Se(e)?e.map((t)=>t.collapsibleJson):e.collapsibleJson,mt={};N.nodesByRegisteredId=mt;var nd=(e)=>(I_[e]??=0,`${e}${++I_[e]}`),rd=(e)=>{let t=Ei[e.kind],n=t.applyConfig?.(e.def,e.$.resolvedConfig)??e.def,r={},{meta:s,...o}=n,a=s===void 0?{}:typeof s==="string"?{description:s}:s,l=ku(o).sort(([u],[d])=>vi(u)?vi(d)?xi(u)-xi(d):1:vi(d)?-1:u<d?-1:1).filter(([u,d])=>{if(u.startsWith("meta.")){let f=u.slice(5);return a[f]=d,!1}return!0});for(let u of l){let d=u[0],f=t.keys[d];if(!f)return A(`Key ${d} is not valid on ${e.kind} schema`);let p=f.parse?f.parse(u[1],e):u[1];if(p!==$t&&(p!==void 0||f.preserveUndefined))r[d]=p}if(t.reduce&&!e.prereduced){let u=t.reduce(r,e.$);if(u){if(u instanceof q)return u.throw();return GC(u,a)}}return id({id:e.id,kind:e.kind,inner:r,meta:a,$:e.$})},id=({id:e,kind:t,inner:n,meta:r,$:s,ignoreCache:o})=>{let a=Ei[t],l=ku(n),c=[],u={};for(let[x,S]of l){let P=a.keys[x],M=P.serialize??(P.child?KC:Gt);if(u[x]=M(S),P.child===!0){let k=S;if(Se(k))c.push(...k);else c.push(k)}else if(typeof P.child==="function")c.push(...P.child(S))}if(a.finalizeInnerJson)u=a.finalizeInnerJson(u);let d={...u},f={};if(!vn(r))f=ie(r,(x,S)=>[x,x==="examples"?S:Gt(S)]),d.meta=Ba(f,"description",!0);u=Ba(u,a.collapsibleKey,!1);let p=JSON.stringify({kind:t,...u});d=Ba(d,a.collapsibleKey,!1);let h=Ba(d,a.collapsibleKey,!0),g=JSON.stringify({kind:t,...d});if(s.nodesByHash[g]&&!o)return s.nodesByHash[g];let w={id:e,kind:t,impl:a,inner:n,innerEntries:l,innerJson:u,innerHash:p,meta:r,metaJson:f,json:d,hash:g,collapsibleJson:h,children:c};if(t!=="intersection"){for(let x in n)if(x!=="in"&&x!=="out")w[x]=n[x]}let b=new M_[t](w,s);return s.nodesByHash[g]=b},P_=(e,t)=>{if(e.id===t)return e;if($e(mt[t]))he(`Unexpected attempt to overwrite node id ${t}`);return id({id:t,kind:e.kind,inner:e.inner,meta:e.meta,$:e.$,ignoreCache:!0})},GC=(e,t,n)=>{if(n&&$e(mt[n]))he(`Unexpected attempt to overwrite node id ${n}`);return id({id:n??nd(t.alias??e.kind),kind:e.kind,inner:e.inner,meta:t,$:e.$})},Ba=(e,t,n)=>{let r=Object.keys(e);if(r.length===1&&r[0]===t){let s=e[t];if(n)return s;if(St(s,"object")&&(Object.keys(s).length===1||Array.isArray(s)))return s}return e};var Ls=(e,t,n)=>{if(e.key!==t.key)return null;let r=e.key,s=ke(e.value,t.value,n),o=e.required||t.required?"required":"optional";if(s instanceof q)if(o==="optional")s=N.intrinsic.never.internal;else return s.withPrefixKey(e.key,e.required&&t.required?"required":"optional");if(o==="required")return n.$.node("required",{key:r,value:s});let a=e.hasDefault()?t.hasDefault()?e.default===t.default?e.default:A(sd(e.default,t.default)):e.default:t.hasDefault()?t.default:$t;return n.$.node("optional",{key:r,value:s,default:a})};class js extends Wt{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=N.intrinsic.object.internal;serializedKey=on(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=de(this.value.flatRefs.map((e)=>ln([this.key,...e.path],e.node)),ln([this.key],this.value));_transform(e,t){t.path.push(this.key);let n=super._transform(e,t);return t.path.pop(),n}hasDefault(){return"default"in this.inner}traverseAllows=(e,t)=>{if(this.key in e)return Ct(this.key,()=>this.value.traverseAllows(e[this.key],t),t);return this.optional};traverseApply=(e,t)=>{if(this.key in e)Ct(this.key,()=>this.value.traverseApply(e[this.key],t),t);else if(this.hasKind("required"))t.errorFromNodeContext(this.errorContext)};compile(e){if(e.if(`${this.serializedKey} in data`,()=>e.traverseKey(this.serializedKey,`data${e.prop(this.key)}`,this.value)),this.hasKind("required"))e.else(()=>e.traversalKind==="Apply"?e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):e.return(!1));if(e.traversalKind==="Allows")e.return(!0)}}var sd=(e,t)=>`Invalid intersection of default values ${se(e)} & ${se(t)}`;var WC=ae({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(e,t)=>t.$.parseSchema(e)},default:{preserveUndefined:!0}},normalize:(e)=>e,reduce:(e,t)=>{if(t.resolvedConfig.exactOptionalPropertyTypes===!1){if(!e.value.allows(void 0))return t.node("optional",{...e,value:e.value.or(ee.undefined)},{prereduced:!0})}},defaults:{description:(e)=>`${e.compiledKey}?: ${e.value.description}`},intersections:{optional:Ls}});class T_ extends js{constructor(...e){super(...e);if("default"in this.inner)Bs(this.value,this.inner.default,this.key)}get rawIn(){let e=super.rawIn;if(!this.hasDefault())return e;return this.$.node("optional",Ea(e.inner,{default:!0}),{prereduced:!0})}get outProp(){if(!this.hasDefault())return this;let{default:e,...t}=this.inner;return this.cacheGetter("outProp",this.$.node("required",t,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${se(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=zC(this);defaultValueMorphRef=this.defaultValueMorph&&Me(this.defaultValueMorph)}var Us={implementation:WC,Node:T_},VC={},zC=(e)=>{if(!e.hasDefault())return;let t=`{${e.compiledKey}: ${e.value.id} = ${Gt(e.default)}}`;return VC[t]??=od(e.key,e.value,e.default)},od=(e,t,n)=>{if(typeof n==="function")return t.includesTransform?(s,o)=>(Ct(e,()=>t(s[e]=n(),o),o),s):(s)=>(s[e]=n(),s);let r=t.includesTransform?t.assert(n):n;return St(r,"object")?(s,o)=>(Ct(e,()=>t(s[e]=n,o),o),s):(s)=>(s[e]=r,s)},Bs=(e,t,n)=>{let r=ir(t);if(St(t,"object")&&!r)A(JC(n));let s=e.in(r?t():t);if(s instanceof Et){if(n===null)A(`Default ${s.summary}`);let o=s.transform((a)=>a.transform((l)=>({...l,prefixPath:[n]})));A(`Default for ${o.summary}`)}return t},JC=(e)=>`Non-primitive default ${e===null?"":typeof e==="number"?`for value at [${e}] `:`for ${on(e)} `}must be specified as a function like () => ({my: 'object'})`;class Vt extends Ds{constructor(e,t){super(e,t);Object.defineProperty(this,ht,{value:"root",enumerable:!1})}get rawIn(){return super.rawIn}get rawOut(){return super.rawOut}get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:(e)=>{let t=this(e);if(t instanceof Et)return t;return{value:t}},jsonSchema:{input:(e)=>this.rawIn.toJsonSchema({target:D_(e.target),...e.libraryOptions}),output:(e)=>this.rawOut.toJsonSchema({target:D_(e.target),...e.libraryOptions})}}}as(){return this}brand(e){if(e==="")return A(XC);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(e,t){let n=this.branches.map(e);return t?.(n)??n}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(e={}){let t=Uu(this.$.resolvedConfig.toJsonSchema,e);t.useRefs||=this.isCyclic;let n=typeof t.dialect==="string"?{$schema:t.dialect}:{};if(Object.assign(n,this.toJsonSchemaRecurse(t)),t.useRefs){let r=ie(this.references,(s,o)=>o.isRoot()&&!o.alwaysExpandJsonSchema?[o.id,o.toResolvedJsonSchema(t)]:[]);if(t.target==="draft-07")Object.assign(n,{definitions:r});else n.$defs=r}return n}toJsonSchemaRecurse(e){if(e.useRefs&&!this.alwaysExpandJsonSchema)return{$ref:`#/${e.target==="draft-07"?"definitions":"$defs"}/${this.id}`};return this.toResolvedJsonSchema(e)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(e){let t=this.innerToJsonSchema(e);return Object.assign(t,this.metaJson)}intersect(e){let t=this.$.parseDefinition(e),n=this.rawIntersect(t);if(n instanceof q)return n;return this.$.finalize(n)}rawIntersect(e){return At(this,e,this.$)}toNeverIfDisjoint(){return this}and(e){let t=this.intersect(e);return t instanceof q?t.throw():t}rawAnd(e){let t=this.rawIntersect(e);return t instanceof q?t.throw():t}or(e){let t=this.$.parseDefinition(e);return this.$.finalize(this.rawOr(t))}rawOr(e){let t=[...this.branches,...e.branches];return this.$.node("union",t)}map(e){return this.$.schema(this.applyStructuralOperation("map",[e]))}pick(...e){return this.$.schema(this.applyStructuralOperation("pick",e))}omit(...e){return this.$.schema(this.applyStructuralOperation("omit",e))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let e=this.applyStructuralOperation("keyof",[]).reduce((t,n)=>t.intersect(n).toNeverIfDisjoint(),N.intrinsic.unknown.internal);if(e.branches.length===0)A(Ku(`keyof ${this.expression}`));return this._keyof=this.$.finalize(e)}get props(){if(this.branches.length!==1)return A(ZC(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(e){let t=this.$.parseDefinition(e);return this.$.schema(t.distribute((n)=>this.applyStructuralOperation("merge",[N_(n)??A(F_("merge",n.expression))])))}applyStructuralOperation(e,t){return this.distribute((n)=>{if(n.equals(N.intrinsic.object)&&e!=="merge")return n;let r=N_(n);if(!r)A(F_(e,n.expression));if(e==="keyof")return r.keyof();if(e==="get")return r.get(...t);if(e==="props")return r.props;let s=e==="required"?"require":e==="partial"?"optionalize":e;return this.$.node("intersection",{domain:"object",structure:r[s](...t)})})}get(...e){if(e[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",e))}extract(e){let t=this.$.parseDefinition(e);return this.$.schema(this.branches.filter((n)=>n.extends(t)))}exclude(e){let t=this.$.parseDefinition(e);return this.$.schema(this.branches.filter((n)=>!n.extends(t)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(e){return!(this.intersect(e)instanceof q)}extends(e){if(this.isNever())return!0;let t=this.intersect(e);return!(t instanceof q)&&this.equals(t)}ifExtends(e){return this.extends(e)?this:void 0}subsumes(e){return this.$.parseDefinition(e).extends(this)}configure(e,t="shallow"){return this.configureReferences(e,t)}describe(e,t="shallow"){return this.configure({description:e},t)}optional(){return[this,"?"]}default(e){return Bs(this,e,null),[this,"=",e]}from(e){return this.assert(e)}_pipe(...e){let t=e.reduce((n,r)=>n.rawPipeOnce(r),this);return this.$.finalize(t)}tryPipe(...e){let t=e.reduce((n,r)=>n.rawPipeOnce(X(r,"root")?r:(s,o)=>{try{return r(s,o)}catch(a){return o.error({code:"predicate",predicate:r,actual:`aborted due to error:
594
594
  ${a}
595
- `})}}),this);return this.$.finalize(t)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(e){return this.$.finalize(this.toNode(this.$.parseDefinition(e)))}toNode(e){let t=As(this,e,this.$);if(t instanceof q)return t.throw();return t}rawPipeOnce(e){if(X(e,"root"))return this.toNode(e);return this.distribute((t)=>t.hasKind("morph")?this.$.node("morph",{in:t.inner.in,morphs:[...t.morphs,e]}):this.$.node("morph",{in:t,morphs:[e]}),this.$.parseSchema)}narrow(e){return this.constrainOut("predicate",e)}constrain(e,t){return this._constrain("root",e,t)}constrainIn(e,t){return this._constrain("in",e,t)}constrainOut(e,t){return this._constrain("out",e,t)}_constrain(e,t,n){let r=this.$.node(t,n);if(r.isRoot())return r.isUnknown()?this:he(`Unexpected constraint node ${r}`);let s=e==="root"?this:e==="in"?this.rawIn:this.rawOut;if(s.hasKind("morph")||r.impliedBasis&&!s.extends(r.impliedBasis))return Hg(t,r.impliedBasis,this);let o=this.$.node("intersection",{[r.kind]:r}),a=e==="out"?As(this,o,this.$):Ct(this,o,this.$);if(a instanceof q)a.throw();return this.$.finalize(a)}onUndeclaredKey(e){let t=typeof e==="string"?e:e.rule,n=typeof e==="string"?!1:e.deep;return this.$.finalize(this.transform((r,s)=>r==="structure"?t==="ignore"?ya(s,{undeclared:1}):{...s,undeclared:t}:s,n?void 0:{shouldTransform:(r)=>!Ht(hi,r.kind)}))}hasEqualMorphs(e){if(!this.includesTransform&&!e.includesTransform)return!0;if(!Pn(this.shallowMorphs,e.shallowMorphs))return!1;if(!Pn(this.flatMorphs,e.flatMorphs,{isEqual:(t,n)=>t.propString===n.propString&&(t.node.hasKind("morph")&&n.node.hasKind("morph")?t.node.hasEqualMorphs(n.node):t.node.hasKind("intersection")&&n.node.hasKind("intersection")?t.node.structure?.structuralMorphRef===n.node.structure?.structuralMorphRef:!1)}))return!1;return!0}onDeepUndeclaredKey(e){return this.onUndeclaredKey({rule:e,deep:!0})}filter(e){return this.constrainIn("predicate",e)}divisibleBy(e){return this.constrain("divisor",e)}matching(e){return this.constrain("pattern",e)}atLeast(e){return this.constrain("min",e)}atMost(e){return this.constrain("max",e)}moreThan(e){return this.constrain("min",Ri(e))}lessThan(e){return this.constrain("max",Ri(e))}atLeastLength(e){return this.constrain("minLength",e)}atMostLength(e){return this.constrain("maxLength",e)}moreThanLength(e){return this.constrain("minLength",Ri(e))}lessThanLength(e){return this.constrain("maxLength",Ri(e))}exactlyLength(e){return this.constrain("exactLength",e)}atOrAfter(e){return this.constrain("after",e)}atOrBefore(e){return this.constrain("before",e)}laterThan(e){return this.constrain("after",Ri(e))}earlierThan(e){return this.constrain("before",Ri(e))}}var l0="Expected a non-empty brand name after #",p_=["draft-2020-12","draft-07"],c0=(e)=>`JSONSchema target '${e}' is not supported (must be ${p_.map((t)=>`"${t}"`).join(" or ")})`,u_=(e)=>{if(!Ht(p_,e))C(c0(e));return e},Ri=(e)=>typeof e==="object"&&!(e instanceof Date)?{...e,exclusive:!0}:{rule:e,exclusive:!0},Ts=(e,t)=>X(t,"root")?X(e,"root")?e.extends(t):t.allows(e):X(e,"root")?e.hasUnit(t):t===e,d_=(e)=>{if(e.hasKind("morph"))return null;if(e.hasKind("intersection"))return e.inner.structure??(e.basis?.domain==="object"?e.$.bindReference(N.intrinsic.emptyStructure):null);if(e.isBasis()&&e.domain==="object")return e.$.bindReference(N.intrinsic.emptyStructure);return null},u0=(e)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
596
- ${e}`,f_=(e,t)=>`${e} operand must be an object (was ${t})`;var bn=(e,t)=>ie(Ea(e),(n,r)=>[r,t]);var d0=(e)=>typeof e==="string"?{reference:e}:e,h_=(e)=>e instanceof q?N.intrinsic.never.internal:e,f0=ae({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(e)=>e.startsWith("$")?e:`$ark.${e}`},resolve:{}},normalize:d0,defaults:{description:(e)=>e.reference},intersections:{alias:(e,t,n)=>n.$.lazilyResolve(()=>h_(ke(e.resolution,t.resolution,n)),`${e.reference}${n.pipe?"=>":"&"}${t.reference}`),...bn("alias",(e,t,n)=>{if(t.isUnknown())return e;if(t.isNever())return t;if(t.isBasis()&&!t.overlaps(N.intrinsic.object))return q.init("assignability",N.intrinsic.object,t);return n.$.lazilyResolve(()=>h_(ke(e.resolution,t,n)),`${e.reference}${n.pipe?"=>":"&"}${t.id}`)})}});class m_ extends Gt{expression=this.reference;structure=void 0;get resolution(){let e=this._resolve();return mt[this.id]=e}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]==="$")return this.$.resolveRoot(this.reference.slice(1));let e=this.reference,t=mt[e],n=[];while(X(t,"context")){if(n.includes(t.id))return C(p0(t.id,n));n.push(t.id),t=mt[t.id]}if(!X(t,"root"))return he(`Unexpected resolution for reference ${this.reference}
595
+ `})}}),this);return this.$.finalize(t)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(e){return this.$.finalize(this.toNode(this.$.parseDefinition(e)))}toNode(e){let t=Ns(this,e,this.$);if(t instanceof q)return t.throw();return t}rawPipeOnce(e){if(X(e,"root"))return this.toNode(e);return this.distribute((t)=>t.hasKind("morph")?this.$.node("morph",{in:t.inner.in,morphs:[...t.morphs,e]}):this.$.node("morph",{in:t,morphs:[e]}),this.$.parseSchema)}narrow(e){return this.constrainOut("predicate",e)}constrain(e,t){return this._constrain("root",e,t)}constrainIn(e,t){return this._constrain("in",e,t)}constrainOut(e,t){return this._constrain("out",e,t)}_constrain(e,t,n){let r=this.$.node(t,n);if(r.isRoot())return r.isUnknown()?this:he(`Unexpected constraint node ${r}`);let s=e==="root"?this:e==="in"?this.rawIn:this.rawOut;if(s.hasKind("morph")||r.impliedBasis&&!s.extends(r.impliedBasis))return h_(t,r.impliedBasis,this);let o=this.$.node("intersection",{[r.kind]:r}),a=e==="out"?Ns(this,o,this.$):At(this,o,this.$);if(a instanceof q)a.throw();return this.$.finalize(a)}onUndeclaredKey(e){let t=typeof e==="string"?e:e.rule,n=typeof e==="string"?!1:e.deep;return this.$.finalize(this.transform((r,s)=>r==="structure"?t==="ignore"?Ea(s,{undeclared:1}):{...s,undeclared:t}:s,n?void 0:{shouldTransform:(r)=>!Kt(yi,r.kind)}))}hasEqualMorphs(e){if(!this.includesTransform&&!e.includesTransform)return!0;if(!Tn(this.shallowMorphs,e.shallowMorphs))return!1;if(!Tn(this.flatMorphs,e.flatMorphs,{isEqual:(t,n)=>t.propString===n.propString&&(t.node.hasKind("morph")&&n.node.hasKind("morph")?t.node.hasEqualMorphs(n.node):t.node.hasKind("intersection")&&n.node.hasKind("intersection")?t.node.structure?.structuralMorphRef===n.node.structure?.structuralMorphRef:!1)}))return!1;return!0}onDeepUndeclaredKey(e){return this.onUndeclaredKey({rule:e,deep:!0})}filter(e){return this.constrainIn("predicate",e)}divisibleBy(e){return this.constrain("divisor",e)}matching(e){return this.constrain("pattern",e)}atLeast(e){return this.constrain("min",e)}atMost(e){return this.constrain("max",e)}moreThan(e){return this.constrain("min",Ci(e))}lessThan(e){return this.constrain("max",Ci(e))}atLeastLength(e){return this.constrain("minLength",e)}atMostLength(e){return this.constrain("maxLength",e)}moreThanLength(e){return this.constrain("minLength",Ci(e))}lessThanLength(e){return this.constrain("maxLength",Ci(e))}exactlyLength(e){return this.constrain("exactLength",e)}atOrAfter(e){return this.constrain("after",e)}atOrBefore(e){return this.constrain("before",e)}laterThan(e){return this.constrain("after",Ci(e))}earlierThan(e){return this.constrain("before",Ci(e))}}var XC="Expected a non-empty brand name after #",L_=["draft-2020-12","draft-07"],YC=(e)=>`JSONSchema target '${e}' is not supported (must be ${L_.map((t)=>`"${t}"`).join(" or ")})`,D_=(e)=>{if(!Kt(L_,e))A(YC(e));return e},Ci=(e)=>typeof e==="object"&&!(e instanceof Date)?{...e,exclusive:!0}:{rule:e,exclusive:!0},qs=(e,t)=>X(t,"root")?X(e,"root")?e.extends(t):t.allows(e):X(e,"root")?e.hasUnit(t):t===e,N_=(e)=>{if(e.hasKind("morph"))return null;if(e.hasKind("intersection"))return e.inner.structure??(e.basis?.domain==="object"?e.$.bindReference(N.intrinsic.emptyStructure):null);if(e.isBasis()&&e.domain==="object")return e.$.bindReference(N.intrinsic.emptyStructure);return null},ZC=(e)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
596
+ ${e}`,F_=(e,t)=>`${e} operand must be an object (was ${t})`;var xn=(e,t)=>ie(Da(e),(n,r)=>[r,t]);var QC=(e)=>typeof e==="string"?{reference:e}:e,j_=(e)=>e instanceof q?N.intrinsic.never.internal:e,e0=ae({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(e)=>e.startsWith("$")?e:`$ark.${e}`},resolve:{}},normalize:QC,defaults:{description:(e)=>e.reference},intersections:{alias:(e,t,n)=>n.$.lazilyResolve(()=>j_(ke(e.resolution,t.resolution,n)),`${e.reference}${n.pipe?"=>":"&"}${t.reference}`),...xn("alias",(e,t,n)=>{if(t.isUnknown())return e;if(t.isNever())return t;if(t.isBasis()&&!t.overlaps(N.intrinsic.object))return q.init("assignability",N.intrinsic.object,t);return n.$.lazilyResolve(()=>j_(ke(e.resolution,t,n)),`${e.reference}${n.pipe?"=>":"&"}${t.id}`)})}});class U_ extends Vt{expression=this.reference;structure=void 0;get resolution(){let e=this._resolve();return mt[this.id]=e}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]==="$")return this.$.resolveRoot(this.reference.slice(1));let e=this.reference,t=mt[e],n=[];while(X(t,"context")){if(n.includes(t.id))return A(t0(t.id,n));n.push(t.id),t=mt[t.id]}if(!X(t,"root"))return he(`Unexpected resolution for reference ${this.reference}
597
597
  Seen: [${n.join("->")}]
598
- Resolution: ${se(t)}`);return t}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;let e=this.reference.slice(1),t=this.$.resolutions[e];if(typeof t==="string")return t;if(X(t,"root"))return t.id;return he(`Unexpected resolution for reference ${this.reference}: ${se(t)}`)}get defaultShortDescription(){return St.object}innerToJsonSchema(e){return this.resolution.toJsonSchemaRecurse(e)}traverseAllows=(e,t)=>{let n=t.seen[this.reference];if(n?.includes(e))return!0;return t.seen[this.reference]=de(n,e),this.resolution.traverseAllows(e,t)};traverseApply=(e,t)=>{let n=t.seen[this.reference];if(n?.includes(e))return;t.seen[this.reference]=de(n,e),this.resolution.traverseApply(e,t)};compile(e){let t=this.resolutionId;e.if(`ctx.seen.${t} && ctx.seen.${t}.includes(data)`,()=>e.return(!0)),e.if(`!ctx.seen.${t}`,()=>e.line(`ctx.seen.${t} = []`)),e.line(`ctx.seen.${t}.push(data)`),e.return(e.invoke(t))}}var p0=(e,t)=>`Alias '${e}' has a shallow resolution cycle: ${[...t,e].join("->")}`,Fs={implementation:f0,Node:m_};class Tr extends Gt{traverseApply=(e,t)=>{if(!this.traverseAllows(e,t))t.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return ir(this.errorContext)}compile(e){if(e.traversalKind==="Allows")e.return(this.compiledCondition);else e.if(this.compiledNegation,()=>e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}}var h0=ae({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(e)=>typeof e==="string"?{domain:e}:fi(e,"numberAllowsNaN")&&e.domain!=="number"?C(Ta.writeBadAllowNanMessage(e.domain)):e,applyConfig:(e,t)=>e.numberAllowsNaN===void 0&&e.domain==="number"&&t.numberAllowsNaN?{...e,numberAllowsNaN:!0}:e,defaults:{description:(e)=>St[e.domain],actual:(e)=>Number.isNaN(e)?"NaN":St[Ke(e)]},intersections:{domain:(e,t)=>e.domain==="number"&&t.domain==="number"?e.numberAllowsNaN?t:e:q.init("domain",e,t)}});class g_ extends Tr{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?(e)=>typeof e==="number"&&!Number.isNaN(e):(e)=>Ke(e)===this.domain;compiledCondition=this.domain==="object"?'((typeof data === "object" && data !== null) || typeof data === "function")':`typeof data === "${this.domain}"${this.requiresNaNCheck?" && !Number.isNaN(data)":""}`;compiledNegation=this.domain==="object"?'((typeof data !== "object" || data === null) && typeof data !== "function")':`typeof data !== "${this.domain}"${this.requiresNaNCheck?" || Number.isNaN(data)":""}`;expression=this.numberAllowsNaN?"number | NaN":this.domain;get nestableExpression(){return this.numberAllowsNaN?`(${this.expression})`:this.expression}get defaultShortDescription(){return St[this.domain]}innerToJsonSchema(e){if(this.domain==="bigint"||this.domain==="symbol")return e.fallback.domain({code:"domain",base:{},domain:this.domain});return{type:this.domain}}}var Ta={implementation:h0,Node:g_,writeBadAllowNanMessage:(e)=>`numberAllowsNaN may only be specified with domain "number" (was ${e})`};var m0=ae({kind:"intersection",hasAssociatedError:!0,normalize:(e)=>{if($e(e))return e;let{structure:t,...n}=e,r=!!t,s=t??{},o=ie(n,(a,l)=>{if(We(a,Tg)){if(r)C(`Flattened structure key ${a} cannot be specified alongside a root 'structure' key.`);return s[a]=l,[]}return[a,l]});if(X(s,"constraint")||!yn(s))o.structure=s;return o},finalizeInnerJson:({structure:e,...t})=>Rt(e,"object")?{...e,...t}:t,keys:{domain:{child:!0,parse:(e,t)=>t.$.node("domain",e)},proto:{child:!0,parse:(e,t)=>t.$.node("proto",e)},structure:{child:!0,parse:(e,t)=>t.$.node("structure",e),serialize:(e)=>{if(!e.sequence?.minLength)return e.collapsibleJson;let{sequence:t,...n}=e.collapsibleJson,{minVariadicLength:r,...s}=t,o=s.variadic&&Object.keys(s).length===1?s.variadic:s;return{...n,sequence:o}}},divisor:{child:!0,parse:lt("divisor")},max:{child:!0,parse:lt("max")},min:{child:!0,parse:lt("min")},maxLength:{child:!0,parse:lt("maxLength")},minLength:{child:!0,parse:lt("minLength")},exactLength:{child:!0,parse:lt("exactLength")},before:{child:!0,parse:lt("before")},after:{child:!0,parse:lt("after")},pattern:{child:!0,parse:lt("pattern")},predicate:{child:!0,parse:lt("predicate")}},reduce:(e,t)=>__({},e,{$:t,invert:!1,pipe:!1}),defaults:{description:(e)=>{if(e.children.length===0)return"unknown";if(e.structure)return e.structure.description;let t=[];if(e.basis&&!e.prestructurals.some((n)=>n.impl.obviatesBasisDescription))t.push(e.basis.description);if(e.prestructurals.length){let n=e.prestructurals.slice().sort((r,s)=>r.kind==="min"&&s.kind==="max"?-1:0).map((r)=>r.description);t.push(...n)}if(e.inner.predicate)t.push(...e.inner.predicate.map((n)=>n.description));return t.join(" and ")},expected:(e)=>` \u25E6 ${e.errors.map((t)=>t.expected).join(`
598
+ Resolution: ${se(t)}`);return t}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;let e=this.reference.slice(1),t=this.$.resolutions[e];if(typeof t==="string")return t;if(X(t,"root"))return t.id;return he(`Unexpected resolution for reference ${this.reference}: ${se(t)}`)}get defaultShortDescription(){return Rt.object}innerToJsonSchema(e){return this.resolution.toJsonSchemaRecurse(e)}traverseAllows=(e,t)=>{let n=t.seen[this.reference];if(n?.includes(e))return!0;return t.seen[this.reference]=de(n,e),this.resolution.traverseAllows(e,t)};traverseApply=(e,t)=>{let n=t.seen[this.reference];if(n?.includes(e))return;t.seen[this.reference]=de(n,e),this.resolution.traverseApply(e,t)};compile(e){let t=this.resolutionId;e.if(`ctx.seen.${t} && ctx.seen.${t}.includes(data)`,()=>e.return(!0)),e.if(`!ctx.seen.${t}`,()=>e.line(`ctx.seen.${t} = []`)),e.line(`ctx.seen.${t}.push(data)`),e.return(e.invoke(t))}}var t0=(e,t)=>`Alias '${e}' has a shallow resolution cycle: ${[...t,e].join("->")}`,Hs={implementation:e0,Node:U_};class Lr extends Vt{traverseApply=(e,t)=>{if(!this.traverseAllows(e,t))t.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return ar(this.errorContext)}compile(e){if(e.traversalKind==="Allows")e.return(this.compiledCondition);else e.if(this.compiledNegation,()=>e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}}var n0=ae({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(e)=>typeof e==="string"?{domain:e}:_i(e,"numberAllowsNaN")&&e.domain!=="number"?A(qa.writeBadAllowNanMessage(e.domain)):e,applyConfig:(e,t)=>e.numberAllowsNaN===void 0&&e.domain==="number"&&t.numberAllowsNaN?{...e,numberAllowsNaN:!0}:e,defaults:{description:(e)=>Rt[e.domain],actual:(e)=>Number.isNaN(e)?"NaN":Rt[Ke(e)]},intersections:{domain:(e,t)=>e.domain==="number"&&t.domain==="number"?e.numberAllowsNaN?t:e:q.init("domain",e,t)}});class B_ extends Lr{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?(e)=>typeof e==="number"&&!Number.isNaN(e):(e)=>Ke(e)===this.domain;compiledCondition=this.domain==="object"?'((typeof data === "object" && data !== null) || typeof data === "function")':`typeof data === "${this.domain}"${this.requiresNaNCheck?" && !Number.isNaN(data)":""}`;compiledNegation=this.domain==="object"?'((typeof data !== "object" || data === null) && typeof data !== "function")':`typeof data !== "${this.domain}"${this.requiresNaNCheck?" || Number.isNaN(data)":""}`;expression=this.numberAllowsNaN?"number | NaN":this.domain;get nestableExpression(){return this.numberAllowsNaN?`(${this.expression})`:this.expression}get defaultShortDescription(){return Rt[this.domain]}innerToJsonSchema(e){if(this.domain==="bigint"||this.domain==="symbol")return e.fallback.domain({code:"domain",base:{},domain:this.domain});return{type:this.domain}}}var qa={implementation:n0,Node:B_,writeBadAllowNanMessage:(e)=>`numberAllowsNaN may only be specified with domain "number" (was ${e})`};var r0=ae({kind:"intersection",hasAssociatedError:!0,normalize:(e)=>{if($e(e))return e;let{structure:t,...n}=e,r=!!t,s=t??{},o=ie(n,(a,l)=>{if(Ge(a,s_)){if(r)A(`Flattened structure key ${a} cannot be specified alongside a root 'structure' key.`);return s[a]=l,[]}return[a,l]});if(X(s,"constraint")||!vn(s))o.structure=s;return o},finalizeInnerJson:({structure:e,...t})=>St(e,"object")?{...e,...t}:t,keys:{domain:{child:!0,parse:(e,t)=>t.$.node("domain",e)},proto:{child:!0,parse:(e,t)=>t.$.node("proto",e)},structure:{child:!0,parse:(e,t)=>t.$.node("structure",e),serialize:(e)=>{if(!e.sequence?.minLength)return e.collapsibleJson;let{sequence:t,...n}=e.collapsibleJson,{minVariadicLength:r,...s}=t,o=s.variadic&&Object.keys(s).length===1?s.variadic:s;return{...n,sequence:o}}},divisor:{child:!0,parse:lt("divisor")},max:{child:!0,parse:lt("max")},min:{child:!0,parse:lt("min")},maxLength:{child:!0,parse:lt("maxLength")},minLength:{child:!0,parse:lt("minLength")},exactLength:{child:!0,parse:lt("exactLength")},before:{child:!0,parse:lt("before")},after:{child:!0,parse:lt("after")},pattern:{child:!0,parse:lt("pattern")},predicate:{child:!0,parse:lt("predicate")}},reduce:(e,t)=>q_({},e,{$:t,invert:!1,pipe:!1}),defaults:{description:(e)=>{if(e.children.length===0)return"unknown";if(e.structure)return e.structure.description;let t=[];if(e.basis&&!e.prestructurals.some((n)=>n.impl.obviatesBasisDescription))t.push(e.basis.description);if(e.prestructurals.length){let n=e.prestructurals.slice().sort((r,s)=>r.kind==="min"&&s.kind==="max"?-1:0).map((r)=>r.description);t.push(...n)}if(e.inner.predicate)t.push(...e.inner.predicate.map((n)=>n.description));return t.join(" and ")},expected:(e)=>` \u25E6 ${e.errors.map((t)=>t.expected).join(`
599
599
  \u25E6 `)}`,problem:(e)=>`(${e.actual}) must be...
600
- ${e.expected}`},intersections:{intersection:(e,t,n)=>__(e.inner,t.inner,n),...bn("intersection",(e,t,n)=>{if(e.children.length===0)return t;let{domain:r,proto:s,...o}=e.inner,a=s??r,l=a?ke(a,t,n):t;return l instanceof q?l:e?.basis?.equals(l)?e:e.$.node("intersection",{...o,[l.kind]:l},{prereduced:!0})})}});class w_ extends Gt{basis=this.inner.domain??this.inner.proto??null;prestructurals=[];refinements=this.children.filter((e)=>{if(!e.isRefinement())return!1;if(Ht($u,e.kind))this.prestructurals.push(e);return!0});structure=this.inner.structure;expression=g0(this);get shallowMorphs(){return this.inner.structure?.structuralMorph?[this.inner.structure.structuralMorph]:[]}get defaultShortDescription(){return this.basis?.defaultShortDescription??"present"}innerToJsonSchema(e){return this.children.reduce((t,n)=>n.isBasis()?n.toJsonSchemaRecurse(e):n.reduceJsonSchema(t,e),{})}traverseAllows=(e,t)=>this.children.every((n)=>n.traverseAllows(e,t));traverseApply=(e,t)=>{let n=t.currentErrorCount;if(this.basis){if(this.basis.traverseApply(e,t),t.currentErrorCount>n)return}if(this.prestructurals.length){for(let r=0;r<this.prestructurals.length-1;r++)if(this.prestructurals[r].traverseApply(e,t),t.failFast&&t.currentErrorCount>n)return;if(this.prestructurals[this.prestructurals.length-1].traverseApply(e,t),t.currentErrorCount>n)return}if(this.structure){if(this.structure.traverseApply(e,t),t.currentErrorCount>n)return}if(this.inner.predicate){for(let r=0;r<this.inner.predicate.length-1;r++)if(this.inner.predicate[r].traverseApply(e,t),t.failFast&&t.currentErrorCount>n)return;this.inner.predicate[this.inner.predicate.length-1].traverseApply(e,t)}};compile(e){if(e.traversalKind==="Allows"){for(let t of this.children)e.check(t);e.return(!0);return}if(e.initializeErrorCount(),this.basis){if(e.check(this.basis),this.children.length>1)e.returnIfFail()}if(this.prestructurals.length){for(let t=0;t<this.prestructurals.length-1;t++)e.check(this.prestructurals[t]),e.returnIfFailFast();if(e.check(this.prestructurals[this.prestructurals.length-1]),this.structure||this.inner.predicate)e.returnIfFail()}if(this.structure){if(e.check(this.structure),this.inner.predicate)e.returnIfFail()}if(this.inner.predicate){for(let t=0;t<this.inner.predicate.length-1;t++)e.check(this.inner.predicate[t]),e.returnIfFail();e.check(this.inner.predicate[this.inner.predicate.length-1])}}}var zu={implementation:m0,Node:w_},g0=(e)=>{if(e.structure?.expression)return e.structure.expression;let t=e.basis&&!e.prestructurals.some((s)=>s.impl.obviatesBasisExpression)?e.basis.nestableExpression:"",n=e.prestructurals.map((s)=>s.expression).join(" & "),r=`${t}${t?" ":""}${n}`;if(r==="Array == 0")return"[]";return r||"unknown"},__=(e,t,n)=>{let r={},s=e.proto??e.domain,o=t.proto??t.domain,a=s?o?ke(s,o,n):s:o;if(a instanceof q)return a;if(a)r[a.kind]=a;return yi({kind:"intersection",baseInner:r,l:bi(e),r:bi(t),roots:[],ctx:n})};var _0=ae({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(e,t)=>t.$.parseSchema(e)},morphs:{parse:er,serialize:(e)=>e.map((t)=>X(t,"root")?t.json:Me(t))},declaredIn:{child:!1,serialize:(e)=>e.json},declaredOut:{child:!1,serialize:(e)=>e.json}},normalize:(e)=>e,defaults:{description:(e)=>`a morph from ${e.rawIn.description} to ${e.rawOut?.description??"unknown"}`},intersections:{morph:(e,t,n)=>{if(!e.hasEqualMorphs(t))return C(w0(e.expression,t.expression));let r=ke(e.rawIn,t.rawIn,n);if(r instanceof q)return r;let s={morphs:e.morphs};if(e.declaredIn||t.declaredIn){let o=ke(e.rawIn,t.rawIn,n);if(o instanceof q)return o.throw();else s.declaredIn=o}if(e.declaredOut||t.declaredOut){let o=ke(e.rawOut,t.rawOut,n);if(o instanceof q)return o.throw();else s.declaredOut=o}return r.distribute((o)=>n.$.node("morph",{...s,in:o}),n.$.parseSchema)},...bn("morph",(e,t,n)=>{let r=e.inner.in?ke(e.inner.in,t,n):t;return r instanceof q?r:r.equals(e.inner.in)?e:n.$.node("morph",{...e.inner,in:r})})}});class y_ extends Gt{serializedMorphs=this.morphs.map(Me);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs[this.inner.morphs.length-1];lastMorphIfNode=X(this.lastMorph,"root")?this.lastMorph:void 0;introspectableIn=this.inner.in;introspectableOut=this.lastMorphIfNode?Object.assign(this.referencesById,this.lastMorphIfNode.referencesById)&&this.lastMorphIfNode.rawOut:void 0;get shallowMorphs(){return Array.isArray(this.inner.in?.shallowMorphs)?[...this.inner.in.shallowMorphs,...this.morphs]:this.morphs}get rawIn(){return this.declaredIn??this.inner.in?.rawIn??N.intrinsic.unknown.internal}get rawOut(){return this.declaredOut??this.introspectableOut??N.intrinsic.unknown.internal}declareIn(e){return this.$.node("morph",{...this.inner,declaredIn:e})}declareOut(e){return this.$.node("morph",{...this.inner,declaredOut:e})}expression=`(In: ${this.rawIn.expression}) => ${this.lastMorphIfNode?"To":"Out"}<${this.rawOut.expression}>`;get defaultShortDescription(){return this.rawIn.meta.description??this.rawIn.defaultShortDescription}innerToJsonSchema(e){return e.fallback.morph({code:"morph",base:this.rawIn.toJsonSchemaRecurse(e),out:this.introspectableOut?.toJsonSchemaRecurse(e)??null})}compile(e){if(e.traversalKind==="Allows"){if(!this.introspectableIn)return;e.return(e.invoke(this.introspectableIn));return}if(this.introspectableIn)e.line(e.invoke(this.introspectableIn));e.line(`ctx.queueMorphs(${this.compiledMorphs})`)}traverseAllows=(e,t)=>!this.introspectableIn||this.introspectableIn.traverseAllows(e,t);traverseApply=(e,t)=>{if(this.introspectableIn)this.introspectableIn.traverseApply(e,t);t.queueMorphs(this.morphs)};hasEqualMorphs(e){return Pn(this.morphs,e.morphs,{isEqual:(t,n)=>t===n||X(t,"root")&&X(n,"root")&&t.equals(n)})}}var Ju={implementation:_0,Node:y_},w0=(e,t)=>`The intersection of distinct morphs at a single path is indeterminate:
600
+ ${e.expected}`},intersections:{intersection:(e,t,n)=>q_(e.inner,t.inner,n),...xn("intersection",(e,t,n)=>{if(e.children.length===0)return t;let{domain:r,proto:s,...o}=e.inner,a=s??r,l=a?ke(a,t,n):t;return l instanceof q?l:e?.basis?.equals(l)?e:e.$.node("intersection",{...o,[l.kind]:l},{prereduced:!0})})}});class H_ extends Vt{basis=this.inner.domain??this.inner.proto??null;prestructurals=[];refinements=this.children.filter((e)=>{if(!e.isRefinement())return!1;if(Kt(Lu,e.kind))this.prestructurals.push(e);return!0});structure=this.inner.structure;expression=i0(this);get shallowMorphs(){return this.inner.structure?.structuralMorph?[this.inner.structure.structuralMorph]:[]}get defaultShortDescription(){return this.basis?.defaultShortDescription??"present"}innerToJsonSchema(e){return this.children.reduce((t,n)=>n.isBasis()?n.toJsonSchemaRecurse(e):n.reduceJsonSchema(t,e),{})}traverseAllows=(e,t)=>this.children.every((n)=>n.traverseAllows(e,t));traverseApply=(e,t)=>{let n=t.currentErrorCount;if(this.basis){if(this.basis.traverseApply(e,t),t.currentErrorCount>n)return}if(this.prestructurals.length){for(let r=0;r<this.prestructurals.length-1;r++)if(this.prestructurals[r].traverseApply(e,t),t.failFast&&t.currentErrorCount>n)return;if(this.prestructurals[this.prestructurals.length-1].traverseApply(e,t),t.currentErrorCount>n)return}if(this.structure){if(this.structure.traverseApply(e,t),t.currentErrorCount>n)return}if(this.inner.predicate){for(let r=0;r<this.inner.predicate.length-1;r++)if(this.inner.predicate[r].traverseApply(e,t),t.failFast&&t.currentErrorCount>n)return;this.inner.predicate[this.inner.predicate.length-1].traverseApply(e,t)}};compile(e){if(e.traversalKind==="Allows"){for(let t of this.children)e.check(t);e.return(!0);return}if(e.initializeErrorCount(),this.basis){if(e.check(this.basis),this.children.length>1)e.returnIfFail()}if(this.prestructurals.length){for(let t=0;t<this.prestructurals.length-1;t++)e.check(this.prestructurals[t]),e.returnIfFailFast();if(e.check(this.prestructurals[this.prestructurals.length-1]),this.structure||this.inner.predicate)e.returnIfFail()}if(this.structure){if(e.check(this.structure),this.inner.predicate)e.returnIfFail()}if(this.inner.predicate){for(let t=0;t<this.inner.predicate.length-1;t++)e.check(this.inner.predicate[t]),e.returnIfFail();e.check(this.inner.predicate[this.inner.predicate.length-1])}}}var ad={implementation:r0,Node:H_},i0=(e)=>{if(e.structure?.expression)return e.structure.expression;let t=e.basis&&!e.prestructurals.some((s)=>s.impl.obviatesBasisExpression)?e.basis.nestableExpression:"",n=e.prestructurals.map((s)=>s.expression).join(" & "),r=`${t}${t?" ":""}${n}`;if(r==="Array == 0")return"[]";return r||"unknown"},q_=(e,t,n)=>{let r={},s=e.proto??e.domain,o=t.proto??t.domain,a=s?o?ke(s,o,n):s:o;if(a instanceof q)return a;if(a)r[a.kind]=a;return Ri({kind:"intersection",baseInner:r,l:$i(e),r:$i(t),roots:[],ctx:n})};var s0=ae({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(e,t)=>t.$.parseSchema(e)},morphs:{parse:rr,serialize:(e)=>e.map((t)=>X(t,"root")?t.json:Me(t))},declaredIn:{child:!1,serialize:(e)=>e.json},declaredOut:{child:!1,serialize:(e)=>e.json}},normalize:(e)=>e,defaults:{description:(e)=>`a morph from ${e.rawIn.description} to ${e.rawOut?.description??"unknown"}`},intersections:{morph:(e,t,n)=>{if(!e.hasEqualMorphs(t))return A(o0(e.expression,t.expression));let r=ke(e.rawIn,t.rawIn,n);if(r instanceof q)return r;let s={morphs:e.morphs};if(e.declaredIn||t.declaredIn){let o=ke(e.rawIn,t.rawIn,n);if(o instanceof q)return o.throw();else s.declaredIn=o}if(e.declaredOut||t.declaredOut){let o=ke(e.rawOut,t.rawOut,n);if(o instanceof q)return o.throw();else s.declaredOut=o}return r.distribute((o)=>n.$.node("morph",{...s,in:o}),n.$.parseSchema)},...xn("morph",(e,t,n)=>{let r=e.inner.in?ke(e.inner.in,t,n):t;return r instanceof q?r:r.equals(e.inner.in)?e:n.$.node("morph",{...e.inner,in:r})})}});class K_ extends Vt{serializedMorphs=this.morphs.map(Me);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs[this.inner.morphs.length-1];lastMorphIfNode=X(this.lastMorph,"root")?this.lastMorph:void 0;introspectableIn=this.inner.in;introspectableOut=this.lastMorphIfNode?Object.assign(this.referencesById,this.lastMorphIfNode.referencesById)&&this.lastMorphIfNode.rawOut:void 0;get shallowMorphs(){return Array.isArray(this.inner.in?.shallowMorphs)?[...this.inner.in.shallowMorphs,...this.morphs]:this.morphs}get rawIn(){return this.declaredIn??this.inner.in?.rawIn??N.intrinsic.unknown.internal}get rawOut(){return this.declaredOut??this.introspectableOut??N.intrinsic.unknown.internal}declareIn(e){return this.$.node("morph",{...this.inner,declaredIn:e})}declareOut(e){return this.$.node("morph",{...this.inner,declaredOut:e})}expression=`(In: ${this.rawIn.expression}) => ${this.lastMorphIfNode?"To":"Out"}<${this.rawOut.expression}>`;get defaultShortDescription(){return this.rawIn.meta.description??this.rawIn.defaultShortDescription}innerToJsonSchema(e){return e.fallback.morph({code:"morph",base:this.rawIn.toJsonSchemaRecurse(e),out:this.introspectableOut?.toJsonSchemaRecurse(e)??null})}compile(e){if(e.traversalKind==="Allows"){if(!this.introspectableIn)return;e.return(e.invoke(this.introspectableIn));return}if(this.introspectableIn)e.line(e.invoke(this.introspectableIn));e.line(`ctx.queueMorphs(${this.compiledMorphs})`)}traverseAllows=(e,t)=>!this.introspectableIn||this.introspectableIn.traverseAllows(e,t);traverseApply=(e,t)=>{if(this.introspectableIn)this.introspectableIn.traverseApply(e,t);t.queueMorphs(this.morphs)};hasEqualMorphs(e){return Tn(this.morphs,e.morphs,{isEqual:(t,n)=>t===n||X(t,"root")&&X(n,"root")&&t.equals(n)})}}var ld={implementation:s0,Node:K_},o0=(e,t)=>`The intersection of distinct morphs at a single path is indeterminate:
601
601
  Left: ${e}
602
- Right: ${t}`;var y0=ae({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(e)=>_s(e)??Kt(e)},dateAllowsInvalid:{}},normalize:(e)=>{let t=typeof e==="string"?{proto:Or[e]}:typeof e==="function"?$e(e)?e:{proto:e}:typeof e.proto==="string"?{...e,proto:Or[e.proto]}:e;if(typeof t.proto!=="function")C(Ns.writeInvalidSchemaMessage(t.proto));if(fi(t,"dateAllowsInvalid")&&t.proto!==Date)C(Ns.writeBadInvalidDateMessage(t.proto));return t},applyConfig:(e,t)=>{if(e.dateAllowsInvalid===void 0&&e.proto===Date&&t.dateAllowsInvalid)return{...e,dateAllowsInvalid:!0};return e},defaults:{description:(e)=>e.builtinName?cg[e.builtinName]:`an instance of ${e.proto.name}`,actual:(e)=>e instanceof Date&&e.toString()==="Invalid Date"?"an invalid Date":gs(e)},intersections:{proto:(e,t)=>e.proto===Date&&t.proto===Date?e.dateAllowsInvalid?t:e:wu(e.proto,t.proto)?e:wu(t.proto,e.proto)?t:q.init("proto",e,t),domain:(e,t)=>t.domain==="object"?e:q.init("domain",N.intrinsic.object.internal,t)}});class b_ extends Tr{builtinName=_s(this.proto);serializedConstructor=this.json.proto;requiresInvalidDateCheck=this.proto===Date&&!this.dateAllowsInvalid;traverseAllows=this.requiresInvalidDateCheck?(e)=>e instanceof Date&&e.toString()!=="Invalid Date":(e)=>e instanceof this.proto;compiledCondition=`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?' && data.toString() !== "Invalid Date"':""}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema(e){switch(this.builtinName){case"Array":return{type:"array"};case"Date":return e.fallback.date?.({code:"date",base:{}})??e.fallback.proto({code:"proto",base:{},proto:this.proto});default:return e.fallback.proto({code:"proto",base:{},proto:this.proto})}}expression=this.dateAllowsInvalid?"Date | InvalidDate":this.proto.name;get nestableExpression(){return this.dateAllowsInvalid?`(${this.expression})`:this.expression}domain="object";get defaultShortDescription(){return this.description}}var Ns={implementation:y0,Node:b_,writeBadInvalidDateMessage:(e)=>`dateAllowsInvalid may only be specified with constructor Date (was ${e.name})`,writeInvalidSchemaMessage:(e)=>`instanceOf operand must be a function (was ${Ke(e)})`};var b0=ae({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(e,t)=>{let n=[];for(let r of e){let s=X(r,"root")?r.branches:t.$.parseSchema(r).branches;for(let o of s)if(o.hasKind("morph")){let a=n.findIndex((l)=>l.hasKind("morph")&&l.hasEqualMorphs(o));if(a===-1)n.push(o);else{let l=n[a];n[a]=t.$.node("morph",{...l.inner,in:l.rawIn.rawOr(o.rawIn)})}}else n.push(o)}if(!t.def.ordered)n.sort((r,s)=>r.hash<s.hash?-1:1);return n}}},normalize:(e)=>Re(e)?{branches:e}:e,reduce:(e,t)=>{let n=O0(e);if(n.length===1)return n[0];if(n.length===e.branches.length)return;return t.node("union",{...e,branches:n},{prereduced:!0})},defaults:{description:(e)=>e.distribute((t)=>t.description,Si),expected:(e)=>{let t=tg(e.errors,"propString"),n=Object.entries(t).map(([r,s])=>{let o=[];for(let c of s)wn(o,c.expected);let a=Si(o),l=s.every((c)=>c.actual===s[0].actual)?s[0].actual:se(s[0].data);return`${r&&`${r} `}must be ${a}${l&&` (was ${l})`}`});return Si(n)},problem:(e)=>e.expected,message:(e)=>{if(e.problem[0]==="[")return`value at ${e.problem}`;return e.problem}},intersections:{union:(e,t,n)=>{if(e.isNever!==t.isNever)return q.init("presence",e,t);let r;if(e.ordered){if(t.ordered)C(P0(e.expression,t.expression));if(r=Xu(t.branches,e.branches,n),r instanceof q)r.invert()}else r=Xu(e.branches,t.branches,n);if(r instanceof q)return r;return n.$.parseSchema(e.ordered||t.ordered?{branches:r,ordered:!0}:{branches:r})},...bn("union",(e,t,n)=>{let r=Xu(e.branches,[t],n);if(r instanceof q)return r;if(r.length===1)return r[0];return n.$.parseSchema(e.ordered?{branches:r,ordered:!0}:{branches:r})})}});class R_ extends Gt{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let e=[],t=-1;for(let n of this.branches){if(n.hasKind("unit")&&n.domain==="boolean"){if(t===-1)t=e.length,e.push(n);else e[t]=N.intrinsic.boolean;continue}e.push(n)}return e}unitBranches=this.branches.filter((e)=>e.rawIn.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?E0(this.discriminant):null;expression=this.distribute((e)=>e.nestableExpression,C0);createBranchedOptimisticRootApply(){return(e,t)=>{let n=this.traverseOptimistic(e);if(n!==$t)return n;let r=new sn(e,this.$.resolvedConfig);return this.traverseApply(e,r),r.finalize(t)}}get shallowMorphs(){return this.branches.reduce((e,t)=>wn(e,t.shallowMorphs),[])}get defaultShortDescription(){return this.distribute((e)=>e.defaultShortDescription,Si)}innerToJsonSchema(e){if(this.branchGroups.length===1&&this.branchGroups[0].equals(N.intrinsic.boolean))return{type:"boolean"};let t=this.branchGroups.map((n)=>n.toJsonSchemaRecurse(e));if(t.every((n)=>Object.keys(n).length===1&&fi(n,"const")))return{enum:t.map((n)=>n.const)};return{anyOf:t}}traverseAllows=(e,t)=>this.branches.some((n)=>n.traverseAllows(e,t));traverseApply=(e,t)=>{let n=[];for(let r=0;r<this.branches.length;r++){if(t.pushBranch(),this.branches[r].traverseApply(e,t),!t.hasError()){if(this.branches[r].includesTransform)return t.queuedMorphs.push(...t.popBranch().queuedMorphs);return t.popBranch()}n.push(t.popBranch().error)}t.errorFromNodeContext({code:"union",errors:n,meta:this.meta})};traverseOptimistic=(e)=>{for(let t=0;t<this.branches.length;t++){let n=this.branches[t];if(n.traverseAllows(e)){if(n.contextFreeMorph)return n.contextFreeMorph(e);return e}}return $t};compile(e){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(e);let t=this.discriminant.optionallyChainedPropString;if(this.discriminant.kind==="domain")t=`typeof ${t} === "object" ? ${t} === null ? "null" : "object" : typeof ${t} === "function" ? "object" : typeof ${t}`;let n=this.discriminant.cases,r=Object.keys(n),{optimistic:s}=e;if(e.optimistic=!1,e.block(`switch(${t})`,()=>{for(let u in n){let d=n[u],f=u==="default"?u:`case ${u}`,p;if(d===!0)p=s?"data":"true";else if(s)if(d.rootApplyStrategy==="branchedOptimistic")p=e.invoke(d,{kind:"Optimistic"});else if(d.contextFreeMorph)p=`${e.invoke(d)} ? ${Me(d.contextFreeMorph)}(data) : "${$t}"`;else p=`${e.invoke(d)} ? data : "${$t}"`;else p=e.invoke(d);e.line(`${f}: return ${p}`)}return e}),e.traversalKind==="Allows"){e.return(s?`"${$t}"`:!1);return}let o=Si(this.discriminant.kind==="domain"?r.map((u)=>{let d=u.slice(1,-1);return d==="function"?St.object:St[d]}):r),a=this.discriminant.path.map((u)=>typeof u==="symbol"?Me(u):JSON.stringify(u)),l=JSON.stringify(o),c=this.discriminant.kind==="domain"?`${$0}[${t}]`:`${k0}(${t})`;e.line(`ctx.errorFromNodeContext({
602
+ Right: ${t}`;var a0=ae({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(e)=>$s(e)??Gt(e)},dateAllowsInvalid:{}},normalize:(e)=>{let t=typeof e==="string"?{proto:Tr[e]}:typeof e==="function"?$e(e)?e:{proto:e}:typeof e.proto==="string"?{...e,proto:Tr[e.proto]}:e;if(typeof t.proto!=="function")A(Ks.writeInvalidSchemaMessage(t.proto));if(_i(t,"dateAllowsInvalid")&&t.proto!==Date)A(Ks.writeBadInvalidDateMessage(t.proto));return t},applyConfig:(e,t)=>{if(e.dateAllowsInvalid===void 0&&e.proto===Date&&t.dateAllowsInvalid)return{...e,dateAllowsInvalid:!0};return e},defaults:{description:(e)=>e.builtinName?Tg[e.builtinName]:`an instance of ${e.proto.name}`,actual:(e)=>e instanceof Date&&e.toString()==="Invalid Date"?"an invalid Date":Rs(e)},intersections:{proto:(e,t)=>e.proto===Date&&t.proto===Date?e.dateAllowsInvalid?t:e:Iu(e.proto,t.proto)?e:Iu(t.proto,e.proto)?t:q.init("proto",e,t),domain:(e,t)=>t.domain==="object"?e:q.init("domain",N.intrinsic.object.internal,t)}});class G_ extends Lr{builtinName=$s(this.proto);serializedConstructor=this.json.proto;requiresInvalidDateCheck=this.proto===Date&&!this.dateAllowsInvalid;traverseAllows=this.requiresInvalidDateCheck?(e)=>e instanceof Date&&e.toString()!=="Invalid Date":(e)=>e instanceof this.proto;compiledCondition=`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?' && data.toString() !== "Invalid Date"':""}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema(e){switch(this.builtinName){case"Array":return{type:"array"};case"Date":return e.fallback.date?.({code:"date",base:{}})??e.fallback.proto({code:"proto",base:{},proto:this.proto});default:return e.fallback.proto({code:"proto",base:{},proto:this.proto})}}expression=this.dateAllowsInvalid?"Date | InvalidDate":this.proto.name;get nestableExpression(){return this.dateAllowsInvalid?`(${this.expression})`:this.expression}domain="object";get defaultShortDescription(){return this.description}}var Ks={implementation:a0,Node:G_,writeBadInvalidDateMessage:(e)=>`dateAllowsInvalid may only be specified with constructor Date (was ${e.name})`,writeInvalidSchemaMessage:(e)=>`instanceOf operand must be a function (was ${Ke(e)})`};var l0=ae({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(e,t)=>{let n=[];for(let r of e){let s=X(r,"root")?r.branches:t.$.parseSchema(r).branches;for(let o of s)if(o.hasKind("morph")){let a=n.findIndex((l)=>l.hasKind("morph")&&l.hasEqualMorphs(o));if(a===-1)n.push(o);else{let l=n[a];n[a]=t.$.node("morph",{...l.inner,in:l.rawIn.rawOr(o.rawIn)})}}else n.push(o)}if(!t.def.ordered)n.sort((r,s)=>r.hash<s.hash?-1:1);return n}}},normalize:(e)=>Se(e)?{branches:e}:e,reduce:(e,t)=>{let n=w0(e);if(n.length===1)return n[0];if(n.length===e.branches.length)return;return t.node("union",{...e,branches:n},{prereduced:!0})},defaults:{description:(e)=>e.distribute((t)=>t.description,Ai),expected:(e)=>{let t=kg(e.errors,"propString"),n=Object.entries(t).map(([r,s])=>{let o=[];for(let c of s)bn(o,c.expected);let a=Ai(o),l=s.every((c)=>c.actual===s[0].actual)?s[0].actual:se(s[0].data);return`${r&&`${r} `}must be ${a}${l&&` (was ${l})`}`});return Ai(n)},problem:(e)=>e.expected,message:(e)=>{if(e.problem[0]==="[")return`value at ${e.problem}`;return e.problem}},intersections:{union:(e,t,n)=>{if(e.isNever!==t.isNever)return q.init("presence",e,t);let r;if(e.ordered){if(t.ordered)A(b0(e.expression,t.expression));if(r=cd(t.branches,e.branches,n),r instanceof q)r.invert()}else r=cd(e.branches,t.branches,n);if(r instanceof q)return r;return n.$.parseSchema(e.ordered||t.ordered?{branches:r,ordered:!0}:{branches:r})},...xn("union",(e,t,n)=>{let r=cd(e.branches,[t],n);if(r instanceof q)return r;if(r.length===1)return r[0];return n.$.parseSchema(e.ordered?{branches:r,ordered:!0}:{branches:r})})}});class z_ extends Vt{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let e=[],t=-1;for(let n of this.branches){if(n.hasKind("unit")&&n.domain==="boolean"){if(t===-1)t=e.length,e.push(n);else e[t]=N.intrinsic.boolean;continue}e.push(n)}return e}unitBranches=this.branches.filter((e)=>e.rawIn.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?m0(this.discriminant):null;expression=this.distribute((e)=>e.nestableExpression,_0);createBranchedOptimisticRootApply(){return(e,t)=>{let n=this.traverseOptimistic(e);if(n!==$t)return n;let r=new an(e,this.$.resolvedConfig);return this.traverseApply(e,r),r.finalize(t)}}get shallowMorphs(){return this.branches.reduce((e,t)=>bn(e,t.shallowMorphs),[])}get defaultShortDescription(){return this.distribute((e)=>e.defaultShortDescription,Ai)}innerToJsonSchema(e){if(this.branchGroups.length===1&&this.branchGroups[0].equals(N.intrinsic.boolean))return{type:"boolean"};let t=this.branchGroups.map((n)=>n.toJsonSchemaRecurse(e));if(t.every((n)=>Object.keys(n).length===1&&_i(n,"const")))return{enum:t.map((n)=>n.const)};return{anyOf:t}}traverseAllows=(e,t)=>this.branches.some((n)=>n.traverseAllows(e,t));traverseApply=(e,t)=>{let n=[];for(let r=0;r<this.branches.length;r++){if(t.pushBranch(),this.branches[r].traverseApply(e,t),!t.hasError()){if(this.branches[r].includesTransform)return t.queuedMorphs.push(...t.popBranch().queuedMorphs);return t.popBranch()}n.push(t.popBranch().error)}t.errorFromNodeContext({code:"union",errors:n,meta:this.meta})};traverseOptimistic=(e)=>{for(let t=0;t<this.branches.length;t++){let n=this.branches[t];if(n.traverseAllows(e)){if(n.contextFreeMorph)return n.contextFreeMorph(e);return e}}return $t};compile(e){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(e);let t=this.discriminant.optionallyChainedPropString;if(this.discriminant.kind==="domain")t=`typeof ${t} === "object" ? ${t} === null ? "null" : "object" : typeof ${t} === "function" ? "object" : typeof ${t}`;let n=this.discriminant.cases,r=Object.keys(n),{optimistic:s}=e;if(e.optimistic=!1,e.block(`switch(${t})`,()=>{for(let u in n){let d=n[u],f=u==="default"?u:`case ${u}`,p;if(d===!0)p=s?"data":"true";else if(s)if(d.rootApplyStrategy==="branchedOptimistic")p=e.invoke(d,{kind:"Optimistic"});else if(d.contextFreeMorph)p=`${e.invoke(d)} ? ${Me(d.contextFreeMorph)}(data) : "${$t}"`;else p=`${e.invoke(d)} ? data : "${$t}"`;else p=e.invoke(d);e.line(`${f}: return ${p}`)}return e}),e.traversalKind==="Allows"){e.return(s?`"${$t}"`:!1);return}let o=Ai(this.discriminant.kind==="domain"?r.map((u)=>{let d=u.slice(1,-1);return d==="function"?Rt.object:Rt[d]}):r),a=this.discriminant.path.map((u)=>typeof u==="symbol"?Me(u):JSON.stringify(u)),l=JSON.stringify(o),c=this.discriminant.kind==="domain"?`${p0}[${t}]`:`${h0}(${t})`;e.line(`ctx.errorFromNodeContext({
603
603
  code: "predicate",
604
604
  expected: ${l},
605
605
  actual: ${c},
606
606
  relativePath: [${a}],
607
607
  meta: ${this.compiledMeta}
608
- })`)}compileIndiscriminable(e){if(e.traversalKind==="Apply"){e.const("errors","[]");for(let t of this.branches)e.line("ctx.pushBranch()").line(e.invoke(t)).if("!ctx.hasError()",()=>e.return(t.includesTransform?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)");e.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{let{optimistic:t}=e;e.optimistic=!1;for(let n of this.branches)e.if(`${e.invoke(n)}`,()=>e.return(t?n.contextFreeMorph?`${Me(n.contextFreeMorph)}(data)`:"data":!0));e.return(t?`"${$t}"`:!1)}}get nestableExpression(){return this.isBoolean?"boolean":`(${this.expression})`}discriminate(){if(this.branches.length<2||this.isCyclic)return null;if(this.unitBranches.length===this.branches.length){let s=ie(this.unitBranches,(o,a)=>[`${a.rawIn.serializedValue}`,a.hasKind("morph")?a:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:s}}let e=[];for(let s=0;s<this.branches.length-1;s++){let o=this.branches[s];for(let a=s+1;a<this.branches.length;a++){let l=this.branches[a],c=Ct(o.rawIn,l.rawIn,o.$);if(!(c instanceof q))continue;for(let u of c){if(!u.kind||u.optional)continue;let d,f;if(u.kind==="domain"){let{l:h,r:g}=u;d=`"${typeof h==="string"?h:h.domain}"`,f=`"${typeof g==="string"?g:g.domain}"`}else if(u.kind==="unit")d=u.l.serializedValue,f=u.r.serializedValue;else continue;let p=e.find((h)=>Pn(h.path,u.path)&&h.kind===u.kind);if(!p)e.push({kind:u.kind,cases:{[d]:{branchIndices:[s],condition:u.l},[f]:{branchIndices:[a],condition:u.r}},path:u.path});else{if(p.cases[d])p.cases[d].branchIndices=wn(p.cases[d].branchIndices,s);else p.cases[d]??={branchIndices:[s],condition:u.l};if(p.cases[f])p.cases[f].branchIndices=wn(p.cases[f].branchIndices,a);else p.cases[f]??={branchIndices:[a],condition:u.r}}}}}let t=this.ordered?R0(e,this.branches):e;if(!t.length)return null;let n=v0(t,this),r={};for(let s in n.best.cases){let o=x0(n,s);if(o===null){r[s]=!0;continue}if(o.length===this.branches.length)return null;if(this.ordered)o.sort((c,u)=>c.originalIndex-u.originalIndex);let a=o.map((c)=>c.branch),l=a.length===1?a[0]:this.$.node("union",this.ordered?{branches:a,ordered:!0}:a);Object.assign(this.referencesById,l.referencesById),r[s]=l}if(n.defaultEntries.length){let s=n.defaultEntries.map((o)=>o.branch);r.default=this.$.node("union",this.ordered?{branches:s,ordered:!0}:s,{prereduced:!0}),Object.assign(this.referencesById,r.default.referencesById)}return Object.assign(n.location,{cases:r})}}var v0=(e,t)=>{let r=e.sort((a,l)=>a.path.length===l.path.length?Object.keys(l.cases).length-Object.keys(a.cases).length:a.path.length-l.path.length)[0],s={kind:r.kind,path:r.path,optionallyChainedPropString:S_(r.path)},o=t.branches.map((a,l)=>({originalIndex:l,branch:a}));return{best:r,location:s,defaultEntries:o,node:t}},x0=(e,t)=>{let n=e.best.cases[t],r=S0(n.condition,e.location.path,e.node.$),s=[],o=[];for(let a=0;a<e.defaultEntries.length;a++){let l=e.defaultEntries[a];if(n.branchIndices.includes(l.originalIndex)){let c=v_(e.node.branches[l.originalIndex],e.location);if(c===null)s=null;else s?.push({originalIndex:l.originalIndex,branch:c})}else if(l.branch.hasKind("alias")&&r.hasKind("domain")&&r.domain==="object")s?.push(l);else{if(l.branch.rawIn.overlaps(r)){let c=v_(l.branch,e.location);s?.push({originalIndex:l.originalIndex,branch:c})}o.push(l)}}return e.defaultEntries=o,s},R0=(e,t)=>e.filter((r)=>{let s=Object.values(r.cases).map((o)=>o.branchIndices);for(let o=0;o<s.length-1;o++){let a=s[o];for(let l=o+1;l<s.length;l++){let c=s[l];for(let u of a)for(let d of c)if(u>d){if(t[u].overlaps(t[d]))return!1}}}return!0}),S0=(e,t,n)=>{let r=e==="undefined"?n.node("unit",{unit:void 0}):e==="null"?n.node("unit",{unit:null}):e==="boolean"?n.units([!0,!1]):e;for(let s=t.length-1;s>=0;s--){let o=t[s];r=n.node("intersection",typeof o==="number"?{proto:"Array",sequence:[...Qm(o).map((a)=>({})),r]}:{domain:"object",required:[{key:o,value:r}]})}return r},S_=(e)=>e.reduce((t,n)=>t+Su(n,!0),"data"),$0=Me(ng),k0=Me(se),Yu={implementation:b0,Node:R_},E0=(e)=>({kind:e.kind,path:e.path.map((t)=>typeof t==="string"?t:rn(t)),cases:ie(e.cases,(t,n)=>[t,n===!0?n:n.hasKind("union")&&n.discriminantJson?n.discriminantJson:n.json])}),A0={delimiter:" | ",finalDelimiter:" | "},C0=(e)=>Si(e,A0),Si=(e,t)=>{let n=t?.delimiter??", ",r=t?.finalDelimiter??" or ";if(e.length===0)return"never";if(e.length===1)return e[0];if(e.length===2&&e[0]==="false"&&e[1]==="true"||e[0]==="true"&&e[1]==="false")return"boolean";let s={},o=e.filter((l)=>s[l]?!1:s[l]=!0),a=o.pop();return`${o.join(n)}${o.length?r:""}${a}`},Xu=(e,t,n)=>{let r=t.map(()=>[]);for(let o=0;o<e.length;o++){let a={};for(let l=0;l<t.length;l++){if(r[l]===null)continue;if(e[o].equals(t[l])){r[l]=null,a={};break}let c=ke(e[o],t[l],n);if(c instanceof q)continue;if(c.equals(e[o])){r[l].push(e[o]),a={};break}if(c.equals(t[l]))r[l]=null;else a[l]=c}for(let l in a)r[l][o]=a[l]}let s=r.flatMap((o,a)=>o?.flatMap((l)=>l.branches)??t[a]);return s.length===0?q.init("union",e,t):s},O0=({branches:e,ordered:t})=>{if(e.length<2)return e;let n=e.map(()=>!0);for(let r=0;r<e.length;r++)for(let s=r+1;s<e.length&&n[r]&&n[s];s++){if(e[r].equals(e[s])){n[s]=!1;continue}let o=Ct(e[r].rawIn,e[s].rawIn,e[0].$);if(o instanceof q)continue;if(!t)I0(e[r],e[s]);if(o.equals(e[r].rawIn))n[r]=!!t;else if(o.equals(e[s].rawIn))n[s]=!1}return e.filter((r,s)=>n[s])},I0=(e,t)=>{if(!e.includesTransform&&!t.includesTransform)return;if(!Pn(e.shallowMorphs,t.shallowMorphs))C(x_(e.expression,t.expression));if(!Pn(e.flatMorphs,t.flatMorphs,{isEqual:(n,r)=>n.propString===r.propString&&(n.node.hasKind("morph")&&r.node.hasKind("morph")?n.node.hasEqualMorphs(r.node):n.node.hasKind("intersection")&&r.node.hasKind("intersection")?n.node.structure?.structuralMorphRef===r.node.structure?.structuralMorphRef:!1)}))C(x_(e.expression,t.expression))},v_=(e,t)=>e.transform((n,r)=>{if(n==="domain"||n==="unit")return null;return r},{shouldTransform:(n,r)=>{let s=S_(r.path);if(!t.optionallyChainedPropString.startsWith(s))return!1;if(n.hasKind("domain")&&n.domain==="object")return!0;if((n.hasKind("domain")||t.kind==="unit")&&s===t.optionallyChainedPropString)return!0;return n.children.length!==0&&n.kind!=="index"}}),x_=(e,t)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
608
+ })`)}compileIndiscriminable(e){if(e.traversalKind==="Apply"){e.const("errors","[]");for(let t of this.branches)e.line("ctx.pushBranch()").line(e.invoke(t)).if("!ctx.hasError()",()=>e.return(t.includesTransform?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)");e.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{let{optimistic:t}=e;e.optimistic=!1;for(let n of this.branches)e.if(`${e.invoke(n)}`,()=>e.return(t?n.contextFreeMorph?`${Me(n.contextFreeMorph)}(data)`:"data":!0));e.return(t?`"${$t}"`:!1)}}get nestableExpression(){return this.isBoolean?"boolean":`(${this.expression})`}discriminate(){if(this.branches.length<2||this.isCyclic)return null;if(this.unitBranches.length===this.branches.length){let s=ie(this.unitBranches,(o,a)=>[`${a.rawIn.serializedValue}`,a.hasKind("morph")?a:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:s}}let e=[];for(let s=0;s<this.branches.length-1;s++){let o=this.branches[s];for(let a=s+1;a<this.branches.length;a++){let l=this.branches[a],c=At(o.rawIn,l.rawIn,o.$);if(!(c instanceof q))continue;for(let u of c){if(!u.kind||u.optional)continue;let d,f;if(u.kind==="domain"){let{l:h,r:g}=u;d=`"${typeof h==="string"?h:h.domain}"`,f=`"${typeof g==="string"?g:g.domain}"`}else if(u.kind==="unit")d=u.l.serializedValue,f=u.r.serializedValue;else continue;let p=e.find((h)=>Tn(h.path,u.path)&&h.kind===u.kind);if(!p)e.push({kind:u.kind,cases:{[d]:{branchIndices:[s],condition:u.l},[f]:{branchIndices:[a],condition:u.r}},path:u.path});else{if(p.cases[d])p.cases[d].branchIndices=bn(p.cases[d].branchIndices,s);else p.cases[d]??={branchIndices:[s],condition:u.l};if(p.cases[f])p.cases[f].branchIndices=bn(p.cases[f].branchIndices,a);else p.cases[f]??={branchIndices:[a],condition:u.r}}}}}let t=this.ordered?d0(e,this.branches):e;if(!t.length)return null;let n=c0(t,this),r={};for(let s in n.best.cases){let o=u0(n,s);if(o===null){r[s]=!0;continue}if(o.length===this.branches.length)return null;if(this.ordered)o.sort((c,u)=>c.originalIndex-u.originalIndex);let a=o.map((c)=>c.branch),l=a.length===1?a[0]:this.$.node("union",this.ordered?{branches:a,ordered:!0}:a);Object.assign(this.referencesById,l.referencesById),r[s]=l}if(n.defaultEntries.length){let s=n.defaultEntries.map((o)=>o.branch);r.default=this.$.node("union",this.ordered?{branches:s,ordered:!0}:s,{prereduced:!0}),Object.assign(this.referencesById,r.default.referencesById)}return Object.assign(n.location,{cases:r})}}var c0=(e,t)=>{let r=e.sort((a,l)=>a.path.length===l.path.length?Object.keys(l.cases).length-Object.keys(a.cases).length:a.path.length-l.path.length)[0],s={kind:r.kind,path:r.path,optionallyChainedPropString:J_(r.path)},o=t.branches.map((a,l)=>({originalIndex:l,branch:a}));return{best:r,location:s,defaultEntries:o,node:t}},u0=(e,t)=>{let n=e.best.cases[t],r=f0(n.condition,e.location.path,e.node.$),s=[],o=[];for(let a=0;a<e.defaultEntries.length;a++){let l=e.defaultEntries[a];if(n.branchIndices.includes(l.originalIndex)){let c=W_(e.node.branches[l.originalIndex],e.location);if(c===null)s=null;else s?.push({originalIndex:l.originalIndex,branch:c})}else if(l.branch.hasKind("alias")&&r.hasKind("domain")&&r.domain==="object")s?.push(l);else{if(l.branch.rawIn.overlaps(r)){let c=W_(l.branch,e.location);s?.push({originalIndex:l.originalIndex,branch:c})}o.push(l)}}return e.defaultEntries=o,s},d0=(e,t)=>e.filter((r)=>{let s=Object.values(r.cases).map((o)=>o.branchIndices);for(let o=0;o<s.length-1;o++){let a=s[o];for(let l=o+1;l<s.length;l++){let c=s[l];for(let u of a)for(let d of c)if(u>d){if(t[u].overlaps(t[d]))return!1}}}return!0}),f0=(e,t,n)=>{let r=e==="undefined"?n.node("unit",{unit:void 0}):e==="null"?n.node("unit",{unit:null}):e==="boolean"?n.units([!0,!1]):e;for(let s=t.length-1;s>=0;s--){let o=t[s];r=n.node("intersection",typeof o==="number"?{proto:"Array",sequence:[...Rg(o).map((a)=>({})),r]}:{domain:"object",required:[{key:o,value:r}]})}return r},J_=(e)=>e.reduce((t,n)=>t+Fu(n,!0),"data"),p0=Me(Eg),h0=Me(se),ud={implementation:l0,Node:z_},m0=(e)=>({kind:e.kind,path:e.path.map((t)=>typeof t==="string"?t:on(t)),cases:ie(e.cases,(t,n)=>[t,n===!0?n:n.hasKind("union")&&n.discriminantJson?n.discriminantJson:n.json])}),g0={delimiter:" | ",finalDelimiter:" | "},_0=(e)=>Ai(e,g0),Ai=(e,t)=>{let n=t?.delimiter??", ",r=t?.finalDelimiter??" or ";if(e.length===0)return"never";if(e.length===1)return e[0];if(e.length===2&&e[0]==="false"&&e[1]==="true"||e[0]==="true"&&e[1]==="false")return"boolean";let s={},o=e.filter((l)=>s[l]?!1:s[l]=!0),a=o.pop();return`${o.join(n)}${o.length?r:""}${a}`},cd=(e,t,n)=>{let r=t.map(()=>[]);for(let o=0;o<e.length;o++){let a={};for(let l=0;l<t.length;l++){if(r[l]===null)continue;if(e[o].equals(t[l])){r[l]=null,a={};break}let c=ke(e[o],t[l],n);if(c instanceof q)continue;if(c.equals(e[o])){r[l].push(e[o]),a={};break}if(c.equals(t[l]))r[l]=null;else a[l]=c}for(let l in a)r[l][o]=a[l]}let s=r.flatMap((o,a)=>o?.flatMap((l)=>l.branches)??t[a]);return s.length===0?q.init("union",e,t):s},w0=({branches:e,ordered:t})=>{if(e.length<2)return e;let n=e.map(()=>!0);for(let r=0;r<e.length;r++)for(let s=r+1;s<e.length&&n[r]&&n[s];s++){if(e[r].equals(e[s])){n[s]=!1;continue}let o=At(e[r].rawIn,e[s].rawIn,e[0].$);if(o instanceof q)continue;if(!t)y0(e[r],e[s]);if(o.equals(e[r].rawIn))n[r]=!!t;else if(o.equals(e[s].rawIn))n[s]=!1}return e.filter((r,s)=>n[s])},y0=(e,t)=>{if(!e.includesTransform&&!t.includesTransform)return;if(!Tn(e.shallowMorphs,t.shallowMorphs))A(V_(e.expression,t.expression));if(!Tn(e.flatMorphs,t.flatMorphs,{isEqual:(n,r)=>n.propString===r.propString&&(n.node.hasKind("morph")&&r.node.hasKind("morph")?n.node.hasEqualMorphs(r.node):n.node.hasKind("intersection")&&r.node.hasKind("intersection")?n.node.structure?.structuralMorphRef===r.node.structure?.structuralMorphRef:!1)}))A(V_(e.expression,t.expression))},W_=(e,t)=>e.transform((n,r)=>{if(n==="domain"||n==="unit")return null;return r},{shouldTransform:(n,r)=>{let s=J_(r.path);if(!t.optionallyChainedPropString.startsWith(s))return!1;if(n.hasKind("domain")&&n.domain==="object")return!0;if((n.hasKind("domain")||t.kind==="unit")&&s===t.optionallyChainedPropString)return!0;return n.children.length!==0&&n.kind!=="index"}}),V_=(e,t)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
609
609
  Left: ${e}
610
- Right: ${t}`,P0=(e,t)=>`The intersection of two ordered unions is indeterminate:
610
+ Right: ${t}`,b0=(e,t)=>`The intersection of two ordered unions is indeterminate:
611
611
  Left: ${e}
612
- Right: ${t}`;var M0=ae({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(e)=>e instanceof Date?e.toISOString():Kt(e)}},normalize:(e)=>e,defaults:{description:(e)=>se(e.unit),problem:({expected:e,actual:t})=>`${e===t?`must be reference equal to ${e} (serialized to the same value)`:`must be ${e} (was ${t})`}`},intersections:{unit:(e,t)=>q.init("unit",e,t),...bn("unit",(e,t)=>{if(t.allows(e.unit))return e;let n=t.hasKind("intersection")?t.basis:t;if(n){let r=n.hasKind("domain")?n:N.intrinsic.object;if(e.domain!==r.domain){let s=e.domain==="undefined"||e.domain==="null"||e.domain==="boolean"?e.domain:N.intrinsic[e.domain];return q.init("domain",s,r)}}return q.init("assignability",e,t.hasKind("intersection")?t.children.find((r)=>!r.allows(e.unit)):t)})}});class k_ extends Tr{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=$_(this.unit,this.serializedValue);compiledNegation=$_(this.unit,this.serializedValue,"negated");expression=se(this.unit);domain=Ke(this.unit);get defaultShortDescription(){return this.domain==="object"?St.object:this.description}innerToJsonSchema(e){return this.unit===null?{type:"null"}:N.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:e.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?(e)=>e instanceof Date&&e.toISOString()===this.compiledValue:Number.isNaN(this.unit)?(e)=>Number.isNaN(e):(e)=>e===this.unit}var Zu={implementation:M0,Node:k_},$_=(e,t,n)=>{if(e instanceof Date){let r=`data instanceof Date && data.toISOString() === ${t}`;return n?`!(${r})`:r}if(Number.isNaN(e))return`${n?"!":""}Number.isNaN(data)`;return`data ${n?"!":"="}== ${t}`};var T0=ae({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(e,t)=>{let n=t.$.parseSchema(e);if(!n.extends(N.intrinsic.key))return C(N0(n.expression));let r=n.branches.filter((s)=>s.hasKind("unit"));if(r.length)return C(F0(r.map((s)=>se(s.unit))));return n}},value:{child:!0,parse:(e,t)=>t.$.parseSchema(e)}},normalize:(e)=>e,defaults:{description:(e)=>`[${e.signature.expression}]: ${e.value.description}`},intersections:{index:(e,t,n)=>{if(e.signature.equals(t.signature)){let r=ke(e.value,t.value,n),s=r instanceof q?N.intrinsic.never.internal:r;return n.$.node("index",{signature:e.signature,value:s})}if(e.signature.extends(t.signature)&&e.value.subsumes(t.value))return t;if(t.signature.extends(e.signature)&&t.value.subsumes(e.value))return e;return null}}});class E_ extends Wt{impliedBasis=N.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=de(this.value.flatRefs.map((e)=>on([this.signature,...e.path],e.node)),on([this.signature],this.value));traverseAllows=(e,t)=>Cr(e).every((n)=>{if(this.signature.traverseAllows(n[0],t))return At(n[0],()=>this.value.traverseAllows(n[1],t),t);return!0});traverseApply=(e,t)=>{for(let n of Cr(e))if(this.signature.traverseAllows(n[0],t))At(n[0],()=>this.value.traverseApply(n[1],t),t)};_transform(e,t){t.path.push(this.signature);let n=super._transform(e,t);return t.path.pop(),n}compile(){}}var Qu={implementation:T0,Node:E_},F0=(e)=>`Index keys ${e.join(", ")} should be specified as named props.`,N0=(e)=>`Indexed key definition '${e}' must be a string or symbol`;var D0=ae({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(e,t)=>t.$.parseSchema(e)}},normalize:(e)=>e,defaults:{description:(e)=>`${e.compiledKey}: ${e.value.description}`,expected:(e)=>e.missingValueDescription,actual:()=>"missing"},intersections:{required:Os,optional:Os}});class A_ extends Is{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=ir(this.errorContext)}var ed={implementation:D0,Node:A_};var L0=ae({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(e,t)=>{if(e.length===0)return;return e.map((n)=>t.$.parseSchema(n))}},optionals:{child:!0,parse:(e,t)=>{if(e.length===0)return;return e.map((n)=>t.$.parseSchema(n))}},defaultables:{child:(e)=>e.map((t)=>t[0]),parse:(e,t)=>{if(e.length===0)return;return e.map((n)=>{let r=t.$.parseSchema(n[0]);return Ms(r,n[1],null),[r,n[1]]})},serialize:(e)=>e.map((t)=>[t[0].collapsibleJson,Kt(t[1])]),reduceIo:(e,t,n)=>{if(e==="in"){t.optionals=n.map((r)=>r[0].rawIn);return}t.prefix=n.map((r)=>r[0].rawOut);return}},variadic:{child:!0,parse:(e,t)=>t.$.parseSchema(e,t)},minVariadicLength:{parse:(e)=>e===0?void 0:e},postfix:{child:!0,parse:(e,t)=>{if(e.length===0)return;return e.map((n)=>t.$.parseSchema(n))}}},normalize:(e)=>{if(typeof e==="string")return{variadic:e};if("variadic"in e||"prefix"in e||"defaultables"in e||"optionals"in e||"postfix"in e||"minVariadicLength"in e){if(e.postfix?.length){if(!e.variadic)return C(q0);if(e.optionals?.length||e.defaultables?.length)return C(nd)}if(e.minVariadicLength&&!e.variadic)return C("minVariadicLength may not be specified without a variadic element");return e}return{variadic:e}},reduce:(e,t)=>{let n=e.minVariadicLength??0,r=e.prefix?.slice()??[],s=e.defaultables?.slice()??[],o=e.optionals?.slice()??[],a=e.postfix?.slice()??[];if(e.variadic){while(o[o.length-1]?.equals(e.variadic))o.pop();if(o.length===0&&s.length===0)while(r[r.length-1]?.equals(e.variadic))r.pop(),n++;while(a[0]?.equals(e.variadic))a.shift(),n++}else if(o.length===0&&s.length===0)r.push(...a.splice(0));if(n!==e.minVariadicLength||e.prefix&&e.prefix.length!==r.length)return t.node("sequence",{...e,prefix:r,defaultables:s,optionals:o,postfix:a,minVariadicLength:n},{prereduced:!0})},defaults:{description:(e)=>{if(e.isVariadicOnly)return`${e.variadic.nestableExpression}[]`;return`[${e.tuple.map((n)=>n.kind==="defaultables"?`${n.node.nestableExpression} = ${se(n.default)}`:n.kind==="optionals"?`${n.node.nestableExpression}?`:n.kind==="variadic"?`...${n.node.nestableExpression}[]`:n.node.expression).join(", ")}]`}},intersections:{sequence:(e,t,n)=>{let r=Ds({l:e.tuple,r:t.tuple,disjoint:new q,result:[],fixedVariants:[],ctx:n}),s=r.disjoint.length===0?[r,...r.fixedVariants]:r.fixedVariants;return s.length===0?r.disjoint:s.length===1?n.$.node("sequence",C_(s[0].result)):n.$.node("union",s.map((o)=>({proto:Array,sequence:C_(o.result)})))}}});class I_ extends Wt{impliedBasis=N.intrinsic.Array.internal;tuple=B0(this.inner);prefixLength=this.prefix?.length??0;defaultablesLength=this.defaultables?.length??0;optionalsLength=this.optionals?.length??0;postfixLength=this.postfix?.length??0;defaultablesAndOptionals=[];prevariadic=this.tuple.filter((e)=>{if(e.kind==="defaultables"||e.kind==="optionals")return this.defaultablesAndOptionals.push(e.node),!0;return e.kind==="prefix"});variadicOrPostfix=In(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return Cu(this.flatRefs,this.prevariadic.flatMap((e,t)=>de(e.node.flatRefs.map((n)=>on([`${t}`,...n.path],n.node)),on([`${t}`],e.node)))),Cu(this.flatRefs,this.variadicOrPostfix.flatMap((e)=>de(e.flatRefs.map((t)=>on([N.intrinsic.nonNegativeIntegerString.internal,...t.path],t.node)),on([N.intrinsic.nonNegativeIntegerString.internal],e)))),this.flatRefs}isVariadicOnly=this.prevariadic.length+this.postfixLength===0;minVariadicLength=this.inner.minVariadicLength??0;minLength=this.prefixLength+this.minVariadicLength+this.postfixLength;minLengthNode=this.minLength===0?null:this.$.node("minLength",this.minLength);maxLength=this.variadic?null:this.tuple.length;maxLengthNode=this.maxLength===null?null:this.$.node("maxLength",this.maxLength);impliedSiblings=this.minLengthNode?this.maxLengthNode?[this.minLengthNode,this.maxLengthNode]:[this.minLengthNode]:this.maxLengthNode?[this.maxLengthNode]:[];defaultValueMorphs=U0(this);defaultValueMorphsReference=this.defaultValueMorphs.length?Me(this.defaultValueMorphs):void 0;elementAtIndex(e,t){if(t<this.prevariadic.length)return this.tuple[t];let n=e.length-this.postfixLength;if(t>=n)return{kind:"postfix",node:this.postfix[t-n]};return{kind:"variadic",node:this.variadic??he(`Unexpected attempt to access index ${t} on ${this}`)}}traverseAllows=(e,t)=>{for(let n=0;n<e.length;n++)if(!this.elementAtIndex(e,n).node.traverseAllows(e[n],t))return!1;return!0};traverseApply=(e,t)=>{let n=0;for(;n<e.length;n++)At(n,()=>this.elementAtIndex(e,n).node.traverseApply(e[n],t),t)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(e){if(this.prefix)for(let[t,n]of this.prefix.entries())e.traverseKey(`${t}`,`data[${t}]`,n);for(let[t,n]of this.defaultablesAndOptionals.entries()){let r=`${t+this.prefixLength}`;e.if(`${r} >= data.length`,()=>e.traversalKind==="Allows"?e.return(!0):e.return()),e.traverseKey(r,`data[${r}]`,n)}if(this.variadic){if(this.postfix)e.const("firstPostfixIndex",`data.length${this.postfix?`- ${this.postfix.length}`:""}`);if(e.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>e.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[t,n]of this.postfix.entries()){let r=`firstPostfixIndex + ${t}`;e.traverseKey(r,`data[${r}]`,n)}}if(e.traversalKind==="Allows")e.return(!0)}_transform(e,t){t.path.push(N.intrinsic.nonNegativeIntegerString.internal);let n=super._transform(e,t);return t.path.pop(),n}expression=this.description;reduceJsonSchema(e,t){let n=t.target==="draft-07";if(this.prevariadic.length){let r=this.prevariadic.map((s)=>{let o=s.node.toJsonSchemaRecurse(t);if(s.kind==="defaultables"){let a=typeof s.default==="function"?s.default():s.default;o.default=N.intrinsic.jsonData.allows(a)?a:t.fallback.defaultValue({code:"defaultValue",base:o,value:a})}return o});if(n)e.items=r;else e.prefixItems=r}if(this.minLength)e.minItems=this.minLength;if(this.variadic){let r=this.variadic.toJsonSchemaRecurse(t);if(n&&this.prevariadic.length)e.additionalItems=r;else e.items=r;if(this.maxLength)e.maxItems=this.maxLength;if(this.postfix){let s=this.postfix.map((o)=>o.toJsonSchemaRecurse(t));e=t.fallback.arrayPostfix({code:"arrayPostfix",base:e,elements:s})}}else{if(n)e.additionalItems=!1;else e.items=!1;delete e.maxItems}return e}}var j0={},U0=(e)=>{if(!e.defaultables)return[];let t=[],n="[",r=e.prefixLength+e.defaultablesLength-1;for(let s=e.prefixLength;s<=r;s++){let[o,a]=e.defaultables[s-e.prefixLength];t.push(Vu(s,o,a)),n+=`${s}: ${o.id} = ${Kt(a)}, `}return n+="]",j0[n]??=t},td={implementation:L0,Node:I_},B0=(e)=>{let t=[];if(e.prefix)for(let n of e.prefix)t.push({kind:"prefix",node:n});if(e.defaultables)for(let[n,r]of e.defaultables)t.push({kind:"defaultables",node:n,default:r});if(e.optionals)for(let n of e.optionals)t.push({kind:"optionals",node:n});if(e.variadic)t.push({kind:"variadic",node:e.variadic});if(e.postfix)for(let n of e.postfix)t.push({kind:"postfix",node:n});return t},C_=(e)=>e.reduce((t,n)=>{if(n.kind==="variadic")t.variadic=n.node;else if(n.kind==="defaultables")t.defaultables=de(t.defaultables,[[n.node,n.default]]);else t[n.kind]=de(t[n.kind],n.node);return t},{}),nd="A postfix required element cannot follow an optional or defaultable element",q0="A postfix element requires a variadic element",Ds=(e)=>{let[t,...n]=e.l,[r,...s]=e.r;if(!t||!r)return e;let o=n[n.length-1]?.kind==="postfix",a=s[s.length-1]?.kind==="postfix",l=t.kind==="prefix"||r.kind==="prefix"?"prefix":t.kind==="postfix"||r.kind==="postfix"?"postfix":t.kind==="variadic"&&r.kind==="variadic"?"variadic":o||a?"prefix":t.kind==="defaultables"||r.kind==="defaultables"?"defaultables":"optionals";if(t.kind==="prefix"&&r.kind==="variadic"&&a){let f=Ds({...e,fixedVariants:[],r:s.map((p)=>({...p,kind:"prefix"}))});if(f.disjoint.length===0)e.fixedVariants.push(f)}else if(r.kind==="prefix"&&t.kind==="variadic"&&o){let f=Ds({...e,fixedVariants:[],l:n.map((p)=>({...p,kind:"prefix"}))});if(f.disjoint.length===0)e.fixedVariants.push(f)}let c=ke(t.node,r.node,e.ctx);if(c instanceof q)if(l==="prefix"||l==="postfix")e.disjoint.push(...c.withPrefixKey(l==="prefix"?e.result.length:`-${n.length+1}`,O_(t)&&O_(r)?"required":"optional")),e.result=[...e.result,{kind:l,node:N.intrinsic.never.internal}];else if(l==="optionals"||l==="defaultables")return e;else return Ds({...e,fixedVariants:[],l:n.map((f)=>({...f,kind:"prefix"})),r:n.map((f)=>({...f,kind:"prefix"}))});else if(l==="defaultables"){if(t.kind==="defaultables"&&r.kind==="defaultables"&&t.default!==r.default)C(Gu(t.default,r.default));e.result=[...e.result,{kind:l,node:c,default:t.kind==="defaultables"?t.default:r.kind==="defaultables"?r.default:he(`Unexpected defaultable intersection from ${t.kind} and ${r.kind} elements.`)}]}else e.result=[...e.result,{kind:l,node:c}];let u=e.l.length,d=e.r.length;if(t.kind!=="variadic"||u>=d&&(r.kind==="variadic"||d===1))e.l=n;if(r.kind!=="variadic"||d>=u&&(t.kind==="variadic"||u===1))e.r=s;return Ds(e)},O_=(e)=>e.kind==="prefix"||e.kind==="postfix";var F_=(e)=>(t)=>{if(t.props.length||t.index){let n=t.index?.map((s)=>s[e])??[];for(let s of t.props)n.push(s[e]);if(t.undeclared)n.push(`+ (undeclared): ${t.undeclared}`);let r=`{ ${n.join(", ")} }`;return t.sequence?`${r} & ${t.sequence.description}`:r}return t.sequence?.description??"{}"},H0=F_("description"),K0=F_("expression"),P_=(e,t,n)=>{let r=e.required?"required":"optional";if(!t.signature.allows(e.key))return null;let s=Ct(e.value,t.value,n);if(s instanceof q)return r==="optional"?n.node("optional",{key:e.key,value:N.intrinsic.never.internal}):s.withPrefixKey(e.key,e.kind);return null},W0=ae({kind:"structure",hasAssociatedError:!1,normalize:(e)=>e,applyConfig:(e,t)=>{if(!e.undeclared&&t.onUndeclaredKey!=="ignore")return{...e,undeclared:t.onUndeclaredKey};return e},keys:{required:{child:!0,parse:lt("required"),reduceIo:(e,t,n)=>{t.required=de(t.required,n.map((r)=>e==="in"?r.rawIn:r.rawOut));return}},optional:{child:!0,parse:lt("optional"),reduceIo:(e,t,n)=>{if(e==="in"){t.optional=n.map((r)=>r.rawIn);return}for(let r of n)t[r.outProp.kind]=de(t[r.outProp.kind],r.outProp.rawOut)}},index:{child:!0,parse:lt("index")},sequence:{child:!0,parse:lt("sequence")},undeclared:{parse:(e)=>e==="ignore"?void 0:e,reduceIo:(e,t,n)=>{if(n==="reject"){t.undeclared="reject";return}if(e==="in")delete t.undeclared;else t.undeclared="reject"}}},defaults:{description:H0},intersections:{structure:(e,t,n)=>{let r={...e.inner},s={...t.inner},o=new q;if(e.undeclared){let c=e.keyof();for(let u of t.requiredKeys)if(!c.allows(u))o.add("presence",N.intrinsic.never.internal,t.propsByKey[u].value,{path:[u]});if(s.optional)s.optional=s.optional.filter((u)=>c.allows(u.key));if(s.index)s.index=s.index.flatMap((u)=>{if(u.signature.extends(c))return u;let d=Ct(c,u.signature,n.$);if(d instanceof q)return[];let f=Fa(d,u.value,n.$);if(f.required)s.required=In(s.required,f.required);if(f.optional)s.optional=In(s.optional,f.optional);return f.index??[]})}if(t.undeclared){let c=t.keyof();for(let u of e.requiredKeys)if(!c.allows(u))o.add("presence",e.propsByKey[u].value,N.intrinsic.never.internal,{path:[u]});if(r.optional)r.optional=r.optional.filter((u)=>c.allows(u.key));if(r.index)r.index=r.index.flatMap((u)=>{if(u.signature.extends(c))return u;let d=Ct(c,u.signature,n.$);if(d instanceof q)return[];let f=Fa(d,u.value,n.$);if(f.required)r.required=In(r.required,f.required);if(f.optional)r.optional=In(r.optional,f.optional);return f.index??[]})}let a={};if(e.undeclared||t.undeclared)a.undeclared=e.undeclared==="reject"||t.undeclared==="reject"?"reject":"delete";let l=yi({kind:"structure",baseInner:a,l:bi(r),r:bi(s),roots:[],ctx:n});if(l instanceof q)o.push(...l);if(o.length)return o;return l}},reduce:(e,t)=>{if(!e.required&&!e.optional)return;let n={},r=!1,s=e.optional?[...e.optional]:[];if(e.required)for(let o=0;o<e.required.length;o++){let a=e.required[o];if(a.key in n)C(T_(a.key));if(n[a.key]=!0,e.index)for(let l of e.index){let c=P_(a,l,t);if(c instanceof q)return c}}if(e.optional)for(let o=0;o<e.optional.length;o++){let a=e.optional[o];if(a.key in n)C(T_(a.key));if(n[a.key]=!0,e.index)for(let l of e.index){let c=P_(a,l,t);if(c instanceof q)return c;if(c!==null)s[o]=c,r=!0}}if(r)return t.node("structure",{...e,optional:s},{prereduced:!0})}});class N_ extends Wt{impliedBasis=N.intrinsic.object.internal;impliedSiblings=this.children.flatMap((e)=>e.impliedSiblings??[]);props=In(this.required,this.optional);propsByKey=ie(this.props,(e,t)=>[t.key,t]);propsByKeyReference=Me(this.propsByKey);expression=K0(this);requiredKeys=this.required?.map((e)=>e.key)??[];optionalKeys=this.optional?.map((e)=>e.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let e=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:t}of this.index)e=e.concat(t.branches);return this._keyof=this.$.node("union",e)}map(e){return this.$.node("structure",this.props.flatMap(e).reduce((t,n)=>{let r=this.propsByKey[n.key];if($e(n)){if(n.kind!=="required"&&n.kind!=="optional")return C(`Map result must have kind "required" or "optional" (was ${n.kind})`);return t[n.kind]=de(t[n.kind],n),t}let s=n.kind??r?.kind??"required",o=ie(n,(a,l)=>(a in Ps.implementation.keys)?[a,l]:[]);return t[s]=de(t[s],this.$.node(s,o)),t},{}))}assertHasKeys(e){let t=e.filter((n)=>!Ts(n,this.keyof()));if(t.length)return C(M_(this.expression,t))}get(e,...t){let n,r=!1,s=J0(e);if((typeof s==="string"||typeof s==="symbol")&&this.propsByKey[s])n=this.propsByKey[s].value,r=this.propsByKey[s].required;if(this.index){for(let a of this.index)if(Ts(s,a.signature))n=n?.and(a.value)??a.value}if(this.sequence&&Ts(s,N.intrinsic.nonNegativeIntegerString))if(X(s,"root")){if(this.sequence.variadic)n=n?.and(this.sequence.element)??this.sequence.element}else{let a=Number.parseInt(s);if(a<this.sequence.prevariadic.length){let l=this.sequence.prevariadic[a].node;n=n?.and(l)??l,r||=a<this.sequence.prefixLength}else if(this.sequence.variadic){let l=this.$.node("union",this.sequence.variadicOrPostfix);n=n?.and(l)??l}}if(!n){if(this.sequence?.variadic&&X(s,"root")&&s.extends(N.intrinsic.number))return C(X0(s.expression,this.sequence.expression));return C(M_(this.expression,[s]))}let o=n.get(...t);return r?o:o.or(N.intrinsic.undefined)}pick(...e){return this.assertHasKeys(e),this.$.node("structure",this.filterKeys("pick",e))}omit(...e){return this.assertHasKeys(e),this.$.node("structure",this.filterKeys("omit",e))}optionalize(){let{required:e,...t}=this.inner;return this.$.node("structure",{...t,optional:this.props.map((n)=>n.hasKind("required")?this.$.node("optional",n.inner):n)})}require(){let{optional:e,...t}=this.inner;return this.$.node("structure",{...t,required:this.props.map((n)=>n.hasKind("optional")?{key:n.key,value:n.value}:n)})}merge(e){let t=this.filterKeys("omit",[e.keyof()]);if(e.required)t.required=de(t.required,e.required);if(e.optional)t.optional=de(t.optional,e.optional);if(e.index)t.index=de(t.index,e.index);if(e.sequence)t.sequence=e.sequence;if(e.undeclared)t.undeclared=e.undeclared;else delete t.undeclared;return this.$.node("structure",t)}filterKeys(e,t){let n=Sa(this.inner),r=(s)=>{let o=t.some((a)=>Ts(s,a));return e==="pick"?o:!o};if(n.required)n.required=n.required.filter((s)=>r(s.key));if(n.optional)n.optional=n.optional.filter((s)=>r(s.key));if(n.index)n.index=n.index.filter((s)=>r(s.signature));return n}traverseAllows=(e,t)=>this._traverse("Allows",e,t);traverseApply=(e,t)=>this._traverse("Apply",e,t);_traverse=(e,t,n)=>{let r=n?.currentErrorCount??0;for(let s=0;s<this.props.length;s++)if(e==="Allows"){if(!this.props[s].traverseAllows(t,n))return!1}else if(this.props[s].traverseApply(t,n),n.failFast&&n.currentErrorCount>r)return!1;if(this.sequence){if(e==="Allows"){if(!this.sequence.traverseAllows(t,n))return!1}else if(this.sequence.traverseApply(t,n),n.failFast&&n.currentErrorCount>r)return!1}if(this.index||this.undeclared==="reject"){let s=Object.keys(t);s.push(...Object.getOwnPropertySymbols(t));for(let o=0;o<s.length;o++){let a=s[o];if(this.index){for(let l of this.index)if(l.signature.traverseAllows(a,n)){if(e==="Allows"){if(!At(a,()=>l.value.traverseAllows(t[a],n),n))return!1}else if(At(a,()=>l.value.traverseApply(t[a],n),n),n.failFast&&n.currentErrorCount>r)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(a)){if(e==="Allows")return!1;if(n.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[a],meta:this.meta}),n.failFast)return!1}}}if(this.structuralMorph&&n&&!n.hasError())n.queueMorphs([this.structuralMorph]);return!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter((e)=>e.hasDefault())??[])}declaresKey=(e)=>(e in this.propsByKey)||this.index?.some((t)=>t.signature.allows(e))||this.sequence!==void 0&&N.intrinsic.nonNegativeIntegerString.allows(e);_compileDeclaresKey(e){let t=[];if(this.props.length)t.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let n of this.index)t.push(e.invoke(n.signature,{kind:"Allows",arg:"k"}));if(this.sequence)t.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return t.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",V0(this))}structuralMorphRef=this.structuralMorph&&Me(this.structuralMorph);compile(e){if(e.traversalKind==="Apply")e.initializeErrorCount();for(let t of this.props)if(e.check(t),e.traversalKind==="Apply")e.returnIfFailFast();if(this.sequence){if(e.check(this.sequence),e.traversalKind==="Apply")e.returnIfFailFast()}if(this.index||this.undeclared==="reject")e.const("keys","Object.keys(data)"),e.line("keys.push(...Object.getOwnPropertySymbols(data))"),e.for("i < keys.length",()=>this.compileExhaustiveEntry(e));if(e.traversalKind==="Allows")return e.return(!0);if(this.structuralMorphRef)e.if("ctx && !ctx.hasError()",()=>(e.line("ctx.queueMorphs(["),z0(e,this),e.line("])")))}compileExhaustiveEntry(e){if(e.const("k","keys[i]"),this.index)for(let t of this.index)e.if(`${e.invoke(t.signature,{arg:"k",kind:"Allows"})}`,()=>e.traverseKey("k","data[k]",t.value));if(this.undeclared==="reject")e.if(`!(${this._compileDeclaresKey(e)})`,()=>{if(e.traversalKind==="Allows")return e.return(!1);return e.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>e.return())});return e}reduceJsonSchema(e,t){switch(e.type){case"object":return this.reduceObjectJsonSchema(e,t);case"array":let n=this.sequence?.reduceJsonSchema(e,t)??e;if(this.props.length||this.index)return t.fallback.arrayObject({code:"arrayObject",base:n,object:this.reduceObjectJsonSchema({type:"object"},t)});return n;default:return Ee.throwInternalOperandError("structure",e)}}reduceObjectJsonSchema(e,t){if(this.props.length){e.properties={};for(let n of this.props){let r=n.value.toJsonSchemaRecurse(t);if(typeof n.key==="symbol"){t.fallback.symbolKey({code:"symbolKey",base:e,key:n.key,value:r,optional:n.optional});continue}if(n.hasDefault()){let s=typeof n.default==="function"?n.default():n.default;r.default=N.intrinsic.jsonData.allows(s)?s:t.fallback.defaultValue({code:"defaultValue",base:r,value:s})}e.properties[n.key]=r}if(this.requiredKeys.length&&e.properties)e.required=this.requiredKeys.filter((n)=>typeof n==="string"&&(n in e.properties))}if(this.index)for(let n of this.index){let r=n.value.toJsonSchemaRecurse(t);if(n.signature.equals(N.intrinsic.string)){e.additionalProperties=r;continue}for(let s of n.signature.branches){if(!s.extends(N.intrinsic.string)){e=t.fallback.symbolKey({code:"symbolKey",base:e,key:null,value:r,optional:!1});continue}let o={type:"string"};if(s.hasKind("morph"))o=t.fallback.morph({code:"morph",base:s.rawIn.toJsonSchemaRecurse(t),out:s.rawOut.toJsonSchemaRecurse(t)});if(!s.hasKind("intersection"))return he(`Unexpected index branch kind ${s.kind}.`);let{pattern:a}=s.inner;if(a){let l=Object.assign(o,{pattern:a[0].rule});for(let c=1;c<a.length;c++)o=t.fallback.patternIntersection({code:"patternIntersection",base:l,pattern:a[c].rule});e.patternProperties??={},e.patternProperties[l.pattern]=r}}}if(this.undeclared&&!e.additionalProperties)e.additionalProperties=!1;return e}}var rd={},G0=(e)=>{let t="";for(let n=0;n<e.defaultable.length;n++)t+=e.defaultable[n].defaultValueMorphRef;if(e.sequence?.defaultValueMorphsReference)t+=e.sequence?.defaultValueMorphsReference;if(e.undeclared==="delete"){if(t+="delete !(",e.required)for(let n of e.required)t+=n.compiledKey+" | ";if(e.optional)for(let n of e.optional)t+=n.compiledKey+" | ";if(e.index)for(let n of e.index)t+=n.signature.id+" | ";if(e.sequence)if(e.sequence.maxLength===null)t+=ee.nonNegativeIntegerString.id;else for(let n=0;n<e.sequence.tuple.length;n++)t+=n+" | ";t+=")"}return t},V0=(e)=>{let t=G0(e);if(!t)return;if(rd[t])return rd[t];let n=(r,s)=>{for(let o=0;o<e.defaultable.length;o++)if(!(e.defaultable[o].key in r))e.defaultable[o].defaultValueMorph(r,s);if(e.sequence?.defaultables)for(let o=r.length-e.sequence.prefixLength;o<e.sequence.defaultables.length;o++)e.sequence.defaultValueMorphs[o](r,s);if(e.undeclared==="delete"){for(let o in r)if(!e.declaresKey(o))delete r[o]}return r};return rd[t]=n},z0=(e,t)=>{let r=`(data${t.defaultable.some((s)=>s.defaultValueMorph.length===2)||t.sequence?.defaultValueMorphs.some((s)=>s.length===2)?", ctx":""})`;return e.block(`${r} => `,(s)=>{for(let o=0;o<t.defaultable.length;o++){let{serializedKey:a,defaultValueMorphRef:l}=t.defaultable[o];s.if(`!(${a} in data)`,(c)=>c.line(`${l}${r}`))}if(t.sequence?.defaultables)s.for(`i < ${t.sequence.defaultables.length}`,(o)=>o.set("data[i]",5),`data.length - ${t.sequence.prefixLength}`);if(t.undeclared==="delete")s.forIn("data",(o)=>o.if(`!(${t._compileDeclaresKey(o)})`,(a)=>a.line("delete data[k]")));return s.return("data")})},id={implementation:W0,Node:N_},J0=(e)=>{if(X(e,"root")&&e.hasKind("unit"))e=e.unit;if(typeof e==="number")e=`${e}`;return e},X0=(e,t)=>`${e} is not allowed as an array index on ${t}. Use the 'nonNegativeIntegerString' keyword instead.`,Fa=(e,t,n)=>{let[r,s]=Zm(e.branches,(a)=>a.hasKind("unit"));if(!r.length)return{index:n.node("index",{signature:e,value:t})};let o={};for(let a of r){let l=n.node("required",{key:a.unit,value:t});o[l.kind]=de(o[l.kind],l)}if(s.length)o.index=n.node("index",{signature:s,value:t});return o},Y0=(e)=>X(e,"root")?e.expression:se(e),M_=(e,t)=>`Key${t.length===1?"":"s"} ${t.map(Y0).join(", ")} ${t.length===1?"does":"do"} not exist on ${e}`,T_=(e)=>`Duplicate key ${rn(e)}`;var xi={...n_,alias:Fs.implementation,domain:Ta.implementation,unit:Zu.implementation,proto:Ns.implementation,union:Yu.implementation,morph:Ju.implementation,intersection:zu.implementation,divisor:Tu.implementation,pattern:qu.implementation,predicate:Mu.implementation,required:ed.implementation,optional:Ps.implementation,index:Qu.implementation,sequence:td.implementation,structure:id.implementation};N.defaultConfig=ag(Object.assign(ie(xi,(e,t)=>[e,t.defaults]),{jitless:pg(),clone:ug,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:Ee.defaultConfig}));N.resolvedConfig=$s(N.defaultConfig,N.config);var l_={...r_,alias:Fs.Node,domain:Ta.Node,unit:Zu.Node,proto:Ns.Node,union:Yu.Node,morph:Ju.Node,intersection:zu.Node,divisor:Tu.Node,pattern:qu.Node,predicate:Mu.Node,required:ed.Node,optional:Ps.Node,index:Qu.Node,sequence:td.Node,structure:id.Node};class $i extends hu{get[ht](){return"module"}}var sd=(e,t)=>new $i(ie(e,(n,r)=>[n,X(r,"module")?sd(r,t):t.bindReference(r)]));var Z0=(e)=>Re(e)?e:("branches"in e)&&Re(e.branches)?e.branches:void 0,Q0=(e,t)=>C(`Node of kind ${t} is not valid as a ${e} definition`),D_=(e)=>`#${e} duplicates public alias ${e}`,od={};N.ambient??={};var L_,U_="function $",eA=(e)=>B_(e,q_(e)),B_=(e,t)=>{let n=t.write(U_,4),r=t.compile()();for(let s of e){if(s.precompilation)continue;if(s.traverseAllows=r[`${s.id}Allows`].bind(r),s.isRoot()&&!s.allowsRequiresContext)s.allows=s.traverseAllows;if(s.traverseApply=r[`${s.id}Apply`].bind(r),r[`${s.id}Optimistic`])s.traverseOptimistic=r[`${s.id}Optimistic`].bind(r);s.precompilation=n}},q_=(e)=>new Ra().return(e.reduce((t,n)=>{let r=new Ss({kind:"Allows"}).indent();n.compile(r);let s=r.write(`${n.id}Allows`),o=new Ss({kind:"Apply"}).indent();n.compile(o);let a=o.write(`${n.id}Apply`),l=`${t}${s},
612
+ Right: ${t}`;var v0=ae({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(e)=>e instanceof Date?e.toISOString():Gt(e)}},normalize:(e)=>e,defaults:{description:(e)=>se(e.unit),problem:({expected:e,actual:t})=>`${e===t?`must be reference equal to ${e} (serialized to the same value)`:`must be ${e} (was ${t})`}`},intersections:{unit:(e,t)=>q.init("unit",e,t),...xn("unit",(e,t)=>{if(t.allows(e.unit))return e;let n=t.hasKind("intersection")?t.basis:t;if(n){let r=n.hasKind("domain")?n:N.intrinsic.object;if(e.domain!==r.domain){let s=e.domain==="undefined"||e.domain==="null"||e.domain==="boolean"?e.domain:N.intrinsic[e.domain];return q.init("domain",s,r)}}return q.init("assignability",e,t.hasKind("intersection")?t.children.find((r)=>!r.allows(e.unit)):t)})}});class Y_ extends Lr{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=X_(this.unit,this.serializedValue);compiledNegation=X_(this.unit,this.serializedValue,"negated");expression=se(this.unit);domain=Ke(this.unit);get defaultShortDescription(){return this.domain==="object"?Rt.object:this.description}innerToJsonSchema(e){return this.unit===null?{type:"null"}:N.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:e.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?(e)=>e instanceof Date&&e.toISOString()===this.compiledValue:Number.isNaN(this.unit)?(e)=>Number.isNaN(e):(e)=>e===this.unit}var dd={implementation:v0,Node:Y_},X_=(e,t,n)=>{if(e instanceof Date){let r=`data instanceof Date && data.toISOString() === ${t}`;return n?`!(${r})`:r}if(Number.isNaN(e))return`${n?"!":""}Number.isNaN(data)`;return`data ${n?"!":"="}== ${t}`};var x0=ae({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(e,t)=>{let n=t.$.parseSchema(e);if(!n.extends(N.intrinsic.key))return A(R0(n.expression));let r=n.branches.filter((s)=>s.hasKind("unit"));if(r.length)return A(S0(r.map((s)=>se(s.unit))));return n}},value:{child:!0,parse:(e,t)=>t.$.parseSchema(e)}},normalize:(e)=>e,defaults:{description:(e)=>`[${e.signature.expression}]: ${e.value.description}`},intersections:{index:(e,t,n)=>{if(e.signature.equals(t.signature)){let r=ke(e.value,t.value,n),s=r instanceof q?N.intrinsic.never.internal:r;return n.$.node("index",{signature:e.signature,value:s})}if(e.signature.extends(t.signature)&&e.value.subsumes(t.value))return t;if(t.signature.extends(e.signature)&&t.value.subsumes(e.value))return e;return null}}});class Z_ extends Wt{impliedBasis=N.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=de(this.value.flatRefs.map((e)=>ln([this.signature,...e.path],e.node)),ln([this.signature],this.value));traverseAllows=(e,t)=>Mr(e).every((n)=>{if(this.signature.traverseAllows(n[0],t))return Ct(n[0],()=>this.value.traverseAllows(n[1],t),t);return!0});traverseApply=(e,t)=>{for(let n of Mr(e))if(this.signature.traverseAllows(n[0],t))Ct(n[0],()=>this.value.traverseApply(n[1],t),t)};_transform(e,t){t.path.push(this.signature);let n=super._transform(e,t);return t.path.pop(),n}compile(){}}var fd={implementation:x0,Node:Z_},S0=(e)=>`Index keys ${e.join(", ")} should be specified as named props.`,R0=(e)=>`Indexed key definition '${e}' must be a string or symbol`;var $0=ae({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(e,t)=>t.$.parseSchema(e)}},normalize:(e)=>e,defaults:{description:(e)=>`${e.compiledKey}: ${e.value.description}`,expected:(e)=>e.missingValueDescription,actual:()=>"missing"},intersections:{required:Ls,optional:Ls}});class Q_ extends js{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=ar(this.errorContext)}var pd={implementation:$0,Node:Q_};var k0=ae({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(e,t)=>{if(e.length===0)return;return e.map((n)=>t.$.parseSchema(n))}},optionals:{child:!0,parse:(e,t)=>{if(e.length===0)return;return e.map((n)=>t.$.parseSchema(n))}},defaultables:{child:(e)=>e.map((t)=>t[0]),parse:(e,t)=>{if(e.length===0)return;return e.map((n)=>{let r=t.$.parseSchema(n[0]);return Bs(r,n[1],null),[r,n[1]]})},serialize:(e)=>e.map((t)=>[t[0].collapsibleJson,Gt(t[1])]),reduceIo:(e,t,n)=>{if(e==="in"){t.optionals=n.map((r)=>r[0].rawIn);return}t.prefix=n.map((r)=>r[0].rawOut);return}},variadic:{child:!0,parse:(e,t)=>t.$.parseSchema(e,t)},minVariadicLength:{parse:(e)=>e===0?void 0:e},postfix:{child:!0,parse:(e,t)=>{if(e.length===0)return;return e.map((n)=>t.$.parseSchema(n))}}},normalize:(e)=>{if(typeof e==="string")return{variadic:e};if("variadic"in e||"prefix"in e||"defaultables"in e||"optionals"in e||"postfix"in e||"minVariadicLength"in e){if(e.postfix?.length){if(!e.variadic)return A(O0);if(e.optionals?.length||e.defaultables?.length)return A(md)}if(e.minVariadicLength&&!e.variadic)return A("minVariadicLength may not be specified without a variadic element");return e}return{variadic:e}},reduce:(e,t)=>{let n=e.minVariadicLength??0,r=e.prefix?.slice()??[],s=e.defaultables?.slice()??[],o=e.optionals?.slice()??[],a=e.postfix?.slice()??[];if(e.variadic){while(o[o.length-1]?.equals(e.variadic))o.pop();if(o.length===0&&s.length===0)while(r[r.length-1]?.equals(e.variadic))r.pop(),n++;while(a[0]?.equals(e.variadic))a.shift(),n++}else if(o.length===0&&s.length===0)r.push(...a.splice(0));if(n!==e.minVariadicLength||e.prefix&&e.prefix.length!==r.length)return t.node("sequence",{...e,prefix:r,defaultables:s,optionals:o,postfix:a,minVariadicLength:n},{prereduced:!0})},defaults:{description:(e)=>{if(e.isVariadicOnly)return`${e.variadic.nestableExpression}[]`;return`[${e.tuple.map((n)=>n.kind==="defaultables"?`${n.node.nestableExpression} = ${se(n.default)}`:n.kind==="optionals"?`${n.node.nestableExpression}?`:n.kind==="variadic"?`...${n.node.nestableExpression}[]`:n.node.expression).join(", ")}]`}},intersections:{sequence:(e,t,n)=>{let r=Gs({l:e.tuple,r:t.tuple,disjoint:new q,result:[],fixedVariants:[],ctx:n}),s=r.disjoint.length===0?[r,...r.fixedVariants]:r.fixedVariants;return s.length===0?r.disjoint:s.length===1?n.$.node("sequence",ew(s[0].result)):n.$.node("union",s.map((o)=>({proto:Array,sequence:ew(o.result)})))}}});class nw extends Wt{impliedBasis=N.intrinsic.Array.internal;tuple=A0(this.inner);prefixLength=this.prefix?.length??0;defaultablesLength=this.defaultables?.length??0;optionalsLength=this.optionals?.length??0;postfixLength=this.postfix?.length??0;defaultablesAndOptionals=[];prevariadic=this.tuple.filter((e)=>{if(e.kind==="defaultables"||e.kind==="optionals")return this.defaultablesAndOptionals.push(e.node),!0;return e.kind==="prefix"});variadicOrPostfix=Mn(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return qu(this.flatRefs,this.prevariadic.flatMap((e,t)=>de(e.node.flatRefs.map((n)=>ln([`${t}`,...n.path],n.node)),ln([`${t}`],e.node)))),qu(this.flatRefs,this.variadicOrPostfix.flatMap((e)=>de(e.flatRefs.map((t)=>ln([N.intrinsic.nonNegativeIntegerString.internal,...t.path],t.node)),ln([N.intrinsic.nonNegativeIntegerString.internal],e)))),this.flatRefs}isVariadicOnly=this.prevariadic.length+this.postfixLength===0;minVariadicLength=this.inner.minVariadicLength??0;minLength=this.prefixLength+this.minVariadicLength+this.postfixLength;minLengthNode=this.minLength===0?null:this.$.node("minLength",this.minLength);maxLength=this.variadic?null:this.tuple.length;maxLengthNode=this.maxLength===null?null:this.$.node("maxLength",this.maxLength);impliedSiblings=this.minLengthNode?this.maxLengthNode?[this.minLengthNode,this.maxLengthNode]:[this.minLengthNode]:this.maxLengthNode?[this.maxLengthNode]:[];defaultValueMorphs=C0(this);defaultValueMorphsReference=this.defaultValueMorphs.length?Me(this.defaultValueMorphs):void 0;elementAtIndex(e,t){if(t<this.prevariadic.length)return this.tuple[t];let n=e.length-this.postfixLength;if(t>=n)return{kind:"postfix",node:this.postfix[t-n]};return{kind:"variadic",node:this.variadic??he(`Unexpected attempt to access index ${t} on ${this}`)}}traverseAllows=(e,t)=>{for(let n=0;n<e.length;n++)if(!this.elementAtIndex(e,n).node.traverseAllows(e[n],t))return!1;return!0};traverseApply=(e,t)=>{let n=0;for(;n<e.length;n++)Ct(n,()=>this.elementAtIndex(e,n).node.traverseApply(e[n],t),t)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(e){if(this.prefix)for(let[t,n]of this.prefix.entries())e.traverseKey(`${t}`,`data[${t}]`,n);for(let[t,n]of this.defaultablesAndOptionals.entries()){let r=`${t+this.prefixLength}`;e.if(`${r} >= data.length`,()=>e.traversalKind==="Allows"?e.return(!0):e.return()),e.traverseKey(r,`data[${r}]`,n)}if(this.variadic){if(this.postfix)e.const("firstPostfixIndex",`data.length${this.postfix?`- ${this.postfix.length}`:""}`);if(e.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>e.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[t,n]of this.postfix.entries()){let r=`firstPostfixIndex + ${t}`;e.traverseKey(r,`data[${r}]`,n)}}if(e.traversalKind==="Allows")e.return(!0)}_transform(e,t){t.path.push(N.intrinsic.nonNegativeIntegerString.internal);let n=super._transform(e,t);return t.path.pop(),n}expression=this.description;reduceJsonSchema(e,t){let n=t.target==="draft-07";if(this.prevariadic.length){let r=this.prevariadic.map((s)=>{let o=s.node.toJsonSchemaRecurse(t);if(s.kind==="defaultables"){let a=typeof s.default==="function"?s.default():s.default;o.default=N.intrinsic.jsonData.allows(a)?a:t.fallback.defaultValue({code:"defaultValue",base:o,value:a})}return o});if(n)e.items=r;else e.prefixItems=r}if(this.minLength)e.minItems=this.minLength;if(this.variadic){let r=this.variadic.toJsonSchemaRecurse(t);if(n&&this.prevariadic.length)e.additionalItems=r;else e.items=r;if(this.maxLength)e.maxItems=this.maxLength;if(this.postfix){let s=this.postfix.map((o)=>o.toJsonSchemaRecurse(t));e=t.fallback.arrayPostfix({code:"arrayPostfix",base:e,elements:s})}}else{if(n)e.additionalItems=!1;else e.items=!1;delete e.maxItems}return e}}var E0={},C0=(e)=>{if(!e.defaultables)return[];let t=[],n="[",r=e.prefixLength+e.defaultablesLength-1;for(let s=e.prefixLength;s<=r;s++){let[o,a]=e.defaultables[s-e.prefixLength];t.push(od(s,o,a)),n+=`${s}: ${o.id} = ${Gt(a)}, `}return n+="]",E0[n]??=t},hd={implementation:k0,Node:nw},A0=(e)=>{let t=[];if(e.prefix)for(let n of e.prefix)t.push({kind:"prefix",node:n});if(e.defaultables)for(let[n,r]of e.defaultables)t.push({kind:"defaultables",node:n,default:r});if(e.optionals)for(let n of e.optionals)t.push({kind:"optionals",node:n});if(e.variadic)t.push({kind:"variadic",node:e.variadic});if(e.postfix)for(let n of e.postfix)t.push({kind:"postfix",node:n});return t},ew=(e)=>e.reduce((t,n)=>{if(n.kind==="variadic")t.variadic=n.node;else if(n.kind==="defaultables")t.defaultables=de(t.defaultables,[[n.node,n.default]]);else t[n.kind]=de(t[n.kind],n.node);return t},{}),md="A postfix required element cannot follow an optional or defaultable element",O0="A postfix element requires a variadic element",Gs=(e)=>{let[t,...n]=e.l,[r,...s]=e.r;if(!t||!r)return e;let o=n[n.length-1]?.kind==="postfix",a=s[s.length-1]?.kind==="postfix",l=t.kind==="prefix"||r.kind==="prefix"?"prefix":t.kind==="postfix"||r.kind==="postfix"?"postfix":t.kind==="variadic"&&r.kind==="variadic"?"variadic":o||a?"prefix":t.kind==="defaultables"||r.kind==="defaultables"?"defaultables":"optionals";if(t.kind==="prefix"&&r.kind==="variadic"&&a){let f=Gs({...e,fixedVariants:[],r:s.map((p)=>({...p,kind:"prefix"}))});if(f.disjoint.length===0)e.fixedVariants.push(f)}else if(r.kind==="prefix"&&t.kind==="variadic"&&o){let f=Gs({...e,fixedVariants:[],l:n.map((p)=>({...p,kind:"prefix"}))});if(f.disjoint.length===0)e.fixedVariants.push(f)}let c=ke(t.node,r.node,e.ctx);if(c instanceof q)if(l==="prefix"||l==="postfix")e.disjoint.push(...c.withPrefixKey(l==="prefix"?e.result.length:`-${n.length+1}`,tw(t)&&tw(r)?"required":"optional")),e.result=[...e.result,{kind:l,node:N.intrinsic.never.internal}];else if(l==="optionals"||l==="defaultables")return e;else return Gs({...e,fixedVariants:[],l:n.map((f)=>({...f,kind:"prefix"})),r:n.map((f)=>({...f,kind:"prefix"}))});else if(l==="defaultables"){if(t.kind==="defaultables"&&r.kind==="defaultables"&&t.default!==r.default)A(sd(t.default,r.default));e.result=[...e.result,{kind:l,node:c,default:t.kind==="defaultables"?t.default:r.kind==="defaultables"?r.default:he(`Unexpected defaultable intersection from ${t.kind} and ${r.kind} elements.`)}]}else e.result=[...e.result,{kind:l,node:c}];let u=e.l.length,d=e.r.length;if(t.kind!=="variadic"||u>=d&&(r.kind==="variadic"||d===1))e.l=n;if(r.kind!=="variadic"||d>=u&&(t.kind==="variadic"||u===1))e.r=s;return Gs(e)},tw=(e)=>e.kind==="prefix"||e.kind==="postfix";var ow=(e)=>(t)=>{if(t.props.length||t.index){let n=t.index?.map((s)=>s[e])??[];for(let s of t.props)n.push(s[e]);if(t.undeclared)n.push(`+ (undeclared): ${t.undeclared}`);let r=`{ ${n.join(", ")} }`;return t.sequence?`${r} & ${t.sequence.description}`:r}return t.sequence?.description??"{}"},I0=ow("description"),P0=ow("expression"),rw=(e,t,n)=>{let r=e.required?"required":"optional";if(!t.signature.allows(e.key))return null;let s=At(e.value,t.value,n);if(s instanceof q)return r==="optional"?n.node("optional",{key:e.key,value:N.intrinsic.never.internal}):s.withPrefixKey(e.key,e.kind);return null},M0=ae({kind:"structure",hasAssociatedError:!1,normalize:(e)=>e,applyConfig:(e,t)=>{if(!e.undeclared&&t.onUndeclaredKey!=="ignore")return{...e,undeclared:t.onUndeclaredKey};return e},keys:{required:{child:!0,parse:lt("required"),reduceIo:(e,t,n)=>{t.required=de(t.required,n.map((r)=>e==="in"?r.rawIn:r.rawOut));return}},optional:{child:!0,parse:lt("optional"),reduceIo:(e,t,n)=>{if(e==="in"){t.optional=n.map((r)=>r.rawIn);return}for(let r of n)t[r.outProp.kind]=de(t[r.outProp.kind],r.outProp.rawOut)}},index:{child:!0,parse:lt("index")},sequence:{child:!0,parse:lt("sequence")},undeclared:{parse:(e)=>e==="ignore"?void 0:e,reduceIo:(e,t,n)=>{if(n==="reject"){t.undeclared="reject";return}if(e==="in")delete t.undeclared;else t.undeclared="reject"}}},defaults:{description:I0},intersections:{structure:(e,t,n)=>{let r={...e.inner},s={...t.inner},o=new q;if(e.undeclared){let c=e.keyof();for(let u of t.requiredKeys)if(!c.allows(u))o.add("presence",N.intrinsic.never.internal,t.propsByKey[u].value,{path:[u]});if(s.optional)s.optional=s.optional.filter((u)=>c.allows(u.key));if(s.index)s.index=s.index.flatMap((u)=>{if(u.signature.extends(c))return u;let d=At(c,u.signature,n.$);if(d instanceof q)return[];let f=Ha(d,u.value,n.$);if(f.required)s.required=Mn(s.required,f.required);if(f.optional)s.optional=Mn(s.optional,f.optional);return f.index??[]})}if(t.undeclared){let c=t.keyof();for(let u of e.requiredKeys)if(!c.allows(u))o.add("presence",e.propsByKey[u].value,N.intrinsic.never.internal,{path:[u]});if(r.optional)r.optional=r.optional.filter((u)=>c.allows(u.key));if(r.index)r.index=r.index.flatMap((u)=>{if(u.signature.extends(c))return u;let d=At(c,u.signature,n.$);if(d instanceof q)return[];let f=Ha(d,u.value,n.$);if(f.required)r.required=Mn(r.required,f.required);if(f.optional)r.optional=Mn(r.optional,f.optional);return f.index??[]})}let a={};if(e.undeclared||t.undeclared)a.undeclared=e.undeclared==="reject"||t.undeclared==="reject"?"reject":"delete";let l=Ri({kind:"structure",baseInner:a,l:$i(r),r:$i(s),roots:[],ctx:n});if(l instanceof q)o.push(...l);if(o.length)return o;return l}},reduce:(e,t)=>{if(!e.required&&!e.optional)return;let n={},r=!1,s=e.optional?[...e.optional]:[];if(e.required)for(let o=0;o<e.required.length;o++){let a=e.required[o];if(a.key in n)A(sw(a.key));if(n[a.key]=!0,e.index)for(let l of e.index){let c=rw(a,l,t);if(c instanceof q)return c}}if(e.optional)for(let o=0;o<e.optional.length;o++){let a=e.optional[o];if(a.key in n)A(sw(a.key));if(n[a.key]=!0,e.index)for(let l of e.index){let c=rw(a,l,t);if(c instanceof q)return c;if(c!==null)s[o]=c,r=!0}}if(r)return t.node("structure",{...e,optional:s},{prereduced:!0})}});class aw extends Wt{impliedBasis=N.intrinsic.object.internal;impliedSiblings=this.children.flatMap((e)=>e.impliedSiblings??[]);props=Mn(this.required,this.optional);propsByKey=ie(this.props,(e,t)=>[t.key,t]);propsByKeyReference=Me(this.propsByKey);expression=P0(this);requiredKeys=this.required?.map((e)=>e.key)??[];optionalKeys=this.optional?.map((e)=>e.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let e=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:t}of this.index)e=e.concat(t.branches);return this._keyof=this.$.node("union",e)}map(e){return this.$.node("structure",this.props.flatMap(e).reduce((t,n)=>{let r=this.propsByKey[n.key];if($e(n)){if(n.kind!=="required"&&n.kind!=="optional")return A(`Map result must have kind "required" or "optional" (was ${n.kind})`);return t[n.kind]=de(t[n.kind],n),t}let s=n.kind??r?.kind??"required",o=ie(n,(a,l)=>(a in Us.implementation.keys)?[a,l]:[]);return t[s]=de(t[s],this.$.node(s,o)),t},{}))}assertHasKeys(e){let t=e.filter((n)=>!qs(n,this.keyof()));if(t.length)return A(iw(this.expression,t))}get(e,...t){let n,r=!1,s=F0(e);if((typeof s==="string"||typeof s==="symbol")&&this.propsByKey[s])n=this.propsByKey[s].value,r=this.propsByKey[s].required;if(this.index){for(let a of this.index)if(qs(s,a.signature))n=n?.and(a.value)??a.value}if(this.sequence&&qs(s,N.intrinsic.nonNegativeIntegerString))if(X(s,"root")){if(this.sequence.variadic)n=n?.and(this.sequence.element)??this.sequence.element}else{let a=Number.parseInt(s);if(a<this.sequence.prevariadic.length){let l=this.sequence.prevariadic[a].node;n=n?.and(l)??l,r||=a<this.sequence.prefixLength}else if(this.sequence.variadic){let l=this.$.node("union",this.sequence.variadicOrPostfix);n=n?.and(l)??l}}if(!n){if(this.sequence?.variadic&&X(s,"root")&&s.extends(N.intrinsic.number))return A(L0(s.expression,this.sequence.expression));return A(iw(this.expression,[s]))}let o=n.get(...t);return r?o:o.or(N.intrinsic.undefined)}pick(...e){return this.assertHasKeys(e),this.$.node("structure",this.filterKeys("pick",e))}omit(...e){return this.assertHasKeys(e),this.$.node("structure",this.filterKeys("omit",e))}optionalize(){let{required:e,...t}=this.inner;return this.$.node("structure",{...t,optional:this.props.map((n)=>n.hasKind("required")?this.$.node("optional",n.inner):n)})}require(){let{optional:e,...t}=this.inner;return this.$.node("structure",{...t,required:this.props.map((n)=>n.hasKind("optional")?{key:n.key,value:n.value}:n)})}merge(e){let t=this.filterKeys("omit",[e.keyof()]);if(e.required)t.required=de(t.required,e.required);if(e.optional)t.optional=de(t.optional,e.optional);if(e.index)t.index=de(t.index,e.index);if(e.sequence)t.sequence=e.sequence;if(e.undeclared)t.undeclared=e.undeclared;else delete t.undeclared;return this.$.node("structure",t)}filterKeys(e,t){let n=Pa(this.inner),r=(s)=>{let o=t.some((a)=>qs(s,a));return e==="pick"?o:!o};if(n.required)n.required=n.required.filter((s)=>r(s.key));if(n.optional)n.optional=n.optional.filter((s)=>r(s.key));if(n.index)n.index=n.index.filter((s)=>r(s.signature));return n}traverseAllows=(e,t)=>this._traverse("Allows",e,t);traverseApply=(e,t)=>this._traverse("Apply",e,t);_traverse=(e,t,n)=>{let r=n?.currentErrorCount??0;for(let s=0;s<this.props.length;s++)if(e==="Allows"){if(!this.props[s].traverseAllows(t,n))return!1}else if(this.props[s].traverseApply(t,n),n.failFast&&n.currentErrorCount>r)return!1;if(this.sequence){if(e==="Allows"){if(!this.sequence.traverseAllows(t,n))return!1}else if(this.sequence.traverseApply(t,n),n.failFast&&n.currentErrorCount>r)return!1}if(this.index||this.undeclared==="reject"){let s=Object.keys(t);s.push(...Object.getOwnPropertySymbols(t));for(let o=0;o<s.length;o++){let a=s[o];if(this.index){for(let l of this.index)if(l.signature.traverseAllows(a,n)){if(e==="Allows"){if(!Ct(a,()=>l.value.traverseAllows(t[a],n),n))return!1}else if(Ct(a,()=>l.value.traverseApply(t[a],n),n),n.failFast&&n.currentErrorCount>r)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(a)){if(e==="Allows")return!1;if(n.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[a],meta:this.meta}),n.failFast)return!1}}}if(this.structuralMorph&&n&&!n.hasError())n.queueMorphs([this.structuralMorph]);return!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter((e)=>e.hasDefault())??[])}declaresKey=(e)=>(e in this.propsByKey)||this.index?.some((t)=>t.signature.allows(e))||this.sequence!==void 0&&N.intrinsic.nonNegativeIntegerString.allows(e);_compileDeclaresKey(e){let t=[];if(this.props.length)t.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let n of this.index)t.push(e.invoke(n.signature,{kind:"Allows",arg:"k"}));if(this.sequence)t.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return t.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",D0(this))}structuralMorphRef=this.structuralMorph&&Me(this.structuralMorph);compile(e){if(e.traversalKind==="Apply")e.initializeErrorCount();for(let t of this.props)if(e.check(t),e.traversalKind==="Apply")e.returnIfFailFast();if(this.sequence){if(e.check(this.sequence),e.traversalKind==="Apply")e.returnIfFailFast()}if(this.index||this.undeclared==="reject")e.const("keys","Object.keys(data)"),e.line("keys.push(...Object.getOwnPropertySymbols(data))"),e.for("i < keys.length",()=>this.compileExhaustiveEntry(e));if(e.traversalKind==="Allows")return e.return(!0);if(this.structuralMorphRef)e.if("ctx && !ctx.hasError()",()=>(e.line("ctx.queueMorphs(["),N0(e,this),e.line("])")))}compileExhaustiveEntry(e){if(e.const("k","keys[i]"),this.index)for(let t of this.index)e.if(`${e.invoke(t.signature,{arg:"k",kind:"Allows"})}`,()=>e.traverseKey("k","data[k]",t.value));if(this.undeclared==="reject")e.if(`!(${this._compileDeclaresKey(e)})`,()=>{if(e.traversalKind==="Allows")return e.return(!1);return e.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>e.return())});return e}reduceJsonSchema(e,t){switch(e.type){case"object":return this.reduceObjectJsonSchema(e,t);case"array":let n=this.sequence?.reduceJsonSchema(e,t)??e;if(this.props.length||this.index)return t.fallback.arrayObject({code:"arrayObject",base:n,object:this.reduceObjectJsonSchema({type:"object"},t)});return n;default:return Ee.throwInternalOperandError("structure",e)}}reduceObjectJsonSchema(e,t){if(this.props.length){e.properties={};for(let n of this.props){let r=n.value.toJsonSchemaRecurse(t);if(typeof n.key==="symbol"){t.fallback.symbolKey({code:"symbolKey",base:e,key:n.key,value:r,optional:n.optional});continue}if(n.hasDefault()){let s=typeof n.default==="function"?n.default():n.default;r.default=N.intrinsic.jsonData.allows(s)?s:t.fallback.defaultValue({code:"defaultValue",base:r,value:s})}e.properties[n.key]=r}if(this.requiredKeys.length&&e.properties)e.required=this.requiredKeys.filter((n)=>typeof n==="string"&&(n in e.properties))}if(this.index)for(let n of this.index){let r=n.value.toJsonSchemaRecurse(t);if(n.signature.equals(N.intrinsic.string)){e.additionalProperties=r;continue}for(let s of n.signature.branches){if(!s.extends(N.intrinsic.string)){e=t.fallback.symbolKey({code:"symbolKey",base:e,key:null,value:r,optional:!1});continue}let o={type:"string"};if(s.hasKind("morph"))o=t.fallback.morph({code:"morph",base:s.rawIn.toJsonSchemaRecurse(t),out:s.rawOut.toJsonSchemaRecurse(t)});if(!s.hasKind("intersection"))return he(`Unexpected index branch kind ${s.kind}.`);let{pattern:a}=s.inner;if(a){let l=Object.assign(o,{pattern:a[0].rule});for(let c=1;c<a.length;c++)o=t.fallback.patternIntersection({code:"patternIntersection",base:l,pattern:a[c].rule});e.patternProperties??={},e.patternProperties[l.pattern]=r}}}if(this.undeclared&&!e.additionalProperties)e.additionalProperties=!1;return e}}var gd={},T0=(e)=>{let t="";for(let n=0;n<e.defaultable.length;n++)t+=e.defaultable[n].defaultValueMorphRef;if(e.sequence?.defaultValueMorphsReference)t+=e.sequence?.defaultValueMorphsReference;if(e.undeclared==="delete"){if(t+="delete !(",e.required)for(let n of e.required)t+=n.compiledKey+" | ";if(e.optional)for(let n of e.optional)t+=n.compiledKey+" | ";if(e.index)for(let n of e.index)t+=n.signature.id+" | ";if(e.sequence)if(e.sequence.maxLength===null)t+=ee.nonNegativeIntegerString.id;else for(let n=0;n<e.sequence.tuple.length;n++)t+=n+" | ";t+=")"}return t},D0=(e)=>{let t=T0(e);if(!t)return;if(gd[t])return gd[t];let n=(r,s)=>{for(let o=0;o<e.defaultable.length;o++)if(!(e.defaultable[o].key in r))e.defaultable[o].defaultValueMorph(r,s);if(e.sequence?.defaultables)for(let o=r.length-e.sequence.prefixLength;o<e.sequence.defaultables.length;o++)e.sequence.defaultValueMorphs[o](r,s);if(e.undeclared==="delete"){for(let o in r)if(!e.declaresKey(o))delete r[o]}return r};return gd[t]=n},N0=(e,t)=>{let r=`(data${t.defaultable.some((s)=>s.defaultValueMorph.length===2)||t.sequence?.defaultValueMorphs.some((s)=>s.length===2)?", ctx":""})`;return e.block(`${r} => `,(s)=>{for(let o=0;o<t.defaultable.length;o++){let{serializedKey:a,defaultValueMorphRef:l}=t.defaultable[o];s.if(`!(${a} in data)`,(c)=>c.line(`${l}${r}`))}if(t.sequence?.defaultables)s.for(`i < ${t.sequence.defaultables.length}`,(o)=>o.set("data[i]",5),`data.length - ${t.sequence.prefixLength}`);if(t.undeclared==="delete")s.forIn("data",(o)=>o.if(`!(${t._compileDeclaresKey(o)})`,(a)=>a.line("delete data[k]")));return s.return("data")})},_d={implementation:M0,Node:aw},F0=(e)=>{if(X(e,"root")&&e.hasKind("unit"))e=e.unit;if(typeof e==="number")e=`${e}`;return e},L0=(e,t)=>`${e} is not allowed as an array index on ${t}. Use the 'nonNegativeIntegerString' keyword instead.`,Ha=(e,t,n)=>{let[r,s]=Sg(e.branches,(a)=>a.hasKind("unit"));if(!r.length)return{index:n.node("index",{signature:e,value:t})};let o={};for(let a of r){let l=n.node("required",{key:a.unit,value:t});o[l.kind]=de(o[l.kind],l)}if(s.length)o.index=n.node("index",{signature:s,value:t});return o},j0=(e)=>X(e,"root")?e.expression:se(e),iw=(e,t)=>`Key${t.length===1?"":"s"} ${t.map(j0).join(", ")} ${t.length===1?"does":"do"} not exist on ${e}`,sw=(e)=>`Duplicate key ${on(e)}`;var Ei={...E_,alias:Hs.implementation,domain:qa.implementation,unit:dd.implementation,proto:Ks.implementation,union:ud.implementation,morph:ld.implementation,intersection:ad.implementation,divisor:Vu.implementation,pattern:td.implementation,predicate:Wu.implementation,required:pd.implementation,optional:Us.implementation,index:fd.implementation,sequence:hd.implementation,structure:_d.implementation};N.defaultConfig=Pg(Object.assign(ie(Ei,(e,t)=>[e,t.defaults]),{jitless:Lg(),clone:Dg,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:Ee.defaultConfig}));N.resolvedConfig=Ms(N.defaultConfig,N.config);var M_={...C_,alias:Hs.Node,domain:qa.Node,unit:dd.Node,proto:Ks.Node,union:ud.Node,morph:ld.Node,intersection:ad.Node,divisor:Vu.Node,pattern:td.Node,predicate:Wu.Node,required:pd.Node,optional:Us.Node,index:fd.Node,sequence:hd.Node,structure:_d.Node};class Oi extends Eu{get[ht](){return"module"}}var wd=(e,t)=>new Oi(ie(e,(n,r)=>[n,X(r,"module")?wd(r,t):t.bindReference(r)]));var U0=(e)=>Se(e)?e:("branches"in e)&&Se(e.branches)?e.branches:void 0,B0=(e,t)=>A(`Node of kind ${t} is not valid as a ${e} definition`),lw=(e)=>`#${e} duplicates public alias ${e}`,yd={};N.ambient??={};var cw,dw="function $",q0=(e)=>fw(e,pw(e)),fw=(e,t)=>{let n=t.write(dw,4),r=t.compile()();for(let s of e){if(s.precompilation)continue;if(s.traverseAllows=r[`${s.id}Allows`].bind(r),s.isRoot()&&!s.allowsRequiresContext)s.allows=s.traverseAllows;if(s.traverseApply=r[`${s.id}Apply`].bind(r),r[`${s.id}Optimistic`])s.traverseOptimistic=r[`${s.id}Optimistic`].bind(r);s.precompilation=n}},pw=(e)=>new Ia().return(e.reduce((t,n)=>{let r=new Ps({kind:"Allows"}).indent();n.compile(r);let s=r.write(`${n.id}Allows`),o=new Ps({kind:"Apply"}).indent();n.compile(o);let a=o.write(`${n.id}Apply`),l=`${t}${s},
613
613
  ${a},
614
- `;if(!n.hasKind("union"))return l;let c=new Ss({kind:"Allows",optimistic:!0}).indent();n.compile(c);let u=c.write(`${n.id}Optimistic`);return`${l}${u},
614
+ `;if(!n.hasKind("union"))return l;let c=new Ps({kind:"Allows",optimistic:!0}).indent();n.compile(c);let u=c.write(`${n.id}Optimistic`);return`${l}${u},
615
615
  `},`{
616
- `)+"}");class Na{config;resolvedConfig;name;get[ht](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(e,t){if(this.config=$s(N.config,t),this.resolvedConfig=$s(N.resolvedConfig,t),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(od).length}`,this.name in od)C(`A Scope already named ${this.name} already exists`);od[this.name]=this;let n=Object.entries(e).map((r)=>this.preparseOwnAliasEntry(...r));for(let[r,s]of n){let o=r;if(r[0]==="#"){if(o=r.slice(1),o in this.aliases)C(D_(o));this.aliases[o]=s}else{if(o in this.aliases)C(D_(r));this.aliases[o]=s,this.exportedNames.push(o)}if(!X(s,"module")&&!X(s,"generic")&&!tr(s)){let a=this.preparseOwnDefinitionFormat(s,{alias:o});this.resolutions[o]=X(a,"root")?this.bindReference(a):this.createParseContext(a).id}}L_??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[L_.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=N.intrinsic?ie(N.intrinsic,(r,s)=>r.startsWith("json")?[]:[r,this.bindReference(s)]):{}}cacheGetter(e,t){return Object.defineProperty(this,e,{value:t}),t}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(e){return e}generic=(...e)=>{let t=this;return(n,r)=>new or(e,r?new Aa(n):n,t,t,r??null)};units=(e,t)=>{let n=[];for(let s of e)if(!n.includes(s))n.push(s);let r=n.map((s)=>this.node("unit",{unit:s},t));return this.node("union",r,{...t,prereduced:!0})};lazyResolutions=[];lazilyResolve(e,t){let n=this.node("alias",{reference:t??"synthetic",resolve:e},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(n);return n}schema=(e,t)=>this.finalize(this.parseSchema(e,t));parseSchema=(e,t)=>this.node(Cs(e),e,t);preparseNode(e,t,n){let r=typeof e==="string"?e:Cs(t,e);if($e(t)&&t.kind===r)return t;if(r==="alias"&&!n?.prereduced){let{reference:a}=Fs.implementation.normalize(t,this);if(a.startsWith("$")){let l=this.resolveRoot(a.slice(1));t=l,r=l.kind}}else if(r==="union"&&Rt(t,"object")){let a=Z0(t);if(a?.length===1)t=a[0],r=Cs(t)}if($e(t)&&t.kind===r)return t;let o=xi[r].normalize?.(t,this)??t;if($e(o))return o.kind===r?o:Q0(r,o.kind);return{...n,$:this,kind:r,def:o,prefix:n.alias??r}}bindReference(e){let t;if($e(e))t=e.$===this?e:new e.constructor(e.attachments,this);else t=e.$===this?e:new or(e.params,e.bodyDef,e.$,this,e.hkt);if(!this.resolved)Object.assign(this.referencesById,t.referencesById);return t}resolveRoot(e){return this.maybeResolveRoot(e)??C(cd(e))}maybeResolveRoot(e){let t=this.maybeResolve(e);if(X(t,"generic"))return;return t}maybeResolveSubalias(e){return ad(this.aliases,e)??ad(this.ambient,e)}get ambient(){return N.ambient}maybeResolve(e){let t=this.resolutions[e];if(t){if(typeof t!=="string")return this.bindReference(t);let r=mt[t];if(X(r,"root"))return this.resolutions[e]=r;if(X(r,"context")){if(r.phase==="resolving")return this.node("alias",{reference:`$${e}`},{prereduced:!0});if(r.phase==="resolved")return he(`Unexpected resolved context for was uncached by its scope: ${se(r)}`);r.phase="resolving";let s=this.bindReference(this.parseOwnDefinitionFormat(r.def,r));return r.phase="resolved",mt[s.id]=s,mt[r.id]=s,this.resolutions[e]=s}return he(`Unexpected nodesById entry for ${t}: ${se(r)}`)}let n=this.aliases[e]??this.ambient?.[e];if(!n)return this.maybeResolveSubalias(e);if(n=this.normalizeRootScopeValue(n),X(n,"generic"))return this.resolutions[e]=this.bindReference(n);if(X(n,"module")){if(!n.root)C(W_(e));return this.resolutions[e]=this.bindReference(n.root)}return this.resolutions[e]=this.parse(n,{alias:e})}createParseContext(e){let t=e.id??Hu(e.prefix);return mt[t]=Object.assign(e,{[ht]:"context",$:this,id:t,phase:"unresolved"})}traversal(e){return new sn(e,this.resolvedConfig)}import(...e){return new $i(ie(this.export(...e),(t,n)=>[`#${t}`,n]))}precompilation;_exportedResolutions;_exports;export(...e){if(!this._exports){this._exports={};for(let n of this.exportedNames){let r=this.aliases[n];this._exports[n]=X(r,"module")?sd(r,this):j_(this.maybeResolve(n))}for(let n of this.lazyResolutions)n.resolution;if(this._exportedResolutions=K_(this,this._exports),this._json=H_(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let n=q_(this.references);this.precompilation=n.write(U_,4),B_(this.references,n)}this.resolved=!0}let t=e.length?e:this.exportedNames;return new $i(ie(t,(n,r)=>[r,this._exports[r]]))}resolve(e){return this.export()[e]}node=(e,t,n={})=>{let r=this.preparseNode(e,t,n);if($e(r))return this.bindReference(r);let s=this.createParseContext(r),o=Ku(s),a=this.bindReference(o);return mt[s.id]=a};parse=(e,t={})=>this.finalize(this.parseDefinition(e,t));parseDefinition(e,t={}){if(X(e,"root"))return this.bindReference(e);let n=this.preparseOwnDefinitionFormat(e,t);if(X(n,"root"))return this.bindReference(n);let r=this.createParseContext(n);mt[r.id]=r;let s=this.bindReference(this.parseOwnDefinitionFormat(e,r));if(s.isCyclic)s=a_(s,r.id);return mt[r.id]=s,s}finalize(e){if(j_(e),!e.precompilation&&!this.resolvedConfig.jitless)eA(e.references);return e}}class ld extends Na{parseOwnDefinitionFormat(e,t){return Ku(t)}preparseOwnDefinitionFormat(e,t){return this.preparseNode(Cs(e),e,t)}preparseOwnAliasEntry(e,t){return[e,t]}normalizeRootScopeValue(e){return e}}var j_=(e)=>{let t=e.references.filter((n)=>n.hasKind("alias"));for(let n of t){Object.assign(n.referencesById,n.resolution.referencesById);for(let r of e.references)if(n.id in r.referencesById)Object.assign(r.referencesById,n.referencesById)}return e},H_=(e)=>ie(e,(t,n)=>[t,X(n,"root")||X(n,"generic")?n.json:X(n,"module")?H_(n):he(`Unexpected resolution ${se(n)}`)]),ad=(e,t)=>{let n=t.indexOf(".");if(n===-1)return;let r=t.slice(0,n),s=e[r];if(s===void 0)return;if(!X(s,"module"))return C(tA(r));let o=t.slice(n+1),a=s[o];if(a===void 0)return ad(s,o);if(X(a,"root")||X(a,"generic"))return a;if(X(a,"module"))return a.root??C(W_(t));he(`Unexpected resolution for alias '${t}': ${se(a)}`)},Da=(e,t)=>new ld(e,t),Ls=new ld({});var K_=(e,t)=>{let n={};for(let r in t){let s=t[r];if(X(s,"module")){let o=K_(e,s),a=ie(o,(l,c)=>[`${r}.${l}`,c]);Object.assign(n,a)}else if(X(s,"root")||X(s,"generic"))n[r]=s;else he(`Unexpected scope resolution ${se(s)}`)}return n},cd=(e)=>`'${e}' is unresolvable`,tA=(e)=>`'${e}' must reference a module to be accessed using dot syntax`,W_=(e)=>`Reference to submodule '${e}' must specify an alias`;Ls.export();var{schema:ge,node:ki,defineSchema:Hq,generic:Vt}=Ls;var ud="^(?:0|[1-9]\\d*)$",nA=new RegExp(ud),Gq=Me(nA);var G_=Da({bigint:"bigint",boolean:[{unit:!1},{unit:!0}],false:{unit:!1},never:[],null:{unit:null},number:"number",object:"object",string:"string",symbol:"symbol",true:{unit:!0},unknown:{},undefined:{unit:void 0},Array,Date},{prereducedAliases:!0}).export();N.intrinsic={...G_};var V_=Da({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:ud}},{prereducedAliases:!0}).export();Object.assign(N.intrinsic,V_);var rA=Da({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),ee={...G_,...V_,...rA,emptyStructure:ki("structure",{},{prereduced:!0})};N.intrinsic={...ee};var La=(e,t)=>new RegExp(e,t);Object.assign(La,{as:La});var J_=(e)=>typeof e==="string"&&e[0]==="d"&&(e[1]==="'"||e[1]==='"')&&e[e.length-1]===e[1],z_=(e)=>e.toString()!=="Invalid Date",X_=(e)=>e.slice(2,-1),dd=(e)=>`'${e}' could not be parsed by the Date constructor`,Y_=(e,t)=>iA(e,t),iA=(e,t)=>{let n=new Date(e);if(z_(n))return n;let r=Rg(e);if(r!==void 0){let s=new Date(r);if(z_(s))return s}return t?C(t===!0?dd(e):t):void 0};var sA=ge({proto:"Array",sequence:"string",required:{key:"groups",value:["object",{unit:void 0}]}}),ja=(e,t)=>{let n=e.scanner.shiftUntilEscapable(aA[ew[t]]);if(e.scanner.lookahead==="")return e.error(cA(n,t));if(e.scanner.shift(),t in Q_){let r;try{r=new RegExp(n)}catch(s){C(String(s))}if(e.root=e.ctx.$.node("intersection",{domain:"string",pattern:n},{prereduced:!0}),t==="x/")e.root=e.ctx.$.node("morph",{in:e.root,morphs:(s)=>r.exec(s),declaredOut:sA})}else if(We(t,fd))e.root=e.ctx.$.node("unit",{unit:n});else{let r=Y_(n,dd(n));e.root=e.ctx.$.node("unit",{meta:n,unit:r})}},fd={"'":1,'"':1},Z_={"/":1,"'":1,'"':1},oA={"d'":"'",'d"':'"',"'":"'",'"':'"'},Q_={"/":"/","x/":"/"},ew={...oA,...Q_},aA={"'":(e)=>e.lookahead==="'",'"':(e)=>e.lookahead==='"',"/":(e)=>e.lookahead==="/"},lA={'"':"double-quote","'":"single-quote","/":"forward slash"},cA=(e,t)=>`${t}${e} requires a closing ${lA[ew[t]]}`;var tw=(e)=>`Private type references should not include '#'. Use '${e}' instead.`,Ua="Optional definitions like 'string?' are only valid as properties in an object or tuple",Ba="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var vn={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...nr};var nw=(e,t)=>e===">"?t[0]==="="?t[1]==="=":t.trimStart()===""||We(t.trimStart()[0],vn):e==="="?t[0]!=="=":e===","||e==="?";var rw=(e,t,n)=>iw(e,t,n,[]),iw=(e,t,n,r)=>{let s=n.parseUntilFinalizer();if(r.push(s.root),s.finalizer===">"){if(r.length!==t.params.length)return n.error(pd(e,t.names,r.map((o)=>o.expression)));return r}if(s.finalizer===",")return iw(e,t,n,r);return s.error(xa(">"))},pd=(e,t,n)=>`${e}<${t.join(", ")}> requires exactly ${t.length} args (got ${n.length}${n.length===0?"":`: ${n.join(", ")}`})`;var qa=(e)=>{let t=e.scanner.shiftUntilLookahead(vn);if(t==="keyof")e.addPrefix("keyof");else e.root=dA(e,t)},uA=(e,t,n)=>{if(n.scanner.shiftUntilNonWhitespace(),n.scanner.shift()!=="<")return n.error(pd(e,t.names,[]));let s=rw(e,t,n);return t(...s)},dA=(e,t)=>fA(e,t)??pA(e,t)??e.error(t===""?e.scanner.lookahead==="#"?tw(e.shiftedBy(1).scanner.shiftUntilLookahead(vn)):hd(e):cd(t)),fA=(e,t)=>{if(e.ctx.args?.[t]){let r=e.ctx.args[t];if(typeof r!=="string")return r;return e.ctx.$.node("alias",{reference:r},{prereduced:!0})}let n=e.ctx.$.maybeResolve(t);if(X(n,"root"))return n;if(n===void 0)return;if(X(n,"generic"))return uA(t,n,e);return C(`Unexpected resolution ${se(n)}`)},pA=(e,t)=>{let n=Sg(t);if(n!==void 0)return e.ctx.$.node("unit",{unit:n});let r=kg(t);if(r!==void 0)return e.ctx.$.node("unit",{unit:r})},hd=(e)=>{let t=e.previousOperator();return t?md(t,e.scanner.unscanned):hA(e.scanner.unscanned)},md=(e,t="")=>`Token '${e}' requires a right operand${t?` before '${t}'`:""}`,hA=(e)=>`Expected an expression${e?` before '${e}'`:""}`;var gd=(e)=>e.scanner.lookahead===""?e.error(hd(e)):e.scanner.lookahead==="("?e.shiftedBy(1).reduceGroupOpen():e.scanner.lookaheadIsIn(Z_)?ja(e,e.scanner.shift()):e.scanner.lookaheadIsIn(nr)?gd(e.shiftedBy(1)):e.scanner.lookahead==="d"?e.scanner.nextLookahead in fd?ja(e,`${e.scanner.shift()}${e.scanner.shift()}`):qa(e):e.scanner.lookahead==="x"?e.scanner.nextLookahead==="/"?e.shiftedBy(2)&&ja(e,"x/"):qa(e):qa(e);var sw={">":!0,">=":!0},ow={"<":!0,"<=":!0};var Ei={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},aw=(e,t)=>`Left bounds are only valid when paired with right bounds (try ...${t}${e})`,Ha=(e)=>`Left-bounded expressions must specify their limits using < or <= (was ${e})`,lw=(e,t,n,r)=>`An expression may have at most one left bound (parsed ${e}${Ei[t]}, ${n}${Ei[r]})`;var uw=(e,t)=>{let n=mA(e,t);if(e.root.hasKind("unit")){if(typeof e.root.unit==="number"){e.reduceLeftBound(e.root.unit,n),e.unsetRoot();return}if(e.root.unit instanceof Date){let r=`d'${e.root.description??e.root.unit.toISOString()}'`;e.unsetRoot(),e.reduceLeftBound(r,n);return}}return _A(e,n)},dw={"<":1,">":1,"=":1},mA=(e,t)=>e.scanner.lookaheadIs("=")?`${t}${e.scanner.shift()}`:t;var cw=(e,t,n,r)=>{if(n.extends(N.intrinsic.number)){if(typeof t!=="number")return C(_d(e,t,r));return e==="=="?["min","max"]:e[0]===">"?["min"]:["max"]}if(n.extends(N.intrinsic.lengthBoundable)){if(typeof t!=="number")return C(_d(e,t,r));return e==="=="?["exactLength"]:e[0]===">"?["minLength"]:["maxLength"]}if(n.extends(N.intrinsic.Date))return e==="=="?["after","before"]:e[0]===">"?["after"]:["before"];return C(zg(n.expression))},gA=(e)=>({rule:J_(e.limit)?X_(e.limit):e.limit,exclusive:e.comparator.length===1}),_A=(e,t)=>{let n=e.unsetRoot(),r=e.scanner.location;e.parseOperand();let s=e.unsetRoot(),o=e.scanner.sliceChars(r,e.scanner.location);if(e.root=n,!s.hasKind("unit")||typeof s.unit!=="number"&&!(s.unit instanceof Date))return e.error(_d(t,o,"right"));let a=s.unit,l=t.length===1,c=cw(t,typeof a==="number"?a:o,n,"right");for(let d of c)e.constrainRoot(d,t==="=="?{rule:a}:{rule:a,exclusive:l});if(!e.branches.leftBound)return;if(!We(t,ow))return e.error(Ha(t));let u=cw(e.branches.leftBound.comparator,e.branches.leftBound.limit,n,"left");e.constrainRoot(u[0],gA(e.branches.leftBound)),e.branches.leftBound=null},_d=(e,t,n)=>`Comparator ${n==="left"?Ei[e]:e} must be ${n==="left"?"preceded":"followed"} by a corresponding literal (was ${t})`;var fw=(e)=>{e.scanner.shiftUntilNonWhitespace();let t=e.scanner.shiftUntilLookahead(vn);e.root=e.root.brand(t)};var hw=(e)=>{e.scanner.shiftUntilNonWhitespace();let t=e.scanner.shiftUntilLookahead(vn),n=$g(t,{errorOnFail:pw(t)});if(n===0)e.error(pw(0));e.root=e.root.constrain("divisor",n)},pw=(e)=>`% operator must be followed by a non-zero integer literal (was ${e})`;var wd=(e)=>{let t=e.scanner.shift();return t===""?e.finalize(""):t==="["?e.scanner.shift()==="]"?e.setRoot(e.root.array()):e.error(wA):t==="|"?e.scanner.lookahead===">"?e.shiftedBy(1).pushRootToBranch("|>"):e.pushRootToBranch(t):t==="&"?e.pushRootToBranch(t):t===")"?e.finalizeGroup():nw(t,e.scanner.unscanned)?e.finalize(t):We(t,dw)?uw(e,t):t==="%"?hw(e):t==="#"?fw(e):(t in nr)?wd(e):e.error(Ka(t))},Ka=(e,t="")=>`'${e}' is not allowed here${t&&` (should be ${t})`}`,wA="Missing expected ']'";var mw=(e)=>{let t=e.unsetRoot();e.parseOperand();let n=e.unsetRoot();if(!n.hasKind("unit"))return e.error(yA(n.expression));let r=n.unit instanceof Date?()=>new Date(n.unit):n.unit;return[t,"=",r]},yA=(e)=>`Default value '${e}' must be a literal value`;var yd=(e,t)=>{let n=t.$.maybeResolveRoot(e);if(n)return n;if(e.endsWith("[]")){let o=t.$.maybeResolveRoot(e.slice(0,-2));if(o)return o.array()}let r=new Ai(new Rs(e),t),s=bA(r);if(r.finalizer===">")C(Ka(">"));return s},bA=(e)=>{e.parseOperand();let t=js(e).root;if(!t)return he(`Root was unexpectedly unset after parsing string '${e.scanner.scanned}'`);if(e.finalizer==="=")t=mw(e);else if(e.finalizer==="?")t=[t,"?"];if(e.scanner.shiftUntilNonWhitespace(),e.scanner.lookahead)C(Ka(e.scanner.lookahead));return t},js=(e)=>{while(e.finalizer===void 0)vA(e);return e},vA=(e)=>e.hasRoot()?e.parseOperator():e.parseOperand();class Ai{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(e,t){this.scanner=e,this.ctx=t}error(e){return C(e)}hasRoot(){return this.root!==void 0}setRoot(e){this.root=e}unsetRoot(){let e=this.root;return this.root=void 0,e}constrainRoot(...e){this.root=this.root.constrain(e[0],e[1])}finalize(e){if(this.groups.length)return this.error(xa(")"));this.finalizeBranches(),this.finalizer=e}reduceLeftBound(e,t){let n=Ei[t];if(!We(n,sw))return this.error(Ha(t));if(this.branches.leftBound)return this.error(lw(this.branches.leftBound.limit,this.branches.leftBound.comparator,e,n));this.branches.leftBound={comparator:n,limit:e}}finalizeBranches(){if(this.assertRangeUnset(),this.branches.pipe){this.pushRootToBranch("|>"),this.root=this.branches.pipe;return}if(this.branches.union){this.pushRootToBranch("|"),this.root=this.branches.union;return}if(this.branches.intersection){this.pushRootToBranch("&"),this.root=this.branches.intersection;return}this.applyPrefixes()}finalizeGroup(){this.finalizeBranches();let e=this.groups.pop();if(!e)return this.error(Og(")",this.scanner.unscanned));this.branches=e}addPrefix(e){this.branches.prefixes.push(e)}applyPrefixes(){while(this.branches.prefixes.length){let e=this.branches.prefixes.pop();this.root=e==="keyof"?this.root.keyof():he(`Unexpected prefix '${e}'`)}}pushRootToBranch(e){this.assertRangeUnset(),this.applyPrefixes();let t=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(t)??t,e==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,e==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return js(new Ai(this.scanner,this.ctx))}parseOperator(){return wd(this)}parseOperand(){return gd(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(aw(this.branches.leftBound.limit,this.branches.leftBound.comparator))}reduceGroupOpen(){this.groups.push(this.branches),this.branches={prefixes:[],leftBound:null,union:null,intersection:null,pipe:null}}previousOperator(){return this.branches.leftBound?.comparator??this.branches.prefixes[this.branches.prefixes.length-1]??(this.branches.intersection?"&":this.branches.union?"|":this.branches.pipe?"|>":void 0)}shiftedBy(e){return this.scanner.jumpForward(e),this}}var xA="An empty string is not a valid generic parameter name",Wa=(e,t,n)=>{e.shiftUntilNonWhitespace();let r=e.shiftUntilLookahead(vn);if(r===""){if(e.lookahead===""&&t.length)return t;return C(xA)}return e.shiftUntilNonWhitespace(),RA(e,r,t,n)},gw="extends ",RA=(e,t,n,r)=>{if(e.shiftUntilNonWhitespace(),e.unscanned.startsWith(gw))e.jumpForward(gw.length);else{if(e.lookahead===",")e.shift();return n.push(t),Wa(e,n,r)}let s=js(new Ai(e,r));return n.push([t,s.root]),Wa(e,n,r)};class bd extends kt{constructor(e){let t={$:e,raw:e.fn};super((...n)=>{let r=n.indexOf(":"),s=r===-1?n.length-1:r-1,o=n.slice(0,s+1),a=e.parse(o).assertHasKind("intersection"),l=e.intrinsic.unknown;if(r!==-1){if(r!==n.length-2)return C(SA);l=e.parse(n[r+1])}return(c)=>new _w(c,a,l)},{attach:t})}}class _w extends kt{raw;params;returns;expression;constructor(e,t,n){let r=`typed ${e.name}`,s={[r]:(...a)=>{let l=t.assert(a),c=e(...l);return n.assert(c)}}[r];super(s);this.raw=e,this.params=t,this.returns=n;let o=t.expression;if(o[0]==="["&&o[o.length-1]==="]")o=o.slice(1,-1);else if(o.endsWith("[]"))o=`...${o}`;this.expression=`(${o}) => ${n?.expression??"unknown"}`}}var SA=`":" must be followed by exactly one return type e.g:
617
- fn("string", ":", "number")(s => s.length)`;class vd extends kt{$;constructor(e){super((...t)=>new Us(e)(...t),{bind:e});this.$=e}in(e){return new Us(this.$,e===void 0?void 0:this.$.parse(e))}at(e,t){return new Us(this.$).at(e,t)}case(e,t){return new Us(this.$).case(e,t)}}class Us extends kt{$;in;key;branches=[];constructor(e,t){super((n)=>this.caseEntries(Object.entries(n).map(([r,s])=>r==="default"?[r,s]:[this.$.parse(r),s])));this.$=e,this.in=t}at(e,t){if(this.key)C(kA);if(this.branches.length)C($A);return this.key=e,t?this.match(t):this}case(e,t){return this.caseEntry(this.$.parse(e),t)}caseEntry(e,t){let r=(this.key?this.$.parse({[this.key]:e}):e).pipe(t);return this.branches.push(r),this}match(e){return this(e)}strings(e){return this.caseEntries(Object.entries(e).map(([t,n])=>t==="default"?[t,n]:[this.$.node("unit",{unit:t}),n]))}caseEntries(e){for(let t=0;t<e.length;t++){let[n,r]=e[t];if(n==="default"){if(t!==e.length-1)C("default may only be specified as the last key of a switch definition");return this.default(r)}if(typeof r!=="function")return C(`Value for case "${n}" must be a function (was ${Ke(r)})`);this.caseEntry(n,r)}return this}default(e){if(typeof e==="function")this.case(ee.unknown,e);let t={branches:this.branches,ordered:!0};if(e==="never"||e==="assert")t.meta={onFail:ww};let n=this.$.node("union",t);if(!this.in)return this.$.finalize(n);let r=this.in.pipe(n);if(e==="never"||e==="assert")r=r.configureReferences({onFail:ww},"self");return this.$.finalize(r)}}var ww=(e)=>e.throw(),$A="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",kA="At most one key matcher may be specified per expression";var Ga=(e,t)=>{if(Re(e)){if(e[1]==="=")return[t.$.parseOwnDefinitionFormat(e[0],t),"=",e[2]];if(e[1]==="?")return[t.$.parseOwnDefinitionFormat(e[0],t),"?"]}return Va(e,t)},yw="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",bw="Only required keys may specify default values, e.g. { value: 'number = 0' }";var vw=(e,t)=>{let n,r={},s=Cr(e);for(let[a,l]of s){let c=CA(a);if(c.kind==="spread"){if(!yn(r))return C(AA);let h=t.$.parseOwnDefinitionFormat(l,t);if(h.equals(ee.object))continue;if(!h.hasKind("intersection")||!h.basis?.equals(ee.object))return C(OA(h.expression));n=h.structure;continue}if(c.kind==="undeclared"){if(l!=="reject"&&l!=="delete"&&l!=="ignore")C(EA(l));r.undeclared=l;continue}let u=Ga(l,t),d=c;if(c.kind==="required"){if(!Re(u))xd(r,"required",{key:c.normalized,value:u},t);else xd(r,"optional",u[1]==="="?{key:c.normalized,value:u[0],default:u[2]}:{key:c.normalized,value:u[0]},t);continue}if(Re(u)){if(u[1]==="?")C(yw);if(u[1]==="=")C(bw)}if(c.kind==="optional"){xd(r,"optional",{key:c.normalized,value:u},t);continue}let f=t.$.parseOwnDefinitionFormat(d.normalized,t),p=Fa(f,u,t.$);if(p.index)r.index=de(r.index,p.index);if(p.required)r.required=de(r.required,p.required)}let o=t.$.node("structure",r);return t.$.parseSchema({domain:"object",structure:n?.merge(o)??o})},xd=(e,t,n,r)=>{e[t]=de(e[t],r.$.node(t,n))},EA=(e)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${se(e)})`,AA="Spread operator may only be used as the first key in an object",CA=(e)=>typeof e==="symbol"?{kind:"required",normalized:e}:e[e.length-1]==="?"?e[e.length-2]===Ir?{kind:"required",normalized:`${e.slice(0,-2)}?`}:{kind:"optional",normalized:e.slice(0,-1)}:e[0]==="["&&e[e.length-1]==="]"?{kind:"index",normalized:e.slice(1,-1)}:e[0]===Ir&&e[1]==="["&&e[e.length-1]==="]"?{kind:"required",normalized:e.slice(1)}:e==="..."?{kind:"spread"}:e==="+"?{kind:"undeclared"}:{kind:"required",normalized:e==="\\..."?"...":e==="\\+"?"+":e},OA=(e)=>`Spread operand must resolve to an object literal type (was ${e})`;var Rw=(e,t)=>UA(e)?Ew[e[0]](e,t):LA(e)?kw[e[1]](e,t):null,IA=(e,t)=>t.$.parseOwnDefinitionFormat(e[1],t).keyof(),Rd=(e,t)=>{if(e[2]===void 0)return C(md(e[1],""));let n=t.$.parseOwnDefinitionFormat(e[0],t),r=t.$.parseOwnDefinitionFormat(e[2],t);if(e[1]==="|")return t.$.node("union",{branches:[n,r]});let s=e[1]==="&"?Ct(n,r,t.$):As(n,r,t.$);if(s instanceof q)return s.throw();return s},PA=(e,t)=>t.$.parseOwnDefinitionFormat(e[0],t).array(),MA=(e,t)=>{if(typeof e[2]!=="function")return C(Sw("=>",e[2]));return t.$.parseOwnDefinitionFormat(e[0],t).pipe(e[2])},Sw=(e,t)=>`${e===":"?"Narrow":"Morph"} expression requires a function following '${e}' (was ${typeof t})`,TA=(e,t)=>{if(typeof e[2]!=="function")return C(Sw(":",e[2]));return t.$.parseOwnDefinitionFormat(e[0],t).constrain("predicate",e[2])},FA=(e,t)=>t.$.parseOwnDefinitionFormat(e[0],t).configure(e[2],e[3]),$w=(e)=>e,NA=$w({"[]":PA,"?":()=>C(Ua)}),DA=$w({"|":Rd,"&":Rd,":":TA,"=>":MA,"|>":Rd,"@":FA,"=":()=>C(Ba)}),kw={...NA,...DA},LA=(e)=>kw[e[1]]!==void 0,jA=(e)=>e,Ew=jA({keyof:IA,instanceof:(e,t)=>{if(typeof e[1]!=="function")return C(xw(gs(e[1])));let n=e.slice(1).map((r)=>typeof r==="function"?t.$.node("proto",{proto:r}):C(xw(gs(r))));return n.length===1?n[0]:t.$.node("union",{branches:n})},"===":(e,t)=>t.$.units(e.slice(1))}),UA=(e)=>Ew[e[0]]!==void 0,xw=(e)=>`Expected a constructor following 'instanceof' operator (was ${e})`;var Ow=(e,t)=>{let n=[{}],r=0;while(r<e.length){let s=!1;if(e[r]==="..."&&r<e.length-1)s=!0,r++;let o=Ga(e[r],t),[a,l,c]=!Re(o)?[o]:o;if(r++,s){if(!a.extends(N.intrinsic.Array))return C(HA(a.expression));n=n.flatMap((u)=>a.distribute((d)=>qA(Sa(u),d)))}else n=n.map((u)=>{if(l==="?")return Iw(u,a);if(l==="=")return BA(u,a,c);return Sd(u,a)})}return t.$.parseSchema(n.map((s)=>yn(s)?{proto:Array,exactLength:0}:{proto:Array,sequence:s}))},Sd=(e,t)=>{if(e.defaultables||e.optionals)return C(e.variadic?nd:KA);if(e.variadic)e.postfix=de(e.postfix,t);else e.prefix=de(e.prefix,t);return e},Iw=(e,t)=>{if(e.variadic)return C(Pw);return e.optionals=de(e.optionals,t),e},BA=(e,t,n)=>{if(e.variadic)return C(Pw);if(e.optionals)return C(WA);return e.defaultables=de(e.defaultables,[[t,n]]),e},Aw=(e,t)=>{if(e.postfix)C(Cw);if(e.variadic){if(!e.variadic.equals(t))C(Cw)}else e.variadic=t.internal;return e},qA=(e,t)=>{let n=t.select({method:"find",kind:"sequence"});if(!n)return Aw(e,N.intrinsic.unknown);if(n.prefix)for(let r of n.prefix)Sd(e,r);if(n.optionals)for(let r of n.optionals)Iw(e,r);if(n.variadic)Aw(e,n.variadic);if(n.postfix)for(let r of n.postfix)Sd(e,r);return e},HA=(e)=>`Spread element must be an array (was ${e})`,Cw="A tuple may have at most one variadic element",KA="A required element may not follow an optional element",Pw="An optional element may not follow a variadic element";var WA="A defaultable element may not follow an optional element without a default";var GA={},Va=(e,t)=>{if(typeof e==="string"){if(t.args&&Object.keys(t.args).some((r)=>e.includes(r)))return yd(e,t);let n=GA[t.$.name]??={};return n[e]??=yd(e,t)}return Rt(e,"object")?VA(e,t):C($d(Ke(e)))},VA=(e,t)=>{let n=ms(e);switch(n){case void 0:if(X(e,"root"))return e;if("~standard"in e)return zA(e,t);return vw(e,t);case"Array":return JA(e,t);case"RegExp":return t.$.node("intersection",{domain:"string",pattern:e},{prereduced:!0});case"Function":{let r=tr(e)?e():e;if(X(r,"root"))return r;return C($d("Function"))}default:return C($d(n??se(e)))}},zA=(e,t)=>t.$.intrinsic.unknown.pipe((n,r)=>{let s=e["~standard"].validate(n);if(!s.issues)return s.value;for(let{message:o,path:a}of s.issues)if(a)if(a.length)r.error({problem:_g(o),relativePath:a.map((l)=>typeof l==="object"?l.key:l)});else r.error({message:o});else r.error({message:o})}),JA=(e,t)=>Rw(e,t)??Ow(e,t),$d=(e)=>`Type definitions must be strings or objects (was ${e})`;class kd extends kt{constructor(e){let t=Object.assign({errors:Et,hkt:at,$:e,raw:e.parse,module:e.constructor.module,scope:e.constructor.scope,declare:e.declare,define:e.define,match:e.match,generic:e.generic,schema:e.schema,keywords:e.ambient,unit:e.unit,enumerated:e.enumerated,instanceOf:e.instanceOf,valueOf:e.valueOf,or:e.or,and:e.and,merge:e.merge,pipe:e.pipe,fn:e.fn},e.ambientAttachments);super((...n)=>{if(n.length===1)return e.parse(n[0]);if(n.length===2&&typeof n[0]==="string"&&n[0][0]==="<"&&n[0][n[0].length-1]===">"){let r=n[0].slice(1,-1),s=e.parseGenericParams(r,{});return new or(s,n[1],e,e,null)}return e.parse(n)},{attach:t})}}var Ci=N;class za extends Na{get ambientAttachments(){if(!Ci.typeAttachments)return;return this.cacheGetter("ambientAttachments",ie(Ci.typeAttachments,(e,t)=>[e,this.bindReference(t)]))}preparseOwnAliasEntry(e,t){let n=e.indexOf("<");if(n===-1){if(X(t,"module")||X(t,"generic"))return[e,t];let o=this.name==="ark"?e:e==="root"?this.name:`${this.name}.${e}`,a=this.resolvedConfig.keywords?.[o];if(a)t=[t,"@",a];return[e,t]}if(e[e.length-1]!==">")C("'>' must be the last character of a generic declaration in a scope");let r=e.slice(0,n),s=e.slice(n+1,-1);return[r,()=>{let o=this.parseGenericParams(s,{alias:r});return Wg(o,t,this)}]}parseGenericParams(e,t){return Wa(new Rs(e),[],this.createParseContext({...t,def:e,prefix:"generic"}))}normalizeRootScopeValue(e){if(tr(e)&&!X(e,"generic"))return e();return e}preparseOwnDefinitionFormat(e,t){return{...t,def:e,prefix:t.alias??"type"}}parseOwnDefinitionFormat(e,t){if(!(t.alias&&(t.alias in this.aliases))&&!t.args)t.args={this:t.id};let r=Va(e,t);if(Re(r)){if(r[1]==="=")return C(Ba);if(r[1]==="?")return C(Ua)}return r}unit=(e)=>this.units([e]);valueOf=(e)=>this.units(lg(e));enumerated=(...e)=>this.units(e);instanceOf=(e)=>this.node("proto",{proto:e},{prereduced:!0});or=(...e)=>this.schema(e.map((t)=>this.parse(t)));and=(...e)=>e.reduce((t,n)=>t.and(this.parse(n)),this.intrinsic.unknown);merge=(...e)=>e.reduce((t,n)=>t.merge(this.parse(n)),this.intrinsic.object);pipe=(...e)=>this.intrinsic.unknown.pipe(...e);fn=new bd(this);match=new vd(this);declare=()=>({type:this.type});define(e){return e}type=new kd(this);static scope=(e,t={})=>new za(e,t);static module=(e,t={})=>this.scope(e,t).export()}var Ed=Object.assign(za.scope,{define:(e)=>e}),ue=za;class Mw extends at{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var XA=Vt(["base",ee.object],["props",ee.object])((e)=>e.base.merge(e.props),Mw),Tw=ue.module({Key:ee.key,Merge:XA});class Fw extends at{}var YA=Vt("element")((e)=>{let t=e.element.exclude(ee.Array),n=t.array();return t.rawOr(n).pipe(er).distribute((r)=>r.assertHasKind("morph").declareOut(n),ge)},Fw),Nw=ue.module({root:ee.Array,readonly:"root",index:ee.nonNegativeIntegerString,liftFrom:YA},{name:"Array"});var Ad=ge(["string",Pr.FileConstructor]),ZA=Ad.rawOr(Ad.array()),Dw=ge({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:ZA}}),Lw=ue.module({root:["instanceof",FormData],value:Ad,parsed:Dw,parse:ge({in:FormData,morphs:(e)=>{let t={};for(let[n,r]of e)if(n in t){let s=t[n];if(typeof s==="string"||s instanceof Pr.FileConstructor)t[n]=[s,r];else s.push(r)}else t[n]=r;return t},declaredOut:Dw})},{name:"FormData"});var jw=ue.module({Int8:["instanceof",Int8Array],Uint8:["instanceof",Uint8Array],Uint8Clamped:["instanceof",Uint8ClampedArray],Int16:["instanceof",Int16Array],Uint16:["instanceof",Uint16Array],Int32:["instanceof",Int32Array],Uint32:["instanceof",Uint32Array],Float32:["instanceof",Float32Array],Float64:["instanceof",Float64Array],BigInt64:["instanceof",BigInt64Array],BigUint64:["instanceof",BigUint64Array]},{name:"TypedArray"});var QA={Boolean:1,Number:1,String:1},Uw=ue.module({...ie({...mu,..._u},(e,t)=>(e in QA)?[]:[e,["instanceof",t]]),Array:Nw,TypedArray:jw,FormData:Lw});var eC=ge({domain:{domain:"number",meta:"a number representing a Unix timestamp"},divisor:{rule:1,meta:"an integer representing a Unix timestamp"},min:{rule:-8640000000000000,meta:"a Unix timestamp after -8640000000000000"},max:{rule:8640000000000000,meta:"a Unix timestamp before 8640000000000000"},meta:"an integer representing a safe Unix timestamp"}),tC=ge({domain:"number",divisor:1}),Ja=ue.module({root:ee.number,integer:tC,epoch:eC,safe:ge({domain:{domain:"number",numberAllowsNaN:!1},min:Number.MIN_SAFE_INTEGER,max:Number.MAX_SAFE_INTEGER}),NaN:["===",Number.NaN],Infinity:["===",Number.POSITIVE_INFINITY],NegativeInfinity:["===",Number.NEGATIVE_INFINITY]},{name:"number"});var Ae=(e,t,n)=>{let r={domain:"string",pattern:{rule:e.source,flags:e.flags,meta:t}};if(n)r.meta={format:n};return ki("intersection",r)},Bw=Ae(ws,"a well-formed integer string"),Qw=ue.module({root:Bw,parse:ge({in:Bw,morphs:(e,t)=>{let n=Number.parseInt(e);return Number.isSafeInteger(n)?n:t.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:ee.integer})},{name:"string.integer"}),nC=Ae(/^[\dA-Fa-f]+$/,"hex characters only"),rC=ue.module({root:Ae(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:Ae(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),qw=Ae(/^[A-Z].*$/,"capitalized"),iC=ue.module({root:ge({in:"string",morphs:(e)=>e.charAt(0).toUpperCase()+e.slice(1),declaredOut:qw}),preformatted:qw},{name:"string.capitalize"}),sC=(e)=>{let t=e.replace(/[ -]+/g,""),n=0,r,s,o=!1;for(let a=t.length-1;a>=0;a--){if(r=t.substring(a,a+1),s=Number.parseInt(r,10),o)s*=2,n+=s>=10?s%10+1:s;else n+=s;o=!o}return!!(n%10===0?t:!1)},oC=/^(?:4\d{12}(?:\d{3,6})?|5[1-5]\d{14}|(222[1-9]|22[3-9]\d|2[3-6]\d{2}|27[01]\d|2720)\d{12}|6(?:011|5\d\d)\d{12,15}|3[47]\d{13}|3(?:0[0-5]|[68]\d)\d{11}|(?:2131|1800|35\d{3})\d{11}|6[27]\d{14}|^(81\d{14,17}))$/,aC=ge({domain:"string",pattern:{meta:"a credit card number",rule:oC.source},predicate:{meta:"a credit card number",predicate:sC}});var lC=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))(T((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([,.]\d+(?!:))?)?(\17[0-5]\d([,.]\d+)?)?([Zz]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;var cC=(e)=>!Number.isNaN(new Date(e).valueOf()),Hw=ge({domain:"string",predicate:{meta:"a parsable date",predicate:cC}}).assertHasKind("intersection"),Kw=Qw.root.internal.narrow((e,t)=>{let n=Number.parseInt(e),r=Ja.epoch(n);if(r instanceof Et)return t.errors.merge(r),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),uC=ue.module({root:Kw,parse:ge({in:Kw,morphs:(e)=>new Date(e),declaredOut:ee.Date})},{name:"string.date.epoch"}),Ww=Ae(lC,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),dC=ue.module({root:Ww,parse:ge({in:Ww,morphs:(e)=>new Date(e),declaredOut:ee.Date})},{name:"string.date.iso"}),fC=ue.module({root:Hw,parse:ge({declaredIn:Hw,in:"string",morphs:(e,t)=>{let n=new Date(e);if(Number.isNaN(n.valueOf()))return t.error("a parsable date");return n},declaredOut:ee.Date}),iso:dC,epoch:uC},{name:"string.date"}),pC=Ae(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),Gw="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",ar=`(${Gw}[.]){3}${Gw}`,hC=new RegExp(`^${ar}$`),Le="(?:[0-9a-fA-F]{1,4})",mC=new RegExp(`^((?:${Le}:){7}(?:${Le}|:)|(?:${Le}:){6}(?:${ar}|:${Le}|:)|(?:${Le}:){5}(?::${ar}|(:${Le}){1,2}|:)|(?:${Le}:){4}(?:(:${Le}){0,1}:${ar}|(:${Le}){1,3}|:)|(?:${Le}:){3}(?:(:${Le}){0,2}:${ar}|(:${Le}){1,4}|:)|(?:${Le}:){2}(?:(:${Le}){0,3}:${ar}|(:${Le}){1,5}|:)|(?:${Le}:){1}(?:(:${Le}){0,4}:${ar}|(:${Le}){1,6}|:)|(?::((?::${Le}){0,5}:${ar}|(?::${Le}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),gC=ue.module({root:["v4 | v6","@","an IP address"],v4:Ae(hC,"an IPv4 address","ipv4"),v6:Ae(mC,"an IPv6 address","ipv6")},{name:"string.ip"}),Oi="a JSON string",ey=(e)=>{if(!(e instanceof SyntaxError))throw e;return`must be ${Oi} (${e})`},_C=ge({meta:Oi,domain:"string",predicate:{meta:Oi,predicate:(e,t)=>{try{return JSON.parse(e),!0}catch(n){return t.reject({code:"predicate",expected:Oi,problem:ey(n)})}}}}),wC=(e,t)=>{if(e.length===0)return t.error({code:"predicate",expected:Oi,actual:"empty"});try{return JSON.parse(e)}catch(n){return t.error({code:"predicate",expected:Oi,problem:ey(n)})}},yC=ue.module({root:_C,parse:ge({meta:"safe JSON string parser",in:"string",morphs:wC,declaredOut:ee.jsonObject})},{name:"string.json"}),Vw=Ae(/^[a-z]*$/,"only lowercase letters"),bC=ue.module({root:ge({in:"string",morphs:(e)=>e.toLowerCase(),declaredOut:Vw}),preformatted:Vw},{name:"string.lower"}),ty=["NFC","NFD","NFKC","NFKD"],Bs=ie(ty,(e,t)=>[t,ge({domain:"string",predicate:(n)=>n.normalize(t)===n,meta:`${t}-normalized unicode`})]),Xa=ie(ty,(e,t)=>[t,ge({in:"string",morphs:(n)=>n.normalize(t),declaredOut:Bs[t]})]),vC=ue.module({root:Xa.NFC,preformatted:Bs.NFC},{name:"string.normalize.NFC"}),xC=ue.module({root:Xa.NFD,preformatted:Bs.NFD},{name:"string.normalize.NFD"}),RC=ue.module({root:Xa.NFKC,preformatted:Bs.NFKC},{name:"string.normalize.NFKC"}),SC=ue.module({root:Xa.NFKD,preformatted:Bs.NFKD},{name:"string.normalize.NFKD"}),$C=ue.module({root:"NFC",NFC:vC,NFD:xC,NFKC:RC,NFKD:SC},{name:"string.normalize"}),zw=Ae(ba,"a well-formed numeric string"),kC=ue.module({root:zw,parse:ge({in:zw,morphs:(e)=>Number.parseFloat(e),declaredOut:ee.number})},{name:"string.numeric"}),Jw="a regex pattern",EC=ge({domain:"string",predicate:{meta:Jw,predicate:(e,t)=>{try{return new RegExp(e),!0}catch(n){return t.reject({code:"predicate",expected:Jw,problem:String(n)})}}},meta:{format:"regex"}}),AC=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*))*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?$/,CC=Ae(AC,"a semantic version (see https://semver.org/)"),Xw=Ae(/^\S.*\S$|^\S?$/,"trimmed"),OC=ue.module({root:ge({in:"string",morphs:(e)=>e.trim(),declaredOut:Xw}),preformatted:Xw},{name:"string.trim"}),Yw=Ae(/^[A-Z]*$/,"only uppercase letters"),IC=ue.module({root:ge({in:"string",morphs:(e)=>e.toUpperCase(),declaredOut:Yw}),preformatted:Yw},{name:"string.upper"}),PC=(e)=>URL.canParse(e),Zw=ge({domain:"string",predicate:{meta:"a URL string",predicate:PC},meta:{format:"uri"}}),MC=ue.module({root:Zw,parse:ge({declaredIn:Zw,in:"string",morphs:(e,t)=>{try{return new URL(e)}catch{return t.error("a URL string")}},declaredOut:ge(URL)})},{name:"string.url"}),TC=ue.module({root:["versioned | nil | max","@",{description:"a UUID",format:"uuid"}],"#nil":"'00000000-0000-0000-0000-000000000000'","#max":"'ffffffff-ffff-ffff-ffff-ffffffffffff'","#versioned":/[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}/i,v1:Ae(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:Ae(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:Ae(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:Ae(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:Ae(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:Ae(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:Ae(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:Ae(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),ny=ue.module({root:ee.string,alpha:Ae(/^[A-Za-z]*$/,"only letters"),alphanumeric:Ae(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:nC,base64:rC,capitalize:iC,creditCard:aC,date:fC,digits:Ae(/^\d*$/,"only digits 0-9"),email:pC,integer:Qw,ip:gC,json:yC,lower:bC,normalize:$C,numeric:kC,regex:EC,semver:CC,trim:OC,upper:IC,url:MC,uuid:TC},{name:"string"});var ry=ue.module({bigint:ee.bigint,boolean:ee.boolean,false:ee.false,never:ee.never,null:ee.null,number:ee.number,object:ee.object,string:ee.string,symbol:ee.symbol,true:ee.true,unknown:ee.unknown,undefined:ee.undefined}),iy=ue.module({root:ee.unknown,any:ee.unknown},{name:"unknown"}),FC=ue.module({root:ee.jsonObject,stringify:ki("morph",{in:ee.jsonObject,morphs:(e)=>JSON.stringify(e),declaredOut:ee.string})},{name:"object.json"}),sy=ue.module({root:ee.object,json:FC},{name:"object"});class oy extends at{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var NC=Vt(["K",ee.key],"V")((e)=>({domain:"object",index:{signature:e.K,value:e.V}}),oy);class ay extends at{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var DC=Vt(["T",ee.object],["K",ee.key])((e)=>e.T.pick(e.K),ay);class ly extends at{description='omit a set of properties from an object like `Omit(User, "age")`'}var LC=Vt(["T",ee.object],["K",ee.key])((e)=>e.T.omit(e.K),ly);class cy extends at{description="make all named properties of an object optional like `Partial(User)`"}var jC=Vt(["T",ee.object])((e)=>e.T.partial(),cy);class uy extends at{description="make all named properties of an object required like `Required(User)`"}var UC=Vt(["T",ee.object])((e)=>e.T.required(),uy);class dy extends at{description='exclude branches of a union like `Exclude("boolean", "true")`'}var BC=Vt("T","U")((e)=>e.T.exclude(e.U),dy);class fy extends at{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var qC=Vt("T","U")((e)=>e.T.extract(e.U),fy),py=ue.module({Exclude:BC,Extract:qC,Omit:LC,Partial:jC,Pick:DC,Record:NC,Required:UC});var Nn=Ed({...ry,...py,...Uw,...Tw,string:ny,number:Ja,object:sy,unknown:iy},{prereducedAliases:!0,name:"ark"}),Ge=Nn.export();Object.assign(Ci.ambient,Ge);Ci.typeAttachments={string:Ge.string.root,number:Ge.number.root,bigint:Ge.bigint,boolean:Ge.boolean,symbol:Ge.symbol,undefined:Ge.undefined,null:Ge.null,object:Ge.object.root,unknown:Ge.unknown.root,false:Ge.false,true:Ge.true,never:Ge.never,arrayIndex:Ge.Array.index,Key:Ge.Key,Record:Ge.Record,Array:Ge.Array.root,Date:Ge.Date};var Z=Object.assign(Nn.type,Ci.typeAttachments),{match:HC,fn:KC,generic:WC,schema:S2,define:GC,declare:VC}=Nn;var Ya=Z("'running' | 'complete' | 'failed' | 'cancelled'"),Za=Z({kind:"'pr'",number:"number",url:"string",title:"string",author:"string",baseRef:"string",headRef:"string",state:"string",isDraft:"boolean"}).or({kind:"'range' | 'branch' | 'commit'",spec:"string"}).or({kind:"'staged' | 'worktree'","branch?":"string"}),my=Z("'additions' | 'deletions'"),zC=Z("'not-in-diff' | 'far-from-diff' | 'no-line' | 'deleted-file' | 'no-hunks'"),gy=Z({file:"string",side:my,kind:"'line' | 'nearby' | 'file'",line:"number","endLine?":"number",cited:{line:"number","endLine?":"number"},"text?":"string","reason?":zC}),JC=Z("'added' | 'removed' | 'modified' | 'renamed' | 'copied'"),_y=Z("'product' | 'deploy' | 'tooling'"),XC=Z({path:"string","previousPath?":"string",status:JC,additions:"number",deletions:"number",isBinary:"boolean","blob?":"string",groupId:"string",classification:"'code' | 'docs' | 'skip'","surface?":_y}),YC=Z("'bug' | 'wrench' | 'path' | 'flask' | 'doc' | 'gear'"),Od=Z({id:"string","parentId?":"string",title:"string","summary?":"string","icon?":YC,files:"string[]",findingIds:"string[]",stopIds:"string[]",critical:"boolean"}),ZC=Z({id:"string",chapterId:"string",index:"number",title:"string","prose?":"string",importance:"'critical' | 'normal' | 'context'",locations:gy.and({"label?":"string"}).array()}),wy=Z("'blocker' | 'should-fix' | 'nice-to-have' | 'question'"),hy=Z({id:"string",file:"string",anchor:gy,severity:wy,category:"string",title:"string",explanation:"string",evidence:"string","impact?":"string",confidence:"'high' | 'medium' | 'low'","effort?":"'quick' | 'moderate' | 'involved'","suggestion?":"string","suggestedCode?":"string","crossFileRefs?":Z({file:"string","line?":"number"}).array(),"alsoAt?":Z({file:"string","line?":"number"}).array(),"repeatOf?":"number","carriedFrom?":"string","surface?":_y,"preexisting?":"boolean"}),yy=Z({input:"number",output:"number",reasoning:"number",cacheRead:"number",cacheWrite:"number","firstStep?":{input:"number",cacheRead:"number",cacheWrite:"number"}}),QC=Z({unit:"string",part:"number",parts:"number",status:"'ok' | 'failed'",costUsd:"number",wallMs:"number","usage?":yy}),Cd=Z({costUsd:"number",wallMs:"number","usage?":yy}),Qa=Z({root:"string","slug?":"string","remote?":"boolean"}),qs=Z("'review' | 'diff'");function by(e){return e.meta.kind??"review"}var eO=Z({fp:"string",outcome:"'withdrawn' | 'upheld' | 'unjudged'","earlier?":"boolean","file?":"string","line?":"string","claim?":"string","note?":"string"}),tO=Z({open:"number",fixed:"number",withdrawn:"number",upheld:"number",fixedThisRound:"number",withdrawnThisRound:"number",new:"number"}),nO=Z({id:"string",acted:"boolean",control:"boolean"}),vy=Z({schemaVersion:"1",id:"string",status:Ya,createdAt:"string",repo:Qa,target:Za,base:"string",head:"string",intent:{"stated?":"string","inferred?":"string","alignment?":"'aligned' | 'partial' | 'misaligned'","matches?":"string[]","mismatches?":"string[]","unstated?":"string[]","missing?":"string[]"},overview:{"focus?":"string","changeType?":"string",startHere:Z({file:"string",why:"string"}).array()},files:XC.array(),groups:Od.array(),stops:ZC.array(),findings:hy.array(),overCapFindings:hy.array(),resolved:Z({id:"string","note?":"string","title?":"string","file?":"string"}).array(),"disputes?":eO.array(),"roundProgress?":tO,unreviewed:{overCap:"string[]",failed:"string[]","budget?":"string[]"},meta:{"model?":"string","effort?":"string","models?":{"review?":{model:"string","source?":"string"},"coordinator?":{model:"string","source?":"string"},"walkthrough?":{model:"string","source?":"string"},"intent?":{model:"string","source?":"string"}},"kind?":qs,wallMs:"number",costUsd:"number",slices:QC.array(),"stages?":{"coordinator?":Cd,"walkthrough?":Cd,"intent?":Cd},rejectedCount:"number",coreSource:"string","mergeMode?":"'coordinator' | 'nothing-to-merge' | 'deterministic-fallback'","budgetStopped?":"boolean","postMinSeverity?":wy,"reviewScope?":"'full' | 'incremental'","reviewedFiles?":"number","scopeReason?":"string","promptVersion?":"string","instructionsHash?":"string","roundLimit?":{maxRounds:"number",round:"number"}},untrackedSkipped:"string[]","priorRunId?":"string","round?":"number","priorActedOn?":nO.array(),"error?":"string"}),Id=Z("'open' | 'accepted' | 'dismissed'"),Pd=Z("'wrong' | 'not-worth-fixing' | 'already-handled' | 'duplicate' | 'other'"),el=["wrong","not-worth-fixing","already-handled","duplicate","other"],rO=Z({reason:Pd,"note?":"string",at:"string"}),xy=Z({reviewedFiles:Z.Record("string","string"),findingStatus:Z.Record("string",Id),"findingNotes?":Z.Record("string",rO),comments:Z({id:"string",file:"string",side:my,line:"number","endLine?":"number",body:"string"}).array(),"submitted?":{at:"string","url?":"string"}}),q2=Z({id:"string",status:Ya,createdAt:"string",target:Za,repo:Qa,"kind?":qs,findingCounts:{blocker:"number","should-fix":"number","nice-to-have":"number",question:"number"},costUsd:"number","roundLimited?":"true","invalid?":"string"});function lr(e){if(e.kind==="pr")return`PR #${e.number} ${e.title}`;if("spec"in e)return`${e.kind} ${e.spec}`;return e.branch?`${e.kind} (${e.branch})`:e.kind}function Ld(e){let t=e.side==="deletions"?" [base]":"";if(e.kind==="file")return`${e.file} (file${e.reason?`: ${e.reason}`:""})`;let n=(r,s)=>s&&s!==r?`${r}-${s}`:`${r}`;if(e.kind==="nearby")return`${e.file}:${n(e.cited.line,e.cited.endLine)} \u2192 ${e.line} (nearby)${t}`;return`${e.file}:${n(e.line,e.endLine)} (line)${t}`}function sO(e){let t=[e.blocker&&`${e.blocker} blocker`,e["should-fix"]&&`${e["should-fix"]} should-fix`,e["nice-to-have"]&&`${e["nice-to-have"]} nice-to-have`,e.question&&`${e.question} question`].filter(Boolean);return t.length?t.join(", "):"no findings"}function Ay(e){if(e.length===0)return"No saved runs.";return e.map((t)=>[t.id,` ${(t.kind??"review").padEnd(6)} ${t.status.padEnd(8)} ${t.createdAt} ${lr(t.target)}`,t.kind==="diff"?` ${t.repo.slug??t.repo.root}${t.costUsd?` $${t.costUsd.toFixed(2)}`:""}`:` ${t.repo.slug??t.repo.root} ${sO(t.findingCounts)} $${t.costUsd.toFixed(2)}`].join(`
616
+ `)+"}");class Ka{config;resolvedConfig;name;get[ht](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(e,t){if(this.config=Ms(N.config,t),this.resolvedConfig=Ms(N.resolvedConfig,t),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(yd).length}`,this.name in yd)A(`A Scope already named ${this.name} already exists`);yd[this.name]=this;let n=Object.entries(e).map((r)=>this.preparseOwnAliasEntry(...r));for(let[r,s]of n){let o=r;if(r[0]==="#"){if(o=r.slice(1),o in this.aliases)A(lw(o));this.aliases[o]=s}else{if(o in this.aliases)A(lw(r));this.aliases[o]=s,this.exportedNames.push(o)}if(!X(s,"module")&&!X(s,"generic")&&!ir(s)){let a=this.preparseOwnDefinitionFormat(s,{alias:o});this.resolutions[o]=X(a,"root")?this.bindReference(a):this.createParseContext(a).id}}cw??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[cw.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=N.intrinsic?ie(N.intrinsic,(r,s)=>r.startsWith("json")?[]:[r,this.bindReference(s)]):{}}cacheGetter(e,t){return Object.defineProperty(this,e,{value:t}),t}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(e){return e}generic=(...e)=>{let t=this;return(n,r)=>new cr(e,r?new Na(n):n,t,t,r??null)};units=(e,t)=>{let n=[];for(let s of e)if(!n.includes(s))n.push(s);let r=n.map((s)=>this.node("unit",{unit:s},t));return this.node("union",r,{...t,prereduced:!0})};lazyResolutions=[];lazilyResolve(e,t){let n=this.node("alias",{reference:t??"synthetic",resolve:e},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(n);return n}schema=(e,t)=>this.finalize(this.parseSchema(e,t));parseSchema=(e,t)=>this.node(Fs(e),e,t);preparseNode(e,t,n){let r=typeof e==="string"?e:Fs(t,e);if($e(t)&&t.kind===r)return t;if(r==="alias"&&!n?.prereduced){let{reference:a}=Hs.implementation.normalize(t,this);if(a.startsWith("$")){let l=this.resolveRoot(a.slice(1));t=l,r=l.kind}}else if(r==="union"&&St(t,"object")){let a=U0(t);if(a?.length===1)t=a[0],r=Fs(t)}if($e(t)&&t.kind===r)return t;let o=Ei[r].normalize?.(t,this)??t;if($e(o))return o.kind===r?o:B0(r,o.kind);return{...n,$:this,kind:r,def:o,prefix:n.alias??r}}bindReference(e){let t;if($e(e))t=e.$===this?e:new e.constructor(e.attachments,this);else t=e.$===this?e:new cr(e.params,e.bodyDef,e.$,this,e.hkt);if(!this.resolved)Object.assign(this.referencesById,t.referencesById);return t}resolveRoot(e){return this.maybeResolveRoot(e)??A(xd(e))}maybeResolveRoot(e){let t=this.maybeResolve(e);if(X(t,"generic"))return;return t}maybeResolveSubalias(e){return bd(this.aliases,e)??bd(this.ambient,e)}get ambient(){return N.ambient}maybeResolve(e){let t=this.resolutions[e];if(t){if(typeof t!=="string")return this.bindReference(t);let r=mt[t];if(X(r,"root"))return this.resolutions[e]=r;if(X(r,"context")){if(r.phase==="resolving")return this.node("alias",{reference:`$${e}`},{prereduced:!0});if(r.phase==="resolved")return he(`Unexpected resolved context for was uncached by its scope: ${se(r)}`);r.phase="resolving";let s=this.bindReference(this.parseOwnDefinitionFormat(r.def,r));return r.phase="resolved",mt[s.id]=s,mt[r.id]=s,this.resolutions[e]=s}return he(`Unexpected nodesById entry for ${t}: ${se(r)}`)}let n=this.aliases[e]??this.ambient?.[e];if(!n)return this.maybeResolveSubalias(e);if(n=this.normalizeRootScopeValue(n),X(n,"generic"))return this.resolutions[e]=this.bindReference(n);if(X(n,"module")){if(!n.root)A(gw(e));return this.resolutions[e]=this.bindReference(n.root)}return this.resolutions[e]=this.parse(n,{alias:e})}createParseContext(e){let t=e.id??nd(e.prefix);return mt[t]=Object.assign(e,{[ht]:"context",$:this,id:t,phase:"unresolved"})}traversal(e){return new an(e,this.resolvedConfig)}import(...e){return new Oi(ie(this.export(...e),(t,n)=>[`#${t}`,n]))}precompilation;_exportedResolutions;_exports;export(...e){if(!this._exports){this._exports={};for(let n of this.exportedNames){let r=this.aliases[n];this._exports[n]=X(r,"module")?wd(r,this):uw(this.maybeResolve(n))}for(let n of this.lazyResolutions)n.resolution;if(this._exportedResolutions=mw(this,this._exports),this._json=hw(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let n=pw(this.references);this.precompilation=n.write(dw,4),fw(this.references,n)}this.resolved=!0}let t=e.length?e:this.exportedNames;return new Oi(ie(t,(n,r)=>[r,this._exports[r]]))}resolve(e){return this.export()[e]}node=(e,t,n={})=>{let r=this.preparseNode(e,t,n);if($e(r))return this.bindReference(r);let s=this.createParseContext(r),o=rd(s),a=this.bindReference(o);return mt[s.id]=a};parse=(e,t={})=>this.finalize(this.parseDefinition(e,t));parseDefinition(e,t={}){if(X(e,"root"))return this.bindReference(e);let n=this.preparseOwnDefinitionFormat(e,t);if(X(n,"root"))return this.bindReference(n);let r=this.createParseContext(n);mt[r.id]=r;let s=this.bindReference(this.parseOwnDefinitionFormat(e,r));if(s.isCyclic)s=P_(s,r.id);return mt[r.id]=s,s}finalize(e){if(uw(e),!e.precompilation&&!this.resolvedConfig.jitless)q0(e.references);return e}}class vd extends Ka{parseOwnDefinitionFormat(e,t){return rd(t)}preparseOwnDefinitionFormat(e,t){return this.preparseNode(Fs(e),e,t)}preparseOwnAliasEntry(e,t){return[e,t]}normalizeRootScopeValue(e){return e}}var uw=(e)=>{let t=e.references.filter((n)=>n.hasKind("alias"));for(let n of t){Object.assign(n.referencesById,n.resolution.referencesById);for(let r of e.references)if(n.id in r.referencesById)Object.assign(r.referencesById,n.referencesById)}return e},hw=(e)=>ie(e,(t,n)=>[t,X(n,"root")||X(n,"generic")?n.json:X(n,"module")?hw(n):he(`Unexpected resolution ${se(n)}`)]),bd=(e,t)=>{let n=t.indexOf(".");if(n===-1)return;let r=t.slice(0,n),s=e[r];if(s===void 0)return;if(!X(s,"module"))return A(H0(r));let o=t.slice(n+1),a=s[o];if(a===void 0)return bd(s,o);if(X(a,"root")||X(a,"generic"))return a;if(X(a,"module"))return a.root??A(gw(t));he(`Unexpected resolution for alias '${t}': ${se(a)}`)},Ga=(e,t)=>new vd(e,t),Ws=new vd({});var mw=(e,t)=>{let n={};for(let r in t){let s=t[r];if(X(s,"module")){let o=mw(e,s),a=ie(o,(l,c)=>[`${r}.${l}`,c]);Object.assign(n,a)}else if(X(s,"root")||X(s,"generic"))n[r]=s;else he(`Unexpected scope resolution ${se(s)}`)}return n},xd=(e)=>`'${e}' is unresolvable`,H0=(e)=>`'${e}' must reference a module to be accessed using dot syntax`,gw=(e)=>`Reference to submodule '${e}' must specify an alias`;Ws.export();var{schema:ge,node:Ii,defineSchema:BH,generic:zt}=Ws;var Sd="^(?:0|[1-9]\\d*)$",K0=new RegExp(Sd),KH=Me(K0);var _w=Ga({bigint:"bigint",boolean:[{unit:!1},{unit:!0}],false:{unit:!1},never:[],null:{unit:null},number:"number",object:"object",string:"string",symbol:"symbol",true:{unit:!0},unknown:{},undefined:{unit:void 0},Array,Date},{prereducedAliases:!0}).export();N.intrinsic={..._w};var ww=Ga({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:Sd}},{prereducedAliases:!0}).export();Object.assign(N.intrinsic,ww);var G0=Ga({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),ee={..._w,...ww,...G0,emptyStructure:Ii("structure",{},{prereduced:!0})};N.intrinsic={...ee};var Wa=(e,t)=>new RegExp(e,t);Object.assign(Wa,{as:Wa});var bw=(e)=>typeof e==="string"&&e[0]==="d"&&(e[1]==="'"||e[1]==='"')&&e[e.length-1]===e[1],yw=(e)=>e.toString()!=="Invalid Date",vw=(e)=>e.slice(2,-1),Rd=(e)=>`'${e}' could not be parsed by the Date constructor`,xw=(e,t)=>W0(e,t),W0=(e,t)=>{let n=new Date(e);if(yw(n))return n;let r=zg(e);if(r!==void 0){let s=new Date(r);if(yw(s))return s}return t?A(t===!0?Rd(e):t):void 0};var V0=ge({proto:"Array",sequence:"string",required:{key:"groups",value:["object",{unit:void 0}]}}),Va=(e,t)=>{let n=e.scanner.shiftUntilEscapable(J0[$w[t]]);if(e.scanner.lookahead==="")return e.error(Y0(n,t));if(e.scanner.shift(),t in Rw){let r;try{r=new RegExp(n)}catch(s){A(String(s))}if(e.root=e.ctx.$.node("intersection",{domain:"string",pattern:n},{prereduced:!0}),t==="x/")e.root=e.ctx.$.node("morph",{in:e.root,morphs:(s)=>r.exec(s),declaredOut:V0})}else if(Ge(t,$d))e.root=e.ctx.$.node("unit",{unit:n});else{let r=xw(n,Rd(n));e.root=e.ctx.$.node("unit",{meta:n,unit:r})}},$d={"'":1,'"':1},Sw={"/":1,"'":1,'"':1},z0={"d'":"'",'d"':'"',"'":"'",'"':'"'},Rw={"/":"/","x/":"/"},$w={...z0,...Rw},J0={"'":(e)=>e.lookahead==="'",'"':(e)=>e.lookahead==='"',"/":(e)=>e.lookahead==="/"},X0={'"':"double-quote","'":"single-quote","/":"forward slash"},Y0=(e,t)=>`${t}${e} requires a closing ${X0[$w[t]]}`;var kw=(e)=>`Private type references should not include '#'. Use '${e}' instead.`,za="Optional definitions like 'string?' are only valid as properties in an object or tuple",Ja="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var Sn={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...sr};var Ew=(e,t)=>e===">"?t[0]==="="?t[1]==="=":t.trimStart()===""||Ge(t.trimStart()[0],Sn):e==="="?t[0]!=="=":e===","||e==="?";var Cw=(e,t,n)=>Aw(e,t,n,[]),Aw=(e,t,n,r)=>{let s=n.parseUntilFinalizer();if(r.push(s.root),s.finalizer===">"){if(r.length!==t.params.length)return n.error(kd(e,t.names,r.map((o)=>o.expression)));return r}if(s.finalizer===",")return Aw(e,t,n,r);return s.error(Oa(">"))},kd=(e,t,n)=>`${e}<${t.join(", ")}> requires exactly ${t.length} args (got ${n.length}${n.length===0?"":`: ${n.join(", ")}`})`;var Xa=(e)=>{let t=e.scanner.shiftUntilLookahead(Sn);if(t==="keyof")e.addPrefix("keyof");else e.root=Q0(e,t)},Z0=(e,t,n)=>{if(n.scanner.shiftUntilNonWhitespace(),n.scanner.shift()!=="<")return n.error(kd(e,t.names,[]));let s=Cw(e,t,n);return t(...s)},Q0=(e,t)=>eA(e,t)??tA(e,t)??e.error(t===""?e.scanner.lookahead==="#"?kw(e.shiftedBy(1).scanner.shiftUntilLookahead(Sn)):Ed(e):xd(t)),eA=(e,t)=>{if(e.ctx.args?.[t]){let r=e.ctx.args[t];if(typeof r!=="string")return r;return e.ctx.$.node("alias",{reference:r},{prereduced:!0})}let n=e.ctx.$.maybeResolve(t);if(X(n,"root"))return n;if(n===void 0)return;if(X(n,"generic"))return Z0(t,n,e);return A(`Unexpected resolution ${se(n)}`)},tA=(e,t)=>{let n=Jg(t);if(n!==void 0)return e.ctx.$.node("unit",{unit:n});let r=Yg(t);if(r!==void 0)return e.ctx.$.node("unit",{unit:r})},Ed=(e)=>{let t=e.previousOperator();return t?Cd(t,e.scanner.unscanned):nA(e.scanner.unscanned)},Cd=(e,t="")=>`Token '${e}' requires a right operand${t?` before '${t}'`:""}`,nA=(e)=>`Expected an expression${e?` before '${e}'`:""}`;var Ad=(e)=>e.scanner.lookahead===""?e.error(Ed(e)):e.scanner.lookahead==="("?e.shiftedBy(1).reduceGroupOpen():e.scanner.lookaheadIsIn(Sw)?Va(e,e.scanner.shift()):e.scanner.lookaheadIsIn(sr)?Ad(e.shiftedBy(1)):e.scanner.lookahead==="d"?e.scanner.nextLookahead in $d?Va(e,`${e.scanner.shift()}${e.scanner.shift()}`):Xa(e):e.scanner.lookahead==="x"?e.scanner.nextLookahead==="/"?e.shiftedBy(2)&&Va(e,"x/"):Xa(e):Xa(e);var Ow={">":!0,">=":!0},Iw={"<":!0,"<=":!0};var Pi={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},Pw=(e,t)=>`Left bounds are only valid when paired with right bounds (try ...${t}${e})`,Ya=(e)=>`Left-bounded expressions must specify their limits using < or <= (was ${e})`,Mw=(e,t,n,r)=>`An expression may have at most one left bound (parsed ${e}${Pi[t]}, ${n}${Pi[r]})`;var Dw=(e,t)=>{let n=rA(e,t);if(e.root.hasKind("unit")){if(typeof e.root.unit==="number"){e.reduceLeftBound(e.root.unit,n),e.unsetRoot();return}if(e.root.unit instanceof Date){let r=`d'${e.root.description??e.root.unit.toISOString()}'`;e.unsetRoot(),e.reduceLeftBound(r,n);return}}return sA(e,n)},Nw={"<":1,">":1,"=":1},rA=(e,t)=>e.scanner.lookaheadIs("=")?`${t}${e.scanner.shift()}`:t;var Tw=(e,t,n,r)=>{if(n.extends(N.intrinsic.number)){if(typeof t!=="number")return A(Od(e,t,r));return e==="=="?["min","max"]:e[0]===">"?["min"]:["max"]}if(n.extends(N.intrinsic.lengthBoundable)){if(typeof t!=="number")return A(Od(e,t,r));return e==="=="?["exactLength"]:e[0]===">"?["minLength"]:["maxLength"]}if(n.extends(N.intrinsic.Date))return e==="=="?["after","before"]:e[0]===">"?["after"]:["before"];return A(y_(n.expression))},iA=(e)=>({rule:bw(e.limit)?vw(e.limit):e.limit,exclusive:e.comparator.length===1}),sA=(e,t)=>{let n=e.unsetRoot(),r=e.scanner.location;e.parseOperand();let s=e.unsetRoot(),o=e.scanner.sliceChars(r,e.scanner.location);if(e.root=n,!s.hasKind("unit")||typeof s.unit!=="number"&&!(s.unit instanceof Date))return e.error(Od(t,o,"right"));let a=s.unit,l=t.length===1,c=Tw(t,typeof a==="number"?a:o,n,"right");for(let d of c)e.constrainRoot(d,t==="=="?{rule:a}:{rule:a,exclusive:l});if(!e.branches.leftBound)return;if(!Ge(t,Iw))return e.error(Ya(t));let u=Tw(e.branches.leftBound.comparator,e.branches.leftBound.limit,n,"left");e.constrainRoot(u[0],iA(e.branches.leftBound)),e.branches.leftBound=null},Od=(e,t,n)=>`Comparator ${n==="left"?Pi[e]:e} must be ${n==="left"?"preceded":"followed"} by a corresponding literal (was ${t})`;var Fw=(e)=>{e.scanner.shiftUntilNonWhitespace();let t=e.scanner.shiftUntilLookahead(Sn);e.root=e.root.brand(t)};var jw=(e)=>{e.scanner.shiftUntilNonWhitespace();let t=e.scanner.shiftUntilLookahead(Sn),n=Xg(t,{errorOnFail:Lw(t)});if(n===0)e.error(Lw(0));e.root=e.root.constrain("divisor",n)},Lw=(e)=>`% operator must be followed by a non-zero integer literal (was ${e})`;var Id=(e)=>{let t=e.scanner.shift();return t===""?e.finalize(""):t==="["?e.scanner.shift()==="]"?e.setRoot(e.root.array()):e.error(oA):t==="|"?e.scanner.lookahead===">"?e.shiftedBy(1).pushRootToBranch("|>"):e.pushRootToBranch(t):t==="&"?e.pushRootToBranch(t):t===")"?e.finalizeGroup():Ew(t,e.scanner.unscanned)?e.finalize(t):Ge(t,Nw)?Dw(e,t):t==="%"?jw(e):t==="#"?Fw(e):(t in sr)?Id(e):e.error(Za(t))},Za=(e,t="")=>`'${e}' is not allowed here${t&&` (should be ${t})`}`,oA="Missing expected ']'";var Uw=(e)=>{let t=e.unsetRoot();e.parseOperand();let n=e.unsetRoot();if(!n.hasKind("unit"))return e.error(aA(n.expression));let r=n.unit instanceof Date?()=>new Date(n.unit):n.unit;return[t,"=",r]},aA=(e)=>`Default value '${e}' must be a literal value`;var Pd=(e,t)=>{let n=t.$.maybeResolveRoot(e);if(n)return n;if(e.endsWith("[]")){let o=t.$.maybeResolveRoot(e.slice(0,-2));if(o)return o.array()}let r=new Mi(new Is(e),t),s=lA(r);if(r.finalizer===">")A(Za(">"));return s},lA=(e)=>{e.parseOperand();let t=Vs(e).root;if(!t)return he(`Root was unexpectedly unset after parsing string '${e.scanner.scanned}'`);if(e.finalizer==="=")t=Uw(e);else if(e.finalizer==="?")t=[t,"?"];if(e.scanner.shiftUntilNonWhitespace(),e.scanner.lookahead)A(Za(e.scanner.lookahead));return t},Vs=(e)=>{while(e.finalizer===void 0)cA(e);return e},cA=(e)=>e.hasRoot()?e.parseOperator():e.parseOperand();class Mi{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(e,t){this.scanner=e,this.ctx=t}error(e){return A(e)}hasRoot(){return this.root!==void 0}setRoot(e){this.root=e}unsetRoot(){let e=this.root;return this.root=void 0,e}constrainRoot(...e){this.root=this.root.constrain(e[0],e[1])}finalize(e){if(this.groups.length)return this.error(Oa(")"));this.finalizeBranches(),this.finalizer=e}reduceLeftBound(e,t){let n=Pi[t];if(!Ge(n,Ow))return this.error(Ya(t));if(this.branches.leftBound)return this.error(Mw(this.branches.leftBound.limit,this.branches.leftBound.comparator,e,n));this.branches.leftBound={comparator:n,limit:e}}finalizeBranches(){if(this.assertRangeUnset(),this.branches.pipe){this.pushRootToBranch("|>"),this.root=this.branches.pipe;return}if(this.branches.union){this.pushRootToBranch("|"),this.root=this.branches.union;return}if(this.branches.intersection){this.pushRootToBranch("&"),this.root=this.branches.intersection;return}this.applyPrefixes()}finalizeGroup(){this.finalizeBranches();let e=this.groups.pop();if(!e)return this.error(t_(")",this.scanner.unscanned));this.branches=e}addPrefix(e){this.branches.prefixes.push(e)}applyPrefixes(){while(this.branches.prefixes.length){let e=this.branches.prefixes.pop();this.root=e==="keyof"?this.root.keyof():he(`Unexpected prefix '${e}'`)}}pushRootToBranch(e){this.assertRangeUnset(),this.applyPrefixes();let t=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(t)??t,e==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,e==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return Vs(new Mi(this.scanner,this.ctx))}parseOperator(){return Id(this)}parseOperand(){return Ad(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(Pw(this.branches.leftBound.limit,this.branches.leftBound.comparator))}reduceGroupOpen(){this.groups.push(this.branches),this.branches={prefixes:[],leftBound:null,union:null,intersection:null,pipe:null}}previousOperator(){return this.branches.leftBound?.comparator??this.branches.prefixes[this.branches.prefixes.length-1]??(this.branches.intersection?"&":this.branches.union?"|":this.branches.pipe?"|>":void 0)}shiftedBy(e){return this.scanner.jumpForward(e),this}}var uA="An empty string is not a valid generic parameter name",Qa=(e,t,n)=>{e.shiftUntilNonWhitespace();let r=e.shiftUntilLookahead(Sn);if(r===""){if(e.lookahead===""&&t.length)return t;return A(uA)}return e.shiftUntilNonWhitespace(),dA(e,r,t,n)},Bw="extends ",dA=(e,t,n,r)=>{if(e.shiftUntilNonWhitespace(),e.unscanned.startsWith(Bw))e.jumpForward(Bw.length);else{if(e.lookahead===",")e.shift();return n.push(t),Qa(e,n,r)}let s=Vs(new Mi(e,r));return n.push([t,s.root]),Qa(e,n,r)};class Md extends kt{constructor(e){let t={$:e,raw:e.fn};super((...n)=>{let r=n.indexOf(":"),s=r===-1?n.length-1:r-1,o=n.slice(0,s+1),a=e.parse(o).assertHasKind("intersection"),l=e.intrinsic.unknown;if(r!==-1){if(r!==n.length-2)return A(fA);l=e.parse(n[r+1])}return(c)=>new qw(c,a,l)},{attach:t})}}class qw extends kt{raw;params;returns;expression;constructor(e,t,n){let r=`typed ${e.name}`,s={[r]:(...a)=>{let l=t.assert(a),c=e(...l);return n.assert(c)}}[r];super(s);this.raw=e,this.params=t,this.returns=n;let o=t.expression;if(o[0]==="["&&o[o.length-1]==="]")o=o.slice(1,-1);else if(o.endsWith("[]"))o=`...${o}`;this.expression=`(${o}) => ${n?.expression??"unknown"}`}}var fA=`":" must be followed by exactly one return type e.g:
617
+ fn("string", ":", "number")(s => s.length)`;class Td extends kt{$;constructor(e){super((...t)=>new zs(e)(...t),{bind:e});this.$=e}in(e){return new zs(this.$,e===void 0?void 0:this.$.parse(e))}at(e,t){return new zs(this.$).at(e,t)}case(e,t){return new zs(this.$).case(e,t)}}class zs extends kt{$;in;key;branches=[];constructor(e,t){super((n)=>this.caseEntries(Object.entries(n).map(([r,s])=>r==="default"?[r,s]:[this.$.parse(r),s])));this.$=e,this.in=t}at(e,t){if(this.key)A(hA);if(this.branches.length)A(pA);return this.key=e,t?this.match(t):this}case(e,t){return this.caseEntry(this.$.parse(e),t)}caseEntry(e,t){let r=(this.key?this.$.parse({[this.key]:e}):e).pipe(t);return this.branches.push(r),this}match(e){return this(e)}strings(e){return this.caseEntries(Object.entries(e).map(([t,n])=>t==="default"?[t,n]:[this.$.node("unit",{unit:t}),n]))}caseEntries(e){for(let t=0;t<e.length;t++){let[n,r]=e[t];if(n==="default"){if(t!==e.length-1)A("default may only be specified as the last key of a switch definition");return this.default(r)}if(typeof r!=="function")return A(`Value for case "${n}" must be a function (was ${Ke(r)})`);this.caseEntry(n,r)}return this}default(e){if(typeof e==="function")this.case(ee.unknown,e);let t={branches:this.branches,ordered:!0};if(e==="never"||e==="assert")t.meta={onFail:Hw};let n=this.$.node("union",t);if(!this.in)return this.$.finalize(n);let r=this.in.pipe(n);if(e==="never"||e==="assert")r=r.configureReferences({onFail:Hw},"self");return this.$.finalize(r)}}var Hw=(e)=>e.throw(),pA="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",hA="At most one key matcher may be specified per expression";var el=(e,t)=>{if(Se(e)){if(e[1]==="=")return[t.$.parseOwnDefinitionFormat(e[0],t),"=",e[2]];if(e[1]==="?")return[t.$.parseOwnDefinitionFormat(e[0],t),"?"]}return tl(e,t)},Kw="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",Gw="Only required keys may specify default values, e.g. { value: 'number = 0' }";var Ww=(e,t)=>{let n,r={},s=Mr(e);for(let[a,l]of s){let c=_A(a);if(c.kind==="spread"){if(!vn(r))return A(gA);let h=t.$.parseOwnDefinitionFormat(l,t);if(h.equals(ee.object))continue;if(!h.hasKind("intersection")||!h.basis?.equals(ee.object))return A(wA(h.expression));n=h.structure;continue}if(c.kind==="undeclared"){if(l!=="reject"&&l!=="delete"&&l!=="ignore")A(mA(l));r.undeclared=l;continue}let u=el(l,t),d=c;if(c.kind==="required"){if(!Se(u))Dd(r,"required",{key:c.normalized,value:u},t);else Dd(r,"optional",u[1]==="="?{key:c.normalized,value:u[0],default:u[2]}:{key:c.normalized,value:u[0]},t);continue}if(Se(u)){if(u[1]==="?")A(Kw);if(u[1]==="=")A(Gw)}if(c.kind==="optional"){Dd(r,"optional",{key:c.normalized,value:u},t);continue}let f=t.$.parseOwnDefinitionFormat(d.normalized,t),p=Ha(f,u,t.$);if(p.index)r.index=de(r.index,p.index);if(p.required)r.required=de(r.required,p.required)}let o=t.$.node("structure",r);return t.$.parseSchema({domain:"object",structure:n?.merge(o)??o})},Dd=(e,t,n,r)=>{e[t]=de(e[t],r.$.node(t,n))},mA=(e)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${se(e)})`,gA="Spread operator may only be used as the first key in an object",_A=(e)=>typeof e==="symbol"?{kind:"required",normalized:e}:e[e.length-1]==="?"?e[e.length-2]===Dr?{kind:"required",normalized:`${e.slice(0,-2)}?`}:{kind:"optional",normalized:e.slice(0,-1)}:e[0]==="["&&e[e.length-1]==="]"?{kind:"index",normalized:e.slice(1,-1)}:e[0]===Dr&&e[1]==="["&&e[e.length-1]==="]"?{kind:"required",normalized:e.slice(1)}:e==="..."?{kind:"spread"}:e==="+"?{kind:"undeclared"}:{kind:"required",normalized:e==="\\..."?"...":e==="\\+"?"+":e},wA=(e)=>`Spread operand must resolve to an object literal type (was ${e})`;var zw=(e,t)=>CA(e)?Zw[e[0]](e,t):kA(e)?Yw[e[1]](e,t):null,yA=(e,t)=>t.$.parseOwnDefinitionFormat(e[1],t).keyof(),Nd=(e,t)=>{if(e[2]===void 0)return A(Cd(e[1],""));let n=t.$.parseOwnDefinitionFormat(e[0],t),r=t.$.parseOwnDefinitionFormat(e[2],t);if(e[1]==="|")return t.$.node("union",{branches:[n,r]});let s=e[1]==="&"?At(n,r,t.$):Ns(n,r,t.$);if(s instanceof q)return s.throw();return s},bA=(e,t)=>t.$.parseOwnDefinitionFormat(e[0],t).array(),vA=(e,t)=>{if(typeof e[2]!=="function")return A(Jw("=>",e[2]));return t.$.parseOwnDefinitionFormat(e[0],t).pipe(e[2])},Jw=(e,t)=>`${e===":"?"Narrow":"Morph"} expression requires a function following '${e}' (was ${typeof t})`,xA=(e,t)=>{if(typeof e[2]!=="function")return A(Jw(":",e[2]));return t.$.parseOwnDefinitionFormat(e[0],t).constrain("predicate",e[2])},SA=(e,t)=>t.$.parseOwnDefinitionFormat(e[0],t).configure(e[2],e[3]),Xw=(e)=>e,RA=Xw({"[]":bA,"?":()=>A(za)}),$A=Xw({"|":Nd,"&":Nd,":":xA,"=>":vA,"|>":Nd,"@":SA,"=":()=>A(Ja)}),Yw={...RA,...$A},kA=(e)=>Yw[e[1]]!==void 0,EA=(e)=>e,Zw=EA({keyof:yA,instanceof:(e,t)=>{if(typeof e[1]!=="function")return A(Vw(Rs(e[1])));let n=e.slice(1).map((r)=>typeof r==="function"?t.$.node("proto",{proto:r}):A(Vw(Rs(r))));return n.length===1?n[0]:t.$.node("union",{branches:n})},"===":(e,t)=>t.$.units(e.slice(1))}),CA=(e)=>Zw[e[0]]!==void 0,Vw=(e)=>`Expected a constructor following 'instanceof' operator (was ${e})`;var ty=(e,t)=>{let n=[{}],r=0;while(r<e.length){let s=!1;if(e[r]==="..."&&r<e.length-1)s=!0,r++;let o=el(e[r],t),[a,l,c]=!Se(o)?[o]:o;if(r++,s){if(!a.extends(N.intrinsic.Array))return A(IA(a.expression));n=n.flatMap((u)=>a.distribute((d)=>OA(Pa(u),d)))}else n=n.map((u)=>{if(l==="?")return ny(u,a);if(l==="=")return AA(u,a,c);return Fd(u,a)})}return t.$.parseSchema(n.map((s)=>vn(s)?{proto:Array,exactLength:0}:{proto:Array,sequence:s}))},Fd=(e,t)=>{if(e.defaultables||e.optionals)return A(e.variadic?md:PA);if(e.variadic)e.postfix=de(e.postfix,t);else e.prefix=de(e.prefix,t);return e},ny=(e,t)=>{if(e.variadic)return A(ry);return e.optionals=de(e.optionals,t),e},AA=(e,t,n)=>{if(e.variadic)return A(ry);if(e.optionals)return A(MA);return e.defaultables=de(e.defaultables,[[t,n]]),e},Qw=(e,t)=>{if(e.postfix)A(ey);if(e.variadic){if(!e.variadic.equals(t))A(ey)}else e.variadic=t.internal;return e},OA=(e,t)=>{let n=t.select({method:"find",kind:"sequence"});if(!n)return Qw(e,N.intrinsic.unknown);if(n.prefix)for(let r of n.prefix)Fd(e,r);if(n.optionals)for(let r of n.optionals)ny(e,r);if(n.variadic)Qw(e,n.variadic);if(n.postfix)for(let r of n.postfix)Fd(e,r);return e},IA=(e)=>`Spread element must be an array (was ${e})`,ey="A tuple may have at most one variadic element",PA="A required element may not follow an optional element",ry="An optional element may not follow a variadic element";var MA="A defaultable element may not follow an optional element without a default";var TA={},tl=(e,t)=>{if(typeof e==="string"){if(t.args&&Object.keys(t.args).some((r)=>e.includes(r)))return Pd(e,t);let n=TA[t.$.name]??={};return n[e]??=Pd(e,t)}return St(e,"object")?DA(e,t):A(Ld(Ke(e)))},DA=(e,t)=>{let n=Ss(e);switch(n){case void 0:if(X(e,"root"))return e;if("~standard"in e)return NA(e,t);return Ww(e,t);case"Array":return FA(e,t);case"RegExp":return t.$.node("intersection",{domain:"string",pattern:e},{prereduced:!0});case"Function":{let r=ir(e)?e():e;if(X(r,"root"))return r;return A(Ld("Function"))}default:return A(Ld(n??se(e)))}},NA=(e,t)=>t.$.intrinsic.unknown.pipe((n,r)=>{let s=e["~standard"].validate(n);if(!s.issues)return s.value;for(let{message:o,path:a}of s.issues)if(a)if(a.length)r.error({problem:qg(o),relativePath:a.map((l)=>typeof l==="object"?l.key:l)});else r.error({message:o});else r.error({message:o})}),FA=(e,t)=>zw(e,t)??ty(e,t),Ld=(e)=>`Type definitions must be strings or objects (was ${e})`;class jd extends kt{constructor(e){let t=Object.assign({errors:Et,hkt:at,$:e,raw:e.parse,module:e.constructor.module,scope:e.constructor.scope,declare:e.declare,define:e.define,match:e.match,generic:e.generic,schema:e.schema,keywords:e.ambient,unit:e.unit,enumerated:e.enumerated,instanceOf:e.instanceOf,valueOf:e.valueOf,or:e.or,and:e.and,merge:e.merge,pipe:e.pipe,fn:e.fn},e.ambientAttachments);super((...n)=>{if(n.length===1)return e.parse(n[0]);if(n.length===2&&typeof n[0]==="string"&&n[0][0]==="<"&&n[0][n[0].length-1]===">"){let r=n[0].slice(1,-1),s=e.parseGenericParams(r,{});return new cr(s,n[1],e,e,null)}return e.parse(n)},{attach:t})}}var Ti=N;class nl extends Ka{get ambientAttachments(){if(!Ti.typeAttachments)return;return this.cacheGetter("ambientAttachments",ie(Ti.typeAttachments,(e,t)=>[e,this.bindReference(t)]))}preparseOwnAliasEntry(e,t){let n=e.indexOf("<");if(n===-1){if(X(t,"module")||X(t,"generic"))return[e,t];let o=this.name==="ark"?e:e==="root"?this.name:`${this.name}.${e}`,a=this.resolvedConfig.keywords?.[o];if(a)t=[t,"@",a];return[e,t]}if(e[e.length-1]!==">")A("'>' must be the last character of a generic declaration in a scope");let r=e.slice(0,n),s=e.slice(n+1,-1);return[r,()=>{let o=this.parseGenericParams(s,{alias:r});return g_(o,t,this)}]}parseGenericParams(e,t){return Qa(new Is(e),[],this.createParseContext({...t,def:e,prefix:"generic"}))}normalizeRootScopeValue(e){if(ir(e)&&!X(e,"generic"))return e();return e}preparseOwnDefinitionFormat(e,t){return{...t,def:e,prefix:t.alias??"type"}}parseOwnDefinitionFormat(e,t){if(!(t.alias&&(t.alias in this.aliases))&&!t.args)t.args={this:t.id};let r=tl(e,t);if(Se(r)){if(r[1]==="=")return A(Ja);if(r[1]==="?")return A(za)}return r}unit=(e)=>this.units([e]);valueOf=(e)=>this.units(Mg(e));enumerated=(...e)=>this.units(e);instanceOf=(e)=>this.node("proto",{proto:e},{prereduced:!0});or=(...e)=>this.schema(e.map((t)=>this.parse(t)));and=(...e)=>e.reduce((t,n)=>t.and(this.parse(n)),this.intrinsic.unknown);merge=(...e)=>e.reduce((t,n)=>t.merge(this.parse(n)),this.intrinsic.object);pipe=(...e)=>this.intrinsic.unknown.pipe(...e);fn=new Md(this);match=new Td(this);declare=()=>({type:this.type});define(e){return e}type=new jd(this);static scope=(e,t={})=>new nl(e,t);static module=(e,t={})=>this.scope(e,t).export()}var Ud=Object.assign(nl.scope,{define:(e)=>e}),ue=nl;class iy extends at{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var LA=zt(["base",ee.object],["props",ee.object])((e)=>e.base.merge(e.props),iy),sy=ue.module({Key:ee.key,Merge:LA});class oy extends at{}var jA=zt("element")((e)=>{let t=e.element.exclude(ee.Array),n=t.array();return t.rawOr(n).pipe(rr).distribute((r)=>r.assertHasKind("morph").declareOut(n),ge)},oy),ay=ue.module({root:ee.Array,readonly:"root",index:ee.nonNegativeIntegerString,liftFrom:jA},{name:"Array"});var Bd=ge(["string",Nr.FileConstructor]),UA=Bd.rawOr(Bd.array()),ly=ge({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:UA}}),cy=ue.module({root:["instanceof",FormData],value:Bd,parsed:ly,parse:ge({in:FormData,morphs:(e)=>{let t={};for(let[n,r]of e)if(n in t){let s=t[n];if(typeof s==="string"||s instanceof Nr.FileConstructor)t[n]=[s,r];else s.push(r)}else t[n]=r;return t},declaredOut:ly})},{name:"FormData"});var uy=ue.module({Int8:["instanceof",Int8Array],Uint8:["instanceof",Uint8Array],Uint8Clamped:["instanceof",Uint8ClampedArray],Int16:["instanceof",Int16Array],Uint16:["instanceof",Uint16Array],Int32:["instanceof",Int32Array],Uint32:["instanceof",Uint32Array],Float32:["instanceof",Float32Array],Float64:["instanceof",Float64Array],BigInt64:["instanceof",BigInt64Array],BigUint64:["instanceof",BigUint64Array]},{name:"TypedArray"});var BA={Boolean:1,Number:1,String:1},dy=ue.module({...ie({...Cu,...Ou},(e,t)=>(e in BA)?[]:[e,["instanceof",t]]),Array:ay,TypedArray:uy,FormData:cy});var qA=ge({domain:{domain:"number",meta:"a number representing a Unix timestamp"},divisor:{rule:1,meta:"an integer representing a Unix timestamp"},min:{rule:-8640000000000000,meta:"a Unix timestamp after -8640000000000000"},max:{rule:8640000000000000,meta:"a Unix timestamp before 8640000000000000"},meta:"an integer representing a safe Unix timestamp"}),HA=ge({domain:"number",divisor:1}),rl=ue.module({root:ee.number,integer:HA,epoch:qA,safe:ge({domain:{domain:"number",numberAllowsNaN:!1},min:Number.MIN_SAFE_INTEGER,max:Number.MAX_SAFE_INTEGER}),NaN:["===",Number.NaN],Infinity:["===",Number.POSITIVE_INFINITY],NegativeInfinity:["===",Number.NEGATIVE_INFINITY]},{name:"number"});var Ce=(e,t,n)=>{let r={domain:"string",pattern:{rule:e.source,flags:e.flags,meta:t}};if(n)r.meta={format:n};return Ii("intersection",r)},fy=Ce(ks,"a well-formed integer string"),Ry=ue.module({root:fy,parse:ge({in:fy,morphs:(e,t)=>{let n=Number.parseInt(e);return Number.isSafeInteger(n)?n:t.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:ee.integer})},{name:"string.integer"}),KA=Ce(/^[\dA-Fa-f]+$/,"hex characters only"),GA=ue.module({root:Ce(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:Ce(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),py=Ce(/^[A-Z].*$/,"capitalized"),WA=ue.module({root:ge({in:"string",morphs:(e)=>e.charAt(0).toUpperCase()+e.slice(1),declaredOut:py}),preformatted:py},{name:"string.capitalize"}),VA=(e)=>{let t=e.replace(/[ -]+/g,""),n=0,r,s,o=!1;for(let a=t.length-1;a>=0;a--){if(r=t.substring(a,a+1),s=Number.parseInt(r,10),o)s*=2,n+=s>=10?s%10+1:s;else n+=s;o=!o}return!!(n%10===0?t:!1)},zA=/^(?:4\d{12}(?:\d{3,6})?|5[1-5]\d{14}|(222[1-9]|22[3-9]\d|2[3-6]\d{2}|27[01]\d|2720)\d{12}|6(?:011|5\d\d)\d{12,15}|3[47]\d{13}|3(?:0[0-5]|[68]\d)\d{11}|(?:2131|1800|35\d{3})\d{11}|6[27]\d{14}|^(81\d{14,17}))$/,JA=ge({domain:"string",pattern:{meta:"a credit card number",rule:zA.source},predicate:{meta:"a credit card number",predicate:VA}});var XA=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))(T((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([,.]\d+(?!:))?)?(\17[0-5]\d([,.]\d+)?)?([Zz]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;var YA=(e)=>!Number.isNaN(new Date(e).valueOf()),hy=ge({domain:"string",predicate:{meta:"a parsable date",predicate:YA}}).assertHasKind("intersection"),my=Ry.root.internal.narrow((e,t)=>{let n=Number.parseInt(e),r=rl.epoch(n);if(r instanceof Et)return t.errors.merge(r),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),ZA=ue.module({root:my,parse:ge({in:my,morphs:(e)=>new Date(e),declaredOut:ee.Date})},{name:"string.date.epoch"}),gy=Ce(XA,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),QA=ue.module({root:gy,parse:ge({in:gy,morphs:(e)=>new Date(e),declaredOut:ee.Date})},{name:"string.date.iso"}),eO=ue.module({root:hy,parse:ge({declaredIn:hy,in:"string",morphs:(e,t)=>{let n=new Date(e);if(Number.isNaN(n.valueOf()))return t.error("a parsable date");return n},declaredOut:ee.Date}),iso:QA,epoch:ZA},{name:"string.date"}),tO=Ce(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),_y="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",ur=`(${_y}[.]){3}${_y}`,nO=new RegExp(`^${ur}$`),je="(?:[0-9a-fA-F]{1,4})",rO=new RegExp(`^((?:${je}:){7}(?:${je}|:)|(?:${je}:){6}(?:${ur}|:${je}|:)|(?:${je}:){5}(?::${ur}|(:${je}){1,2}|:)|(?:${je}:){4}(?:(:${je}){0,1}:${ur}|(:${je}){1,3}|:)|(?:${je}:){3}(?:(:${je}){0,2}:${ur}|(:${je}){1,4}|:)|(?:${je}:){2}(?:(:${je}){0,3}:${ur}|(:${je}){1,5}|:)|(?:${je}:){1}(?:(:${je}){0,4}:${ur}|(:${je}){1,6}|:)|(?::((?::${je}){0,5}:${ur}|(?::${je}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),iO=ue.module({root:["v4 | v6","@","an IP address"],v4:Ce(nO,"an IPv4 address","ipv4"),v6:Ce(rO,"an IPv6 address","ipv6")},{name:"string.ip"}),Di="a JSON string",$y=(e)=>{if(!(e instanceof SyntaxError))throw e;return`must be ${Di} (${e})`},sO=ge({meta:Di,domain:"string",predicate:{meta:Di,predicate:(e,t)=>{try{return JSON.parse(e),!0}catch(n){return t.reject({code:"predicate",expected:Di,problem:$y(n)})}}}}),oO=(e,t)=>{if(e.length===0)return t.error({code:"predicate",expected:Di,actual:"empty"});try{return JSON.parse(e)}catch(n){return t.error({code:"predicate",expected:Di,problem:$y(n)})}},aO=ue.module({root:sO,parse:ge({meta:"safe JSON string parser",in:"string",morphs:oO,declaredOut:ee.jsonObject})},{name:"string.json"}),wy=Ce(/^[a-z]*$/,"only lowercase letters"),lO=ue.module({root:ge({in:"string",morphs:(e)=>e.toLowerCase(),declaredOut:wy}),preformatted:wy},{name:"string.lower"}),ky=["NFC","NFD","NFKC","NFKD"],Js=ie(ky,(e,t)=>[t,ge({domain:"string",predicate:(n)=>n.normalize(t)===n,meta:`${t}-normalized unicode`})]),il=ie(ky,(e,t)=>[t,ge({in:"string",morphs:(n)=>n.normalize(t),declaredOut:Js[t]})]),cO=ue.module({root:il.NFC,preformatted:Js.NFC},{name:"string.normalize.NFC"}),uO=ue.module({root:il.NFD,preformatted:Js.NFD},{name:"string.normalize.NFD"}),dO=ue.module({root:il.NFKC,preformatted:Js.NFKC},{name:"string.normalize.NFKC"}),fO=ue.module({root:il.NFKD,preformatted:Js.NFKD},{name:"string.normalize.NFKD"}),pO=ue.module({root:"NFC",NFC:cO,NFD:uO,NFKC:dO,NFKD:fO},{name:"string.normalize"}),yy=Ce(Ca,"a well-formed numeric string"),hO=ue.module({root:yy,parse:ge({in:yy,morphs:(e)=>Number.parseFloat(e),declaredOut:ee.number})},{name:"string.numeric"}),by="a regex pattern",mO=ge({domain:"string",predicate:{meta:by,predicate:(e,t)=>{try{return new RegExp(e),!0}catch(n){return t.reject({code:"predicate",expected:by,problem:String(n)})}}},meta:{format:"regex"}}),gO=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*))*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?$/,_O=Ce(gO,"a semantic version (see https://semver.org/)"),vy=Ce(/^\S.*\S$|^\S?$/,"trimmed"),wO=ue.module({root:ge({in:"string",morphs:(e)=>e.trim(),declaredOut:vy}),preformatted:vy},{name:"string.trim"}),xy=Ce(/^[A-Z]*$/,"only uppercase letters"),yO=ue.module({root:ge({in:"string",morphs:(e)=>e.toUpperCase(),declaredOut:xy}),preformatted:xy},{name:"string.upper"}),bO=(e)=>URL.canParse(e),Sy=ge({domain:"string",predicate:{meta:"a URL string",predicate:bO},meta:{format:"uri"}}),vO=ue.module({root:Sy,parse:ge({declaredIn:Sy,in:"string",morphs:(e,t)=>{try{return new URL(e)}catch{return t.error("a URL string")}},declaredOut:ge(URL)})},{name:"string.url"}),xO=ue.module({root:["versioned | nil | max","@",{description:"a UUID",format:"uuid"}],"#nil":"'00000000-0000-0000-0000-000000000000'","#max":"'ffffffff-ffff-ffff-ffff-ffffffffffff'","#versioned":/[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}/i,v1:Ce(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:Ce(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:Ce(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:Ce(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:Ce(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:Ce(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:Ce(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:Ce(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),Ey=ue.module({root:ee.string,alpha:Ce(/^[A-Za-z]*$/,"only letters"),alphanumeric:Ce(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:KA,base64:GA,capitalize:WA,creditCard:JA,date:eO,digits:Ce(/^\d*$/,"only digits 0-9"),email:tO,integer:Ry,ip:iO,json:aO,lower:lO,normalize:pO,numeric:hO,regex:mO,semver:_O,trim:wO,upper:yO,url:vO,uuid:xO},{name:"string"});var Cy=ue.module({bigint:ee.bigint,boolean:ee.boolean,false:ee.false,never:ee.never,null:ee.null,number:ee.number,object:ee.object,string:ee.string,symbol:ee.symbol,true:ee.true,unknown:ee.unknown,undefined:ee.undefined}),Ay=ue.module({root:ee.unknown,any:ee.unknown},{name:"unknown"}),SO=ue.module({root:ee.jsonObject,stringify:Ii("morph",{in:ee.jsonObject,morphs:(e)=>JSON.stringify(e),declaredOut:ee.string})},{name:"object.json"}),Oy=ue.module({root:ee.object,json:SO},{name:"object"});class Iy extends at{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var RO=zt(["K",ee.key],"V")((e)=>({domain:"object",index:{signature:e.K,value:e.V}}),Iy);class Py extends at{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var $O=zt(["T",ee.object],["K",ee.key])((e)=>e.T.pick(e.K),Py);class My extends at{description='omit a set of properties from an object like `Omit(User, "age")`'}var kO=zt(["T",ee.object],["K",ee.key])((e)=>e.T.omit(e.K),My);class Ty extends at{description="make all named properties of an object optional like `Partial(User)`"}var EO=zt(["T",ee.object])((e)=>e.T.partial(),Ty);class Dy extends at{description="make all named properties of an object required like `Required(User)`"}var CO=zt(["T",ee.object])((e)=>e.T.required(),Dy);class Ny extends at{description='exclude branches of a union like `Exclude("boolean", "true")`'}var AO=zt("T","U")((e)=>e.T.exclude(e.U),Ny);class Fy extends at{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var OO=zt("T","U")((e)=>e.T.extract(e.U),Fy),Ly=ue.module({Exclude:AO,Extract:OO,Omit:kO,Partial:EO,Pick:$O,Record:RO,Required:CO});var Ln=Ud({...Cy,...Ly,...dy,...sy,string:Ey,number:rl,object:Oy,unknown:Ay},{prereducedAliases:!0,name:"ark"}),We=Ln.export();Object.assign(Ti.ambient,We);Ti.typeAttachments={string:We.string.root,number:We.number.root,bigint:We.bigint,boolean:We.boolean,symbol:We.symbol,undefined:We.undefined,null:We.null,object:We.object.root,unknown:We.unknown.root,false:We.false,true:We.true,never:We.never,arrayIndex:We.Array.index,Key:We.Key,Record:We.Record,Array:We.Array.root,Date:We.Date};var Z=Object.assign(Ln.type,Ti.typeAttachments),{match:IO,fn:PO,generic:MO,schema:x2,define:TO,declare:DO}=Ln;var sl=Z("'running' | 'complete' | 'failed' | 'cancelled'"),ol=Z({kind:"'pr'",number:"number",url:"string",title:"string",author:"string",baseRef:"string",headRef:"string",state:"string",isDraft:"boolean"}).or({kind:"'range' | 'branch' | 'commit'",spec:"string"}).or({kind:"'staged' | 'worktree'","branch?":"string"}),Uy=Z("'additions' | 'deletions'"),NO=Z("'not-in-diff' | 'far-from-diff' | 'no-line' | 'deleted-file' | 'no-hunks'"),By=Z({file:"string",side:Uy,kind:"'line' | 'nearby' | 'file'",line:"number","endLine?":"number",cited:{line:"number","endLine?":"number"},"text?":"string","reason?":NO}),FO=Z("'added' | 'removed' | 'modified' | 'renamed' | 'copied'"),qy=Z("'product' | 'deploy' | 'tooling'"),LO=Z({path:"string","previousPath?":"string",status:FO,additions:"number",deletions:"number",isBinary:"boolean","blob?":"string",groupId:"string",classification:"'code' | 'docs' | 'skip'","surface?":qy}),jO=Z("'bug' | 'wrench' | 'path' | 'flask' | 'doc' | 'gear'"),Hd=Z({id:"string","parentId?":"string",title:"string","summary?":"string","icon?":jO,files:"string[]",findingIds:"string[]",stopIds:"string[]",critical:"boolean"}),UO=Z({id:"string",chapterId:"string",index:"number",title:"string","prose?":"string",importance:"'critical' | 'normal' | 'context'",locations:By.and({"label?":"string"}).array()}),Hy=Z("'blocker' | 'should-fix' | 'nice-to-have' | 'question'"),jy=Z({id:"string",file:"string",anchor:By,severity:Hy,category:"string",title:"string",explanation:"string",evidence:"string","impact?":"string",confidence:"'high' | 'medium' | 'low'","effort?":"'quick' | 'moderate' | 'involved'","suggestion?":"string","suggestedCode?":"string","crossFileRefs?":Z({file:"string","line?":"number"}).array(),"alsoAt?":Z({file:"string","line?":"number"}).array(),"repeatOf?":"number","carriedFrom?":"string","surface?":qy,"preexisting?":"boolean"}),Ky=Z({input:"number",output:"number",reasoning:"number",cacheRead:"number",cacheWrite:"number","firstStep?":{input:"number",cacheRead:"number",cacheWrite:"number"}}),BO=Z({unit:"string",part:"number",parts:"number",status:"'ok' | 'failed'",costUsd:"number",wallMs:"number","usage?":Ky}),qd=Z({costUsd:"number",wallMs:"number","usage?":Ky}),al=Z({root:"string","slug?":"string","remote?":"boolean"}),Xs=Z("'review' | 'diff'");function Gy(e){return e.meta.kind??"review"}var qO=Z({fp:"string",outcome:"'withdrawn' | 'upheld' | 'unjudged'","earlier?":"boolean","file?":"string","line?":"string","claim?":"string","note?":"string"}),HO=Z({open:"number",fixed:"number",withdrawn:"number",upheld:"number",fixedThisRound:"number",withdrawnThisRound:"number",new:"number"}),KO=Z({id:"string",acted:"boolean",control:"boolean"}),Wy=Z({schemaVersion:"1",id:"string",status:sl,createdAt:"string",repo:al,target:ol,base:"string",head:"string",intent:{"stated?":"string","inferred?":"string","alignment?":"'aligned' | 'partial' | 'misaligned'","matches?":"string[]","mismatches?":"string[]","unstated?":"string[]","missing?":"string[]"},overview:{"focus?":"string","changeType?":"string",startHere:Z({file:"string",why:"string"}).array()},files:LO.array(),groups:Hd.array(),stops:UO.array(),findings:jy.array(),overCapFindings:jy.array(),resolved:Z({id:"string","note?":"string","title?":"string","file?":"string"}).array(),"disputes?":qO.array(),"roundProgress?":HO,unreviewed:{overCap:"string[]",failed:"string[]","budget?":"string[]"},meta:{"model?":"string","effort?":"string","models?":{"review?":{model:"string","source?":"string"},"coordinator?":{model:"string","source?":"string"},"walkthrough?":{model:"string","source?":"string"},"intent?":{model:"string","source?":"string"}},"kind?":Xs,wallMs:"number",costUsd:"number",slices:BO.array(),"stages?":{"coordinator?":qd,"walkthrough?":qd,"intent?":qd},rejectedCount:"number",coreSource:"string","mergeMode?":"'coordinator' | 'nothing-to-merge' | 'deterministic-fallback'","budgetStopped?":"boolean","postMinSeverity?":Hy,"reviewScope?":"'full' | 'incremental'","reviewedFiles?":"number","scopeReason?":"string","promptVersion?":"string","instructionsHash?":"string","roundLimit?":{maxRounds:"number",round:"number"}},untrackedSkipped:"string[]","priorRunId?":"string","round?":"number","priorActedOn?":KO.array(),"error?":"string"}),Kd=Z("'open' | 'accepted' | 'dismissed'"),Gd=Z("'wrong' | 'not-worth-fixing' | 'already-handled' | 'duplicate' | 'other'"),ll=["wrong","not-worth-fixing","already-handled","duplicate","other"],GO=Z({reason:Gd,"note?":"string",at:"string"}),Vy=Z({reviewedFiles:Z.Record("string","string"),findingStatus:Z.Record("string",Kd),"findingNotes?":Z.Record("string",GO),comments:Z({id:"string",file:"string",side:Uy,line:"number","endLine?":"number",body:"string"}).array(),"submitted?":{at:"string","url?":"string"}}),U2=Z({id:"string",status:sl,createdAt:"string",target:ol,repo:al,"kind?":Xs,findingCounts:{blocker:"number","should-fix":"number","nice-to-have":"number",question:"number"},costUsd:"number","roundLimited?":"true","invalid?":"string"});function dr(e){if(e.kind==="pr")return`PR #${e.number} ${e.title}`;if("spec"in e)return`${e.kind} ${e.spec}`;return e.branch?`${e.kind} (${e.branch})`:e.kind}function Yd(e){let t=e.side==="deletions"?" [base]":"";if(e.kind==="file")return`${e.file} (file${e.reason?`: ${e.reason}`:""})`;let n=(r,s)=>s&&s!==r?`${r}-${s}`:`${r}`;if(e.kind==="nearby")return`${e.file}:${n(e.cited.line,e.cited.endLine)} \u2192 ${e.line} (nearby)${t}`;return`${e.file}:${n(e.line,e.endLine)} (line)${t}`}function VO(e){let t=[e.blocker&&`${e.blocker} blocker`,e["should-fix"]&&`${e["should-fix"]} should-fix`,e["nice-to-have"]&&`${e["nice-to-have"]} nice-to-have`,e.question&&`${e.question} question`].filter(Boolean);return t.length?t.join(", "):"no findings"}function Qy(e){if(e.length===0)return"No saved runs.";return e.map((t)=>[t.id,` ${(t.kind??"review").padEnd(6)} ${t.status.padEnd(8)} ${t.createdAt} ${dr(t.target)}`,t.kind==="diff"?` ${t.repo.slug??t.repo.root}${t.costUsd?` $${t.costUsd.toFixed(2)}`:""}`:` ${t.repo.slug??t.repo.root} ${VO(t.findingCounts)} $${t.costUsd.toFixed(2)}`].join(`
618
618
  `)).join(`
619
619
 
620
- `)}function oO(e,t){let n=t?.findingStatus[e.id];if(n==="accepted")return"accepted";if(n!=="dismissed")return;let r=t?.findingNotes?.[e.id]?.reason;return r?`dismissed: ${r}`:"dismissed"}function Cy(e,t){let n=[oO(e,t),e.preexisting&&"pre-existing",e.carriedFrom&&`open since ${e.carriedFrom}`].filter(Boolean);return n.length?` (${n.join(", ")})`:""}function Nd(e,t){return` [${e.severity}] ${e.title}${Cy(e,t)}
621
- ${Ld(e.anchor)} id ${e.id}`}function Oy(e,t){if(!e.resolved.length)return[];return["",`Fixed since the prior run (${e.resolved.length})`,...e.resolved.map((n)=>`${t}${n.title??n.id}${n.file?` ${n.file}`:""}${n.note?`
622
- ${t} ${n.note}`:""}`)]}function il(e){if(!e.round||e.round<2)return;let{reviewScope:t,reviewedFiles:n,scopeReason:r}=e.meta;if(t==="incremental"){let s=n??0;return s===0?`Round ${e.round}: no code changed since the last review`:`Round ${e.round}: only the ${s===1?"file":`${s} files`} changed since the last review ${s===1?"was":"were"} reviewed again`}return`Round ${e.round}: full review${r?` (${r})`:""}`}function Iy(e,t){let n=[];if(n.push(`${e.id} ${e.status}`),n.push(`${lr(e.target)} ${e.base.slice(0,12)}..${e.head.slice(0,12)}`),n.push(`${e.repo.slug??e.repo.root} ${e.createdAt}`),e.error)n.push(`error: ${e.error}`);if(e.priorRunId)n.push(`prior run: ${e.priorRunId}`);let r=il(e);if(r)n.push(r);if(e.overview.focus)n.push(`focus: ${e.overview.focus}`);if(e.intent.alignment)n.push(`intent: ${e.intent.alignment}`);let s=new Map(e.files.map((c)=>[c.path,c]));n.push(...My(e,t));let o=e.findings.filter((c)=>!s.has(c.file));if(o.length){n.push("",`Findings on files outside the diff (${o.length})`);for(let c of o)n.push(Nd(c,t))}if(e.overCapFindings.length){n.push("",`Over the posting cap (${e.overCapFindings.length})`);for(let c of e.overCapFindings)n.push(Nd(c,t))}if(n.push(...Oy(e," ")),e.stops.length){n.push("",`Walkthrough stops (${e.stops.length})`);for(let c of e.stops){n.push(` ${c.id} ${c.title}${c.importance==="normal"?"":` [${c.importance}]`}`);for(let u of c.locations)n.push(` ${Ld(u)}`)}}if(e.untrackedSkipped.length)n.push("",`Untracked files skipped: ${e.untrackedSkipped.join(", ")}`);if(e.unreviewed.failed.length)n.push("",`Failed slices: ${e.unreviewed.failed.join(", ")}`);if(e.unreviewed.budget?.length)n.push("",`Not reviewed (cost limit): ${e.unreviewed.budget.join(", ")}`);if(by(e)==="diff")return n.push("",`${e.files.length} files${Py(e)}, ${(e.meta.wallMs/1000).toFixed(1)}s`),n.join(`
623
- `);n.push("",`${e.findings.length} findings, ${e.files.length} files, $${e.meta.costUsd.toFixed(2)}, ${Math.round(e.meta.wallMs/1000)}s`,`anchors: ${ga(e)}`);let a=Ks(Hs(e));if(a)n.push(`tokens: ${a}`);let l=t?aO(e,t):void 0;if(l)n.push(`triage: ${l}`);return n.join(`
624
- `)}function aO(e,t){let n=new Set([...e.findings,...e.overCapFindings].map((c)=>c.id)),r=Object.entries(t.findingStatus).filter(([c])=>n.has(c)),s=r.filter(([,c])=>c==="accepted").length,o=r.filter(([,c])=>c==="dismissed").length,a=e.files.filter((c)=>(c.path in t.reviewedFiles)).length,l=[s&&`${s} accepted`,o&&`${o} dismissed`,a&&`${a} of ${e.files.length} files reviewed`].filter(Boolean);return l.length?l.join(", "):void 0}function Py(e){return e.meta.costUsd?`, $${e.meta.costUsd.toFixed(2)}`:""}function My(e,t){let n=[],r=new Map(e.findings.map((o)=>[o.id,o])),s=new Map(e.files.map((o)=>[o.path,o]));for(let o of e.groups){let a=!e.groups.some((c)=>c.parentId===o.id);if(!a||!o.parentId&&o.files.length===0){let c=a&&o.stopIds.length?` (stops ${o.stopIds.join(", ")}; files sit in other groups)`:"";n.push("",`${o.critical?"! ":""}${o.title}${c}`);continue}let l=o.parentId?" ":"";n.push(`${o.parentId?"":`
625
- `}${l}${o.critical?"! ":""}${o.title}`);for(let c of o.files){let u=s.get(c),d=u?` ${u.status} +${u.additions} -${u.deletions}${u.isBinary?" binary":""}`:"";n.push(`${l} ${c}${d}`);for(let f of o.findingIds){let p=r.get(f);if(p?.file===c)n.push(Nd(p,t))}}}return n}function Ty(e){let t=[];if(t.push(`${lr(e.target)} ${e.base.slice(0,12)}..${e.head.slice(0,12)}`),e.intent.inferred)t.push("",`What it does: ${Dd(e.intent.inferred,400)}`);if(t.push(...My(e)),e.untrackedSkipped.length)t.push("",`Untracked files skipped: ${e.untrackedSkipped.join(", ")}`);let n=e.files.reduce((s,o)=>s+o.additions,0),r=e.files.reduce((s,o)=>s+o.deletions,0);return t.push("",`${e.files.length} files, +${n} -${r}${Py(e)}`),t.join(`
626
- `)}var Ey=["blocker","should-fix","question","nice-to-have"];function Dd(e,t=200){let n=e.trim().split(/(?<=[.!?])\s+/)[0]??"";return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function Fy(e){let t=[];t.push(`${lr(e.target)} ${e.base.slice(0,12)}..${e.head.slice(0,12)}`);let n=il(e);if(n)t.push(n);if(e.unreviewed.failed.length)t.push(`Incomplete: ${e.unreviewed.failed.length} slice(s) failed.`);let r=e.unreviewed.budget??[];if(r.length)t.push(`Incomplete: cost limit reached, ${r.length} file(s) not reviewed.`);let{intent:s}=e;if(s.alignment){t.push("",`Intent: ${s.alignment}`);for(let a of s.mismatches??[])t.push(` - ${a}`)}else if(s.inferred)t.push("",`What it does: ${Dd(s.inferred,400)}`);if(e.overview.focus)t.push("",`Focus: ${e.overview.focus}`);let o=[...e.findings].sort((a,l)=>Number(a.preexisting??!1)-Number(l.preexisting??!1)||Ey.indexOf(a.severity)-Ey.indexOf(l.severity));t.push("",o.length?`Findings (${o.length})`:"No findings.");for(let a of o){t.push(` [${a.severity}] ${a.title}${Cy(a)}`,` ${Ld(a.anchor)} id ${a.id}`);let l=Dd(a.impact??a.explanation);if(l&&l!==a.title)t.push(` ${l}`)}if(e.overCapFindings.length)t.push(` \u2026and ${e.overCapFindings.length} more over the cap (runs show)`);if(t.push(...Oy(e," ")),e.overview.startHere.length)t.push("","Start here"),e.overview.startHere.forEach((a,l)=>t.push(` ${l+1}. ${a.file} \u2014 ${a.why}`));return t.join(`
627
- `)}var Ft=["blocker","should-fix","nice-to-have","question"],lO={ts:"ts",mts:"ts",cts:"ts",tsx:"tsx",js:"js",mjs:"js",cjs:"js",jsx:"jsx",json:"json",css:"css",scss:"scss",html:"html",md:"md",py:"python",rs:"rust",go:"go",rb:"ruby",java:"java",kt:"kotlin",swift:"swift",c:"c",h:"c",cc:"cpp",cpp:"cpp",cxx:"cpp",hpp:"cpp",hh:"cpp",sh:"sh",bash:"sh",yml:"yaml",yaml:"yaml",toml:"toml",sql:"sql"};function cO(e){let t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return n>0?lO[t.slice(n+1).toLowerCase()]??"":""}function jd(e,t){return t&&t!==e?`${e}-${t}`:`${e}`}function Ny(e){let t=e.side==="deletions"?" (old)":"";if(e.kind==="file")return e.cited.line>0?`${e.file}:${jd(e.cited.line,e.cited.endLine)}`:e.file;if(e.kind==="nearby")return`${e.file}:${jd(e.cited.line,e.cited.endLine)}${t}`;return`${e.file}:${jd(e.line,e.endLine)}${t}`}function Dy(e,t){let n=t?.findingStatus[e.id];if(n==="accepted")return" (accepted)";if(n!=="dismissed")return"";let r=t?.findingNotes?.[e.id]?.reason;return r?` (dismissed: ${r})`:" (dismissed)"}function uO(e,t,n={}){let r=[`### [${e.severity}] ${e.title}${Dy(e,t)}`,`${_n(Ny(e.anchor))} \xB7 id ${_n(e.id)}`],s=t?.findingStatus[e.id]==="dismissed"?t.findingNotes?.[e.id]?.note?.trim():void 0;if(s)r.push(`> Dismissed: ${s}`);let o=[!n.github&&e.carriedFrom&&`Open since run ${e.carriedFrom}.`,e.repeatOf!==void 0&&`Repeats PR comment #${e.repeatOf}.`,e.preexisting&&"Pre-existing: not introduced by this change."].filter(Boolean);if(o.length)r.push(`_${o.join(" ")}_`);if(r.push(e.explanation.trim()),e.impact?.trim())r.push(`**Impact:** ${e.impact.trim()}`);if(e.alsoAt?.length)r.push(`**Also at:** ${e.alsoAt.map((a)=>_n(a.line?`${a.file}:${a.line}`:a.file)).join(", ")}`);if(e.evidence.trim())r.push(`**Evidence:** ${e.evidence.trim()}`);if(e.suggestedCode){if(e.suggestion?.trim())r.push(`**Suggestion:** ${e.suggestion.trim()}`);r.push(di(e.suggestedCode,cO(e.file)))}else if(e.suggestion?.trim())r.push(`**Suggestion:** ${e.suggestion.trim()}`);return r.join(`
620
+ `)}function zO(e,t){let n=t?.findingStatus[e.id];if(n==="accepted")return"accepted";if(n!=="dismissed")return;let r=t?.findingNotes?.[e.id]?.reason;return r?`dismissed: ${r}`:"dismissed"}function eb(e,t){let n=[zO(e,t),e.preexisting&&"pre-existing",e.carriedFrom&&`open since ${e.carriedFrom}`].filter(Boolean);return n.length?` (${n.join(", ")})`:""}function Jd(e,t){return` [${e.severity}] ${e.title}${eb(e,t)}
621
+ ${Yd(e.anchor)} id ${e.id}`}function tb(e,t){if(!e.resolved.length)return[];return["",`Fixed since the prior run (${e.resolved.length})`,...e.resolved.map((n)=>`${t}${n.title??n.id}${n.file?` ${n.file}`:""}${n.note?`
622
+ ${t} ${n.note}`:""}`)]}function fl(e){if(!e.round||e.round<2)return;let{reviewScope:t,reviewedFiles:n,scopeReason:r}=e.meta;if(t==="incremental"){let s=n??0;return s===0?`Round ${e.round}: no code changed since the last review`:`Round ${e.round}: only the ${s===1?"file":`${s} files`} changed since the last review ${s===1?"was":"were"} reviewed again`}return`Round ${e.round}: full review${r?` (${r})`:""}`}function nb(e,t){let n=[];if(n.push(`${e.id} ${e.status}`),n.push(`${dr(e.target)} ${e.base.slice(0,12)}..${e.head.slice(0,12)}`),n.push(`${e.repo.slug??e.repo.root} ${e.createdAt}`),e.error)n.push(`error: ${e.error}`);if(e.priorRunId)n.push(`prior run: ${e.priorRunId}`);let r=fl(e);if(r)n.push(r);if(e.overview.focus)n.push(`focus: ${e.overview.focus}`);if(e.intent.alignment)n.push(`intent: ${e.intent.alignment}`);let s=new Map(e.files.map((c)=>[c.path,c]));n.push(...ib(e,t));let o=e.findings.filter((c)=>!s.has(c.file));if(o.length){n.push("",`Findings on files outside the diff (${o.length})`);for(let c of o)n.push(Jd(c,t))}if(e.overCapFindings.length){n.push("",`Over the posting cap (${e.overCapFindings.length})`);for(let c of e.overCapFindings)n.push(Jd(c,t))}if(n.push(...tb(e," ")),e.stops.length){n.push("",`Walkthrough stops (${e.stops.length})`);for(let c of e.stops){n.push(` ${c.id} ${c.title}${c.importance==="normal"?"":` [${c.importance}]`}`);for(let u of c.locations)n.push(` ${Yd(u)}`)}}if(e.untrackedSkipped.length)n.push("",`Untracked files skipped: ${e.untrackedSkipped.join(", ")}`);if(e.unreviewed.failed.length)n.push("",`Failed slices: ${e.unreviewed.failed.join(", ")}`);if(e.unreviewed.budget?.length)n.push("",`Not reviewed (cost limit): ${e.unreviewed.budget.join(", ")}`);if(Gy(e)==="diff")return n.push("",`${e.files.length} files${rb(e)}, ${(e.meta.wallMs/1000).toFixed(1)}s`),n.join(`
623
+ `);n.push("",`${e.findings.length} findings, ${e.files.length} files, $${e.meta.costUsd.toFixed(2)}, ${Math.round(e.meta.wallMs/1000)}s`,`anchors: ${Ra(e)}`);let a=Zs(Ys(e));if(a)n.push(`tokens: ${a}`);let l=t?JO(e,t):void 0;if(l)n.push(`triage: ${l}`);return n.join(`
624
+ `)}function JO(e,t){let n=new Set([...e.findings,...e.overCapFindings].map((c)=>c.id)),r=Object.entries(t.findingStatus).filter(([c])=>n.has(c)),s=r.filter(([,c])=>c==="accepted").length,o=r.filter(([,c])=>c==="dismissed").length,a=e.files.filter((c)=>(c.path in t.reviewedFiles)).length,l=[s&&`${s} accepted`,o&&`${o} dismissed`,a&&`${a} of ${e.files.length} files reviewed`].filter(Boolean);return l.length?l.join(", "):void 0}function rb(e){return e.meta.costUsd?`, $${e.meta.costUsd.toFixed(2)}`:""}function ib(e,t){let n=[],r=new Map(e.findings.map((o)=>[o.id,o])),s=new Map(e.files.map((o)=>[o.path,o]));for(let o of e.groups){let a=!e.groups.some((c)=>c.parentId===o.id);if(!a||!o.parentId&&o.files.length===0){let c=a&&o.stopIds.length?` (stops ${o.stopIds.join(", ")}; files sit in other groups)`:"";n.push("",`${o.critical?"! ":""}${o.title}${c}`);continue}let l=o.parentId?" ":"";n.push(`${o.parentId?"":`
625
+ `}${l}${o.critical?"! ":""}${o.title}`);for(let c of o.files){let u=s.get(c),d=u?` ${u.status} +${u.additions} -${u.deletions}${u.isBinary?" binary":""}`:"";n.push(`${l} ${c}${d}`);for(let f of o.findingIds){let p=r.get(f);if(p?.file===c)n.push(Jd(p,t))}}}return n}function sb(e){let t=[];if(t.push(`${dr(e.target)} ${e.base.slice(0,12)}..${e.head.slice(0,12)}`),e.intent.inferred)t.push("",`What it does: ${Xd(e.intent.inferred,400)}`);if(t.push(...ib(e)),e.untrackedSkipped.length)t.push("",`Untracked files skipped: ${e.untrackedSkipped.join(", ")}`);let n=e.files.reduce((s,o)=>s+o.additions,0),r=e.files.reduce((s,o)=>s+o.deletions,0);return t.push("",`${e.files.length} files, +${n} -${r}${rb(e)}`),t.join(`
626
+ `)}var Zy=["blocker","should-fix","question","nice-to-have"];function Xd(e,t=200){let n=e.trim().split(/(?<=[.!?])\s+/)[0]??"";return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function ob(e){let t=[];t.push(`${dr(e.target)} ${e.base.slice(0,12)}..${e.head.slice(0,12)}`);let n=fl(e);if(n)t.push(n);if(e.unreviewed.failed.length)t.push(`Incomplete: ${e.unreviewed.failed.length} slice(s) failed.`);let r=e.unreviewed.budget??[];if(r.length)t.push(`Incomplete: cost limit reached, ${r.length} file(s) not reviewed.`);let{intent:s}=e;if(s.alignment){t.push("",`Intent: ${s.alignment}`);for(let a of s.mismatches??[])t.push(` - ${a}`)}else if(s.inferred)t.push("",`What it does: ${Xd(s.inferred,400)}`);if(e.overview.focus)t.push("",`Focus: ${e.overview.focus}`);let o=[...e.findings].sort((a,l)=>Number(a.preexisting??!1)-Number(l.preexisting??!1)||Zy.indexOf(a.severity)-Zy.indexOf(l.severity));t.push("",o.length?`Findings (${o.length})`:"No findings.");for(let a of o){t.push(` [${a.severity}] ${a.title}${eb(a)}`,` ${Yd(a.anchor)} id ${a.id}`);let l=Xd(a.impact??a.explanation);if(l&&l!==a.title)t.push(` ${l}`)}if(e.overCapFindings.length)t.push(` \u2026and ${e.overCapFindings.length} more over the cap (runs show)`);if(t.push(...tb(e," ")),e.overview.startHere.length)t.push("","Start here"),e.overview.startHere.forEach((a,l)=>t.push(` ${l+1}. ${a.file} \u2014 ${a.why}`));return t.join(`
627
+ `)}var Nt=["blocker","should-fix","nice-to-have","question"],XO={ts:"ts",mts:"ts",cts:"ts",tsx:"tsx",js:"js",mjs:"js",cjs:"js",jsx:"jsx",json:"json",css:"css",scss:"scss",html:"html",md:"md",py:"python",rs:"rust",go:"go",rb:"ruby",java:"java",kt:"kotlin",swift:"swift",c:"c",h:"c",cc:"cpp",cpp:"cpp",cxx:"cpp",hpp:"cpp",hh:"cpp",sh:"sh",bash:"sh",yml:"yaml",yaml:"yaml",toml:"toml",sql:"sql"};function YO(e){let t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return n>0?XO[t.slice(n+1).toLowerCase()]??"":""}function Zd(e,t){return t&&t!==e?`${e}-${t}`:`${e}`}function ab(e){let t=e.side==="deletions"?" (old)":"";if(e.kind==="file")return e.cited.line>0?`${e.file}:${Zd(e.cited.line,e.cited.endLine)}`:e.file;if(e.kind==="nearby")return`${e.file}:${Zd(e.cited.line,e.cited.endLine)}${t}`;return`${e.file}:${Zd(e.line,e.endLine)}${t}`}function lb(e,t){let n=t?.findingStatus[e.id];if(n==="accepted")return" (accepted)";if(n!=="dismissed")return"";let r=t?.findingNotes?.[e.id]?.reason;return r?` (dismissed: ${r})`:" (dismissed)"}function ZO(e,t,n={}){let r=[`### [${e.severity}] ${e.title}${lb(e,t)}`,`${yn(ab(e.anchor))} \xB7 id ${yn(e.id)}`],s=t?.findingStatus[e.id]==="dismissed"?t.findingNotes?.[e.id]?.note?.trim():void 0;if(s)r.push(`> Dismissed: ${s}`);let o=[!n.github&&e.carriedFrom&&`Open since run ${e.carriedFrom}.`,e.repeatOf!==void 0&&`Repeats PR comment #${e.repeatOf}.`,e.preexisting&&"Pre-existing: not introduced by this change."].filter(Boolean);if(o.length)r.push(`_${o.join(" ")}_`);if(r.push(e.explanation.trim()),e.impact?.trim())r.push(`**Impact:** ${e.impact.trim()}`);if(e.alsoAt?.length)r.push(`**Also at:** ${e.alsoAt.map((a)=>yn(a.line?`${a.file}:${a.line}`:a.file)).join(", ")}`);if(e.evidence.trim())r.push(`**Evidence:** ${e.evidence.trim()}`);if(e.suggestedCode){if(e.suggestion?.trim())r.push(`**Suggestion:** ${e.suggestion.trim()}`);r.push(gi(e.suggestedCode,YO(e.file)))}else if(e.suggestion?.trim())r.push(`**Suggestion:** ${e.suggestion.trim()}`);return r.join(`
628
628
 
629
- `)}function Ud(e){return[...e].sort((t,n)=>Ft.indexOf(t.severity)-Ft.indexOf(n.severity)||t.file.localeCompare(n.file)||t.anchor.line-n.anchor.line)}function dO(e,t,n){let r=(t.length?` ${t.length} pre-existing.`:"")+(n?` ${n} more over the posting cap.`:"");if(e.length===0)return`${t.length?"No issues found in this change.":"No issues found."}${r}`;let s=Ft.map((a)=>[a,e.filter((l)=>l.severity===a).length]).filter(([,a])=>a>0).map(([a,l])=>`${l} ${a}`),o=e.length;return`${o} finding${o===1?"":"s"}: ${s.join(", ")}.${r}`}function fO(e,t){return[`### [${e.severity}] ${e.title}${Dy(e,t)}`,`${_n(Ny(e.anchor))} \xB7 id ${_n(e.id)}`].join(`
629
+ `)}function Qd(e){return[...e].sort((t,n)=>Nt.indexOf(t.severity)-Nt.indexOf(n.severity)||t.file.localeCompare(n.file)||t.anchor.line-n.anchor.line)}function QO(e,t,n){let r=(t.length?` ${t.length} pre-existing.`:"")+(n?` ${n} more over the posting cap.`:"");if(e.length===0)return`${t.length?"No issues found in this change.":"No issues found."}${r}`;let s=Nt.map((a)=>[a,e.filter((l)=>l.severity===a).length]).filter(([,a])=>a>0).map(([a,l])=>`${l} ${a}`),o=e.length;return`${o} finding${o===1?"":"s"}: ${s.join(", ")}.${r}`}function eI(e,t){return[`### [${e.severity}] ${e.title}${lb(e,t)}`,`${yn(ab(e.anchor))} \xB7 id ${yn(e.id)}`].join(`
630
630
 
631
- `)}function Ws(e,t={}){let n=il(e),r=[`# Review findings: ${lr(e.target)}`,`Base ${_n(e.base.slice(0,12))}, head ${_n(e.head.slice(0,12))}${n?`. ${n}.`:""}`],{state:s}=t,o=(P)=>t.includeDismissed||s?.findingStatus[P.id]!=="dismissed",a=e.findings.filter(o),l=e.overCapFindings.filter(o),c=t.includeOverCap?l:[],u=a.filter((P)=>!P.preexisting),d=a.filter((P)=>P.preexisting),f=e.findings.length-a.length+e.overCapFindings.length-l.length;r.push(dO(u,d,l.length)+(f?` ${f} dismissed finding${f===1?"":"s"} left out.`:""));let p=[Ud(u),Ud(d),Ud(c)],h=Math.min(t.shorten?.count??0,p.flat().length),g=new Set(h>0?p.flat().slice(-h):[]);if(h>0&&t.shorten)r.push(t.shorten.note);let w=(P)=>g.has(P)?fO(P,s):uO(P,s,t),[b=[],x=[],R=[]]=p;for(let P of b)r.push(w(P));if(x.length){r.push("## Pre-existing (not introduced by this change)");for(let P of x)r.push(w(P))}if(R.length){r.push(`## Over the posting cap (${R.length})`);for(let P of R)r.push(w(P))}return`${r.join(`
631
+ `)}function Qs(e,t={}){let n=fl(e),r=[`# Review findings: ${dr(e.target)}`,`Base ${yn(e.base.slice(0,12))}, head ${yn(e.head.slice(0,12))}${n?`. ${n}.`:""}`],{state:s}=t,o=(P)=>t.includeDismissed||s?.findingStatus[P.id]!=="dismissed",a=e.findings.filter(o),l=e.overCapFindings.filter(o),c=t.includeOverCap?l:[],u=a.filter((P)=>!P.preexisting),d=a.filter((P)=>P.preexisting),f=e.findings.length-a.length+e.overCapFindings.length-l.length;r.push(QO(u,d,l.length)+(f?` ${f} dismissed finding${f===1?"":"s"} left out.`:""));let p=[Qd(u),Qd(d),Qd(c)],h=Math.min(t.shorten?.count??0,p.flat().length),g=new Set(h>0?p.flat().slice(-h):[]);if(h>0&&t.shorten)r.push(t.shorten.note);let w=(P)=>g.has(P)?eI(P,s):ZO(P,s,t),[b=[],x=[],S=[]]=p;for(let P of b)r.push(w(P));if(x.length){r.push("## Pre-existing (not introduced by this change)");for(let P of x)r.push(w(P))}if(S.length){r.push(`## Over the posting cap (${S.length})`);for(let P of S)r.push(w(P))}return`${r.join(`
632
632
 
633
633
  `)}
634
- `}import Ii from"path";bt();ls();import{spawn as pO}from"child_process";import{posix as hO}from"path";function Gs(e,t,n,r){return new Promise((s,o)=>{let a=pO("git",["-C",e,...t],{stdio:[n===void 0?"ignore":"pipe","pipe","pipe"],...r?{env:{...process.env,...r}}:{}}),l=[],c=[];if(a.stdout?.on("data",(u)=>l.push(u)),a.stderr?.on("data",(u)=>c.push(u)),a.on("error",o),a.on("close",(u)=>{if(u===0)s(Buffer.concat(l));else o(Error(`git ${t.join(" ")} exited ${u}
635
- ${Buffer.concat(c).toString("utf8").slice(0,2000)}`))}),n!==void 0)a.stdin?.on("error",()=>{}),a.stdin?.end(n)})}async function mO(e,t){let n=(await Gs(e,["ls-tree","-r","-z",t])).toString("utf8"),r=new Map;for(let s of n.split("\x00")){let o=s.indexOf("\t");if(o<0)continue;let[,a,l]=s.slice(0,o).split(" ");if(a==="blob"&&l)r.set(s.slice(o+1),l)}return r}async function gO(e,t){if(t.length===0)return;let n=(await Gs(e,["config","--get","extensions.partialClone"]).catch(()=>Buffer.alloc(0))).toString("utf8").trim();if(!n)return;let s=(await Gs(e,["cat-file","--batch-check"],`${t.join(`
634
+ `}import Ni from"path";bt();_s();import{spawn as tI}from"child_process";import{posix as nI}from"path";function eo(e,t,n,r){return new Promise((s,o)=>{let a=tI("git",["-C",e,...t],{stdio:[n===void 0?"ignore":"pipe","pipe","pipe"],...r?{env:{...process.env,...r}}:{}}),l=[],c=[];if(a.stdout?.on("data",(u)=>l.push(u)),a.stderr?.on("data",(u)=>c.push(u)),a.on("error",o),a.on("close",(u)=>{if(u===0)s(Buffer.concat(l));else o(Error(`git ${t.join(" ")} exited ${u}
635
+ ${Buffer.concat(c).toString("utf8").slice(0,2000)}`))}),n!==void 0)a.stdin?.on("error",()=>{}),a.stdin?.end(n)})}async function rI(e,t){let n=(await eo(e,["ls-tree","-r","-z",t])).toString("utf8"),r=new Map;for(let s of n.split("\x00")){let o=s.indexOf("\t");if(o<0)continue;let[,a,l]=s.slice(0,o).split(" ");if(a==="blob"&&l)r.set(s.slice(o+1),l)}return r}async function iI(e,t){if(t.length===0)return;let n=(await eo(e,["config","--get","extensions.partialClone"]).catch(()=>Buffer.alloc(0))).toString("utf8").trim();if(!n)return;let s=(await eo(e,["cat-file","--batch-check"],`${t.join(`
636
636
  `)}
637
637
  `,{GIT_NO_LAZY_FETCH:"1"})).toString("utf8").split(`
638
- `).flatMap((o)=>o.endsWith(" missing")?[o.slice(0,o.indexOf(" "))]:[]);if(s.length===0)return;await Gs(e,["-c","fetch.negotiationAlgorithm=noop","fetch","-q","--no-tags","--no-write-fetch-head","--recurse-submodules=no","--filter=blob:none","--stdin",n],`${s.join(`
638
+ `).flatMap((o)=>o.endsWith(" missing")?[o.slice(0,o.indexOf(" "))]:[]);if(s.length===0)return;await eo(e,["-c","fetch.negotiationAlgorithm=noop","fetch","-q","--no-tags","--no-write-fetch-head","--recurse-submodules=no","--filter=blob:none","--stdin",n],`${s.join(`
639
639
  `)}
640
- `)}async function _O(e,t,n){let r=n.filter((l)=>!l.includes(`
641
- `)),s=new Map;if(r.length===0)return s;let o=await Gs(e,["cat-file","--batch"],r.map((l)=>`${t}:${l}
642
- `).join("")),a=0;for(let l of r){let c=o.indexOf(10,a);if(c<0)break;let u=o.subarray(a,c).toString("utf8");if(a=c+1,u.endsWith(" missing")||u.endsWith(" ambiguous"))continue;let d=Number(u.split(" ")[2]);if(!Number.isFinite(d))break;if(u.split(" ")[1]==="blob")s.set(l,o.subarray(a,a+d).toString("utf8"));a+=d+1}return s}var wO=/^(?:(?:tsconfig|jsconfig).*\.json|package\.json)$/;async function Ly(e,t,n){let r=await mO(e,t),s=new Set(r.keys()),o=[...s].filter((c)=>wO.test(hO.basename(c))),a=[...new Set([...n.filter((c)=>s.has(c)),...o])];await gO(e,a.map((c)=>r.get(c)??"").filter(Boolean));let l=await _O(e,t,a);return{paths:s,read:(c)=>l.get(c)}}aa();async function jy(e){if(e.config)Ho(e.config);let{signal:t}=e;if(t?.aborted)throw new Bt;let n=()=>void li();t?.addEventListener("abort",n,{once:!0}),Zr({subject:e.repo,repoName:e.target.slug??Ii.basename(e.repo),...t?{signal:t}:{}});try{return await yO(e)}finally{t?.removeEventListener("abort",n),await li(),Ko(),la()}}async function yO(e){let t=(ne)=>e.onProgress?.(ne),n=()=>{if(e.signal?.aborted)throw new Bt},r=Date.now(),{base:s,head:o,pr:a,slug:l}=e.target,c=`${s}..${o}`;t({type:"stage",stage:"grouping"});let u=(await pt(["diff","--name-only",c])).trim().split(`
643
- `).filter(Boolean),d={skip:[],docs:[],code:[]};for(let ne of u)d[ai(ne)].push(ne);let f=(ne,ce=null,Be=0)=>({record:ce,units:ne,byClass:d,costUsd:Be,wallMs:Date.now()-r});if(!d.code.length)return t({type:"units",units:[],byClass:d}),f([]);let{wholeDiff:p,diffstat:h,diffU0:g,fileTokens:w,facts:b,links:x,grouping:R}=await ta({base:s,head:o,files:d.code,source:(ne)=>Ly(e.repo,o,ne)}),P=si(R.groups,(ne)=>w.get(ne)??0),M=R.groups.map((ne,ce)=>({id:ne.id,title:P[ce]??ne.id,files:ne.files,priority:ce+1}));if(t({type:"units",units:M,byClass:d}),n(),!e.walkthrough)return f(M);t({type:"stage",stage:"walkthrough"}),await Sn(wt),await Sn(Ii.join(ye,"prompts")),await Sn(Ii.join(ye,"logs")),await De(Ii.join(ye,".gitignore"),`*
644
- `);let k=await Qo(l,a,s,o,e.intent),E=`${e.tag}-walk`,D=Ii.join(wt,`${E}.json`);await Yt(D);let{shown:L,sketched:O}=ia(M,w,Zi),U=O.length?_r(await pt(["diff",c,"--",...L]),s):p,I=na(g,b),j=ha({diffstat:h,diff:U,sketches:O.map((ne)=>ra(I.get(ne)??{file:ne,added:0,removed:0,defines:[],touches:[]})),crossLinks:oa(M,x),intent:k,unitSummary:M.map((ne)=>{let ce=sa(ne.files,x);return`**${ne.title}** (${ne.id})
645
- ${ne.files.map((Be)=>` - ${Be}`).join(`
640
+ `)}async function sI(e,t,n){let r=n.filter((l)=>!l.includes(`
641
+ `)),s=new Map;if(r.length===0)return s;let o=await eo(e,["cat-file","--batch"],r.map((l)=>`${t}:${l}
642
+ `).join("")),a=0;for(let l of r){let c=o.indexOf(10,a);if(c<0)break;let u=o.subarray(a,c).toString("utf8");if(a=c+1,u.endsWith(" missing")||u.endsWith(" ambiguous"))continue;let d=Number(u.split(" ")[2]);if(!Number.isFinite(d))break;if(u.split(" ")[1]==="blob")s.set(l,o.subarray(a,a+d).toString("utf8"));a+=d+1}return s}var oI=/^(?:(?:tsconfig|jsconfig).*\.json|package\.json)$/;async function cb(e,t,n){let r=await rI(e,t),s=new Set(r.keys()),o=[...s].filter((c)=>oI.test(nI.basename(c))),a=[...new Set([...n.filter((c)=>s.has(c)),...o])];await iI(e,a.map((c)=>r.get(c)??"").filter(Boolean));let l=await sI(e,t,a);return{paths:s,read:(c)=>l.get(c)}}ma();async function ub(e){if(e.config)ta(e.config);let{signal:t}=e;if(t?.aborted)throw new qt;let n=()=>void pi();t?.addEventListener("abort",n,{once:!0}),ri({subject:e.repo,repoName:e.target.slug??Ni.basename(e.repo),...t?{signal:t}:{}});try{return await aI(e)}finally{t?.removeEventListener("abort",n),await pi(),na(),ga()}}async function aI(e){let t=(ne)=>e.onProgress?.(ne),n=()=>{if(e.signal?.aborted)throw new qt},r=Date.now(),{base:s,head:o,pr:a,slug:l}=e.target,c=`${s}..${o}`;t({type:"stage",stage:"grouping"});let u=(await pt(["diff","--name-only",c])).trim().split(`
643
+ `).filter(Boolean),d={skip:[],docs:[],code:[]};for(let ne of u)d[fi(ne)].push(ne);let f=(ne,ce=null,qe=0)=>({record:ce,units:ne,byClass:d,costUsd:qe,wallMs:Date.now()-r});if(!d.code.length)return t({type:"units",units:[],byClass:d}),f([]);let{wholeDiff:p,diffstat:h,diffU0:g,fileTokens:w,facts:b,links:x,grouping:S}=await ca({base:s,head:o,files:d.code,source:(ne)=>cb(e.repo,o,ne)}),P=ui(S.groups,(ne)=>w.get(ne)??0),M=S.groups.map((ne,ce)=>({id:ne.id,title:P[ce]??ne.id,files:ne.files,priority:ce+1}));if(t({type:"units",units:M,byClass:d}),n(),!e.walkthrough)return f(M);t({type:"stage",stage:"walkthrough"}),await Cn(wt),await Cn(Ni.join(ye,"prompts")),await Cn(Ni.join(ye,"logs")),await Fe(Ni.join(ye,".gitignore"),`*
644
+ `);let k=await aa(l,a,s,o,e.intent),E=`${e.tag}-walk`,F=Ni.join(wt,`${E}.json`);await Qt(F);let{shown:L,sketched:O}=fa(M,w,os),U=O.length?vr(await pt(["diff",c,"--",...L]),s):p,I=ua(g,b),j=xa({diffstat:h,diff:U,sketches:O.map((ne)=>da(I.get(ne)??{file:ne,added:0,removed:0,defines:[],touches:[]})),crossLinks:ha(M,x),intent:k,unitSummary:M.map((ne)=>{let ce=pa(ne.files,x);return`**${ne.title}** (${ne.id})
645
+ ${ne.files.map((qe)=>` - ${qe}`).join(`
646
646
  `)}`+(ce.length?`
647
647
  Links: ${ce.join("; ")}`:"")}).join(`
648
648
 
649
- `),docsFiles:d.docs,registry:"",outFile:D});await De(Ii.join(ye,"prompts",`${E}.txt`),j);let H=await On(j,{budget:Yi,outFile:D,tag:E,model:kn,effort:Zt,tools:"none",answerKeys:["chapters"]}).catch((ne)=>(n(),t({type:"log",message:` walkthrough failed: ${ne instanceof Error?ne.message:String(ne)}`}),{costUsd:0,payload:null}));n(),t({type:"cost",totalUsd:H.costUsd});let ve=H.payload??void 0;if(!ve)t({type:"log",message:" walkthrough returned no guide"});let Se=Date.now()-r;return f(M,ve?{walkthrough:ve,wallMs:Se,totalCostUsd:H.costUsd}:null,H.costUsd)}function qy(e,t){let n=new Map(t.files.map((r)=>[r.path,r]));return{...e,groups:t.groups,files:e.files.map((r)=>{let s=n.get(r.path);return s?{...r,groupId:s.groupId,classification:s.classification}:r})}}function Hy(e){return{type:"groups",groups:e.groups,files:e.files.map((t)=>({path:t.path,groupId:t.groupId,classification:t.classification}))}}import vO from"os";import je from"path";import{appendFile as vG,mkdir as xO,readdir as Vs,readFile as Kd,rename as RO,rm as Hd,writeFile as Wd}from"fs/promises";class Pi extends Error{constructor(e){super(e);this.name="StateOpError"}}function Mi(){return{reviewedFiles:{},findingStatus:{},comments:[]}}function Wy(e){let t=typeof e==="object"&&e!==null&&Array.isArray(e.reviewedFiles);return xy(t?{...e,reviewedFiles:{}}:e)}var bO=/^0+$/;function Ky(e,t,n){let r=t.filter((s)=>!n.has(s));if(r.length>0)throw new Pi(`unknown ${e}: ${r.join(", ")}`)}function Gy(e,t,n){if(t.op==="reviewed"){let l=new Map(n.files.map((u)=>[u.path,u]));Ky(t.paths.length===1?"file":"files",t.paths,new Set(l.keys()));let c={...e.reviewedFiles};for(let u of t.paths){let d=l.get(u);if(!t.value)delete c[u];else c[u]=d?.status==="removed"||!d?.blob||bO.test(d.blob)?"":d.blob}return{...e,reviewedFiles:c}}if(t.ids.length===0)throw new Pi("no finding ids given");let r=new Set([...n.findings,...n.overCapFindings].map((l)=>l.id));if(Ky(t.ids.length===1?"finding":"findings",t.ids,r),t.status==="dismissed"&&!t.reason)throw new Pi("dismissing a finding needs a reason");let s={...e.findingStatus},o={...e.findingNotes};for(let l of t.ids){if(delete o[l],t.status==="open")delete s[l];else s[l]=t.status;if(t.status==="dismissed"&&t.reason)o[l]={reason:t.reason,...t.note?{note:t.note}:{},at:t.at}}let a={...e,findingStatus:s,findingNotes:o};if(Object.keys(o).length===0)delete a.findingNotes;return a}function an(){return je.join(process.env.XDG_DATA_HOME||je.join(vO.homedir(),".local","share"),"diffloupe")}function Js(){return je.join(an(),"runs")}function cr(){return je.join(an(),"artifacts")}function Gd(e){let[t="",n=""]=e.toLowerCase().split("/");return je.join(an(),"repos",t,`${n}.git`)}function Ve(e){if(!e||e.includes("/")||e.includes("\\")||e.startsWith("."))throw Error(`invalid run id: ${e}`);return je.join(Js(),e)}async function Vy(e){let t=Ve(e);return await xO(je.join(t,"raw"),{recursive:!0}),await Wd(je.join(t,"state.json"),`${JSON.stringify(Mi(),null,2)}
650
- `),t}async function Ti(e){await Wd(je.join(Ve(e.id),"run.json"),`${JSON.stringify(e,null,2)}
651
- `)}class Ln extends Error{id;summary;raw;constructor(e,t,n){super(`run ${e} has an invalid run.json: ${t}`);this.id=e;this.summary=t;this.raw=n;this.name="InvalidRunError"}}async function gt(e){let t=JSON.parse(await Kd(je.join(Ve(e),"run.json"),"utf8")),n=vy(t);if(n instanceof Z.errors)throw new Ln(e,n.summary,t);return n}async function Vd(e){let t=await gt(e);if(ky(t))return t;try{return $y(t,JSON.parse(await Kd(je.join(Ve(e),"raw","record.json"),"utf8")))}catch{return t}}class zs extends Error{id;summary;constructor(e,t){super(`run ${e} has an invalid state.json: ${t}`);this.id=e;this.summary=t;this.name="InvalidStateError"}}async function zy(e){let t;try{t=await Kd(je.join(Ve(e),"state.json"),"utf8")}catch(s){if(s.code==="ENOENT")return Mi();throw s}let n;try{n=JSON.parse(t)}catch(s){throw new zs(e,s instanceof Error?s.message:String(s))}let r=Wy(n);if(r instanceof Z.errors)throw new zs(e,r.summary);return r}async function Fr(e){try{return await zy(e)}catch{return Mi()}}async function SO(e,t){let n=je.join(Ve(e),"state.json"),r=`${n}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;try{await Wd(r,`${JSON.stringify(t,null,2)}
652
- `),await RO(r,n)}catch(s){throw await Hd(r,{force:!0}),s}}var sl=new Map;async function zd(e,t){let r=(sl.get(e)??Promise.resolve()).catch(()=>{return}).then(async()=>{let[s,o]=await Promise.all([gt(e),zy(e)]),a=Gy(o,t,s);return await SO(e,a),a});sl.set(e,r);try{return await r}finally{if(sl.get(e)===r)sl.delete(e)}}function Jy(e,t,n,r={}){return zd(e,{op:"finding",ids:t,status:n,reason:r.reason,note:r.note,at:new Date().toISOString()})}function $O(e){let t={blocker:0,"should-fix":0,"nice-to-have":0,question:0};for(let n of e.findings??[])t[n.severity]=(t[n.severity]??0)+1;return t}function qd(e,t,n){let r=e(t);return r instanceof Z.errors?n:r}function Xy(e){let t=typeof e.raw==="object"&&e.raw!==null?e.raw:{},n=typeof t.meta==="object"&&t.meta!==null?t.meta:{};return{id:e.id,status:qd(Ya,t.status,"failed"),createdAt:typeof t.createdAt==="string"?t.createdAt:"",target:qd(Za,t.target,{kind:"worktree"}),repo:qd(Qa,t.repo,{root:""}),findingCounts:{blocker:0,"should-fix":0,"nice-to-have":0,question:0},costUsd:typeof n.costUsd==="number"?n.costUsd:0,...n.kind==="diff"?{kind:"diff"}:{},invalid:e.summary}}async function zt(){let e;try{e=await Vs(Js())}catch{return[]}let t=[];for(let n of e)try{let r=await gt(n);t.push({id:r.id,status:r.status,createdAt:r.createdAt,target:r.target,repo:r.repo,findingCounts:$O(r),costUsd:r.meta?.costUsd??0,...r.meta?.kind?{kind:r.meta.kind}:{},...r.meta?.roundLimit?{roundLimited:!0}:{}})}catch(r){if(r instanceof Ln)t.push(Xy(r))}return t.sort((n,r)=>r.createdAt.localeCompare(n.createdAt))}function ol(e,t){if(t.kind==="pr")return`pr:${e.slug??e.root}#${t.number}`;if("spec"in t)return`${t.kind}:${e.root}:${t.spec}`;return`local:${e.root}:${t.branch??""}`}async function Yy(e,t,n){let r=ol(e,t);return(await zt()).find((o)=>o.status==="complete"&&o.kind!=="diff"&&!o.roundLimited&&o.createdAt<n&&ol(o.repo,o.target)===r)?.id}function Xs(){return je.join(an(),"scratch")}function al(){let e=je.join(Xs(),"oc","shared");return[je.join(e,"data"),je.join(e,"state")]}function kO(){let e=cr();return[...["logs","prompts","raw","reviews","runs"].map((t)=>je.join(e,t)),Xs(),...al()]}async function EO(e,t){try{if((await re("git",["-C",e,"show-ref","--verify","--quiet",t],{allowFail:!0})).code!==0)return!1;return await oe("git",["-C",e,"update-ref","-d",t]),!0}catch{return!1}}async function Ys(e){let t=[],n=Ve(e),r;try{r=(await gt(e)).repo.root}catch(s){if(s instanceof Ln)r=Xy(s).repo.root||void 0}for(let s of kO()){let o;try{o=await Vs(s)}catch{continue}for(let a of o)if(a.startsWith(`${e}-`)||a.startsWith(`${e}.`)){let l=je.join(s,a);await Hd(l,{recursive:!0,force:!0}),t.push(l)}}if(r){for(let s of[`refs/diffloupe/${e}`,`refs/diffloupe/${e}-base`])if(await EO(r,s))t.push(s)}try{await Vs(n),await Hd(n,{recursive:!0,force:!0}),t.push(n)}catch{}return t}function Zy(e,t){let n=(t.now??Date.now())-t.olderThanMs;return e.toSorted((r,s)=>s.createdAt.localeCompare(r.createdAt)).slice(Math.max(0,t.keep)).filter((r)=>r.status!=="running"&&Date.parse(r.createdAt)<n)}async function Qy(){let e=[];try{e=await Vs(Js())}catch{}let t=(await zt()).filter((o)=>o.status==="running").map((o)=>o.id),n=(o,a)=>a.some((l)=>o.startsWith(`${l}-`)||o.startsWith(`${l}.`)),r=[],s=async(o,a)=>{let l;try{l=await Vs(o)}catch{return}for(let c of l)if(!a(c))r.push(je.join(o,c))};await s(Xs(),(o)=>!o.endsWith(".json")||n(o,e));for(let o of al())await s(o,(a)=>n(a,t));return r}import{readFile as HO}from"fs/promises";bt();import{copyFile as AO,mkdir as CO,rm as OO,stat as Jd,utimes as IO}from"fs/promises";import PO from"os";import Fi from"path";import{randomBytes as MO}from"crypto";function Yd(e,t){if(!t)return e;let n=e;for(let r=2;t(n);r++)n=`${e}-${r}`;return n}var TO=1048576;class _e extends Error{name="TargetError"}function Rn(e){let t=(e??"worktree").trim();if(t===""||t==="worktree")return{kind:"worktree"};if(t==="staged")return{kind:"staged"};if(t==="HEAD")return{kind:"commit",rev:"HEAD"};let n=t.match(/^(?:#|pr:)(\d+)$/);if(n?.[1])return{kind:"pr",pr:Number(n[1])};let r=t.match(/^([\w.-]+\/[\w.-]+)#(\d+)$/);if(r?.[1]&&r[2])return{kind:"pr",pr:Number(r[2]),repo:r[1]};if(/github\.com\//.test(t)){let l=t.match(/^(?:https?:\/\/)?(?:www\.)?github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)(?:[/?#].*)?$/);if(!l?.[1]||!l[2]||!l[3])throw new _e(`not a GitHub pull request URL: ${t}`);return{kind:"pr",pr:Number(l[3]),repo:`${l[1]}/${l[2]}`}}let s=t.indexOf(":"),o=s>0?t.slice(0,s):"",a=s>0?t.slice(s+1):"";if(o==="branch"&&a)return{kind:"branch",branch:a};if(o==="commit"&&a)return{kind:"commit",rev:a};if(o==="range"){let l=eb(a);if(l)return l}if(!o&&!t.startsWith("-")&&!/\s/.test(t))if(t.includes("..")){let l=eb(t);if(l)return l}else return{kind:"commit",rev:t};throw new _e(`unrecognized target "${t}". Use worktree, staged, a commit (<sha>, HEAD~2, commit:<rev>), a range (<a>..<b>, <a>...<b>, range:<a>..<b>), branch:<name>, #<pr>, pr:<n>, owner/repo#<n>, or a pull request URL.`)}function eb(e){let t=e.includes("..."),n=e.split(t?"...":"..");if(n.length!==2)return;let[r="",s=""]=n;if(!r&&!s)return;if(r.includes("..")||s.includes(".."))return;return{kind:"range",from:r||"HEAD",to:s||"HEAD",mergeBase:t}}function Zd(e,t,n,r=new Date){let s=(c)=>String(c).padStart(2,"0"),o=`${r.getFullYear()}${s(r.getMonth()+1)}${s(r.getDate())}${s(r.getHours())}${s(r.getMinutes())}${s(r.getSeconds())}`,a=t.kind==="pr"?`pr${t.pr}`:t.kind;return`${e.replace(/[^\w.-]+/g,"_")}-${a}-${n.slice(0,12)}-${o}`}async function nb(e,t,n={}){let r=Rn(t),s=(M,k={})=>oe("git",["-C",e,...M],k),o=async(M)=>{let k=await re("git",["-C",e,"rev-parse","--verify","--quiet",`${M}^{commit}`],{allowFail:!0});if(k.code!==0){let E=/^\d+$/.test(M)?` (for pull request ${M}, use #${M})`:"";throw new _e(`unknown revision "${M}": not a commit in ${e}${E}`)}return k.stdout.trim()},a=async(M,k)=>(await s(["merge-base",M,k])).trim();if((await re("git",["-C",e,"rev-parse","--show-toplevel"],{allowFail:!0})).code!==0)throw new _e(`${e} is not inside a git repository`+(r.kind==="pr"&&r.repo?". diffloupe diff can show this pull request without a clone.":""));let c=await oi(e),u,d,f,p=[],h=!1,g;if(r.kind==="commit"&&jO(t)&&await UO(e,r.rev)){if(g=await tb(e).catch(()=>{return}),g){let M=await o(r.rev);if(await a(g,M)!==M)r={kind:"branch",branch:r.rev}}}switch(r.kind){case"pr":{if(r.repo&&!c.startsWith("local/")&&r.repo.toLowerCase()!==c.toLowerCase())throw new _e(`pull request is in ${r.repo} but ${e} is a clone of ${c}. Run from a clone of ${r.repo} or pass -C. diffloupe diff can show it without a clone.`);if(f=await ab(e,r.pr,r.repo??(c.startsWith("local/")?void 0:c)),d=f.headRefOid,await Xd(e,d,[`refs/pull/${r.pr}/head`]),n.head)d=await LO(e,r.pr,d,n.head);await Xd(e,f.baseRefOid,[f.baseRefName]),u=await a(f.baseRefOid,d);break}case"branch":{d=await o(r.branch),u=await a(g??await tb(e),d);break}case"range":{let M=await o(r.from);d=await o(r.to),u=r.mergeBase?await a(M,d):M;break}case"commit":{d=await o(r.rev);let M=await re("git",["-C",e,"rev-parse","--verify","--quiet",`${d}^`],{allowFail:!0});if(M.code!==0)throw new _e(`${r.rev} is a root commit; use range: instead`);u=M.stdout.trim();break}case"staged":case"worktree":{let M=await o("HEAD"),k=r.kind==="staged"?await BO(e,M):await qO(e,M);d=k.commit,p=k.skipped,u=n.base?await a(await o(n.base),M):M,h=!0;break}}let w=c.split("/").pop()??Fi.basename(e),b=Yd(Zd(w,r,d,n.now),n.isTaken);if(h)await s(["update-ref",`refs/diffloupe/${b}`,d]);let x=await Qd(e,u,d),R=h?void 0:Number((await s(["rev-list","--count",`${u}..${d}`])).trim()),P={base:u,head:d,slug:c,...r.kind==="pr"?{pr:String(r.pr)}:{}};return{spec:r,target:P,tag:b,changes:x,...R!==void 0?{commits:R}:{},skippedUntracked:p,...f?{pullRequest:f}:{}}}async function rb(e,t,n,r,s={}){let o=await Promise.all([n,r].map((f)=>ll(e,f))),a=[n,r].filter((f,p)=>!o[p]);if(a.length)throw new _e(`commit ${a[0]} is no longer in ${e}`);let l=await oi(e),c=l.split("/").pop()??Fi.basename(e),u=Yd(Zd(c,t,r,s.now),s.isTaken);if(t.kind==="staged"||t.kind==="worktree")await oe("git",["-C",e,"update-ref",`refs/diffloupe/${u}`,r]);let d={base:n,head:r,slug:l,...t.kind==="pr"?{pr:String(t.pr)}:{}};return{spec:t,target:d,tag:u,changes:await Qd(e,n,r),skippedUntracked:[]}}var FO=/^(?!\.{1,2}$)[\w.-]+$/;function NO(e){let t=e.split("/");return t.length===2&&t.every((n)=>FO.test(n))}async function ib(e,t){if(t.kind!=="pr"||!t.repo)return!1;if((await re("git",["-C",e,"rev-parse","--show-toplevel"],{allowFail:!0})).code!==0)return!0;let r=await oi(e);return!r.startsWith("local/")&&r.toLowerCase()!==t.repo.toLowerCase()}async function sb(e,t,n=`https://github.com/${t}.git`){if(!NO(t))throw new _e(`not a GitHub repository: ${t}`);let r=(...o)=>oe("git",["-C",e,...o]);if(await Jd(Fi.join(e,"HEAD")).catch(()=>null))return;await CO(e,{recursive:!0}),await r("init","-q","--bare"),await r("remote","add","origin",n),await r("config","core.repositoryformatversion","1"),await r("config","extensions.partialClone","origin"),await r("config","remote.origin.promisor","true"),await r("config","remote.origin.partialclonefilter","blob:none"),await r("config","gc.auto","0"),await r("config","credential.helper",""),await r("config","--add","credential.helper","!gh auth git-credential")}async function ob(e,t,n={}){let r=await ab(e,t.pr,t.repo),s=r.headRefOid,o=await re("gh",["api",`repos/${t.repo}/compare/${r.baseRefOid}...${s}`,"--jq",".merge_base_commit.sha"],{cwd:e,allowFail:!0}),a=o.code===0&&o.stdout.trim()?o.stdout.trim():r.baseRefOid;await DO(e,[a,s],[`refs/pull/${t.pr}/head`]);let l=t.repo.split("/").pop()??t.repo,c=Yd(Zd(l,t,s,n.now),n.isTaken);return await oe("git",["-C",e,"update-ref",`refs/diffloupe/${c}`,s]),await oe("git",["-C",e,"update-ref",`refs/diffloupe/${c}-base`,a]),{spec:t,target:{base:a,head:s,slug:t.repo,pr:String(t.pr)},tag:c,changes:await Qd(e,a,s),skippedUntracked:[],pullRequest:r}}async function DO(e,t,n){let r=async()=>{let l=await Promise.all(t.map((c)=>ll(e,c)));return t.filter((c,u)=>!l[u])},s=(l)=>re("git",["-C",e,"fetch","-q","--depth=1","--filter=blob:none","--no-tags","origin",...l],{allowFail:!0}),o=await r();if(o.length===0)return;let a=await s(o);o=await r();for(let l of n){if(o.length===0)return;await s([l]),o=await r()}if(o.length)throw new _e(`could not fetch ${o.map((l)=>l.slice(0,12)).join(", ")} from GitHub: ${a.stderr.trim()||"not found"}`)}async function ab(e,t,n){let s=["pr","view",String(t),"--json","number,title,body,author,url,state,isDraft,baseRefName,headRefName,baseRefOid,headRefOid",...n?["--repo",n]:[]],o=await re("gh",s,{cwd:e,allowFail:!0});if(o.code!==0)throw new _e(`gh pr view ${t} failed: ${o.stderr.trim()||`exit ${o.code}`}`);return JSON.parse(o.stdout)}async function ll(e,t){return(await re("git",["-C",e,"cat-file","-e",`${t}^{commit}`],{allowFail:!0,env:{...process.env,GIT_NO_LAZY_FETCH:"1"}})).code===0}async function Xd(e,t,n){if(await ll(e,t))return;for(let r of n)if(await re("git",["-C",e,"fetch","-q","origin",r],{allowFail:!0}),await ll(e,t))return;throw new _e(`commit ${t} is not in this clone and could not be fetched from origin`)}async function LO(e,t,n,r){if(!/^[0-9a-f]{40}$/i.test(r))throw new _e(`--head must be a full 40-character commit SHA, not "${r}"`);let s=r.toLowerCase();if(s===n)return n;if(await Xd(e,s,[`refs/pull/${t}/head`,s]),(await re("git",["-C",e,"merge-base","--is-ancestor",s,n],{allowFail:!0})).code!==0)throw new _e(`--head ${s} is not in the history of pull request #${t} (head ${n.slice(0,12)})`);return s}function jO(e){return!(e??"").trim().startsWith("commit:")}async function UO(e,t){return(await Promise.all([`refs/heads/${t}`,`refs/remotes/${t}`].map((r)=>re("git",["-C",e,"show-ref","--verify","--quiet",r],{allowFail:!0})))).some((r)=>r.code===0)}async function tb(e){let t=await re("gh",["repo","view","--json","defaultBranchRef","-q",".defaultBranchRef.name"],{cwd:e,allowFail:!0}).catch(()=>null),n=[],r=t?.code===0?t.stdout.trim():"";if(r)n.push(`origin/${r}`,r);let s=await re("git",["-C",e,"symbolic-ref","--short","refs/remotes/origin/HEAD"],{allowFail:!0});if(s.code===0&&s.stdout.trim())n.push(s.stdout.trim());n.push("origin/main","main","origin/master","master");for(let o of n)if((await re("git",["-C",e,"rev-parse","--verify","--quiet",`${o}^{commit}`],{allowFail:!0})).code===0)return o;throw new _e("could not determine the default branch; use range:<base>..<branch> instead")}async function lb(e,t,n,r,s){let o=(await oe("git",["-C",e,"rev-parse",`${n}^{tree}`])).trim();if(t===o)throw new _e("no changes to review");return(await oe("git",["-C",e,"commit-tree",t,"-p",n,"-m",r],s?{env:s}:{})).trim()}async function BO(e,t){let n=(await oe("git",["-C",e,"write-tree"])).trim();return{commit:await lb(e,n,t,"diffloupe: staged changes"),skipped:[]}}async function qO(e,t){let n=(await oe("git",["-C",e,"rev-parse","--show-toplevel"])).trim(),r=Fi.resolve(n,(await oe("git",["-C",n,"rev-parse","--git-path","index"])).trim()),s=Fi.join(PO.tmpdir(),`diffloupe-index-${process.pid}-${MO(4).toString("hex")}`);try{await AO(r,s).then(async()=>{let{mtimeMs:d}=await Jd(r),f=Math.floor(d/1000);await IO(s,f,f)},async()=>{await oe("git",["-C",n,"read-tree",t],{env:{...process.env,GIT_INDEX_FILE:s}})});let o={...process.env,GIT_INDEX_FILE:s},a=(await oe("git",["-C",n,"ls-files","--others","--exclude-standard","-z"])).split("\x00").filter(Boolean),l=[];for(let d of a){let f=await Jd(Fi.join(n,d)).catch(()=>null);if(f&&f.isFile()&&f.size>TO)l.push(d)}let c=l.map((d)=>`:(exclude,literal)${d}`);await oe("git",["-C",n,"add","-A","--",".",...c],{env:o});let u=(await oe("git",["-C",n,"write-tree"],{env:o})).trim();return{commit:await lb(n,u,t,"diffloupe: working tree",o),skipped:l}}finally{await OO(s,{force:!0})}}async function Qd(e,t,n){let r=await oe("git",["-C",e,"diff","--numstat","--no-renames",t,n]),s={files:0,insertions:0,deletions:0};for(let o of r.split(`
653
- `)){if(!o.trim())continue;let[a,l]=o.split("\t");s.files++,s.insertions+=Number(a)||0,s.deletions+=Number(l)||0}return s}var KO=Z({"+":"reject","$schema?":"string","provider?":"string","models?":{"+":"reject","review?":"string","coordinator?":"string","walkthrough?":"string","intent?":"string"},"effort?":"string","surfaces?":{"+":"reject","deploy?":"string[]","tooling?":"string[]"},"extraExcludes?":"string[]","instructions?":"string | string[]","post?":{"+":"reject","minSeverity?":"'blocker' | 'should-fix' | 'nice-to-have' | 'question'","questions?":"'keep' | 'drop'"}});function WO(e,t){let n=KO(e);if(n instanceof Z.errors)throw new _e(`invalid settings in ${t}: ${n.summary}`);for(let r of[...n.surfaces?.deploy??[],...n.surfaces?.tooling??[]])try{new RegExp(r)}catch(s){throw new _e(`invalid surface pattern in ${t}: ${s instanceof Error?s.message:String(s)}`)}return n}async function cl(e){let t;try{t=await HO(e,"utf8")}catch(r){throw new _e(`cannot read settings file ${e}: ${r instanceof Error?r.message:String(r)}`)}let n;try{n=JSON.parse(t)}catch(r){throw new _e(`settings file ${e} is not valid JSON: ${r instanceof Error?r.message:String(r)}`)}return WO(n,e)}function cb(e){let t={};return t.surfaces={deploy:e.surfaces?.deploy??Lo.deploy,tooling:e.surfaces?.tooling??Lo.tooling},t.extraExcludes=e.extraExcludes??[],t.postMinSeverity=e.post?.minSeverity??null,t.dropQuestions=e.post?.questions==="drop",t}function ub(e){let{instructions:t}=e;return(Array.isArray(t)?t.join(`
654
- `):t??"").trim()||void 0}var db={anthropic:["ANTHROPIC_API_KEY"],openai:["OPENAI_API_KEY"],openrouter:["OPENROUTER_API_KEY"],google:["GOOGLE_GENERATIVE_AI_API_KEY","GEMINI_API_KEY"],groq:["GROQ_API_KEY"],mistral:["MISTRAL_API_KEY"],xai:["XAI_API_KEY"],deepseek:["DEEPSEEK_API_KEY"],cerebras:["CEREBRAS_API_KEY"],togetherai:["TOGETHER_AI_API_KEY"],"fireworks-ai":["FIREWORKS_API_KEY"],neuralwatt:["NEURALWATT_API_KEY"],opencode:["OPENCODE_API_KEY"]},fb=new Set(["amazon-bedrock","google-vertex","google-vertex-anthropic","ollama","lmstudio","vllm"]);function Zs(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function pb(e,t){let n=t?.[e],r=Zs(n)&&Array.isArray(n.env)?n.env.filter((s)=>typeof s==="string"):[];return[...new Set([...r,...db[e]??[]])]}function GO(e,t){let n=t?.[e];if(!Zs(n))return!1;for(let r of[n.settings,n.options])if(Zs(r)&&typeof r.apiKey==="string"&&r.apiKey)return!0;return!1}function hb(e){for(let t of e.providers.keys()){if(fb.has(t))continue;if(pb(t,e.userProviders).some((n)=>e.env[n]))continue;if(e.apiKeys?.[t])continue;return!0}return!1}function VO(e,t,n){let r=t.map((o)=>Io[o]).join(", "),s=n[0]?`set ${n[0]}, `:"";return`No credential for provider \`${e}\` (used by ${r}). Run \`opencode auth login ${e}\`, ${s}or add apiKeys.${e} to ~/.config/diffloupe/config.json.`}function mb(e){let t={childEnv:{},imports:[],coverage:[],warnings:[],errors:[]};for(let[n,r]of e.providers){let s=(f,p)=>t.coverage.push({provider:n,stages:r,source:f,detail:p}),o=pb(n,e.userProviders),a=o.find((f)=>e.env[f]);if(a){s("env",a);continue}let l=e.apiKeys?.[n];if(l){let f=o[0];if(f)t.childEnv[f]=l;else t.imports.push({id:`cred_diffloupe_${n.replace(/[^\w-]/g,"_")}`,integrationID:n,label:"API key",active:!0,value:{type:"key",key:l}});s("config",`apiKeys.${n}`);continue}let c=(e.saved??[]).filter((f)=>f.integrationID===n),u=c.filter((f)=>f.value?.type==="key"&&typeof f.value.key==="string");if(u.length){let f=u.find((p)=>p.active)??u[0];if(f)t.imports.push({...f,active:!0});s("opencode","opencode auth login");continue}let d=c.length>0;if(d)t.warnings.push(`OpenCode has a ${n} login that is not an API key; DiffLoupe does not copy those. Set ${o[0]??"an API key"} or add apiKeys.${n} to ~/.config/diffloupe/config.json.`);if(GO(n,e.userProviders)){s("providers",`providers.${n} in the OpenCode config`);continue}if(fb.has(n)){s("ambient","credentials from the machine");continue}if(s("none",""),db[n]||d)t.errors.push(VO(n,r,o));else t.warnings.push(`No credential found for provider \`${n}\`; assuming OpenCode can reach it without one. If the review fails to authenticate, add apiKeys.${n} to ~/.config/diffloupe/config.json.`)}return t}async function gb(e=process.env){try{let t=await re("opencode",["auth","export"],{env:e,allowFail:!0,timeoutMs:20000});if(t.code!==0)return;let n=JSON.parse(t.stdout);if(!Array.isArray(n))return;return n.filter((r)=>Zs(r)&&typeof r.id==="string"&&typeof r.integrationID==="string"&&Zs(r.value))}catch{return}}function _b(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}async function wb(e=1e4){try{let t=await re("opencode",["api","GET","/api/model"],{allowFail:!0,timeoutMs:e});if(t.code!==0)return;let n=JSON.parse(t.stdout),r=_b(n)&&Array.isArray(n.data)?n.data:void 0;if(!r)return;return r.filter((s)=>_b(s)&&typeof s.id==="string"&&typeof s.providerID==="string")}catch{return}}function yb(e,t,n=dn){let r={errors:[],zeroCost:[]};for(let s of n){let o=e[s],a=t.filter((f)=>f.providerID===o.provider);if(!a.length)continue;let l=a.find((f)=>f.id===o.id||f.modelID===o.id),c=(f)=>r.errors.push(`Model \`${o.model}\` is not available in OpenCode: ${f}. Set \`${Io[s]}\` in ~/.config/diffloupe/config.json or pass --model ${s}=<provider/model>.`);if(!l){c(`provider \`${o.provider}\` has no model \`${o.id}\``);continue}let u=l.variants?.map((f)=>f.id)??[];if(o.variant&&!u.includes(o.variant)){c(u.length?`it has no variant \`${o.variant}\` (variants: ${u.join(", ")})`:`it has no variants, so \`#${o.variant}\` and effort cannot apply`);continue}let d=l.cost??[];if(d.length&&d.every((f)=>!f.input&&!f.output))r.zeroCost.push(s)}return r}import{readFileSync as zO}from"fs";import vb from"os";import ef from"path";function JO(e=process.env,t=vb.homedir()){let n=e.XDG_CONFIG_HOME?e.XDG_CONFIG_HOME:ef.join(t,".config"),r=ef.join(n,"opencode");return["opencode.jsonc","opencode.json"].map((s)=>ef.join(r,s))}function XO(e){let t=Bun.JSONC;if(t)try{return t.parse(e)}catch{return}return Ec(e)}function bb(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function YO(e,t){if(!bb(e))return{};let n=t?{path:t}:{};if(typeof e.model==="string"&&e.model.trim())n.model=e.model.trim();if(bb(e.providers))n.providers=e.providers;return n}function xb(e=process.env,t=vb.homedir()){for(let n of JO(e,t)){let r;try{r=zO(n,"utf8")}catch{continue}return YO(XO(r),n)}return{}}async function ul(e){let t=e.env??process.env,n=e.openCodeUser??xb(t),r=e.settings??{},s={env:t,...e.cli?{cli:e.cli}:{},settings:r,config:e.userConfig,...n.model?{openCodeModel:n.model}:{}},o=Ep(s),a={providers:Ap(o,e.stages),env:t,...e.userConfig.apiKeys?{apiKeys:e.userConfig.apiKeys}:{},...n.providers?{userProviders:n.providers}:{}},l=hb(a)?await(e.exportCredentials??(()=>gb(t)))():void 0,c=mb({...a,...l?{saved:l}:{}}),u=await(e.readCatalog??(()=>wb()))();return{provider:dc(s),models:o,openCodeUser:n,credentials:c,...u?{catalog:yb(o,u,e.stages)}:{}}}function Rb(e){return{provider:e.provider,model:e.models.review.model,modelMerge:e.models.coordinator.model,modelWalk:e.models.walkthrough.model,modelIntent:e.models.intent.model,effort:"",effortAux:"",providers:e.openCodeUser.providers??{},childEnv:e.credentials.childEnv,authImport:e.credentials.imports.length?JSON.stringify(e.credentials.imports):""}}function Sb(e,t=dn){let n={};for(let r of t)n[r]={model:e.models[r].model,source:e.models[r].source};return n}var hl={git:"https://git-scm.com/downloads",opencode:"https://opencode.ai/v2/docs/ (npm i -g @opencode/cli)",tilth:"https://github.com/jahala/tilth (cargo install tilth)",gh:"https://cli.github.com/ (then `gh auth login`)"},rv={review:"model",coordinator:"modelMerge",walkthrough:"modelWalk",intent:"modelIntent"};function OI(e){let t={};for(let n of e){let r=n.indexOf("="),s=n.slice(0,r),o=n.slice(r+1);if(r<=0||!o||!(s in rv))throw new _e(`--model expects stage=model-id with stage one of ${Object.keys(rv).join(", ")}; got "${n}"`);t[s]=o}return t}async function no(e){let t=e.intent?.trim();if(!t&&e.intentFile)t=(await pl(e.intentFile,"utf8")).trim();let n=OI(e.model??[]);return{...e.kind==="diff"?{kind:"diff"}:{},...e.kind==="diff"&&e.walkthrough?{walkthrough:!0}:{},repo:et.resolve(e.repo??process.cwd()),...e.target?{target:e.target}:{},...e.base?{base:e.base}:{},...t?{intent:t}:{},...Object.keys(n).length?{models:n}:{},...e.effort?{effort:e.effort}:{},...e.maxCost!==void 0?{maxCostUsd:e.maxCost}:{},...e.maxRounds!==void 0?{maxRounds:e.maxRounds}:{},...e.config?{settingsFile:et.resolve(e.config)}:{},...e.full?{full:!0}:{},...e.github?{github:!0}:{},...e.head?{head:e.head}:{}}}function II(e,t={}){let n=Rn(e),o=["git",...t.kind==="diff"?t.walkthrough?["opencode"]:[]:["opencode","tilth"],...n.kind==="pr"?["gh"]:[]].filter((a)=>!Bun.which(a,{PATH:process.env.PATH??""}));if(o.length)throw new _e(["Missing required tools on PATH:",...o.map((a)=>` ${a}: ${hl[a]??""}`)].join(`
655
- `))}function hf(e){return e!==null&&/^2\./.test(e)}function PI(e){return/\d+\.\d+(?:\.\d+)?/.exec(e)?.[0]??null}async function MI(){let e=Bun.which("opencode",{PATH:process.env.PATH??""});if(!e)return;let t=await re(e,["--version"],{allowFail:!0}).catch(()=>null),n=t&&t.code===0?PI(t.stdout):null;if(hf(n))return;throw new _e(`DiffLoupe needs OpenCode 2.x, but the opencode on PATH (${e}) is ${n??"an unknown version"}.
656
- Install: ${hl.opencode}`)}async function sv(e,t,n,r={}){let s=e.kind??"review",o=s==="diff",a=o&&e.walkthrough===!0,l=e.fromRun,c=l?await gt(l).catch((te)=>{throw new _e(`cannot start from run ${l}: ${te instanceof Error?te.message:String(te)}`)}):void 0,u=c?BI(c.target):void 0;if(c?.repo.remote&&!o)throw new _e(`reviewing ${c.repo.slug??"this repository"} needs a local clone; run diffloupe review from a clone of it`);for(let te of["github","head"])if(e[te]&&(o||c||Rn(e.target).kind!=="pr"))throw new _e(`--${te} needs a review of a pull request target`);if(II(u?u.kind==="pr"?`#${u.pr}`:"":e.target,{kind:s,walkthrough:a}),!o||a)await MI();let d=et.resolve(e.repo??t),f=c?void 0:Rn(e.target),p=o&&f?.kind==="pr"&&f.repo&&await ib(d,f)?{...f,repo:f.repo}:void 0;if(p)await sb(Gd(p.repo),p.repo);let h=c?c.repo.root:p?Gd(p.repo):d,g=p!==void 0||c?.repo.remote===!0,w=e.intent?.trim()||c?.intent.stated||void 0,b=await Kr(),x=e.settingsFile?await cl(et.resolve(e.settingsFile)):{},R=o?a?["walkthrough"]:[]:dn,P=R.length?await(r.resolveSetup??ul)({cli:{...e.models?{models:e.models}:{},...e.effort?{effort:e.effort}:{}},settings:x,userConfig:b,stages:R}):void 0,M=P?[...P.credentials.errors,...P.catalog?.errors??[]]:[];if(M.length)throw new _e(M.join(`
657
- `));let k={artifacts:cr(),out:et.join(an(),"scratch"),...cb(x),...P?Rb(P):{}},E=o?void 0:e.maxCostUsd??b.maxCostUsd,D=o?void 0:ub(x),L=c&&u?await rb(h,u,c.base,c.head,{isTaken:pf}):p?await ob(h,p,{isTaken:pf}):await nb(h,e.target,{...e.base?{base:e.base}:{},...e.head?{head:e.head}:{},isTaken:pf}),{target:O,changes:U,tag:I}=L,j=L.pullRequest,H=o?"Diff of":"Reviewing";n(j?`${H} ${O.slug}#${j.number}: ${j.title}`:`${H} ${O.slug} (${qI(L.spec)})`);let ve=L.commits===void 0?"":` (${L.commits} commit${L.commits===1?"":"s"})`;if(n(` ${O.base.slice(0,12)}..${O.head.slice(0,12)}${ve}`),n(` ${U.files} file(s) changed, +${U.insertions} -${U.deletions}`),n(` run ${I}`),P){for(let te of R){let we=P.models[te];n(` ${te}: ${we.model} (${Po(we.source)})`)}for(let te of P.credentials.warnings)n(` warning: ${te}`)}if(E!==void 0)n(P?.catalog?.zeroCost.includes("review")?" cost limit not enforced: models report no cost":` cost limit $${E.toFixed(2)}`);if(L.skippedUntracked.length){n(` skipped ${L.skippedUntracked.length} untracked file(s) over 1 MB:`);for(let te of L.skippedUntracked)n(` ${te}`)}let Se=new Date().toISOString(),ne={root:h,...O.slug?{slug:O.slug}:{},...g?{remote:g}:{}},ce=c?c.target:await HI(h,L),Be=c?c.untrackedSkipped:L.skippedUntracked,ze=await Vy(I),Je=await oe("git",["-C",h,"diff","--no-color","--no-ext-diff","--full-index","-M",O.base,O.head]);await Nr(et.join(ze,"diff.patch"),Je);let Xe=e.full===!0,nt=e.github===!0,be=o||nt?void 0:await Yy(ne,ce,Se),Te=be?await LI(h,be,O.head):void 0;if(Te?.run.findings.length)n(` ${Te.run.findings.length} finding(s) from prior run ${Te.run.id}`);let me=o?void 0:Te?await DI(Te.run)+1:1;if(me!==void 0&&me>1){if(n(Xe?` round ${me}, full review (--full)`:` round ${me}: reviewing what changed since ${Te?.run.head.slice(0,12)??"the last review"} (--full to review everything)`),me>NI)n(` warning: this change has been reviewed ${me-1} times; later rounds mostly find smaller problems`)}let W=await jI(),T=P?Sb(P,R):void 0;await Promise.resolve().then(() => df());let z=nv({id:I,createdAt:Se,repo:ne,target:ce,base:O.base,head:O.head,...w?{statedIntent:w}:{},patch:Je,untrackedSkipped:Be,coreSource:W,...be?{priorRunId:be}:{},...me!==void 0?{round:me}:{},...T?{models:T}:{},...o?{kind:s}:{}});return await Ti(z),{id:I,kind:s,walkthrough:a,dir:ze,createdAt:Se,repo:h,target:O,reviewTarget:ce,config:k,...E!==void 0?{maxCostUsd:E}:{},...!o&&e.maxRounds!==void 0?{maxRounds:e.maxRounds}:{},...w?{intent:w}:{},...D?{instructions:D}:{},patch:Je,...be?{priorRunId:be}:{},...Te?{previous:Te}:{},...me!==void 0?{round:me}:{},full:Xe,github:nt,untrackedSkipped:Be,coreSource:W,...T?{models:T}:{},pending:z}}async function ov(e,t){let{id:n,dir:r}=e;await Promise.resolve().then(() => df());let a=e.pending,l=Promise.resolve(),c=(h)=>{if(h.type!=="units"){t.onProgress(h);return}a=tv(iv(e),h.units,h.byClass),t.onProgress(Hy(a));let g=a;l=l.then(()=>Ti(g).catch((w)=>{t.log(` could not save the grouped run: ${w instanceof Error?w.message:String(w)}`)}))},u;try{u=e.kind==="diff"?await jy({repo:e.repo,target:e.target,tag:n,config:e.config,walkthrough:e.walkthrough,signal:t.signal,...e.intent?{intent:e.intent}:{},onProgress:c}):await zm({repo:e.repo,target:e.target,tag:n,config:e.config,signal:t.signal,...e.maxCostUsd!==void 0?{maxCostUsd:e.maxCostUsd}:{},...e.maxRounds!==void 0?{maxRounds:e.maxRounds}:{},...e.round!==void 0?{round:e.round}:{},...e.intent?{intent:e.intent}:{},...e.instructions?{instructions:e.instructions}:{},...FI(e),onProgress:c})}catch(h){let g=t.signal.aborted;throw await l,await Ti({...a,status:g?"cancelled":"failed",...g?{}:{error:h instanceof Error?h.message:String(h)}}),h}if(u.markdownPath){let h=e.config.artifacts??cr();await ff(et.join(h,"runs",`${n}.json`),et.join(r,"raw","record.json")),await ff(u.markdownPath,et.join(r,"raw","review.md")),await ff(et.join(h,"reviews",`${n}.payloads.json`),et.join(r,"raw","payloads.json"))}else if(u.record)await Nr(et.join(r,"raw","record.json"),`${JSON.stringify(u.record,null,2)}
658
- `);await Nr(et.join(r,"raw","units.json"),`${JSON.stringify(u.units,null,2)}
659
- `),await Nr(et.join(r,"raw","byClass.json"),`${JSON.stringify(u.byClass,null,2)}
660
- `);let d;await l;try{d=uf({...iv(e),result:u,...e.previous?{previous:e.previous}:{},log:t.log})}catch(h){let g=`building run.json: ${h instanceof Error?h.message:String(h)}`;throw await Ti({...a,status:"failed",error:g}),Error(g,{cause:h})}let{roundLimit:f}=u;if(f)d={...d,round:f.round,meta:{...d.meta,roundLimit:f}};await Ti(d);let p=e.kind==="diff"||u.record!==null;if(e.kind==="review")t.log(` anchors: ${ga(d)}`);if(e.github&&e.kind==="review"&&p)await TI(r,d);return{run:d,reviewed:p,...f?{roundLimit:f}:{}}}async function TI(e,t){let n=Ws(t,{includeOverCap:!0,github:!0});await Nr(et.join(e,"raw",kr),n);let r=t.findings.length+t.overCapFindings.length;if(r===0)return;let s=et.join(e,"raw","payloads.json"),o;try{o=JSON.parse(await pl(s,"utf8"))}catch{return}let a=o.summary?.body?.body;if(typeof a!=="string"||!o.summary?.body)return;let l=t.target.kind==="pr"?us(t.target.number,t.head):void 0;function*c(){yield n;for(let p=1;p<=r;p++)yield Ws(t,{includeOverCap:!0,github:!0,shorten:{count:p,note:Nm(p,l)}})}let u=Dm(a,c(),{artifact:l});o.summary.body.body=u,await Nr(s,`${JSON.stringify(o,null,2)}
661
- `);let d=et.join(e,"raw","review.md"),f=await pl(d,"utf8").catch(()=>{return});if(f?.includes(a))await Nr(d,f.replace(a,()=>u))}function iv(e){return{id:e.id,createdAt:e.createdAt,repo:e.pending.repo,target:e.reviewTarget,base:e.target.base,head:e.target.head,...e.intent?{statedIntent:e.intent}:{},patch:e.patch,untrackedSkipped:e.untrackedSkipped,coreSource:e.coreSource,...e.priorRunId?{priorRunId:e.priorRunId}:{},...e.round!==void 0?{round:e.round}:{},...e.models?{models:e.models}:{},...e.kind==="diff"?{kind:e.kind}:{}}}function FI(e){return{local:!e.github,...e.previous?{prior:Uy(e.previous.run)}:{},...e.previous&&!e.full?{priorHead:e.previous.run.head}:{}}}var NI=3;async function DI(e,t=gt){if(e.round!==void 0)return e.round;let n=async(r,s)=>{if(!r||s.has(r))return 1;s.add(r);let o=await t(r).catch(()=>{return});if(!o)return 1;return 1+(o.round??await n(o.priorRunId,s))};return n(e.priorRunId,new Set)}async function LI(e,t,n){try{let r=await gt(t),s=await Fr(t),o=Object.entries(s.findingStatus).filter(([,c])=>c==="dismissed").map(([c])=>c),a=new Map,l=[...new Set(r.findings.flatMap((c)=>[c.file,...(c.alsoAt??[]).map((u)=>u.file)]))];if(r.head!==n&&l.length)try{let c=await oe("git",["-C",e,"diff","-U0","--no-color","--no-ext-diff",r.head,n,"--",...l]);a=By(c)}catch{a=void 0}return{run:r,dismissed:o,...a?{lineMap:a}:{}}}catch{return}}async function ff(e,t){try{await CI(e,t)}catch{}}var fl;async function jI(){if(fl)return fl;return fl=await UI(import.meta.dir),fl}async function UI(e,t=Vn){if(e.split(/[\\/]/).includes("node_modules"))return`diffloupe@${t}`;try{let n=(await oe("git",["-C",e,"rev-parse","--short=12","HEAD"])).trim();return`diffloupe@${t}+${n}`}catch{return`diffloupe@${t}`}}var pf=(e)=>AI(Ve(e));function BI(e){switch(e.kind){case"pr":return{kind:"pr",pr:e.number};case"branch":return{kind:"branch",branch:e.spec};case"commit":return{kind:"commit",rev:e.spec};case"range":return Rn(`range:${e.spec}`);default:return{kind:e.kind}}}function qI(e){switch(e.kind){case"branch":return`branch ${e.branch}`;case"commit":return`commit ${e.rev}`;case"range":return`range ${e.from}${e.mergeBase?"...":".."}${e.to}`;default:return e.kind}}async function HI(e,t){let{spec:n,pullRequest:r}=t;if(n.kind==="pr")return{kind:"pr",number:n.pr,url:r?.url??"",title:r?.title??"",author:r?.author.login??"",baseRef:r?.baseRefName??"",headRef:r?.headRefName??"",state:r?.state??"",isDraft:r?.isDraft??!1};if(n.kind==="branch")return{kind:"branch",spec:n.branch};if(n.kind==="commit")return{kind:"commit",spec:n.rev};if(n.kind==="range")return{kind:"range",spec:`${n.from}${n.mergeBase?"...":".."}${n.to}`};let s;try{s=(await oe("git",["-C",e,"rev-parse","--abbrev-ref","HEAD"])).trim()||void 0}catch{}return{kind:n.kind,...s?{branch:s}:{}}}async function av(e){try{return await pl(et.join(e,"raw","review.md"),"utf8")}catch{return}}var mf=Ao.engines.bun.replace(/^>=\s*/,"");function lv(e,t){let n=e.split(".").map((s)=>Number.parseInt(s,10)||0),r=t.split(".").map((s)=>Number.parseInt(s,10)||0);for(let s=0;s<Math.max(n.length,r.length);s++){let o=(n[s]??0)-(r[s]??0);if(o!==0)return o>0}return!0}function GI(e){return/\d+\.\d+(?:\.\d+)?/.exec(e)?.[0]??null}function cv(e){if(e<1024)return`${e} B`;let t=["KB","MB","GB"],n=e/1024,r=0;while(n>=1024&&r<t.length-1)n/=1024,r++;return`${n.toFixed(n<10?1:0)} ${t[r]}`}async function ml(e,t,n,r){if(!e.which(t))return{name:t,status:n,detail:`not found on PATH. Install: ${hl[t]??t}`};let s=await e.exec(t,["--version"]),o=s&&s.code===0?GI(s.output):null,a=r?.(o)??{status:"ok"},l=[o??"version unknown",a.note].filter(Boolean).join(", ");return{name:t,status:a.status,detail:l}}async function VI(e){let t=[];if(e.platform==="win32")t.push({name:"platform",status:"fail",detail:"Windows is not supported natively. Run DiffLoupe inside WSL."});t.push({name:"bun",status:lv(e.bunVersion,mf)?"ok":"fail",detail:lv(e.bunVersion,mf)?e.bunVersion:`${e.bunVersion}, needs ${mf} or newer`}),t.push(await ml(e,"git","fail")),t.push(await ml(e,"opencode","fail",(a)=>hf(a)?{status:"ok"}:{status:"fail",note:"needs OpenCode 2.x (https://opencode.ai/v2/docs/)"})),t.push(await ml(e,"tilth","fail"));let n=await ml(e,"gh","warn");if(n.status==="warn")n.detail+=" (only needed to review pull requests)";else{let a=await e.exec("gh",["auth","status"]);if(!a||a.code!==0)n.status="warn",n.detail+=", not logged in: run `gh auth login` to review pull requests";else n.detail+=", logged in"}t.push(n);let r;try{r=await e.setup()}catch(a){t.push({name:"models",status:"fail",detail:a instanceof Error?a.message:String(a)})}if(r){for(let a of dn){let l=r.models[a];t.push({name:`model: ${a}`,status:"ok",detail:`${l.model} (${Po(l.source)})`})}if(!r.catalog)t.push({name:"model catalog",status:"warn",detail:"could not ask OpenCode for its models; not checked"});else{for(let a of r.catalog.errors)t.push({name:"model catalog",status:"fail",detail:a});if(r.catalog.zeroCost.length>0)t.push({name:"model catalog",status:"warn",detail:`no cost reported for ${r.catalog.zeroCost.join(", ")}: --max-cost cannot be enforced`})}for(let a of r.credentials.coverage){if(a.source==="none")continue;t.push({name:`credential: ${a.provider}`,status:"ok",detail:`${a.source}: ${a.detail}`})}for(let a of r.credentials.warnings)t.push({name:"credentials",status:"warn",detail:a});for(let a of r.credentials.errors)t.push({name:"credentials",status:"fail",detail:a})}let s=await e.dataSizes(),o=Object.values(s).reduce((a,l)=>a+l,0);return t.push({name:"data dir",status:"ok",detail:`${an()}: ${cv(o)} (${Object.entries(s).map(([a,l])=>`${a} ${cv(l)}`).join(", ")}). \`diffloupe runs prune\` removes old runs`}),t}async function gl(e){let t=0,n;try{n=await KI(e,{withFileTypes:!0})}catch{return 0}for(let r of n){let s=uv.join(e,r.name);if(r.isDirectory())t+=await gl(s);else if(r.isFile())t+=await WI(s).then((o)=>o.size,()=>0)}return t}async function zI(e,t){try{let n=await re(e,t,{allowFail:!0,timeoutMs:20000});return{code:n.code,output:`${n.stdout}
662
- ${n.stderr}`}}catch{return null}}function JI(e,t){return e.some((n)=>n.status==="fail"||t&&n.status==="warn")}var XI={ok:ro.default.green("ok "),warn:ro.default.yellow("warn"),fail:ro.default.red("FAIL")};function dv(){return new It("doctor").description("Check tools, models, credentials and disk use").option("--config <file>","Per-repo review settings, as passed to review").option("--strict","Exit 1 on warnings too, for CI (a model with no reported cost makes --max-cost unenforceable)").option("--json","Print the checks as a JSON array instead of text").action(async(e)=>{let t=await VI({platform:process.platform,bunVersion:Bun.version,which:(n)=>Bun.which(n),exec:zI,setup:async()=>{let n=e.config?await cl(uv.resolve(e.config)):{};return ul({settings:n,userConfig:await Kr()})},dataSizes:async()=>({runs:await gl(Js()),artifacts:await gl(cr()),scratch:await gl(Xs())})});if(e.json)console.log(JSON.stringify(t,null,2));else for(let n of t)console.log(`${XI[n.status]} ${ro.default.bold(n.name)}: ${n.detail}`);if(JI(t,e.strict===!0))process.exit(1)})}var Mf=ko(zi(),1);xr();Sr();var YI="diffloupe/gate";function fv(e,t){if(e&&Ft.includes(e))return e;return Object.entries(tt).find(([,r])=>t.includes(r.badge))?.[0]??"unknown"}function ZI(e,t,n){let r=e.comments[0];if(!r||!Cn(r.body,r.authorType))return null;let s=ri(r.body,"inline");if(!s)return null;if(e.resolved&&(n||e.resolvedBy!==t))return null;if(Yo(e.comments.map((c)=>({body:c.body,user:{type:c.authorType},...c.replyTo?{in_reply_to_id:c.replyTo}:{}}))).has(r.id))return null;let a=e.comments.some((c)=>Cn(c.body,c.authorType,"reply")&&ri(c.body,"reply")?.fields.dispute==="upheld"),l=jt(r.body).split(`
663
- `).find((c)=>c.trim())?.replace(/^#+\s*/,"").trim()??"";return{fp:s.fields.fp??null,severity:fv(s.fields.sev,r.body),file:s.fields.file??e.file??null,line:s.fields.line??(e.line?String(e.line):null),title:l,url:r.url||null,where:"thread",...e.outdated?{outdated:!0}:{},...a?{upheld:!0}:{},...s.fields.pre==="1"?{preexisting:!0}:{}}}function QI(e){let t=jt(e).replace(/^\s*[-*]\s*/,"").trim();for(let{badge:r}of Object.values(tt))if(t.startsWith(r))t=t.slice(r.length).trim();let n=t.lastIndexOf(" \u2014 ");return n>0?t.slice(0,n):t}function eP(e){let t=null;for(let n of e){if(!Cn(n.body??"",n.user?.type,"summary"))continue;if(!t||n.id>t.id)t=n}return t}function tP(e,t,n={}){let r=[],s=new Set;for(let u of e.threads){let d=ZI(u,e.author,n.countAuthorResolved===!0);if(!d)continue;if(d.fp){if(s.has(d.fp))continue;s.add(d.fp)}r.push(d)}if(!t?.body)return r;let o=ni(t.body),a=Hc(o),l=new Set(a.filter((u)=>u.outcome==="withdrawn").map((u)=>u.fp)),c=new Set(a.filter((u)=>u.outcome==="upheld").map((u)=>u.fp));for(let u of o.split(`
664
- `))for(let d of tn(u)){let f=d.fields.fp;if(d.kind!=="summary-item"||!f||s.has(f)||l.has(f))continue;s.add(f),r.push({fp:f,severity:fv(d.fields.sev,u),file:d.fields.file??null,line:d.fields.line??null,title:QI(u),url:t.html_url??null,where:"summary",...c.has(f)?{upheld:!0}:{},...d.fields.pre==="1"?{preexisting:!0}:{}})}return r}function nP(e,t){let n=Ft.indexOf(t);return e.filter((r)=>!r.preexisting&&r.severity!=="unknown"&&Ft.indexOf(r.severity)<=n)}function rP(e,t,n){let r=eP(t),s=tP(e,r,n),o=nP(s,n.failOn),a=n.overrideLabel&&e.labels.includes(n.overrideLabel)?n.overrideLabel:null,l=n.reviewMissing===!0&&!r;return{pr:e.number,url:e.url,head:e.headSha,failOn:n.failOn,open:s,matched:o,override:a,summaryUrl:r?.html_url??null,unreviewed:l,fails:(o.length>0||l)&&!a}}function gf(e,t){return`${e} ${t}${e===1?"":"s"}`}function pv(e){let t=`at ${e.failOn} or above`,n=e.unreviewed?e.override?`Not reviewed: the review failed, passed by the ${e.override} label`:"Not reviewed: the review failed and no earlier review reached this PR":!e.matched.length?`No open findings ${t}`:e.override?`${gf(e.matched.length,"open finding")} ${t}, passed by the ${e.override} label`:`${gf(e.matched.length,"open finding")} ${t}`;return n.length>140?`${n.slice(0,139)}\u2026`:n}function hv(e){let t=[`PR #${e.pr}: ${pv(e)}`],n=(o)=>{let a=o.file?`${o.file}${o.line?`:${o.line}`:""}`:"(no file)",l=[o.where==="summary"?"in the summary":"",o.outdated?"outdated":"",o.upheld?"upheld after a dispute, needs a person":"",o.preexisting?"pre-existing, not counted":""].filter(Boolean);return` ${o.severity.padEnd(12)} ${a} ${o.title}${l.length?` (${l.join(", ")})`:""}${o.url?`
665
- ${" ".repeat(15)}${o.url}`:""}`},r=e.open.filter((o)=>!e.matched.includes(o));if(e.matched.length)t.push("",`Open at ${e.failOn} or above:`,...e.matched.map(n));if(r.length)t.push("","Other open findings:",...r.map(n));let s=e.open.filter((o)=>o.severity==="unknown").length;if(s)t.push("",`${gf(s,"finding")} with no readable severity; not counted against --fail-on.`);return t}async function mv(e,t,n,r){let[s,o]=await Promise.all([r.readThreads(e,t),r.readComments(e,t)]),a=rP(s,o,n);if(n.status)await r.gh(["api","--method","POST",`repos/${e}/statuses/${n.status.sha??a.head}`,"-f",`state=${a.fails?"failure":"success"}`,"-f",`context=${YI}`,"-f",`description=${pv(a)}`,"-f",`target_url=${a.summaryUrl??a.url}`]);return a}import iM from"path";var ln=ko(zi(),1);function io(e){switch(e.type){case"stage":return`\xBB ${e.stage.replaceAll("_"," ")}`;case"log":return e.message;case"cost":return null;case"groups":{let t=e.groups.filter((n)=>n.files.length).length;return` ${e.files.length} file(s) in ${t} group(s)`}case"budget":return` cost limit reached: $${e.totalUsd.toFixed(2)} of $${e.limitUsd.toFixed(2)}, ${e.skippedSlices} slice(s) not started`;case"slice":{let t=`[${e.index+1}/${e.total}]`;if(e.status==="started")return` ${t} ${e.title}`;let n=e.costUsd!==void 0?` $${e.costUsd.toFixed(2)}`:"",r=e.wallMs!==void 0?` ${Math.round(e.wallMs/1000)}s`:"",s=e.findings!==void 0?` ${e.findings} finding(s)`:"";return` ${t} ${e.status==="ok"?"done":"FAILED"}${n}${r}${s} \u2014 ${e.title}`}case"done":{if(e.kind==="diff"){let r=e.costUsd?` \xB7 $${e.costUsd.toFixed(2)}`:"";return`${e.files??0} file(s) changed${r} \xB7 ${(e.wallMs/1000).toFixed(1)}s`}if(e.roundLimit)return`Not reviewed: this change already had ${e.roundLimit} round(s) of review (--max-rounds).`;if(e.noChanges)return"No code changes to review.";let t=e.carriedOver??0;return`${t?`${e.findings-t} new finding(s), ${t} carried over`:`${e.findings} finding(s)`} \xB7 $${e.costUsd.toFixed(2)} \xB7 ${Math.round(e.wallMs/1000)}s`}case"cancelled":return"Run cancelled.";case"error":return`Run failed: ${e.message}`}}import bl from"path";import iP from"path";import{appendFileSync as sP}from"fs";import{readFile as oP}from"fs/promises";function aP(e){return async(t,n)=>{let r=await e.prepare(t,n);return{id:r.id,pending:r.pending,execute:(s)=>e.execute(r,s)}}}function _l(e){return aP({prepare:(t,n)=>sv(t,e,n),execute:ov})}class wl extends Error{activeRunId;constructor(e){super(e?`run ${e} is still running`:"a run is starting");this.activeRunId=e;this.name="RunBusyError"}}function gv(e){return iP.join(Ve(e),"events.jsonl")}async function _v(e){let t;try{t=await oP(gv(e),"utf8")}catch{return[]}let n=[];return t.split(`
666
- `).forEach((r,s)=>{if(!r.trim())return;try{let o=JSON.parse(r);n.push(typeof o.seq==="number"?o:{...o,seq:s+1})}catch{}}),n}class so{prepare;active=null;starting=!1;watchers=new Set;constructor(e){this.prepare=e}watch(e){return this.watchers.add(e),()=>this.watchers.delete(e)}get activeRunId(){return this.active?.id??null}isActive(e){return this.active?.id===e}pendingRun(e){return this.active?.id===e?this.active.pending:void 0}async start(e){if(this.active||this.starting)throw new wl(this.activeRunId);this.starting=!0;let t=[],n;try{n=await this.prepare(e,(a)=>t.push(a))}finally{this.starting=!1}let r=new AbortController,s={id:n.id,controller:r,seq:0,subscribers:new Set,pending:n.pending,done:Promise.resolve({status:"cancelled"})};this.active=s;let o=(a)=>this.emit(s,a);for(let a of t)o({type:"log",message:a});return s.done=n.execute({signal:r.signal,onProgress:o,log:(a)=>o({type:"log",message:a})}).then(({run:a,reviewed:l,roundLimit:c})=>(o({type:"done",status:"complete",findings:a.findings.length,carriedOver:a.findings.filter((u)=>u.carriedFrom).length,costUsd:a.meta.costUsd,wallMs:a.meta.wallMs,...c?{roundLimit:c.maxRounds}:l?{}:{noChanges:!0},...a.meta.kind==="diff"?{kind:"diff",files:a.files.length}:{}}),{status:"complete",run:a,reviewed:l,...c?{roundLimit:c}:{}}),(a)=>{if(r.signal.aborted||a instanceof Bt)return o({type:"cancelled"}),{status:"cancelled"};let l=a instanceof Error?a.message:String(a);return o({type:"error",message:l}),{status:"failed",error:l}}).finally(()=>{if(this.active===s)this.active=null}),{id:n.id,done:s.done}}cancel(e){let t=this.active;if(!t||t.id!==e)return;return t.controller.abort(),t.done}subscribe(e,t){let n=this.active;if(!n||n.id!==e)return;return n.subscribers.add(t),{lastSeq:n.seq,unsubscribe:()=>n.subscribers.delete(t)}}emit(e,t){if(t.type==="groups")e.pending=qy(e.pending,t);let n={...t,seq:++e.seq,at:new Date().toISOString()};try{sP(gv(e.id),`${JSON.stringify(n)}
667
- `)}catch{}let r=[...[...this.watchers].map((s)=>()=>s(e.id,n)),...[...e.subscribers].map((s)=>()=>s(n))];for(let s of r)try{s()}catch{}}}import{copyFile as lP,mkdir as yv,writeFile as cP}from"fs/promises";import yl from"path";function bv(e,t){let n={blocker:0,"should-fix":0,"nice-to-have":0,question:0};for(let o of e?.findings??[])n[o.severity]++;let r=(e?.findings??[]).filter(ou(e?.meta.postMinSeverity)).length,s=e?.target.kind==="pr"?e.target.number:null;return{id:t.id,status:t.status,reviewed:t.status==="complete",skipReason:t.skipReason??null,pr:s,base:e?.base??null,head:e?.head??null,runDir:t.runDir,outDir:t.outDir??null,payloads:t.payloads??null,artifactName:s!==null&&e?us(s,e.head):null,costUsd:e?.meta.costUsd??0,wallMs:e?.meta.wallMs??0,budgetStopped:e?.meta.budgetStopped===!0,skippedSlices:t.skippedSlices??0,findings:{total:(e?.findings.length??0)+(e?.overCapFindings.length??0),posted:(e?.findings.length??0)-r,minor:r,bySeverity:n},progress:e?.roundProgress??null,round:t.round??e?.round??1,incremental:e?.meta.reviewScope==="incremental",version:Vn}}var wv=[["raw/review.md","review.md"],["raw/payloads.json","payloads.json"],["raw/record.json","record.json"],["raw/units.json","units.json"],["raw/byClass.json","byClass.json"],[`raw/${kr}`,kr],["run.json","run.json"]];async function vv(e,t,n={}){await yv(t,{recursive:!0});let r=Ve(e),s=`${e}.detail.md`,a=[...(n.payloads===!1?wv.filter(([,c])=>c!=="payloads.json"):wv).map(([c,u])=>[yl.join(r,c),u]),[yl.join(cr(),"reviews",s),s]];return(await Promise.all(a.map(async([c,u])=>{try{return await lP(c,yl.join(t,u)),u}catch(d){if(d.code!=="ENOENT")throw d;return null}}))).filter((c)=>c!==null)}async function xv(e,t){await yv(e,{recursive:!0}),await cP(yl.join(e,"result.json"),`${JSON.stringify(t,null,2)}
668
- `)}function Rv(e,t){let n=Ft.indexOf(t);return e.findings.some((r)=>Ft.indexOf(r.severity)<=n)}async function Sv(e){let t=(h)=>console.error(h),n=new so(_l(process.cwd())),r=0;n.watch((h,g)=>{if(g.type==="budget")r=g.skippedSlices;let w=io(g);if(w)t(w)});let s;try{s=await n.start(await no(e))}catch(h){return t(`Error: ${h instanceof Error?h.message:String(h)}`),2}let o=oo(()=>{t(`
669
- Cancelling: stopping agents and removing the worktree (Ctrl+C again to exit now)...`),n.cancel(s.id)}),a=await s.done;o();let l=Ve(s.id),c=a.status==="complete"?a.run:await gt(s.id).catch(()=>null),u=a.status==="complete"?a.reviewed?"complete":"skipped":a.status,d=a.status==="complete"?a.roundLimit:void 0,f=u!=="skipped"?null:d?"round-limit":"no-code-files",p=await uP(s.id,c,u,f,r,e);if(e.json)process.stdout.write(`${JSON.stringify(p,null,2)}
649
+ `),docsFiles:d.docs,registry:"",outFile:F});await Fe(Ni.join(ye,"prompts",`${E}.txt`),j);let H=await Pn(j,{budget:ss,outFile:F,tag:E,model:On,effort:en,tools:"none",answerKeys:["chapters"]}).catch((ne)=>(n(),t({type:"log",message:` walkthrough failed: ${ne instanceof Error?ne.message:String(ne)}`}),{costUsd:0,payload:null}));n(),t({type:"cost",totalUsd:H.costUsd});let ve=H.payload??void 0;if(!ve)t({type:"log",message:" walkthrough returned no guide"});let Re=Date.now()-r;return f(M,ve?{walkthrough:ve,wallMs:Re,totalCostUsd:H.costUsd}:null,H.costUsd)}function pb(e,t){let n=new Map(t.files.map((r)=>[r.path,r]));return{...e,groups:t.groups,files:e.files.map((r)=>{let s=n.get(r.path);return s?{...r,groupId:s.groupId,classification:s.classification}:r})}}function hb(e){return{type:"groups",groups:e.groups,files:e.files.map((t)=>({path:t.path,groupId:t.groupId,classification:t.classification}))}}import cI from"os";import Ue from"path";import{appendFile as yV,mkdir as uI,readdir as to,readFile as rf,rename as dI,rm as nf,writeFile as sf}from"fs/promises";class Fi extends Error{constructor(e){super(e);this.name="StateOpError"}}function Li(){return{reviewedFiles:{},findingStatus:{},comments:[]}}function gb(e){let t=typeof e==="object"&&e!==null&&Array.isArray(e.reviewedFiles);return Vy(t?{...e,reviewedFiles:{}}:e)}var lI=/^0+$/;function mb(e,t,n){let r=t.filter((s)=>!n.has(s));if(r.length>0)throw new Fi(`unknown ${e}: ${r.join(", ")}`)}function _b(e,t,n){if(t.op==="reviewed"){let l=new Map(n.files.map((u)=>[u.path,u]));mb(t.paths.length===1?"file":"files",t.paths,new Set(l.keys()));let c={...e.reviewedFiles};for(let u of t.paths){let d=l.get(u);if(!t.value)delete c[u];else c[u]=d?.status==="removed"||!d?.blob||lI.test(d.blob)?"":d.blob}return{...e,reviewedFiles:c}}if(t.ids.length===0)throw new Fi("no finding ids given");let r=new Set([...n.findings,...n.overCapFindings].map((l)=>l.id));if(mb(t.ids.length===1?"finding":"findings",t.ids,r),t.status==="dismissed"&&!t.reason)throw new Fi("dismissing a finding needs a reason");let s={...e.findingStatus},o={...e.findingNotes};for(let l of t.ids){if(delete o[l],t.status==="open")delete s[l];else s[l]=t.status;if(t.status==="dismissed"&&t.reason)o[l]={reason:t.reason,...t.note?{note:t.note}:{},at:t.at}}let a={...e,findingStatus:s,findingNotes:o};if(Object.keys(o).length===0)delete a.findingNotes;return a}function cn(){return Ue.join(process.env.XDG_DATA_HOME||Ue.join(cI.homedir(),".local","share"),"diffloupe")}function ro(){return Ue.join(cn(),"runs")}function fr(){return Ue.join(cn(),"artifacts")}function of(e){let[t="",n=""]=e.toLowerCase().split("/");return Ue.join(cn(),"repos",t,`${n}.git`)}function Ve(e){if(!e||e.includes("/")||e.includes("\\")||e.startsWith("."))throw Error(`invalid run id: ${e}`);return Ue.join(ro(),e)}async function wb(e){let t=Ve(e);return await uI(Ue.join(t,"raw"),{recursive:!0}),await sf(Ue.join(t,"state.json"),`${JSON.stringify(Li(),null,2)}
650
+ `),t}async function ji(e){await sf(Ue.join(Ve(e.id),"run.json"),`${JSON.stringify(e,null,2)}
651
+ `)}class Un extends Error{id;summary;raw;constructor(e,t,n){super(`run ${e} has an invalid run.json: ${t}`);this.id=e;this.summary=t;this.raw=n;this.name="InvalidRunError"}}async function gt(e){let t=JSON.parse(await rf(Ue.join(Ve(e),"run.json"),"utf8")),n=Wy(t);if(n instanceof Z.errors)throw new Un(e,n.summary,t);return n}async function af(e){let t=await gt(e);if(Yy(t))return t;try{return Xy(t,JSON.parse(await rf(Ue.join(Ve(e),"raw","record.json"),"utf8")))}catch{return t}}class no extends Error{id;summary;constructor(e,t){super(`run ${e} has an invalid state.json: ${t}`);this.id=e;this.summary=t;this.name="InvalidStateError"}}async function yb(e){let t;try{t=await rf(Ue.join(Ve(e),"state.json"),"utf8")}catch(s){if(s.code==="ENOENT")return Li();throw s}let n;try{n=JSON.parse(t)}catch(s){throw new no(e,s instanceof Error?s.message:String(s))}let r=gb(n);if(r instanceof Z.errors)throw new no(e,r.summary);return r}async function jr(e){try{return await yb(e)}catch{return Li()}}async function fI(e,t){let n=Ue.join(Ve(e),"state.json"),r=`${n}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;try{await sf(r,`${JSON.stringify(t,null,2)}
652
+ `),await dI(r,n)}catch(s){throw await nf(r,{force:!0}),s}}var pl=new Map;async function lf(e,t){let r=(pl.get(e)??Promise.resolve()).catch(()=>{return}).then(async()=>{let[s,o]=await Promise.all([gt(e),yb(e)]),a=_b(o,t,s);return await fI(e,a),a});pl.set(e,r);try{return await r}finally{if(pl.get(e)===r)pl.delete(e)}}function bb(e,t,n,r={}){return lf(e,{op:"finding",ids:t,status:n,reason:r.reason,note:r.note,at:new Date().toISOString()})}function pI(e){let t={blocker:0,"should-fix":0,"nice-to-have":0,question:0};for(let n of e.findings??[])t[n.severity]=(t[n.severity]??0)+1;return t}function tf(e,t,n){let r=e(t);return r instanceof Z.errors?n:r}function vb(e){let t=typeof e.raw==="object"&&e.raw!==null?e.raw:{},n=typeof t.meta==="object"&&t.meta!==null?t.meta:{};return{id:e.id,status:tf(sl,t.status,"failed"),createdAt:typeof t.createdAt==="string"?t.createdAt:"",target:tf(ol,t.target,{kind:"worktree"}),repo:tf(al,t.repo,{root:""}),findingCounts:{blocker:0,"should-fix":0,"nice-to-have":0,question:0},costUsd:typeof n.costUsd==="number"?n.costUsd:0,...n.kind==="diff"?{kind:"diff"}:{},invalid:e.summary}}async function Jt(){let e;try{e=await to(ro())}catch{return[]}let t=[];for(let n of e)try{let r=await gt(n);t.push({id:r.id,status:r.status,createdAt:r.createdAt,target:r.target,repo:r.repo,findingCounts:pI(r),costUsd:r.meta?.costUsd??0,...r.meta?.kind?{kind:r.meta.kind}:{},...r.meta?.roundLimit?{roundLimited:!0}:{}})}catch(r){if(r instanceof Un)t.push(vb(r))}return t.sort((n,r)=>r.createdAt.localeCompare(n.createdAt))}function hl(e,t){if(t.kind==="pr")return`pr:${e.slug??e.root}#${t.number}`;if("spec"in t)return`${t.kind}:${e.root}:${t.spec}`;return`local:${e.root}:${t.branch??""}`}async function xb(e,t,n){let r=hl(e,t);return(await Jt()).find((o)=>o.status==="complete"&&o.kind!=="diff"&&!o.roundLimited&&o.createdAt<n&&hl(o.repo,o.target)===r)?.id}function io(){return Ue.join(cn(),"scratch")}function ml(){let e=Ue.join(io(),"oc","shared");return[Ue.join(e,"data"),Ue.join(e,"state")]}function hI(){let e=fr();return[...["logs","prompts","raw","reviews","runs"].map((t)=>Ue.join(e,t)),io(),...ml()]}async function mI(e,t){try{if((await re("git",["-C",e,"show-ref","--verify","--quiet",t],{allowFail:!0})).code!==0)return!1;return await oe("git",["-C",e,"update-ref","-d",t]),!0}catch{return!1}}async function so(e){let t=[],n=Ve(e),r;try{r=(await gt(e)).repo.root}catch(s){if(s instanceof Un)r=vb(s).repo.root||void 0}for(let s of hI()){let o;try{o=await to(s)}catch{continue}for(let a of o)if(a.startsWith(`${e}-`)||a.startsWith(`${e}.`)){let l=Ue.join(s,a);await nf(l,{recursive:!0,force:!0}),t.push(l)}}if(r){for(let s of[`refs/diffloupe/${e}`,`refs/diffloupe/${e}-base`])if(await mI(r,s))t.push(s)}try{await to(n),await nf(n,{recursive:!0,force:!0}),t.push(n)}catch{}return t}function Sb(e,t){let n=(t.now??Date.now())-t.olderThanMs;return e.toSorted((r,s)=>s.createdAt.localeCompare(r.createdAt)).slice(Math.max(0,t.keep)).filter((r)=>r.status!=="running"&&Date.parse(r.createdAt)<n)}async function Rb(){let e=[];try{e=await to(ro())}catch{}let t=(await Jt()).filter((o)=>o.status==="running").map((o)=>o.id),n=(o,a)=>a.some((l)=>o.startsWith(`${l}-`)||o.startsWith(`${l}.`)),r=[],s=async(o,a)=>{let l;try{l=await to(o)}catch{return}for(let c of l)if(!a(c))r.push(Ue.join(o,c))};await s(io(),(o)=>!o.endsWith(".json")||n(o,e));for(let o of ml())await s(o,(a)=>n(a,t));return r}import{readFile as II}from"fs/promises";bt();import{copyFile as gI,mkdir as _I,rm as wI,stat as cf,utimes as yI}from"fs/promises";import bI from"os";import Ui from"path";import{randomBytes as vI}from"crypto";function df(e,t){if(!t)return e;let n=e;for(let r=2;t(n);r++)n=`${e}-${r}`;return n}var xI=1048576;class _e extends Error{name="TargetError"}function $n(e){let t=(e??"worktree").trim();if(t===""||t==="worktree")return{kind:"worktree"};if(t==="staged")return{kind:"staged"};if(t==="HEAD")return{kind:"commit",rev:"HEAD"};let n=t.match(/^(?:#|pr:)(\d+)$/);if(n?.[1])return{kind:"pr",pr:Number(n[1])};let r=t.match(/^([\w.-]+\/[\w.-]+)#(\d+)$/);if(r?.[1]&&r[2])return{kind:"pr",pr:Number(r[2]),repo:r[1]};if(/github\.com\//.test(t)){let l=t.match(/^(?:https?:\/\/)?(?:www\.)?github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)(?:[/?#].*)?$/);if(!l?.[1]||!l[2]||!l[3])throw new _e(`not a GitHub pull request URL: ${t}`);return{kind:"pr",pr:Number(l[3]),repo:`${l[1]}/${l[2]}`}}let s=t.indexOf(":"),o=s>0?t.slice(0,s):"",a=s>0?t.slice(s+1):"";if(o==="branch"&&a)return{kind:"branch",branch:a};if(o==="commit"&&a)return{kind:"commit",rev:a};if(o==="range"){let l=$b(a);if(l)return l}if(!o&&!t.startsWith("-")&&!/\s/.test(t))if(t.includes("..")){let l=$b(t);if(l)return l}else return{kind:"commit",rev:t};throw new _e(`unrecognized target "${t}". Use worktree, staged, a commit (<sha>, HEAD~2, commit:<rev>), a range (<a>..<b>, <a>...<b>, range:<a>..<b>), branch:<name>, #<pr>, pr:<n>, owner/repo#<n>, or a pull request URL.`)}function $b(e){let t=e.includes("..."),n=e.split(t?"...":"..");if(n.length!==2)return;let[r="",s=""]=n;if(!r&&!s)return;if(r.includes("..")||s.includes(".."))return;return{kind:"range",from:r||"HEAD",to:s||"HEAD",mergeBase:t}}function ff(e,t,n,r=new Date){let s=(c)=>String(c).padStart(2,"0"),o=`${r.getFullYear()}${s(r.getMonth()+1)}${s(r.getDate())}${s(r.getHours())}${s(r.getMinutes())}${s(r.getSeconds())}`,a=t.kind==="pr"?`pr${t.pr}`:t.kind;return`${e.replace(/[^\w.-]+/g,"_")}-${a}-${n.slice(0,12)}-${o}`}async function Eb(e,t,n={}){let r=$n(t),s=(M,k={})=>oe("git",["-C",e,...M],k),o=async(M)=>{let k=await re("git",["-C",e,"rev-parse","--verify","--quiet",`${M}^{commit}`],{allowFail:!0});if(k.code!==0){let E=/^\d+$/.test(M)?` (for pull request ${M}, use #${M})`:"";throw new _e(`unknown revision "${M}": not a commit in ${e}${E}`)}return k.stdout.trim()},a=async(M,k)=>(await s(["merge-base",M,k])).trim();if((await re("git",["-C",e,"rev-parse","--show-toplevel"],{allowFail:!0})).code!==0)throw new _e(`${e} is not inside a git repository`+(r.kind==="pr"&&r.repo?". diffloupe diff can show this pull request without a clone.":""));let c=await di(e),u,d,f,p=[],h=!1,g;if(r.kind==="commit"&&EI(t)&&await CI(e,r.rev)){if(g=await kb(e).catch(()=>{return}),g){let M=await o(r.rev);if(await a(g,M)!==M)r={kind:"branch",branch:r.rev}}}switch(r.kind){case"pr":{if(r.repo&&!c.startsWith("local/")&&r.repo.toLowerCase()!==c.toLowerCase())throw new _e(`pull request is in ${r.repo} but ${e} is a clone of ${c}. Run from a clone of ${r.repo} or pass -C. diffloupe diff can show it without a clone.`);if(f=await Pb(e,r.pr,r.repo??(c.startsWith("local/")?void 0:c)),d=f.headRefOid,await uf(e,d,[`refs/pull/${r.pr}/head`]),n.head)d=await kI(e,r.pr,d,n.head);await uf(e,f.baseRefOid,[f.baseRefName]),u=await a(f.baseRefOid,d);break}case"branch":{d=await o(r.branch),u=await a(g??await kb(e),d);break}case"range":{let M=await o(r.from);d=await o(r.to),u=r.mergeBase?await a(M,d):M;break}case"commit":{d=await o(r.rev);let M=await re("git",["-C",e,"rev-parse","--verify","--quiet",`${d}^`],{allowFail:!0});if(M.code!==0)throw new _e(`${r.rev} is a root commit; use range: instead`);u=M.stdout.trim();break}case"staged":case"worktree":{let M=await o("HEAD"),k=r.kind==="staged"?await AI(e,M):await OI(e,M);d=k.commit,p=k.skipped,u=n.base?await a(await o(n.base),M):M,h=!0;break}}let w=c.split("/").pop()??Ui.basename(e),b=df(ff(w,r,d,n.now),n.isTaken);if(h)await s(["update-ref",`refs/diffloupe/${b}`,d]);let x=await pf(e,u,d),S=h?void 0:Number((await s(["rev-list","--count",`${u}..${d}`])).trim()),P={base:u,head:d,slug:c,...r.kind==="pr"?{pr:String(r.pr)}:{}};return{spec:r,target:P,tag:b,changes:x,...S!==void 0?{commits:S}:{},skippedUntracked:p,...f?{pullRequest:f}:{}}}async function Cb(e,t,n,r,s={}){let o=await Promise.all([n,r].map((f)=>gl(e,f))),a=[n,r].filter((f,p)=>!o[p]);if(a.length)throw new _e(`commit ${a[0]} is no longer in ${e}`);let l=await di(e),c=l.split("/").pop()??Ui.basename(e),u=df(ff(c,t,r,s.now),s.isTaken);if(t.kind==="staged"||t.kind==="worktree")await oe("git",["-C",e,"update-ref",`refs/diffloupe/${u}`,r]);let d={base:n,head:r,slug:l,...t.kind==="pr"?{pr:String(t.pr)}:{}};return{spec:t,target:d,tag:u,changes:await pf(e,n,r),skippedUntracked:[]}}var SI=/^(?!\.{1,2}$)[\w.-]+$/;function RI(e){let t=e.split("/");return t.length===2&&t.every((n)=>SI.test(n))}async function Ab(e,t){if(t.kind!=="pr"||!t.repo)return!1;if((await re("git",["-C",e,"rev-parse","--show-toplevel"],{allowFail:!0})).code!==0)return!0;let r=await di(e);return!r.startsWith("local/")&&r.toLowerCase()!==t.repo.toLowerCase()}async function Ob(e,t,n=`https://github.com/${t}.git`){if(!RI(t))throw new _e(`not a GitHub repository: ${t}`);let r=(...o)=>oe("git",["-C",e,...o]);if(await cf(Ui.join(e,"HEAD")).catch(()=>null))return;await _I(e,{recursive:!0}),await r("init","-q","--bare"),await r("remote","add","origin",n),await r("config","core.repositoryformatversion","1"),await r("config","extensions.partialClone","origin"),await r("config","remote.origin.promisor","true"),await r("config","remote.origin.partialclonefilter","blob:none"),await r("config","gc.auto","0"),await r("config","credential.helper",""),await r("config","--add","credential.helper","!gh auth git-credential")}async function Ib(e,t,n={}){let r=await Pb(e,t.pr,t.repo),s=r.headRefOid,o=await re("gh",["api",`repos/${t.repo}/compare/${r.baseRefOid}...${s}`,"--jq",".merge_base_commit.sha"],{cwd:e,allowFail:!0}),a=o.code===0&&o.stdout.trim()?o.stdout.trim():r.baseRefOid;await $I(e,[a,s],[`refs/pull/${t.pr}/head`]);let l=t.repo.split("/").pop()??t.repo,c=df(ff(l,t,s,n.now),n.isTaken);return await oe("git",["-C",e,"update-ref",`refs/diffloupe/${c}`,s]),await oe("git",["-C",e,"update-ref",`refs/diffloupe/${c}-base`,a]),{spec:t,target:{base:a,head:s,slug:t.repo,pr:String(t.pr)},tag:c,changes:await pf(e,a,s),skippedUntracked:[],pullRequest:r}}async function $I(e,t,n){let r=async()=>{let l=await Promise.all(t.map((c)=>gl(e,c)));return t.filter((c,u)=>!l[u])},s=(l)=>re("git",["-C",e,"fetch","-q","--depth=1","--filter=blob:none","--no-tags","origin",...l],{allowFail:!0}),o=await r();if(o.length===0)return;let a=await s(o);o=await r();for(let l of n){if(o.length===0)return;await s([l]),o=await r()}if(o.length)throw new _e(`could not fetch ${o.map((l)=>l.slice(0,12)).join(", ")} from GitHub: ${a.stderr.trim()||"not found"}`)}async function Pb(e,t,n){let s=["pr","view",String(t),"--json","number,title,body,author,url,state,isDraft,baseRefName,headRefName,baseRefOid,headRefOid",...n?["--repo",n]:[]],o=await re("gh",s,{cwd:e,allowFail:!0});if(o.code!==0)throw new _e(`gh pr view ${t} failed: ${o.stderr.trim()||`exit ${o.code}`}`);return JSON.parse(o.stdout)}async function gl(e,t){return(await re("git",["-C",e,"cat-file","-e",`${t}^{commit}`],{allowFail:!0,env:{...process.env,GIT_NO_LAZY_FETCH:"1"}})).code===0}async function uf(e,t,n){if(await gl(e,t))return;for(let r of n)if(await re("git",["-C",e,"fetch","-q","origin",r],{allowFail:!0}),await gl(e,t))return;throw new _e(`commit ${t} is not in this clone and could not be fetched from origin`)}async function kI(e,t,n,r){if(!/^[0-9a-f]{40}$/i.test(r))throw new _e(`--head must be a full 40-character commit SHA, not "${r}"`);let s=r.toLowerCase();if(s===n)return n;if(await uf(e,s,[`refs/pull/${t}/head`,s]),(await re("git",["-C",e,"merge-base","--is-ancestor",s,n],{allowFail:!0})).code!==0)throw new _e(`--head ${s} is not in the history of pull request #${t} (head ${n.slice(0,12)})`);return s}function EI(e){return!(e??"").trim().startsWith("commit:")}async function CI(e,t){return(await Promise.all([`refs/heads/${t}`,`refs/remotes/${t}`].map((r)=>re("git",["-C",e,"show-ref","--verify","--quiet",r],{allowFail:!0})))).some((r)=>r.code===0)}async function kb(e){let t=await re("gh",["repo","view","--json","defaultBranchRef","-q",".defaultBranchRef.name"],{cwd:e,allowFail:!0}).catch(()=>null),n=[],r=t?.code===0?t.stdout.trim():"";if(r)n.push(`origin/${r}`,r);let s=await re("git",["-C",e,"symbolic-ref","--short","refs/remotes/origin/HEAD"],{allowFail:!0});if(s.code===0&&s.stdout.trim())n.push(s.stdout.trim());n.push("origin/main","main","origin/master","master");for(let o of n)if((await re("git",["-C",e,"rev-parse","--verify","--quiet",`${o}^{commit}`],{allowFail:!0})).code===0)return o;throw new _e("could not determine the default branch; use range:<base>..<branch> instead")}async function Mb(e,t,n,r,s){let o=(await oe("git",["-C",e,"rev-parse",`${n}^{tree}`])).trim();if(t===o)throw new _e("no changes to review");return(await oe("git",["-C",e,"commit-tree",t,"-p",n,"-m",r],s?{env:s}:{})).trim()}async function AI(e,t){let n=(await oe("git",["-C",e,"write-tree"])).trim();return{commit:await Mb(e,n,t,"diffloupe: staged changes"),skipped:[]}}async function OI(e,t){let n=(await oe("git",["-C",e,"rev-parse","--show-toplevel"])).trim(),r=Ui.resolve(n,(await oe("git",["-C",n,"rev-parse","--git-path","index"])).trim()),s=Ui.join(bI.tmpdir(),`diffloupe-index-${process.pid}-${vI(4).toString("hex")}`);try{await gI(r,s).then(async()=>{let{mtimeMs:d}=await cf(r),f=Math.floor(d/1000);await yI(s,f,f)},async()=>{await oe("git",["-C",n,"read-tree",t],{env:{...process.env,GIT_INDEX_FILE:s}})});let o={...process.env,GIT_INDEX_FILE:s},a=(await oe("git",["-C",n,"ls-files","--others","--exclude-standard","-z"])).split("\x00").filter(Boolean),l=[];for(let d of a){let f=await cf(Ui.join(n,d)).catch(()=>null);if(f&&f.isFile()&&f.size>xI)l.push(d)}let c=l.map((d)=>`:(exclude,literal)${d}`);await oe("git",["-C",n,"add","-A","--",".",...c],{env:o});let u=(await oe("git",["-C",n,"write-tree"],{env:o})).trim();return{commit:await Mb(n,u,t,"diffloupe: working tree",o),skipped:l}}finally{await wI(s,{force:!0})}}async function pf(e,t,n){let r=await oe("git",["-C",e,"diff","--numstat","--no-renames",t,n]),s={files:0,insertions:0,deletions:0};for(let o of r.split(`
653
+ `)){if(!o.trim())continue;let[a,l]=o.split("\t");s.files++,s.insertions+=Number(a)||0,s.deletions+=Number(l)||0}return s}var PI=Z({"+":"reject","$schema?":"string","provider?":"string","models?":{"+":"reject","review?":"string","coordinator?":"string","walkthrough?":"string","intent?":"string"},"effort?":"string","surfaces?":{"+":"reject","deploy?":"string[]","tooling?":"string[]"},"extraExcludes?":"string[]","instructions?":"string | string[]","post?":{"+":"reject","minSeverity?":"'blocker' | 'should-fix' | 'nice-to-have' | 'question'","questions?":"'keep' | 'drop'"}});function MI(e,t){let n=PI(e);if(n instanceof Z.errors)throw new _e(`invalid settings in ${t}: ${n.summary}`);for(let r of[...n.surfaces?.deploy??[],...n.surfaces?.tooling??[]])try{new RegExp(r)}catch(s){throw new _e(`invalid surface pattern in ${t}: ${s instanceof Error?s.message:String(s)}`)}return n}async function _l(e){let t;try{t=await II(e,"utf8")}catch(r){throw new _e(`cannot read settings file ${e}: ${r instanceof Error?r.message:String(r)}`)}let n;try{n=JSON.parse(t)}catch(r){throw new _e(`settings file ${e} is not valid JSON: ${r instanceof Error?r.message:String(r)}`)}return MI(n,e)}function Tb(e){let t={};return t.surfaces={deploy:e.surfaces?.deploy??Xo.deploy,tooling:e.surfaces?.tooling??Xo.tooling},t.extraExcludes=e.extraExcludes??[],t.postMinSeverity=e.post?.minSeverity??null,t.dropQuestions=e.post?.questions==="drop",t}function Db(e){let{instructions:t}=e;return(Array.isArray(t)?t.join(`
654
+ `):t??"").trim()||void 0}var Nb={anthropic:["ANTHROPIC_API_KEY"],openai:["OPENAI_API_KEY"],openrouter:["OPENROUTER_API_KEY"],google:["GOOGLE_GENERATIVE_AI_API_KEY","GEMINI_API_KEY"],groq:["GROQ_API_KEY"],mistral:["MISTRAL_API_KEY"],xai:["XAI_API_KEY"],deepseek:["DEEPSEEK_API_KEY"],cerebras:["CEREBRAS_API_KEY"],togetherai:["TOGETHER_AI_API_KEY"],"fireworks-ai":["FIREWORKS_API_KEY"],neuralwatt:["NEURALWATT_API_KEY"],opencode:["OPENCODE_API_KEY"]},Fb=new Set(["amazon-bedrock","google-vertex","google-vertex-anthropic","ollama","lmstudio","vllm"]);function oo(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Lb(e,t){let n=t?.[e],r=oo(n)&&Array.isArray(n.env)?n.env.filter((s)=>typeof s==="string"):[];return[...new Set([...r,...Nb[e]??[]])]}function TI(e,t){let n=t?.[e];if(!oo(n))return!1;for(let r of[n.settings,n.options])if(oo(r)&&typeof r.apiKey==="string"&&r.apiKey)return!0;return!1}function jb(e){for(let t of e.providers.keys()){if(Fb.has(t))continue;if(Lb(t,e.userProviders).some((n)=>e.env[n]))continue;if(e.apiKeys?.[t])continue;return!0}return!1}function wl(e){return e.map((t)=>Xn[t]).join(", ")}function DI(e,t,n,r){let s=[...r?[]:[`run \`opencode auth login ${e}\``],...n[0]?[`set ${n[0]}`]:[],`add apiKeys.${e} to ~/.config/diffloupe/config.json`],o=s.pop(),a=s.length?`${s.join(", ")}, or ${o}`:o;return`${r?`OpenCode's ${e} login is not an API key, and DiffLoupe can only copy API keys`:`No credential for provider \`${e}\``} (used by ${wl(t)}). To fix, ${a}.`}function NI(e,t,n){let r=pn,s=(e.saved??[]).find((a)=>a.integrationID===r&&a.value?.type==="external"&&a.value.methodID===Gp),o=(a)=>{n.coverage.push({provider:r,stages:t,source:"none",detail:""}),n.errors.push(br(a,t,e.openCodeDefault))};if(!s){o(e.saved?`OpenCode has no Claude Code login (used by ${wl(t)}). Connect Claude Agent in OpenCode with /connect, then run DiffLoupe again.`:`Could not read OpenCode's logins with \`opencode auth export\`, so the Claude Code login (used by ${wl(t)}) can't be copied.`);return}if(!e.claudePath){o(`Claude Code's \`claude\` CLI was not found on PATH or in OPENCODE_CLAUDE_PATH (used by ${wl(t)}). Install Claude Code and run \`claude auth login\`.`);return}n.imports.push({...s,active:!0}),n.coverage.push({provider:r,stages:t,source:"opencode",detail:`Claude Code login (${e.claudePath})`})}function Ub(e){let t={childEnv:{},imports:[],coverage:[],warnings:[],errors:[]};for(let[n,r]of e.providers){if(n===pn){NI(e,r,t);continue}let s=(f,p)=>t.coverage.push({provider:n,stages:r,source:f,detail:p}),o=Lb(n,e.userProviders),a=o.find((f)=>e.env[f]);if(a){s("env",a);continue}let l=e.apiKeys?.[n];if(l){let f=o[0];if(f)t.childEnv[f]=l;else t.imports.push({id:`cred_diffloupe_${n.replace(/[^\w-]/g,"_")}`,integrationID:n,label:"API key",active:!0,value:{type:"key",key:l}});s("config",`apiKeys.${n}`);continue}let c=(e.saved??[]).filter((f)=>f.integrationID===n),u=c.filter((f)=>f.value?.type==="key"&&typeof f.value.key==="string");if(u.length){let f=u.find((p)=>p.active)??u[0];if(f)t.imports.push({...f,active:!0});s("opencode","opencode auth login");continue}let d=c.length>0;if(TI(n,e.userProviders)){s("providers",`providers.${n} in the OpenCode config`);continue}if(Fb.has(n)){s("ambient","credentials from the machine");continue}if(s("none",""),Nb[n]||d)t.errors.push(br(DI(n,r,o,d),r,e.openCodeDefault));else t.warnings.push(`No credential found for provider \`${n}\`; assuming OpenCode can reach it without one. If the review fails to authenticate, add apiKeys.${n} to ~/.config/diffloupe/config.json.`)}return t}async function Bb(e=process.env){try{let t=await re("opencode",["auth","export"],{env:e,allowFail:!0,timeoutMs:20000});if(t.code!==0)return;let n=JSON.parse(t.stdout);if(!Array.isArray(n))return;return n.filter((r)=>oo(r)&&typeof r.id==="string"&&typeof r.integrationID==="string"&&oo(r.value))}catch{return}}function qb(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}async function Hb(e=1e4){try{let t=await re("opencode",["api","GET","/api/model"],{allowFail:!0,timeoutMs:e});if(t.code!==0)return;let n=JSON.parse(t.stdout),r=qb(n)&&Array.isArray(n.data)?n.data:void 0;if(!r)return;return r.filter((s)=>qb(s)&&typeof s.id==="string"&&typeof s.providerID==="string")}catch{return}}function Kb(e,t,n=Zt,r){let s={errors:[],zeroCost:[]};for(let o of n){let a=e[o];if(a.provider===pn)continue;let l=t.filter((f)=>f.providerID===a.provider);if(!l.length)continue;let c=l.find((f)=>f.id===a.id||f.modelID===a.id),u=(f)=>s.errors.push(br(`Model \`${a.model}\` is not available in OpenCode: ${f}. Set \`${Xn[o]}\` in ~/.config/diffloupe/config.json or pass --model ${o}=<provider/model>.`,[o],r));if(!c){u(`provider \`${a.provider}\` has no model \`${a.id}\``);continue}let d=c.variants?.map((f)=>f.id)??[];if(a.variant&&!d.includes(a.variant)){u(d.length?`it has no variant \`${a.variant}\` (variants: ${d.join(", ")})`:`it has no variants, so \`#${a.variant}\` and effort cannot apply`);continue}if(c.cost&&c.cost.every((f)=>!f.input&&!f.output))s.zeroCost.push(o)}return s}function FI(e,t,n){let r=t.filter((o)=>e[o].source==="opencode"),s=r[0];if(!s||!n.modelFile)return;return{stages:r,hint:`\`${n.model}\` is OpenCode's default model, set in ${zr(n.modelFile)}. To review with another model, pass --model ${s}=<provider/model>, set \`${Xn[s]}\` in ~/.config/diffloupe/config.json, or set \`opencode.useDefaultModel\` to false there.`}}async function yl(e){let t=e.env??process.env,n=e.stages??Zt,r=e.openCodeUser??sh({env:t,...e.cwd?{cwd:e.cwd}:{}}),s=e.settings??{},o={env:t,...e.cli?{cli:e.cli}:{},settings:s,config:e.userConfig,...r.model?{openCodeModel:r.model}:{}},a=Bp(o),l=FI(a,n,r),c=qp(a,n),u=c.has(pn),d=u?(e.findClaude??(()=>zp(t)))():void 0,f={providers:c,env:t,...e.userConfig.apiKeys?{apiKeys:e.userConfig.apiKeys}:{},...r.providers?{userProviders:r.providers}:{},...d?{claudePath:d}:{},...l?{openCodeDefault:l}:{}},p=jb(f)?await(e.exportCredentials??(()=>Bb(t)))():void 0,h=Ub({...f,...p?{saved:p}:{}}),g=await(e.readCatalog??(()=>Hb()))(),w;if(u){let b=Rc(t),x=(e.readClaudeCatalog??(()=>Wp(b)))();w=Vp(a,n,x,b,l)}return{provider:vc(o),models:a,openCodeUser:r,credentials:h,...g?{catalog:Kb(a,g,n,l)}:{},...w?{claude:w}:{},...d?{claudePath:d}:{}}}function Gb(e){return[...e.credentials.errors,...e.catalog?.errors??[],...e.claude?.errors??[]]}function bl(e){return[...new Set([...e.catalog?.zeroCost??[],...e.claude?.zeroCost??[]])]}function vl(e,t){let n=Up(e);return e==="opencode"&&t.modelFile?`${n}, from ${zr(t.modelFile)}`:n}function Wb(e,t,n){let r=`cost limit $${e.toFixed(2)}`,s=t.filter((o)=>n.includes(o));if(!s.length)return r;if(s.length===t.length)return`${r} not enforced: the models report no cost (a Claude subscription or free model)`;return`${r} counts only ${t.filter((o)=>!s.includes(o)).join(", ")}; ${s.join(", ")} report no cost`}function Vb(e){return{provider:e.provider,model:e.models.review.model,modelMerge:e.models.coordinator.model,modelWalk:e.models.walkthrough.model,modelIntent:e.models.intent.model,effort:"",effortAux:"",providers:e.openCodeUser.providers??{},childEnv:e.credentials.childEnv,authImport:e.credentials.imports.length?JSON.stringify(e.credentials.imports):"",pluginStorage:e.claude?.seed.length?JSON.stringify(e.claude.seed):""}}function zb(e,t=Zt){let n={};for(let r of t)n[r]={model:e.models[r].model,source:e.models[r].source};return n}var $l={git:"https://git-scm.com/downloads",opencode:"https://opencode.ai/v2/docs/ (npm i -g @opencode/cli)",tilth:"https://crates.io/crates/tilth (cargo install tilth)",gh:"https://cli.github.com/ (then `gh auth login`)"},Ev={review:"model",coordinator:"modelMerge",walkthrough:"modelWalk",intent:"modelIntent"};function gP(e){let t={};for(let n of e){let r=n.indexOf("="),s=n.slice(0,r),o=n.slice(r+1);if(r<=0||!o||!(s in Ev))throw new _e(`--model expects stage=model-id with stage one of ${Object.keys(Ev).join(", ")}; got "${n}"`);t[s]=o}return t}async function uo(e){let t=e.intent?.trim();if(!t&&e.intentFile)t=(await Rl(e.intentFile,"utf8")).trim();let n=gP(e.model??[]);return{...e.kind==="diff"?{kind:"diff"}:{},...e.kind==="diff"&&e.walkthrough?{walkthrough:!0}:{},repo:et.resolve(e.repo??process.cwd()),...e.target?{target:e.target}:{},...e.base?{base:e.base}:{},...t?{intent:t}:{},...Object.keys(n).length?{models:n}:{},...e.effort?{effort:e.effort}:{},...e.maxCost!==void 0?{maxCostUsd:e.maxCost}:{},...e.maxRounds!==void 0?{maxRounds:e.maxRounds}:{},...e.config?{settingsFile:et.resolve(e.config)}:{},...e.full?{full:!0}:{},...e.github?{github:!0}:{},...e.head?{head:e.head}:{}}}function _P(e,t={}){let n=$n(e),o=["git",...t.kind==="diff"?t.walkthrough?["opencode"]:[]:["opencode","tilth"],...n.kind==="pr"?["gh"]:[]].filter((a)=>!Bun.which(a,{PATH:process.env.PATH??""}));if(o.length)throw new _e(["Missing required tools on PATH:",...o.map((a)=>` ${a}: ${$l[a]??""}`)].join(`
655
+ `))}function kf(e){return e!==null&&/^2\./.test(e)}function wP(e){return/\d+\.\d+(?:\.\d+)?/.exec(e)?.[0]??null}async function yP(){let e=Bun.which("opencode",{PATH:process.env.PATH??""});if(!e)return;let t=await re("opencode",["--version"],{allowFail:!0}).catch(()=>null),n=t&&t.code===0?wP(t.stdout):null;if(kf(n))return;throw new _e(`DiffLoupe needs OpenCode 2.x, but the opencode on PATH (${e}) is ${n??"an unknown version"}.
656
+ Install: ${$l.opencode}`)}async function Av(e,t,n,r={}){let s=e.kind??"review",o=s==="diff",a=o&&e.walkthrough===!0,l=e.fromRun,c=l?await gt(l).catch((te)=>{throw new _e(`cannot start from run ${l}: ${te instanceof Error?te.message:String(te)}`)}):void 0,u=c?EP(c.target):void 0;if(c?.repo.remote&&!o)throw new _e(`reviewing ${c.repo.slug??"this repository"} needs a local clone; run diffloupe review from a clone of it`);for(let te of["github","head"])if(e[te]&&(o||c||$n(e.target).kind!=="pr"))throw new _e(`--${te} needs a review of a pull request target`);if(_P(u?u.kind==="pr"?`#${u.pr}`:"":e.target,{kind:s,walkthrough:a}),!o||a)await yP();let d=et.resolve(e.repo??t),f=c?void 0:$n(e.target),p=o&&f?.kind==="pr"&&f.repo&&await Ab(d,f)?{...f,repo:f.repo}:void 0;if(p)await Ob(of(p.repo),p.repo);let h=c?c.repo.root:p?of(p.repo):d,g=p!==void 0||c?.repo.remote===!0,w=e.intent?.trim()||c?.intent.stated||void 0,b=await Jr(),x=e.settingsFile?await _l(et.resolve(e.settingsFile)):{},S=o?a?["walkthrough"]:[]:Zt,P=S.length?await(r.resolveSetup??yl)({cli:{...e.models?{models:e.models}:{},...e.effort?{effort:e.effort}:{}},settings:x,userConfig:b,stages:S,cwd:h}):void 0,M=P?Gb(P):[];if(M.length)throw new _e(M.join(`
657
+ `));let k={artifacts:fr(),out:et.join(cn(),"scratch"),...Tb(x),...P?Vb(P):{}},E=o?void 0:e.maxCostUsd??b.maxCostUsd,F=o?void 0:Db(x),L=c&&u?await Cb(h,u,c.base,c.head,{isTaken:$f}):p?await Ib(h,p,{isTaken:$f}):await Eb(h,e.target,{...e.base?{base:e.base}:{},...e.head?{head:e.head}:{},isTaken:$f}),{target:O,changes:U,tag:I}=L,j=L.pullRequest,H=o?"Diff of":"Reviewing";n(j?`${H} ${O.slug}#${j.number}: ${j.title}`:`${H} ${O.slug} (${CP(L.spec)})`);let ve=L.commits===void 0?"":` (${L.commits} commit${L.commits===1?"":"s"})`;if(n(` ${O.base.slice(0,12)}..${O.head.slice(0,12)}${ve}`),n(` ${U.files} file(s) changed, +${U.insertions} -${U.deletions}`),n(` run ${I}`),P){for(let te of S){let we=P.models[te];n(` ${te}: ${we.model} (${vl(we.source,P.openCodeUser)})`)}for(let te of P.credentials.warnings)n(` warning: ${te}`)}if(E!==void 0)n(` ${Wb(E,S,P?bl(P):[])}`);if(L.skippedUntracked.length){n(` skipped ${L.skippedUntracked.length} untracked file(s) over 1 MB:`);for(let te of L.skippedUntracked)n(` ${te}`)}let Re=new Date().toISOString(),ne={root:h,...O.slug?{slug:O.slug}:{},...g?{remote:g}:{}},ce=c?c.target:await AP(h,L),qe=c?c.untrackedSkipped:L.skippedUntracked,ze=await wb(I),Je=await oe("git",["-C",h,"diff","--no-color","--no-ext-diff","--full-index","-M",O.base,O.head]);await Ur(et.join(ze,"diff.patch"),Je);let Xe=e.full===!0,nt=e.github===!0,be=o||nt?void 0:await xb(ne,ce,Re),Te=be?await RP(h,be,O.head):void 0;if(Te?.run.findings.length)n(` ${Te.run.findings.length} finding(s) from prior run ${Te.run.id}`);let me=o?void 0:Te?await SP(Te.run)+1:1;if(me!==void 0&&me>1){if(n(Xe?` round ${me}, full review (--full)`:` round ${me}: reviewing what changed since ${Te?.run.head.slice(0,12)??"the last review"} (--full to review everything)`),me>xP)n(` warning: this change has been reviewed ${me-1} times; later rounds mostly find smaller problems`)}let G=await $P(),T=P?zb(P,S):void 0;await Promise.resolve().then(() => Sf());let z=kv({id:I,createdAt:Re,repo:ne,target:ce,base:O.base,head:O.head,...w?{statedIntent:w}:{},patch:Je,untrackedSkipped:qe,coreSource:G,...be?{priorRunId:be}:{},...me!==void 0?{round:me}:{},...T?{models:T}:{},...o?{kind:s}:{}});return await ji(z),{id:I,kind:s,walkthrough:a,dir:ze,createdAt:Re,repo:h,target:O,reviewTarget:ce,config:k,...E!==void 0?{maxCostUsd:E}:{},...!o&&e.maxRounds!==void 0?{maxRounds:e.maxRounds}:{},...w?{intent:w}:{},...F?{instructions:F}:{},patch:Je,...be?{priorRunId:be}:{},...Te?{previous:Te}:{},...me!==void 0?{round:me}:{},full:Xe,github:nt,untrackedSkipped:qe,coreSource:G,...T?{models:T}:{},pending:z}}async function Ov(e,t){let{id:n,dir:r}=e;await Promise.resolve().then(() => Sf());let a=e.pending,l=Promise.resolve(),c=(h)=>{if(h.type!=="units"){t.onProgress(h);return}a=$v(Cv(e),h.units,h.byClass),t.onProgress(hb(a));let g=a;l=l.then(()=>ji(g).catch((w)=>{t.log(` could not save the grouped run: ${w instanceof Error?w.message:String(w)}`)}))},u;try{u=e.kind==="diff"?await ub({repo:e.repo,target:e.target,tag:n,config:e.config,walkthrough:e.walkthrough,signal:t.signal,...e.intent?{intent:e.intent}:{},onProgress:c}):await yg({repo:e.repo,target:e.target,tag:n,config:e.config,signal:t.signal,...e.maxCostUsd!==void 0?{maxCostUsd:e.maxCostUsd}:{},...e.maxRounds!==void 0?{maxRounds:e.maxRounds}:{},...e.round!==void 0?{round:e.round}:{},...e.intent?{intent:e.intent}:{},...e.instructions?{instructions:e.instructions}:{},...vP(e),onProgress:c})}catch(h){let g=t.signal.aborted;throw await l,await ji({...a,status:g?"cancelled":"failed",...g?{}:{error:h instanceof Error?h.message:String(h)}}),h}if(u.markdownPath){let h=e.config.artifacts??fr();await Rf(et.join(h,"runs",`${n}.json`),et.join(r,"raw","record.json")),await Rf(u.markdownPath,et.join(r,"raw","review.md")),await Rf(et.join(h,"reviews",`${n}.payloads.json`),et.join(r,"raw","payloads.json"))}else if(u.record)await Ur(et.join(r,"raw","record.json"),`${JSON.stringify(u.record,null,2)}
658
+ `);await Ur(et.join(r,"raw","units.json"),`${JSON.stringify(u.units,null,2)}
659
+ `),await Ur(et.join(r,"raw","byClass.json"),`${JSON.stringify(u.byClass,null,2)}
660
+ `);let d;await l;try{d=xf({...Cv(e),result:u,...e.previous?{previous:e.previous}:{},log:t.log})}catch(h){let g=`building run.json: ${h instanceof Error?h.message:String(h)}`;throw await ji({...a,status:"failed",error:g}),Error(g,{cause:h})}let{roundLimit:f}=u;if(f)d={...d,round:f.round,meta:{...d.meta,roundLimit:f}};await ji(d);let p=e.kind==="diff"||u.record!==null;if(e.kind==="review")t.log(` anchors: ${Ra(d)}`);if(e.github&&e.kind==="review"&&p)await bP(r,d);return{run:d,reviewed:p,...f?{roundLimit:f}:{}}}async function bP(e,t){let n=Qs(t,{includeOverCap:!0,github:!0});await Ur(et.join(e,"raw",Or),n);let r=t.findings.length+t.overCapFindings.length;if(r===0)return;let s=et.join(e,"raw","payloads.json"),o;try{o=JSON.parse(await Rl(s,"utf8"))}catch{return}let a=o.summary?.body?.body;if(typeof a!=="string"||!o.summary?.body)return;let l=t.target.kind==="pr"?ys(t.target.number,t.head):void 0;function*c(){yield n;for(let p=1;p<=r;p++)yield Qs(t,{includeOverCap:!0,github:!0,shorten:{count:p,note:ag(p,l)}})}let u=lg(a,c(),{artifact:l});o.summary.body.body=u,await Ur(s,`${JSON.stringify(o,null,2)}
661
+ `);let d=et.join(e,"raw","review.md"),f=await Rl(d,"utf8").catch(()=>{return});if(f?.includes(a))await Ur(d,f.replace(a,()=>u))}function Cv(e){return{id:e.id,createdAt:e.createdAt,repo:e.pending.repo,target:e.reviewTarget,base:e.target.base,head:e.target.head,...e.intent?{statedIntent:e.intent}:{},patch:e.patch,untrackedSkipped:e.untrackedSkipped,coreSource:e.coreSource,...e.priorRunId?{priorRunId:e.priorRunId}:{},...e.round!==void 0?{round:e.round}:{},...e.models?{models:e.models}:{},...e.kind==="diff"?{kind:e.kind}:{}}}function vP(e){return{local:!e.github,...e.previous?{prior:db(e.previous.run)}:{},...e.previous&&!e.full?{priorHead:e.previous.run.head}:{}}}var xP=3;async function SP(e,t=gt){if(e.round!==void 0)return e.round;let n=async(r,s)=>{if(!r||s.has(r))return 1;s.add(r);let o=await t(r).catch(()=>{return});if(!o)return 1;return 1+(o.round??await n(o.priorRunId,s))};return n(e.priorRunId,new Set)}async function RP(e,t,n){try{let r=await gt(t),s=await jr(t),o=Object.entries(s.findingStatus).filter(([,c])=>c==="dismissed").map(([c])=>c),a=new Map,l=[...new Set(r.findings.flatMap((c)=>[c.file,...(c.alsoAt??[]).map((u)=>u.file)]))];if(r.head!==n&&l.length)try{let c=await oe("git",["-C",e,"diff","-U0","--no-color","--no-ext-diff",r.head,n,"--",...l]);a=fb(c)}catch{a=void 0}return{run:r,dismissed:o,...a?{lineMap:a}:{}}}catch{return}}async function Rf(e,t){try{await mP(e,t)}catch{}}var Sl;async function $P(){if(Sl)return Sl;return Sl=await kP(import.meta.dir),Sl}async function kP(e,t=Jn){if(e.split(/[\\/]/).includes("node_modules"))return`diffloupe@${t}`;try{let n=(await oe("git",["-C",e,"rev-parse","--short=12","HEAD"])).trim();return`diffloupe@${t}+${n}`}catch{return`diffloupe@${t}`}}var $f=(e)=>hP(Ve(e));function EP(e){switch(e.kind){case"pr":return{kind:"pr",pr:e.number};case"branch":return{kind:"branch",branch:e.spec};case"commit":return{kind:"commit",rev:e.spec};case"range":return $n(`range:${e.spec}`);default:return{kind:e.kind}}}function CP(e){switch(e.kind){case"branch":return`branch ${e.branch}`;case"commit":return`commit ${e.rev}`;case"range":return`range ${e.from}${e.mergeBase?"...":".."}${e.to}`;default:return e.kind}}async function AP(e,t){let{spec:n,pullRequest:r}=t;if(n.kind==="pr")return{kind:"pr",number:n.pr,url:r?.url??"",title:r?.title??"",author:r?.author.login??"",baseRef:r?.baseRefName??"",headRef:r?.headRefName??"",state:r?.state??"",isDraft:r?.isDraft??!1};if(n.kind==="branch")return{kind:"branch",spec:n.branch};if(n.kind==="commit")return{kind:"commit",spec:n.rev};if(n.kind==="range")return{kind:"range",spec:`${n.from}${n.mergeBase?"...":".."}${n.to}`};let s;try{s=(await oe("git",["-C",e,"rev-parse","--abbrev-ref","HEAD"])).trim()||void 0}catch{}return{kind:n.kind,...s?{branch:s}:{}}}async function Iv(e){try{return await Rl(et.join(e,"raw","review.md"),"utf8")}catch{return}}var Ef=Fo.engines.bun.replace(/^>=\s*/,"");function Cf(e,t){let n=e.split(".").map((s)=>Number.parseInt(s,10)||0),r=t.split(".").map((s)=>Number.parseInt(s,10)||0);for(let s=0;s<Math.max(n.length,r.length);s++){let o=(n[s]??0)-(r[s]??0);if(o!==0)return o>0}return!0}function PP(e){return/\d+\.\d+(?:\.\d+)?/.exec(e)?.[0]??null}function Pv(e){if(e<1024)return`${e} B`;let t=["KB","MB","GB"],n=e/1024,r=0;while(n>=1024&&r<t.length-1)n/=1024,r++;return`${n.toFixed(n<10?1:0)} ${t[r]}`}async function fo(e,t,n,r,s){if(!s&&!e.which(t))return{name:t,status:n,detail:`not found on PATH. Install: ${$l[t]??t}`};let o=await e.exec(s??t,["--version"]),a=o&&o.code===0?PP(o.output):null,l=r?.(a)??{status:"ok"},c=[a??"version unknown",l.note].filter(Boolean).join(", ");return{name:t,status:l.status,detail:c}}async function MP(e){let t=[];if(e.platform==="win32")t.push({name:"platform",status:"warn",detail:"native Windows is best-effort (WSL is better tested). Cancelling a review can leave behind programs an agent started through Git Bash."});t.push({name:"bun",status:Cf(e.bunVersion,Ef)?"ok":"fail",detail:Cf(e.bunVersion,Ef)?e.bunVersion:`${e.bunVersion}, needs ${Ef} or newer`}),t.push(await fo(e,"git","fail")),t.push(await fo(e,"opencode","fail",(a)=>kf(a)?{status:"ok"}:{status:"fail",note:"needs OpenCode 2.x (https://opencode.ai/v2/docs/)"})),t.push(await fo(e,"tilth","fail"));let n=await fo(e,"gh","warn");if(n.status==="warn")n.detail+=" (only needed to review pull requests)";else{let a=await e.exec("gh",["auth","status"]);if(!a||a.code!==0)n.status="warn",n.detail+=", not logged in: run `gh auth login` to review pull requests";else n.detail+=", logged in"}t.push(n);let r;try{r=await e.setup()}catch(a){t.push({name:"models",status:"fail",detail:a instanceof Error?a.message:String(a)})}if(r){let a=r.openCodeUser.files??[];t.push({name:"opencode config",status:"ok",detail:a.length?a.map((u)=>u.kind==="system"?`${zr(u)}, also applies to reviewer runs`:zr(u)).join("; "):"no config files found"});for(let u of Zt){let d=r.models[u];t.push({name:`model: ${u}`,status:"ok",detail:`${d.model} (${vl(d.source,r.openCodeUser)})`})}if(!r.catalog)t.push({name:"model catalog",status:"warn",detail:"could not ask OpenCode for its models; not checked"});else for(let u of r.catalog.errors)t.push({name:"model catalog",status:"fail",detail:u});if(r.claude)for(let u of r.claude.errors)t.push({name:"claude-agent models",status:"fail",detail:u});let l=r.claudePath;if(l){let u=(d)=>d&&Cf(d,Sc)?{status:"ok",note:l}:{status:"fail",note:`claude-agent needs Claude Code ${Sc} or newer`};t.push(await fo(e,"claude","fail",u,l))}let c=bl(r);if(c.length>0){let u=r.claude?.zeroCost.length?" (claude-agent on a Claude subscription reports $0)":"";t.push({name:"cost",status:"warn",detail:`no cost reported for ${c.join(", ")}${u}: --max-cost cannot count their spend`})}for(let u of r.credentials.coverage){if(u.source==="none")continue;t.push({name:`credential: ${u.provider}`,status:"ok",detail:`${u.source}: ${u.detail}`})}for(let u of r.credentials.warnings)t.push({name:"credentials",status:"warn",detail:u});for(let u of r.credentials.errors)t.push({name:"credentials",status:"fail",detail:u})}let s=await e.dataSizes(),o=Object.values(s).reduce((a,l)=>a+l,0);return t.push({name:"data dir",status:"ok",detail:`${cn()}: ${Pv(o)} (${Object.entries(s).map(([a,l])=>`${a} ${Pv(l)}`).join(", ")}). \`diffloupe runs prune\` removes old runs`}),t}async function kl(e){let t=0,n;try{n=await OP(e,{withFileTypes:!0})}catch{return 0}for(let r of n){let s=Mv.join(e,r.name);if(r.isDirectory())t+=await kl(s);else if(r.isFile())t+=await IP(s).then((o)=>o.size,()=>0)}return t}async function TP(e,t){try{let n=await re(e,t,{allowFail:!0,timeoutMs:20000});return{code:n.code,output:`${n.stdout}
662
+ ${n.stderr}`}}catch{return null}}function DP(e,t){return e.some((n)=>n.status==="fail"||t&&n.status==="warn")}var NP={ok:po.default.green("ok "),warn:po.default.yellow("warn"),fail:po.default.red("FAIL")};function Tv(){return new It("doctor").description("Check tools, models, credentials and disk use").option("--config <file>","Per-repo review settings, as passed to review").option("--strict","Exit 1 on warnings too, for CI (a model with no reported cost, such as claude-agent on a subscription, makes --max-cost unenforceable)").option("--json","Print the checks as a JSON array instead of text").action(async(e)=>{let t=await MP({platform:process.platform,bunVersion:Bun.version,which:(n)=>Bun.which(n),exec:TP,setup:async()=>{let n=e.config?await _l(Mv.resolve(e.config)):{};return yl({settings:n,userConfig:await Jr(),cwd:process.cwd()})},dataSizes:async()=>({runs:await kl(ro()),artifacts:await kl(fr()),scratch:await kl(io())})});if(e.json)console.log(JSON.stringify(t,null,2));else for(let n of t)console.log(`${NP[n.status]} ${po.default.bold(n.name)}: ${n.detail}`);if(DP(t,e.strict===!0))process.exit(1)})}var Wf=Do(Qi(),1);kr();Cr();var FP="diffloupe/gate";function Dv(e,t){if(e&&Nt.includes(e))return e;return Object.entries(tt).find(([,r])=>t.includes(r.badge))?.[0]??"unknown"}function LP(e,t,n){let r=e.comments[0];if(!r||!In(r.body,r.authorType))return null;let s=li(r.body,"inline");if(!s)return null;if(e.resolved&&(n||e.resolvedBy!==t))return null;if(sa(e.comments.map((c)=>({body:c.body,user:{type:c.authorType},...c.replyTo?{in_reply_to_id:c.replyTo}:{}}))).has(r.id))return null;let a=e.comments.some((c)=>In(c.body,c.authorType,"reply")&&li(c.body,"reply")?.fields.dispute==="upheld"),l=Ut(r.body).split(`
663
+ `).find((c)=>c.trim())?.replace(/^#+\s*/,"").trim()??"";return{fp:s.fields.fp??null,severity:Dv(s.fields.sev,r.body),file:s.fields.file??e.file??null,line:s.fields.line??(e.line?String(e.line):null),title:l,url:r.url||null,where:"thread",...e.outdated?{outdated:!0}:{},...a?{upheld:!0}:{},...s.fields.pre==="1"?{preexisting:!0}:{}}}function jP(e){let t=Ut(e).replace(/^\s*[-*]\s*/,"").trim();for(let{badge:r}of Object.values(tt))if(t.startsWith(r))t=t.slice(r.length).trim();let n=t.lastIndexOf(" \u2014 ");return n>0?t.slice(0,n):t}function UP(e){let t=null;for(let n of e){if(!In(n.body??"",n.user?.type,"summary"))continue;if(!t||n.id>t.id)t=n}return t}function BP(e,t,n={}){let r=[],s=new Set;for(let u of e.threads){let d=LP(u,e.author,n.countAuthorResolved===!0);if(!d)continue;if(d.fp){if(s.has(d.fp))continue;s.add(d.fp)}r.push(d)}if(!t?.body)return r;let o=ai(t.body),a=nu(o),l=new Set(a.filter((u)=>u.outcome==="withdrawn").map((u)=>u.fp)),c=new Set(a.filter((u)=>u.outcome==="upheld").map((u)=>u.fp));for(let u of o.split(`
664
+ `))for(let d of rn(u)){let f=d.fields.fp;if(d.kind!=="summary-item"||!f||s.has(f)||l.has(f))continue;s.add(f),r.push({fp:f,severity:Dv(d.fields.sev,u),file:d.fields.file??null,line:d.fields.line??null,title:jP(u),url:t.html_url??null,where:"summary",...c.has(f)?{upheld:!0}:{},...d.fields.pre==="1"?{preexisting:!0}:{}})}return r}function qP(e,t){let n=Nt.indexOf(t);return e.filter((r)=>!r.preexisting&&r.severity!=="unknown"&&Nt.indexOf(r.severity)<=n)}function HP(e,t,n){let r=UP(t),s=BP(e,r,n),o=qP(s,n.failOn),a=n.overrideLabel&&e.labels.includes(n.overrideLabel)?n.overrideLabel:null,l=n.reviewMissing===!0&&!r;return{pr:e.number,url:e.url,head:e.headSha,failOn:n.failOn,open:s,matched:o,override:a,summaryUrl:r?.html_url??null,unreviewed:l,fails:(o.length>0||l)&&!a}}function Af(e,t){return`${e} ${t}${e===1?"":"s"}`}function Nv(e){let t=`at ${e.failOn} or above`,n=e.unreviewed?e.override?`Not reviewed: the review failed, passed by the ${e.override} label`:"Not reviewed: the review failed and no earlier review reached this PR":!e.matched.length?`No open findings ${t}`:e.override?`${Af(e.matched.length,"open finding")} ${t}, passed by the ${e.override} label`:`${Af(e.matched.length,"open finding")} ${t}`;return n.length>140?`${n.slice(0,139)}\u2026`:n}function Fv(e){let t=[`PR #${e.pr}: ${Nv(e)}`],n=(o)=>{let a=o.file?`${o.file}${o.line?`:${o.line}`:""}`:"(no file)",l=[o.where==="summary"?"in the summary":"",o.outdated?"outdated":"",o.upheld?"upheld after a dispute, needs a person":"",o.preexisting?"pre-existing, not counted":""].filter(Boolean);return` ${o.severity.padEnd(12)} ${a} ${o.title}${l.length?` (${l.join(", ")})`:""}${o.url?`
665
+ ${" ".repeat(15)}${o.url}`:""}`},r=e.open.filter((o)=>!e.matched.includes(o));if(e.matched.length)t.push("",`Open at ${e.failOn} or above:`,...e.matched.map(n));if(r.length)t.push("","Other open findings:",...r.map(n));let s=e.open.filter((o)=>o.severity==="unknown").length;if(s)t.push("",`${Af(s,"finding")} with no readable severity; not counted against --fail-on.`);return t}async function Lv(e,t,n,r){let[s,o]=await Promise.all([r.readThreads(e,t),r.readComments(e,t)]),a=HP(s,o,n);if(n.status)await r.gh(["api","--method","POST",`repos/${e}/statuses/${n.status.sha??a.head}`,"-f",`state=${a.fails?"failure":"success"}`,"-f",`context=${FP}`,"-f",`description=${Nv(a)}`,"-f",`target_url=${a.summaryUrl??a.url}`]);return a}import KM from"path";var un=Do(Qi(),1);function ho(e){switch(e.type){case"stage":return`\xBB ${e.stage.replaceAll("_"," ")}`;case"log":return e.message;case"cost":return null;case"groups":{let t=e.groups.filter((n)=>n.files.length).length;return` ${e.files.length} file(s) in ${t} group(s)`}case"budget":return` cost limit reached: $${e.totalUsd.toFixed(2)} of $${e.limitUsd.toFixed(2)}, ${e.skippedSlices} slice(s) not started`;case"slice":{let t=`[${e.index+1}/${e.total}]`;if(e.status==="started")return` ${t} ${e.title}`;let n=e.costUsd!==void 0?` $${e.costUsd.toFixed(2)}`:"",r=e.wallMs!==void 0?` ${Math.round(e.wallMs/1000)}s`:"",s=e.findings!==void 0?` ${e.findings} finding(s)`:"";return` ${t} ${e.status==="ok"?"done":"FAILED"}${n}${r}${s} \u2014 ${e.title}`}case"done":{if(e.kind==="diff"){let r=e.costUsd?` \xB7 $${e.costUsd.toFixed(2)}`:"";return`${e.files??0} file(s) changed${r} \xB7 ${(e.wallMs/1000).toFixed(1)}s`}if(e.roundLimit)return`Not reviewed: this change already had ${e.roundLimit} round(s) of review (--max-rounds).`;if(e.noChanges)return"No code changes to review.";let t=e.carriedOver??0;return`${t?`${e.findings-t} new finding(s), ${t} carried over`:`${e.findings} finding(s)`} \xB7 $${e.costUsd.toFixed(2)} \xB7 ${Math.round(e.wallMs/1000)}s`}case"cancelled":return"Run cancelled.";case"error":return`Run failed: ${e.message}`}}import Ol from"path";import KP from"path";import{appendFileSync as GP}from"fs";import{readFile as WP}from"fs/promises";function VP(e){return async(t,n)=>{let r=await e.prepare(t,n);return{id:r.id,pending:r.pending,execute:(s)=>e.execute(r,s)}}}function El(e){return VP({prepare:(t,n)=>Av(t,e,n),execute:Ov})}class Cl extends Error{activeRunId;constructor(e){super(e?`run ${e} is still running`:"a run is starting");this.activeRunId=e;this.name="RunBusyError"}}function jv(e){return KP.join(Ve(e),"events.jsonl")}async function Uv(e){let t;try{t=await WP(jv(e),"utf8")}catch{return[]}let n=[];return t.split(`
666
+ `).forEach((r,s)=>{if(!r.trim())return;try{let o=JSON.parse(r);n.push(typeof o.seq==="number"?o:{...o,seq:s+1})}catch{}}),n}class mo{prepare;active=null;starting=!1;watchers=new Set;constructor(e){this.prepare=e}watch(e){return this.watchers.add(e),()=>this.watchers.delete(e)}get activeRunId(){return this.active?.id??null}isActive(e){return this.active?.id===e}pendingRun(e){return this.active?.id===e?this.active.pending:void 0}async start(e){if(this.active||this.starting)throw new Cl(this.activeRunId);this.starting=!0;let t=[],n;try{n=await this.prepare(e,(a)=>t.push(a))}finally{this.starting=!1}let r=new AbortController,s={id:n.id,controller:r,seq:0,subscribers:new Set,pending:n.pending,done:Promise.resolve({status:"cancelled"})};this.active=s;let o=(a)=>this.emit(s,a);for(let a of t)o({type:"log",message:a});return s.done=n.execute({signal:r.signal,onProgress:o,log:(a)=>o({type:"log",message:a})}).then(({run:a,reviewed:l,roundLimit:c})=>(o({type:"done",status:"complete",findings:a.findings.length,carriedOver:a.findings.filter((u)=>u.carriedFrom).length,costUsd:a.meta.costUsd,wallMs:a.meta.wallMs,...c?{roundLimit:c.maxRounds}:l?{}:{noChanges:!0},...a.meta.kind==="diff"?{kind:"diff",files:a.files.length}:{}}),{status:"complete",run:a,reviewed:l,...c?{roundLimit:c}:{}}),(a)=>{if(r.signal.aborted||a instanceof qt)return o({type:"cancelled"}),{status:"cancelled"};let l=a instanceof Error?a.message:String(a);return o({type:"error",message:l}),{status:"failed",error:l}}).finally(()=>{if(this.active===s)this.active=null}),{id:n.id,done:s.done}}cancel(e){let t=this.active;if(!t||t.id!==e)return;return t.controller.abort(),t.done}subscribe(e,t){let n=this.active;if(!n||n.id!==e)return;return n.subscribers.add(t),{lastSeq:n.seq,unsubscribe:()=>n.subscribers.delete(t)}}emit(e,t){if(t.type==="groups")e.pending=pb(e.pending,t);let n={...t,seq:++e.seq,at:new Date().toISOString()};try{GP(jv(e.id),`${JSON.stringify(n)}
667
+ `)}catch{}let r=[...[...this.watchers].map((s)=>()=>s(e.id,n)),...[...e.subscribers].map((s)=>()=>s(n))];for(let s of r)try{s()}catch{}}}import{copyFile as zP,mkdir as qv,writeFile as JP}from"fs/promises";import Al from"path";function Hv(e,t){let n={blocker:0,"should-fix":0,"nice-to-have":0,question:0};for(let o of e?.findings??[])n[o.severity]++;let r=(e?.findings??[]).filter(yu(e?.meta.postMinSeverity)).length,s=e?.target.kind==="pr"?e.target.number:null;return{id:t.id,status:t.status,reviewed:t.status==="complete",skipReason:t.skipReason??null,pr:s,base:e?.base??null,head:e?.head??null,runDir:t.runDir,outDir:t.outDir??null,payloads:t.payloads??null,artifactName:s!==null&&e?ys(s,e.head):null,costUsd:e?.meta.costUsd??0,wallMs:e?.meta.wallMs??0,budgetStopped:e?.meta.budgetStopped===!0,skippedSlices:t.skippedSlices??0,findings:{total:(e?.findings.length??0)+(e?.overCapFindings.length??0),posted:(e?.findings.length??0)-r,minor:r,bySeverity:n},progress:e?.roundProgress??null,round:t.round??e?.round??1,incremental:e?.meta.reviewScope==="incremental",version:Jn}}var Bv=[["raw/review.md","review.md"],["raw/payloads.json","payloads.json"],["raw/record.json","record.json"],["raw/units.json","units.json"],["raw/byClass.json","byClass.json"],[`raw/${Or}`,Or],["run.json","run.json"]];async function Kv(e,t,n={}){await qv(t,{recursive:!0});let r=Ve(e),s=`${e}.detail.md`,a=[...(n.payloads===!1?Bv.filter(([,c])=>c!=="payloads.json"):Bv).map(([c,u])=>[Al.join(r,c),u]),[Al.join(fr(),"reviews",s),s]];return(await Promise.all(a.map(async([c,u])=>{try{return await zP(c,Al.join(t,u)),u}catch(d){if(d.code!=="ENOENT")throw d;return null}}))).filter((c)=>c!==null)}async function Gv(e,t){await qv(e,{recursive:!0}),await JP(Al.join(e,"result.json"),`${JSON.stringify(t,null,2)}
668
+ `)}function Wv(e,t){let n=Nt.indexOf(t);return e.findings.some((r)=>Nt.indexOf(r.severity)<=n)}async function Vv(e){let t=(h)=>console.error(h),n=new mo(El(process.cwd())),r=0;n.watch((h,g)=>{if(g.type==="budget")r=g.skippedSlices;let w=ho(g);if(w)t(w)});let s;try{s=await n.start(await uo(e))}catch(h){return t(`Error: ${h instanceof Error?h.message:String(h)}`),2}let o=go(()=>{t(`
669
+ Cancelling: stopping agents and removing the worktree (Ctrl+C again to exit now)...`),n.cancel(s.id)}),a=await s.done;o();let l=Ve(s.id),c=a.status==="complete"?a.run:await gt(s.id).catch(()=>null),u=a.status==="complete"?a.reviewed?"complete":"skipped":a.status,d=a.status==="complete"?a.roundLimit:void 0,f=u!=="skipped"?null:d?"round-limit":"no-code-files",p=await XP(s.id,c,u,f,r,e);if(e.json)process.stdout.write(`${JSON.stringify(p,null,2)}
670
670
  `);if(a.status==="cancelled")return t(`Run saved as cancelled: ${l}`),130;if(a.status==="failed")return t(`Run saved as failed: ${l}`),1;if(t(`Run saved: ${l} (diffloupe runs show ${s.id})
671
- `),d)return t(`Not reviewed: round ${d.round} is past --max-rounds ${d.maxRounds}`),4;if(!e.json){if(e.kind==="diff")process.stdout.write(`${Ty(a.run)}
672
- `);else if(a.reviewed){let h=e.markdown?await av(l):void 0;process.stdout.write(h??`${Fy(a.run)}
673
- `)}}if(e.failOn&&a.reviewed&&Rv(a.run,e.failOn))return t(`Failing: a finding is at or above ${e.failOn}`),3;return 0}async function uP(e,t,n,r,s,o){let a=Ve(e),l=o.out?bl.resolve(o.out):null,c=n==="complete"||r==="round-limit",u=bl.join(a,"raw","payloads.json"),d=c&&await Bun.file(u).exists()?u:null;if(l)d=(await vv(e,l,{payloads:c})).includes("payloads.json")?bl.join(l,"payloads.json"):null;let f=bv(t,{id:e,status:n,runDir:a,outDir:l,payloads:d,skippedSlices:s,...o.github?{round:await dP(a)}:{},skipReason:r});if(l)await xv(l,f);return f}async function dP(e){try{let t=await Bun.file(bl.join(e,"raw","record.json")).json();return typeof t.runs==="number"?t.runs:void 0}catch{return}}function oo(e){let t=!1,n=()=>{if(t)process.exit(130);t=!0,e()};return process.on("SIGINT",n),process.on("SIGTERM",n),()=>{process.off("SIGINT",n),process.off("SIGTERM",n)}}import fP from"os";import{existsSync as pP,readFileSync as hP}from"fs";var mP=new Set(["true","false","none",":","0","1"]);function gP(){if(process.platform!=="linux")return!1;if(fP.release().toLowerCase().includes("microsoft"))return!0;try{let e=hP("/proc/version","utf8").toLowerCase();return e.includes("microsoft")||e.includes("wsl")}catch{return!1}}function _P(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("/mnt/")||e.toLowerCase().endsWith(".exe")}function wP(e,t){let n=t.browser?.trim()&&!mP.has(t.browser.trim().toLowerCase())?t.browser.trim():void 0;if(t.wsl){if(!n)return["cmd.exe","/c","start","",e];if(_P(n))return["cmd.exe","/c","start","",n,e];return[n,e]}if(n)return[n,e];if(t.platform==="darwin")return["open",e];if(t.platform==="win32")return["cmd.exe","/c","start","",e];return["xdg-open",e]}async function $v(e){let t=gP(),n=wP(e,{browser:process.env.BROWSER,wsl:t,platform:process.platform});try{return await Bun.spawn(n,{stdio:["ignore","ignore","ignore"],...t&&n[0]==="cmd.exe"&&pP("/mnt/c")?{cwd:"/mnt/c"}:{}}).exited===0}catch{return!1}}var _f=(e,t,n)=>(r,s)=>{let o=-1;return a(0);async function a(l){if(l<=o)throw Error("next() called multiple times");o=l;let c,u=!1,d;if(e[l])d=e[l][0][0],r.req.routeIndex=l;else d=l===e.length&&s||void 0;if(d)try{c=await d(r,()=>a(l+1))}catch(f){if(f instanceof Error&&t)r.error=f,c=await t(f,r),u=!0;else throw f}else if(r.finalized===!1&&n)c=await n(r);if(c&&(r.finalized===!1||u))r.res=c;return r}};var kv=Symbol();var Ev=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,o=(e instanceof vl?e.raw.headers:e.headers).get("Content-Type");if(o?.startsWith("multipart/form-data")||o?.startsWith("application/x-www-form-urlencoded"))return yP(e,{all:n,dot:r});return{}};async function yP(e,t){let n=await e.formData();if(n)return bP(n,t);return{}}function bP(e,t){let n=Object.create(null);if(e.forEach((r,s)=>{if(!(t.all||s.endsWith("[]")))n[s]=r;else vP(n,s,r)}),t.dot)Object.entries(n).forEach(([r,s])=>{if(r.includes("."))xP(n,r,s),delete n[r]});return n}var vP=(e,t,n)=>{if(e[t]!==void 0)if(Array.isArray(e[t]))e[t].push(n);else e[t]=[e[t],n];else if(!t.endsWith("[]"))e[t]=n;else e[t]=[n]},xP=(e,t,n)=>{let r=e,s=t.split(".");s.forEach((o,a)=>{if(a===s.length-1)r[o]=n;else{if(!r[o]||typeof r[o]!=="object"||Array.isArray(r[o])||r[o]instanceof File)r[o]=Object.create(null);r=r[o]}})};var yf=(e)=>{let t=e.split("/");if(t[0]==="")t.shift();return t},Av=(e)=>{let{groups:t,path:n}=RP(e),r=yf(n);return SP(r,t)},RP=(e)=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(n,r)=>{let s=`@${r}`;return t.push([s,n]),s}),{groups:t,path:e}},SP=(e,t)=>{for(let n=t.length-1;n>=0;n--){let[r]=t[n];for(let s=e.length-1;s>=0;s--)if(e[s].includes(r)){e[s]=e[s].replace(r,t[n][1]);break}}return e},xl={},Cv=(e,t)=>{if(e==="*")return"*";let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;if(!xl[r])if(n[2])xl[r]=t&&t[0]!==":"&&t[0]!=="*"?[r,n[1],new RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],new RegExp(`^${n[2]}$`)];else xl[r]=[e,n[1],!0];return xl[r]}return null},Rl=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,(n)=>{try{return t(n)}catch{return n}})}},$P=(e)=>Rl(e,decodeURI),bf=(e)=>{let t=e.url,n=t.indexOf("/",t.indexOf(":")+4),r=n;for(;r<t.length;r++){let s=t.charCodeAt(r);if(s===37){let o=t.indexOf("?",r),a=t.slice(n,o===-1?void 0:o);return $P(a.includes("%25")?a.replace(/%25/g,"%2525"):a)}else if(s===63)break}return t.slice(n,r)};var Ov=(e)=>{let t=bf(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},Dr=(e,t,...n)=>{if(n.length)t=Dr(t,...n);return`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`},Sl=(e)=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),n=[],r="";return t.forEach((s)=>{if(s!==""&&!/\:/.test(s))r+="/"+s;else if(/\:/.test(s))if(/\?/.test(s)){if(n.length===0&&r==="")n.push("/");else n.push(r);let o=s.replace("?","");r+="/"+o,n.push(r)}else r+="/"+s}),n.filter((s,o,a)=>a.indexOf(s)===o)},wf=(e)=>{if(!/[%+]/.test(e))return e;if(e.indexOf("+")!==-1)e=e.replace(/\+/g," ");return e.indexOf("%")!==-1?Rl(e,vf):e},Iv=(e,t,n)=>{let r;if(!n&&t&&!/[%+]/.test(t)){let a=e.indexOf("?",8);if(a===-1)return;if(!e.startsWith(t,a+1))a=e.indexOf(`&${t}`,a+1);while(a!==-1){let l=e.charCodeAt(a+t.length+1);if(l===61){let c=a+t.length+2,u=e.indexOf("&",c);return wf(e.slice(c,u===-1?void 0:u))}else if(l==38||isNaN(l))return"";a=e.indexOf(`&${t}`,a+1)}if(r=/[%+]/.test(e),!r)return}let s={};r??=/[%+]/.test(e);let o=e.indexOf("?",8);while(o!==-1){let a=e.indexOf("&",o+1),l=e.indexOf("=",o);if(l>a&&a!==-1)l=-1;let c=e.slice(o+1,l===-1?a===-1?void 0:a:l);if(r)c=wf(c);if(o=a,c==="")continue;let u;if(l===-1)u="";else if(u=e.slice(l+1,a===-1?void 0:a),r)u=wf(u);if(n){if(!(s[c]&&Array.isArray(s[c])))s[c]=[];s[c].push(u)}else s[c]??=u}return t?s[t]:s},Pv=Iv,Mv=(e,t)=>Iv(e,t,!0),vf=decodeURIComponent;var Tv=(e)=>Rl(e,vf),vl=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(e,t="/",n=[[]]){this.raw=e,this.path=t,this.#e=n,this.#t={}}param(e){return e?this.#n(e):this.#s()}#n(e){let t=this.#e[0][this.routeIndex][1][e],n=this.#i(t);return n&&/\%/.test(n)?Tv(n):n}#s(){let e={},t=Object.keys(this.#e[0][this.routeIndex][1]);for(let n of t){let r=this.#i(this.#e[0][this.routeIndex][1][n]);if(r!==void 0)e[n]=/\%/.test(r)?Tv(r):r}return e}#i(e){return this.#e[1]?this.#e[1][e]:e}query(e){return Pv(this.url,e)}queries(e){return Mv(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((n,r)=>{t[r]=n}),t}async parseBody(e){return this.bodyCache.parsedBody??=await Ev(this,e)}#r=(e)=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let s=Object.keys(t)[0];if(s)return t[s].then((o)=>{if(s==="json")o=JSON.stringify(o);return new Response(o)[e]()});return t[e]=n[e]()};json(){return this.#r("text").then((e)=>JSON.parse(e))}text(){return this.#r("text")}arrayBuffer(){return this.#r("arrayBuffer")}blob(){return this.#r("blob")}formData(){return this.#r("formData")}addValidatedData(e,t){this.#t[e]=t}valid(e){return this.#t[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[kv](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,e]])=>e)}get routePath(){return this.#e[0].map(([[,e]])=>e)[this.routeIndex].path}};var $l={Stringify:1,BeforeStream:2,Stream:3},kP=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n};var ao=async(e,t,n,r,s)=>{if(typeof e==="object"&&!(e instanceof String)){if(!(e instanceof Promise))e=e.toString();if(e instanceof Promise)e=await e}let o=e.callbacks;if(!o?.length)return Promise.resolve(e);if(s)s[0]+=e;else s=[e];let a=Promise.all(o.map((l)=>l({phase:t,buffer:s,context:r}))).then((l)=>Promise.all(l.filter(Boolean).map((c)=>ao(c,t,!1,r,s))).then(()=>s[0]));if(n)return kP(await a,o);else return a};var Fv="text/plain; charset=UTF-8",xf=(e,t)=>({"Content-Type":e,...t}),Nv=class{#t;#e;env={};#n;finalized=!1;error;#s;#i;#r;#u;#l;#c;#a;#d;#f;constructor(e,t){if(this.#t=e,t)this.#i=t.executionCtx,this.env=t.env,this.#c=t.notFoundHandler,this.#f=t.path,this.#d=t.matchResult}get req(){return this.#e??=new vl(this.#t,this.#f,this.#d),this.#e}get event(){if(this.#i&&"respondWith"in this.#i)return this.#i;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#i)return this.#i;else throw Error("This context has no ExecutionContext")}get res(){return this.#r||=new Response(null,{headers:this.#a??=new Headers})}set res(e){if(this.#r&&e){e=new Response(e.body,e);for(let[t,n]of this.#r.headers.entries()){if(t==="content-type")continue;if(t==="set-cookie"){let r=this.#r.headers.getSetCookie();e.headers.delete("set-cookie");for(let s of r)e.headers.append("set-cookie",s)}else e.headers.set(t,n)}}this.#r=e,this.finalized=!0}render=(...e)=>(this.#l??=(t)=>this.html(t),this.#l(...e));setLayout=(e)=>this.#u=e;getLayout=()=>this.#u;setRenderer=(e)=>{this.#l=e};header=(e,t,n)=>{if(this.finalized)this.#r=new Response(this.#r.body,this.#r);let r=this.#r?this.#r.headers:this.#a??=new Headers;if(t===void 0)r.delete(e);else if(n?.append)r.append(e,t);else r.set(e,t)};status=(e)=>{this.#s=e};set=(e,t)=>{this.#n??=new Map,this.#n.set(e,t)};get=(e)=>this.#n?this.#n.get(e):void 0;get var(){if(!this.#n)return{};return Object.fromEntries(this.#n)}#o(e,t,n){let r=this.#r?new Headers(this.#r.headers):this.#a??new Headers;if(typeof t==="object"&&"headers"in t){let o=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[a,l]of o)if(a.toLowerCase()==="set-cookie")r.append(a,l);else r.set(a,l)}if(n)for(let[o,a]of Object.entries(n))if(typeof a==="string")r.set(o,a);else{r.delete(o);for(let l of a)r.append(o,l)}let s=typeof t==="number"?t:t?.status??this.#s;return new Response(e,{status:s,headers:r})}newResponse=(...e)=>this.#o(...e);body=(e,t,n)=>this.#o(e,t,n);text=(e,t,n)=>!this.#a&&!this.#s&&!t&&!n&&!this.finalized?new Response(e):this.#o(e,t,xf(Fv,n));json=(e,t,n)=>this.#o(JSON.stringify(e),t,xf("application/json",n));html=(e,t,n)=>{let r=(s)=>this.#o(s,t,xf("text/html; charset=UTF-8",n));return typeof e==="object"?ao(e,$l.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header("Location",!/[^\x00-\xFF]/.test(n)?n:encodeURI(n)),this.newResponse(null,t??302)};notFound=()=>(this.#c??=()=>new Response,this.#c(this))};var Ie="ALL",Dv="all",Lv=["get","post","put","delete","options","patch"],kl="Can not add a route since the matcher is already built.",El=class extends Error{};var jv="__COMPOSED_HANDLER";var EP=(e)=>e.text("404 Not Found",404),Uv=(e,t)=>{if("getResponse"in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text("Internal Server Error",500)},Bv=class e{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...Lv,Dv].forEach((o)=>{this[o]=(a,...l)=>{if(typeof a==="string")this.#t=a;else this.#s(o,this.#t,a);return l.forEach((c)=>{this.#s(o,this.#t,c)}),this}}),this.on=(o,a,...l)=>{for(let c of[a].flat()){this.#t=c;for(let u of[o].flat())l.map((d)=>{this.#s(u.toUpperCase(),this.#t,d)})}return this},this.use=(o,...a)=>{if(typeof o==="string")this.#t=o;else this.#t="*",a.unshift(o);return a.forEach((l)=>{this.#s(Ie,this.#t,l)}),this};let{strict:r,...s}=t;Object.assign(this,s),this.getPath=r??!0?t.getPath??bf:Ov}#e(){let t=new e({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#n=this.#n,t.routes=this.routes,t}#n=EP;errorHandler=Uv;route(t,n){let r=this.basePath(t);return n.routes.map((s)=>{let o;if(n.errorHandler===Uv)o=s.handler;else o=async(a,l)=>(await _f([],n.errorHandler)(a,()=>s.handler(a,l))).res,o[jv]=s.handler;r.#s(s.method,s.path,o)}),this}basePath(t){let n=this.#e();return n._basePath=Dr(this._basePath,t),n}onError=(t)=>(this.errorHandler=t,this);notFound=(t)=>(this.#n=t,this);mount(t,n,r){let s,o;if(r)if(typeof r==="function")o=r;else if(o=r.optionHandler,r.replaceRequest===!1)s=(c)=>c;else s=r.replaceRequest;let a=o?(c)=>{let u=o(c);return Array.isArray(u)?u:[u]}:(c)=>{let u=void 0;try{u=c.executionCtx}catch{}return[c.env,u]};s||=(()=>{let c=Dr(this._basePath,t),u=c==="/"?0:c.length;return(d)=>{let f=new URL(d.url);return f.pathname=f.pathname.slice(u)||"/",new Request(f,d)}})();let l=async(c,u)=>{let d=await n(s(c.req.raw),...a(c));if(d)return d;await u()};return this.#s(Ie,Dr(t,"*"),l),this}#s(t,n,r){t=t.toUpperCase(),n=Dr(this._basePath,n);let s={basePath:this._basePath,path:n,method:t,handler:r};this.router.add(t,n,[r,s]),this.routes.push(s)}#i(t,n){if(t instanceof Error)return this.errorHandler(t,n);throw t}#r(t,n,r,s){if(s==="HEAD")return(async()=>new Response(null,await this.#r(t,n,r,"GET")))();let o=this.getPath(t,{env:r}),a=this.router.match(s,o),l=new Nv(t,{path:o,matchResult:a,env:r,executionCtx:n,notFoundHandler:this.#n});if(a[0].length===1){let u;try{u=a[0][0][0][0](l,async()=>{l.res=await this.#n(l)})}catch(d){return this.#i(d,l)}return u instanceof Promise?u.then((d)=>d||(l.finalized?l.res:this.#n(l))).catch((d)=>this.#i(d,l)):u??this.#n(l)}let c=_f(a[0],this.errorHandler,this.#n);return(async()=>{try{let u=await c(l);if(!u.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return u.res}catch(u){return this.#i(u,l)}})()}fetch=(t,...n)=>this.#r(t,n[1],n[0],t.method);request=(t,n,r,s)=>{if(t instanceof Request)return this.fetch(n?new Request(t,n):t,r,s);return t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${Dr("/",t)}`,n),r,s)};fire=()=>{addEventListener("fetch",(t)=>{t.respondWith(this.#r(t.request,t,void 0,t.request.method))})}};var Al=[];function Rf(e,t){let n=this.buildAllMatchers(),r=(s,o)=>{let a=n[s]||n[Ie],l=a[2][o];if(l)return l;let c=o.match(a[0]);if(!c)return[[],Al];let u=c.indexOf("",1);return[a[1][u],c]};return this.match=r,r(e,t)}var Cl="[^/]+",lo=".*",co="(?:|/.*)",Lr=Symbol(),AP=new Set(".\\+*[^]$()");function CP(e,t){if(e.length===1)return t.length===1?e<t?-1:1:-1;if(t.length===1)return 1;if(e===lo||e===co)return 1;else if(t===lo||t===co)return-1;if(e===Cl)return 1;else if(t===Cl)return-1;return e.length===t.length?e<t?-1:1:t.length-e.length}var qv=class e{#t;#e;#n=Object.create(null);insert(t,n,r,s,o){if(t.length===0){if(this.#t!==void 0)throw Lr;if(o)return;this.#t=n;return}let[a,...l]=t,c=a==="*"?l.length===0?["","",lo]:["","",Cl]:a==="/*"?["","",co]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),u;if(c){let d=c[1],f=c[2]||Cl;if(d&&c[2]){if(f===".*")throw Lr;if(f=f.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(f))throw Lr}if(u=this.#n[f],!u){if(Object.keys(this.#n).some((p)=>p!==lo&&p!==co))throw Lr;if(o)return;if(u=this.#n[f]=new e,d!=="")u.#e=s.varIndex++}if(!o&&d!=="")r.push([d,u.#e])}else if(u=this.#n[a],!u){if(Object.keys(this.#n).some((d)=>d.length>1&&d!==lo&&d!==co))throw Lr;if(o)return;u=this.#n[a]=new e}u.insert(l,n,r,s,o)}buildRegExpStr(){let n=Object.keys(this.#n).sort(CP).map((r)=>{let s=this.#n[r];return(typeof s.#e==="number"?`(${r})@${s.#e}`:AP.has(r)?`\\${r}`:r)+s.buildRegExpStr()});if(typeof this.#t==="number")n.unshift(`#${this.#t}`);if(n.length===0)return"";if(n.length===1)return n[0];return"(?:"+n.join("|")+")"}};var Hv=class{#t={varIndex:0};#e=new qv;insert(e,t,n){let r=[],s=[];for(let a=0;;){let l=!1;if(e=e.replace(/\{[^}]+\}/g,(c)=>{let u=`@\\${a}`;return s[a]=[u,c],a++,l=!0,u}),!l)break}let o=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let a=s.length-1;a>=0;a--){let[l]=s[a];for(let c=o.length-1;c>=0;c--)if(o[c].indexOf(l)!==-1){o[c]=o[c].replace(l,s[a][1]);break}}return this.#e.insert(o,t,r,this.#t,n),r}buildRegExp(){let e=this.#e.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(s,o,a)=>{if(o!==void 0)return n[++t]=Number(o),"$()";if(a!==void 0)return r[Number(a)]=++t,"";return""}),[new RegExp(`^${e}`),n,r]}};var OP=[/^$/,[],Object.create(null)],Kv=Object.create(null);function Wv(e){return Kv[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(t,n)=>n?`\\${n}`:"(?:|/.*)")}$`)}function IP(){Kv=Object.create(null)}function PP(e){let t=new Hv,n=[];if(e.length===0)return OP;let r=e.map((u)=>[!/\*|\/:/.test(u[0]),...u]).sort(([u,d],[f,p])=>u?1:f?-1:d.length-p.length),s=Object.create(null);for(let u=0,d=-1,f=r.length;u<f;u++){let[p,h,g]=r[u];if(p)s[h]=[g.map(([b])=>[b,Object.create(null)]),Al];else d++;let w;try{w=t.insert(h,d,p)}catch(b){throw b===Lr?new El(h):b}if(p)continue;n[d]=g.map(([b,x])=>{let R=Object.create(null);x-=1;for(;x>=0;x--){let[P,M]=w[x];R[P]=M}return[b,R]})}let[o,a,l]=t.buildRegExp();for(let u=0,d=n.length;u<d;u++)for(let f=0,p=n[u].length;f<p;f++){let h=n[u][f]?.[1];if(!h)continue;let g=Object.keys(h);for(let w=0,b=g.length;w<b;w++)h[g[w]]=l[h[g[w]]]}let c=[];for(let u in a)c[u]=n[a[u]];return[o,c,s]}function Di(e,t){if(!e)return;for(let n of Object.keys(e).sort((r,s)=>s.length-r.length))if(Wv(n).test(t))return[...e[n]];return}var Ol=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[Ie]:Object.create(null)},this.#e={[Ie]:Object.create(null)}}add(e,t,n){let r=this.#t,s=this.#e;if(!r||!s)throw Error(kl);if(!r[e])[r,s].forEach((l)=>{l[e]=Object.create(null),Object.keys(l[Ie]).forEach((c)=>{l[e][c]=[...l[Ie][c]]})});if(t==="/*")t="*";let o=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let l=Wv(t);if(e===Ie)Object.keys(r).forEach((c)=>{r[c][t]||=Di(r[c],t)||Di(r[Ie],t)||[]});else r[e][t]||=Di(r[e],t)||Di(r[Ie],t)||[];Object.keys(r).forEach((c)=>{if(e===Ie||e===c)Object.keys(r[c]).forEach((u)=>{l.test(u)&&r[c][u].push([n,o])})}),Object.keys(s).forEach((c)=>{if(e===Ie||e===c)Object.keys(s[c]).forEach((u)=>l.test(u)&&s[c][u].push([n,o]))});return}let a=Sl(t)||[t];for(let l=0,c=a.length;l<c;l++){let u=a[l];Object.keys(s).forEach((d)=>{if(e===Ie||e===d)s[d][u]||=[...Di(r[d],u)||Di(r[Ie],u)||[]],s[d][u].push([n,o-c+l+1])})}}match=Rf;buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#t)).forEach((t)=>{e[t]||=this.#n(t)}),this.#t=this.#e=void 0,IP(),e}#n(e){let t=[],n=e===Ie;if([this.#t,this.#e].forEach((r)=>{let s=r[e]?Object.keys(r[e]).map((o)=>[o,r[e][o]]):[];if(s.length!==0)n||=!0,t.push(...s);else if(e!==Ie)t.push(...Object.keys(r[Ie]).map((o)=>[o,r[Ie][o]]))}),!n)return null;else return PP(t)}};var Sf=class{name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,n){if(!this.#e)throw Error(kl);this.#e.push([e,t,n])}match(e,t){if(!this.#e)throw Error("Fatal error");let n=this.#t,r=this.#e,s=n.length,o=0,a;for(;o<s;o++){let l=n[o];try{for(let c=0,u=r.length;c<u;c++)l.add(...r[c]);a=l.match(e,t)}catch(c){if(c instanceof El)continue;throw c}this.match=l.match.bind(l),this.#t=[l],this.#e=void 0;break}if(o===s)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,a}get activeRouter(){if(this.#e||this.#t.length!==1)throw Error("No active router has been determined yet.");return this.#t[0]}};var uo=Object.create(null),Gv=class e{#t;#e;#n;#s=0;#i=uo;constructor(t,n,r){if(this.#e=r||Object.create(null),this.#t=[],t&&n){let s=Object.create(null);s[t]={handler:n,possibleKeys:[],score:0},this.#t=[s]}this.#n=[]}insert(t,n,r){this.#s=++this.#s;let s=this,o=Av(n),a=[];for(let l=0,c=o.length;l<c;l++){let u=o[l],d=o[l+1],f=Cv(u,d),p=Array.isArray(f)?f[0]:u;if(p in s.#e){if(s=s.#e[p],f)a.push(f[1]);continue}if(s.#e[p]=new e,f)s.#n.push(f),a.push(f[1]);s=s.#e[p]}return s.#t.push({[t]:{handler:r,possibleKeys:a.filter((l,c,u)=>u.indexOf(l)===c),score:this.#s}}),s}#r(t,n,r,s){let o=[];for(let a=0,l=t.#t.length;a<l;a++){let c=t.#t[a],u=c[n]||c[Ie],d={};if(u!==void 0){if(u.params=Object.create(null),o.push(u),r!==uo||s&&s!==uo)for(let f=0,p=u.possibleKeys.length;f<p;f++){let h=u.possibleKeys[f],g=d[u.score];u.params[h]=s?.[h]&&!g?s[h]:r[h]??s?.[h],d[u.score]=!0}}}return o}search(t,n){let r=[];this.#i=uo;let o=[this],a=yf(n),l=[];for(let c=0,u=a.length;c<u;c++){let d=a[c],f=c===u-1,p=[];for(let h=0,g=o.length;h<g;h++){let w=o[h],b=w.#e[d];if(b)if(b.#i=w.#i,f){if(b.#e["*"])r.push(...this.#r(b.#e["*"],t,w.#i));r.push(...this.#r(b,t,w.#i))}else p.push(b);for(let x=0,R=w.#n.length;x<R;x++){let P=w.#n[x],M=w.#i===uo?{}:{...w.#i};if(P==="*"){let U=w.#e["*"];if(U)r.push(...this.#r(U,t,w.#i)),U.#i=M,p.push(U);continue}let[k,E,D]=P;if(!d&&!(D instanceof RegExp))continue;let L=w.#e[k],O=a.slice(c).join("/");if(D instanceof RegExp){let U=D.exec(O);if(U){if(M[E]=U[0],r.push(...this.#r(L,t,w.#i,M)),Object.keys(L.#e).length){L.#i=M;let I=U[0].match(/\//)?.length??0;(l[I]||=[]).push(L)}continue}}if(D===!0||D.test(d))if(M[E]=d,f){if(r.push(...this.#r(L,t,M,w.#i)),L.#e["*"])r.push(...this.#r(L.#e["*"],t,M,w.#i))}else L.#i=M,p.push(L)}}o=p.concat(l.shift()??[])}if(r.length>1)r.sort((c,u)=>c.score-u.score);return[r.map(({handler:c,params:u})=>[c,u])]}};var $f=class{name="TrieRouter";#t;constructor(){this.#t=new Gv}add(e,t,n){let r=Sl(t);if(r){for(let s=0,o=r.length;s<o;s++)this.#t.insert(e,r[s],n);return}this.#t.insert(e,t,n)}match(e,t){return this.#t.search(e,t)}};var jr=class extends Bv{constructor(e={}){super(e);this.router=e.router??new Sf({routers:[new Ol,new $f]})}};import{readdir as Vv,rm as zv,stat as MP}from"fs/promises";import TP from"os";import Jv from"path";async function Yv(){if(!Bun.which("gh"))return{available:!1,authed:!1,message:"gh is not installed"};try{return(await re("gh",["auth","status"],{allowFail:!0})).code===0?{available:!0,authed:!0}:{available:!0,authed:!1,message:"gh is not authenticated; run `gh auth login`"}}catch(e){return{available:!0,authed:!1,message:e instanceof Error?e.message:String(e)}}}async function Zv(){let e=Bun.which("opencode");if(!e)return{path:null,version:null};try{let t=await re(e,["--version"],{allowFail:!0});return{path:e,version:t.code===0?t.stdout.trim()||null:null}}catch{return{path:e,version:null}}}var FP=86400000,Xv="code-review-subject-";function NP(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}async function Qv(e,t){let n=TP.tmpdir(),r=[];try{r=await Vv(n)}catch{}for(let o of r){if(!o.startsWith(Xv))continue;let a=Number(o.slice(Xv.length).split("-")[1]);if(!Number.isInteger(a)||a<=0||NP(a))continue;let l=Jv.join(n,o);await zv(l,{recursive:!0,force:!0}).catch(()=>{}),t(`removed stale review worktree ${l}`)}if(e)await re("git",["-C",e,"worktree","prune"],{allowFail:!0}).catch(()=>{});let s=(await zt()).filter((o)=>o.status==="running").map((o)=>o.id);for(let o of al()){let a;try{a=await Vv(o)}catch{continue}for(let l of a){let c=Jv.join(o,l);try{if(!(s.some((d)=>l.startsWith(`${d}-`))&&Date.now()-(await MP(c)).mtimeMs<FP))await zv(c,{recursive:!0,force:!0})}catch{}}}}import tx from"os";function ex(e,t,n){if(!e)return!0;if(e.trim()==="null")return!1;if((Array.isArray(n)?n[0]:n)?.trim().toLowerCase()==="same-origin")return!0;try{return new URL(e).host===t}catch{return!1}}var DP="DIFFLOUPE_ALLOWED_HOSTS",nx=["localhost","127.0.0.1","::1"];function kf(e){let t=e?.trim().toLowerCase();if(!t)return;let n=t,r;if(t.startsWith("[")){let s=t.indexOf("]");if(s<0)return null;n=t.slice(1,s);let o=t.slice(s+1);if(o){if(!o.startsWith(":"))return null;r=o.slice(1)}if(!n.includes(":")||!/^[0-9a-f:.]+$/.test(n))return null}else{let s=t.indexOf(":");if(s>=0)n=t.slice(0,s),r=t.slice(s+1);if(n.endsWith("."))n=n.slice(0,-1);if(!/^[a-z0-9_-]+(\.[a-z0-9_-]+)*$/.test(n))return null}if(r!==void 0&&(!/^\d{1,5}$/.test(r)||Number(r)>65535))return null;return n}function fo(e){let t=e.replace(/^\[|\]$/g,"").toLowerCase();return nx.includes(t)||t.startsWith("127.")||t.endsWith(".localhost")}function Ef(e,t=process.env[DP]){let n=new Set(nx);for(let r of(t??"").split(",")){let s=kf(r);if(s)n.add(s)}if(!fo(e)){let r=kf(e.includes(":")&&!e.startsWith("[")?`[${e}]`:e);if(r)n.add(r);n.add(tx.hostname().toLowerCase());for(let s of Object.values(tx.networkInterfaces()))for(let o of s??[])n.add(o.address.toLowerCase())}return n}function rx(e){return async(t,n)=>{let r=kf(t.req.header("host"));if(r===null||r!==void 0&&!e.has(r)&&!fo(r))return t.json({error:"host not allowed"},403);await n()}}function ix(){return async(e,t)=>{let n=e.req.method;if(n!=="GET"&&n!=="HEAD"&&n!=="OPTIONS"){if(!ex(e.req.header("origin"),e.req.header("host")??"",e.req.header("sec-fetch-site")))return e.json({error:"cross-origin request refused"},403)}await t()}}function sx(e){let t=new jr;return t.get("/",(n)=>n.json({app:"diffloupe",version:e.version,pid:process.pid,defaultRepo:e.defaultRepo,activeRunId:e.runs.activeRunId,gh:e.gh,opencode:e.opencode})),t}import{readFile as zP}from"fs/promises";import JP from"path";var Af=class{writer;encoder;writable;abortSubscribers=[];responseReadable;aborted=!1;closed=!1;constructor(e,t){this.writable=e,this.writer=e.getWriter(),this.encoder=new TextEncoder;let n=t.getReader();this.abortSubscribers.push(async()=>{await n.cancel()}),this.responseReadable=new ReadableStream({async pull(r){let{done:s,value:o}=await n.read();s?r.close():r.enqueue(o)},cancel:()=>{this.abort()}})}async write(e){try{if(typeof e==="string")e=this.encoder.encode(e);await this.writer.write(e)}catch{}return this}async writeln(e){return await this.write(e+`
674
- `),this}sleep(e){return new Promise((t)=>setTimeout(t,e))}async close(){try{await this.writer.close()}catch{}this.closed=!0}async pipe(e){this.writer.releaseLock(),await e.pipeTo(this.writable,{preventClose:!0}),this.writer=this.writable.getWriter()}onAbort(e){this.abortSubscribers.push(e)}abort(){if(!this.aborted)this.aborted=!0,this.abortSubscribers.forEach((e)=>e())}};var Il=()=>{let e=typeof Bun<"u"?Bun.version:void 0;if(e===void 0)return!1;let t=e.startsWith("1.1")||e.startsWith("1.0")||e.startsWith("0.");return Il=()=>t,t};var ox=class extends Af{constructor(e,t){super(e,t)}async writeSSE(e){let n=(await ao(e.data,$l.Stringify,!1,{})).split(/\r\n|\r|\n/).map((s)=>`data: ${s}`).join(`
671
+ `),d)return t(`Not reviewed: round ${d.round} is past --max-rounds ${d.maxRounds}`),4;if(!e.json){if(e.kind==="diff")process.stdout.write(`${sb(a.run)}
672
+ `);else if(a.reviewed){let h=e.markdown?await Iv(l):void 0;process.stdout.write(h??`${ob(a.run)}
673
+ `)}}if(e.failOn&&a.reviewed&&Wv(a.run,e.failOn))return t(`Failing: a finding is at or above ${e.failOn}`),3;return 0}async function XP(e,t,n,r,s,o){let a=Ve(e),l=o.out?Ol.resolve(o.out):null,c=n==="complete"||r==="round-limit",u=Ol.join(a,"raw","payloads.json"),d=c&&await Bun.file(u).exists()?u:null;if(l)d=(await Kv(e,l,{payloads:c})).includes("payloads.json")?Ol.join(l,"payloads.json"):null;let f=Hv(t,{id:e,status:n,runDir:a,outDir:l,payloads:d,skippedSlices:s,...o.github?{round:await YP(a)}:{},skipReason:r});if(l)await Gv(l,f);return f}async function YP(e){try{let t=await Bun.file(Ol.join(e,"raw","record.json")).json();return typeof t.runs==="number"?t.runs:void 0}catch{return}}function go(e){let t=!1,n=()=>{if(t)process.exit(130);t=!0,e()};return process.on("SIGINT",n),process.on("SIGTERM",n),()=>{process.off("SIGINT",n),process.off("SIGTERM",n)}}import ZP from"os";import{existsSync as QP,readFileSync as eM}from"fs";var tM=new Set(["true","false","none",":","0","1"]);function nM(){if(process.platform!=="linux")return!1;if(ZP.release().toLowerCase().includes("microsoft"))return!0;try{let e=eM("/proc/version","utf8").toLowerCase();return e.includes("microsoft")||e.includes("wsl")}catch{return!1}}function rM(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("/mnt/")||e.toLowerCase().endsWith(".exe")}function iM(e,t){let n=t.browser?.trim()&&!tM.has(t.browser.trim().toLowerCase())?t.browser.trim():void 0;if(t.wsl){if(!n)return["cmd.exe","/c","start","",e];if(rM(n))return["cmd.exe","/c","start","",n,e];return[n,e]}if(n)return[n,e];if(t.platform==="darwin")return["open",e];if(t.platform==="win32")return["cmd.exe","/c","start","",e];return["xdg-open",e]}async function zv(e){let t=nM(),n=iM(e,{browser:process.env.BROWSER,wsl:t,platform:process.platform});try{return await Bun.spawn(n,{stdio:["ignore","ignore","ignore"],...t&&n[0]==="cmd.exe"&&QP("/mnt/c")?{cwd:"/mnt/c"}:{}}).exited===0}catch{return!1}}var Of=(e,t,n)=>(r,s)=>{let o=-1;return a(0);async function a(l){if(l<=o)throw Error("next() called multiple times");o=l;let c,u=!1,d;if(e[l])d=e[l][0][0],r.req.routeIndex=l;else d=l===e.length&&s||void 0;if(d)try{c=await d(r,()=>a(l+1))}catch(f){if(f instanceof Error&&t)r.error=f,c=await t(f,r),u=!0;else throw f}else if(r.finalized===!1&&n)c=await n(r);if(c&&(r.finalized===!1||u))r.res=c;return r}};var Jv=Symbol();var Xv=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,o=(e instanceof Il?e.raw.headers:e.headers).get("Content-Type");if(o?.startsWith("multipart/form-data")||o?.startsWith("application/x-www-form-urlencoded"))return sM(e,{all:n,dot:r});return{}};async function sM(e,t){let n=await e.formData();if(n)return oM(n,t);return{}}function oM(e,t){let n=Object.create(null);if(e.forEach((r,s)=>{if(!(t.all||s.endsWith("[]")))n[s]=r;else aM(n,s,r)}),t.dot)Object.entries(n).forEach(([r,s])=>{if(r.includes("."))lM(n,r,s),delete n[r]});return n}var aM=(e,t,n)=>{if(e[t]!==void 0)if(Array.isArray(e[t]))e[t].push(n);else e[t]=[e[t],n];else if(!t.endsWith("[]"))e[t]=n;else e[t]=[n]},lM=(e,t,n)=>{let r=e,s=t.split(".");s.forEach((o,a)=>{if(a===s.length-1)r[o]=n;else{if(!r[o]||typeof r[o]!=="object"||Array.isArray(r[o])||r[o]instanceof File)r[o]=Object.create(null);r=r[o]}})};var Pf=(e)=>{let t=e.split("/");if(t[0]==="")t.shift();return t},Yv=(e)=>{let{groups:t,path:n}=cM(e),r=Pf(n);return uM(r,t)},cM=(e)=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(n,r)=>{let s=`@${r}`;return t.push([s,n]),s}),{groups:t,path:e}},uM=(e,t)=>{for(let n=t.length-1;n>=0;n--){let[r]=t[n];for(let s=e.length-1;s>=0;s--)if(e[s].includes(r)){e[s]=e[s].replace(r,t[n][1]);break}}return e},Pl={},Zv=(e,t)=>{if(e==="*")return"*";let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;if(!Pl[r])if(n[2])Pl[r]=t&&t[0]!==":"&&t[0]!=="*"?[r,n[1],new RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],new RegExp(`^${n[2]}$`)];else Pl[r]=[e,n[1],!0];return Pl[r]}return null},Ml=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,(n)=>{try{return t(n)}catch{return n}})}},dM=(e)=>Ml(e,decodeURI),Mf=(e)=>{let t=e.url,n=t.indexOf("/",t.indexOf(":")+4),r=n;for(;r<t.length;r++){let s=t.charCodeAt(r);if(s===37){let o=t.indexOf("?",r),a=t.slice(n,o===-1?void 0:o);return dM(a.includes("%25")?a.replace(/%25/g,"%2525"):a)}else if(s===63)break}return t.slice(n,r)};var Qv=(e)=>{let t=Mf(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},Br=(e,t,...n)=>{if(n.length)t=Br(t,...n);return`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`},Tl=(e)=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),n=[],r="";return t.forEach((s)=>{if(s!==""&&!/\:/.test(s))r+="/"+s;else if(/\:/.test(s))if(/\?/.test(s)){if(n.length===0&&r==="")n.push("/");else n.push(r);let o=s.replace("?","");r+="/"+o,n.push(r)}else r+="/"+s}),n.filter((s,o,a)=>a.indexOf(s)===o)},If=(e)=>{if(!/[%+]/.test(e))return e;if(e.indexOf("+")!==-1)e=e.replace(/\+/g," ");return e.indexOf("%")!==-1?Ml(e,Tf):e},ex=(e,t,n)=>{let r;if(!n&&t&&!/[%+]/.test(t)){let a=e.indexOf("?",8);if(a===-1)return;if(!e.startsWith(t,a+1))a=e.indexOf(`&${t}`,a+1);while(a!==-1){let l=e.charCodeAt(a+t.length+1);if(l===61){let c=a+t.length+2,u=e.indexOf("&",c);return If(e.slice(c,u===-1?void 0:u))}else if(l==38||isNaN(l))return"";a=e.indexOf(`&${t}`,a+1)}if(r=/[%+]/.test(e),!r)return}let s={};r??=/[%+]/.test(e);let o=e.indexOf("?",8);while(o!==-1){let a=e.indexOf("&",o+1),l=e.indexOf("=",o);if(l>a&&a!==-1)l=-1;let c=e.slice(o+1,l===-1?a===-1?void 0:a:l);if(r)c=If(c);if(o=a,c==="")continue;let u;if(l===-1)u="";else if(u=e.slice(l+1,a===-1?void 0:a),r)u=If(u);if(n){if(!(s[c]&&Array.isArray(s[c])))s[c]=[];s[c].push(u)}else s[c]??=u}return t?s[t]:s},tx=ex,nx=(e,t)=>ex(e,t,!0),Tf=decodeURIComponent;var rx=(e)=>Ml(e,Tf),Il=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(e,t="/",n=[[]]){this.raw=e,this.path=t,this.#e=n,this.#t={}}param(e){return e?this.#n(e):this.#s()}#n(e){let t=this.#e[0][this.routeIndex][1][e],n=this.#i(t);return n&&/\%/.test(n)?rx(n):n}#s(){let e={},t=Object.keys(this.#e[0][this.routeIndex][1]);for(let n of t){let r=this.#i(this.#e[0][this.routeIndex][1][n]);if(r!==void 0)e[n]=/\%/.test(r)?rx(r):r}return e}#i(e){return this.#e[1]?this.#e[1][e]:e}query(e){return tx(this.url,e)}queries(e){return nx(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((n,r)=>{t[r]=n}),t}async parseBody(e){return this.bodyCache.parsedBody??=await Xv(this,e)}#r=(e)=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let s=Object.keys(t)[0];if(s)return t[s].then((o)=>{if(s==="json")o=JSON.stringify(o);return new Response(o)[e]()});return t[e]=n[e]()};json(){return this.#r("text").then((e)=>JSON.parse(e))}text(){return this.#r("text")}arrayBuffer(){return this.#r("arrayBuffer")}blob(){return this.#r("blob")}formData(){return this.#r("formData")}addValidatedData(e,t){this.#t[e]=t}valid(e){return this.#t[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[Jv](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,e]])=>e)}get routePath(){return this.#e[0].map(([[,e]])=>e)[this.routeIndex].path}};var Dl={Stringify:1,BeforeStream:2,Stream:3},fM=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n};var _o=async(e,t,n,r,s)=>{if(typeof e==="object"&&!(e instanceof String)){if(!(e instanceof Promise))e=e.toString();if(e instanceof Promise)e=await e}let o=e.callbacks;if(!o?.length)return Promise.resolve(e);if(s)s[0]+=e;else s=[e];let a=Promise.all(o.map((l)=>l({phase:t,buffer:s,context:r}))).then((l)=>Promise.all(l.filter(Boolean).map((c)=>_o(c,t,!1,r,s))).then(()=>s[0]));if(n)return fM(await a,o);else return a};var ix="text/plain; charset=UTF-8",Df=(e,t)=>({"Content-Type":e,...t}),sx=class{#t;#e;env={};#n;finalized=!1;error;#s;#i;#r;#u;#l;#c;#a;#d;#f;constructor(e,t){if(this.#t=e,t)this.#i=t.executionCtx,this.env=t.env,this.#c=t.notFoundHandler,this.#f=t.path,this.#d=t.matchResult}get req(){return this.#e??=new Il(this.#t,this.#f,this.#d),this.#e}get event(){if(this.#i&&"respondWith"in this.#i)return this.#i;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#i)return this.#i;else throw Error("This context has no ExecutionContext")}get res(){return this.#r||=new Response(null,{headers:this.#a??=new Headers})}set res(e){if(this.#r&&e){e=new Response(e.body,e);for(let[t,n]of this.#r.headers.entries()){if(t==="content-type")continue;if(t==="set-cookie"){let r=this.#r.headers.getSetCookie();e.headers.delete("set-cookie");for(let s of r)e.headers.append("set-cookie",s)}else e.headers.set(t,n)}}this.#r=e,this.finalized=!0}render=(...e)=>(this.#l??=(t)=>this.html(t),this.#l(...e));setLayout=(e)=>this.#u=e;getLayout=()=>this.#u;setRenderer=(e)=>{this.#l=e};header=(e,t,n)=>{if(this.finalized)this.#r=new Response(this.#r.body,this.#r);let r=this.#r?this.#r.headers:this.#a??=new Headers;if(t===void 0)r.delete(e);else if(n?.append)r.append(e,t);else r.set(e,t)};status=(e)=>{this.#s=e};set=(e,t)=>{this.#n??=new Map,this.#n.set(e,t)};get=(e)=>this.#n?this.#n.get(e):void 0;get var(){if(!this.#n)return{};return Object.fromEntries(this.#n)}#o(e,t,n){let r=this.#r?new Headers(this.#r.headers):this.#a??new Headers;if(typeof t==="object"&&"headers"in t){let o=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[a,l]of o)if(a.toLowerCase()==="set-cookie")r.append(a,l);else r.set(a,l)}if(n)for(let[o,a]of Object.entries(n))if(typeof a==="string")r.set(o,a);else{r.delete(o);for(let l of a)r.append(o,l)}let s=typeof t==="number"?t:t?.status??this.#s;return new Response(e,{status:s,headers:r})}newResponse=(...e)=>this.#o(...e);body=(e,t,n)=>this.#o(e,t,n);text=(e,t,n)=>!this.#a&&!this.#s&&!t&&!n&&!this.finalized?new Response(e):this.#o(e,t,Df(ix,n));json=(e,t,n)=>this.#o(JSON.stringify(e),t,Df("application/json",n));html=(e,t,n)=>{let r=(s)=>this.#o(s,t,Df("text/html; charset=UTF-8",n));return typeof e==="object"?_o(e,Dl.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header("Location",!/[^\x00-\xFF]/.test(n)?n:encodeURI(n)),this.newResponse(null,t??302)};notFound=()=>(this.#c??=()=>new Response,this.#c(this))};var Ie="ALL",ox="all",ax=["get","post","put","delete","options","patch"],Nl="Can not add a route since the matcher is already built.",Fl=class extends Error{};var lx="__COMPOSED_HANDLER";var pM=(e)=>e.text("404 Not Found",404),cx=(e,t)=>{if("getResponse"in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text("Internal Server Error",500)},ux=class e{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...ax,ox].forEach((o)=>{this[o]=(a,...l)=>{if(typeof a==="string")this.#t=a;else this.#s(o,this.#t,a);return l.forEach((c)=>{this.#s(o,this.#t,c)}),this}}),this.on=(o,a,...l)=>{for(let c of[a].flat()){this.#t=c;for(let u of[o].flat())l.map((d)=>{this.#s(u.toUpperCase(),this.#t,d)})}return this},this.use=(o,...a)=>{if(typeof o==="string")this.#t=o;else this.#t="*",a.unshift(o);return a.forEach((l)=>{this.#s(Ie,this.#t,l)}),this};let{strict:r,...s}=t;Object.assign(this,s),this.getPath=r??!0?t.getPath??Mf:Qv}#e(){let t=new e({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#n=this.#n,t.routes=this.routes,t}#n=pM;errorHandler=cx;route(t,n){let r=this.basePath(t);return n.routes.map((s)=>{let o;if(n.errorHandler===cx)o=s.handler;else o=async(a,l)=>(await Of([],n.errorHandler)(a,()=>s.handler(a,l))).res,o[lx]=s.handler;r.#s(s.method,s.path,o)}),this}basePath(t){let n=this.#e();return n._basePath=Br(this._basePath,t),n}onError=(t)=>(this.errorHandler=t,this);notFound=(t)=>(this.#n=t,this);mount(t,n,r){let s,o;if(r)if(typeof r==="function")o=r;else if(o=r.optionHandler,r.replaceRequest===!1)s=(c)=>c;else s=r.replaceRequest;let a=o?(c)=>{let u=o(c);return Array.isArray(u)?u:[u]}:(c)=>{let u=void 0;try{u=c.executionCtx}catch{}return[c.env,u]};s||=(()=>{let c=Br(this._basePath,t),u=c==="/"?0:c.length;return(d)=>{let f=new URL(d.url);return f.pathname=f.pathname.slice(u)||"/",new Request(f,d)}})();let l=async(c,u)=>{let d=await n(s(c.req.raw),...a(c));if(d)return d;await u()};return this.#s(Ie,Br(t,"*"),l),this}#s(t,n,r){t=t.toUpperCase(),n=Br(this._basePath,n);let s={basePath:this._basePath,path:n,method:t,handler:r};this.router.add(t,n,[r,s]),this.routes.push(s)}#i(t,n){if(t instanceof Error)return this.errorHandler(t,n);throw t}#r(t,n,r,s){if(s==="HEAD")return(async()=>new Response(null,await this.#r(t,n,r,"GET")))();let o=this.getPath(t,{env:r}),a=this.router.match(s,o),l=new sx(t,{path:o,matchResult:a,env:r,executionCtx:n,notFoundHandler:this.#n});if(a[0].length===1){let u;try{u=a[0][0][0][0](l,async()=>{l.res=await this.#n(l)})}catch(d){return this.#i(d,l)}return u instanceof Promise?u.then((d)=>d||(l.finalized?l.res:this.#n(l))).catch((d)=>this.#i(d,l)):u??this.#n(l)}let c=Of(a[0],this.errorHandler,this.#n);return(async()=>{try{let u=await c(l);if(!u.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return u.res}catch(u){return this.#i(u,l)}})()}fetch=(t,...n)=>this.#r(t,n[1],n[0],t.method);request=(t,n,r,s)=>{if(t instanceof Request)return this.fetch(n?new Request(t,n):t,r,s);return t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${Br("/",t)}`,n),r,s)};fire=()=>{addEventListener("fetch",(t)=>{t.respondWith(this.#r(t.request,t,void 0,t.request.method))})}};var Ll=[];function Nf(e,t){let n=this.buildAllMatchers(),r=(s,o)=>{let a=n[s]||n[Ie],l=a[2][o];if(l)return l;let c=o.match(a[0]);if(!c)return[[],Ll];let u=c.indexOf("",1);return[a[1][u],c]};return this.match=r,r(e,t)}var jl="[^/]+",wo=".*",yo="(?:|/.*)",qr=Symbol(),hM=new Set(".\\+*[^]$()");function mM(e,t){if(e.length===1)return t.length===1?e<t?-1:1:-1;if(t.length===1)return 1;if(e===wo||e===yo)return 1;else if(t===wo||t===yo)return-1;if(e===jl)return 1;else if(t===jl)return-1;return e.length===t.length?e<t?-1:1:t.length-e.length}var dx=class e{#t;#e;#n=Object.create(null);insert(t,n,r,s,o){if(t.length===0){if(this.#t!==void 0)throw qr;if(o)return;this.#t=n;return}let[a,...l]=t,c=a==="*"?l.length===0?["","",wo]:["","",jl]:a==="/*"?["","",yo]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),u;if(c){let d=c[1],f=c[2]||jl;if(d&&c[2]){if(f===".*")throw qr;if(f=f.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(f))throw qr}if(u=this.#n[f],!u){if(Object.keys(this.#n).some((p)=>p!==wo&&p!==yo))throw qr;if(o)return;if(u=this.#n[f]=new e,d!=="")u.#e=s.varIndex++}if(!o&&d!=="")r.push([d,u.#e])}else if(u=this.#n[a],!u){if(Object.keys(this.#n).some((d)=>d.length>1&&d!==wo&&d!==yo))throw qr;if(o)return;u=this.#n[a]=new e}u.insert(l,n,r,s,o)}buildRegExpStr(){let n=Object.keys(this.#n).sort(mM).map((r)=>{let s=this.#n[r];return(typeof s.#e==="number"?`(${r})@${s.#e}`:hM.has(r)?`\\${r}`:r)+s.buildRegExpStr()});if(typeof this.#t==="number")n.unshift(`#${this.#t}`);if(n.length===0)return"";if(n.length===1)return n[0];return"(?:"+n.join("|")+")"}};var fx=class{#t={varIndex:0};#e=new dx;insert(e,t,n){let r=[],s=[];for(let a=0;;){let l=!1;if(e=e.replace(/\{[^}]+\}/g,(c)=>{let u=`@\\${a}`;return s[a]=[u,c],a++,l=!0,u}),!l)break}let o=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let a=s.length-1;a>=0;a--){let[l]=s[a];for(let c=o.length-1;c>=0;c--)if(o[c].indexOf(l)!==-1){o[c]=o[c].replace(l,s[a][1]);break}}return this.#e.insert(o,t,r,this.#t,n),r}buildRegExp(){let e=this.#e.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(s,o,a)=>{if(o!==void 0)return n[++t]=Number(o),"$()";if(a!==void 0)return r[Number(a)]=++t,"";return""}),[new RegExp(`^${e}`),n,r]}};var gM=[/^$/,[],Object.create(null)],px=Object.create(null);function hx(e){return px[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(t,n)=>n?`\\${n}`:"(?:|/.*)")}$`)}function _M(){px=Object.create(null)}function wM(e){let t=new fx,n=[];if(e.length===0)return gM;let r=e.map((u)=>[!/\*|\/:/.test(u[0]),...u]).sort(([u,d],[f,p])=>u?1:f?-1:d.length-p.length),s=Object.create(null);for(let u=0,d=-1,f=r.length;u<f;u++){let[p,h,g]=r[u];if(p)s[h]=[g.map(([b])=>[b,Object.create(null)]),Ll];else d++;let w;try{w=t.insert(h,d,p)}catch(b){throw b===qr?new Fl(h):b}if(p)continue;n[d]=g.map(([b,x])=>{let S=Object.create(null);x-=1;for(;x>=0;x--){let[P,M]=w[x];S[P]=M}return[b,S]})}let[o,a,l]=t.buildRegExp();for(let u=0,d=n.length;u<d;u++)for(let f=0,p=n[u].length;f<p;f++){let h=n[u][f]?.[1];if(!h)continue;let g=Object.keys(h);for(let w=0,b=g.length;w<b;w++)h[g[w]]=l[h[g[w]]]}let c=[];for(let u in a)c[u]=n[a[u]];return[o,c,s]}function qi(e,t){if(!e)return;for(let n of Object.keys(e).sort((r,s)=>s.length-r.length))if(hx(n).test(t))return[...e[n]];return}var Ul=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[Ie]:Object.create(null)},this.#e={[Ie]:Object.create(null)}}add(e,t,n){let r=this.#t,s=this.#e;if(!r||!s)throw Error(Nl);if(!r[e])[r,s].forEach((l)=>{l[e]=Object.create(null),Object.keys(l[Ie]).forEach((c)=>{l[e][c]=[...l[Ie][c]]})});if(t==="/*")t="*";let o=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let l=hx(t);if(e===Ie)Object.keys(r).forEach((c)=>{r[c][t]||=qi(r[c],t)||qi(r[Ie],t)||[]});else r[e][t]||=qi(r[e],t)||qi(r[Ie],t)||[];Object.keys(r).forEach((c)=>{if(e===Ie||e===c)Object.keys(r[c]).forEach((u)=>{l.test(u)&&r[c][u].push([n,o])})}),Object.keys(s).forEach((c)=>{if(e===Ie||e===c)Object.keys(s[c]).forEach((u)=>l.test(u)&&s[c][u].push([n,o]))});return}let a=Tl(t)||[t];for(let l=0,c=a.length;l<c;l++){let u=a[l];Object.keys(s).forEach((d)=>{if(e===Ie||e===d)s[d][u]||=[...qi(r[d],u)||qi(r[Ie],u)||[]],s[d][u].push([n,o-c+l+1])})}}match=Nf;buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#t)).forEach((t)=>{e[t]||=this.#n(t)}),this.#t=this.#e=void 0,_M(),e}#n(e){let t=[],n=e===Ie;if([this.#t,this.#e].forEach((r)=>{let s=r[e]?Object.keys(r[e]).map((o)=>[o,r[e][o]]):[];if(s.length!==0)n||=!0,t.push(...s);else if(e!==Ie)t.push(...Object.keys(r[Ie]).map((o)=>[o,r[Ie][o]]))}),!n)return null;else return wM(t)}};var Ff=class{name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,n){if(!this.#e)throw Error(Nl);this.#e.push([e,t,n])}match(e,t){if(!this.#e)throw Error("Fatal error");let n=this.#t,r=this.#e,s=n.length,o=0,a;for(;o<s;o++){let l=n[o];try{for(let c=0,u=r.length;c<u;c++)l.add(...r[c]);a=l.match(e,t)}catch(c){if(c instanceof Fl)continue;throw c}this.match=l.match.bind(l),this.#t=[l],this.#e=void 0;break}if(o===s)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,a}get activeRouter(){if(this.#e||this.#t.length!==1)throw Error("No active router has been determined yet.");return this.#t[0]}};var bo=Object.create(null),mx=class e{#t;#e;#n;#s=0;#i=bo;constructor(t,n,r){if(this.#e=r||Object.create(null),this.#t=[],t&&n){let s=Object.create(null);s[t]={handler:n,possibleKeys:[],score:0},this.#t=[s]}this.#n=[]}insert(t,n,r){this.#s=++this.#s;let s=this,o=Yv(n),a=[];for(let l=0,c=o.length;l<c;l++){let u=o[l],d=o[l+1],f=Zv(u,d),p=Array.isArray(f)?f[0]:u;if(p in s.#e){if(s=s.#e[p],f)a.push(f[1]);continue}if(s.#e[p]=new e,f)s.#n.push(f),a.push(f[1]);s=s.#e[p]}return s.#t.push({[t]:{handler:r,possibleKeys:a.filter((l,c,u)=>u.indexOf(l)===c),score:this.#s}}),s}#r(t,n,r,s){let o=[];for(let a=0,l=t.#t.length;a<l;a++){let c=t.#t[a],u=c[n]||c[Ie],d={};if(u!==void 0){if(u.params=Object.create(null),o.push(u),r!==bo||s&&s!==bo)for(let f=0,p=u.possibleKeys.length;f<p;f++){let h=u.possibleKeys[f],g=d[u.score];u.params[h]=s?.[h]&&!g?s[h]:r[h]??s?.[h],d[u.score]=!0}}}return o}search(t,n){let r=[];this.#i=bo;let o=[this],a=Pf(n),l=[];for(let c=0,u=a.length;c<u;c++){let d=a[c],f=c===u-1,p=[];for(let h=0,g=o.length;h<g;h++){let w=o[h],b=w.#e[d];if(b)if(b.#i=w.#i,f){if(b.#e["*"])r.push(...this.#r(b.#e["*"],t,w.#i));r.push(...this.#r(b,t,w.#i))}else p.push(b);for(let x=0,S=w.#n.length;x<S;x++){let P=w.#n[x],M=w.#i===bo?{}:{...w.#i};if(P==="*"){let U=w.#e["*"];if(U)r.push(...this.#r(U,t,w.#i)),U.#i=M,p.push(U);continue}let[k,E,F]=P;if(!d&&!(F instanceof RegExp))continue;let L=w.#e[k],O=a.slice(c).join("/");if(F instanceof RegExp){let U=F.exec(O);if(U){if(M[E]=U[0],r.push(...this.#r(L,t,w.#i,M)),Object.keys(L.#e).length){L.#i=M;let I=U[0].match(/\//)?.length??0;(l[I]||=[]).push(L)}continue}}if(F===!0||F.test(d))if(M[E]=d,f){if(r.push(...this.#r(L,t,M,w.#i)),L.#e["*"])r.push(...this.#r(L.#e["*"],t,M,w.#i))}else L.#i=M,p.push(L)}}o=p.concat(l.shift()??[])}if(r.length>1)r.sort((c,u)=>c.score-u.score);return[r.map(({handler:c,params:u})=>[c,u])]}};var Lf=class{name="TrieRouter";#t;constructor(){this.#t=new mx}add(e,t,n){let r=Tl(t);if(r){for(let s=0,o=r.length;s<o;s++)this.#t.insert(e,r[s],n);return}this.#t.insert(e,t,n)}match(e,t){return this.#t.search(e,t)}};var Hr=class extends ux{constructor(e={}){super(e);this.router=e.router??new Ff({routers:[new Ul,new Lf]})}};import{readdir as gx,rm as _x,stat as yM}from"fs/promises";import bM from"os";import wx from"path";async function bx(){if(!Bun.which("gh"))return{available:!1,authed:!1,message:"gh is not installed"};try{return(await re("gh",["auth","status"],{allowFail:!0})).code===0?{available:!0,authed:!0}:{available:!0,authed:!1,message:"gh is not authenticated; run `gh auth login`"}}catch(e){return{available:!0,authed:!1,message:e instanceof Error?e.message:String(e)}}}async function vx(){let e=Bun.which("opencode");if(!e)return{path:null,version:null};try{let t=await re("opencode",["--version"],{allowFail:!0});return{path:e,version:t.code===0?t.stdout.trim()||null:null}}catch{return{path:e,version:null}}}var vM=86400000,yx="code-review-subject-";function xM(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}async function xx(e,t){let n=bM.tmpdir(),r=[];try{r=await gx(n)}catch{}for(let o of r){if(!o.startsWith(yx))continue;let a=Number(o.slice(yx.length).split("-")[1]);if(!Number.isInteger(a)||a<=0||xM(a))continue;let l=wx.join(n,o);await _x(l,{recursive:!0,force:!0}).catch(()=>{}),t(`removed stale review worktree ${l}`)}if(e)await re("git",["-C",e,"worktree","prune"],{allowFail:!0}).catch(()=>{});let s=(await Jt()).filter((o)=>o.status==="running").map((o)=>o.id);for(let o of ml()){let a;try{a=await gx(o)}catch{continue}for(let l of a){let c=wx.join(o,l);try{if(!(s.some((d)=>l.startsWith(`${d}-`))&&Date.now()-(await yM(c)).mtimeMs<vM))await _x(c,{recursive:!0,force:!0})}catch{}}}}import Rx from"os";function Sx(e,t,n){if(!e)return!0;if(e.trim()==="null")return!1;if((Array.isArray(n)?n[0]:n)?.trim().toLowerCase()==="same-origin")return!0;try{return new URL(e).host===t}catch{return!1}}var SM="DIFFLOUPE_ALLOWED_HOSTS",$x=["localhost","127.0.0.1","::1"];function jf(e){let t=e?.trim().toLowerCase();if(!t)return;let n=t,r;if(t.startsWith("[")){let s=t.indexOf("]");if(s<0)return null;n=t.slice(1,s);let o=t.slice(s+1);if(o){if(!o.startsWith(":"))return null;r=o.slice(1)}if(!n.includes(":")||!/^[0-9a-f:.]+$/.test(n))return null}else{let s=t.indexOf(":");if(s>=0)n=t.slice(0,s),r=t.slice(s+1);if(n.endsWith("."))n=n.slice(0,-1);if(!/^[a-z0-9_-]+(\.[a-z0-9_-]+)*$/.test(n))return null}if(r!==void 0&&(!/^\d{1,5}$/.test(r)||Number(r)>65535))return null;return n}function vo(e){let t=e.replace(/^\[|\]$/g,"").toLowerCase();return $x.includes(t)||t.startsWith("127.")||t.endsWith(".localhost")}function Uf(e,t=process.env[SM]){let n=new Set($x);for(let r of(t??"").split(",")){let s=jf(r);if(s)n.add(s)}if(!vo(e)){let r=jf(e.includes(":")&&!e.startsWith("[")?`[${e}]`:e);if(r)n.add(r);n.add(Rx.hostname().toLowerCase());for(let s of Object.values(Rx.networkInterfaces()))for(let o of s??[])n.add(o.address.toLowerCase())}return n}function kx(e){return async(t,n)=>{let r=jf(t.req.header("host"));if(r===null||r!==void 0&&!e.has(r)&&!vo(r))return t.json({error:"host not allowed"},403);await n()}}function Ex(){return async(e,t)=>{let n=e.req.method;if(n!=="GET"&&n!=="HEAD"&&n!=="OPTIONS"){if(!Sx(e.req.header("origin"),e.req.header("host")??"",e.req.header("sec-fetch-site")))return e.json({error:"cross-origin request refused"},403)}await t()}}function Cx(e){let t=new Hr;return t.get("/",(n)=>n.json({app:"diffloupe",version:e.version,pid:process.pid,defaultRepo:e.defaultRepo,activeRunId:e.runs.activeRunId,gh:e.gh,opencode:e.opencode})),t}import{readFile as TM}from"fs/promises";import DM from"path";var Bf=class{writer;encoder;writable;abortSubscribers=[];responseReadable;aborted=!1;closed=!1;constructor(e,t){this.writable=e,this.writer=e.getWriter(),this.encoder=new TextEncoder;let n=t.getReader();this.abortSubscribers.push(async()=>{await n.cancel()}),this.responseReadable=new ReadableStream({async pull(r){let{done:s,value:o}=await n.read();s?r.close():r.enqueue(o)},cancel:()=>{this.abort()}})}async write(e){try{if(typeof e==="string")e=this.encoder.encode(e);await this.writer.write(e)}catch{}return this}async writeln(e){return await this.write(e+`
674
+ `),this}sleep(e){return new Promise((t)=>setTimeout(t,e))}async close(){try{await this.writer.close()}catch{}this.closed=!0}async pipe(e){this.writer.releaseLock(),await e.pipeTo(this.writable,{preventClose:!0}),this.writer=this.writable.getWriter()}onAbort(e){this.abortSubscribers.push(e)}abort(){if(!this.aborted)this.aborted=!0,this.abortSubscribers.forEach((e)=>e())}};var Bl=()=>{let e=typeof Bun<"u"?Bun.version:void 0;if(e===void 0)return!1;let t=e.startsWith("1.1")||e.startsWith("1.0")||e.startsWith("0.");return Bl=()=>t,t};var Ax=class extends Bf{constructor(e,t){super(e,t)}async writeSSE(e){let n=(await _o(e.data,Dl.Stringify,!1,{})).split(/\r\n|\r|\n/).map((s)=>`data: ${s}`).join(`
675
675
  `),r=[e.event&&`event: ${e.event}`,n,e.id&&`id: ${e.id}`,e.retry&&`retry: ${e.retry}`].filter(Boolean).join(`
676
676
  `)+`
677
677
 
678
- `;await this.write(r)}},LP=async(e,t,n)=>{try{await t(e)}catch(r){if(r instanceof Error&&n)await n(r,e),await e.writeSSE({event:"error",data:r.message});else console.error(r)}finally{e.close()}},jP=new WeakMap,Cf=(e,t,n)=>{let{readable:r,writable:s}=new TransformStream,o=new ox(s,r);if(Il())e.req.raw.signal.addEventListener("abort",()=>{if(!o.closed)o.abort()});return jP.set(o.responseReadable,e),e.header("Transfer-Encoding","chunked"),e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),LP(o,t,n),e.newResponse(o.responseReadable)};var BP=15000,qP=new Set(["done","cancelled","error"]);function HP(e){let t=e.req.header("last-event-id")??e.req.query("after")??"0",n=Number(t);return Number.isFinite(n)&&n>=0?n:0}function lx(e,t,n){e.header("Cache-Control","no-cache"),e.header("X-Accel-Buffering","no");let r=HP(e);return Cf(e,async(s)=>{let o=r,a=null,l=[],c=!1,u=null,d=async(h)=>{if(h.seq<=o)return;if(o=h.seq,await s.writeSSE({id:String(h.seq),event:h.type,data:JSON.stringify(h)}),qP.has(h.type))c=!0},f=t.subscribe(n,(h)=>{if(a)a(h);else l.push(h)});s.onAbort(()=>{f?.unsubscribe(),c=!0,u?.()});for(let h of await _v(n))await d(h);for(let h of l.splice(0))await d(h);if(!f||c){await ax(s),f?.unsubscribe();return}let p=[];a=(h)=>{p.push(h),u?.()};while(!c&&!s.aborted){if(p.length===0){if(await new Promise((h)=>{let g=setTimeout(h,BP);u=()=>{clearTimeout(g),h()}}),u=null,p.length===0&&!c&&!s.aborted)await s.write(`: keepalive
678
+ `;await this.write(r)}},RM=async(e,t,n)=>{try{await t(e)}catch(r){if(r instanceof Error&&n)await n(r,e),await e.writeSSE({event:"error",data:r.message});else console.error(r)}finally{e.close()}},$M=new WeakMap,qf=(e,t,n)=>{let{readable:r,writable:s}=new TransformStream,o=new Ax(s,r);if(Bl())e.req.raw.signal.addEventListener("abort",()=>{if(!o.closed)o.abort()});return $M.set(o.responseReadable,e),e.header("Transfer-Encoding","chunked"),e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),RM(o,t,n),e.newResponse(o.responseReadable)};var EM=15000,CM=new Set(["done","cancelled","error"]);function AM(e){let t=e.req.header("last-event-id")??e.req.query("after")??"0",n=Number(t);return Number.isFinite(n)&&n>=0?n:0}function Ix(e,t,n){e.header("Cache-Control","no-cache"),e.header("X-Accel-Buffering","no");let r=AM(e);return qf(e,async(s)=>{let o=r,a=null,l=[],c=!1,u=null,d=async(h)=>{if(h.seq<=o)return;if(o=h.seq,await s.writeSSE({id:String(h.seq),event:h.type,data:JSON.stringify(h)}),CM.has(h.type))c=!0},f=t.subscribe(n,(h)=>{if(a)a(h);else l.push(h)});s.onAbort(()=>{f?.unsubscribe(),c=!0,u?.()});for(let h of await Uv(n))await d(h);for(let h of l.splice(0))await d(h);if(!f||c){await Ox(s),f?.unsubscribe();return}let p=[];a=(h)=>{p.push(h),u?.()};while(!c&&!s.aborted){if(p.length===0){if(await new Promise((h)=>{let g=setTimeout(h,EM);u=()=>{clearTimeout(g),h()}}),u=null,p.length===0&&!c&&!s.aborted)await s.write(`: keepalive
679
679
 
680
- `);continue}for(let h of p.splice(0))await d(h)}if(f.unsubscribe(),!s.aborted)await ax(s)})}async function ax(e){await e.writeSSE({event:"end",data:"{}"})}var cx=Z({"+":"reject","target?":"string","repo?":"string","base?":"string","intent?":"string","models?":{"+":"reject","review?":"string","coordinator?":"string","walkthrough?":"string","intent?":"string"},"effort?":"string","maxCostUsd?":"number > 0","maxRounds?":"number.integer > 0","settingsFile?":"string","kind?":qs,"walkthrough?":"boolean","fromRun?":"string","full?":"boolean","github?":"boolean","head?":/^[0-9a-fA-F]{40}$/}),K4=Z({id:"string",url:"string"}),ux=Z({status:Id,"reason?":Pd,"note?":"string"}),dx=Z({path:"string",reviewed:"boolean"}),KP=Z("'resolving_target' | 'checking_registry' | 'building_map' | 'grouping' | 'reviewing' | 'coordinating' | 'walkthrough' | 'verifying' | 'writing'"),WP=Z({type:"'stage'",stage:KP}).or({type:"'slice'",index:"number",total:"number",title:"string",status:"'started' | 'ok' | 'failed'","costUsd?":"number","wallMs?":"number","findings?":"number"}).or({type:"'log'",message:"string"}).or({type:"'cost'",totalUsd:"number"}).or({type:"'budget'",totalUsd:"number",limitUsd:"number",skippedSlices:"number"}),GP=Z({type:"'groups'",groups:Od.array(),files:Z({path:"string",groupId:"string",classification:"'code' | 'docs' | 'skip'"}).array()}),VP=WP.or(GP).or({type:"'done'",status:"'complete'",findings:"number","carriedOver?":"number",costUsd:"number",wallMs:"number","noChanges?":"boolean","roundLimit?":"number","kind?":qs,"files?":"number"}).or({type:"'cancelled'"}).or({type:"'error'",message:"string"}),W4=VP.and({seq:"number",at:"string"}),G4=Z({app:"'diffloupe'",version:"string",pid:"number",defaultRepo:"string | null",activeRunId:"string | null",gh:{available:"boolean",authed:"boolean","message?":"string"},opencode:{path:"string | null",version:"string | null"}}),V4=Z({error:"string","activeRunId?":"string"});var XP=2097152;function fx(e){try{return Ve(e),!0}catch{return!1}}function px(e){let t=new jr;async function n(o){let a=e.runs.pendingRun(o);if(a)return a;if(!fx(o))return;try{return await gt(o)}catch(l){if(l instanceof Ln)return l;return}}let r=(o)=>({error:`no run ${o}`});t.get("/",async(o)=>o.json(await zt())),t.post("/",async(o)=>{let a;try{a=await o.req.json()}catch{return o.json({error:"request body must be JSON"},400)}let l=cx(a);if(l instanceof Z.errors)return o.json({error:l.summary},400);if(!l.repo&&!l.fromRun&&!e.defaultRepo)return o.json({error:"repo is required: the server was not started in a repository"},400);try{let{id:c}=await e.runs.start(l),u=new URL(`/runs/${c}`,o.req.url).href;return o.json({id:c,url:u},202)}catch(c){if(c instanceof wl)return o.json({error:c.message,...c.activeRunId?{activeRunId:c.activeRunId}:{}},409);let u=c instanceof Error?c.message:String(c);return o.json({error:u},c instanceof _e?400:500)}}),t.get("/:id",async(o)=>{let a=o.req.param("id"),l=await n(a);if(l instanceof Ln)return o.json({error:l.message},422);return l?o.json(l):o.json(r(a),404)}),t.get("/:id/diff",async(o)=>{let a=o.req.param("id");if(!fx(a))return o.json(r(a),404);try{let l=await zP(JP.join(Ve(a),"diff.patch"),"utf8");return o.text(l,200,{"Content-Type":"text/plain; charset=utf-8"})}catch{return o.json(r(a),404)}}),t.get("/:id/file",async(o)=>{let a=o.req.param("id"),l=o.req.query("side"),c=o.req.query("path");if(l!=="base"&&l!=="head"||!c)return o.json({error:"side=base|head and path are required"},400);let u=await n(a);if(!u)return o.json(r(a),404);if(u instanceof Ln)return o.json({error:u.message},422);let d=u.files.find((b)=>b.path===c);if(!d)return o.json({error:`${c} is not part of run ${a}`},404);if(l==="base"&&d.status==="added"||l==="head"&&d.status==="removed")return o.json({error:`${c} does not exist on the ${l} side`},404);if(d.isBinary)return o.json({error:`${c} is a binary file`},415);let f=l==="base"?u.base:u.head,p=l==="base"?d.previousPath??d.path:d.path,h=`${f}:${p}`,g=await re("git",["-C",u.repo.root,"cat-file","-s",h],{allowFail:!0});if(g.code!==0)return o.json({error:`cannot read ${h}`},404);if(Number(g.stdout.trim())>XP)return o.json({error:`${p} is larger than 2 MB`},413);let w=await re("git",["-C",u.repo.root,"show",h],{allowFail:!0});if(w.code!==0)return o.json({error:`cannot read ${h}`},404);return o.text(w.stdout,200,{"Content-Type":"text/plain; charset=utf-8"})}),t.get("/:id/events",async(o)=>{let a=o.req.param("id");if(!e.runs.isActive(a)&&!await n(a))return o.json(r(a),404);return lx(o,e.runs,a)}),t.get("/:id/state",async(o)=>{let a=o.req.param("id");if(!await n(a))return o.json(r(a),404);if(e.runs.pendingRun(a))return o.json(Mi());return o.json(await Fr(a))});async function s(o,a,l){let c=o.req.param("id")??"",u;try{u=await o.req.json()}catch{return o.json({error:"request body must be JSON"},400)}let d=a(u);if(d instanceof Z.errors)return o.json({error:d.summary},400);if(e.runs.isActive(c))return o.json({error:`run ${c} is still running`,activeRunId:c},409);let f=await n(c);if(!f)return o.json(r(c),404);if(f instanceof Ln)return o.json({error:f.message},422);try{return o.json(await zd(c,l(d)))}catch(p){if(p instanceof Pi)return o.json({error:p.message},400);if(p instanceof zs)return o.json({error:p.message},422);throw p}}return t.put("/:id/state/findings/:fid",(o)=>s(o,ux,(a)=>({op:"finding",ids:[o.req.param("fid")],status:a.status,reason:a.reason,note:a.note,at:new Date().toISOString()}))),t.put("/:id/state/files",(o)=>s(o,dx,(a)=>({op:"reviewed",paths:[a.path],value:a.reviewed}))),t.post("/:id/cancel",async(o)=>{let a=o.req.param("id");if(!e.runs.cancel(a))return o.json({error:`run ${a} is not running`},404);return o.json({id:a,cancelling:!0},202)}),t.delete("/:id",async(o)=>{let a=o.req.param("id");if(e.runs.isActive(a))return o.json({error:`run ${a} is still running`,activeRunId:a},409);if(!await n(a))return o.json(r(a),404);return o.json({removed:await Ys(a)})}),t}import jn from"path";import{existsSync as YP}from"fs";var hx=`<!doctype html>
680
+ `);continue}for(let h of p.splice(0))await d(h)}if(f.unsubscribe(),!s.aborted)await Ox(s)})}async function Ox(e){await e.writeSSE({event:"end",data:"{}"})}var Px=Z({"+":"reject","target?":"string","repo?":"string","base?":"string","intent?":"string","models?":{"+":"reject","review?":"string","coordinator?":"string","walkthrough?":"string","intent?":"string"},"effort?":"string","maxCostUsd?":"number > 0","maxRounds?":"number.integer > 0","settingsFile?":"string","kind?":Xs,"walkthrough?":"boolean","fromRun?":"string","full?":"boolean","github?":"boolean","head?":/^[0-9a-fA-F]{40}$/}),qJ=Z({id:"string",url:"string"}),Mx=Z({status:Kd,"reason?":Gd,"note?":"string"}),Tx=Z({path:"string",reviewed:"boolean"}),OM=Z("'resolving_target' | 'checking_registry' | 'building_map' | 'grouping' | 'reviewing' | 'coordinating' | 'walkthrough' | 'verifying' | 'writing'"),IM=Z({type:"'stage'",stage:OM}).or({type:"'slice'",index:"number",total:"number",title:"string",status:"'started' | 'ok' | 'failed'","costUsd?":"number","wallMs?":"number","findings?":"number"}).or({type:"'log'",message:"string"}).or({type:"'cost'",totalUsd:"number"}).or({type:"'budget'",totalUsd:"number",limitUsd:"number",skippedSlices:"number"}),PM=Z({type:"'groups'",groups:Hd.array(),files:Z({path:"string",groupId:"string",classification:"'code' | 'docs' | 'skip'"}).array()}),MM=IM.or(PM).or({type:"'done'",status:"'complete'",findings:"number","carriedOver?":"number",costUsd:"number",wallMs:"number","noChanges?":"boolean","roundLimit?":"number","kind?":Xs,"files?":"number"}).or({type:"'cancelled'"}).or({type:"'error'",message:"string"}),HJ=MM.and({seq:"number",at:"string"}),KJ=Z({app:"'diffloupe'",version:"string",pid:"number",defaultRepo:"string | null",activeRunId:"string | null",gh:{available:"boolean",authed:"boolean","message?":"string"},opencode:{path:"string | null",version:"string | null"}}),GJ=Z({error:"string","activeRunId?":"string"});var NM=2097152;function Dx(e){try{return Ve(e),!0}catch{return!1}}function Nx(e){let t=new Hr;async function n(o){let a=e.runs.pendingRun(o);if(a)return a;if(!Dx(o))return;try{return await gt(o)}catch(l){if(l instanceof Un)return l;return}}let r=(o)=>({error:`no run ${o}`});t.get("/",async(o)=>o.json(await Jt())),t.post("/",async(o)=>{let a;try{a=await o.req.json()}catch{return o.json({error:"request body must be JSON"},400)}let l=Px(a);if(l instanceof Z.errors)return o.json({error:l.summary},400);if(!l.repo&&!l.fromRun&&!e.defaultRepo)return o.json({error:"repo is required: the server was not started in a repository"},400);try{let{id:c}=await e.runs.start(l),u=new URL(`/runs/${c}`,o.req.url).href;return o.json({id:c,url:u},202)}catch(c){if(c instanceof Cl)return o.json({error:c.message,...c.activeRunId?{activeRunId:c.activeRunId}:{}},409);let u=c instanceof Error?c.message:String(c);return o.json({error:u},c instanceof _e?400:500)}}),t.get("/:id",async(o)=>{let a=o.req.param("id"),l=await n(a);if(l instanceof Un)return o.json({error:l.message},422);return l?o.json(l):o.json(r(a),404)}),t.get("/:id/diff",async(o)=>{let a=o.req.param("id");if(!Dx(a))return o.json(r(a),404);try{let l=await TM(DM.join(Ve(a),"diff.patch"),"utf8");return o.text(l,200,{"Content-Type":"text/plain; charset=utf-8"})}catch{return o.json(r(a),404)}}),t.get("/:id/file",async(o)=>{let a=o.req.param("id"),l=o.req.query("side"),c=o.req.query("path");if(l!=="base"&&l!=="head"||!c)return o.json({error:"side=base|head and path are required"},400);let u=await n(a);if(!u)return o.json(r(a),404);if(u instanceof Un)return o.json({error:u.message},422);let d=u.files.find((b)=>b.path===c);if(!d)return o.json({error:`${c} is not part of run ${a}`},404);if(l==="base"&&d.status==="added"||l==="head"&&d.status==="removed")return o.json({error:`${c} does not exist on the ${l} side`},404);if(d.isBinary)return o.json({error:`${c} is a binary file`},415);let f=l==="base"?u.base:u.head,p=l==="base"?d.previousPath??d.path:d.path,h=`${f}:${p}`,g=await re("git",["-C",u.repo.root,"cat-file","-s",h],{allowFail:!0});if(g.code!==0)return o.json({error:`cannot read ${h}`},404);if(Number(g.stdout.trim())>NM)return o.json({error:`${p} is larger than 2 MB`},413);let w=await re("git",["-C",u.repo.root,"show",h],{allowFail:!0});if(w.code!==0)return o.json({error:`cannot read ${h}`},404);return o.text(w.stdout,200,{"Content-Type":"text/plain; charset=utf-8"})}),t.get("/:id/events",async(o)=>{let a=o.req.param("id");if(!e.runs.isActive(a)&&!await n(a))return o.json(r(a),404);return Ix(o,e.runs,a)}),t.get("/:id/state",async(o)=>{let a=o.req.param("id");if(!await n(a))return o.json(r(a),404);if(e.runs.pendingRun(a))return o.json(Li());return o.json(await jr(a))});async function s(o,a,l){let c=o.req.param("id")??"",u;try{u=await o.req.json()}catch{return o.json({error:"request body must be JSON"},400)}let d=a(u);if(d instanceof Z.errors)return o.json({error:d.summary},400);if(e.runs.isActive(c))return o.json({error:`run ${c} is still running`,activeRunId:c},409);let f=await n(c);if(!f)return o.json(r(c),404);if(f instanceof Un)return o.json({error:f.message},422);try{return o.json(await lf(c,l(d)))}catch(p){if(p instanceof Fi)return o.json({error:p.message},400);if(p instanceof no)return o.json({error:p.message},422);throw p}}return t.put("/:id/state/findings/:fid",(o)=>s(o,Mx,(a)=>({op:"finding",ids:[o.req.param("fid")],status:a.status,reason:a.reason,note:a.note,at:new Date().toISOString()}))),t.put("/:id/state/files",(o)=>s(o,Tx,(a)=>({op:"reviewed",paths:[a.path],value:a.reviewed}))),t.post("/:id/cancel",async(o)=>{let a=o.req.param("id");if(!e.runs.cancel(a))return o.json({error:`run ${a} is not running`},404);return o.json({id:a,cancelling:!0},202)}),t.delete("/:id",async(o)=>{let a=o.req.param("id");if(e.runs.isActive(a))return o.json({error:`run ${a} is still running`,activeRunId:a},409);if(!await n(a))return o.json(r(a),404);return o.json({removed:await so(a)})}),t}import Bn from"path";import{existsSync as FM}from"fs";var Fx=`<!doctype html>
681
681
  <html lang="en">
682
682
  <head>
683
683
  <meta charset="utf-8">
@@ -743,11 +743,11 @@ setInterval(loadRuns, 5000);
743
743
  </script>
744
744
  </body>
745
745
  </html>
746
- `;function mx(e=import.meta.dir){let t=process.env.DIFFLOUPE_WEB_DIR;if(t)return jn.resolve(t);for(let n of[jn.join(e,"web"),jn.resolve(e,"../../dist/web")])if(YP(jn.join(n,"index.html")))return n;return null}async function gx(e,t){if(!t)return e.html(hx,200,{"Cache-Control":"no-cache"});let n;try{n=decodeURIComponent(new URL(e.req.url).pathname)}catch{return e.text("bad path",400)}let r=jn.resolve(t),s=jn.resolve(r,`.${n}`);if(s!==r&&!s.startsWith(r+jn.sep))return e.text("not found",404);if(s!==r&&!n.endsWith("/")){let a=Bun.file(s);if(await a.exists()){let l=n.startsWith("/assets/");return new Response(a,{headers:{"Cache-Control":l?"public, max-age=31536000, immutable":"no-cache"}})}if(jn.extname(n))return e.text("not found",404)}let o=Bun.file(jn.join(r,"index.html"));if(!await o.exists())return e.text("web UI not built",404);return new Response(o,{headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}var Ur=4517,ur="127.0.0.1",ZP=10;function QP(e,t=Ef(ur)){let n=new jr;return n.use("*",rx(t)),n.use("*",ix()),n.route("/api/health",sx(e)),n.route("/api/runs",px(e)),n.all("/api/*",(r)=>r.json({error:"not found"},404)),n.get("*",(r)=>gx(r,e.webDir)),n}function eM(e){let t=e;return t?.code==="EADDRINUSE"||/address already in use|EADDRINUSE|port .* in use/i.test(t?.message??"")}function tM(e,t){if(fo(e)||e==="0.0.0.0"||e==="::")return`http://localhost:${t}`;return`http://${e.includes(":")?`[${e}]`:e}:${t}`}async function Of(e){let t=e.host??ur,n=e.port??Ur,r=e.log??((f)=>console.error(f)),[s,o]=await Promise.all([Yv(),Zv()]);await Qv(e.defaultRepo,r);let a={version:Vn,defaultRepo:e.defaultRepo,dataDir:an(),webDir:mx(),gh:s,opencode:o,runs:new so(_l(e.defaultRepo??process.cwd()))},l=Ef(t),c=QP(a,l),u=e.strictPort?n:Math.min(n+ZP,65535),d;for(let f=n;f<=u;f++)try{let p=Bun.serve({hostname:t,port:f,fetch:c.fetch,idleTimeout:0});if(!fo(t))r(`Warning: listening on ${t}; anyone who can reach this machine on port ${f} can start reviews.`);return{ctx:a,url:tM(t,f),port:f,stop:()=>p.stop(!0)}}catch(p){if(!eM(p))throw p;d=p}throw Error(`no free port in ${n}-${u}: ${d instanceof Error?d.message:String(d)}`)}async function nM(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/health`,{signal:AbortSignal.timeout(500)});if(!t.ok)return null;let n=await t.json();return n.app==="diffloupe"?n:null}catch{return null}}async function If(e){let t=Array.from({length:11},(r,s)=>e+s).filter((r)=>r<=65535),n=await Promise.all(t.map(nM));return t.flatMap((r,s)=>{let o=n[s];return o?[{base:`http://localhost:${r}`,port:r,health:o}]:[]})}class Pl extends Error{status;constructor(e,t){super(e);this.status=t;this.name="ServerRequestError"}}async function _x(e,t){let n=await fetch(`${e}/api/runs`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json();if(!n.ok||"error"in r)throw new Pl("error"in r?r.error:`HTTP ${n.status}`,n.status);return r}async function wx(e,t){try{return(await fetch(`${e}/api/runs/${encodeURIComponent(t)}/cancel`,{method:"POST"})).ok}catch{return!1}}async function yx(e,t,n){let r=null,s=0;for(let o=0;o<5&&!r;o++){let a;try{a=await fetch(`${e}/api/runs/${encodeURIComponent(t)}/events?after=${s}`)}catch{await Bun.sleep(500);continue}if(!a.ok||!a.body)return null;let l=!1;for await(let c of rM(a.body)){if(c.event==="end"){l=!0;break}if(!c.data)continue;let u=JSON.parse(c.data);if(s=u.seq,n(u),u.type==="done"||u.type==="cancelled"||u.type==="error")r=u}if(l)break}return r}async function*rM(e){let t=new TextDecoder,n="",r="message",s=[];for await(let o of e){n+=t.decode(o,{stream:!0});let a;while((a=n.indexOf(`
746
+ `;function Lx(e=import.meta.dir){let t=process.env.DIFFLOUPE_WEB_DIR;if(t)return Bn.resolve(t);for(let n of[Bn.join(e,"web"),Bn.resolve(e,"../../dist/web")])if(FM(Bn.join(n,"index.html")))return n;return null}async function jx(e,t){if(!t)return e.html(Fx,200,{"Cache-Control":"no-cache"});let n;try{n=decodeURIComponent(new URL(e.req.url).pathname)}catch{return e.text("bad path",400)}let r=Bn.resolve(t),s=Bn.resolve(r,`.${n}`);if(s!==r&&!s.startsWith(r+Bn.sep))return e.text("not found",404);if(s!==r&&!n.endsWith("/")){let a=Bun.file(s);if(await a.exists()){let l=n.startsWith("/assets/");return new Response(a,{headers:{"Cache-Control":l?"public, max-age=31536000, immutable":"no-cache"}})}if(Bn.extname(n))return e.text("not found",404)}let o=Bun.file(Bn.join(r,"index.html"));if(!await o.exists())return e.text("web UI not built",404);return new Response(o,{headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}var Kr=4517,pr="127.0.0.1",LM=10;function jM(e,t=Uf(pr)){let n=new Hr;return n.use("*",kx(t)),n.use("*",Ex()),n.route("/api/health",Cx(e)),n.route("/api/runs",Nx(e)),n.all("/api/*",(r)=>r.json({error:"not found"},404)),n.get("*",(r)=>jx(r,e.webDir)),n}function UM(e){let t=e;return t?.code==="EADDRINUSE"||/address already in use|EADDRINUSE|port .* in use/i.test(t?.message??"")}function BM(e,t){if(vo(e)||e==="0.0.0.0"||e==="::")return`http://localhost:${t}`;return`http://${e.includes(":")?`[${e}]`:e}:${t}`}async function Hf(e){let t=e.host??pr,n=e.port??Kr,r=e.log??((f)=>console.error(f)),[s,o]=await Promise.all([bx(),vx()]);await xx(e.defaultRepo,r);let a={version:Jn,defaultRepo:e.defaultRepo,dataDir:cn(),webDir:Lx(),gh:s,opencode:o,runs:new mo(El(e.defaultRepo??process.cwd()))},l=Uf(t),c=jM(a,l),u=e.strictPort?n:Math.min(n+LM,65535),d;for(let f=n;f<=u;f++)try{let p=Bun.serve({hostname:t,port:f,fetch:c.fetch,idleTimeout:0});if(!vo(t))r(`Warning: listening on ${t}; anyone who can reach this machine on port ${f} can start reviews.`);return{ctx:a,url:BM(t,f),port:f,stop:()=>p.stop(!0)}}catch(p){if(!UM(p))throw p;d=p}throw Error(`no free port in ${n}-${u}: ${d instanceof Error?d.message:String(d)}`)}async function qM(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/health`,{signal:AbortSignal.timeout(500)});if(!t.ok)return null;let n=await t.json();return n.app==="diffloupe"?n:null}catch{return null}}async function Kf(e){let t=Array.from({length:11},(r,s)=>e+s).filter((r)=>r<=65535),n=await Promise.all(t.map(qM));return t.flatMap((r,s)=>{let o=n[s];return o?[{base:`http://localhost:${r}`,port:r,health:o}]:[]})}class ql extends Error{status;constructor(e,t){super(e);this.status=t;this.name="ServerRequestError"}}async function Ux(e,t){let n=await fetch(`${e}/api/runs`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json();if(!n.ok||"error"in r)throw new ql("error"in r?r.error:`HTTP ${n.status}`,n.status);return r}async function Bx(e,t){try{return(await fetch(`${e}/api/runs/${encodeURIComponent(t)}/cancel`,{method:"POST"})).ok}catch{return!1}}async function qx(e,t,n){let r=null,s=0;for(let o=0;o<5&&!r;o++){let a;try{a=await fetch(`${e}/api/runs/${encodeURIComponent(t)}/events?after=${s}`)}catch{await Bun.sleep(500);continue}if(!a.ok||!a.body)return null;let l=!1;for await(let c of HM(a.body)){if(c.event==="end"){l=!0;break}if(!c.data)continue;let u=JSON.parse(c.data);if(s=u.seq,n(u),u.type==="done"||u.type==="cancelled"||u.type==="error")r=u}if(l)break}return r}async function*HM(e){let t=new TextDecoder,n="",r="message",s=[];for await(let o of e){n+=t.decode(o,{stream:!0});let a;while((a=n.indexOf(`
747
747
  `))>=0){let l=n.slice(0,a).replace(/\r$/,"");if(n=n.slice(a+1),l===""){if(s.length)yield{event:r,data:s.join(`
748
- `)};else if(r!=="message")yield{event:r,data:""};r="message",s=[]}else if(l.startsWith(":"))continue;else{let c=l.indexOf(":"),u=c<0?l:l.slice(0,c),d=c<0?"":l.slice(c+1).replace(/^ /,"");if(u==="event")r=d;else if(u==="data")s.push(d)}}}}var bx=1e4;function vx(e,t){return[...t,e]}function Ml(e){let t=Number(e);if(!Number.isInteger(t)||t<1||t>65535)throw new Gn("must be a port number 1-65535");return t}function sM(e){let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new Gn("must be a positive number of US dollars");return t}function oM(e){let t=Number(e);if(!Number.isInteger(t)||t<1)throw new Gn("must be a whole number of rounds, 1 or more");return t}function Pf(e){if(!Ft.includes(e))throw new Gn(`must be one of ${Ft.join(", ")}`);return e}function Fe(e){console.error(e)}function xx(e){let t=io(e);if(t)Fe(t)}async function Rx(e){let t=await re("git",["-C",e,"rev-parse","--show-toplevel"],{allowFail:!0}).catch(()=>null);return t&&t.code===0?t.stdout.trim():null}async function Tl(e){let t=await Kr();return{host:e.host??t.host??ur,port:e.port??t.port??Ur}}async function Fl(e,t){if(t&&!await $v(e))Fe(`Could not open a browser; visit ${e}`)}function Nl(e,t){return`${e}/runs/${t}`}async function aM(e,t){let n;try{({id:n}=await _x(e,await no(t)))}catch(a){if(a instanceof Pl&&a.status===409)return-1;return Fe(ln.default.red(`Error: ${a instanceof Error?a.message:String(a)}`)),1}let r=Nl(e,n);Fe(`DiffLoupe ready at ${r} (running on the server already at ${e})`),await Fl(r,t.open);let s=oo(()=>{Fe(`
749
- Cancelling the run (Ctrl+C again to stop following it)...`),wx(e,n)}),o=await yx(e,n,xx);if(s(),o?.type==="done")return Fe(`Results: ${r}`),0;return o?.type==="cancelled"?130:1}async function lM(e){let t=await no(e),{host:n,port:r}=await Tl(e),s;try{s=await Of({host:n,port:r,defaultRepo:await Rx(t.repo??process.cwd())??null,log:Fe})}catch(f){return Fe(ln.default.red(`Error starting server: ${f instanceof Error?f.message:String(f)}`)),1}let o=s.ctx.runs;o.watch((f,p)=>xx(p));let a;try{a=await o.start(t)}catch(f){return Fe(ln.default.red(`Error: ${f instanceof Error?f.message:String(f)}`)),await s.stop(),1}let l=Nl(s.url,a.id);Fe(ln.default.green(`DiffLoupe ready at ${l}`)),await Fl(l,e.open);let c=!0,u=!1;oo(()=>{if(!c)process.exit(0);u=!0,Fe(`
750
- Cancelling: stopping agents and removing the worktree (Ctrl+C again to exit now)...`);let f=o.cancel(a.id)??Promise.resolve();Promise.race([f,Bun.sleep(bx)]).then(()=>process.exit(130))});let d=await a.done;if(c=!1,u)return new Promise(()=>{});if(d.status==="complete")Fe(`Results: ${l}`);else if(d.status==="failed")Fe(`Results (failed run): ${l}`);return Fe(ln.default.dim("Server still running. Press Ctrl+C to stop.")),new Promise(()=>{})}function cM(e){if(e.github||e.head){let t=!1;try{t=Rn(e.target).kind==="pr"}catch{t=!1}if(!t)return`${e.github?"--github":"--head"} needs a pull request target (#<n>, pr:<n>, or a PR URL)`}if(e.head&&!/^[0-9a-f]{40}$/i.test(e.head))return"--head must be a full 40-character commit SHA";if(!e.headless){for(let[t,n]of[["--out",e.out],["--json",e.json],["--fail-on",e.failOn]])if(n)return`${t} needs --headless`}return null}async function Sx(e,t){let n={...t,...e?{target:e}:{}},r=cM(n);if(r)Fe(ln.default.red(`Error: ${r}`)),process.exit(2);if(n.headless)process.exit(await Sv(n));let{port:s}=await Tl(n);for(let o of await If(s)){if(o.health.activeRunId)continue;let a=await aM(o.base,n);if(a>=0)process.exit(a)}process.exit(await lM(n))}var $x="worktree (default), staged, a commit (<sha>, HEAD~2, commit:<rev>), a range (<a>..<b>, <a>...<b>), a branch (<name>, branch:<name>), #<pr>, pr:<n>, or a PR URL";function kx(){return new It("review").description("Review changes with the multi-agent reviewer (requires opencode, tilth, git; gh for PRs)").argument("[target]",$x).option("-C, --repo <path>","Repository to review (default: current directory)").option("--base <ref>","For staged/worktree: diff against merge-base(<ref>, HEAD) instead of HEAD").option("-i, --intent <text>","Describe the intent of the changes").option("--intent-file <path>","Read the intent from a file").option("--model <stage=id>","Model for a stage: review, coordinator, walkthrough, intent (repeatable)",vx,[]).option("--effort <level>","Reasoning effort: the model variant to use, e.g. low, medium, high").option("--config <file>","Per-repo review settings JSON (models, effort, surfaces, extraExcludes, post, instructions)").option("--max-cost <usd>","Stop starting new review slices once spending reaches this many US dollars. Slices already running finish, so the total can exceed the limit by up to 6 slices at $3 each plus the coordinator and walkthrough (default: maxCostUsd from ~/.config/diffloupe/config.json, else no limit)",sM).option("--max-rounds <n>","Skip the review, before any model call, when this change has already been reviewed <n> times (with --headless, exit 4). With --github the rounds are counted from the PR's summary comment",oM).option("--full","Review every changed file even when this target was reviewed before (default: a re-review looks only at files changed since the last run)",!1).option("--host <host>",`Address for the server to listen on (default: ${ur})`).option("--port <port>",`Port for the server (default: ${Ur}, or the next free one)`,Ml).option("--open","Open the run in a browser",!1).option("--headless","Run in the terminal without a server and print a summary to stdout",!1).option("--markdown","With --headless: print the full review markdown instead of the summary",!1).option("--github","For a PR target: render for posting to GitHub (prior comments come from the PR, payloads.json is written, and failing to read the PR is an error)").option("--head <sha>","For a PR target: review this 40-character commit instead of the PR's current head").option("--out <dir>","With --headless: copy the run's files and result.json into <dir>").option("--json","With --headless: print only the result object as JSON on stdout").option("--fail-on <severity>","With --headless: exit 3 when a posted finding is at or above this severity (blocker, should-fix, nice-to-have, question)",Pf).exitOverride((e)=>process.exit(e.exitCode===0?0:2)).action(Sx)}function Ex(){return new It("diff").description("Open a diff grouped by how the code connects, with no review agents (requires git; gh for PRs). --walkthrough adds a guide from one model call.").argument("[target]",$x).option("-C, --repo <path>","Repository to diff (default: current directory)").option("--base <ref>","For staged/worktree: diff against merge-base(<ref>, HEAD) instead of HEAD").option("--walkthrough","Add the walkthrough guide (one model call; needs opencode and a credential)",!1).option("-i, --intent <text>","With --walkthrough: describe the intent of the changes").option("--intent-file <path>","With --walkthrough: read the intent from a file").option("--model <walkthrough=id>","With --walkthrough: the walkthrough model",vx,[]).option("--effort <level>","With --walkthrough: reasoning effort (model variant)").option("--config <file>","Per-repo review settings JSON (models, effort, extraExcludes)").option("--host <host>",`Address for the server to listen on (default: ${ur})`).option("--port <port>",`Port for the server (default: ${Ur}, or the next free one)`,Ml).option("--open","Open the run in a browser",!1).option("--headless","Print the grouped file list to stdout without a server",!1).action((e,t)=>Sx(e,{...t,kind:"diff"}))}function Ax(){return new It("open").description("Print (or open) the URL of a saved run, starting a server if none is running").argument("[runId]","Run to open (default: the run list)").option("--last","Open the most recent run",!1).option("--host <host>",`Address for a new server to listen on (default: ${ur})`).option("--port <port>",`Port to look for a server on (default: ${Ur})`,Ml).option("--open","Open the URL in a browser",!1).action(async(e,t)=>{let n=e;if(!n&&t.last){if(n=(await zt())[0]?.id,!n)Fe("No saved runs."),process.exit(1)}let{host:r,port:s}=await Tl(t),o=(await If(s))[0];if(o){let a=n?Nl(o.base,n):o.base;console.log(a),await Fl(a,t.open),process.exit(0)}await Cx({...t,host:r,port:s},n)})}async function Cx(e,t){let n=iM.resolve(e.repo??process.cwd()),r;try{r=await Of({host:e.host,port:e.port,defaultRepo:await Rx(n),log:Fe})}catch(o){Fe(ln.default.red(`Error starting server: ${o instanceof Error?o.message:String(o)}`)),process.exit(1)}let s=t?Nl(r.url,t):r.url;return Fe(ln.default.green(`DiffLoupe ready at ${s}`)),Fe(ln.default.dim("Press Ctrl+C to stop.")),r.ctx.runs.watch((o,a)=>{let l=io(a);if(l)Fe(`${ln.default.dim(o)} ${l}`)}),oo(()=>{let o=r.ctx.runs.activeRunId;if(!o)process.exit(0);Fe(`
751
- Cancelling the active run (Ctrl+C again to exit now)...`);let a=r.ctx.runs.cancel(o)??Promise.resolve();Promise.race([a,Bun.sleep(bx)]).then(()=>process.exit(130))}),await Fl(s,e.open),r}function Ox(){return new It("serve").description("Start the DiffLoupe server and keep it running").option("-C, --repo <path>","Repository runs use when a request names none (default: current directory)").option("--host <host>",`Address to listen on (default: ${ur})`).option("--port <port>",`Port (default: ${Ur}, or the next free one)`,Ml).option("--open","Open the server in a browser",!1).action(async(e)=>{await Cx({...e,...await Tl(e)})})}var uM=3;function Dl(e){console.error(Mf.default.red(`Error: ${e}`)),process.exit(2)}function Ix(){return new It("gate").description("Fail when a pull request still has open review findings at or above a severity (reads GitHub, runs no model)").argument("<target>","#<pr>, pr:<n>, owner/repo#<n>, or a PR URL").requiredOption("--fail-on <severity>","blocker, should-fix, nice-to-have, or question",Pf).option("--json","Print the result as JSON").option("--status [sha]","Also write the result as the diffloupe/gate commit status on this commit (default: the PR head). Needs statuses: write").option("--override-label <name>","Pass whatever is open when the pull request has this label").option("--count-author-resolved","Treat threads the pull request's author resolved as closed").option("--review-missing","This push's review did not reach the PR (the review or post job failed): fail if the bot has never reviewed it").action(async(e,t)=>{let n;try{n=Rn(e)}catch(a){Dl(a instanceof Error?a.message:String(a))}if(n.kind!=="pr")Dl("gate needs a pull request target (#<n>, pr:<n>, or a PR URL)");let r=t.status===!0?void 0:t.status;if(r!==void 0&&!/^[0-9a-f]{40}$/i.test(r))Dl("--status needs a full 40-character commit SHA, or no value for the PR head");let s=n.repo??await oi(process.cwd());if(s.startsWith("local/"))Dl("no GitHub repository: pass owner/repo#<n> or set GH_REPO");let o=(a)=>oe("gh",a);try{let a=await mv(s,n.pr,{failOn:t.failOn,...t.overrideLabel?{overrideLabel:t.overrideLabel}:{},...t.countAuthorResolved?{countAuthorResolved:!0}:{},...t.reviewMissing?{reviewMissing:!0}:{},...t.status?{status:r?{sha:r}:{}}:{}},{readThreads:(l,c)=>Ph(l,c,{gh:o}),readComments:(l,c)=>as(`repos/${l}/issues/${c}/comments`,o),gh:o});if(t.json)console.log(JSON.stringify(a,null,2));else console.log(hv(a).join(`
752
- `));process.exit(a.fails?uM:0)}catch(a){console.error(Mf.default.red(`Error: ${a instanceof Error?a.message:String(a)}`)),process.exit(1)}})}import{rm as bM}from"fs/promises";import vM from"path";var Br=ko(zi(),1);var dM="unrecorded",Ff=()=>({change:{measured:0,acted:0,control:0},preexisting:{measured:0,acted:0,control:0},stillListed:0});function Fx(e,t){if(!t||!e.priorActedOn)return[];let n=new Set(e.findings.map((r)=>Dn(r.id)));return e.priorActedOn.flatMap((r)=>{let s=t.findings.find((o)=>o.id===r.id);if(!s)return[];return[{acted:r.acted,control:r.control,finding:s,stillListed:r.acted&&n.has(Dn(r.id))}]})}function Nx(e,t){let n=t.finding.preexisting?e.preexisting:e.change;if(n.measured++,t.acted)n.acted++;if(t.control)n.control++;if(t.stillListed)e.stillListed++}function fM(e){let t=Ff();for(let n of e){for(let r of["change","preexisting"])t[r].measured+=n[r].measured,t[r].acted+=n[r].acted,t[r].control+=n[r].control;t.stillListed+=n.stillListed}return t}function pM(e){let t={};for(let n of e)t[n]=(t[n]??0)+1;return t}function hM(e){let t={};for(let n of e)for(let[r,s]of Object.entries(n))t[r]=(t[r]??0)+s;return t}function Px(e){return Object.entries(e).filter(([,t])=>t>0).sort((t,n)=>n[1]-t[1]).map(([t,n])=>`${n} ${t}`).join(", ")}var mM=()=>({blocker:0,"should-fix":0,"nice-to-have":0,question:0}),gM=(e)=>Object.values(e).reduce((t,n)=>t+n,0),Dx=({run:e})=>e.status==="complete"&&e.meta.kind!=="diff"&&!e.meta.roundLimit;function Lx(e){let t=e.filter(Dx),n=new Map(t.map((o)=>[o.run.id,o])),r=(o)=>{let a=new Set,l=o;while(l.run.priorRunId&&n.has(l.run.priorRunId)&&!a.has(l.run.id))a.add(l.run.id),l=n.get(l.run.priorRunId)??l;return l.run.id},s=new Map;for(let o of t){let a=r(o);s.set(a,[...s.get(a)??[],o])}return[...s.values()].map((o)=>_M(o.sort((a,l)=>a.run.createdAt.localeCompare(l.run.createdAt)),n)).sort((o,a)=>a.lastAt.localeCompare(o.lastAt))}function _M(e,t){let n=e[0]?.run,r=e.at(-1);if(!n||!r)throw Error("empty chain");let s=mM(),o=0,a=0,l=0,c=new Map,u=nl(),d=Ff(),f=e.map(({run:h,state:g},w)=>{let b=Hs(h);Hs(h,u);let x=b.calls?rl(b):null,R=h.findings.filter((k)=>!k.carriedFrom);for(let k of R)if(k.preexisting)o++;else s[k.severity]++;let P=h.priorRunId?t.get(h.priorRunId)?.run:void 0,M=P?h.resolved:[];for(let k of M)if(a++,P?.findings.find((E)=>E.id===k.id)?.preexisting)l++;for(let k of Fx(h,P))Nx(d,k);for(let[k,E]of Object.entries(g.findingStatus))if(E==="dismissed")c.set(k,g.findingNotes?.[k]?.reason??"unrecorded");return{id:h.id,round:h.round??w+1,createdAt:h.createdAt,new:R.length,newPreexisting:R.filter((k)=>k.preexisting).length,carried:h.findings.length-R.length,resolved:M.length,costUsd:h.meta.costUsd,...h.meta.reviewScope?{scope:h.meta.reviewScope}:{},...h.meta.promptVersion?{promptVersion:h.meta.promptVersion}:{},...x!==null?{cacheShare:x}:{}}}),p=new Set(Object.entries(r.state.findingStatus).flatMap(([h,g])=>g==="dismissed"?[h]:[]));return{key:ol(n.repo,n.target),repo:n.repo.slug??n.repo.root,target:lr(n.target),rounds:f,raised:s,raisedPreexisting:o,fixed:a,fixedPreexisting:l,dismissed:c.size,dismissedBy:pM(c.values()),open:r.run.findings.filter((h)=>!p.has(h.id)).length,costUsd:f.reduce((h,g)=>h+g.costUsd,0),usage:u,acted:d,disputes:wM(r.run),lastAt:r.run.createdAt}}function wM(e){let t={withdrawn:0,upheld:0,unjudged:0};for(let n of e.disputes??[])t[n.outcome]++;return t}function Mx(e){if(!e.withdrawn&&!e.upheld&&!e.unjudged)return null;return`${e.withdrawn} withdrawn, ${e.upheld} upheld for a human, ${e.unjudged} awaiting a ruling`}function Nf(e){let t=e.reduce((s,o)=>s+gM(o.raised),0),n=e.reduce((s,o)=>s+o.fixed-o.fixedPreexisting,0),r=e.reduce((s,o)=>s+o.rounds.length,0);return{chains:e.length,meanRounds:e.length?r/e.length:0,pastThreeRounds:e.length?e.filter((s)=>s.rounds.length>3).length/e.length:0,raised:t,fixed:e.reduce((s,o)=>s+o.fixed,0),dismissed:e.reduce((s,o)=>s+o.dismissed,0),dismissedBy:hM(e.map((s)=>s.dismissedBy)),resolutionRate:t?n/t:null,costUsd:e.reduce((s,o)=>s+o.costUsd,0),usage:e.reduce((s,o)=>(s.input+=o.usage.input,s.output+=o.usage.output,s.reasoning+=o.usage.reasoning,s.cacheRead+=o.usage.cacheRead,s.cacheWrite+=o.usage.cacheWrite,s.calls+=o.usage.calls,s.firstStepShares.push(...o.usage.firstStepShares),s),nl()),acted:fM(e.map((s)=>s.acted)),disputes:e.reduce((s,o)=>({withdrawn:s.withdrawn+o.disputes.withdrawn,upheld:s.upheld+o.disputes.upheld,unjudged:s.unjudged+o.disputes.unjudged}),{withdrawn:0,upheld:0,unjudged:0})}}function jx(e){let t=e.filter(Dx),n=new Map(t.map((o)=>[o.run.id,o.run])),r=new Map,s=(o)=>{let a=o.meta.promptVersion??dM,l=o.meta.instructionsHash??"none",c=`${a}/${l}`,u=r.get(c);if(!u)u={promptVersion:a,instructionsHash:l,runs:0,raised:0,raisedPreexisting:0,fixed:0,fixedPreexisting:0,costUsd:0,acted:Ff()},r.set(c,u);return u};for(let{run:o}of t){let a=s(o);a.runs++,a.costUsd+=o.meta.costUsd;for(let u of o.findings){if(u.carriedFrom)continue;if(u.preexisting)a.raisedPreexisting++;else a.raised++}let l=o.priorRunId?n.get(o.priorRunId):void 0;if(!l)continue;let c=(u)=>n.get(u?.carriedFrom??l.id)??l;for(let u of o.resolved){let d=l.findings.find((p)=>p.id===u.id),f=s(c(d));if(d?.preexisting)f.fixedPreexisting++;else f.fixed++}for(let u of Fx(o,l))Nx(s(c(u.finding)).acted,u)}return[...r.values()].sort((o,a)=>a.runs-o.runs)}var Li=(e)=>e===null?"n/a":`${Math.round(e*100)}%`,po=(e)=>`$${e.toFixed(2)}`;function yM(e){let t=Object.entries(e).filter(([,n])=>n>0).map(([n,r])=>`${r} ${n}`);return t.length?t.join(", "):"none"}function Tx(e){let t=e.measured?e.acted/e.measured:0,n=e.measured?e.control/e.measured:0,r=Math.round((t-n)*100);return`${e.acted} of ${e.measured} edited (${Li(t)}), control ${Li(n)}, ${r>=0?"+":""}${r} points`}function Tf(e){if(!e.change.measured&&!e.preexisting.measured)return null;let t=[e.change.measured?Tx(e.change):"none on the change"];if(e.preexisting.measured)t.push(`pre-existing ${Tx(e.preexisting)}`);if(e.stillListed)t.push(`${e.stillListed} edited but still listed`);return t.join("; ")}function Ux(e,t){if(e.length===0)return"No complete review runs match.";let n=[];for(let l of e){let c=l.rounds.length;n.push(`${l.target} ${l.repo} (${c} round${c===1?"":"s"}, ${po(l.costUsd)})`);for(let g of l.rounds){let w=g.newPreexisting?` (${g.newPreexisting} pre-existing)`:"",b=g.scope==="incremental"?", changes only":"",x=g.cacheShare===void 0?"":`, ${Li(g.cacheShare)} cached`;n.push(` round ${g.round} ${g.id} ${g.new} new${w}, ${g.carried} carried, ${g.resolved} fixed${b}, ${po(g.costUsd)}${x}`)}let u=Ks(l.usage);if(u)n.push(` tokens: ${u}`);let d=l.fixed?`, ${po(l.costUsd/l.fixed)} per fixed finding`:"";n.push(` raised: ${yM(l.raised)}${l.raisedPreexisting?`; ${l.raisedPreexisting} pre-existing`:""}`);let f=Px(l.dismissedBy);n.push(` fixed ${l.fixed}, dismissed ${l.dismissed}${f?` (${f})`:""}, still open at last run ${l.open}${d}`);let p=Tf(l.acted);if(p)n.push(` acted on: ${p}`);let h=Mx(l.disputes);if(h)n.push(` disputes: ${h}`);n.push("")}let r=Nf(e);if(n.push(`${r.chains} chain${r.chains===1?"":"s"}, ${r.meanRounds.toFixed(1)} rounds on average, ${Li(r.pastThreeRounds)} past three rounds`,`${r.raised} raised on the change, ${r.fixed} fixed, resolution rate ${Li(r.resolutionRate)}, ${po(r.costUsd)} total`),r.dismissed)n.push(`${r.dismissed} dismissed: ${Px(r.dismissedBy)}`);let s=Ks(r.usage);if(s)n.push(`tokens over ${r.usage.calls} agent calls: ${s}`);let o=Tf(r.acted);if(o)n.push(`prior findings acted on: ${o}`);let a=Mx(r.disputes);if(a)n.push(`disputes: ${a}`);if(t){n.push("","By prompt version / instructions:");for(let l of t){let c=l.raised?Li(l.fixed/l.raised):"n/a";n.push(` ${l.promptVersion} / ${l.instructionsHash} ${l.runs} run${l.runs===1?"":"s"}, ${l.raised} raised (${l.raisedPreexisting} pre-existing), ${l.fixed} fixed, resolution rate ${c}, ${po(l.costUsd)}`);let u=Tf(l.acted);if(u)n.push(` acted on: ${u}`)}}return n.join(`
753
- `)}async function xM(e,t=gt){try{return await t(e)}catch(n){console.error(Br.default.red(`No run.json for ${e}: ${n instanceof Error?n.message:String(n)}`)),process.exit(1)}}function Kx(){let e=new It("runs").description("List saved runs").enablePositionalOptions().option("--json","Print run headers as JSON",!1).option("--kind <kind>","Only review or diff runs",Bx).action(async(r)=>{let s=qx(await zt(),r.kind);console.log(r.json?JSON.stringify(s,null,2):Ay(s))});e.command("show").description("Show a saved run: groups, files, findings and anchors").argument("<id>","Run id").option("--json","Print run.json",!1).option("--markdown","Print the findings as markdown, as the web UI's Copy all does",!1).option("--over-cap","With --markdown, include findings over the posting cap",!1).option("--dismissed","With --markdown, include dismissed findings",!1).action(async(r,s)=>{let o=await xM(r,s.json||s.markdown?gt:Vd),a=await Fr(r);if(s.markdown){process.stdout.write(Ws(o,{includeOverCap:s.overCap,state:a,includeDismissed:s.dismissed}));return}console.log(s.json?JSON.stringify({...o,state:a},null,2):Iy(o,a))});let t=(r,s)=>e.command(r).description(s).argument("<run>","Run id").argument("<findings...>","Finding ids, as runs show and the markdown export print them"),n=async(r,s,o,a={})=>{try{await Jy(r,s,o,a)}catch(c){console.error(Br.default.red(c instanceof Error?c.message:String(c))),process.exit(1)}console.log(`${o==="open"?"reopened":o} ${s.length} finding${s.length===1?"":"s"} in ${r}`)};return t("dismiss","Dismiss findings, with the reason, so later rounds and stats know why").requiredOption("--reason <reason>",`Why: ${el.join(", ")}`,RM).option("--note <text>","A short explanation").action(async(r,s,o)=>n(r,s,"dismissed",o)),t("accept","Mark findings accepted: real problems to fix").action(async(r,s)=>n(r,s,"accepted")),t("reopen","Clear the accepted or dismissed mark on findings").action(async(r,s)=>n(r,s,"open")),e.command("stats").description("How findings fared across re-reviews of the same change: raised, fixed, dismissed, still open").option("--repo <path-or-slug>","Only runs in this repository (a path, or owner/name)").option("--since <age>","Only chains reviewed within this window, e.g. 30d, 12h, 2w").option("--by-version","Also split the counts by prompt version and repo instructions",!1).option("--json","Print the stats as JSON",!1).action(async(r)=>{let s=r.since===void 0?void 0:Hx(r.since);if(s===null)console.error(Br.default.red("--since takes a number with d, h, or w")),process.exit(1);let o=r.repo===void 0?void 0:vM.resolve(r.repo),a=(await zt()).filter((p)=>!p.invalid&&p.status==="complete"&&p.kind!=="diff"&&(r.repo===void 0||p.repo.root===o||p.repo.slug===r.repo)),l=await Promise.all(a.map(async(p)=>({run:await Vd(p.id),state:await Fr(p.id)}))),c=s===void 0?void 0:new Date(Date.now()-s).toISOString(),u=Lx(l).filter((p)=>c===void 0||p.lastAt>=c),d=new Set(u.flatMap((p)=>p.rounds.map((h)=>h.id))),f=r.byVersion?jx(l.filter((p)=>d.has(p.run.id))):void 0;if(r.json){console.log(JSON.stringify({chains:u,totals:Nf(u),...f?{versions:f}:{}},null,2));return}console.log(Ux(u,f))}),e.command("rm").description("Delete a saved run, its artifacts and the git refs that pin its commits").argument("<id>","Run id").action(async(r)=>{let s=await Ys(r);if(s.length===0)console.error(Br.default.yellow(`Nothing found for ${r}`)),process.exit(1);for(let o of s)console.log(`removed ${o}`)}),e.command("prune").description("Delete old runs and orphaned scratch files. Lists what would go unless --yes is given").option("--older-than <age>","Only runs older than this, e.g. 30d, 12h, 2w","30d").option("--keep <n>","Always keep this many of the newest runs","20").option("--kind <kind>","Only review or diff runs (--keep then counts runs of that kind)",Bx).option("--yes","Delete instead of listing",!1).action(async(r)=>{let s=Hx(r.olderThan),o=Number(r.keep);if(s===null||!Number.isInteger(o)||o<0)console.error(Br.default.red("--older-than takes a number with d, h, or w; --keep takes a whole number")),process.exit(1);let a=Zy(qx(await zt(),r.kind),{olderThanMs:s,keep:o}),l=await Qy();if(a.length===0&&l.length===0){console.log("Nothing to prune");return}if(!r.yes){for(let c of a)console.log(`would delete run ${c.id} (${c.createdAt})`);if(l.length>0)console.log(`would delete ${l.length} orphaned scratch entries`);console.log(Br.default.dim("Run again with --yes to delete."));return}for(let c of a)await Ys(c.id),console.log(`deleted run ${c.id}`);for(let c of l)await bM(c,{recursive:!0,force:!0});if(l.length>0)console.log(`deleted ${l.length} orphaned scratch entries`)}),e}function RM(e){let t=el.find((n)=>n===e);if(!t)throw new Gn(`must be one of ${el.join(", ")}`);return t}function Bx(e){if(e!=="review"&&e!=="diff")throw new Gn("must be review or diff");return e}function qx(e,t){return t?e.filter((n)=>(n.kind??"review")===t):e}var SM={h:3600000,d:86400000,w:604800000};function Hx(e){let t=/^(\d+)([hdw])$/.exec(e.trim());return t?Number(t[1])*SM[t[2]]:null}function $M(){return new It().name("diffloupe").description("Grouped diffs and multi-agent code review for local changes and pull requests").version(Vn).enablePositionalOptions().addCommand(kx()).addCommand(Ex()).addCommand(Ax()).addCommand(Ox()).addCommand(Kx()).addCommand(dv()).addCommand(Ix())}function Wx(){$M().parseAsync()}Wx();
748
+ `)};else if(r!=="message")yield{event:r,data:""};r="message",s=[]}else if(l.startsWith(":"))continue;else{let c=l.indexOf(":"),u=c<0?l:l.slice(0,c),d=c<0?"":l.slice(c+1).replace(/^ /,"");if(u==="event")r=d;else if(u==="data")s.push(d)}}}}var Hx=1e4;function Kx(e,t){return[...t,e]}function Hl(e){let t=Number(e);if(!Number.isInteger(t)||t<1||t>65535)throw new zn("must be a port number 1-65535");return t}function GM(e){let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new zn("must be a positive number of US dollars");return t}function WM(e){let t=Number(e);if(!Number.isInteger(t)||t<1)throw new zn("must be a whole number of rounds, 1 or more");return t}function Gf(e){if(!Nt.includes(e))throw new zn(`must be one of ${Nt.join(", ")}`);return e}function De(e){console.error(e)}function Gx(e){let t=ho(e);if(t)De(t)}async function Wx(e){let t=await re("git",["-C",e,"rev-parse","--show-toplevel"],{allowFail:!0}).catch(()=>null);return t&&t.code===0?t.stdout.trim():null}async function Kl(e){let t=await Jr();return{host:e.host??t.host??pr,port:e.port??t.port??Kr}}async function Gl(e,t){if(t&&!await zv(e))De(`Could not open a browser; visit ${e}`)}function Wl(e,t){return`${e}/runs/${t}`}async function VM(e,t){let n;try{({id:n}=await Ux(e,await uo(t)))}catch(a){if(a instanceof ql&&a.status===409)return-1;return De(un.default.red(`Error: ${a instanceof Error?a.message:String(a)}`)),1}let r=Wl(e,n);De(`DiffLoupe ready at ${r} (running on the server already at ${e})`),await Gl(r,t.open);let s=go(()=>{De(`
749
+ Cancelling the run (Ctrl+C again to stop following it)...`),Bx(e,n)}),o=await qx(e,n,Gx);if(s(),o?.type==="done")return De(`Results: ${r}`),0;return o?.type==="cancelled"?130:1}async function zM(e){let t=await uo(e),{host:n,port:r}=await Kl(e),s;try{s=await Hf({host:n,port:r,defaultRepo:await Wx(t.repo??process.cwd())??null,log:De})}catch(f){return De(un.default.red(`Error starting server: ${f instanceof Error?f.message:String(f)}`)),1}let o=s.ctx.runs;o.watch((f,p)=>Gx(p));let a;try{a=await o.start(t)}catch(f){return De(un.default.red(`Error: ${f instanceof Error?f.message:String(f)}`)),await s.stop(),1}let l=Wl(s.url,a.id);De(un.default.green(`DiffLoupe ready at ${l}`)),await Gl(l,e.open);let c=!0,u=!1;go(()=>{if(!c)process.exit(0);u=!0,De(`
750
+ Cancelling: stopping agents and removing the worktree (Ctrl+C again to exit now)...`);let f=o.cancel(a.id)??Promise.resolve();Promise.race([f,Bun.sleep(Hx)]).then(()=>process.exit(130))});let d=await a.done;if(c=!1,u)return new Promise(()=>{});if(d.status==="complete")De(`Results: ${l}`);else if(d.status==="failed")De(`Results (failed run): ${l}`);return De(un.default.dim("Server still running. Press Ctrl+C to stop.")),new Promise(()=>{})}function JM(e){if(e.github||e.head){let t=!1;try{t=$n(e.target).kind==="pr"}catch{t=!1}if(!t)return`${e.github?"--github":"--head"} needs a pull request target (#<n>, pr:<n>, or a PR URL)`}if(e.head&&!/^[0-9a-f]{40}$/i.test(e.head))return"--head must be a full 40-character commit SHA";if(!e.headless){for(let[t,n]of[["--out",e.out],["--json",e.json],["--fail-on",e.failOn]])if(n)return`${t} needs --headless`}return null}async function Vx(e,t){let n={...t,...e?{target:e}:{}},r=JM(n);if(r)De(un.default.red(`Error: ${r}`)),process.exit(2);if(n.headless)process.exit(await Vv(n));let{port:s}=await Kl(n);for(let o of await Kf(s)){if(o.health.activeRunId)continue;let a=await VM(o.base,n);if(a>=0)process.exit(a)}process.exit(await zM(n))}var zx="worktree (default), staged, a commit (<sha>, HEAD~2, commit:<rev>), a range (<a>..<b>, <a>...<b>), a branch (<name>, branch:<name>), #<pr>, pr:<n>, or a PR URL";function Jx(){return new It("review").description("Review changes with the multi-agent reviewer (requires opencode, tilth, git; gh for PRs)").argument("[target]",zx).option("-C, --repo <path>","Repository to review (default: current directory)").option("--base <ref>","For staged/worktree: diff against merge-base(<ref>, HEAD) instead of HEAD").option("-i, --intent <text>","Describe the intent of the changes").option("--intent-file <path>","Read the intent from a file").option("--model <stage=id>","Model for a stage: review, coordinator, walkthrough, intent (repeatable)",Kx,[]).option("--effort <level>","Reasoning effort: the model variant to use, e.g. low, medium, high").option("--config <file>","Per-repo review settings JSON (models, effort, surfaces, extraExcludes, post, instructions)").option("--max-cost <usd>","Stop starting new review slices once spending reaches this many US dollars. Slices already running finish, so the total can exceed the limit by up to 6 slices at $3 each plus the coordinator and walkthrough (default: maxCostUsd from ~/.config/diffloupe/config.json, else no limit)",GM).option("--max-rounds <n>","Skip the review, before any model call, when this change has already been reviewed <n> times (with --headless, exit 4). With --github the rounds are counted from the PR's summary comment",WM).option("--full","Review every changed file even when this target was reviewed before (default: a re-review looks only at files changed since the last run)",!1).option("--host <host>",`Address for the server to listen on (default: ${pr})`).option("--port <port>",`Port for the server (default: ${Kr}, or the next free one)`,Hl).option("--open","Open the run in a browser",!1).option("--headless","Run in the terminal without a server and print a summary to stdout",!1).option("--markdown","With --headless: print the full review markdown instead of the summary",!1).option("--github","For a PR target: render for posting to GitHub (prior comments come from the PR, payloads.json is written, and failing to read the PR is an error)").option("--head <sha>","For a PR target: review this 40-character commit instead of the PR's current head").option("--out <dir>","With --headless: copy the run's files and result.json into <dir>").option("--json","With --headless: print only the result object as JSON on stdout").option("--fail-on <severity>","With --headless: exit 3 when a posted finding is at or above this severity (blocker, should-fix, nice-to-have, question)",Gf).exitOverride((e)=>process.exit(e.exitCode===0?0:2)).action(Vx)}function Xx(){return new It("diff").description("Open a diff grouped by how the code connects, with no review agents (requires git; gh for PRs). --walkthrough adds a guide from one model call.").argument("[target]",zx).option("-C, --repo <path>","Repository to diff (default: current directory)").option("--base <ref>","For staged/worktree: diff against merge-base(<ref>, HEAD) instead of HEAD").option("--walkthrough","Add the walkthrough guide (one model call; needs opencode and a credential)",!1).option("-i, --intent <text>","With --walkthrough: describe the intent of the changes").option("--intent-file <path>","With --walkthrough: read the intent from a file").option("--model <walkthrough=id>","With --walkthrough: the walkthrough model",Kx,[]).option("--effort <level>","With --walkthrough: reasoning effort (model variant)").option("--config <file>","Per-repo review settings JSON (models, effort, extraExcludes)").option("--host <host>",`Address for the server to listen on (default: ${pr})`).option("--port <port>",`Port for the server (default: ${Kr}, or the next free one)`,Hl).option("--open","Open the run in a browser",!1).option("--headless","Print the grouped file list to stdout without a server",!1).action((e,t)=>Vx(e,{...t,kind:"diff"}))}function Yx(){return new It("open").description("Print (or open) the URL of a saved run, starting a server if none is running").argument("[runId]","Run to open (default: the run list)").option("--last","Open the most recent run",!1).option("--host <host>",`Address for a new server to listen on (default: ${pr})`).option("--port <port>",`Port to look for a server on (default: ${Kr})`,Hl).option("--open","Open the URL in a browser",!1).action(async(e,t)=>{let n=e;if(!n&&t.last){if(n=(await Jt())[0]?.id,!n)De("No saved runs."),process.exit(1)}let{host:r,port:s}=await Kl(t),o=(await Kf(s))[0];if(o){let a=n?Wl(o.base,n):o.base;console.log(a),await Gl(a,t.open),process.exit(0)}await Zx({...t,host:r,port:s},n)})}async function Zx(e,t){let n=KM.resolve(e.repo??process.cwd()),r;try{r=await Hf({host:e.host,port:e.port,defaultRepo:await Wx(n),log:De})}catch(o){De(un.default.red(`Error starting server: ${o instanceof Error?o.message:String(o)}`)),process.exit(1)}let s=t?Wl(r.url,t):r.url;return De(un.default.green(`DiffLoupe ready at ${s}`)),De(un.default.dim("Press Ctrl+C to stop.")),r.ctx.runs.watch((o,a)=>{let l=ho(a);if(l)De(`${un.default.dim(o)} ${l}`)}),go(()=>{let o=r.ctx.runs.activeRunId;if(!o)process.exit(0);De(`
751
+ Cancelling the active run (Ctrl+C again to exit now)...`);let a=r.ctx.runs.cancel(o)??Promise.resolve();Promise.race([a,Bun.sleep(Hx)]).then(()=>process.exit(130))}),await Gl(s,e.open),r}function Qx(){return new It("serve").description("Start the DiffLoupe server and keep it running").option("-C, --repo <path>","Repository runs use when a request names none (default: current directory)").option("--host <host>",`Address to listen on (default: ${pr})`).option("--port <port>",`Port (default: ${Kr}, or the next free one)`,Hl).option("--open","Open the server in a browser",!1).action(async(e)=>{await Zx({...e,...await Kl(e)})})}var XM=3;function Vl(e){console.error(Wf.default.red(`Error: ${e}`)),process.exit(2)}function eS(){return new It("gate").description("Fail when a pull request still has open review findings at or above a severity (reads GitHub, runs no model)").argument("<target>","#<pr>, pr:<n>, owner/repo#<n>, or a PR URL").requiredOption("--fail-on <severity>","blocker, should-fix, nice-to-have, or question",Gf).option("--json","Print the result as JSON").option("--status [sha]","Also write the result as the diffloupe/gate commit status on this commit (default: the PR head). Needs statuses: write").option("--override-label <name>","Pass whatever is open when the pull request has this label").option("--count-author-resolved","Treat threads the pull request's author resolved as closed").option("--review-missing","This push's review did not reach the PR (the review or post job failed): fail if the bot has never reviewed it").action(async(e,t)=>{let n;try{n=$n(e)}catch(a){Vl(a instanceof Error?a.message:String(a))}if(n.kind!=="pr")Vl("gate needs a pull request target (#<n>, pr:<n>, or a PR URL)");let r=t.status===!0?void 0:t.status;if(r!==void 0&&!/^[0-9a-f]{40}$/i.test(r))Vl("--status needs a full 40-character commit SHA, or no value for the PR head");let s=n.repo??await di(process.cwd());if(s.startsWith("local/"))Vl("no GitHub repository: pass owner/repo#<n> or set GH_REPO");let o=(a)=>oe("gh",a);try{let a=await Lv(s,n.pr,{failOn:t.failOn,...t.overrideLabel?{overrideLabel:t.overrideLabel}:{},...t.countAuthorResolved?{countAuthorResolved:!0}:{},...t.reviewMissing?{reviewMissing:!0}:{},...t.status?{status:r?{sha:r}:{}}:{}},{readThreads:(l,c)=>nm(l,c,{gh:o}),readComments:(l,c)=>gs(`repos/${l}/issues/${c}/comments`,o),gh:o});if(t.json)console.log(JSON.stringify(a,null,2));else console.log(Fv(a).join(`
752
+ `));process.exit(a.fails?XM:0)}catch(a){console.error(Wf.default.red(`Error: ${a instanceof Error?a.message:String(a)}`)),process.exit(1)}})}import{rm as oT}from"fs/promises";import aT from"path";var Gr=Do(Qi(),1);var YM="unrecorded",zf=()=>({change:{measured:0,acted:0,control:0},preexisting:{measured:0,acted:0,control:0},stillListed:0});function iS(e,t){if(!t||!e.priorActedOn)return[];let n=new Set(e.findings.map((r)=>jn(r.id)));return e.priorActedOn.flatMap((r)=>{let s=t.findings.find((o)=>o.id===r.id);if(!s)return[];return[{acted:r.acted,control:r.control,finding:s,stillListed:r.acted&&n.has(jn(r.id))}]})}function sS(e,t){let n=t.finding.preexisting?e.preexisting:e.change;if(n.measured++,t.acted)n.acted++;if(t.control)n.control++;if(t.stillListed)e.stillListed++}function ZM(e){let t=zf();for(let n of e){for(let r of["change","preexisting"])t[r].measured+=n[r].measured,t[r].acted+=n[r].acted,t[r].control+=n[r].control;t.stillListed+=n.stillListed}return t}function QM(e){let t={};for(let n of e)t[n]=(t[n]??0)+1;return t}function eT(e){let t={};for(let n of e)for(let[r,s]of Object.entries(n))t[r]=(t[r]??0)+s;return t}function tS(e){return Object.entries(e).filter(([,t])=>t>0).sort((t,n)=>n[1]-t[1]).map(([t,n])=>`${n} ${t}`).join(", ")}var tT=()=>({blocker:0,"should-fix":0,"nice-to-have":0,question:0}),nT=(e)=>Object.values(e).reduce((t,n)=>t+n,0),oS=({run:e})=>e.status==="complete"&&e.meta.kind!=="diff"&&!e.meta.roundLimit;function aS(e){let t=e.filter(oS),n=new Map(t.map((o)=>[o.run.id,o])),r=(o)=>{let a=new Set,l=o;while(l.run.priorRunId&&n.has(l.run.priorRunId)&&!a.has(l.run.id))a.add(l.run.id),l=n.get(l.run.priorRunId)??l;return l.run.id},s=new Map;for(let o of t){let a=r(o);s.set(a,[...s.get(a)??[],o])}return[...s.values()].map((o)=>rT(o.sort((a,l)=>a.run.createdAt.localeCompare(l.run.createdAt)),n)).sort((o,a)=>a.lastAt.localeCompare(o.lastAt))}function rT(e,t){let n=e[0]?.run,r=e.at(-1);if(!n||!r)throw Error("empty chain");let s=tT(),o=0,a=0,l=0,c=new Map,u=ul(),d=zf(),f=e.map(({run:h,state:g},w)=>{let b=Ys(h);Ys(h,u);let x=b.calls?dl(b):null,S=h.findings.filter((k)=>!k.carriedFrom);for(let k of S)if(k.preexisting)o++;else s[k.severity]++;let P=h.priorRunId?t.get(h.priorRunId)?.run:void 0,M=P?h.resolved:[];for(let k of M)if(a++,P?.findings.find((E)=>E.id===k.id)?.preexisting)l++;for(let k of iS(h,P))sS(d,k);for(let[k,E]of Object.entries(g.findingStatus))if(E==="dismissed")c.set(k,g.findingNotes?.[k]?.reason??"unrecorded");return{id:h.id,round:h.round??w+1,createdAt:h.createdAt,new:S.length,newPreexisting:S.filter((k)=>k.preexisting).length,carried:h.findings.length-S.length,resolved:M.length,costUsd:h.meta.costUsd,...h.meta.reviewScope?{scope:h.meta.reviewScope}:{},...h.meta.promptVersion?{promptVersion:h.meta.promptVersion}:{},...x!==null?{cacheShare:x}:{}}}),p=new Set(Object.entries(r.state.findingStatus).flatMap(([h,g])=>g==="dismissed"?[h]:[]));return{key:hl(n.repo,n.target),repo:n.repo.slug??n.repo.root,target:dr(n.target),rounds:f,raised:s,raisedPreexisting:o,fixed:a,fixedPreexisting:l,dismissed:c.size,dismissedBy:QM(c.values()),open:r.run.findings.filter((h)=>!p.has(h.id)).length,costUsd:f.reduce((h,g)=>h+g.costUsd,0),usage:u,acted:d,disputes:iT(r.run),lastAt:r.run.createdAt}}function iT(e){let t={withdrawn:0,upheld:0,unjudged:0};for(let n of e.disputes??[])t[n.outcome]++;return t}function nS(e){if(!e.withdrawn&&!e.upheld&&!e.unjudged)return null;return`${e.withdrawn} withdrawn, ${e.upheld} upheld for a human, ${e.unjudged} awaiting a ruling`}function Jf(e){let t=e.reduce((s,o)=>s+nT(o.raised),0),n=e.reduce((s,o)=>s+o.fixed-o.fixedPreexisting,0),r=e.reduce((s,o)=>s+o.rounds.length,0);return{chains:e.length,meanRounds:e.length?r/e.length:0,pastThreeRounds:e.length?e.filter((s)=>s.rounds.length>3).length/e.length:0,raised:t,fixed:e.reduce((s,o)=>s+o.fixed,0),dismissed:e.reduce((s,o)=>s+o.dismissed,0),dismissedBy:eT(e.map((s)=>s.dismissedBy)),resolutionRate:t?n/t:null,costUsd:e.reduce((s,o)=>s+o.costUsd,0),usage:e.reduce((s,o)=>(s.input+=o.usage.input,s.output+=o.usage.output,s.reasoning+=o.usage.reasoning,s.cacheRead+=o.usage.cacheRead,s.cacheWrite+=o.usage.cacheWrite,s.calls+=o.usage.calls,s.firstStepShares.push(...o.usage.firstStepShares),s),ul()),acted:ZM(e.map((s)=>s.acted)),disputes:e.reduce((s,o)=>({withdrawn:s.withdrawn+o.disputes.withdrawn,upheld:s.upheld+o.disputes.upheld,unjudged:s.unjudged+o.disputes.unjudged}),{withdrawn:0,upheld:0,unjudged:0})}}function lS(e){let t=e.filter(oS),n=new Map(t.map((o)=>[o.run.id,o.run])),r=new Map,s=(o)=>{let a=o.meta.promptVersion??YM,l=o.meta.instructionsHash??"none",c=`${a}/${l}`,u=r.get(c);if(!u)u={promptVersion:a,instructionsHash:l,runs:0,raised:0,raisedPreexisting:0,fixed:0,fixedPreexisting:0,costUsd:0,acted:zf()},r.set(c,u);return u};for(let{run:o}of t){let a=s(o);a.runs++,a.costUsd+=o.meta.costUsd;for(let u of o.findings){if(u.carriedFrom)continue;if(u.preexisting)a.raisedPreexisting++;else a.raised++}let l=o.priorRunId?n.get(o.priorRunId):void 0;if(!l)continue;let c=(u)=>n.get(u?.carriedFrom??l.id)??l;for(let u of o.resolved){let d=l.findings.find((p)=>p.id===u.id),f=s(c(d));if(d?.preexisting)f.fixedPreexisting++;else f.fixed++}for(let u of iS(o,l))sS(s(c(u.finding)).acted,u)}return[...r.values()].sort((o,a)=>a.runs-o.runs)}var Hi=(e)=>e===null?"n/a":`${Math.round(e*100)}%`,xo=(e)=>`$${e.toFixed(2)}`;function sT(e){let t=Object.entries(e).filter(([,n])=>n>0).map(([n,r])=>`${r} ${n}`);return t.length?t.join(", "):"none"}function rS(e){let t=e.measured?e.acted/e.measured:0,n=e.measured?e.control/e.measured:0,r=Math.round((t-n)*100);return`${e.acted} of ${e.measured} edited (${Hi(t)}), control ${Hi(n)}, ${r>=0?"+":""}${r} points`}function Vf(e){if(!e.change.measured&&!e.preexisting.measured)return null;let t=[e.change.measured?rS(e.change):"none on the change"];if(e.preexisting.measured)t.push(`pre-existing ${rS(e.preexisting)}`);if(e.stillListed)t.push(`${e.stillListed} edited but still listed`);return t.join("; ")}function cS(e,t){if(e.length===0)return"No complete review runs match.";let n=[];for(let l of e){let c=l.rounds.length;n.push(`${l.target} ${l.repo} (${c} round${c===1?"":"s"}, ${xo(l.costUsd)})`);for(let g of l.rounds){let w=g.newPreexisting?` (${g.newPreexisting} pre-existing)`:"",b=g.scope==="incremental"?", changes only":"",x=g.cacheShare===void 0?"":`, ${Hi(g.cacheShare)} cached`;n.push(` round ${g.round} ${g.id} ${g.new} new${w}, ${g.carried} carried, ${g.resolved} fixed${b}, ${xo(g.costUsd)}${x}`)}let u=Zs(l.usage);if(u)n.push(` tokens: ${u}`);let d=l.fixed?`, ${xo(l.costUsd/l.fixed)} per fixed finding`:"";n.push(` raised: ${sT(l.raised)}${l.raisedPreexisting?`; ${l.raisedPreexisting} pre-existing`:""}`);let f=tS(l.dismissedBy);n.push(` fixed ${l.fixed}, dismissed ${l.dismissed}${f?` (${f})`:""}, still open at last run ${l.open}${d}`);let p=Vf(l.acted);if(p)n.push(` acted on: ${p}`);let h=nS(l.disputes);if(h)n.push(` disputes: ${h}`);n.push("")}let r=Jf(e);if(n.push(`${r.chains} chain${r.chains===1?"":"s"}, ${r.meanRounds.toFixed(1)} rounds on average, ${Hi(r.pastThreeRounds)} past three rounds`,`${r.raised} raised on the change, ${r.fixed} fixed, resolution rate ${Hi(r.resolutionRate)}, ${xo(r.costUsd)} total`),r.dismissed)n.push(`${r.dismissed} dismissed: ${tS(r.dismissedBy)}`);let s=Zs(r.usage);if(s)n.push(`tokens over ${r.usage.calls} agent calls: ${s}`);let o=Vf(r.acted);if(o)n.push(`prior findings acted on: ${o}`);let a=nS(r.disputes);if(a)n.push(`disputes: ${a}`);if(t){n.push("","By prompt version / instructions:");for(let l of t){let c=l.raised?Hi(l.fixed/l.raised):"n/a";n.push(` ${l.promptVersion} / ${l.instructionsHash} ${l.runs} run${l.runs===1?"":"s"}, ${l.raised} raised (${l.raisedPreexisting} pre-existing), ${l.fixed} fixed, resolution rate ${c}, ${xo(l.costUsd)}`);let u=Vf(l.acted);if(u)n.push(` acted on: ${u}`)}}return n.join(`
753
+ `)}async function lT(e,t=gt){try{return await t(e)}catch(n){console.error(Gr.default.red(`No run.json for ${e}: ${n instanceof Error?n.message:String(n)}`)),process.exit(1)}}function pS(){let e=new It("runs").description("List saved runs").enablePositionalOptions().option("--json","Print run headers as JSON",!1).option("--kind <kind>","Only review or diff runs",uS).action(async(r)=>{let s=dS(await Jt(),r.kind);console.log(r.json?JSON.stringify(s,null,2):Qy(s))});e.command("show").description("Show a saved run: groups, files, findings and anchors").argument("<id>","Run id").option("--json","Print run.json",!1).option("--markdown","Print the findings as markdown, as the web UI's Copy all does",!1).option("--over-cap","With --markdown, include findings over the posting cap",!1).option("--dismissed","With --markdown, include dismissed findings",!1).action(async(r,s)=>{let o=await lT(r,s.json||s.markdown?gt:af),a=await jr(r);if(s.markdown){process.stdout.write(Qs(o,{includeOverCap:s.overCap,state:a,includeDismissed:s.dismissed}));return}console.log(s.json?JSON.stringify({...o,state:a},null,2):nb(o,a))});let t=(r,s)=>e.command(r).description(s).argument("<run>","Run id").argument("<findings...>","Finding ids, as runs show and the markdown export print them"),n=async(r,s,o,a={})=>{try{await bb(r,s,o,a)}catch(c){console.error(Gr.default.red(c instanceof Error?c.message:String(c))),process.exit(1)}console.log(`${o==="open"?"reopened":o} ${s.length} finding${s.length===1?"":"s"} in ${r}`)};return t("dismiss","Dismiss findings, with the reason, so later rounds and stats know why").requiredOption("--reason <reason>",`Why: ${ll.join(", ")}`,cT).option("--note <text>","A short explanation").action(async(r,s,o)=>n(r,s,"dismissed",o)),t("accept","Mark findings accepted: real problems to fix").action(async(r,s)=>n(r,s,"accepted")),t("reopen","Clear the accepted or dismissed mark on findings").action(async(r,s)=>n(r,s,"open")),e.command("stats").description("How findings fared across re-reviews of the same change: raised, fixed, dismissed, still open").option("--repo <path-or-slug>","Only runs in this repository (a path, or owner/name)").option("--since <age>","Only chains reviewed within this window, e.g. 30d, 12h, 2w").option("--by-version","Also split the counts by prompt version and repo instructions",!1).option("--json","Print the stats as JSON",!1).action(async(r)=>{let s=r.since===void 0?void 0:fS(r.since);if(s===null)console.error(Gr.default.red("--since takes a number with d, h, or w")),process.exit(1);let o=r.repo===void 0?void 0:aT.resolve(r.repo),a=(await Jt()).filter((p)=>!p.invalid&&p.status==="complete"&&p.kind!=="diff"&&(r.repo===void 0||p.repo.root===o||p.repo.slug===r.repo)),l=await Promise.all(a.map(async(p)=>({run:await af(p.id),state:await jr(p.id)}))),c=s===void 0?void 0:new Date(Date.now()-s).toISOString(),u=aS(l).filter((p)=>c===void 0||p.lastAt>=c),d=new Set(u.flatMap((p)=>p.rounds.map((h)=>h.id))),f=r.byVersion?lS(l.filter((p)=>d.has(p.run.id))):void 0;if(r.json){console.log(JSON.stringify({chains:u,totals:Jf(u),...f?{versions:f}:{}},null,2));return}console.log(cS(u,f))}),e.command("rm").description("Delete a saved run, its artifacts and the git refs that pin its commits").argument("<id>","Run id").action(async(r)=>{let s=await so(r);if(s.length===0)console.error(Gr.default.yellow(`Nothing found for ${r}`)),process.exit(1);for(let o of s)console.log(`removed ${o}`)}),e.command("prune").description("Delete old runs and orphaned scratch files. Lists what would go unless --yes is given").option("--older-than <age>","Only runs older than this, e.g. 30d, 12h, 2w","30d").option("--keep <n>","Always keep this many of the newest runs","20").option("--kind <kind>","Only review or diff runs (--keep then counts runs of that kind)",uS).option("--yes","Delete instead of listing",!1).action(async(r)=>{let s=fS(r.olderThan),o=Number(r.keep);if(s===null||!Number.isInteger(o)||o<0)console.error(Gr.default.red("--older-than takes a number with d, h, or w; --keep takes a whole number")),process.exit(1);let a=Sb(dS(await Jt(),r.kind),{olderThanMs:s,keep:o}),l=await Rb();if(a.length===0&&l.length===0){console.log("Nothing to prune");return}if(!r.yes){for(let c of a)console.log(`would delete run ${c.id} (${c.createdAt})`);if(l.length>0)console.log(`would delete ${l.length} orphaned scratch entries`);console.log(Gr.default.dim("Run again with --yes to delete."));return}for(let c of a)await so(c.id),console.log(`deleted run ${c.id}`);for(let c of l)await oT(c,{recursive:!0,force:!0});if(l.length>0)console.log(`deleted ${l.length} orphaned scratch entries`)}),e}function cT(e){let t=ll.find((n)=>n===e);if(!t)throw new zn(`must be one of ${ll.join(", ")}`);return t}function uS(e){if(e!=="review"&&e!=="diff")throw new zn("must be review or diff");return e}function dS(e,t){return t?e.filter((n)=>(n.kind??"review")===t):e}var uT={h:3600000,d:86400000,w:604800000};function fS(e){let t=/^(\d+)([hdw])$/.exec(e.trim());return t?Number(t[1])*uT[t[2]]:null}function dT(){return new It().name("diffloupe").description("Grouped diffs and multi-agent code review for local changes and pull requests").version(Jn).enablePositionalOptions().addCommand(Jx()).addCommand(Xx()).addCommand(Yx()).addCommand(Qx()).addCommand(pS()).addCommand(Tv()).addCommand(eS())}function hS(){dT().parseAsync()}hS();