@acemarke/diffloupe 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,38 +1,38 @@
1
1
  #!/usr/bin/env -S bun --no-env-file
2
2
  // @bun
3
- var nv=Object.create;var{getPrototypeOf:rv,defineProperty:uc,getOwnPropertyNames:iv}=Object;var Bd=Object.prototype.hasOwnProperty;function sv(e){return this[e]}var ov,av,dc=(e,t,n)=>{var r=e!=null&&typeof e==="object";if(r){var s=t?ov??=new WeakMap:av??=new WeakMap,o=s.get(e);if(o)return o}n=e!=null?nv(rv(e)):{};let a=t||!e||!e.__esModule||!Bd.call(e,"default")?uc(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let c of iv(e))if(!Bd.call(a,c))uc(a,c,{get:sv.bind(e,c),enumerable:!0})}if(r)s.set(e,a);return a};var Gn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var We=(e,t,n)=>()=>{if(e)try{t=e(e=0)}catch(r){n=[r]}if(n)throw n[0];return t};var cv=(e,t,n)=>{for(var r in t)uc(e,r,{get:t[r],set:n[r],enumerable:!0,configurable:!0})},wi=import.meta.require;var yi=Gn(function(lv){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 qd extends fc{constructor(e){super(1,"commander.invalidArgument",e);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}lv.CommanderError=fc;lv.InvalidArgumentError=qd});var zs=Gn(function(hv){var{InvalidArgumentError:fv}=yi();class Hd{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 fv(`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 pv(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}hv.Argument=Hd;hv.humanReadableArgName=pv});var pc=Gn(function(wv){var{humanReadableArgName:_v}=zs();class Kd{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)=>_v(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 c=t.visibleArguments(e).map((d)=>s(t.styleArgumentTerm(t.argumentTerm(d)),t.styleArgumentDescription(t.argumentDescription(d))));if(o=o.concat(this.formatItemList("Arguments:",c,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 Wd(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)),c=2,u=(this.helpWidth??80)-t-c-2,d;if(u<this.minWidthToWrap||r.preformatted(n))d=n;else d=r.boxWrap(n,u).replace(/\n/g,`
3
+ var cx=Object.create;var{getPrototypeOf:lx,defineProperty:Mc,getOwnPropertyNames:ux}=Object;var Rf=Object.prototype.hasOwnProperty;function dx(e){return this[e]}var fx,px,Tc=(e,t,n)=>{var r=e!=null&&typeof e==="object";if(r){var s=t?fx??=new WeakMap:px??=new WeakMap,o=s.get(e);if(o)return o}n=e!=null?cx(lx(e)):{};let a=t||!e||!e.__esModule||!Rf.call(e,"default")?Mc(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let c of ux(e))if(!Rf.call(a,c))Mc(a,c,{get:dx.bind(e,c),enumerable:!0})}if(r)s.set(e,a);return a};var ir=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var We=(e,t,n)=>()=>{if(e)try{t=e(e=0)}catch(r){n=[r]}if(n)throw n[0];return t};var hx=(e,t,n)=>{for(var r in t)Mc(e,r,{get:t[r],set:n[r],enumerable:!0,configurable:!0})},Mi=import.meta.require;var Ti=ir(function(mx){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 $f extends Fc{constructor(e){super(1,"commander.invalidArgument",e);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}mx.CommanderError=Fc;mx.InvalidArgumentError=$f});var uo=ir(function(bx){var{InvalidArgumentError:wx}=Ti();class kf{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 wx(`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 yx(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}bx.Argument=kf;bx.humanReadableArgName=yx});var Nc=ir(function(Rx){var{humanReadableArgName:Sx}=uo();class Ef{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)=>Sx(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 c=t.visibleArguments(e).map((d)=>s(t.styleArgumentTerm(t.argumentTerm(d)),t.styleArgumentDescription(t.argumentDescription(d))));if(o=o.concat(this.formatItemList("Arguments:",c,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 Af(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)),c=2,u=(this.helpWidth??80)-t-c-2,d;if(u<this.minWidthToWrap||r.preformatted(n))d=n;else d=r.boxWrap(n,u).replace(/\n/g,`
5
5
  `+" ".repeat(t+c));return o+a+" ".repeat(c)+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 c=[a.shift()],l=this.displayWidth(c[0]);a.forEach((u)=>{let d=this.displayWidth(u);if(l+d<=t){c.push(u),l+=d;return}s.push(c.join(""));let f=u.trimStart();c=[f],l=this.displayWidth(f)}),s.push(c.join(""))}),s.join(`
7
- `)}}function Wd(e){let t=/\x1b\[\d*(;\d*)*m/g;return e.replace(t,"")}wv.Help=Kd;wv.stripColor=Wd});var hc=Gn(function($v){var{InvalidArgumentError:vv}=yi();class Gd{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=xv(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 vv(`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 Vd(this.name().replace(/^no-/,""));return Vd(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 zd{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 Vd(e){return e.split("-").reduce((t,n)=>t+n[0].toUpperCase()+n.slice(1))}function xv(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],c=`option creation failed due to '${a}' in option flags '${e}'`;if(/^-[^-][^-]/.test(a))throw Error(`${c}
7
+ `)}}function Af(e){let t=/\x1b\[\d*(;\d*)*m/g;return e.replace(t,"")}Rx.Help=Ef;Rx.stripColor=Af});var Dc=ir(function(Cx){var{InvalidArgumentError:Ex}=Ti();class If{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=Ax(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 Ex(`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 Cf(this.name().replace(/^no-/,""));return Cf(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 Of{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 Cf(e){return e.split("-").reduce((t,n)=>t+n[0].toUpperCase()+n.slice(1))}function Ax(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],c=`option creation failed due to '${a}' in option flags '${e}'`;if(/^-[^-][^-]/.test(a))throw Error(`${c}
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(`${c}
11
11
  - too many short flags`);if(s.test(a))throw Error(`${c}
12
12
  - too many long flags`);throw Error(`${c}
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}}$v.Option=Gd;$v.DualOptions=zd});var Jd=Gn(function(Av){function kv(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 Ev(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 c=kv(e,a),l=Math.max(e.length,a.length);if((l-c)/l>o){if(c<s)s=c,r=[a];else if(c===s)r.push(a)}}),r.sort((a,c)=>a.localeCompare(c)),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}}Cx.Option=If;Cx.DualOptions=Of});var Pf=ir(function(Tx){function Px(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 Mx(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 c=Px(e,a),l=Math.max(e.length,a.length);if((l-c)/l>o){if(c<s)s=c,r=[a];else if(c===s)r.push(a)}}),r.sort((a,c)=>a.localeCompare(c)),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""}Av.suggestSimilar=Ev});var Qd=Gn(function(Dv){var Iv=wi("events").EventEmitter,gr=wi("child_process"),Xe=wi("path"),An=wi("fs"),Y=wi("process"),{Argument:Ov,humanReadableArgName:Pv}=zs(),{CommanderError:mc}=yi(),{Help:Mv,stripColor:Tv}=pc(),{Option:Xd,DualOptions:Nv}=hc(),{suggestSimilar:Yd}=Jd();class _c extends Iv{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)=>Y.stdout.write(t),writeErr:(t)=>Y.stderr.write(t),outputError:(t,n)=>n(t),getOutHelpWidth:()=>Y.stdout.isTTY?Y.stdout.columns:void 0,getErrHelpWidth:()=>Y.stderr.isTTY?Y.stderr.columns:void 0,getOutHasColors:()=>gc()??(Y.stdout.isTTY&&Y.stdout.hasColors?.()),getErrHasColors:()=>gc()??(Y.stderr.isTTY&&Y.stderr.hasColors?.()),stripColor:(t)=>Tv(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(/([^ ]+) *(.*)/),c=this.createCommand(o);if(r)c.description(r),c._executableHandler=!0;if(s.isDefault)this._defaultCommandName=c._name;if(c._hidden=!!(s.noHelp||s.hidden),c._executableFile=s.executableFile||null,a)c.arguments(a);if(this._registerCommand(c),c.parent=this,c.copyInheritedSettings(this),r)return this;return c}createCommand(e){return new _c(e)}createHelp(){return Object.assign(new Mv,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 Ov(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));Y.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 Xd(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 c=this.getOptionValue(n);if(s!==null&&e.parseArg)s=this._callParseArg(e,s,c,o);else if(s!==null&&e.variadic)s=e._collectValue(s,c);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 Xd)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=(c,l)=>{let u=a.exec(c);return u?u[0]:l},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(Y.versions?.electron)t.from="electron";let r=Y.execArgv??[];if(r.includes("-e")||r.includes("--eval")||r.includes("-p")||r.includes("--print"))t.from="eval"}if(e===void 0)e=Y.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(Y.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(An.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""}Tx.suggestSimilar=Mx});var Nf=ir(function(qx){var Nx=Mi("events").EventEmitter,Mr=Mi("child_process"),Qe=Mi("path"),Nn=Mi("fs"),J=Mi("process"),{Argument:Dx,humanReadableArgName:Lx}=uo(),{CommanderError:Lc}=Ti(),{Help:jx,stripColor:Ux}=Nc(),{Option:Mf,DualOptions:Bx}=Dc(),{suggestSimilar:Tf}=Pf();class Uc extends Nx{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:()=>jc()??(J.stdout.isTTY&&J.stdout.hasColors?.()),getErrHasColors:()=>jc()??(J.stderr.isTTY&&J.stderr.hasColors?.()),stripColor:(t)=>Ux(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(/([^ ]+) *(.*)/),c=this.createCommand(o);if(r)c.description(r),c._executableHandler=!0;if(s.isDefault)this._defaultCommandName=c._name;if(c._hidden=!!(s.noHelp||s.hidden),c._executableFile=s.executableFile||null,a)c.arguments(a);if(this._registerCommand(c),c.parent=this,c.copyInheritedSettings(this),r)return this;return c}createCommand(e){return new Uc(e)}createHelp(){return Object.assign(new jx,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 Dx(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 Lc(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 Mf(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 c=this.getOptionValue(n);if(s!==null&&e.parseArg)s=this._callParseArg(e,s,c,o);else if(s!==null&&e.variadic)s=e._collectValue(s,c);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 Mf)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=(c,l)=>{let u=a.exec(c);return u?u[0]:l},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(Nn.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=Xe.resolve(u,d);if(An.existsSync(f))return f;if(r.includes(Xe.extname(d)))return;let p=r.find((h)=>An.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=An.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=Xe.resolve(Xe.dirname(u),a)}if(a){let u=s(a,o);if(!u&&!e._executableFile&&this._scriptPath){let d=Xe.basename(this._scriptPath,Xe.extname(this._scriptPath));if(d!==this._name)u=s(a,`${d}-${e._name}`)}o=u||o}n=r.includes(Xe.extname(o));let c;if(Y.platform!=="win32")if(n)t.unshift(o),t=Zd(Y.execArgv).concat(t),c=gr.spawn(Y.argv[0],t,{stdio:"inherit"});else c=gr.spawn(o,t,{stdio:"inherit"});else this._checkForMissingExecutable(o,a,e._name),t.unshift(o),t=Zd(Y.execArgv).concat(t),c=gr.spawn(Y.execPath,t,{stdio:"inherit"});if(!c.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((d)=>{Y.on(d,()=>{if(c.killed===!1&&c.exitCode===null)c.kill(d)})});let l=this._exitCallback;c.on("close",(u)=>{if(u=u??1,!l)Y.exit(u);else l(new mc(u,"commander.executeSubCommandAsync","(close)"))}),c.on("error",(u)=>{if(u.code==="ENOENT")this._checkForMissingExecutable(o,a,e._name);else if(u.code==="EACCES")throw Error(`'${o}' not executable`);if(!l)Y.exit(1);else{let d=new mc(1,"commander.executeSubCommandAsync","(error)");d.nestedError=u,l(d)}}),this.runningCommand=c}_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,c=null,l=0;while(l<e.length||c){let u=c??e[l++];if(c=null,u==="--"){if(r===n)r.push(u);r.push(...e.slice(l));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[l++];if(f===void 0)this.optionMissingArgument(d);this.emit(`option:${d.name()}`,f)}else if(d.optional){let f=null;if(l<e.length&&(!s(e[l])||o(e[l])))f=e[l++];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()}`),c=`-${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(l));break}else if(this._getHelpCommand()&&u===this._getHelpCommand().name()){t.push(u,...e.slice(l));break}else if(this._defaultCommandName){n.push(u,...e.slice(l));break}}if(this._passThroughOptions){r.push(u,...e.slice(l));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=Qe.resolve(u,d);if(Nn.existsSync(f))return f;if(r.includes(Qe.extname(d)))return;let p=r.find((h)=>Nn.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=Nn.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=Qe.resolve(Qe.dirname(u),a)}if(a){let u=s(a,o);if(!u&&!e._executableFile&&this._scriptPath){let d=Qe.basename(this._scriptPath,Qe.extname(this._scriptPath));if(d!==this._name)u=s(a,`${d}-${e._name}`)}o=u||o}n=r.includes(Qe.extname(o));let c;if(J.platform!=="win32")if(n)t.unshift(o),t=Ff(J.execArgv).concat(t),c=Mr.spawn(J.argv[0],t,{stdio:"inherit"});else c=Mr.spawn(o,t,{stdio:"inherit"});else this._checkForMissingExecutable(o,a,e._name),t.unshift(o),t=Ff(J.execArgv).concat(t),c=Mr.spawn(J.execPath,t,{stdio:"inherit"});if(!c.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((d)=>{J.on(d,()=>{if(c.killed===!1&&c.exitCode===null)c.kill(d)})});let l=this._exitCallback;c.on("close",(u)=>{if(u=u??1,!l)J.exit(u);else l(new Lc(u,"commander.executeSubCommandAsync","(close)"))}),c.on("error",(u)=>{if(u.code==="ENOENT")this._checkForMissingExecutable(o,a,e._name);else if(u.code==="EACCES")throw Error(`'${o}' not executable`);if(!l)J.exit(1);else{let d=new Lc(1,"commander.executeSubCommandAsync","(error)");d.nestedError=u,l(d)}}),this.runningCommand=c}_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,c=null,l=0;while(l<e.length||c){let u=c??e[l++];if(c=null,u==="--"){if(r===n)r.push(u);r.push(...e.slice(l));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[l++];if(f===void 0)this.optionMissingArgument(d);this.emit(`option:${d.name()}`,f)}else if(d.optional){let f=null;if(l<e.length&&(!s(e[l])||o(e[l])))f=e[l++];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()}`),c=`-${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(l));break}else if(this._getHelpCommand()&&u===this._getHelpCommand().name()){t.push(u,...e.slice(l));break}else if(this._defaultCommandName){n.push(u,...e.slice(l));break}}if(this._passThroughOptions){r.push(u,...e.slice(l));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 Y.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()}`,Y.env[e.envVar]);else this.emit(`optionEnv:${e.name()}`)}})}_parseOptionsImplied(){let e=new Nv(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(),c=this.getOptionValue(a),l=this.options.find((d)=>d.negate&&a===d.attributeName()),u=this.options.find((d)=>!d.negate&&a===d.attributeName());if(l&&(l.presetArg===void 0&&c===!1||l.presetArg!==void 0&&c===l.presetArg))return l;return u||o},r=(o)=>{let a=n(o),c=a.attributeName();if(this.getOptionValueSource(c)==="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=Yd(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=Yd(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)=>Pv(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=Xe.basename(e,Xe.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(Y.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 Bx(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(),c=this.getOptionValue(a),l=this.options.find((d)=>d.negate&&a===d.attributeName()),u=this.options.find((d)=>!d.negate&&a===d.attributeName());if(l&&(l.presetArg===void 0&&c===!1||l.presetArg!==void 0&&c===l.presetArg))return l;return u||o},r=(o)=>{let a=n(o),c=a.attributeName();if(this.getOptionValueSource(c)==="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=Tf(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=Tf(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)=>Lx(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=Qe.basename(e,Qe.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 Zd(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(Y.env.NO_COLOR||Y.env.FORCE_COLOR==="0"||Y.env.FORCE_COLOR==="false")return!1;if(Y.env.FORCE_COLOR||Y.env.CLICOLOR_FORCE!==void 0)return!0;return}Dv.Command=_c;Dv.useColor=gc});var Qs=Gn(function(aO,bc){var Zs=process||{},mf=Zs.argv||[],Ys=Zs.env||{},qv=!(!!Ys.NO_COLOR||mf.includes("--no-color"))&&(!!Ys.FORCE_COLOR||mf.includes("--color")||Zs.platform==="win32"||(Zs.stdout||{}).isTTY&&Ys.TERM!=="dumb"||!!Ys.CI),Hv=(e,t,n=e)=>(r)=>{let s=""+r,o=s.indexOf(t,e.length);return~o?e+Kv(s,t,n,o)+t:e+s+t},Kv=(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)},gf=(e=qv)=>{let t=e?Hv:()=>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=gf();bc.exports.createColors=gf});import{extname as ex}from"path";function Mt(e){return tx[ex(e).toLowerCase()]??null}var tx;var vi=We(()=>{tx={".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 lx}from"fs";import ux from"os";import ro from"path";function Gt(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 ao(e){if(e.provider!==void 0)xc=e.provider;if(e.model!==void 0){if(hn=e.model,e.modelMerge===void 0&&process.env.REVIEW_MODEL_MERGE===void 0)Xn=e.model}if(e.modelMerge!==void 0)Xn=e.modelMerge;if(e.modelWalk!==void 0)mn=e.modelWalk;if(e.modelIntent!==void 0)$r=e.modelIntent;if(e.effort!==void 0){if(xr=e.effort,e.effortAux===void 0&&process.env.REVIEW_EFFORT_AUX===void 0)Vt=e.effort}if(e.effortAux!==void 0)Vt=e.effortAux;if(e.sliceBudget!==void 0)Ec=e.sliceBudget;if(e.mergeBudget!==void 0)Ac=e.mergeBudget;if(e.walkBudget!==void 0)$i=e.walkBudget;if(e.partBudget!==void 0)Rc=e.partBudget;if(e.intentBudget!==void 0)kc=e.intentBudget;if(e.pool!==void 0)Cc=e.pool;if(e.maxSlices!==void 0)Yn=e.maxSlices;if(e.maxSliceTokens!==void 0)In=e.maxSliceTokens;if(e.walkDiffTokens!==void 0)Si=e.walkDiffTokens;if(e.maxSteps!==void 0)$c=e.maxSteps;if(e.deadlineMs!==void 0)Sc=e.deadlineMs;if(e.grouping!==void 0)Jn=e.grouping;if(e.artifacts!==void 0)_e=e.artifacts;if(e.out!==void 0)ht=e.out;if(e.extraExcludes!==void 0)Ri=e.extraExcludes;if(e.surfaces!==void 0)Zn=e.surfaces;if(e.providers!==void 0)so=e.providers;if(e.childEnv!==void 0)Ic=e.childEnv;if(e.authImport!==void 0)oo=e.authImport}function Rr(e){if(e.subject!==void 0)tt=e.subject;if(e.releaseSubject!==void 0)io=e.releaseSubject;if(e.repoName!==void 0)mt=e.repoName;if(e.signal!==void 0)Sr=e.signal}function co(){tt=process.cwd(),io=async()=>{},mt="this repository",Sr=void 0}var vr,tt,io=async()=>{},_e,Af="opencode",xc,$c,Sc,hn,xr,mn,Xn,$r,Vt,$i,Rc,kc,Jn,Ec,Ac,Cc,Yn,Cf=2.4,In,Si,If,ht,mt="this repository",Zn,Ri,so,Ic,oo="",Sr;var gt=We(()=>{vr=lx(ro.join(import.meta.dir,"system.md"))?import.meta.dir:ro.join(import.meta.dir,"review-core"),tt=process.cwd(),_e=process.env.CODE_REVIEW_ARTIFACTS??ro.join(process.cwd(),".code-review"),xc=process.env.REVIEW_PROVIDER??"anthropic",$c=Gt("REVIEW_MAX_STEPS",80),Sc=Gt("REVIEW_DEADLINE_S",900)*1000,hn=process.env.REVIEW_MODEL??"claude-opus-5-5",xr=process.env.REVIEW_EFFORT??"medium",mn=process.env.REVIEW_MODEL_WALK??"claude-sonnet-5-5",Xn=process.env.REVIEW_MODEL_MERGE??hn,$r=process.env.REVIEW_MODEL_INTENT??"claude-haiku-5-5",Vt=process.env.REVIEW_EFFORT_AUX??xr;$i=Gt("WALK_BUDGET_USD",2),Rc=Gt("PART_BUDGET",0.6),kc=Gt("INTENT_BUDGET_USD",0.1),Jn=process.env.REVIEW_GROUPING??"code";if(Jn!=="code"&&Jn!=="model")throw Error(`REVIEW_GROUPING must be "code" or "model", got "${Jn}"`);Ec=Gt("SLICE_BUDGET_USD",3),Ac=Gt("MERGE_BUDGET_USD",3),Cc=Gt("SLICE_POOL",6),Yn=Gt("MAX_SLICES",16),In=Gt("MAX_SLICE_TOKENS",42000),Si=Gt("WALK_DIFF_TOKENS",1e5),If=process.env.INLINE_MODE==="tier"?"tier":"none",ht=process.env.CODE_REVIEW_SCRATCH??ro.join(ux.tmpdir(),"code-review-out"),Zn={deploy:[],tooling:["^docs/","(^|/)[^/]*\\.config\\.[cm]?[jt]s$"]},Ri=[],so={},Ic={}});function kr(e){if(e!==Mn)throw Error("Illegal constructor")}function Ai(e){return!!e&&typeof e.row==="number"&&typeof e.column==="number"}function Jf(e){m=e}function Kc(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 Hc(e,t,n,r,s){for(let o=0,a=s.length;o<a;o++){let c=m.getValue(n,"i32");n+=Q;let l=Oe(t,n);n+=wt,s[o]={patternIndex:r,name:e.captureNames[c],node:l}}return n}function oe(e,t=0){let n=z+t*wt;m.setValue(n,e.id,"i32"),n+=Q,m.setValue(n,e.startIndex,"i32"),n+=Q,m.setValue(n,e.startPosition.row,"i32"),n+=Q,m.setValue(n,e.startPosition.column,"i32"),n+=Q,m.setValue(n,e[0],"i32")}function Oe(e,t=z){let n=m.getValue(t,"i32");if(t+=Q,n===0)return null;let r=m.getValue(t,"i32");t+=Q;let s=m.getValue(t,"i32");t+=Q;let o=m.getValue(t,"i32");t+=Q;let a=m.getValue(t,"i32");return new Qx(Mn,{id:n,tree:e,startIndex:r,startPosition:{row:s,column:o},other:a})}function $e(e,t=z){m.setValue(t+0*Q,e[0],"i32"),m.setValue(t+1*Q,e[1],"i32"),m.setValue(t+2*Q,e[2],"i32"),m.setValue(t+3*Q,e[3],"i32")}function It(e){e[0]=m.getValue(z+0*Q,"i32"),e[1]=m.getValue(z+1*Q,"i32"),e[2]=m.getValue(z+2*Q,"i32"),e[3]=m.getValue(z+3*Q,"i32")}function Tt(e,t){m.setValue(e,t.row,"i32"),m.setValue(e+Q,t.column,"i32")}function Qn(e){return{row:m.getValue(e,"i32")>>>0,column:m.getValue(e+Q,"i32")>>>0}}function Xf(e,t){Tt(e,t.startPosition),e+=on,Tt(e,t.endPosition),e+=on,m.setValue(e,t.startIndex,"i32"),e+=Q,m.setValue(e,t.endIndex,"i32"),e+=Q}function ho(e){let t={};return t.startPosition=Qn(e),e+=on,t.endPosition=Qn(e),e+=on,t.startIndex=m.getValue(e,"i32")>>>0,e+=Q,t.endIndex=m.getValue(e,"i32")>>>0,t}function Yf(e,t=z){Tt(t,e.startPosition),t+=on,Tt(t,e.oldEndPosition),t+=on,Tt(t,e.newEndPosition),t+=on,m.setValue(t,e.startIndex,"i32"),t+=Q,m.setValue(t,e.oldEndIndex,"i32"),t+=Q,m.setValue(t,e.newEndIndex,"i32"),t+=Q}function Zf(e){let t=m.getValue(e,"i32"),n=m.getValue(e+=Q,"i32"),r=m.getValue(e+=Q,"i32");return{major_version:t,minor_version:n,patch_version:r}}async function Qf(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_=x((e,t)=>{throw t},"quit_"),_scriptName=import.meta.url,scriptDirectory="";function locateFile(e){if(Module.locateFile)return Module.locateFile(e,scriptDirectory);return scriptDirectory+e}x(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=x((e)=>{e=isFileURI(e)?new URL(e):e;var t=fs.readFileSync(e);return t},"readBinary"),readAsync=x(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_=x((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=x((e)=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)},"readBinary");readAsync=x(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=x((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()}x(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()}x(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)}x(preRun,"preRun");function initRuntime(){runtimeInitialized=!0,callRuntimeCallbacks(__RELOC_FUNCS__),wasmExports.__wasm_call_ctors(),callRuntimeCallbacks(onPostCtors)}x(initRuntime,"initRuntime");function preMain(){}x(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)}x(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}x(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}x(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"}x(getBinarySync,"getBinarySync");async function getWasmBinary(e){if(!wasmBinary)try{var t=await readAsync(e);return new Uint8Array(t)}catch{}return getBinarySync(e)}x(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)}}x(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)}x(instantiateAsync,"instantiateAsync");function getWasmImports(){return{env:wasmImports,wasi_snapshot_preview1:wasmImports,"GOT.mem":new Proxy(wasmImports,GOTHandler),"GOT.func":new Proxy(wasmImports,GOTHandler)}}x(getWasmImports,"getWasmImports");async function createWasm(){function e(o,a){wasmExports=o.exports,wasmExports=relocateExports(wasmExports,1024);var c=getDylinkMetadata(a);if(c.neededDynlibs)dynamicLibraries=c.neededDynlibs.concat(dynamicLibraries);return mergeLibSymbols(wasmExports,"main"),LDSO.init(),loadDylibs(),__RELOC_FUNCS__.push(wasmExports.__wasm_apply_data_relocs),assignWasmExports(wasmExports),wasmExports}x(e,"receiveInstance");function t(o){return e(o.instance,o.module)}x(t,"receiveInstantiationResult");var n=getWasmImports();if(Module.instantiateWasm)return new Promise((o,a)=>{Module.instantiateWasm(n,(c,l)=>{o(e(c,l))})});wasmBinaryFile??=findWasmBinary();var r=await instantiateAsync(wasmBinary,wasmBinaryFile,n),s=t(r);return s}x(createWasm,"createWasm");class ExitStatus{static{x(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=x((e)=>HEAP_DATA_VIEW.getFloat32(e,!0),"LE_HEAP_LOAD_F32"),LE_HEAP_LOAD_F64=x((e)=>HEAP_DATA_VIEW.getFloat64(e,!0),"LE_HEAP_LOAD_F64"),LE_HEAP_LOAD_I16=x((e)=>HEAP_DATA_VIEW.getInt16(e,!0),"LE_HEAP_LOAD_I16"),LE_HEAP_LOAD_I32=x((e)=>HEAP_DATA_VIEW.getInt32(e,!0),"LE_HEAP_LOAD_I32"),LE_HEAP_LOAD_I64=x((e)=>HEAP_DATA_VIEW.getBigInt64(e,!0),"LE_HEAP_LOAD_I64"),LE_HEAP_LOAD_U32=x((e)=>HEAP_DATA_VIEW.getUint32(e,!0),"LE_HEAP_LOAD_U32"),LE_HEAP_STORE_F32=x((e,t)=>HEAP_DATA_VIEW.setFloat32(e,t,!0),"LE_HEAP_STORE_F32"),LE_HEAP_STORE_F64=x((e,t)=>HEAP_DATA_VIEW.setFloat64(e,t,!0),"LE_HEAP_STORE_F64"),LE_HEAP_STORE_I16=x((e,t)=>HEAP_DATA_VIEW.setInt16(e,t,!0),"LE_HEAP_STORE_I16"),LE_HEAP_STORE_I32=x((e,t)=>HEAP_DATA_VIEW.setInt32(e,t,!0),"LE_HEAP_STORE_I32"),LE_HEAP_STORE_I64=x((e,t)=>HEAP_DATA_VIEW.setBigInt64(e,t,!0),"LE_HEAP_STORE_I64"),LE_HEAP_STORE_U32=x((e,t)=>HEAP_DATA_VIEW.setUint32(e,t,!0),"LE_HEAP_STORE_U32"),callRuntimeCallbacks=x((e)=>{while(e.length>0)e.shift()(Module)},"callRuntimeCallbacks"),onPostRuns=[],addOnPostRun=x((e)=>onPostRuns.push(e),"addOnPostRun"),onPreRuns=[],addOnPreRun=x((e)=>onPreRuns.push(e),"addOnPreRun"),UTF8Decoder=typeof TextDecoder<"u"?new TextDecoder:void 0,findStringEnd=x((e,t,n,r)=>{var s=t+n;if(r)return s;while(e[t]&&!(t>=s))++t;return t},"findStringEnd"),UTF8ArrayToString=x((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 c=e[t++]&63;if((a&224)==192){o+=String.fromCharCode((a&31)<<6|c);continue}var l=e[t++]&63;if((a&240)==224)a=(a&15)<<12|c<<6|l;else a=(a&7)<<18|c<<12|l<<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=x((e)=>{var t=0,n=0;function r(){return e[t++]}x(r,"getU8");function s(){var U=0,q=1;while(!0){var Ee=e[t++];if(U+=(Ee&127)*q,q*=128,!(Ee&128))break}return U}x(s,"getLEB");function o(){var U=s();return t+=U,UTF8ArrayToString(e,t-U,U)}x(o,"getString");function a(){var U=s(),q=[];while(U--)q.push(o());return q}x(a,"getStringList");function c(U,q){if(U)throw Error(q)}if(x(c,"failIf"),e instanceof WebAssembly.Module){var l=WebAssembly.Module.customSections(e,"dylink.0");c(l.length===0,"need dylink section"),e=new Uint8Array(l[0]),n=e.length}else{var u=new Uint32Array(new Uint8Array(e.subarray(0,24)).buffer),d=u[0]==1836278016||u[0]==6386541;c(!d,"need to see wasm magic number"),c(e[8]!==0,"need the dylink section to be first"),t=9;var f=s();n=t+f;var p=o();c(p!=="dylink.0")}var h={neededDynlibs:[],tlsExports:new Set,weakImports:new Set,runtimePaths:[]},y=1,v=2,b=3,g=4,R=5,N=256,I=3,_=1;while(t<n){var S=r(),O=s();if(S===y)h.memorySize=s(),h.memoryAlign=s(),h.tableSize=s(),h.tableAlign=s();else if(S===v)h.neededDynlibs=a();else if(S===b){var P=s();while(P--){var C=o(),j=s();if(j&N)h.tlsExports.add(C)}}else if(S===g){var P=s();while(P--){var H=o(),C=o(),j=s();if((j&I)==_)h.weakImports.add(C)}}else if(S===R)h.runtimePaths=a();else t+=O}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}`)}}x(getValue,"getValue");var newDSO=x((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=x((e,t)=>Math.ceil(e/t)*t,"alignMemory"),getMemory=x((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=x((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=x((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=x((e)=>uleb128EncodeWithLen(Array.from(e,(t)=>{var n=wasmTypeCodes[t];return n})),"generateTypePack"),convertJsFunctionToWasm=x((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=x((e)=>{var t=wasmTableMirror[e];if(!t)wasmTableMirror[e]=t=wasmTable.get(e);return t},"getWasmTableEntry"),updateTableMap=x((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=x((e)=>{if(!functionsInTableMap)functionsInTableMap=new WeakMap,updateTableMap(0,wasmTable.length);return functionsInTableMap.get(e)||0},"getFunctionAddress"),freeTableIndexes=[],getEmptyTableSlot=x(()=>{if(freeTableIndexes.length)return freeTableIndexes.pop();return wasmTable.grow(1)},"getEmptyTableSlot"),setWasmTableEntry=x((e,t)=>{wasmTable.set(e,t),wasmTableMirror[e]=wasmTable.get(e)},"setWasmTableEntry"),addFunction=x((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=x((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=x((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=x((e)=>{var t=wasmImports[e];if(!t||t.stub)return!1;return!0},"isSymbolDefined"),dynCall=x((e,t,n=[],r=!1)=>{var s=getWasmTableEntry(t),o=s(...n);function a(c){return c}return x(a,"convert"),a(o)},"dynCall"),stackSave=x(()=>_emscripten_stack_get_current(),"stackSave"),stackRestore=x((e)=>__emscripten_stack_restore(e),"stackRestore"),createInvokeFunction=x((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=x((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=x((e)=>onPostCtors.push(e),"addOnPostCtor"),UTF8ToString=x((e,t,n)=>e?UTF8ArrayToString(HEAPU8,e,t,n):"","UTF8ToString"),loadWebAssemblyModule=x((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}x(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(x(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)}x(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(x(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(x(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=x((e,t)=>{for(var[n,r]of Object.entries(e)){let s=x((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=x(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 l=LE_HEAP_LOAD_U32((r+28>>2)*4),u=LE_HEAP_LOAD_U32((r+32>>2)*4);if(l&&u){var d=HEAP8.slice(l,l+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)}x(o,"loadLibData");function a(){if(t.loadAsync)return o().then((l)=>loadWebAssemblyModule(l,t,e,n,r));return loadWebAssemblyModule(o(),t,e,n,r)}x(a,"getExports");function c(l){if(s.global)mergeLibSymbols(l,e);else if(n)Object.assign(n,l);s.exports=l}if(x(c,"moduleLoaded"),t.loadAsync)return a().then((l)=>(c(l),!0));return c(a()),!0}x(loadDynamicLibrary,"loadDynamicLibrary");var reportUndefinedSymbols=x(()=>{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=x((e)=>{if(runDependencies--,Module.monitorRunDependencies?.(runDependencies),runDependencies==0){if(dependenciesFulfilled){var t=dependenciesFulfilled;dependenciesFulfilled=null,t()}}},"removeRunDependency"),addRunDependency=x((e)=>{runDependencies++,Module.monitorRunDependencies?.(runDependencies)},"addRunDependency"),loadDylibs=x(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}`)}}x(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=x(()=>abort(""),"__abort_js");__abort_js.sig="v";var getHeapMax=x(()=>2147483648,"getHeapMax"),growMemory=x((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=x((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=x((e)=>52,"_fd_close");_fd_close.sig="ii";var INT53_MAX=9007199254740992,INT53_MIN=-9007199254740992,bigintToI53Checked=x((e)=>e<INT53_MIN||e>INT53_MAX?NaN:Number(e),"bigintToI53Checked");function _fd_seek(e,t,n,r){return t=bigintToI53Checked(t),70}x(_fd_seek,"_fd_seek"),_fd_seek.sig="iijip";var printCharBuffers=[null,[],[]],printChar=x((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=x((e,t,n,r)=>{var s=0;for(var o=0;o<n;o++){var a=LE_HEAP_LOAD_U32((t>>2)*4),c=LE_HEAP_LOAD_U32((t+4>>2)*4);t+=8;for(var l=0;l<c;l++)printChar(e,HEAPU8[a+l]);s+=c}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)}}x(_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")}x(_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}x(_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}x(_tree_sitter_query_progress_callback,"_tree_sitter_query_progress_callback");var runtimeKeepaliveCounter=0,keepRuntimeAlive=x(()=>noExitRuntime||runtimeKeepaliveCounter>0,"keepRuntimeAlive"),_proc_exit=x((e)=>{if(EXITSTATUS=e,!keepRuntimeAlive())Module.onExit?.(e),ABORT=!0;quit_(e,new ExitStatus(e))},"_proc_exit");_proc_exit.sig="vi";var exitJS=x((e,t)=>{EXITSTATUS=e,_proc_exit(e)},"exitJS"),handleException=x((e)=>{if(e instanceof ExitStatus||e=="unwind")return EXITSTATUS;quit_(1,e)},"handleException"),lengthBytesUTF8=x((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=x((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 c=e.codePointAt(a);if(c<=127){if(n>=o)break;t[n++]=c}else if(c<=2047){if(n+1>=o)break;t[n++]=192|c>>6,t[n++]=128|c&63}else if(c<=65535){if(n+2>=o)break;t[n++]=224|c>>12,t[n++]=128|c>>6&63,t[n++]=128|c&63}else{if(n+3>=o)break;t[n++]=240|c>>18,t[n++]=128|c>>12&63,t[n++]=128|c>>6&63,t[n++]=128|c&63,a++}}return t[n]=0,n-s},"stringToUTF8Array"),stringToUTF8=x((e,t,n)=>stringToUTF8Array(e,HEAPU8,t,n),"stringToUTF8"),stackAlloc=x((e)=>__emscripten_stack_alloc(e),"stackAlloc"),stringToUTF8OnStack=x((e)=>{var t=lengthBytesUTF8(e)+1,n=stackAlloc(t);return stringToUTF8(e,n,t),n},"stringToUTF8OnStack"),AsciiToString=x((e)=>{var t="";while(!0){var n=HEAPU8[e++];if(!n)return t;t+=String.fromCharCode(n)}},"AsciiToString"),stringToUTF16=x((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}x(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}x(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)}}x(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(x(t,"doRun"),Module.setStatus)Module.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>Module.setStatus(""),1),t()},1);else t()}x(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 tp(e){return ep??=await t$(e)}function np(){return!!ep}function rp(e,t,n,r){if(e.length!==3)throw Error(`Wrong number of arguments to \`#${n}\` predicate. Expected 2, got ${e.length-1}`);if(!zf(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(zf(e[2])){let a=e[1].name,c=e[2].name;r[t].push((l)=>{let u=[],d=[];for(let p of l){if(p.name===a)u.push(p.node);if(p.name===c)d.push(p.node)}let f=x((p,h,y)=>y?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,c=e[2].value,l=x((d)=>d.text===c,"matches"),u=x((d)=>d.text!==c,"doesNotMatch");r[t].push((d)=>{let f=[];for(let h of d)if(h.name===a)f.push(h.node);let p=s?l:u;return o?f.every(p):f.some(p)})}}function ip(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,c=new RegExp(e[2].value);r[t].push((l)=>{let u=[];for(let f of l)if(f.name===a)u.push(f.node.text);let d=x((f,p)=>p?c.test(f):!c.test(f),"test");if(u.length===0)return!s;return o?u.every((f)=>d(f,s)):u.some((f)=>d(f,s))})}function sp(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(Gc))throw Error(`Arguments to \`#${n}\` predicate must be strings.".`);let c=a.map((l)=>l.value);r[t].push((l)=>{let u=[];for(let d of l)if(d.name===o)u.push(d.node.text);if(u.length===0)return!s;return u.every((d)=>c.includes(d))===s})}function op(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(Gc))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 ap(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(Gc))throw Error('Arguments to `#set!` predicate must be strings.".');if(!n[t])n[t]={};n[t][e[1].value]=e[2]?.value??null}function cp(e,t,n,r,s,o,a,c,l,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?":rp(o,e,f,a);break;case"any-not-match?":case"not-match?":case"any-match?":case"match?":ip(o,e,f,a);break;case"not-any-of?":case"any-of?":sp(o,e,f,a);break;case"is?":case"is-not?":op(o,e,f,u,d);break;case"set!":ap(o,e,l);break;default:c[e].push({operator:f,operands:o.slice(1)})}o.length=0}}var Jx,x=(e,t)=>Jx(e,"name",{value:t,configurable:!0}),UO,Gf=2,Q=4,Uc,wt,on,Ci,_t,Mn,m,Xx,Yx,Zx,Qx,e$,Wc,t$,ep=null,z,Bc,qc,Vc,n$=1,r$=2,i$,BO,zf,Gc,zt,Ei,zc;var lp=We(()=>{Jx=Object.defineProperty,UO=class{static{x(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}},Uc=4*Q,wt=5*Q,on=2*Q,Ci=2*Q+2*on,_t={row:0,column:0},Mn=Symbol("INTERNAL");x(kr,"assertInternal");x(Ai,"isPoint");x(Jf,"setModule");Xx=class{static{x(this,"LookaheadIterator")}[0]=0;language;constructor(e,t,n){kr(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:x(()=>{if(m._ts_lookahead_iterator_next(this[0]))return{done:!1,value:this.currentType};return{done:!0,value:""}},"next")}}};x(Kc,"getText");Yx=class e{static{x(this,"Tree")}[0]=0;textCallback;language;constructor(t,n,r,s){kr(t),this[0]=n,this.language=r,this.textCallback=s}copy(){let t=m._ts_tree_copy(this[0]);return new e(Mn,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=z+wt;return m.setValue(r,t,"i32"),Tt(r+Q,n),m._ts_tree_root_node_with_offset_wasm(this[0]),Oe(this)}edit(t){Yf(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(z,"i32"),r=m.getValue(z+Q,"i32"),s=Array(n);if(n>0){let o=r;for(let a=0;a<n;a++)s[a]=ho(o),o+=Ci;m._free(r)}return s}getIncludedRanges(){m._ts_tree_included_ranges_wasm(this[0]);let t=m.getValue(z,"i32"),n=m.getValue(z+Q,"i32"),r=Array(t);if(t>0){let s=n;for(let o=0;o<t;o++)r[o]=ho(s),s+=Ci;m._free(n)}return r}},Zx=class e{static{x(this,"TreeCursor")}[0]=0;[1]=0;[2]=0;[3]=0;tree;constructor(t,n){kr(t),this.tree=n,It(this)}copy(){let t=new e(Mn,this.tree);return m._ts_tree_cursor_copy_wasm(this.tree[0]),It(t),t}delete(){$e(this),m._ts_tree_cursor_delete_wasm(this.tree[0]),this[0]=this[1]=this[2]=0}get currentNode(){return $e(this),m._ts_tree_cursor_current_node_wasm(this.tree[0]),Oe(this.tree)}get currentFieldId(){return $e(this),m._ts_tree_cursor_current_field_id_wasm(this.tree[0])}get currentFieldName(){return this.tree.language.fields[this.currentFieldId]}get currentDepth(){return $e(this),m._ts_tree_cursor_current_depth_wasm(this.tree[0])}get currentDescendantIndex(){return $e(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 $e(this),m._ts_tree_cursor_current_node_type_id_wasm(this.tree[0])}get nodeStateId(){return $e(this),m._ts_tree_cursor_current_node_state_id_wasm(this.tree[0])}get nodeId(){return $e(this),m._ts_tree_cursor_current_node_id_wasm(this.tree[0])}get nodeIsNamed(){return $e(this),m._ts_tree_cursor_current_node_is_named_wasm(this.tree[0])===1}get nodeIsMissing(){return $e(this),m._ts_tree_cursor_current_node_is_missing_wasm(this.tree[0])===1}get nodeText(){$e(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=Qn(z);return Kc(this.tree,t,n,r)}get startPosition(){return $e(this),m._ts_tree_cursor_start_position_wasm(this.tree[0]),Qn(z)}get endPosition(){return $e(this),m._ts_tree_cursor_end_position_wasm(this.tree[0]),Qn(z)}get startIndex(){return $e(this),m._ts_tree_cursor_start_index_wasm(this.tree[0])}get endIndex(){return $e(this),m._ts_tree_cursor_end_index_wasm(this.tree[0])}gotoFirstChild(){$e(this);let t=m._ts_tree_cursor_goto_first_child_wasm(this.tree[0]);return It(this),t===1}gotoLastChild(){$e(this);let t=m._ts_tree_cursor_goto_last_child_wasm(this.tree[0]);return It(this),t===1}gotoParent(){$e(this);let t=m._ts_tree_cursor_goto_parent_wasm(this.tree[0]);return It(this),t===1}gotoNextSibling(){$e(this);let t=m._ts_tree_cursor_goto_next_sibling_wasm(this.tree[0]);return It(this),t===1}gotoPreviousSibling(){$e(this);let t=m._ts_tree_cursor_goto_previous_sibling_wasm(this.tree[0]);return It(this),t===1}gotoDescendant(t){$e(this),m._ts_tree_cursor_goto_descendant_wasm(this.tree[0],t),It(this)}gotoFirstChildForIndex(t){$e(this),m.setValue(z+Uc,t,"i32");let n=m._ts_tree_cursor_goto_first_child_for_index_wasm(this.tree[0]);return It(this),n===1}gotoFirstChildForPosition(t){$e(this),Tt(z+Uc,t);let n=m._ts_tree_cursor_goto_first_child_for_position_wasm(this.tree[0]);return It(this),n===1}reset(t){oe(t),$e(this,z+wt),m._ts_tree_cursor_reset_wasm(this.tree[0]),It(this)}resetTo(t){$e(this,z),$e(t,z+Uc),m._ts_tree_cursor_reset_to_wasm(this.tree[0],t.tree[0]),It(this)}},Qx=class{static{x(this,"Node")}[0]=0;_children;_namedChildren;constructor(e,{id:t,tree:n,startIndex:r,startPosition:s,other:o}){kr(e),this[0]=o,this.id=t,this.tree=n,this.startIndex=r,this.startPosition=s}id;startIndex;startPosition;tree;get typeId(){return oe(this),m._ts_node_symbol_wasm(this.tree[0])}get grammarId(){return oe(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 oe(this),m._ts_node_is_named_wasm(this.tree[0])===1}get isExtra(){return oe(this),m._ts_node_is_extra_wasm(this.tree[0])===1}get isError(){return oe(this),m._ts_node_is_error_wasm(this.tree[0])===1}get isMissing(){return oe(this),m._ts_node_is_missing_wasm(this.tree[0])===1}get hasChanges(){return oe(this),m._ts_node_has_changes_wasm(this.tree[0])===1}get hasError(){return oe(this),m._ts_node_has_error_wasm(this.tree[0])===1}get endIndex(){return oe(this),m._ts_node_end_index_wasm(this.tree[0])}get endPosition(){return oe(this),m._ts_node_end_point_wasm(this.tree[0]),Qn(z)}get text(){return Kc(this.tree,this.startIndex,this.endIndex,this.startPosition)}get parseState(){return oe(this),m._ts_node_parse_state_wasm(this.tree[0])}get nextParseState(){return oe(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 oe(this),m._ts_node_child_wasm(this.tree[0],e),Oe(this.tree)}namedChild(e){return oe(this),m._ts_node_named_child_wasm(this.tree[0],e),Oe(this.tree)}childForFieldId(e){return oe(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){oe(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){oe(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){oe(this),m._ts_node_children_by_field_id_wasm(this.tree[0],e);let t=m.getValue(z,"i32"),n=m.getValue(z+Q,"i32"),r=Array(t);if(t>0){let s=n;for(let o=0;o<t;o++)r[o]=Oe(this.tree,s),s+=wt;m._free(n)}return r}firstChildForIndex(e){oe(this);let t=z+wt;return m.setValue(t,e,"i32"),m._ts_node_first_child_for_byte_wasm(this.tree[0]),Oe(this.tree)}firstNamedChildForIndex(e){oe(this);let t=z+wt;return m.setValue(t,e,"i32"),m._ts_node_first_named_child_for_byte_wasm(this.tree[0]),Oe(this.tree)}get childCount(){return oe(this),m._ts_node_child_count_wasm(this.tree[0])}get namedChildCount(){return oe(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){oe(this),m._ts_node_children_wasm(this.tree[0]);let e=m.getValue(z,"i32"),t=m.getValue(z+Q,"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+=wt;m._free(t)}}return this._children}get namedChildren(){if(!this._namedChildren){oe(this),m._ts_node_named_children_wasm(this.tree[0]);let e=m.getValue(z,"i32"),t=m.getValue(z+Q,"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+=wt;m._free(t)}}return this._namedChildren}descendantsOfType(e,t=_t,n=_t){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(Q*r.length);for(let u=0,d=r.length;u<d;u++)m.setValue(o+u*Q,r[u],"i32");oe(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(z,"i32"),c=m.getValue(z+Q,"i32"),l=Array(a);if(a>0){let u=c;for(let d=0;d<a;d++)l[d]=Oe(this.tree,u),u+=wt}return m._free(c),m._free(o),l}get nextSibling(){return oe(this),m._ts_node_next_sibling_wasm(this.tree[0]),Oe(this.tree)}get previousSibling(){return oe(this),m._ts_node_prev_sibling_wasm(this.tree[0]),Oe(this.tree)}get nextNamedSibling(){return oe(this),m._ts_node_next_named_sibling_wasm(this.tree[0]),Oe(this.tree)}get previousNamedSibling(){return oe(this),m._ts_node_prev_named_sibling_wasm(this.tree[0]),Oe(this.tree)}get descendantCount(){return oe(this),m._ts_node_descendant_count_wasm(this.tree[0])}get parent(){return oe(this),m._ts_node_parent_wasm(this.tree[0]),Oe(this.tree)}childWithDescendant(e){return oe(this),oe(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");oe(this);let n=z+wt;return m.setValue(n,e,"i32"),m.setValue(n+Q,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");oe(this);let n=z+wt;return m.setValue(n,e,"i32"),m.setValue(n+Q,t,"i32"),m._ts_node_named_descendant_for_index_wasm(this.tree[0]),Oe(this.tree)}descendantForPosition(e,t=e){if(!Ai(e)||!Ai(t))throw Error("Arguments must be {row, column} objects");oe(this);let n=z+wt;return Tt(n,e),Tt(n+on,t),m._ts_node_descendant_for_position_wasm(this.tree[0]),Oe(this.tree)}namedDescendantForPosition(e,t=e){if(!Ai(e)||!Ai(t))throw Error("Arguments must be {row, column} objects");oe(this);let n=z+wt;return Tt(n,e),Tt(n+on,t),m._ts_node_named_descendant_for_position_wasm(this.tree[0]),Oe(this.tree)}walk(){return oe(this),m._ts_tree_cursor_new_wasm(this.tree[0]),new Zx(Mn,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(){oe(this);let e=m._ts_node_to_string_wasm(this.tree[0]),t=m.AsciiToString(e);return m._free(e),t}};x(Hc,"unmarshalCaptures");x(oe,"marshalNode");x(Oe,"unmarshalNode");x($e,"marshalTreeCursor");x(It,"unmarshalTreeCursor");x(Tt,"marshalPoint");x(Qn,"unmarshalPoint");x(Xf,"marshalRange");x(ho,"unmarshalRange");x(Yf,"marshalEdit");x(Zf,"unmarshalLanguageMetadata");e$=/^tree_sitter_\w+$/,Wc=class e{static{x(this,"Language")}[0]=0;types;fields;constructor(t,n){kr(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(z,"i32")===0)return null;return Zf(z+Q)}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(z,"i32"),n=m.getValue(z+Q,"i32"),r=Array(t);if(t>0){let s=n;for(let o=0;o<t;o++)r[o]=m.getValue(s,"i16"),s+=Gf}return r}subtypes(t){m._ts_language_subtypes_wasm(this[0],t);let n=m.getValue(z,"i32"),r=m.getValue(z+Q,"i32"),s=Array(n);if(n>0){let o=r;for(let a=0;a<n;a++)s[a]=m.getValue(o,"i16"),o+=Gf}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 Xx(Mn,n,this);return null}static async load(t){let n;if(t instanceof Uint8Array)n=t;else if(globalThis.process?.versions.node){let c=await import("fs/promises");n=await c.readFile(t)}else{let c=await fetch(t);if(!c.ok){let u=await c.text();throw Error(`Language.load failed with status ${c.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 Ff(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 jc(){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}qx.Command=Uc;qx.useColor=jc});var mo=ir(function(LP,Hc){var ho=process||{},Yf=ho.argv||[],po=ho.env||{},zx=!(!!po.NO_COLOR||Yf.includes("--no-color"))&&(!!po.FORCE_COLOR||Yf.includes("--color")||ho.platform==="win32"||(ho.stdout||{}).isTTY&&po.TERM!=="dumb"||!!po.CI),Jx=(e,t,n=e)=>(r)=>{let s=""+r,o=s.indexOf(t,e.length);return~o?e+Xx(s,t,n,o)+t:e+s+t},Xx=(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)},Zf=(e=zx)=>{let t=e?Jx:()=>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")}};Hc.exports=Zf();Hc.exports.createColors=Zf});import{extname as oS}from"path";function Ft(e){return aS[oS(e).toLowerCase()]??null}var aS;var Fi=We(()=>{aS={".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 mS}from"fs";import gS from"os";import yo from"path";function Jt(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 So(e){if(e.provider!==void 0)Wc=e.provider;if(e.model!==void 0){if(_n=e.model,e.modelMerge===void 0&&process.env.REVIEW_MODEL_MERGE===void 0)cr=e.model}if(e.modelMerge!==void 0)cr=e.modelMerge;if(e.modelWalk!==void 0)wn=e.modelWalk;if(e.modelIntent!==void 0)Ur=e.modelIntent;if(e.effort!==void 0){if(jr=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)Xc=e.sliceBudget;if(e.mergeBudget!==void 0)Yc=e.mergeBudget;if(e.walkBudget!==void 0)Di=e.walkBudget;if(e.partBudget!==void 0)zc=e.partBudget;if(e.intentBudget!==void 0)Jc=e.intentBudget;if(e.pool!==void 0)Zc=e.pool;if(e.maxSlices!==void 0)lr=e.maxSlices;if(e.maxSliceTokens!==void 0)jn=e.maxSliceTokens;if(e.walkDiffTokens!==void 0)Li=e.walkDiffTokens;if(e.maxSteps!==void 0)Vc=e.maxSteps;if(e.deadlineMs!==void 0)Gc=e.deadlineMs;if(e.grouping!==void 0)ar=e.grouping;if(e.artifacts!==void 0)we=e.artifacts;if(e.out!==void 0)gt=e.out;if(e.extraExcludes!==void 0)ji=e.extraExcludes;if(e.surfaces!==void 0)ur=e.surfaces;if(e.providers!==void 0)vo=e.providers;if(e.childEnv!==void 0)Qc=e.childEnv;if(e.authImport!==void 0)xo=e.authImport}function qr(e){if(e.subject!==void 0)rt=e.subject;if(e.releaseSubject!==void 0)bo=e.releaseSubject;if(e.repoName!==void 0)_t=e.repoName;if(e.signal!==void 0)Br=e.signal}function Ro(){rt=process.cwd(),bo=async()=>{},_t="this repository",Br=void 0}var Lr,rt,bo=async()=>{},we,up="opencode",Wc,Vc,Gc,_n,jr,wn,cr,Ur,zt,Di,zc,Jc,ar,Xc,Yc,Zc,lr,dp=2.4,jn,Li,fp,gt,_t="this repository",ur,ji,vo,Qc,xo="",Br;var wt=We(()=>{Lr=mS(yo.join(import.meta.dir,"system.md"))?import.meta.dir:yo.join(import.meta.dir,"review-core"),rt=process.cwd(),we=process.env.CODE_REVIEW_ARTIFACTS??yo.join(process.cwd(),".code-review"),Wc=process.env.REVIEW_PROVIDER??"anthropic",Vc=Jt("REVIEW_MAX_STEPS",80),Gc=Jt("REVIEW_DEADLINE_S",900)*1000,_n=process.env.REVIEW_MODEL??"claude-opus-5-5",jr=process.env.REVIEW_EFFORT??"medium",wn=process.env.REVIEW_MODEL_WALK??"claude-sonnet-5-5",cr=process.env.REVIEW_MODEL_MERGE??_n,Ur=process.env.REVIEW_MODEL_INTENT??"claude-haiku-5-5",zt=process.env.REVIEW_EFFORT_AUX??jr;Di=Jt("WALK_BUDGET_USD",2),zc=Jt("PART_BUDGET",0.6),Jc=Jt("INTENT_BUDGET_USD",0.1),ar=process.env.REVIEW_GROUPING??"code";if(ar!=="code"&&ar!=="model")throw Error(`REVIEW_GROUPING must be "code" or "model", got "${ar}"`);Xc=Jt("SLICE_BUDGET_USD",3),Yc=Jt("MERGE_BUDGET_USD",3),Zc=Jt("SLICE_POOL",6),lr=Jt("MAX_SLICES",16),jn=Jt("MAX_SLICE_TOKENS",42000),Li=Jt("WALK_DIFF_TOKENS",1e5),fp=process.env.INLINE_MODE==="tier"?"tier":"none",gt=process.env.CODE_REVIEW_SCRATCH??yo.join(gS.tmpdir(),"code-review-out"),ur={deploy:[],tooling:["^docs/","(^|/)[^/]*\\.config\\.[cm]?[jt]s$"]},ji=[],vo={},Qc={}});function Hr(e){if(e!==qn)throw Error("Illegal constructor")}function qi(e){return!!e&&typeof e.row==="number"&&typeof e.column==="number"}function Op(e){m=e}function pl(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 fl(e,t,n,r,s){for(let o=0,a=s.length;o<a;o++){let c=m.getValue(n,"i32");n+=Y;let l=Ie(t,n);n+=bt,s[o]={patternIndex:r,name:e.captureNames[c],node:l}}return n}function ce(e,t=0){let n=V+t*bt;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 Ie(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 sR(qn,{id:n,tree:e,startIndex:r,startPosition:{row:s,column:o},other:a})}function ve(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 Ot(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 Nt(e,t){m.setValue(e,t.row,"i32"),m.setValue(e+Y,t.column,"i32")}function dr(e){return{row:m.getValue(e,"i32")>>>0,column:m.getValue(e+Y,"i32")>>>0}}function Pp(e,t){Nt(e,t.startPosition),e+=ln,Nt(e,t.endPosition),e+=ln,m.setValue(e,t.startIndex,"i32"),e+=Y,m.setValue(e,t.endIndex,"i32"),e+=Y}function Co(e){let t={};return t.startPosition=dr(e),e+=ln,t.endPosition=dr(e),e+=ln,t.startIndex=m.getValue(e,"i32")>>>0,e+=Y,t.endIndex=m.getValue(e,"i32")>>>0,t}function Mp(e,t=V){Nt(t,e.startPosition),t+=ln,Nt(t,e.oldEndPosition),t+=ln,Nt(t,e.newEndPosition),t+=ln,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 Tp(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 Fp(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_=x((e,t)=>{throw t},"quit_"),_scriptName=import.meta.url,scriptDirectory="";function locateFile(e){if(Module.locateFile)return Module.locateFile(e,scriptDirectory);return scriptDirectory+e}x(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=x((e)=>{e=isFileURI(e)?new URL(e):e;var t=fs.readFileSync(e);return t},"readBinary"),readAsync=x(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_=x((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=x((e)=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)},"readBinary");readAsync=x(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=x((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()}x(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()}x(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)}x(preRun,"preRun");function initRuntime(){runtimeInitialized=!0,callRuntimeCallbacks(__RELOC_FUNCS__),wasmExports.__wasm_call_ctors(),callRuntimeCallbacks(onPostCtors)}x(initRuntime,"initRuntime");function preMain(){}x(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)}x(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}x(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}x(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"}x(getBinarySync,"getBinarySync");async function getWasmBinary(e){if(!wasmBinary)try{var t=await readAsync(e);return new Uint8Array(t)}catch{}return getBinarySync(e)}x(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)}}x(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)}x(instantiateAsync,"instantiateAsync");function getWasmImports(){return{env:wasmImports,wasi_snapshot_preview1:wasmImports,"GOT.mem":new Proxy(wasmImports,GOTHandler),"GOT.func":new Proxy(wasmImports,GOTHandler)}}x(getWasmImports,"getWasmImports");async function createWasm(){function e(o,a){wasmExports=o.exports,wasmExports=relocateExports(wasmExports,1024);var c=getDylinkMetadata(a);if(c.neededDynlibs)dynamicLibraries=c.neededDynlibs.concat(dynamicLibraries);return mergeLibSymbols(wasmExports,"main"),LDSO.init(),loadDylibs(),__RELOC_FUNCS__.push(wasmExports.__wasm_apply_data_relocs),assignWasmExports(wasmExports),wasmExports}x(e,"receiveInstance");function t(o){return e(o.instance,o.module)}x(t,"receiveInstantiationResult");var n=getWasmImports();if(Module.instantiateWasm)return new Promise((o,a)=>{Module.instantiateWasm(n,(c,l)=>{o(e(c,l))})});wasmBinaryFile??=findWasmBinary();var r=await instantiateAsync(wasmBinary,wasmBinaryFile,n),s=t(r);return s}x(createWasm,"createWasm");class ExitStatus{static{x(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=x((e)=>HEAP_DATA_VIEW.getFloat32(e,!0),"LE_HEAP_LOAD_F32"),LE_HEAP_LOAD_F64=x((e)=>HEAP_DATA_VIEW.getFloat64(e,!0),"LE_HEAP_LOAD_F64"),LE_HEAP_LOAD_I16=x((e)=>HEAP_DATA_VIEW.getInt16(e,!0),"LE_HEAP_LOAD_I16"),LE_HEAP_LOAD_I32=x((e)=>HEAP_DATA_VIEW.getInt32(e,!0),"LE_HEAP_LOAD_I32"),LE_HEAP_LOAD_I64=x((e)=>HEAP_DATA_VIEW.getBigInt64(e,!0),"LE_HEAP_LOAD_I64"),LE_HEAP_LOAD_U32=x((e)=>HEAP_DATA_VIEW.getUint32(e,!0),"LE_HEAP_LOAD_U32"),LE_HEAP_STORE_F32=x((e,t)=>HEAP_DATA_VIEW.setFloat32(e,t,!0),"LE_HEAP_STORE_F32"),LE_HEAP_STORE_F64=x((e,t)=>HEAP_DATA_VIEW.setFloat64(e,t,!0),"LE_HEAP_STORE_F64"),LE_HEAP_STORE_I16=x((e,t)=>HEAP_DATA_VIEW.setInt16(e,t,!0),"LE_HEAP_STORE_I16"),LE_HEAP_STORE_I32=x((e,t)=>HEAP_DATA_VIEW.setInt32(e,t,!0),"LE_HEAP_STORE_I32"),LE_HEAP_STORE_I64=x((e,t)=>HEAP_DATA_VIEW.setBigInt64(e,t,!0),"LE_HEAP_STORE_I64"),LE_HEAP_STORE_U32=x((e,t)=>HEAP_DATA_VIEW.setUint32(e,t,!0),"LE_HEAP_STORE_U32"),callRuntimeCallbacks=x((e)=>{while(e.length>0)e.shift()(Module)},"callRuntimeCallbacks"),onPostRuns=[],addOnPostRun=x((e)=>onPostRuns.push(e),"addOnPostRun"),onPreRuns=[],addOnPreRun=x((e)=>onPreRuns.push(e),"addOnPreRun"),UTF8Decoder=typeof TextDecoder<"u"?new TextDecoder:void 0,findStringEnd=x((e,t,n,r)=>{var s=t+n;if(r)return s;while(e[t]&&!(t>=s))++t;return t},"findStringEnd"),UTF8ArrayToString=x((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 c=e[t++]&63;if((a&224)==192){o+=String.fromCharCode((a&31)<<6|c);continue}var l=e[t++]&63;if((a&240)==224)a=(a&15)<<12|c<<6|l;else a=(a&7)<<18|c<<12|l<<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=x((e)=>{var t=0,n=0;function r(){return e[t++]}x(r,"getU8");function s(){var q=0,K=1;while(!0){var ge=e[t++];if(q+=(ge&127)*K,K*=128,!(ge&128))break}return q}x(s,"getLEB");function o(){var q=s();return t+=q,UTF8ArrayToString(e,t-q,q)}x(o,"getString");function a(){var q=s(),K=[];while(q--)K.push(o());return K}x(a,"getStringList");function c(q,K){if(q)throw Error(K)}if(x(c,"failIf"),e instanceof WebAssembly.Module){var l=WebAssembly.Module.customSections(e,"dylink.0");c(l.length===0,"need dylink section"),e=new Uint8Array(l[0]),n=e.length}else{var u=new Uint32Array(new Uint8Array(e.subarray(0,24)).buffer),d=u[0]==1836278016||u[0]==6386541;c(!d,"need to see wasm magic number"),c(e[8]!==0,"need the dylink section to be first"),t=9;var f=s();n=t+f;var p=o();c(p!=="dylink.0")}var h={neededDynlibs:[],tlsExports:new Set,weakImports:new Set,runtimePaths:[]},_=1,v=2,y=3,b=4,S=5,O=256,I=3,g=1;while(t<n){var R=r(),P=s();if(R===_)h.memorySize=s(),h.memoryAlign=s(),h.tableSize=s(),h.tableAlign=s();else if(R===v)h.neededDynlibs=a();else if(R===y){var M=s();while(M--){var C=o(),N=s();if(N&O)h.tlsExports.add(C)}}else if(R===b){var M=s();while(M--){var H=o(),C=o(),N=s();if((N&I)==g)h.weakImports.add(C)}}else if(R===S)h.runtimePaths=a();else t+=P}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}`)}}x(getValue,"getValue");var newDSO=x((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=x((e,t)=>Math.ceil(e/t)*t,"alignMemory"),getMemory=x((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=x((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=x((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=x((e)=>uleb128EncodeWithLen(Array.from(e,(t)=>{var n=wasmTypeCodes[t];return n})),"generateTypePack"),convertJsFunctionToWasm=x((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=x((e)=>{var t=wasmTableMirror[e];if(!t)wasmTableMirror[e]=t=wasmTable.get(e);return t},"getWasmTableEntry"),updateTableMap=x((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=x((e)=>{if(!functionsInTableMap)functionsInTableMap=new WeakMap,updateTableMap(0,wasmTable.length);return functionsInTableMap.get(e)||0},"getFunctionAddress"),freeTableIndexes=[],getEmptyTableSlot=x(()=>{if(freeTableIndexes.length)return freeTableIndexes.pop();return wasmTable.grow(1)},"getEmptyTableSlot"),setWasmTableEntry=x((e,t)=>{wasmTable.set(e,t),wasmTableMirror[e]=wasmTable.get(e)},"setWasmTableEntry"),addFunction=x((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=x((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=x((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=x((e)=>{var t=wasmImports[e];if(!t||t.stub)return!1;return!0},"isSymbolDefined"),dynCall=x((e,t,n=[],r=!1)=>{var s=getWasmTableEntry(t),o=s(...n);function a(c){return c}return x(a,"convert"),a(o)},"dynCall"),stackSave=x(()=>_emscripten_stack_get_current(),"stackSave"),stackRestore=x((e)=>__emscripten_stack_restore(e),"stackRestore"),createInvokeFunction=x((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=x((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=x((e)=>onPostCtors.push(e),"addOnPostCtor"),UTF8ToString=x((e,t,n)=>e?UTF8ArrayToString(HEAPU8,e,t,n):"","UTF8ToString"),loadWebAssemblyModule=x((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}x(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(x(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)}x(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(x(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(x(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=x((e,t)=>{for(var[n,r]of Object.entries(e)){let s=x((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=x(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 l=LE_HEAP_LOAD_U32((r+28>>2)*4),u=LE_HEAP_LOAD_U32((r+32>>2)*4);if(l&&u){var d=HEAP8.slice(l,l+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)}x(o,"loadLibData");function a(){if(t.loadAsync)return o().then((l)=>loadWebAssemblyModule(l,t,e,n,r));return loadWebAssemblyModule(o(),t,e,n,r)}x(a,"getExports");function c(l){if(s.global)mergeLibSymbols(l,e);else if(n)Object.assign(n,l);s.exports=l}if(x(c,"moduleLoaded"),t.loadAsync)return a().then((l)=>(c(l),!0));return c(a()),!0}x(loadDynamicLibrary,"loadDynamicLibrary");var reportUndefinedSymbols=x(()=>{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=x((e)=>{if(runDependencies--,Module.monitorRunDependencies?.(runDependencies),runDependencies==0){if(dependenciesFulfilled){var t=dependenciesFulfilled;dependenciesFulfilled=null,t()}}},"removeRunDependency"),addRunDependency=x((e)=>{runDependencies++,Module.monitorRunDependencies?.(runDependencies)},"addRunDependency"),loadDylibs=x(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}`)}}x(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=x(()=>abort(""),"__abort_js");__abort_js.sig="v";var getHeapMax=x(()=>2147483648,"getHeapMax"),growMemory=x((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=x((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=x((e)=>52,"_fd_close");_fd_close.sig="ii";var INT53_MAX=9007199254740992,INT53_MIN=-9007199254740992,bigintToI53Checked=x((e)=>e<INT53_MIN||e>INT53_MAX?NaN:Number(e),"bigintToI53Checked");function _fd_seek(e,t,n,r){return t=bigintToI53Checked(t),70}x(_fd_seek,"_fd_seek"),_fd_seek.sig="iijip";var printCharBuffers=[null,[],[]],printChar=x((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=x((e,t,n,r)=>{var s=0;for(var o=0;o<n;o++){var a=LE_HEAP_LOAD_U32((t>>2)*4),c=LE_HEAP_LOAD_U32((t+4>>2)*4);t+=8;for(var l=0;l<c;l++)printChar(e,HEAPU8[a+l]);s+=c}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)}}x(_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")}x(_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}x(_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}x(_tree_sitter_query_progress_callback,"_tree_sitter_query_progress_callback");var runtimeKeepaliveCounter=0,keepRuntimeAlive=x(()=>noExitRuntime||runtimeKeepaliveCounter>0,"keepRuntimeAlive"),_proc_exit=x((e)=>{if(EXITSTATUS=e,!keepRuntimeAlive())Module.onExit?.(e),ABORT=!0;quit_(e,new ExitStatus(e))},"_proc_exit");_proc_exit.sig="vi";var exitJS=x((e,t)=>{EXITSTATUS=e,_proc_exit(e)},"exitJS"),handleException=x((e)=>{if(e instanceof ExitStatus||e=="unwind")return EXITSTATUS;quit_(1,e)},"handleException"),lengthBytesUTF8=x((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=x((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 c=e.codePointAt(a);if(c<=127){if(n>=o)break;t[n++]=c}else if(c<=2047){if(n+1>=o)break;t[n++]=192|c>>6,t[n++]=128|c&63}else if(c<=65535){if(n+2>=o)break;t[n++]=224|c>>12,t[n++]=128|c>>6&63,t[n++]=128|c&63}else{if(n+3>=o)break;t[n++]=240|c>>18,t[n++]=128|c>>12&63,t[n++]=128|c>>6&63,t[n++]=128|c&63,a++}}return t[n]=0,n-s},"stringToUTF8Array"),stringToUTF8=x((e,t,n)=>stringToUTF8Array(e,HEAPU8,t,n),"stringToUTF8"),stackAlloc=x((e)=>__emscripten_stack_alloc(e),"stackAlloc"),stringToUTF8OnStack=x((e)=>{var t=lengthBytesUTF8(e)+1,n=stackAlloc(t);return stringToUTF8(e,n,t),n},"stringToUTF8OnStack"),AsciiToString=x((e)=>{var t="";while(!0){var n=HEAPU8[e++];if(!n)return t;t+=String.fromCharCode(n)}},"AsciiToString"),stringToUTF16=x((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}x(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}x(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)}}x(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(x(t,"doRun"),Module.setStatus)Module.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>Module.setStatus(""),1),t()},1);else t()}x(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 Dp(e){return Np??=await aR(e)}function Lp(){return!!Np}function jp(e,t,n,r){if(e.length!==3)throw Error(`Wrong number of arguments to \`#${n}\` predicate. Expected 2, got ${e.length-1}`);if(!Ip(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(Ip(e[2])){let a=e[1].name,c=e[2].name;r[t].push((l)=>{let u=[],d=[];for(let p of l){if(p.name===a)u.push(p.node);if(p.name===c)d.push(p.node)}let f=x((p,h,_)=>_?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,c=e[2].value,l=x((d)=>d.text===c,"matches"),u=x((d)=>d.text!==c,"doesNotMatch");r[t].push((d)=>{let f=[];for(let h of d)if(h.name===a)f.push(h.node);let p=s?l:u;return o?f.every(p):f.some(p)})}}function Up(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,c=new RegExp(e[2].value);r[t].push((l)=>{let u=[];for(let f of l)if(f.name===a)u.push(f.node.text);let d=x((f,p)=>p?c.test(f):!c.test(f),"test");if(u.length===0)return!s;return o?u.every((f)=>d(f,s)):u.some((f)=>d(f,s))})}function Bp(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(gl))throw Error(`Arguments to \`#${n}\` predicate must be strings.".`);let c=a.map((l)=>l.value);r[t].push((l)=>{let u=[];for(let d of l)if(d.name===o)u.push(d.node.text);if(u.length===0)return!s;return u.every((d)=>c.includes(d))===s})}function qp(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(gl))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 Hp(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(gl))throw Error('Arguments to `#set!` predicate must be strings.".');if(!n[t])n[t]={};n[t][e[1].value]=e[2]?.value??null}function Kp(e,t,n,r,s,o,a,c,l,u,d){if(t===cR){let f=r[n];o.push({type:"capture",name:f})}else if(t===lR)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?":jp(o,e,f,a);break;case"any-not-match?":case"not-match?":case"any-match?":case"match?":Up(o,e,f,a);break;case"not-any-of?":case"any-of?":Bp(o,e,f,a);break;case"is?":case"is-not?":qp(o,e,f,u,d);break;case"set!":Hp(o,e,l);break;default:c[e].push({operator:f,operands:o.slice(1)})}o.length=0}}var tR,x=(e,t)=>tR(e,"name",{value:t,configurable:!0}),_M,Cp=2,Y=4,ll,bt,ln,Hi,yt,qn,m,nR,rR,iR,sR,oR,hl,aR,Np=null,V,ul,dl,ml,cR=1,lR=2,uR,wM,Ip,gl,Xt,Bi,_l;var Wp=We(()=>{tR=Object.defineProperty,_M=class{static{x(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}},ll=4*Y,bt=5*Y,ln=2*Y,Hi=2*Y+2*ln,yt={row:0,column:0},qn=Symbol("INTERNAL");x(Hr,"assertInternal");x(qi,"isPoint");x(Op,"setModule");nR=class{static{x(this,"LookaheadIterator")}[0]=0;language;constructor(e,t,n){Hr(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:x(()=>{if(m._ts_lookahead_iterator_next(this[0]))return{done:!1,value:this.currentType};return{done:!0,value:""}},"next")}}};x(pl,"getText");rR=class e{static{x(this,"Tree")}[0]=0;textCallback;language;constructor(t,n,r,s){Hr(t),this[0]=n,this.language=r,this.textCallback=s}copy(){let t=m._ts_tree_copy(this[0]);return new e(qn,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]),Ie(this)}rootNodeWithOffset(t,n){let r=V+bt;return m.setValue(r,t,"i32"),Nt(r+Y,n),m._ts_tree_root_node_with_offset_wasm(this[0]),Ie(this)}edit(t){Mp(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]=Co(o),o+=Hi;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]=Co(s),s+=Hi;m._free(n)}return r}},iR=class e{static{x(this,"TreeCursor")}[0]=0;[1]=0;[2]=0;[3]=0;tree;constructor(t,n){Hr(t),this.tree=n,Ot(this)}copy(){let t=new e(qn,this.tree);return m._ts_tree_cursor_copy_wasm(this.tree[0]),Ot(t),t}delete(){ve(this),m._ts_tree_cursor_delete_wasm(this.tree[0]),this[0]=this[1]=this[2]=0}get currentNode(){return ve(this),m._ts_tree_cursor_current_node_wasm(this.tree[0]),Ie(this.tree)}get currentFieldId(){return ve(this),m._ts_tree_cursor_current_field_id_wasm(this.tree[0])}get currentFieldName(){return this.tree.language.fields[this.currentFieldId]}get currentDepth(){return ve(this),m._ts_tree_cursor_current_depth_wasm(this.tree[0])}get currentDescendantIndex(){return ve(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 ve(this),m._ts_tree_cursor_current_node_type_id_wasm(this.tree[0])}get nodeStateId(){return ve(this),m._ts_tree_cursor_current_node_state_id_wasm(this.tree[0])}get nodeId(){return ve(this),m._ts_tree_cursor_current_node_id_wasm(this.tree[0])}get nodeIsNamed(){return ve(this),m._ts_tree_cursor_current_node_is_named_wasm(this.tree[0])===1}get nodeIsMissing(){return ve(this),m._ts_tree_cursor_current_node_is_missing_wasm(this.tree[0])===1}get nodeText(){ve(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=dr(V);return pl(this.tree,t,n,r)}get startPosition(){return ve(this),m._ts_tree_cursor_start_position_wasm(this.tree[0]),dr(V)}get endPosition(){return ve(this),m._ts_tree_cursor_end_position_wasm(this.tree[0]),dr(V)}get startIndex(){return ve(this),m._ts_tree_cursor_start_index_wasm(this.tree[0])}get endIndex(){return ve(this),m._ts_tree_cursor_end_index_wasm(this.tree[0])}gotoFirstChild(){ve(this);let t=m._ts_tree_cursor_goto_first_child_wasm(this.tree[0]);return Ot(this),t===1}gotoLastChild(){ve(this);let t=m._ts_tree_cursor_goto_last_child_wasm(this.tree[0]);return Ot(this),t===1}gotoParent(){ve(this);let t=m._ts_tree_cursor_goto_parent_wasm(this.tree[0]);return Ot(this),t===1}gotoNextSibling(){ve(this);let t=m._ts_tree_cursor_goto_next_sibling_wasm(this.tree[0]);return Ot(this),t===1}gotoPreviousSibling(){ve(this);let t=m._ts_tree_cursor_goto_previous_sibling_wasm(this.tree[0]);return Ot(this),t===1}gotoDescendant(t){ve(this),m._ts_tree_cursor_goto_descendant_wasm(this.tree[0],t),Ot(this)}gotoFirstChildForIndex(t){ve(this),m.setValue(V+ll,t,"i32");let n=m._ts_tree_cursor_goto_first_child_for_index_wasm(this.tree[0]);return Ot(this),n===1}gotoFirstChildForPosition(t){ve(this),Nt(V+ll,t);let n=m._ts_tree_cursor_goto_first_child_for_position_wasm(this.tree[0]);return Ot(this),n===1}reset(t){ce(t),ve(this,V+bt),m._ts_tree_cursor_reset_wasm(this.tree[0]),Ot(this)}resetTo(t){ve(this,V),ve(t,V+ll),m._ts_tree_cursor_reset_to_wasm(this.tree[0],t.tree[0]),Ot(this)}},sR=class{static{x(this,"Node")}[0]=0;_children;_namedChildren;constructor(e,{id:t,tree:n,startIndex:r,startPosition:s,other:o}){Hr(e),this[0]=o,this.id=t,this.tree=n,this.startIndex=r,this.startPosition=s}id;startIndex;startPosition;tree;get typeId(){return ce(this),m._ts_node_symbol_wasm(this.tree[0])}get grammarId(){return ce(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 ce(this),m._ts_node_is_named_wasm(this.tree[0])===1}get isExtra(){return ce(this),m._ts_node_is_extra_wasm(this.tree[0])===1}get isError(){return ce(this),m._ts_node_is_error_wasm(this.tree[0])===1}get isMissing(){return ce(this),m._ts_node_is_missing_wasm(this.tree[0])===1}get hasChanges(){return ce(this),m._ts_node_has_changes_wasm(this.tree[0])===1}get hasError(){return ce(this),m._ts_node_has_error_wasm(this.tree[0])===1}get endIndex(){return ce(this),m._ts_node_end_index_wasm(this.tree[0])}get endPosition(){return ce(this),m._ts_node_end_point_wasm(this.tree[0]),dr(V)}get text(){return pl(this.tree,this.startIndex,this.endIndex,this.startPosition)}get parseState(){return ce(this),m._ts_node_parse_state_wasm(this.tree[0])}get nextParseState(){return ce(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 ce(this),m._ts_node_child_wasm(this.tree[0],e),Ie(this.tree)}namedChild(e){return ce(this),m._ts_node_named_child_wasm(this.tree[0],e),Ie(this.tree)}childForFieldId(e){return ce(this),m._ts_node_child_by_field_id_wasm(this.tree[0],e),Ie(this.tree)}childForFieldName(e){let t=this.tree.language.fields.indexOf(e);if(t!==-1)return this.childForFieldId(t);return null}fieldNameForChild(e){ce(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){ce(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){ce(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]=Ie(this.tree,s),s+=bt;m._free(n)}return r}firstChildForIndex(e){ce(this);let t=V+bt;return m.setValue(t,e,"i32"),m._ts_node_first_child_for_byte_wasm(this.tree[0]),Ie(this.tree)}firstNamedChildForIndex(e){ce(this);let t=V+bt;return m.setValue(t,e,"i32"),m._ts_node_first_named_child_for_byte_wasm(this.tree[0]),Ie(this.tree)}get childCount(){return ce(this),m._ts_node_child_count_wasm(this.tree[0])}get namedChildCount(){return ce(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){ce(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]=Ie(this.tree,n),n+=bt;m._free(t)}}return this._children}get namedChildren(){if(!this._namedChildren){ce(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]=Ie(this.tree,n),n+=bt;m._free(t)}}return this._namedChildren}descendantsOfType(e,t=yt,n=yt){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");ce(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"),c=m.getValue(V+Y,"i32"),l=Array(a);if(a>0){let u=c;for(let d=0;d<a;d++)l[d]=Ie(this.tree,u),u+=bt}return m._free(c),m._free(o),l}get nextSibling(){return ce(this),m._ts_node_next_sibling_wasm(this.tree[0]),Ie(this.tree)}get previousSibling(){return ce(this),m._ts_node_prev_sibling_wasm(this.tree[0]),Ie(this.tree)}get nextNamedSibling(){return ce(this),m._ts_node_next_named_sibling_wasm(this.tree[0]),Ie(this.tree)}get previousNamedSibling(){return ce(this),m._ts_node_prev_named_sibling_wasm(this.tree[0]),Ie(this.tree)}get descendantCount(){return ce(this),m._ts_node_descendant_count_wasm(this.tree[0])}get parent(){return ce(this),m._ts_node_parent_wasm(this.tree[0]),Ie(this.tree)}childWithDescendant(e){return ce(this),ce(e,1),m._ts_node_child_with_descendant_wasm(this.tree[0]),Ie(this.tree)}descendantForIndex(e,t=e){if(typeof e!=="number"||typeof t!=="number")throw Error("Arguments must be numbers");ce(this);let n=V+bt;return m.setValue(n,e,"i32"),m.setValue(n+Y,t,"i32"),m._ts_node_descendant_for_index_wasm(this.tree[0]),Ie(this.tree)}namedDescendantForIndex(e,t=e){if(typeof e!=="number"||typeof t!=="number")throw Error("Arguments must be numbers");ce(this);let n=V+bt;return m.setValue(n,e,"i32"),m.setValue(n+Y,t,"i32"),m._ts_node_named_descendant_for_index_wasm(this.tree[0]),Ie(this.tree)}descendantForPosition(e,t=e){if(!qi(e)||!qi(t))throw Error("Arguments must be {row, column} objects");ce(this);let n=V+bt;return Nt(n,e),Nt(n+ln,t),m._ts_node_descendant_for_position_wasm(this.tree[0]),Ie(this.tree)}namedDescendantForPosition(e,t=e){if(!qi(e)||!qi(t))throw Error("Arguments must be {row, column} objects");ce(this);let n=V+bt;return Nt(n,e),Nt(n+ln,t),m._ts_node_named_descendant_for_position_wasm(this.tree[0]),Ie(this.tree)}walk(){return ce(this),m._ts_tree_cursor_new_wasm(this.tree[0]),new iR(qn,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(){ce(this);let e=m._ts_node_to_string_wasm(this.tree[0]),t=m.AsciiToString(e);return m._free(e),t}};x(fl,"unmarshalCaptures");x(ce,"marshalNode");x(Ie,"unmarshalNode");x(ve,"marshalTreeCursor");x(Ot,"unmarshalTreeCursor");x(Nt,"marshalPoint");x(dr,"unmarshalPoint");x(Pp,"marshalRange");x(Co,"unmarshalRange");x(Mp,"marshalEdit");x(Tp,"unmarshalLanguageMetadata");oR=/^tree_sitter_\w+$/,hl=class e{static{x(this,"Language")}[0]=0;types;fields;constructor(t,n){Hr(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 Tp(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+=Cp}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+=Cp}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 nR(qn,n,this);return null}static async load(t){let n;if(t instanceof Uint8Array)n=t;else if(globalThis.process?.versions.node){let c=await import("fs/promises");n=await c.readFile(t)}else{let c=await fetch(t);if(!c.ok){let u=await c.text();throw Error(`Language.load failed with status ${c.status}.
29
29
 
30
- ${u}`)}let l=c.clone();try{n=await WebAssembly.compileStreaming(c)}catch(u){console.error("wasm streaming compile failed:",u),console.error("falling back to ArrayBuffer instantiation"),n=new Uint8Array(await l.arrayBuffer())}}let r=await m.loadWebAssemblyModule(n,{loadAsync:!0}),s=Object.keys(r),o=s.find((c)=>e$.test(c)&&!c.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(Mn,a)}};x(Qf,"Module");t$=Qf;x(tp,"initializeBinding");x(np,"checkModule");Vc=class{static{x(this,"Parser")}[0]=0;[1]=0;logCallback=null;language=null;static async init(e){Jf(await tp(e)),z=m._ts_init(),Bc=m.getValue(z,"i32"),qc=m.getValue(z+Q,"i32")}constructor(){this.initialize()}initialize(){if(!np())throw Error("cannot construct a Parser before calling `init()`");m._ts_parser_new_wasm(),this[0]=m.getValue(z,"i32"),this[1]=m.getValue(z+Q,"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===Wc){t=e[0];let n=m._ts_language_abi_version(t);if(n<qc||Bc<n)throw Error(`Incompatible language version ${n}. Compatibility range ${qc} through ${Bc}.`);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=(c)=>e.slice(c);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,Ci);let c=s;for(let l=0;l<r;l++)Xf(c,n.includedRanges[l]),c+=Ci}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 Yx(Mn,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(z,"i32"),t=m.getValue(z+Q,"i32"),n=Array(e);if(e>0){let r=t;for(let s=0;s<e;s++)n[s]=ho(r),r+=Ci;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,BO={Zero:0,ZeroOrOne:1,ZeroOrMore:2,One:3,OneOrMore:4},zf=x((e)=>e.type==="capture","isCaptureStep"),Gc=x((e)=>e.type==="string","isStringStep"),zt={Syntax:1,NodeName:2,FieldName:3,CaptureName:4,PatternStructure:5},Ei=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{x(this,"QueryError")}static formatMessage(t,n){switch(t){case zt.NodeName:return`Bad node name '${n.word}'`;case zt.FieldName:return`Bad field name '${n.word}'`;case zt.CaptureName:return`Bad capture name @${n.word}`;case zt.PatternStructure:return`Bad pattern structure at offset ${n.suffix}`;case zt.Syntax:return`Bad syntax at offset ${n.suffix}`}}};x(rp,"parseAnyPredicate");x(ip,"parseMatchPredicate");x(sp,"parseAnyOfPredicate");x(op,"parseIsPredicate");x(ap,"parseSetDirective");x(cp,"parsePattern");zc=class{static{x(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,z,z+Q);if(!s){let b=m.getValue(z+Q,"i32"),g=m.getValue(z,"i32"),R=m.UTF8ToString(r,g).length,N=t.slice(R,R+100).split(`
32
- `)[0],I=N.match(i$)?.[0]??"";switch(m._free(r),b){case zt.Syntax:throw new Ei(zt.Syntax,{suffix:`${R}: '${N}'...`},R,0);case zt.NodeName:throw new Ei(b,{word:I},R,I.length);case zt.FieldName:throw new Ei(b,{word:I},R,I.length);case zt.CaptureName:throw new Ei(b,{word:I},R,I.length);case zt.PatternStructure:throw new Ei(b,{suffix:`${R}: '${N}'...`},R,0)}}let o=m._ts_query_string_count(s),a=m._ts_query_capture_count(s),c=m._ts_query_pattern_count(s),l=Array(a),u=Array(c),d=Array(o);for(let b=0;b<a;b++){let g=m._ts_query_capture_name_for_id(s,b,z),R=m.getValue(z,"i32");l[b]=m.UTF8ToString(g,R)}for(let b=0;b<c;b++){let g=Array(a);for(let R=0;R<a;R++){let N=m._ts_query_capture_quantifier_for_id(s,b,R);g[R]=N}u[b]=g}for(let b=0;b<o;b++){let g=m._ts_query_string_value_for_id(s,b,z),R=m.getValue(z,"i32");d[b]=m.UTF8ToString(g,R)}let f=Array(c),p=Array(c),h=Array(c),y=Array(c),v=Array(c);for(let b=0;b<c;b++){let g=m._ts_query_predicates_for_pattern(s,b,z),R=m.getValue(z,"i32");y[b]=[],v[b]=[];let N=[],I=g;for(let _=0;_<R;_++){let S=m.getValue(I,"i32");I+=Q;let O=m.getValue(I,"i32");I+=Q,cp(b,S,O,l,d,N,v,y,f,p,h)}Object.freeze(v[b]),Object.freeze(y[b]),Object.freeze(f[b]),Object.freeze(p[b]),Object.freeze(h[b])}m._free(r),this[0]=s,this.captureNames=l,this.captureQuantifiers=u,this.textPredicates=v,this.predicates=y,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??_t,r=t.endPosition??_t,s=t.startIndex??0,o=t.endIndex??0,a=t.startContainingPosition??_t,c=t.endContainingPosition??_t,l=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!==_t&&(n.row>r.row||n.row===r.row&&n.column>r.column))throw Error("`startPosition` cannot be greater than `endPosition`");if(u!==0&&l>u)throw Error("`startContainingIndex` cannot be greater than `endContainingIndex`");if(c!==_t&&(a.row>c.row||a.row===c.row&&a.column>c.column))throw Error("`startContainingPosition` cannot be greater than `endContainingPosition`");if(p)m.currentQueryProgressCallback=p;oe(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,c.row,c.column,l,u,d,f);let h=m.getValue(z,"i32"),y=m.getValue(z+Q,"i32"),v=m.getValue(z+2*Q,"i32"),b=Array(h);this.exceededMatchLimit=Boolean(v);let g=0,R=y;for(let N=0;N<h;N++){let I=m.getValue(R,"i32");R+=Q;let _=m.getValue(R,"i32");R+=Q;let S=Array(_);if(R=Hc(this,e.tree,R,I,S),this.textPredicates[I].every((O)=>O(S))){b[g]={patternIndex:I,captures:S};let O=this.setProperties[I];b[g].setProperties=O;let P=this.assertedProperties[I];b[g].assertedProperties=P;let C=this.refutedProperties[I];b[g].refutedProperties=C,g++}}return b.length=g,m._free(y),m.currentQueryProgressCallback=null,b}captures(e,t={}){let n=t.startPosition??_t,r=t.endPosition??_t,s=t.startIndex??0,o=t.endIndex??0,a=t.startContainingPosition??_t,c=t.endContainingPosition??_t,l=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!==_t&&(n.row>r.row||n.row===r.row&&n.column>r.column))throw Error("`startPosition` cannot be greater than `endPosition`");if(u!==0&&l>u)throw Error("`startContainingIndex` cannot be greater than `endContainingIndex`");if(c!==_t&&(a.row>c.row||a.row===c.row&&a.column>c.column))throw Error("`startContainingPosition` cannot be greater than `endContainingPosition`");if(p)m.currentQueryProgressCallback=p;oe(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,c.row,c.column,l,u,d,f);let h=m.getValue(z,"i32"),y=m.getValue(z+Q,"i32"),v=m.getValue(z+2*Q,"i32"),b=[];this.exceededMatchLimit=Boolean(v);let g=[],R=y;for(let N=0;N<h;N++){let I=m.getValue(R,"i32");R+=Q;let _=m.getValue(R,"i32");R+=Q;let S=m.getValue(R,"i32");if(R+=Q,g.length=_,R=Hc(this,e.tree,R,I,g),this.textPredicates[I].every((O)=>O(g))){let O=g[S],P=this.setProperties[I];O.setProperties=P;let C=this.assertedProperties[I];O.assertedProperties=C;let j=this.refutedProperties[I];O.refutedProperties=j,b.push(O)}}return m._free(y),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 up,readFileSync as s$,statSync as o$}from"fs";import{dirname as a$,join as Ii,posix as Er}from"path";function dp(e,t){let n=import.meta.dir;for(let s of[process.env.DIFFLOUPE_WASM_DIR,Ii(n,"wasm")])if(s&&up(Ii(s,t)))return Ii(s,t);let r=n;for(let s=0;s<8;s++){let o=Ii(r,"node_modules",e,t);if(up(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 Ar{parser;loaded=new Map;constructor(e){this.parser=e}static async create(){return await Vc.init({locateFile:(e)=>dp("web-tree-sitter",e)}),new Ar(new Vc)}async load(e){let t=this.loaded.get(e);if(t)return t;let[n,r]=f$[e],s=await Wc.load(dp(n,r)),o=e==="cpp",a={language:s,definitions:new zc(s,o?u$:c$),imports:new zc(s,o?d$:l$)};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=Mt(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?Xc(s,t,n):null}async parseRaw(e,t,n){let r=n??Mt(t);if(!r)return null;let{language:s,definitions:o,imports:a}=await this.load(r);this.parser.setLanguage(s);let c=this.parser.parse(e);if(!c)return null;try{let l=c.rootNode;return{language:r,lines:e.length===0?0:e.replace(/\n$/,"").split(`
33
- `).length,symbols:_$(l,e,o,r),importSpecs:S$(l,a),parseError:l.hasError}}finally{c.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 g of u.captures){let R=g.node;if(g.name==="name")d=R;else if(g.name.startsWith("definition."))f=R,p=g.name.slice(11)}if(!d||!f||!p)continue;if(w$(f,r))continue;let h=d.text,y=f.startPosition.row+1,v=`${p}:${h}:${y}`;if(o.has(v))continue;o.add(v);let b=y$(f);a.push({name:h,kind:p,line:y,exported:v$(f,r),...b?{container:b}:{},signature:x$(f,t,r)})}let c=new Set(a.filter((u)=>u.kind!=="variable").map((u)=>`${u.name}:${u.line}`)),l=a.filter((u)=>u.kind!=="variable"||!c.has(`${u.name}:${u.line}`));return l.sort((u,d)=>u.line-d.line),l}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 c=e.parent;while(c){if(g$.has(c.type)){r=c;break}c=c.parent}}if(r.type==="variable_declarator"){let c=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 fp(`${c} ${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 fp(a)}function fp(e,t=160){let n=e.replace(/\/\*[\s\S]*?\*\//g," ").split(`
30
+ ${u}`)}let l=c.clone();try{n=await WebAssembly.compileStreaming(c)}catch(u){console.error("wasm streaming compile failed:",u),console.error("falling back to ArrayBuffer instantiation"),n=new Uint8Array(await l.arrayBuffer())}}let r=await m.loadWebAssemblyModule(n,{loadAsync:!0}),s=Object.keys(r),o=s.find((c)=>oR.test(c)&&!c.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(qn,a)}};x(Fp,"Module");aR=Fp;x(Dp,"initializeBinding");x(Lp,"checkModule");ml=class{static{x(this,"Parser")}[0]=0;[1]=0;logCallback=null;language=null;static async init(e){Op(await Dp(e)),V=m._ts_init(),ul=m.getValue(V,"i32"),dl=m.getValue(V+Y,"i32")}constructor(){this.initialize()}initialize(){if(!Lp())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===hl){t=e[0];let n=m._ts_language_abi_version(t);if(n<dl||ul<n)throw Error(`Incompatible language version ${n}. Compatibility range ${dl} through ${ul}.`);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=(c)=>e.slice(c);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,Hi);let c=s;for(let l=0;l<r;l++)Pp(c,n.includedRanges[l]),c+=Hi}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 rR(qn,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]=Co(r),r+=Hi;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}},uR=/[\w-]+/g,wM={Zero:0,ZeroOrOne:1,ZeroOrMore:2,One:3,OneOrMore:4},Ip=x((e)=>e.type==="capture","isCaptureStep"),gl=x((e)=>e.type==="string","isStringStep"),Xt={Syntax:1,NodeName:2,FieldName:3,CaptureName:4,PatternStructure:5},Bi=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{x(this,"QueryError")}static formatMessage(t,n){switch(t){case Xt.NodeName:return`Bad node name '${n.word}'`;case Xt.FieldName:return`Bad field name '${n.word}'`;case Xt.CaptureName:return`Bad capture name @${n.word}`;case Xt.PatternStructure:return`Bad pattern structure at offset ${n.suffix}`;case Xt.Syntax:return`Bad syntax at offset ${n.suffix}`}}};x(jp,"parseAnyPredicate");x(Up,"parseMatchPredicate");x(Bp,"parseAnyOfPredicate");x(qp,"parseIsPredicate");x(Hp,"parseSetDirective");x(Kp,"parsePattern");_l=class{static{x(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 y=m.getValue(V+Y,"i32"),b=m.getValue(V,"i32"),S=m.UTF8ToString(r,b).length,O=t.slice(S,S+100).split(`
32
+ `)[0],I=O.match(uR)?.[0]??"";switch(m._free(r),y){case Xt.Syntax:throw new Bi(Xt.Syntax,{suffix:`${S}: '${O}'...`},S,0);case Xt.NodeName:throw new Bi(y,{word:I},S,I.length);case Xt.FieldName:throw new Bi(y,{word:I},S,I.length);case Xt.CaptureName:throw new Bi(y,{word:I},S,I.length);case Xt.PatternStructure:throw new Bi(y,{suffix:`${S}: '${O}'...`},S,0)}}let o=m._ts_query_string_count(s),a=m._ts_query_capture_count(s),c=m._ts_query_pattern_count(s),l=Array(a),u=Array(c),d=Array(o);for(let y=0;y<a;y++){let b=m._ts_query_capture_name_for_id(s,y,V),S=m.getValue(V,"i32");l[y]=m.UTF8ToString(b,S)}for(let y=0;y<c;y++){let b=Array(a);for(let S=0;S<a;S++){let O=m._ts_query_capture_quantifier_for_id(s,y,S);b[S]=O}u[y]=b}for(let y=0;y<o;y++){let b=m._ts_query_string_value_for_id(s,y,V),S=m.getValue(V,"i32");d[y]=m.UTF8ToString(b,S)}let f=Array(c),p=Array(c),h=Array(c),_=Array(c),v=Array(c);for(let y=0;y<c;y++){let b=m._ts_query_predicates_for_pattern(s,y,V),S=m.getValue(V,"i32");_[y]=[],v[y]=[];let O=[],I=b;for(let g=0;g<S;g++){let R=m.getValue(I,"i32");I+=Y;let P=m.getValue(I,"i32");I+=Y,Kp(y,R,P,l,d,O,v,_,f,p,h)}Object.freeze(v[y]),Object.freeze(_[y]),Object.freeze(f[y]),Object.freeze(p[y]),Object.freeze(h[y])}m._free(r),this[0]=s,this.captureNames=l,this.captureQuantifiers=u,this.textPredicates=v,this.predicates=_,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??yt,r=t.endPosition??yt,s=t.startIndex??0,o=t.endIndex??0,a=t.startContainingPosition??yt,c=t.endContainingPosition??yt,l=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!==yt&&(n.row>r.row||n.row===r.row&&n.column>r.column))throw Error("`startPosition` cannot be greater than `endPosition`");if(u!==0&&l>u)throw Error("`startContainingIndex` cannot be greater than `endContainingIndex`");if(c!==yt&&(a.row>c.row||a.row===c.row&&a.column>c.column))throw Error("`startContainingPosition` cannot be greater than `endContainingPosition`");if(p)m.currentQueryProgressCallback=p;ce(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,c.row,c.column,l,u,d,f);let h=m.getValue(V,"i32"),_=m.getValue(V+Y,"i32"),v=m.getValue(V+2*Y,"i32"),y=Array(h);this.exceededMatchLimit=Boolean(v);let b=0,S=_;for(let O=0;O<h;O++){let I=m.getValue(S,"i32");S+=Y;let g=m.getValue(S,"i32");S+=Y;let R=Array(g);if(S=fl(this,e.tree,S,I,R),this.textPredicates[I].every((P)=>P(R))){y[b]={patternIndex:I,captures:R};let P=this.setProperties[I];y[b].setProperties=P;let M=this.assertedProperties[I];y[b].assertedProperties=M;let C=this.refutedProperties[I];y[b].refutedProperties=C,b++}}return y.length=b,m._free(_),m.currentQueryProgressCallback=null,y}captures(e,t={}){let n=t.startPosition??yt,r=t.endPosition??yt,s=t.startIndex??0,o=t.endIndex??0,a=t.startContainingPosition??yt,c=t.endContainingPosition??yt,l=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!==yt&&(n.row>r.row||n.row===r.row&&n.column>r.column))throw Error("`startPosition` cannot be greater than `endPosition`");if(u!==0&&l>u)throw Error("`startContainingIndex` cannot be greater than `endContainingIndex`");if(c!==yt&&(a.row>c.row||a.row===c.row&&a.column>c.column))throw Error("`startContainingPosition` cannot be greater than `endContainingPosition`");if(p)m.currentQueryProgressCallback=p;ce(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,c.row,c.column,l,u,d,f);let h=m.getValue(V,"i32"),_=m.getValue(V+Y,"i32"),v=m.getValue(V+2*Y,"i32"),y=[];this.exceededMatchLimit=Boolean(v);let b=[],S=_;for(let O=0;O<h;O++){let I=m.getValue(S,"i32");S+=Y;let g=m.getValue(S,"i32");S+=Y;let R=m.getValue(S,"i32");if(S+=Y,b.length=g,S=fl(this,e.tree,S,I,b),this.textPredicates[I].every((P)=>P(b))){let P=b[R],M=this.setProperties[I];P.setProperties=M;let C=this.assertedProperties[I];P.assertedProperties=C;let N=this.refutedProperties[I];P.refutedProperties=N,y.push(P)}}return m._free(_),m.currentQueryProgressCallback=null,y}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 Vp,readFileSync as dR,statSync as fR}from"fs";import{dirname as pR,join as Ki,posix as Kr}from"path";function Gp(e,t){let n=import.meta.dir;for(let s of[process.env.DIFFLOUPE_WASM_DIR,Ki(n,"wasm")])if(s&&Vp(Ki(s,t)))return Ki(s,t);let r=n;for(let s=0;s<8;s++){let o=Ki(r,"node_modules",e,t);if(Vp(o))return o;let a=pR(r);if(a===r)break;r=a}throw Error(`Could not locate ${e}/${t} in any parent node_modules of ${n}`)}class Wr{parser;loaded=new Map;constructor(e){this.parser=e}static async create(){return await ml.init({locateFile:(e)=>Gp("web-tree-sitter",e)}),new Wr(new ml)}async load(e){let t=this.loaded.get(e);if(t)return t;let[n,r]=wR[e],s=await hl.load(Gp(n,r)),o=e==="cpp",a={language:s,definitions:new _l(s,o?gR:hR),imports:new _l(s,o?_R:mR)};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=Ft(t);if(!r)return null;let s;try{s=dR(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?yl(s,t,n):null}async parseRaw(e,t,n){let r=n??Ft(t);if(!r)return null;let{language:s,definitions:o,imports:a}=await this.load(r);this.parser.setLanguage(s);let c=this.parser.parse(e);if(!c)return null;try{let l=c.rootNode;return{language:r,lines:e.length===0?0:e.replace(/\n$/,"").split(`
33
+ `).length,symbols:SR(l,e,o,r),importSpecs:IR(l,a),parseError:l.hasError}}finally{c.delete()}}}function SR(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 b of u.captures){let S=b.node;if(b.name==="name")d=S;else if(b.name.startsWith("definition."))f=S,p=b.name.slice(11)}if(!d||!f||!p)continue;if(RR(f,r))continue;let h=d.text,_=f.startPosition.row+1,v=`${p}:${h}:${_}`;if(o.has(v))continue;o.add(v);let y=$R(f);a.push({name:h,kind:p,line:_,exported:ER(f,r),...y?{container:y}:{},signature:AR(f,t,r)})}let c=new Set(a.filter((u)=>u.kind!=="variable").map((u)=>`${u.name}:${u.line}`)),l=a.filter((u)=>u.kind!=="variable"||!c.has(`${u.name}:${u.line}`));return l.sort((u,d)=>u.line-d.line),l}function RR(e,t){if(t==="cpp")return!1;let n=e.parent;while(n){if(n.type==="object")return!0;if(vR.has(n.type))return!1;n=n.parent}return!1}function $R(e){let t=e.parent;while(t){if(yR.has(t.type)){let n=t.childForFieldName("name");if(n)return n.text}t=t.parent}return}function ER(e,t){let n=e;while(n){if(t==="cpp"){if(bR.has(n.type)&&n!==e)return!1}else{if(kR.has(n.type)&&n!==e)return!1;if(n.type==="export_statement")return!0}n=n.parent}return t==="cpp"}function AR(e,t,n){let r=e;if(n==="cpp"&&e.type==="function_declarator"){let c=e.parent;while(c){if(xR.has(c.type)){r=c;break}c=c.parent}}if(r.type==="variable_declarator"){let c=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 zp(`${c} ${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 zp(a)}function zp(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 Xc(e,t,n){let r=new Set,s=new Set,o=Er.dirname(t.replace(/\\/g,"/"));for(let a of e.importSpecs){let c=e.language==="cpp"?E$(a,o,n):k$(a,o,n);if(c)r.add(c);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 R$(e){try{return o$(e).isFile()}catch{return!1}}function Jc(e,t){let n=Er.normalize(t.replace(/\\/g,"/"));if(n===".."||n.startsWith("../")||Er.isAbsolute(n))return null;if(typeof e==="string")return R$(Ii(e,n))?n:null;return e.has(n)?n:null}function k$(e,t,n){if(!e.startsWith("."))return null;let r=Er.join(t,e);for(let s of $$){let o=Jc(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=Jc(n,Er.join(r,e));if(s)return s;let o=Er.dirname(r);if(o===r||r==="."||r==="")break;r=o}return Jc(n,e)}var c$=`
35
+ `).replace(/\s+/g," ").replace(/[{;,]\s*$/,"").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function IR(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 yl(e,t,n){let r=new Set,s=new Set,o=Kr.dirname(t.replace(/\\/g,"/"));for(let a of e.importSpecs){let c=e.language==="cpp"?MR(a,o,n):PR(a,o,n);if(c)r.add(c);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 OR(e){try{return fR(e).isFile()}catch{return!1}}function wl(e,t){let n=Kr.normalize(t.replace(/\\/g,"/"));if(n===".."||n.startsWith("../")||Kr.isAbsolute(n))return null;if(typeof e==="string")return OR(Ki(e,n))?n:null;return e.has(n)?n:null}function PR(e,t,n){if(!e.startsWith("."))return null;let r=Kr.join(t,e);for(let s of CR){let o=wl(n,`${r}${s}`);if(o)return o}return null}function MR(e,t,n){if(e.startsWith("/"))return null;let r=t;for(;;){let s=wl(n,Kr.join(r,e));if(s)return s;let o=Kr.dirname(r);if(o===r||r==="."||r==="")break;r=o}return wl(n,e)}var hR=`
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
- `,l$=`
62
+ `,mR=`
63
63
  (import_statement source: (string) @path)
64
64
  (export_statement source: (string) @path)
65
- `,u$=`
65
+ `,gR=`
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,82 +80,84 @@ ${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
+ `,_R=`
84
84
  (preproc_include path: (string_literal) @path)
85
- `,f$,p$,h$,m$,g$,b$,$$;var Yc=We(()=>{vi();lp();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"]);$$=["",".ts",".tsx",".d.ts",".js",".jsx","/index.ts","/index.tsx","/index.js"]});import{createHash as O$}from"crypto";function Jt(e,t){let n=t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim();return O$("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 er(e,t={}){let n=[`kind=${e}`];for(let[r,s]of Object.entries(t))n.push(`${r}=${P$(s)}`);return`<!-- ${mp} ${n.join(" ")} -->`}function Zc(e){return e.replace(new RegExp(`[ \\t]*${gp.source}`,"g"),"").replace(/\n{3,}/g,`
85
+ `,wR,yR,bR,vR,xR,kR,CR;var bl=We(()=>{Fi();Wp();wR={typescript:["tree-sitter-typescript","tree-sitter-typescript.wasm"],tsx:["tree-sitter-typescript","tree-sitter-tsx.wasm"],cpp:["tree-sitter-cpp","tree-sitter-cpp.wasm"]};yR=new Set(["class_declaration","abstract_class_declaration","interface_declaration","class_specifier","struct_specifier"]),bR=new Set(["compound_statement"]),vR=new Set(["class_body","interface_body","statement_block","program"]),xR=new Set(["field_declaration","declaration","function_definition","template_declaration"]);kR=new Set(["statement_block","arrow_function","function_expression"]);CR=["",".ts",".tsx",".d.ts",".js",".jsx","/index.ts","/index.tsx","/index.js"]});import{createHash as DR}from"crypto";function Yt(e,t){let n=t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim();return DR("sha1").update(`${e}\x00${n}`).digest("hex").slice(0,10)}function LR(e){return String(e).replace(/\s+/g,"_").replace(/-{2,}/g,"-").replace(/>/g,"_")}function fr(e,t={}){let n=[`kind=${e}`];for(let[r,s]of Object.entries(t))n.push(`${r}=${LR(s)}`);return`<!-- ${Yp} ${n.join(" ")} -->`}function vl(e){return e.replace(new RegExp(`[ \\t]*${Zp.source}`,"g"),"").replace(/\n{3,}/g,`
86
86
 
87
- `).trimEnd()}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 Cr(e){let t=[];for(let n of e.matchAll(gp)){let r=T$(n[1]);if(r)t.push(r)}return t}function Qc(e,t){return Cr(e).find((n)=>n.kind===t)??null}function N$(e){return Cr(e)[0]??null}function mo(e,t,n){if(t!=null&&t!=="Bot")return!1;if(n!==void 0)return Qc(e,n)!==null;return Cr(e).length>0}function _p(e){let t=new Set;for(let n of e){let r=n.body??"";if(!n.in_reply_to_id||!mo(r,n.user?.type,"reply"))continue;let s=N$(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}var mp="ai-review",gp,M$;var Pi=We(()=>{gp=new RegExp(`<!--\\s*${mp}\\s+([^>]*?)\\s*-->`,"g");M$=["summary","summary-item","inline","reply"]});import{posix as il}from"path";function Tp(e){let t=il.dirname(e);return t==="."?void 0:il.basename(t)}function J$(e){let t=il.basename(e);if(!Ip.test(t))return t;let n=t.replace(Ip,"").replace(/\.d$/,""),r=Tp(e);return z$.has(n.toLowerCase())&&r?`${r}/${n}`:n}function X$(e){return e.replace(/[._-](?:test|spec)(\.[^./]+)$/,"$1")}function Y$(e,t){let n=new Map;for(let r of e){let s=X$(r),o=n.get(s)??{path:s,label:J$(s),weight:0};o.weight+=t(r),n.set(s,o)}return[...n.values()].sort((r,s)=>s.weight-r.weight)}function Op(e){let t=Tp(e.path);if(!t||e.label.includes("/"))return e.label;let n=`${t}/${e.label}`;return n.length<=Mp?n:e.label}function Pp(e,t){let[n,r]=e;if(!n)return"Files";let s=t?Op(n):n.label;if(e.length===1)return Op(n);if(e.length===2&&r){let o=`${s}, ${r.label}`;if(o.length<=Mp)return o}return`${s} +${e.length-1}`}function Or(e,t=()=>0){let n=e.map((l)=>Y$(l.files,t)),r=n.map((l)=>Pp(l,!1)),o=((l)=>{let u=new Map;for(let d of l)u.set(d,(u.get(d)??0)+1);return u})(r),a=r.map((l,u)=>(o.get(l)??0)>1?Pp(n[u]??[],!0):l),c=new Map;return a.map((l)=>{let u=(c.get(l)??0)+1;return c.set(l,u),u===1?l:`${l} (${u})`})}var Mp=24,Ip,z$;var So=We(()=>{Ip=/\.(?: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,z$=new Set(["__init__","common","constants","helpers","index","init","lib","main","mod","shared","types","util","utils"])});function Pr(e){if(rS.some((t)=>e.includes(t)))return"skip";if(qp.test(e)||qp.test(e.split("/").pop()??""))return"docs";return"code"}var rS,qp;var Mi=We(()=>{rS=["pnpm-lock.yaml","package-lock.json","bun.lock","yarn.lock","Cargo.lock","go.sum",".min.js",".min.css",".bundle.js",".map","__snapshots__/"],qp=/\.(md|mdx|txt|rst)$|^LICENSE|^\.gitignore$|^\.gitattributes$/});function Vp(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 Gp(e){let t=e.filter((r)=>r.surface==="product"&&!r.preexisting),n=t.filter(SS).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 zp(e){let t=new Set(e);return Kp.find((n)=>t.has(n))??"product"}var Ft,Kp,Wp,SS=(e)=>e.severity==="blocker"||e.severity==="should-fix";var Eo=We(()=>{Ft={product:0,deploy:1,tooling:2},Kp=["product","deploy","tooling"],Wp={product:"Prod risk",deploy:"Deploy risk",tooling:"Main findings \u2014 tooling"}});function nt(e){if(/\.(test|spec)\.[cm]?[jt]sx?$/.test(e))return"tooling";if(Zn.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(Zn.tooling.some((t)=>new RegExp(t).test(e)))return"tooling";if(/^\./.test(e))return"tooling";if(!e.includes("/"))return"tooling";return"product"}function Jp(e,t){let n=e.length?e:t.map((r)=>r.file);return zp(n.map(nt))}function Zp(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 Ao(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 Xp,Tr,yt,Yp,Qp;var Nr=We(()=>{gt();Eo();Eo();Xp={product:"",deploy:"\uD83D\uDEA2 deploy",tooling:"\uD83D\uDD27 tooling"},Tr=["high","medium","low"],yt={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}},Yp={quick:"\u26A1 Quick fix",moderate:"\uD83D\uDD28 Some work",involved:"\uD83C\uDFD7\uFE0F Involved"};Qp={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 Mo(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 wl(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 yl(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 Li(e,t,n){return{file:e,side:"additions",kind:"file",line:0,cited:t,...n?{reason:n}:{}}}function gl(e,t,n,r,s,o){let a=wl(e,n).find((u)=>r>=u.start&&r<=u.end);if(!a)return null;let c=s!==void 0&&s>r?Math.min(s,a.end):void 0,l=yl(e,n,a,r);return{file:t,side:n,kind:"line",line:r,...c!==void 0&&c>r?{endLine:c}:{},cited:o,...l!==void 0?{text:l}:{}}}function To(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,c=o&&r!==void 0&&r>0?Math.max(n,r):void 0,l={line:a,...c!==void 0&&c!==a?{endLine:c}:{}};if(!e)return Li(t,l,"not-in-diff");if(!o)return Li(t,l,"no-line");if(e.type==="deleted")return(s.deletionsFallback?gl(e,t,"deletions",a,c,l):null)??Li(t,l,"deleted-file");let u=wl(e,"additions");if(!u.length)return Li(t,l,"no-hunks");let d=gl(e,t,"additions",a,c,l)??(s.deletionsFallback?gl(e,t,"deletions",a,c,l):null);if(d)return d;let f;for(let p of u){let h=a<p.start?p.start:p.end,y=Math.abs(h-a);if(!f||y<f.distance)f={line:h,range:p,distance:y}}if(f&&f.distance<=20){let p=yl(e,"additions",f.range,f.line);return{file:t,side:"additions",kind:"nearby",line:f.line,cited:l,...p!==void 0?{text:p}:{}}}return Li(t,l,"far-from-diff")}function kh(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 Eh(e,t,n,r={}){if(!e||!n)return t;let s=new RegExp(`(?<![\\w$])${Rh(n)}(?![\\w$])`);if(t.kind!=="file"&&t.text!==void 0&&s.test(t.text))return t;let o=Rh(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("|")),c=e.type==="deleted"?["deletions"]:r.deletionsFallback?["additions","deletions"]:["additions"],l=t.cited.line;for(let u of c){let d=[];for(let y of wl(e,u))for(let v=y.start;v<=y.end;v++){let b=yl(e,u,y,v);if(b===void 0||!s.test(b))continue;d.push({line:v,text:b,definition:a.test(b),distance:l>0?Math.abs(v-l):v})}if(!d.length)continue;let f=(y,v)=>y.distance-v.distance,h=(l>0?d.filter((y)=>y.distance<=zS).sort(f)[0]:void 0)??d.filter((y)=>y.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 zS=3,Rh=(e)=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function jr(e){return e.replace(/-\d+$/,"")}function Ah(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:jr(t.id)}))}function Ch(e){let t=new Map,n;for(let r of e.split(`
88
- `)){let s=r.match(/^\+\+\+ (?:b\/(.+)|\/dev\/null)$/);if(s){if(n=s[1]?[]:void 0,s[1]&&n)t.set(s[1],n);continue}let o=r.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(o&&n)n.push({oldStart:Number(o[1]),oldCount:o[2]===void 0?1:Number(o[2]),newStart:Number(o[3]),newCount:o[4]===void 0?1:Number(o[4])})}return t}function Ih(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 QK,Fw,Hu,Lw,jw,AA,eW,tW;var Uw=We(()=>{QK=(()=>{try{return!0}catch{return!1}})(),Fw=/(?=^From [a-f0-9]+ .+$)/m,Hu=/(?=^diff --git)/gm,Lw=/^(---|\+\+\+)\s+([^\t\r\n]+)/,jw=/^index ([0-9a-f]+)\.\.([0-9a-f]+)(?: (\d+))?$/i,AA={hunkLineCount:50,lineHeight:20,diffHeaderHeight:44,spacing:8},eW={...AA,hunkLineCount:1},tW=Object.freeze({fromStart:0,fromEnd:0})});function xs(e,t){return e-(t===0?0:1)}function Ku(e,t){return xs(e,t)+t}var Bw=()=>{};function Wu(e,...t){return`ck1:${JSON.stringify([e,...t])}`}var qw=()=>{};function Vu(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 Hw=()=>{};function Kw(){if(ci.length!==1024)ci=new Uint8Array(1024)}function Be(e){if(e.length===0)return e;if(OA.test(e))return JSON.parse(JSON.stringify(e));let t=e.length*3;if(ci.length<t)ci=new Uint8Array(t);let{written:n}=CA.encodeInto(e,ci);return IA.decode(ci.subarray(0,n))}var CA,IA,OA,ci;var Ww=We(()=>{CA=new TextEncoder,IA=new TextDecoder("utf-8",{ignoreBOM:!0}),OA=/[\uD800-\uDFFF]/,ci=new Uint8Array(1024)});function Vw(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=MA[e[n+1]];if(s!=null){t+=s,n+=2;continue}let o=[];do{let a=TA(e,n+1);if(a==null)return;o.push(a),n+=4}while(e[n]==="\\"&&e[n+1]>="0"&&e[n+1]<="7");t+=PA.decode(new Uint8Array(o))}}function TA(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 PA,MA;var Gw=We(()=>{PA=new TextDecoder("utf-8",{ignoreBOM:!0}),MA={'"':'"',"\\":"\\",a:"\x07",b:"\b",t:"\t",n:`
89
- `,v:"\v",f:"\f",r:"\r"}});function Jw(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=NA(e,r);if(s!=null)t.hunkContent.splice(n,1,...s),n+=s.length-1}}function NA(e,t){let{deletions:n,additions:r,deletionLineIndex:s,additionLineIndex:o}=t,a=Math.min(n,r),c=Math.abs(r-n);if(a===0||c===0||a*(c+1)>4096)return null;let l=[];for(let v=0;v<n;v++)l.push(zw(e.deletionLines[s+v]??""));let u=[];for(let v=0;v<r;v++)u.push(zw(e.additionLines[o+v]??""));let d=r>n,f=0,p=-1;for(let v=0;v<=c;v++){let b=0;for(let g=0;g<a;g++)b+=FA(l[g+(d?0:v)],u[g+(d?v:0)]);if(v===0)p=b+a*0.5;else if(b>p)p=b,f=v}if(f===0)return null;let h=[],y=(v,b,g,R)=>{if(v>0||b>0)h.push({type:"change",deletions:v,additions:b,deletionLineIndex:g,additionLineIndex:R})};if(d)y(0,f,s,o),y(a,a,s,o+f),y(0,r-a-f,s+a,o+f+a);else y(f,0,s,o),y(a,a,s+f,o),y(n-a-f,0,s+f+a,o+a);return h}function zw(e){return e.replace(DA,"")}function FA(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 DA;var Xw=We(()=>{DA=/\s+/g});function jA(e,t,n=!1,r){let s=zA(e),o=s?qA(e):HA(e),a,c=[];for(let l of o){if(s&&!Hu.test(l)){if(a==null)a=Be(l);else if(n)throw Error("parsePatchContent: unknown file blob");else console.error("parsePatchContent: unknown file blob:",l);continue}else if(!s&&!KA(l)){if(a==null)a=Be(l);else if(n)throw Error("parsePatchContent: unknown file blob");else console.error("parsePatchContent: unknown file blob:",l);continue}let u=UA(l,{cacheKey:t!=null?r==null?Wu("patch-file",t,String(c.length)):Wu("patch-file",t,String(r),String(c.length)):void 0,isGitDiff:s,throwOnError:n});if(u!=null)c.push(u)}return{patchMetadata:a,files:c}}function UA(e,{cacheKey:t,isGitDiff:n=Hu.test(e),oldFile:r,newFile:s,throwOnError:o=!1}={}){let a=0,c=iy(e,"@@ "),l,u=r==null||s==null,d=0,f=0;for(let p of c){let h=ty(p),y=h[0];if(y==null){if(o)throw Error("parsePatchContent: invalid hunk");else console.error("parsePatchContent: invalid hunk",p);continue}let v=ry(y),b=0,g=0;if(v==null||l==null){if(l!=null){if(o)throw Error("parsePatchContent: Invalid hunk");else console.error("parsePatchContent: Invalid hunk",p);continue}if(l={name:"",type:"change",hunks:[],splitLineCount:0,unifiedLineCount:0,isPartial:u,additionLines:!u&&r!=null&&s!=null?Yw(s.contents):[],deletionLines:!u&&r!=null&&s!=null?Yw(r.contents):[],cacheKey:ey(t)},l.additionLines.length===1&&s?.contents==="")l.additionLines.length=0;if(l.deletionLines.length===1&&r?.contents==="")l.deletionLines.length=0;for(let C of h){if(C.startsWith("diff --git")){let H=C.trim().match(LA);if(H==null){if(o)throw Error("parsePatchContent: invalid git diff header");else console.error("parsePatchContent: invalid git diff header",C);continue}let U=$s(H[1],!0),q=$s(H[2],!0);if(l.name=Be(q),U!==q)l.prevName=Be(U);continue}let j=C.startsWith("---")||C.startsWith("+++")?C.match(Lw):null;if(j!=null){let[,H,U]=j,q=$s(U,n);if(H==="---"&&q!=="/dev/null"){let Ee=Be(q);l.prevName=Ee,l.name=Ee}else if(H==="+++"&&q!=="/dev/null")l.name=Be(q)}else if(n){if(C.startsWith("new mode "))l.mode=Be(C.slice(8).trim());if(C.startsWith("old mode "))l.prevMode=Be(C.slice(8).trim());if(C.startsWith("new file mode"))l.type="new",l.mode=Be(C.slice(13).trim());if(C.startsWith("deleted file mode"))l.type="deleted",l.mode=Be(C.slice(17).trim());if(C.startsWith("similarity index"))if(C.startsWith("similarity index 100%"))l.type="rename-pure";else l.type="rename-changed";if(C.startsWith("index ")){let[,H,U,q]=C.trim().match(jw)??[];if(H!=null)l.prevObjectId=Be(H);if(U!=null)l.newObjectId=Be(U);if(q!=null)l.mode=Be(q)}if(C.startsWith("rename from ")||C.startsWith("copy from "))l.prevName=Be($s(C.slice(C.startsWith("rename")?12:10)));if(C.startsWith("rename to ")||C.startsWith("copy to "))l.name=Be($s(C.slice(C.startsWith("rename")?10:8)))}}continue}let R,N;while(h.length>0&&(h[h.length-1]===`
87
+ `).trimEnd()}function Qp(e){let t=e.indexOf(Io),n=e.lastIndexOf(Vi);if(t<0||n<t)return e;return`${e.slice(0,t).trimEnd()}
88
+
89
+ ${e.slice(n+Vi.length).trimStart()}`.trim()}function UR(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(!jR.includes(n))return null;return delete t.kind,{kind:n,fields:t}}function Vr(e){let t=[];for(let n of e.matchAll(Zp)){let r=UR(n[1]);if(r)t.push(r)}return t}function xl(e,t){return Vr(e).find((n)=>n.kind===t)??null}function BR(e){return Vr(e)[0]??null}function Oo(e,t,n){if(t!=null&&t!=="Bot")return!1;if(n!==void 0)return xl(e,n)!==null;return Vr(e).length>0}function eh(e){let t=new Set;for(let n of e){let r=n.body??"";if(!n.in_reply_to_id||!Oo(r,n.user?.type,"reply"))continue;let s=BR(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}var Yp="ai-review",Zp,Io="<!-- ai-review-copy -->",Vi="<!-- /ai-review-copy -->",jR;var Gi=We(()=>{Zp=new RegExp(`<!--\\s*${Yp}\\s+([^>]*?)\\s*-->`,"g");jR=["summary","summary-item","inline","reply"]});import{posix as Cl}from"path";function _h(e){let t=Cl.dirname(e);return t==="."?void 0:Cl.basename(t)}function t$(e){let t=Cl.basename(e);if(!ph.test(t))return t;let n=t.replace(ph,"").replace(/\.d$/,""),r=_h(e);return e$.has(n.toLowerCase())&&r?`${r}/${n}`:n}function n$(e){return e.replace(/[._-](?:test|spec)(\.[^./]+)$/,"$1")}function r$(e,t){let n=new Map;for(let r of e){let s=n$(r),o=n.get(s)??{path:s,label:t$(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=_h(e.path);if(!t||e.label.includes("/"))return e.label;let n=`${t}/${e.label}`;return n.length<=gh?n:e.label}function mh(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<=gh)return o}return`${s} +${e.length-1}`}function zr(e,t=()=>0){let n=e.map((l)=>r$(l.files,t)),r=n.map((l)=>mh(l,!1)),o=((l)=>{let u=new Map;for(let d of l)u.set(d,(u.get(d)??0)+1);return u})(r),a=r.map((l,u)=>(o.get(l)??0)>1?mh(n[u]??[],!0):l),c=new Map;return a.map((l)=>{let u=(c.get(l)??0)+1;return c.set(l,u),u===1?l:`${l} (${u})`})}var gh=24,ph,e$;var Uo=We(()=>{ph=/\.(?: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,e$=new Set(["__init__","common","constants","helpers","index","init","lib","main","mod","shared","types","util","utils"])});function Jr(e){if(l$.some((t)=>e.includes(t)))return"skip";if($h.test(e)||$h.test(e.split("/").pop()??""))return"docs";return"code"}var l$,$h;var zi=We(()=>{l$=["pnpm-lock.yaml","package-lock.json","bun.lock","yarn.lock","Cargo.lock","go.sum",".min.js",".min.css",".bundle.js",".map","__snapshots__/"],$h=/\.(md|mdx|txt|rst)$|^LICENSE|^\.gitignore$|^\.gitattributes$/});function Ch(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 Ih(e){let t=e.filter((r)=>r.surface==="product"&&!r.preexisting),n=t.filter(I$).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 Oh(e){let t=new Set(e);return Eh.find((n)=>t.has(n))??"product"}var jt,Eh,Ah,I$=(e)=>e.severity==="blocker"||e.severity==="should-fix";var Ho=We(()=>{jt={product:0,deploy:1,tooling:2},Eh=["product","deploy","tooling"],Ah={product:"Prod risk",deploy:"Deploy risk",tooling:"Main findings \u2014 tooling"}});function it(e){if(/\.(test|spec)\.[cm]?[jt]sx?$/.test(e))return"tooling";if(ur.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(ur.tooling.some((t)=>new RegExp(t).test(e)))return"tooling";if(/^\./.test(e))return"tooling";if(!e.includes("/"))return"tooling";return"product"}function Ph(e,t){let n=e.length?e:t.map((r)=>r.file);return Oh(n.map(it))}function Fh(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 Ko(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 Mh,Yr,vt,Th,Nh;var Zr=We(()=>{wt();Ho();Ho();Mh={product:"",deploy:"\uD83D\uDEA2 deploy",tooling:"\uD83D\uDD27 tooling"},Yr=["high","medium","low"],vt={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}},Th={quick:"\u26A1 Quick fix",moderate:"\uD83D\uDD28 Some work",involved:"\uD83C\uDFD7\uFE0F Involved"};Nh={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 Jo(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 Hl(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 Kl(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 Zi(e,t,n){return{file:e,side:"additions",kind:"file",line:0,cited:t,...n?{reason:n}:{}}}function ql(e,t,n,r,s,o){let a=Hl(e,n).find((u)=>r>=u.start&&r<=u.end);if(!a)return null;let c=s!==void 0&&s>r?Math.min(s,a.end):void 0,l=Kl(e,n,a,r);return{file:t,side:n,kind:"line",line:r,...c!==void 0&&c>r?{endLine:c}:{},cited:o,...l!==void 0?{text:l}:{}}}function Xo(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,c=o&&r!==void 0&&r>0?Math.max(n,r):void 0,l={line:a,...c!==void 0&&c!==a?{endLine:c}:{}};if(!e)return Zi(t,l,"not-in-diff");if(!o)return Zi(t,l,"no-line");if(e.type==="deleted")return(s.deletionsFallback?ql(e,t,"deletions",a,c,l):null)??Zi(t,l,"deleted-file");let u=Hl(e,"additions");if(!u.length)return Zi(t,l,"no-hunks");let d=ql(e,t,"additions",a,c,l)??(s.deletionsFallback?ql(e,t,"deletions",a,c,l):null);if(d)return d;let f;for(let p of u){let h=a<p.start?p.start:p.end,_=Math.abs(h-a);if(!f||_<f.distance)f={line:h,range:p,distance:_}}if(f&&f.distance<=20){let p=Kl(e,"additions",f.range,f.line);return{file:t,side:"additions",kind:"nearby",line:f.line,cited:l,...p!==void 0?{text:p}:{}}}return Zi(t,l,"far-from-diff")}function um(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 dm(e,t,n,r={}){if(!e||!n)return t;let s=new RegExp(`(?<![\\w$])${lm(n)}(?![\\w$])`);if(t.kind!=="file"&&t.text!==void 0&&s.test(t.text))return t;let o=lm(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("|")),c=e.type==="deleted"?["deletions"]:r.deletionsFallback?["additions","deletions"]:["additions"],l=t.cited.line;for(let u of c){let d=[];for(let _ of Hl(e,u))for(let v=_.start;v<=_.end;v++){let y=Kl(e,u,_,v);if(y===void 0||!s.test(y))continue;d.push({line:v,text:y,definition:a.test(y),distance:l>0?Math.abs(v-l):v})}if(!d.length)continue;let f=(_,v)=>_.distance-v.distance,h=(l>0?d.filter((_)=>_.distance<=z$).sort(f)[0]:void 0)??d.filter((_)=>_.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 z$=3,lm=(e)=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function Ta(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:hn(t.input_tokens),output:hn(t.output_tokens),reasoning:hn(t.reasoning_tokens),cacheRead:hn(t.cache_read_input_tokens),cacheWrite:hn(t.cache_creation_input_tokens),...typeof n==="object"&&n!==null?{firstStep:{input:hn(n.input_tokens),cacheRead:hn(n.cache_read_input_tokens),cacheWrite:hn(n.cache_creation_input_tokens)}}:{}}}function dd(e){if(typeof e!=="object"||e===null)return;let t=e;if(t.cached===!0)return;let n=Ta(t.usage),r=hn(t.costUsd);if(!n&&r===0)return;return{costUsd:r,wallMs:hn(t.wallMs),...n?{usage:n}:{}}}function pd(e){let t=dd(e?.merge),n=dd(e?.walk),r=dd(e?.intentDraft);if(!t&&!n&&!r)return;return{...t?{coordinator:t}:{},...n?{walkthrough:n}:{},...r?{intent:r}:{}}}function Lw(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,c)=>{if(a.usage)return a;let l=r[c];if(!l||l.unit!==a.unit||l.part!==a.part)return a;let u=Ta(l.usage);return u?{...a,usage:u}:a}),o=e.meta.stages??pd(n);return{...e,meta:{...e.meta,slices:s,...o?{stages:o}:{}}}}function jw(e){return e.meta.slices.some((t)=>t.usage)||Object.values(e.meta.stages??{}).some((t)=>t?.usage)}function Na(e){let t=e.input+e.cacheRead+e.cacheWrite;return t>0?e.cacheRead/t:null}function Nw(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 Is(e,t=Fa()){for(let n of e.meta.slices){if(!n.usage)continue;Nw(t,n.usage);let r=n.usage.firstStep?Na(n.usage.firstStep):null;if(r!==null)t.firstStepShares.push(r)}for(let n of Object.values(e.meta.stages??{}))if(n?.usage)Nw(t,n.usage);return t}function rC(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 Os(e){if(!e.calls)return;let t=Na(e),n=rC(e.firstStepShares),r=e.input+e.cacheRead+e.cacheWrite;return`${fd(r)} prompt${t===null?"":` (${Dw(t)} from cache)`}, ${fd(e.output)} output`+(e.reasoning?`, ${fd(e.reasoning)} reasoning`:"")+(n===null?"":`; first requests ${Dw(n)} from cache (median of ${e.firstStepShares.length})`)}var hn=(e)=>typeof e==="number"&&Number.isFinite(e)?e:0,Fa=()=>({input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,calls:0,firstStepShares:[]}),fd=(e)=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1000?`${Math.round(e/1000)}K`:String(e),Dw=(e)=>`${Math.round(e*100)}%`;function In(e){return e.replace(/-\d+$/,"")}function Qw(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:In(t.id)}))}function ey(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 l=a[1]??r;if(n=l?[]:void 0,l&&n)t.set(l,n);continue}let c=s.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(c&&n)n.push({oldStart:Number(c[1]),oldCount:c[2]===void 0?1:Number(c[2]),newStart:Number(c[3]),newCount:c[4]===void 0?1:Number(c[4])})}return t}function ty(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 B2,Uy,Od,By,qy,XC,q2,H2;var Hy=We(()=>{B2=(()=>{try{return!0}catch{return!1}})(),Uy=/(?=^From [a-f0-9]+ .+$)/m,Od=/(?=^diff --git)/gm,By=/^(---|\+\+\+)\s+([^\t\r\n]+)/,qy=/^index ([0-9a-f]+)\.\.([0-9a-f]+)(?: (\d+))?$/i,XC={hunkLineCount:50,lineHeight:20,diffHeaderHeight:44,spacing:8},q2={...XC,hunkLineCount:1},H2=Object.freeze({fromStart:0,fromEnd:0})});function Us(e,t){return e-(t===0?0:1)}function Pd(e,t){return Us(e,t)+t}var Ky=()=>{};function Md(e,...t){return`ck1:${JSON.stringify([e,...t])}`}var Wy=()=>{};function Td(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 Vy=()=>{};function Gy(){if($i.length!==1024)$i=new Uint8Array(1024)}function He(e){if(e.length===0)return e;if(QC.test(e))return JSON.parse(JSON.stringify(e));let t=e.length*3;if($i.length<t)$i=new Uint8Array(t);let{written:n}=YC.encodeInto(e,$i);return ZC.decode($i.subarray(0,n))}var YC,ZC,QC,$i;var zy=We(()=>{YC=new TextEncoder,ZC=new TextDecoder("utf-8",{ignoreBOM:!0}),QC=/[\uD800-\uDFFF]/,$i=new Uint8Array(1024)});function Jy(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=tI[e[n+1]];if(s!=null){t+=s,n+=2;continue}let o=[];do{let a=nI(e,n+1);if(a==null)return;o.push(a),n+=4}while(e[n]==="\\"&&e[n+1]>="0"&&e[n+1]<="7");t+=eI.decode(new Uint8Array(o))}}function nI(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 eI,tI;var Xy=We(()=>{eI=new TextDecoder("utf-8",{ignoreBOM:!0}),tI={'"':'"',"\\":"\\",a:"\x07",b:"\b",t:"\t",n:`
91
+ `,v:"\v",f:"\f",r:"\r"}});function Zy(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=rI(e,r);if(s!=null)t.hunkContent.splice(n,1,...s),n+=s.length-1}}function rI(e,t){let{deletions:n,additions:r,deletionLineIndex:s,additionLineIndex:o}=t,a=Math.min(n,r),c=Math.abs(r-n);if(a===0||c===0||a*(c+1)>4096)return null;let l=[];for(let v=0;v<n;v++)l.push(Yy(e.deletionLines[s+v]??""));let u=[];for(let v=0;v<r;v++)u.push(Yy(e.additionLines[o+v]??""));let d=r>n,f=0,p=-1;for(let v=0;v<=c;v++){let y=0;for(let b=0;b<a;b++)y+=sI(l[b+(d?0:v)],u[b+(d?v:0)]);if(v===0)p=y+a*0.5;else if(y>p)p=y,f=v}if(f===0)return null;let h=[],_=(v,y,b,S)=>{if(v>0||y>0)h.push({type:"change",deletions:v,additions:y,deletionLineIndex:b,additionLineIndex:S})};if(d)_(0,f,s,o),_(a,a,s,o+f),_(0,r-a-f,s+a,o+f+a);else _(f,0,s,o),_(a,a,s+f,o),_(n-a-f,0,s+f+a,o+a);return h}function Yy(e){return e.replace(iI,"")}function sI(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 iI;var Qy=We(()=>{iI=/\s+/g});function aI(e,t,n=!1,r){let s=gI(e),o=s?uI(e):dI(e),a,c=[];for(let l of o){if(s&&!Od.test(l)){if(a==null)a=He(l);else if(n)throw Error("parsePatchContent: unknown file blob");else console.error("parsePatchContent: unknown file blob:",l);continue}else if(!s&&!fI(l)){if(a==null)a=He(l);else if(n)throw Error("parsePatchContent: unknown file blob");else console.error("parsePatchContent: unknown file blob:",l);continue}let u=cI(l,{cacheKey:t!=null?r==null?Md("patch-file",t,String(c.length)):Md("patch-file",t,String(r),String(c.length)):void 0,isGitDiff:s,throwOnError:n});if(u!=null)c.push(u)}return{patchMetadata:a,files:c}}function cI(e,{cacheKey:t,isGitDiff:n=Od.test(e),oldFile:r,newFile:s,throwOnError:o=!1}={}){let a=0,c=ab(e,"@@ "),l,u=r==null||s==null,d=0,f=0;for(let p of c){let h=ib(p),_=h[0];if(_==null){if(o)throw Error("parsePatchContent: invalid hunk");else console.error("parsePatchContent: invalid hunk",p);continue}let v=ob(_),y=0,b=0;if(v==null||l==null){if(l!=null){if(o)throw Error("parsePatchContent: Invalid hunk");else console.error("parsePatchContent: Invalid hunk",p);continue}if(l={name:"",type:"change",hunks:[],splitLineCount:0,unifiedLineCount:0,isPartial:u,additionLines:!u&&r!=null&&s!=null?eb(s.contents):[],deletionLines:!u&&r!=null&&s!=null?eb(r.contents):[],cacheKey:rb(t)},l.additionLines.length===1&&s?.contents==="")l.additionLines.length=0;if(l.deletionLines.length===1&&r?.contents==="")l.deletionLines.length=0;for(let C of h){if(C.startsWith("diff --git")){let H=C.trim().match(oI);if(H==null){if(o)throw Error("parsePatchContent: invalid git diff header");else console.error("parsePatchContent: invalid git diff header",C);continue}let q=Bs(H[1],!0),K=Bs(H[2],!0);if(l.name=He(K),q!==K)l.prevName=He(q);continue}let N=C.startsWith("---")||C.startsWith("+++")?C.match(By):null;if(N!=null){let[,H,q]=N,K=Bs(q,n);if(H==="---"&&K!=="/dev/null"){let ge=He(K);l.prevName=ge,l.name=ge}else if(H==="+++"&&K!=="/dev/null")l.name=He(K)}else if(n){if(C.startsWith("new mode "))l.mode=He(C.slice(8).trim());if(C.startsWith("old mode "))l.prevMode=He(C.slice(8).trim());if(C.startsWith("new file mode"))l.type="new",l.mode=He(C.slice(13).trim());if(C.startsWith("deleted file mode"))l.type="deleted",l.mode=He(C.slice(17).trim());if(C.startsWith("similarity index"))if(C.startsWith("similarity index 100%"))l.type="rename-pure";else l.type="rename-changed";if(C.startsWith("index ")){let[,H,q,K]=C.trim().match(qy)??[];if(H!=null)l.prevObjectId=He(H);if(q!=null)l.newObjectId=He(q);if(K!=null)l.mode=He(K)}if(C.startsWith("rename from ")||C.startsWith("copy from "))l.prevName=He(Bs(C.slice(C.startsWith("rename")?12:10)));if(C.startsWith("rename to ")||C.startsWith("copy to "))l.name=He(Bs(C.slice(C.startsWith("rename")?10:8)))}}continue}let S,O;while(h.length>0&&(h[h.length-1]===`
90
92
  `||h[h.length-1]==="\r"||h[h.length-1]===`\r
91
- `||h[h.length-1]===""))h.pop();let{additionStart:I,deletionStart:_}=v;d=u?d:_-1,f=u?f:I-1;let S={collapsedBefore:0,splitLineCount:0,splitLineStart:0,unifiedLineCount:0,unifiedLineStart:0,additionCount:v.additionCount,additionStart:I,additionLines:b,deletionCount:v.deletionCount,deletionStart:_,deletionLines:g,deletionLineIndex:d,additionLineIndex:f,hunkContent:[],hunkContext:ey(v.hunkContext),hunkSpecs:Be(y),noEOFCRAdditions:!1,noEOFCRDeletions:!1},O=0,P=0;for(let C=1;C<h.length;C++){let j=h[C];if(O>=S.additionCount&&P>=S.deletionCount&&!j.startsWith("\\")){if(!(WA(j)&&!VA(j)))break;if(o)throw Error("parsePatchContent: hunk has more lines than expected")}let H=j[0];if(H!=="+"&&H!=="-"&&H!==" "&&H!=="\\"){if(o)throw Error("parsePatchContent: invalid hunk line");console.error(`parseLineType: Invalid firstChar: "${H}", full line: "${j}"`),console.error("processFile: invalid rawLine:",j);continue}let U=JA(H);if(U==="addition"){if(o&&O>=S.additionCount)throw Error("parsePatchContent: hunk has too many addition lines");let q=Gu(j);if(R==null||R.type!=="change")R=zu("change",d,f),S.hunkContent.push(R);if(f++,O++,u)l.additionLines.push(q);R.additions++,b++,N="addition"}else if(U==="deletion"){if(o&&P>=S.deletionCount)throw Error("parsePatchContent: hunk has too many deletion lines");let q=Gu(j);if(R==null||R.type!=="change")R=zu("change",d,f),S.hunkContent.push(R);if(d++,P++,u)l.deletionLines.push(q);R.deletions++,g++,N="deletion"}else if(U==="context"){if(o&&(P>=S.deletionCount||O>=S.additionCount))throw Error("parsePatchContent: hunk has too many context lines");let q=Gu(j);if(R==null||R.type!=="context")R=zu("context",d,f),S.hunkContent.push(R);if(f++,d++,O++,P++,u)l.deletionLines.push(q),l.additionLines.push(q);R.lines++,N="context"}else if(U==="metadata"&&R!=null){if(R.type==="context")S.noEOFCRAdditions=!0,S.noEOFCRDeletions=!0;else if(N==="deletion")S.noEOFCRDeletions=!0;else if(N==="addition")S.noEOFCRAdditions=!0;if(u&&(N==="addition"||N==="context")){let q=l.additionLines.length-1;if(q>=0)l.additionLines[q]=Vu(l.additionLines[q])}if(u&&(N==="deletion"||N==="context")){let q=l.deletionLines.length-1;if(q>=0)l.deletionLines[q]=Vu(l.deletionLines[q])}}}if(O!==S.additionCount||P!==S.deletionCount){if(o)throw Error("parsePatchContent: hunk line count mismatch");console.error(`parsePatchContent: hunk line count mismatch: "${y.trimEnd()}", declared old/new ${S.deletionCount}/${S.additionCount}, parsed old/new ${P}/${O}`);let C=xs(S.additionStart,S.additionCount)+(O===0?0:1),j=xs(S.deletionStart,S.deletionCount)+(P===0?0:1);if(!u){let H=C-S.additionStart,U=j-S.deletionStart;S.additionLineIndex+=H,S.deletionLineIndex+=U;for(let q of S.hunkContent)q.additionLineIndex+=H,q.deletionLineIndex+=U}S.additionStart=C,S.deletionStart=j,S.additionCount=O,S.deletionCount=P}S.additionLines=b,S.deletionLines=g,S.collapsedBefore=Math.max(xs(S.additionStart,S.additionCount)-a,0),l.hunks.push(S),a=Ku(S.additionStart,S.additionCount);for(let C of S.hunkContent)if(C.type==="context")S.splitLineCount+=C.lines,S.unifiedLineCount+=C.lines;else S.splitLineCount+=Math.max(C.additions,C.deletions),S.unifiedLineCount+=C.deletions+C.additions;S.splitLineStart=l.splitLineCount+S.collapsedBefore,S.unifiedLineStart=l.unifiedLineCount+S.collapsedBefore,l.splitLineCount+=S.collapsedBefore+S.splitLineCount,l.unifiedLineCount+=S.collapsedBefore+S.unifiedLineCount}if(l==null)return;if(o&&u&&!n&&l.hunks.length===0)throw Error("parsePatchContent: unified file has no hunks");if(l.hunks.length>0&&!u&&l.additionLines.length>0&&l.deletionLines.length>0){let p=l.hunks[l.hunks.length-1],h=Ku(p.additionStart,p.additionCount),y=l.additionLines.length,v=Math.max(y-h,0);l.splitLineCount+=v,l.unifiedLineCount+=v}if(!n){if(l.prevName!=null&&l.name!==l.prevName)if(l.hunks.length>0)l.type="rename-changed";else l.type="rename-pure";else if((r==null||r.contents==="")&&s!=null&&s.contents!=="")l.type="new";else if(r!=null&&r.contents!==""&&(s==null||s.contents===""))l.type="deleted"}if(l.type!=="rename-pure"&&l.type!=="rename-changed")l.prevName=void 0;return Jw(l),l}function Xu(e,t,n=!1){let r=[],s=BA(e)?e.split(Fw):[e];for(let o of s)try{r.push(jA(o,t,n,t!=null?r.length:void 0))}catch(a){if(n)throw a;else console.error(a)}finally{Kw()}return r}function $s(e,t=!1){let n=e.trim(),r=n.startsWith('"')?Vw(n)?.fileName??n:n;return t&&(r.startsWith("a/")||r.startsWith("b/"))?r.slice(2):r}function BA(e){return e.startsWith("From ")||e.includes(`
92
- From `)}function Yw(e){let t=ty(e);for(let n=0;n<t.length;n++)t[n]=Be(t[n]);return t}function ty(e){if(e.length===0)return[""];let t=[],n=0;for(;;){let r=e.indexOf(`
93
- `,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 qA(e){return iy(e,"diff --git")}function HA(e){if(e.length===0)return[""];let t=[],n=0,r=0,s=0,o=0,a=!1;while(r<e.length){let c=Ju(e,r);if(s<=0&&o<=0){if(ny(e,r)){if(r>n)t.push(e.slice(n,r));n=r,a=!0,r=Ju(e,c);continue}if(a&&e.startsWith("@@ -",r)){let u=ry(e.slice(r,c));if(u!=null)s=u.deletionCount,o=u.additionCount}r=c;continue}let l=e[r];if(l==="\\"){r=c;continue}if(l===" ")s=Math.max(s-1,0),o=Math.max(o-1,0);else if(l==="-")s=Math.max(s-1,0);else if(l==="+")o=Math.max(o-1,0);r=c}return t.push(e.slice(n)),t}function KA(e){return ny(e,0)}function ny(e,t){let n=Ju(e,t);return Zw(e,t,"---")&&Zw(e,n,"+++")}function Zw(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===`
94
- `||o==="\r")break;if(o!==" "&&o!=="\t")return!0}return!1}function Ju(e,t){let n=e.indexOf(`
95
- `,t);return n===-1?e.length:n+1}function WA(e){let t=e[0];return t==="+"||t==="-"||t===" "}function VA(e){if(!e.startsWith("--"))return!1;for(let t=2;t<e.length;t++){let n=e[t];if(n!==" "&&n!=="\t"&&n!==`
96
- `&&n!=="\r")return!1}return!0}function ry(e){if(!e.startsWith("@@ -"))return;let t=4,n=$a(e,t);if(n==null)return;let r=n.value;t=n.endIndex;let s=1;if(e[t]===","){let d=$a(e,t+1);if(d==null)return;s=d.value,t=d.endIndex}if(e[t]!==" "||e[t+1]!=="+")return;t+=2;let o=$a(e,t);if(o==null)return;let a=o.value;t=o.endIndex;let c=1;if(e[t]===","){let d=$a(e,t+1);if(d==null)return;c=d.value,t=d.endIndex}if(e[t]!==" "||e[t+1]!=="@"||e[t+2]!=="@")return;let l,u=t+3;if(e[u]===" ")l=GA(e.slice(u+1));return{additionCount:c,additionStart:a,deletionCount:s,deletionStart:r,hunkContext:l}}function $a(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 GA(e){if(e.endsWith(`\r
93
+ `||h[h.length-1]===""))h.pop();let{additionStart:I,deletionStart:g}=v;d=u?d:g-1,f=u?f:I-1;let R={collapsedBefore:0,splitLineCount:0,splitLineStart:0,unifiedLineCount:0,unifiedLineStart:0,additionCount:v.additionCount,additionStart:I,additionLines:y,deletionCount:v.deletionCount,deletionStart:g,deletionLines:b,deletionLineIndex:d,additionLineIndex:f,hunkContent:[],hunkContext:rb(v.hunkContext),hunkSpecs:He(_),noEOFCRAdditions:!1,noEOFCRDeletions:!1},P=0,M=0;for(let C=1;C<h.length;C++){let N=h[C];if(P>=R.additionCount&&M>=R.deletionCount&&!N.startsWith("\\")){if(!(pI(N)&&!hI(N)))break;if(o)throw Error("parsePatchContent: hunk has more lines than expected")}let H=N[0];if(H!=="+"&&H!=="-"&&H!==" "&&H!=="\\"){if(o)throw Error("parsePatchContent: invalid hunk line");console.error(`parseLineType: Invalid firstChar: "${H}", full line: "${N}"`),console.error("processFile: invalid rawLine:",N);continue}let q=_I(H);if(q==="addition"){if(o&&P>=R.additionCount)throw Error("parsePatchContent: hunk has too many addition lines");let K=Fd(N);if(S==null||S.type!=="change")S=Nd("change",d,f),R.hunkContent.push(S);if(f++,P++,u)l.additionLines.push(K);S.additions++,y++,O="addition"}else if(q==="deletion"){if(o&&M>=R.deletionCount)throw Error("parsePatchContent: hunk has too many deletion lines");let K=Fd(N);if(S==null||S.type!=="change")S=Nd("change",d,f),R.hunkContent.push(S);if(d++,M++,u)l.deletionLines.push(K);S.deletions++,b++,O="deletion"}else if(q==="context"){if(o&&(M>=R.deletionCount||P>=R.additionCount))throw Error("parsePatchContent: hunk has too many context lines");let K=Fd(N);if(S==null||S.type!=="context")S=Nd("context",d,f),R.hunkContent.push(S);if(f++,d++,P++,M++,u)l.deletionLines.push(K),l.additionLines.push(K);S.lines++,O="context"}else if(q==="metadata"&&S!=null){if(S.type==="context")R.noEOFCRAdditions=!0,R.noEOFCRDeletions=!0;else if(O==="deletion")R.noEOFCRDeletions=!0;else if(O==="addition")R.noEOFCRAdditions=!0;if(u&&(O==="addition"||O==="context")){let K=l.additionLines.length-1;if(K>=0)l.additionLines[K]=Td(l.additionLines[K])}if(u&&(O==="deletion"||O==="context")){let K=l.deletionLines.length-1;if(K>=0)l.deletionLines[K]=Td(l.deletionLines[K])}}}if(P!==R.additionCount||M!==R.deletionCount){if(o)throw Error("parsePatchContent: hunk line count mismatch");console.error(`parsePatchContent: hunk line count mismatch: "${_.trimEnd()}", declared old/new ${R.deletionCount}/${R.additionCount}, parsed old/new ${M}/${P}`);let C=Us(R.additionStart,R.additionCount)+(P===0?0:1),N=Us(R.deletionStart,R.deletionCount)+(M===0?0:1);if(!u){let H=C-R.additionStart,q=N-R.deletionStart;R.additionLineIndex+=H,R.deletionLineIndex+=q;for(let K of R.hunkContent)K.additionLineIndex+=H,K.deletionLineIndex+=q}R.additionStart=C,R.deletionStart=N,R.additionCount=P,R.deletionCount=M}R.additionLines=y,R.deletionLines=b,R.collapsedBefore=Math.max(Us(R.additionStart,R.additionCount)-a,0),l.hunks.push(R),a=Pd(R.additionStart,R.additionCount);for(let C of R.hunkContent)if(C.type==="context")R.splitLineCount+=C.lines,R.unifiedLineCount+=C.lines;else R.splitLineCount+=Math.max(C.additions,C.deletions),R.unifiedLineCount+=C.deletions+C.additions;R.splitLineStart=l.splitLineCount+R.collapsedBefore,R.unifiedLineStart=l.unifiedLineCount+R.collapsedBefore,l.splitLineCount+=R.collapsedBefore+R.splitLineCount,l.unifiedLineCount+=R.collapsedBefore+R.unifiedLineCount}if(l==null)return;if(o&&u&&!n&&l.hunks.length===0)throw Error("parsePatchContent: unified file has no hunks");if(l.hunks.length>0&&!u&&l.additionLines.length>0&&l.deletionLines.length>0){let p=l.hunks[l.hunks.length-1],h=Pd(p.additionStart,p.additionCount),_=l.additionLines.length,v=Math.max(_-h,0);l.splitLineCount+=v,l.unifiedLineCount+=v}if(!n){if(l.prevName!=null&&l.name!==l.prevName)if(l.hunks.length>0)l.type="rename-changed";else l.type="rename-pure";else if((r==null||r.contents==="")&&s!=null&&s.contents!=="")l.type="new";else if(r!=null&&r.contents!==""&&(s==null||s.contents===""))l.type="deleted"}if(l.type!=="rename-pure"&&l.type!=="rename-changed")l.prevName=void 0;return Zy(l),l}function Ld(e,t,n=!1){let r=[],s=lI(e)?e.split(Uy):[e];for(let o of s)try{r.push(aI(o,t,n,t!=null?r.length:void 0))}catch(a){if(n)throw a;else console.error(a)}finally{Gy()}return r}function Bs(e,t=!1){let n=e.trim(),r=n.startsWith('"')?Jy(n)?.fileName??n:n;return t&&(r.startsWith("a/")||r.startsWith("b/"))?r.slice(2):r}function lI(e){return e.startsWith("From ")||e.includes(`
94
+ From `)}function eb(e){let t=ib(e);for(let n=0;n<t.length;n++)t[n]=He(t[n]);return t}function ib(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 uI(e){return ab(e,"diff --git")}function dI(e){if(e.length===0)return[""];let t=[],n=0,r=0,s=0,o=0,a=!1;while(r<e.length){let c=Dd(e,r);if(s<=0&&o<=0){if(sb(e,r)){if(r>n)t.push(e.slice(n,r));n=r,a=!0,r=Dd(e,c);continue}if(a&&e.startsWith("@@ -",r)){let u=ob(e.slice(r,c));if(u!=null)s=u.deletionCount,o=u.additionCount}r=c;continue}let l=e[r];if(l==="\\"){r=c;continue}if(l===" ")s=Math.max(s-1,0),o=Math.max(o-1,0);else if(l==="-")s=Math.max(s-1,0);else if(l==="+")o=Math.max(o-1,0);r=c}return t.push(e.slice(n)),t}function fI(e){return sb(e,0)}function sb(e,t){let n=Dd(e,t);return tb(e,t,"---")&&tb(e,n,"+++")}function tb(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 Dd(e,t){let n=e.indexOf(`
97
+ `,t);return n===-1?e.length:n+1}function pI(e){let t=e[0];return t==="+"||t==="-"||t===" "}function hI(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 ob(e){if(!e.startsWith("@@ -"))return;let t=4,n=Ka(e,t);if(n==null)return;let r=n.value;t=n.endIndex;let s=1;if(e[t]===","){let d=Ka(e,t+1);if(d==null)return;s=d.value,t=d.endIndex}if(e[t]!==" "||e[t+1]!=="+")return;t+=2;let o=Ka(e,t);if(o==null)return;let a=o.value;t=o.endIndex;let c=1;if(e[t]===","){let d=Ka(e,t+1);if(d==null)return;c=d.value,t=d.endIndex}if(e[t]!==" "||e[t+1]!=="@"||e[t+2]!=="@")return;let l,u=t+3;if(e[u]===" ")l=mI(e.slice(u+1));return{additionCount:c,additionStart:a,deletionCount:s,deletionStart:r,hunkContext:l}}function Ka(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 mI(e){if(e.endsWith(`\r
97
99
  `))return e.slice(0,-2);if(e.endsWith(`
98
- `))return e.slice(0,-1);return e}function zA(e){return e.startsWith("diff --git")||e.includes(`
99
- diff --git`)}function iy(e,t){if(e.length===0)return[""];let n=`
100
- ${t}`,r=e.startsWith(t)?0:Qw(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=Qw(e,n,o+1);if(a===-1)break;s.push(e.slice(o,a)),o=a}return s.push(e.slice(o)),s}function Qw(e,t,n){let r=e.indexOf(t,n);return r===-1?-1:r+1}function ey(e){return e==null?e:Be(e)}function JA(e){return e===" "?"context":e==="\\"?"metadata":e==="+"?"addition":"deletion"}function Gu(e){let t=e.slice(1);return Be(t===""?`
101
- `:t)}function zu(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 LA;var sy=We(()=>{Uw();Bw();qw();Hw();Ww();Gw();Xw();LA=/^diff --git ("a\/(?:[^"\\]|\\.)*"|a\/.+?) ("b\/(?:[^"\\]|\\.)*"|b\/.+?)$/});var oy=We(()=>{sy()});function eC(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 cy(e){return Xu(e).flatMap((t)=>t.files)}function ly(e,t,n){let r=eC(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,c=0;for(let l of o.hunks)a+=l.additionLines,c+=l.deletionLines;return{path:o.name,...o.prevName&&o.prevName!==o.name?{previousPath:o.prevName}:{},status:QA[o.type],additions:a,deletions:c,isBinary:r.has(o.name),...o.newObjectId?{blob:o.newObjectId}:{},groupId:"",classification:s.get(o.name)??Pr(o.name),surface:nt(o.name)}})}function tC(e){let t=e.match(/^(.+?):(\d+)(?:-\d+)?$/);return t?.[1]&&t[2]?{file:t[1],line:Number(t[2])}:{file:e}}function ay(e,t,n){return{id:t,file:e.file,anchor:To(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(tC)}:{},...e.repeat_of!==void 0?{repeatOf:e.repeat_of}:{},surface:nt(e.file),...e.preexisting?{preexisting:!0}:{}}}function Ss(e){return[...new Set(e)]}function nC(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 rC(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,c=0;for(let[f,p]of o)if(p>c||p===c&&f<a)a=f,c=p;let l=(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 v=p.slice(p.lastIndexOf("/")+1),b=[...n].find(([g])=>g.endsWith(`/${v}`)||g===v);if(b)return b[1]}let y;for(let v of s){let b=nC(f,v.file);if(b>0&&(!y||b>y.depth||b===y.depth&&v.ci<y.ci))y={depth:b,ci:v.ci}}return y?.ci??a},u=new Map;for(let f of r.files){let p=l(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 iC(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,c=[],l=new Set;for(let h of t){let y=a[h.id-1];if(!y)continue;l.add(y.id),c.push({id:y.id,title:y.title,file:y.file,...h.note?{note:h.note}:{}})}let u=new Map(a.map((h)=>[jr(h.id),h.carriedFrom??o.run.id]));for(let h of n){let y=u.get(jr(h.id));if(y)h.carriedFrom=y}let d=new Set(n.map((h)=>jr(h.id))),f=new Set(o.dismissed??[]),p=[];for(let h of a){if(l.has(h.id)||f.has(h.id)||d.has(jr(h.id)))continue;let y=r.get(h.file);if(!y){s(` prior finding "${h.title}" dropped: ${h.file} is no longer in the diff`);continue}let v=o.lineMap?.get(h.file)??[],b=(g)=>g?Ih(v,g):void 0;p.push({...h,anchor:To(y,h.file,b(h.anchor.cited.line),b(h.anchor.cited.endLine)),carriedFrom:h.carriedFrom??o.run.id})}return{carried:p,resolved:c}}function Yu(e){let t=e.log??((A)=>console.error(A)),n=e.result.record,r=n?.walkthrough??null,s=cy(e.patch),o=new Map(s.map((A)=>[A.name,A])),a=ly(s,e.patch,e.result.byClass),c=new Map(a.map((A)=>[A.path,A])),l=new Map,u=(A)=>{let X=Jt(A.file,A.title),V=(l.get(X)??0)+1;return l.set(X,V),V===1?X:`${X}-${V}`},d=(n?.verifiedFindings??[]).map((A)=>ay(A,u(A),o.get(A.file))),f=(n?.overCapFindings??[]).map((A)=>ay(A,u(A),o.get(A.file))),{carried:p,resolved:h}=iC(e,n?.resolved??[],[...d,...f],o,t);d.push(...p);let y=(A)=>{let X=A.endsWith("/")?A:`${A}/`;return!o.has(A)&&s.some((V)=>V.name.startsWith(X))},v=[],b=r?.chapters??[];b.forEach((A,X)=>{(A.stops??[]).forEach((V,Ne)=>{let pt=[];for(let He of V.locations??[]){if(y(He.file)){t(` walkthrough: dropped directory location ${He.file} in "${V.title}"`);continue}let Ke=o.get(He.file),je={deletionsFallback:!0},Fs=Eh(Ke,To(Ke,He.file,He.line,void 0,je),kh(He.symbol,He.label),je);pt.push({...Fs,...He.label?{label:He.label}:{}})}v.push({id:`c${X+1}-s${Ne+1}`,chapterId:`c${X+1}`,index:Ne,title:V.title,...V.prose?{prose:V.prose}:{},importance:V.importance??"normal",locations:pt})})});let g=new Set,R=(A)=>{let X=[];for(let V of A){if(!c.has(V))continue;if(g.has(V))continue;g.add(V),X.push(V)}return X},N=new Set((r?.start_here??[]).map((A)=>A.file)),I=[...e.result.units].sort((A,X)=>(A.priority??99)-(X.priority??99)),_=new Set,S=(A)=>{let X=`u-${A.id}`;for(let Ne=2;_.has(X);Ne++)X=`u-${A.id}-${Ne}`;_.add(X);let V=A.files.filter((Ne)=>!c.has(Ne));if(V.length)t(` unit "${A.title}": ${V.length} file(s) not in the patch: ${V.join(", ")}`);return{id:X,unit:A,files:R(A.files)}},O=rC(I.map(S).filter((A)=>A.files.length),v),P=new Map(O.flatMap((A)=>A.chapter===void 0?[]:[[A.id,A.chapter]])),C=(A)=>{let X=c.get(A);return X?X.additions+X.deletions:0},j=e.kind==="diff"?Or(O,C):[],H=new Map(O.map((A,X)=>[A.id,j[X]??A.unit.title])),U=[],q=(A,X,V,Ne={})=>({id:A,title:X,files:V,findingIds:[],stopIds:[],critical:!1,...Ne}),Ee=(A,X,V={})=>q(A,X,[],V),we=(A,X)=>q(A.id,H.get(A.id)??A.unit.title,A.files,{...X?{parentId:X}:{},...A.unit.rationale?{summary:A.unit.rationale}:{}}),ce=(A)=>A.files.some((X)=>N.has(X));if(b.length){b.forEach((X,V)=>{let Ne=`c${V+1}`,pt=X.icon;U.push(Ee(Ne,X.title,{...X.blurb?{summary:X.blurb}:{},...pt&&XA.has(pt)?{icon:pt}:{},stopIds:v.filter((je)=>je.chapterId===Ne).map((je)=>je.id)}));let He=O.filter((je)=>P.get(je.id)===V),Ke=[...He.filter(ce),...He.filter((je)=>!ce(je))];for(let je of Ke)U.push(we(je,Ne))});let A=O.filter((X)=>!P.has(X.id));if(A.length){let X=Ss((r?.support??[]).map((V)=>V.reason).filter(Boolean));U.push(Ee("supporting","Supporting changes",X.length?{summary:X.join(" ")}:{}));for(let V of A)U.push(we(V,"supporting"))}}else for(let A of O)U.push(we(A));let Te=R(a.filter((A)=>A.classification==="docs").map((A)=>A.path)),qe=R(a.filter((A)=>A.classification==="skip").map((A)=>A.path)),he=R(a.map((A)=>A.path));if(he.length)t(` ${he.length} file(s) in no review unit: ${he.join(", ")}`);let K=[...he.length?[q("remaining","Remaining changes",he)]:[],...Te.length?[q("docs","Docs",Te,{icon:"doc"})]:[],...qe.length?[q("skipped","Generated and skipped",qe,{icon:"gear"})]:[]],ye=e.kind==="diff"?"Other changes":"Not reviewed in depth",[ve]=K;if(K.length===1&&ve)U.push(e.kind==="diff"?ve:{...ve,title:ye});else if(K.length){U.push(Ee("other",ye));for(let A of K)U.push({...A,parentId:"other"})}let st=new Map;for(let A of U)for(let X of A.files)st.set(X,A);for(let A of a)A.groupId=st.get(A.path)?.id??"";let Ae=new Map(v.map((A)=>[A.id,A]));for(let A of U){if(!A.files.length)continue;let X=new Set(A.files);A.findingIds=d.filter((V)=>X.has(V.file)).map((V)=>V.id),A.stopIds=v.filter((V)=>V.locations.some((Ne)=>X.has(Ne.file))).map((V)=>V.id)}let Le=new Map(d.map((A)=>[A.id,A.severity])),Qe=(A)=>A.findingIds.some((X)=>ZA.has(Le.get(X)??"question"))||A.stopIds.some((X)=>Ae.get(X)?.importance==="critical");for(let A of U)if(A.files.length)A.critical=Qe(A);for(let A of U){if(A.files.length)continue;let X=U.filter((V)=>V.parentId===A.id);A.findingIds=Ss(X.flatMap((V)=>V.findingIds)),A.critical=X.some((V)=>V.critical)||Qe(A)}let T=d.filter((A)=>!st.has(A.file));if(T.length)t(` ${T.length} finding(s) name files outside the patch`);let D=r?.intent,W=n?.intentAlignment??void 0,le=Ss([...D?.unstated??[],...W?.unstated??[]]),w=Ss([...D?.missing??[],...W?.missing??[]]),B=Ss([...W?.summary?[W.summary]:[],...D?.mismatches??[]]),de=D?.alignment==="aligned"&&W?.summary?"partial":D?.alignment,F={...e.statedIntent?{stated:e.statedIntent}:{},...D?.inferred?{inferred:D.inferred}:{},...de?{alignment:de}:{},...D?.matches?.length?{matches:D.matches}:{},...B.length?{mismatches:B}:{},...le.length?{unstated:le}:{},...w.length?{missing:w}:{}},xe=(n?.sliceRuns??[]).map((A)=>({unit:A.unit,part:A.part,parts:A.parts,status:A.ok?"ok":"failed",costUsd:A.costUsd??0,wallMs:A.wallMs??0})),pe=n?.mergeMode;return{schemaVersion:1,id:e.id,status:"complete",createdAt:e.createdAt,repo:e.repo,target:e.target,base:e.base,head:e.head,intent:F,overview:{...r?.focus?{focus:r.focus}:{},...r?.change_type?{changeType:r.change_type}:{},startHere:r?.start_here??[]},files:a,groups:U,stops:v,findings:d,overCapFindings:f,resolved:h,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:xe,rejectedCount:n?.rejected?.length??0,coreSource:e.coreSource,...pe&&YA.has(pe)?{mergeMode:pe}:{},...n?.budgetStopped?{budgetStopped:!0}:{},...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}:{}}}function uy(e,t,n){return{...Yu({...e,result:{record:null,units:t,byClass:n,costUsd:0,wallMs:0},log:()=>{}}),status:"running"}}function dy(e){let t=ly(cy(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 XA,YA,ZA,QA;var Zu=We(()=>{oy();Mi();So();Pi();Nr();XA=new Set(["bug","wrench","path","flask","doc","gear"]),YA=new Set(["coordinator","nothing-to-merge","deterministic-fallback"]),ZA=new Set(["blocker","should-fix"]),QA={new:"added",deleted:"removed",change:"modified","rename-pure":"renamed","rename-changed":"renamed"}});var yc={};cv(yc,{program:()=>rf,createCommand:()=>sf,createOption:()=>of,createArgument:()=>af,Command:()=>cf,Option:()=>lf,Argument:()=>uf,Help:()=>df,CommanderError:()=>ff,InvalidArgumentError:()=>pf,InvalidOptionArgumentError:()=>hf},{program:(VI)=>rf=VI,createCommand:(VI)=>sf=VI,createOption:(VI)=>of=VI,createArgument:(VI)=>af=VI,Command:(VI)=>cf=VI,Option:(VI)=>lf=VI,Argument:(VI)=>uf=VI,Help:(VI)=>df=VI,CommanderError:(VI)=>ff=VI,InvalidArgumentError:(VI)=>pf=VI,InvalidOptionArgumentError:(VI)=>hf=VI});var{Argument:ef}=zs(),{Command:wc}=Qd(),{CommanderError:jv,InvalidArgumentError:tf}=yi(),{Help:Uv}=pc(),{Option:nf}=hc();var rf=new wc,sf=(e)=>new wc(e),of=(e,t)=>new nf(e,t),af=(e,t)=>new ef(e,t),cf=wc,lf=nf,uf=ef,df=Uv,ff=jv,pf=tf,hf=tf;var{program:zI,createCommand:JI,createArgument:XI,createOption:YI,CommanderError:ZI,InvalidArgumentError:bi,InvalidOptionArgumentError:QI,Command:Kt,Argument:eO,Option:tO,Help:nO}=yc;var Js={name:"@acemarke/diffloupe",version:"0.3.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 Xs=Js.version;import{readdir as wC,stat as yC}from"fs/promises";import by from"path";var Es=dc(Qs(),1);import{spawn as Wv}from"child_process";function te(e,t,n={}){return new Promise((r,s)=>{let o=Wv(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,c=[],l=[];o.stdout?.on("data",(u)=>c.push(u)),o.stderr?.on("data",(u)=>l.push(u)),o.on("error",(u)=>{clearTimeout(a),s(u)}),o.on("close",(u,d)=>{clearTimeout(a);let f={stdout:Buffer.concat(c).toString("utf8"),stderr:Buffer.concat(l).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}`}
102
- `+f.stderr.slice(0,2000)));return}r(f)})})}async function se(e,t,n={}){return(await te(e,t,n)).stdout}var nn=["review","coordinator","walkthrough","intent"],Vv={review:"anthropic/claude-opus-5-5",coordinator:"anthropic/claude-opus-5-5",walkthrough:"anthropic/claude-sonnet-5-5",intent:"anthropic/claude-haiku-5-5"},eo={review:"models.review",coordinator:"models.coordinator",walkthrough:"models.walkthrough",intent:"models.intent"};var Gv={env:"REVIEW_* environment variable",cli:"--model",settings:"settings file",config:"~/.config/diffloupe/config.json",opencode:"OpenCode default model",default:"built-in default"};function to(e){return Gv[e]}function at(e){let t=e?.trim();return t?t:void 0}function zv(e){let t=at(e.REVIEW_MODEL),n=at(e.REVIEW_MODEL_MERGE)??t,r=at(e.REVIEW_MODEL_WALK),s=at(e.REVIEW_MODEL_INTENT);return{...t?{review:t}:{},...n?{coordinator:n}:{},...r?{walkthrough:r}:{},...s?{intent:s}:{}}}function Jv(e,t){let n=at(e.REVIEW_EFFORT);return t==="review"?n:at(e.REVIEW_EFFORT_AUX)??n}function Xv(e,t){let n=e.indexOf("#"),r=n===-1?e:e.slice(0,n),s=n===-1?void 0:at(e.slice(n+1)),o=r.indexOf("/"),a=o===-1?t:r.slice(0,o),c=o===-1?r:r.slice(o+1);return{provider:a,id:c,...s?{variant:s}:{}}}function vc(e){return at(e.env?.REVIEW_PROVIDER)??at(e.settings?.provider)??at(e.config?.provider)??"anthropic"}function _f(e){let t=e.env??{},n=vc(e),r=e.config?.opencode?.useDefaultModel!==!1,s=zv(t),o=r?at(e.openCodeModel):void 0,a={};for(let c of nn){let l=[["env",s[c]],["cli",e.cli?.models?.[c]],["settings",e.settings?.models?.[c]],["config",e.config?.models?.[c]]];if(c!=="intent")l.push(["opencode",o]);let u="default",d=Vv[c],f=!1;for(let[v,b]of l){let g=at(b);if(g){u=v,d=g,f=!0;break}}if(c==="intent"&&!f&&a.walkthrough.provider!=="anthropic"){a.intent={...a.walkthrough};continue}let p=Xv(d,n),h=Jv(t,c)??at(e.cli?.effort)??at(e.settings?.effort)??at(e.config?.effort)??(u==="default"?"medium":void 0),y=p.variant??h;a[c]={model:`${p.provider}/${p.id}${y?`#${y}`:""}`,provider:p.provider,id:p.id,...y?{variant:y}:{},source:u}}return a}function wf(e,t=nn){let n=new Map;for(let r of t){let s=e[r].provider;n.set(s,[...n.get(s)??[],r])}return n}import ft from"path";import{existsSync as sC}from"fs";import{copyFile as oC,readFile as hy,writeFile as Sa}from"fs/promises";import{join as yf}from"path";import{homedir as Yv}from"os";function Zv(){let e=process.env.XDG_CONFIG_HOME||yf(Yv(),".config");return yf(e,"diffloupe","config.json")}var Cn=null;async function _r(){if(Cn!==null)return Cn;let e=Bun.file(Zv());if(!await e.exists())return Cn={},Cn;try{let t=await e.text();return Cn=JSON.parse(t),Cn}catch{return Cn={},Cn}}import et from"path";import dx from"path";import{promises as wr}from"fs";import Qv from"path";async function yr(e){try{return await wr.access(e),!0}catch{return!1}}function Ct(e){return wr.readFile(e,"utf8")}async function br(e){return JSON.parse(await Ct(e))}async function Ye(e,t){await wr.mkdir(Qv.dirname(e),{recursive:!0}),await wr.writeFile(e,t,"utf8")}async function fn(e,t){await Ye(e,JSON.stringify(t,null,2))}async function Wt(e){await wr.rm(e,{force:!0})}async function pn(e){await wr.mkdir(e,{recursive:!0})}async function bf(e){try{let t=await Ct(e);if(t==="")return 0;return t.replace(/\n$/,"").split(`
103
- `).length}catch{return null}}vi();async function Sf(e,t,n){return xi(await se("git",["-C",e,"-c","diff.renames=true","diff","--unified=0",`${t}..${n}`]))}function*rn(e){let t,n=!1,r=0,s=0;for(let o of e.split(`
104
- `)){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 c=o.slice(4).trim();t=c==="/dev/null"?void 0:c.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 Rf(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 gI(e){return e.startsWith("diff --git")||e.includes(`
101
+ diff --git`)}function ab(e,t){if(e.length===0)return[""];let n=`
102
+ ${t}`,r=e.startsWith(t)?0:nb(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=nb(e,n,o+1);if(a===-1)break;s.push(e.slice(o,a)),o=a}return s.push(e.slice(o)),s}function nb(e,t,n){let r=e.indexOf(t,n);return r===-1?-1:r+1}function rb(e){return e==null?e:He(e)}function _I(e){return e===" "?"context":e==="\\"?"metadata":e==="+"?"addition":"deletion"}function Fd(e){let t=e.slice(1);return He(t===""?`
103
+ `:t)}function Nd(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 oI;var cb=We(()=>{Hy();Ky();Wy();Vy();zy();Xy();Qy();oI=/^diff --git ("a\/(?:[^"\\]|\\.)*"|a\/.+?) ("b\/(?:[^"\\]|\\.)*"|b\/.+?)$/});var lb=We(()=>{cb()});function ub(e,[t,n]){return e.some((r)=>{let s=r.oldStart+Math.max(r.oldCount,1)-1;return r.oldStart<=n&&t<=s})}function db(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,c=t.get(n.file)??[];return[{id:n.id,acted:ub(c,o),control:ub(c,[o[0]+a,o[1]+a])}]})}function xI(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 pb(e){return Ld(e).flatMap((t)=>t.files)}function hb(e,t,n){let r=xI(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,c=0;for(let l of o.hunks)a+=l.additionLines,c+=l.deletionLines;return{path:o.name,...o.prevName&&o.prevName!==o.name?{previousPath:o.prevName}:{},status:vI[o.type],additions:a,deletions:c,isBinary:r.has(o.name),...o.newObjectId?{blob:o.newObjectId}:{},groupId:"",classification:s.get(o.name)??Jr(o.name),surface:it(o.name)}})}function SI(e){let t=e.match(/^(.+?):(\d+)(?:-\d+)?$/);return t?.[1]&&t[2]?{file:t[1],line:Number(t[2])}:{file:e}}function fb(e,t,n){return{id:t,file:e.file,anchor:Xo(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(SI)}:{},...e.repeat_of!==void 0?{repeatOf:e.repeat_of}:{},surface:it(e.file),...e.preexisting?{preexisting:!0}:{}}}function qs(e){return[...new Set(e)]}function RI(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 $I(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,c=0;for(let[f,p]of o)if(p>c||p===c&&f<a)a=f,c=p;let l=(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 v=p.slice(p.lastIndexOf("/")+1),y=[...n].find(([b])=>b.endsWith(`/${v}`)||b===v);if(y)return y[1]}let _;for(let v of s){let y=RI(f,v.file);if(y>0&&(!_||y>_.depth||y===_.depth&&v.ci<_.ci))_={depth:y,ci:v.ci}}return _?.ci??a},u=new Map;for(let f of r.files){let p=l(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 kI(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,c=[],l=new Set;for(let h of t){let _=a[h.id-1];if(!_)continue;l.add(_.id),c.push({id:_.id,title:_.title,file:_.file,...h.note?{note:h.note}:{}})}let u=new Map(a.map((h)=>[In(h.id),h.carriedFrom??o.run.id]));for(let h of n){let _=u.get(In(h.id));if(_)h.carriedFrom=_}let d=new Set(n.map((h)=>In(h.id))),f=new Set(o.dismissed??[]),p=[];for(let h of a){if(l.has(h.id)||f.has(h.id)||d.has(In(h.id)))continue;let _=r.get(h.file);if(!_){s(` prior finding "${h.title}" dropped: ${h.file} is no longer in the diff`);continue}let v=o.lineMap?.get(h.file)??[],y=(b)=>b?ty(v,b):void 0;p.push({...h,anchor:Xo(_,h.file,y(h.anchor.cited.line),y(h.anchor.cited.endLine)),carriedFrom:h.carriedFrom??o.run.id})}return{carried:p,resolved:c}}function jd(e){let t=e.log??((E)=>console.error(E)),n=e.result.record,r=n?.walkthrough??null,s=pb(e.patch),o=new Map(s.map((E)=>[E.name,E])),a=hb(s,e.patch,e.result.byClass),c=new Map(a.map((E)=>[E.path,E])),l=new Map,u=(E)=>{let z=Yt(E.file,E.title),Q=(l.get(z)??0)+1;return l.set(z,Q),Q===1?z:`${z}-${Q}`},d=(n?.verifiedFindings??[]).map((E)=>fb(E,u(E),o.get(E.file))),f=(n?.overCapFindings??[]).map((E)=>fb(E,u(E),o.get(E.file))),{carried:p,resolved:h}=kI(e,n?.resolved??[],[...d,...f],o,t);d.push(...p);let _=(E)=>{let z=E.endsWith("/")?E:`${E}/`;return!o.has(E)&&s.some((Q)=>Q.name.startsWith(z))},v=[],y=r?.chapters??[];y.forEach((E,z)=>{(E.stops??[]).forEach((Q,Ze)=>{let De=[];for(let Ue of Q.locations??[]){if(_(Ue.file)){t(` walkthrough: dropped directory location ${Ue.file} in "${Q.title}"`);continue}let nr=o.get(Ue.file),Ke={deletionsFallback:!0},rr=dm(nr,Xo(nr,Ue.file,Ue.line,void 0,Ke),um(Ue.symbol,Ue.label),Ke);De.push({...rr,...Ue.label?{label:Ue.label}:{}})}v.push({id:`c${z+1}-s${Ze+1}`,chapterId:`c${z+1}`,index:Ze,title:Q.title,...Q.prose?{prose:Q.prose}:{},importance:Q.importance??"normal",locations:De})})});let b=new Set,S=(E)=>{let z=[];for(let Q of E){if(!c.has(Q))continue;if(b.has(Q))continue;b.add(Q),z.push(Q)}return z},O=new Set((r?.start_here??[]).map((E)=>E.file)),I=[...e.result.units].sort((E,z)=>(E.priority??99)-(z.priority??99)),g=new Set,R=(E)=>{let z=`u-${E.id}`;for(let Ze=2;g.has(z);Ze++)z=`u-${E.id}-${Ze}`;g.add(z);let Q=E.files.filter((Ze)=>!c.has(Ze));if(Q.length)t(` unit "${E.title}": ${Q.length} file(s) not in the patch: ${Q.join(", ")}`);return{id:z,unit:E,files:S(E.files)}},P=$I(I.map(R).filter((E)=>E.files.length),v),M=new Map(P.flatMap((E)=>E.chapter===void 0?[]:[[E.id,E.chapter]])),C=(E)=>{let z=c.get(E);return z?z.additions+z.deletions:0},N=e.kind==="diff"?zr(P,C):[],H=new Map(P.map((E,z)=>[E.id,N[z]??E.unit.title])),q=[],K=(E,z,Q,Ze={})=>({id:E,title:z,files:Q,findingIds:[],stopIds:[],critical:!1,...Ze}),ge=(E,z,Q={})=>K(E,z,[],Q),$e=(E,z)=>K(E.id,H.get(E.id)??E.unit.title,E.files,{...z?{parentId:z}:{},...E.unit.rationale?{summary:E.unit.rationale}:{}}),ie=(E)=>E.files.some((z)=>O.has(z));if(y.length){y.forEach((z,Q)=>{let Ze=`c${Q+1}`,De=z.icon;q.push(ge(Ze,z.title,{...z.blurb?{summary:z.blurb}:{},...De&&wI.has(De)?{icon:De}:{},stopIds:v.filter((Ke)=>Ke.chapterId===Ze).map((Ke)=>Ke.id)}));let Ue=P.filter((Ke)=>M.get(Ke.id)===Q),nr=[...Ue.filter(ie),...Ue.filter((Ke)=>!ie(Ke))];for(let Ke of nr)q.push($e(Ke,Ze))});let E=P.filter((z)=>!M.has(z.id));if(E.length){let z=qs((r?.support??[]).map((Q)=>Q.reason).filter(Boolean));q.push(ge("supporting","Supporting changes",z.length?{summary:z.join(" ")}:{}));for(let Q of E)q.push($e(Q,"supporting"))}}else for(let E of P)q.push($e(E));let Ne=S(a.filter((E)=>E.classification==="docs").map((E)=>E.path)),Ye=S(a.filter((E)=>E.classification==="skip").map((E)=>E.path)),Ae=S(a.map((E)=>E.path));if(Ae.length)t(` ${Ae.length} file(s) in no review unit: ${Ae.join(", ")}`);let B=[...Ae.length?[K("remaining","Remaining changes",Ae)]:[],...Ne.length?[K("docs","Docs",Ne,{icon:"doc"})]:[],...Ye.length?[K("skipped","Generated and skipped",Ye,{icon:"gear"})]:[]],Te=e.kind==="diff"?"Other changes":"Not reviewed in depth",[Pe]=B;if(B.length===1&&Pe)q.push(e.kind==="diff"?Pe:{...Pe,title:Te});else if(B.length){q.push(ge("other",Te));for(let E of B)q.push({...E,parentId:"other"})}let je=new Map;for(let E of q)for(let z of E.files)je.set(z,E);for(let E of a)E.groupId=je.get(E.path)?.id??"";let Ce=new Map(v.map((E)=>[E.id,E]));for(let E of q){if(!E.files.length)continue;let z=new Set(E.files);E.findingIds=d.filter((Q)=>z.has(Q.file)).map((Q)=>Q.id),E.stopIds=v.filter((Q)=>Q.locations.some((Ze)=>z.has(Ze.file))).map((Q)=>Q.id)}let be=new Map(d.map((E)=>[E.id,E.severity])),at=(E)=>E.findingIds.some((z)=>bI.has(be.get(z)??"question"))||E.stopIds.some((z)=>Ce.get(z)?.importance==="critical");for(let E of q)if(E.files.length)E.critical=at(E);for(let E of q){if(E.files.length)continue;let z=q.filter((Q)=>Q.parentId===E.id);E.findingIds=qs(z.flatMap((Q)=>Q.findingIds)),E.critical=z.some((Q)=>Q.critical)||at(E)}let T=d.filter((E)=>!je.has(E.file));if(T.length)t(` ${T.length} finding(s) name files outside the patch`);let L=r?.intent,Z=n?.intentAlignment??void 0,ne=qs([...L?.unstated??[],...Z?.unstated??[]]),w=qs([...L?.missing??[],...Z?.missing??[]]),D=qs([...Z?.summary?[Z.summary]:[],...L?.mismatches??[]]),de=L?.alignment==="aligned"&&Z?.summary?"partial":L?.alignment,j={...e.statedIntent?{stated:e.statedIntent}:{},...L?.inferred?{inferred:L.inferred}:{},...de?{alignment:de}:{},...L?.matches?.length?{matches:L.matches}:{},...D.length?{mismatches:D}:{},...ne.length?{unstated:ne}:{},...w.length?{missing:w}:{}},ye=(n?.sliceRuns??[]).map((E)=>{let z=Ta(E.usage);return{unit:E.unit,part:E.part,parts:E.parts,status:E.ok?"ok":"failed",costUsd:E.costUsd??0,wallMs:E.wallMs??0,...z?{usage:z}:{}}}),he=pd(e.result.record),mt=n?.mergeMode,sn=e.previous,Mt=sn?.lineMap&&sn.run.head!==e.head?db(sn.run.findings,sn.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:j,overview:{...r?.focus?{focus:r.focus}:{},...r?.change_type?{changeType:r.change_type}:{},startHere:r?.start_here??[]},files:a,groups:q,stops:v,findings:d,overCapFindings:f,resolved:h,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:ye,...he?{stages:he}:{},rejectedCount:n?.rejected?.length??0,coreSource:e.coreSource,...mt&&yI.has(mt)?{mergeMode:mt}:{},...n?.budgetStopped?{budgetStopped:!0}:{},...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}:{},...Mt?{priorActedOn:Mt}:{}}}function mb(e,t,n){return{...jd({...e,result:{record:null,units:t,byClass:n,costUsd:0,wallMs:0},log:()=>{}}),status:"running"}}function gb(e){let t=hb(pb(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 wI,yI,bI,vI;var Ud=We(()=>{lb();zi();Uo();Gi();Zr();wI=new Set(["bug","wrench","path","flask","doc","gear"]),yI=new Set(["coordinator","nothing-to-merge","deterministic-fallback"]),bI=new Set(["blocker","should-fix"]),vI={new:"added",deleted:"removed",change:"modified","rename-pure":"renamed","rename-changed":"renamed"}});var qc={};hx(qc,{program:()=>Uf,createCommand:()=>Bf,createOption:()=>qf,createArgument:()=>Hf,Command:()=>Kf,Option:()=>Wf,Argument:()=>Vf,Help:()=>Gf,CommanderError:()=>zf,InvalidArgumentError:()=>Jf,InvalidOptionArgumentError:()=>Xf},{program:(SP)=>Uf=SP,createCommand:(SP)=>Bf=SP,createOption:(SP)=>qf=SP,createArgument:(SP)=>Hf=SP,Command:(SP)=>Kf=SP,Option:(SP)=>Wf=SP,Argument:(SP)=>Vf=SP,Help:(SP)=>Gf=SP,CommanderError:(SP)=>zf=SP,InvalidArgumentError:(SP)=>Jf=SP,InvalidOptionArgumentError:(SP)=>Xf=SP});var{Argument:Df}=uo(),{Command:Bc}=Nf(),{CommanderError:Wx,InvalidArgumentError:Lf}=Ti(),{Help:Vx}=Nc(),{Option:jf}=Dc();var Uf=new Bc,Bf=(e)=>new Bc(e),qf=(e,t)=>new jf(e,t),Hf=(e,t)=>new Df(e,t),Kf=Bc,Wf=jf,Vf=Df,Gf=Vx,zf=Wx,Jf=Lf,Xf=Lf;var{program:$P,createCommand:kP,createArgument:EP,createOption:AP,CommanderError:CP,InvalidArgumentError:sr,InvalidOptionArgumentError:IP,Command:Vt,Argument:OP,Option:PP,Help:MP}=qc;var fo={name:"@acemarke/diffloupe",version:"0.4.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 Dn=fo.version;import{readdir as HI,stat as KI}from"fs/promises";import Rb from"path";var Ks=Tc(mo(),1);import{spawn as Yx}from"child_process";function re(e,t,n={}){return new Promise((r,s)=>{let o=Yx(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,c=[],l=[];o.stdout?.on("data",(u)=>c.push(u)),o.stderr?.on("data",(u)=>l.push(u)),o.on("error",(u)=>{clearTimeout(a),s(u)}),o.on("close",(u,d)=>{clearTimeout(a);let f={stdout:Buffer.concat(c).toString("utf8"),stderr:Buffer.concat(l).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 le(e,t,n={}){return(await re(e,t,n)).stdout}var on=["review","coordinator","walkthrough","intent"],Zx={review:"anthropic/claude-opus-5-5",coordinator:"anthropic/claude-opus-5-5",walkthrough:"anthropic/claude-sonnet-5-5",intent:"anthropic/claude-haiku-5-5"},go={review:"models.review",coordinator:"models.coordinator",walkthrough:"models.walkthrough",intent:"models.intent"};var Qx={env:"REVIEW_* environment variable",cli:"--model",settings:"settings file",config:"~/.config/diffloupe/config.json",opencode:"OpenCode default model",default:"built-in default"};function _o(e){return Qx[e]}function lt(e){let t=e?.trim();return t?t:void 0}function eS(e){let t=lt(e.REVIEW_MODEL),n=lt(e.REVIEW_MODEL_MERGE)??t,r=lt(e.REVIEW_MODEL_WALK),s=lt(e.REVIEW_MODEL_INTENT);return{...t?{review:t}:{},...n?{coordinator:n}:{},...r?{walkthrough:r}:{},...s?{intent:s}:{}}}function tS(e,t){let n=lt(e.REVIEW_EFFORT);return t==="review"?n:lt(e.REVIEW_EFFORT_AUX)??n}function nS(e,t){let n=e.indexOf("#"),r=n===-1?e:e.slice(0,n),s=n===-1?void 0:lt(e.slice(n+1)),o=r.indexOf("/"),a=o===-1?t:r.slice(0,o),c=o===-1?r:r.slice(o+1);return{provider:a,id:c,...s?{variant:s}:{}}}function Kc(e){return lt(e.env?.REVIEW_PROVIDER)??lt(e.settings?.provider)??lt(e.config?.provider)??"anthropic"}function Qf(e){let t=e.env??{},n=Kc(e),r=e.config?.opencode?.useDefaultModel!==!1,s=eS(t),o=r?lt(e.openCodeModel):void 0,a={};for(let c of on){let l=[["env",s[c]],["cli",e.cli?.models?.[c]],["settings",e.settings?.models?.[c]],["config",e.config?.models?.[c]]];if(c!=="intent")l.push(["opencode",o]);let u="default",d=Zx[c],f=!1;for(let[v,y]of l){let b=lt(y);if(b){u=v,d=b,f=!0;break}}if(c==="intent"&&!f&&a.walkthrough.provider!=="anthropic"){a.intent={...a.walkthrough};continue}let p=nS(d,n),h=tS(t,c)??lt(e.cli?.effort)??lt(e.settings?.effort)??lt(e.config?.effort)??(u==="default"?"medium":void 0),_=p.variant??h;a[c]={model:`${p.provider}/${p.id}${_?`#${_}`:""}`,provider:p.provider,id:p.id,..._?{variant:_}:{},source:u}}return a}function ep(e,t=on){let n=new Map;for(let r of t){let s=e[r].provider;n.set(s,[...n.get(s)??[],r])}return n}import tt from"path";import{existsSync as EI}from"fs";import{copyFile as AI,readFile as Va,writeFile as Rr}from"fs/promises";import{join as tp}from"path";import{homedir as rS}from"os";function iS(){let e=process.env.XDG_CONFIG_HOME||tp(rS(),".config");return tp(e,"diffloupe","config.json")}var Ln=null;async function Tr(){if(Ln!==null)return Ln;let e=Bun.file(iS());if(!await e.exists())return Ln={},Ln;try{let t=await e.text();return Ln=JSON.parse(t),Ln}catch{return Ln={},Ln}}import nt from"path";import _S from"path";import{promises as Fr}from"fs";import sS from"path";async function Nr(e){try{return await Fr.access(e),!0}catch{return!1}}function It(e){return Fr.readFile(e,"utf8")}async function Dr(e){return JSON.parse(await It(e))}async function et(e,t){await Fr.mkdir(sS.dirname(e),{recursive:!0}),await Fr.writeFile(e,t,"utf8")}async function mn(e,t){await et(e,JSON.stringify(t,null,2))}async function Gt(e){await Fr.rm(e,{force:!0})}async function gn(e){await Fr.mkdir(e,{recursive:!0})}async function np(e){try{let t=await It(e);if(t==="")return 0;return t.replace(/\n$/,"").split(`
105
+ `).length}catch{return null}}Fi();async function op(e,t,n){return Ni(await le("git",["-C",e,"-c","diff.renames=true","diff","--unified=0",`${t}..${n}`]))}function*an(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 c=o.slice(4).trim();t=c==="/dev/null"?void 0:c.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 ap(e){let t=[],n=0,r=0,s=0,o=0;for(let a of e.split(`
105
107
  `)){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 c=/^@@ -\d+(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(a);if(c)n=c[1]===void 0?1:Number(c[1]),s=Number(c[2]),r=c[3]===void 0?1:Number(c[3]),o=String(Math.max(s+r-1,1)).length;t.push(a)}return t.join(`
106
- `)}function kf(e){let t=new Map,n,r;for(let s of e.split(`
107
- `)){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 nx=40,rx=30,ix=/^(?: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 zn(e,t){return e.split(/^(?=diff --git )/m).map((r)=>{if(!/^\+\+\+ \/dev\/null$/m.test(r))return r;let s=r.split(`
108
- `),o=s.findIndex((d)=>d.startsWith("@@ "));if(o<0)return r;let a=s.slice(o+1).filter((d)=>d.startsWith("-"));if(a.length<=nx)return r;let c=/^--- (?:a\/)?(.+)$/m.exec(r)?.[1]??"",l=a.filter((d)=>ix.test(d.slice(1))).slice(0,rx),u=r.endsWith(`
108
+ `)}function cp(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 cS=40,lS=30,uS=/^(?: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 or(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<=cS)return r;let c=/^--- (?:a\/)?(.+)$/m.exec(r)?.[1]??"",l=a.filter((d)=>uS.test(d.slice(1))).slice(0,lS),u=r.endsWith(`
109
111
  `)?`
110
112
  `:"";return[...s.slice(0,o),...l.length?[`@@ -1,${l.length} +0,0 @@`,...l]:[],`# Deleted file, ${a.length} lines. Only its top-level declarations are shown; read the rest with \`git show ${t.slice(0,12)}:${c}\`.`].join(`
111
- `)+u}).join("")}var vf=" [rest of line cut]",sx=80,ox=36;function Ef(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,c)=>({i:c,size:a.length})).sort((a,c)=>a.size-c.size),o=t;for(let[a,{i:c,size:l}]of s.entries()){let u=Math.floor(o/(s.length-a)),d=Math.min(l,u);r.set(c,d),o-=d}return n.map((a,c)=>{if(a.length<=(r.get(c)??0))return a;let l=(r.get(c)??0)-ox,u=a.replace(/\n$/,"").split(`
112
- `),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,N)=>R+N.length+1,0),y=p.length;for(let R of u.slice(y)){if(h+R.length+1>l)break;p.push(R),h+=R.length+1,y++}let v=l-h-vf.length,b=u[y];if(b!==void 0&&v>=sx)p.push(`${b.slice(0,v)}${vf}`),y++;let g=u.length-y;if(g>0)p.push(`[${g} more lines in this file]`);return`${p.join(`
113
+ `)+u}).join("")}var rp=" [rest of line cut]",dS=80,fS=36;function lp(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,c)=>({i:c,size:a.length})).sort((a,c)=>a.size-c.size),o=t;for(let[a,{i:c,size:l}]of s.entries()){let u=Math.floor(o/(s.length-a)),d=Math.min(l,u);r.set(c,d),o-=d}return n.map((a,c)=>{if(a.length<=(r.get(c)??0))return a;let l=(r.get(c)??0)-fS,u=a.replace(/\n$/,"").split(`
114
+ `),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,O)=>S+O.length+1,0),_=p.length;for(let S of u.slice(_)){if(h+S.length+1>l)break;p.push(S),h+=S.length+1,_++}let v=l-h-rp.length,y=u[_];if(y!==void 0&&v>=dS)p.push(`${y.slice(0,v)}${rp}`),_++;let b=u.length-_;if(b>0)p.push(`[${b} more lines in this file]`);return`${p.join(`
113
115
  `)}
114
- `}).join("")}function xi(e){let t=new Map;for(let{file:n,line:r}of rn(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 ax=20,xf=(e,t)=>e.some((n)=>t>=n.start&&t<=n.end),cx=(e,t,n)=>e.some((r)=>t>=r.start&&t<=r.end&&n>=r.start&&n<=r.end);function $f(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 no(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,c=s!==void 0?Math.max(n,s):n,l=c!==a;if(l&&cx(o,a,c))return{kind:"anchorable",line:c,start_line:a};if(xf(o,c))return{kind:"anchorable",line:c};if(l&&xf(o,a))return{kind:"anchorable",line:a};let u=l&&o.find((h)=>h.start>=a&&h.end<=c);if(u)return{kind:"off-hunk",line:u.start};let d=$f(o,a),f=l?$f(o,c):d,p=!d?f:!f?d:f.distance<d.distance?f:d;if(!p||p.distance>ax)return{kind:"off-diff"};return{kind:"off-hunk",line:p.line}}gt();var fx=["node_modules/","/dist/","/build/","/.next/","/__snapshots__/",".min.js",".d.ts",".js.map","third-party/"],px=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"]),hx=(e)=>[...fx,...Ri].some((t)=>e.includes(t)),mx=new Set([".yml",".yaml",".json",".jsonc",".toml",".ini",".env",".py",".rb",".go",".rs",".java",".kt",".sh",".bash",".tf",".tfvars",".sql",".proto",".graphql",".gql"]),gx=new Set(["Dockerfile","Makefile","Procfile"]);function _x(e){if(Mt(e))return!0;let t=e.slice(e.lastIndexOf("/")+1);if(gx.has(t))return!0;let n=t.lastIndexOf(".");return n>0&&mx.has(t.slice(n))}var wx=(e)=>e.replace(/[.*+?^${}()|[\]\\-]/g,"\\$&");function yx(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 Of(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(px.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 Pf=25;function Mf(e){return e.trim().replace(/["'`][^"'`]*["'`]/g,"~").replace(/[A-Za-z_$][A-Za-z0-9_$]*/g,"X").replace(/\d+/g,"#").replace(/\s+/g,"")}function bx(e){let t=[],n=null,r=0;for(let{file:s,line:o}of rn(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 Tf(e){try{return await vx(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 vx(e){let{repo:t,base:n,head:r}=e,s=t,o=await se("git",["-C",s,"-c","diff.renames=true","diff","-U5",`${n}..${r}`]),a=bx(o),c=new Set(a.map((g)=>g.file)),l=new Map;for(let g of a)for(let R=0;R<g.lines.length;R++){let N=g.lines[R];if(N.kind!=="add")continue;let I=N.text.trim();if(I.length<8)continue;if(yx(I))continue;if(!/[,;]$/.test(I)&&!/^case\b/.test(I)&&!/:\s*\S+$/.test(I))continue;let _=Mf(N.text);if(_.length<4)continue;let S=Of(N.text);if(S.length===0)continue;let O=new Set,P=0;for(let C=Math.max(0,R-5);C<=Math.min(g.lines.length-1,R+5);C++){if(C===R)continue;let j=g.lines[C];if(j.kind!=="ctx")continue;if(Mf(j.text)!==_)continue;P++;for(let H of Of(j.text))if(!S.includes(H))O.add(H)}if(P<2||O.size<2)continue;for(let C of S){let j=`${C}@${g.file}`,H=l.get(j);if(H)for(let U of O)H.siblings.add(U);else l.set(j,{newEntry:C,file:g.file,line:N.newLine,siblings:new Set(O)})}}if(l.size===0)return{findings:[],meta:{hunks:a.length,candidates:0}};let d=(await se("git",["-C",s,"ls-files"])).trim().split(`
115
- `).filter((g)=>g&&!hx(g)&&_x(g)),f=new Set;for(let g of l.values()){f.add(g.newEntry);for(let R of g.siblings)f.add(R)}let p=new Map;for(let g of f)p.set(g,new Set);let h=new Map,y=new Map;for(let g of f){let R=/^[A-Za-z0-9_$]+$/.test(g);if(h.set(g,R),!R)y.set(g,new RegExp(`(?<![A-Za-z0-9_$-])${wx(g)}(?![A-Za-z0-9_$-])`))}let v=0;for(let g of d){let R;try{R=await Ct(dx.join(s,g))}catch{continue}if(R.length>2000000)continue;v++;let N=new Set(R.match(/[A-Za-z0-9_$]+/g)??[]);for(let I of f)if(h.get(I)?N.has(I):y.get(I).test(R))p.get(I).add(g)}let b=[];for(let g of l.values()){let R=[...g.siblings].filter((O)=>{let P=(p.get(O)??new Set).size;return P>0&&P<=Pf});if(R.length<2)continue;if((p.get(g.newEntry)??new Set).size>Pf)continue;let N=new Map;for(let O of R)for(let P of p.get(O)??[]){if(!N.has(P))N.set(P,[]);N.get(P).push(O)}let I=p.get(g.newEntry)??new Set,_=[],S=[];for(let[O,P]of N){if(P.length<2)continue;if(O===g.file)continue;if(I.has(O))S.push({file:O,siblingsPresent:P.sort()});else _.push({file:O,siblingsPresent:P.sort()})}if(_.length===0)continue;_.sort((O,P)=>P.siblingsPresent.length-O.siblingsPresent.length),S.sort((O,P)=>P.siblingsPresent.length-O.siblingsPresent.length),b.push({newEntry:g.newEntry,addedIn:g.file,addedAtLine:g.line,siblings:R.sort(),missingIn:_.slice(0,6),presentIn:S.slice(0,6)})}return b.sort((g,R)=>R.missingIn.length-g.missingIn.length),{findings:b,meta:{hunks:a.length,candidates:l.size,filesScanned:v,changedFiles:c.size}}}function Nf(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(`
116
- `)}import pp from"path";import{mkdirSync as Df,readdirSync as xx,readFileSync as $x,renameSync as Sx,rmSync as Ff,statSync as Oc,utimesSync as Rx,writeFileSync as Lf}from"fs";import On from"path";var kx=1,Pc=86400000,Ex=30;class Tc{dir;hits=0;misses=0;constructor(e){this.dir=On.join(e,`v${kx}`)}file(e,t){return On.join(this.dir,e.slice(0,2),`${e}.${t}.json`)}get(e,t){let n=this.file(e,t),r;try{r=JSON.parse($x(n,"utf8"))}catch{return this.misses++,null}this.hits++;try{if(Date.now()-Oc(n).mtimeMs>Pc){let s=new Date;Rx(n,s,s)}}catch{}return r}set(e,t,n){let r=this.file(e,t);try{Df(On.dirname(r),{recursive:!0});let s=`${r}.${process.pid}.tmp`;Lf(s,JSON.stringify(n)),Sx(s,r)}catch{}}prune(e=Date.now()){let t=On.dirname(this.dir),n=On.join(t,".last-prune");try{if(e-Oc(n).mtimeMs<Pc)return 0}catch{}try{Df(t,{recursive:!0}),Lf(n,new Date(e).toISOString())}catch{return 0}let r=0;for(let s of Mc(t)){let o=On.join(t,s);if(s.startsWith("."))continue;if(o!==this.dir){Ff(o,{recursive:!0,force:!0});continue}for(let a of Mc(o)){let c=On.join(o,a);for(let l of Mc(c)){let u=On.join(c,l);try{if(e-Oc(u).mtimeMs>Ex*Pc)Ff(u,{force:!0}),r++}catch{}}}}return r}}function Mc(e){try{return xx(e)}catch{return[]}}function jf(e,t){let n=new Set(t.split(`
116
+ `}).join("")}function Ni(e){let t=new Map;for(let{file:n,line:r}of an(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 pS=20,ip=(e,t)=>e.some((n)=>t>=n.start&&t<=n.end),hS=(e,t,n)=>e.some((r)=>t>=r.start&&t<=r.end&&n>=r.start&&n<=r.end);function sp(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,c=s!==void 0?Math.max(n,s):n,l=c!==a;if(l&&hS(o,a,c))return{kind:"anchorable",line:c,start_line:a};if(ip(o,c))return{kind:"anchorable",line:c};if(l&&ip(o,a))return{kind:"anchorable",line:a};let u=l&&o.find((h)=>h.start>=a&&h.end<=c);if(u)return{kind:"off-hunk",line:u.start};let d=sp(o,a),f=l?sp(o,c):d,p=!d?f:!f?d:f.distance<d.distance?f:d;if(!p||p.distance>pS)return{kind:"off-diff"};return{kind:"off-hunk",line:p.line}}wt();var wS=["node_modules/","/dist/","/build/","/.next/","/__snapshots__/",".min.js",".d.ts",".js.map","third-party/"],yS=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"]),bS=(e)=>[...wS,...ji].some((t)=>e.includes(t)),vS=new Set([".yml",".yaml",".json",".jsonc",".toml",".ini",".env",".py",".rb",".go",".rs",".java",".kt",".sh",".bash",".tf",".tfvars",".sql",".proto",".graphql",".gql"]),xS=new Set(["Dockerfile","Makefile","Procfile"]);function SS(e){if(Ft(e))return!0;let t=e.slice(e.lastIndexOf("/")+1);if(xS.has(t))return!0;let n=t.lastIndexOf(".");return n>0&&vS.has(t.slice(n))}var RS=(e)=>e.replace(/[.*+?^${}()|[\]\\-]/g,"\\$&");function $S(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 pp(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(yS.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 hp=25;function mp(e){return e.trim().replace(/["'`][^"'`]*["'`]/g,"~").replace(/[A-Za-z_$][A-Za-z0-9_$]*/g,"X").replace(/\d+/g,"#").replace(/\s+/g,"")}function kS(e){let t=[],n=null,r=0;for(let{file:s,line:o}of an(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 gp(e){try{return await ES(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 ES(e){let{repo:t,base:n,head:r}=e,s=t,o=await le("git",["-C",s,"-c","diff.renames=true","diff","-U5",`${n}..${r}`]),a=kS(o),c=new Set(a.map((b)=>b.file)),l=new Map;for(let b of a)for(let S=0;S<b.lines.length;S++){let O=b.lines[S];if(O.kind!=="add")continue;let I=O.text.trim();if(I.length<8)continue;if($S(I))continue;if(!/[,;]$/.test(I)&&!/^case\b/.test(I)&&!/:\s*\S+$/.test(I))continue;let g=mp(O.text);if(g.length<4)continue;let R=pp(O.text);if(R.length===0)continue;let P=new Set,M=0;for(let C=Math.max(0,S-5);C<=Math.min(b.lines.length-1,S+5);C++){if(C===S)continue;let N=b.lines[C];if(N.kind!=="ctx")continue;if(mp(N.text)!==g)continue;M++;for(let H of pp(N.text))if(!R.includes(H))P.add(H)}if(M<2||P.size<2)continue;for(let C of R){let N=`${C}@${b.file}`,H=l.get(N);if(H)for(let q of P)H.siblings.add(q);else l.set(N,{newEntry:C,file:b.file,line:O.newLine,siblings:new Set(P)})}}if(l.size===0)return{findings:[],meta:{hunks:a.length,candidates:0}};let d=(await le("git",["-C",s,"ls-files"])).trim().split(`
117
+ `).filter((b)=>b&&!bS(b)&&SS(b)),f=new Set;for(let b of l.values()){f.add(b.newEntry);for(let S of b.siblings)f.add(S)}let p=new Map;for(let b of f)p.set(b,new Set);let h=new Map,_=new Map;for(let b of f){let S=/^[A-Za-z0-9_$]+$/.test(b);if(h.set(b,S),!S)_.set(b,new RegExp(`(?<![A-Za-z0-9_$-])${RS(b)}(?![A-Za-z0-9_$-])`))}let v=0;for(let b of d){let S;try{S=await It(_S.join(s,b))}catch{continue}if(S.length>2000000)continue;v++;let O=new Set(S.match(/[A-Za-z0-9_$]+/g)??[]);for(let I of f)if(h.get(I)?O.has(I):_.get(I).test(S))p.get(I).add(b)}let y=[];for(let b of l.values()){let S=[...b.siblings].filter((P)=>{let M=(p.get(P)??new Set).size;return M>0&&M<=hp});if(S.length<2)continue;if((p.get(b.newEntry)??new Set).size>hp)continue;let O=new Map;for(let P of S)for(let M of p.get(P)??[]){if(!O.has(M))O.set(M,[]);O.get(M).push(P)}let I=p.get(b.newEntry)??new Set,g=[],R=[];for(let[P,M]of O){if(M.length<2)continue;if(P===b.file)continue;if(I.has(P))R.push({file:P,siblingsPresent:M.sort()});else g.push({file:P,siblingsPresent:M.sort()})}if(g.length===0)continue;g.sort((P,M)=>M.siblingsPresent.length-P.siblingsPresent.length),R.sort((P,M)=>M.siblingsPresent.length-P.siblingsPresent.length),y.push({newEntry:b.newEntry,addedIn:b.file,addedAtLine:b.line,siblings:S.sort(),missingIn:g.slice(0,6),presentIn:R.slice(0,6)})}return y.sort((b,S)=>S.missingIn.length-b.missingIn.length),{findings:y,meta:{hunks:a.length,candidates:l.size,filesScanned:v,changedFiles:c.size}}}function _p(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 Jp from"path";import{mkdirSync as wp,readdirSync as AS,readFileSync as CS,renameSync as IS,rmSync as yp,statSync as el,utimesSync as OS,writeFileSync as bp}from"fs";import Un from"path";var PS=1,tl=86400000,MS=30;class rl{dir;hits=0;misses=0;constructor(e){this.dir=Un.join(e,`v${PS}`)}file(e,t){return Un.join(this.dir,e.slice(0,2),`${e}.${t}.json`)}get(e,t){let n=this.file(e,t),r;try{r=JSON.parse(CS(n,"utf8"))}catch{return this.misses++,null}this.hits++;try{if(Date.now()-el(n).mtimeMs>tl){let s=new Date;OS(n,s,s)}}catch{}return r}set(e,t,n){let r=this.file(e,t);try{wp(Un.dirname(r),{recursive:!0});let s=`${r}.${process.pid}.tmp`;bp(s,JSON.stringify(n)),IS(s,r)}catch{}}prune(e=Date.now()){let t=Un.dirname(this.dir),n=Un.join(t,".last-prune");try{if(e-el(n).mtimeMs<tl)return 0}catch{}try{wp(t,{recursive:!0}),bp(n,new Date(e).toISOString())}catch{return 0}let r=0;for(let s of nl(t)){let o=Un.join(t,s);if(s.startsWith("."))continue;if(o!==this.dir){yp(o,{recursive:!0,force:!0});continue}for(let a of nl(o)){let c=Un.join(o,a);for(let l of nl(c)){let u=Un.join(c,l);try{if(e-el(u).mtimeMs>MS*tl)yp(u,{force:!0}),r++}catch{}}}}return r}}function nl(e){try{return AS(e)}catch{return[]}}function vp(e,t){let n=new Set(t.split(`
117
119
  `).map((s)=>s.trim()).filter(Boolean)),r=new Map;for(let s of e.split(`
118
- `)){let o=s.indexOf("\t");if(o<0)continue;let[a,c,l]=s.slice(0,o).split(" "),u=s.slice(o+1);if(!c||a==="160000"||l!=="0"||n.has(u))continue;r.set(u,c)}return r}vi();import{execFileSync as Ax}from"child_process";import{builtinModules as Cx}from"module";import{existsSync as Ix,readFileSync as Ox}from"fs";import{join as Px,posix as gn}from"path";function Mx(e,t){return{paths:new Set(t),read(n){let r=Px(e,n);try{return Ix(r)?Ox(r,"utf8"):void 0}catch{return}}}}function uo(e){let t=Ax("git",["-C",e,"ls-files"],{encoding:"utf8",maxBuffer:268435456});return Mx(e,t.split(`
119
- `).filter(Boolean))}var Uf=[".ts",".tsx",".d.ts",".js",".jsx",".mts",".cts",".mjs",".cjs"],Tx={".js":[".ts",".tsx"],".jsx":[".tsx"],".mjs":[".mts"],".cjs":[".cts"]},ki=/\.(?:d\.ts|tsx?|jsx?|mts|cts|mjs|cjs)$/;function sn(e,t){let n=gn.normalize(e).replace(/^\.\//,"");if(n.startsWith("../"))return;if(t.has(n))return n;let r=gn.extname(n);for(let s of Tx[r]??[]){let o=n.slice(0,-r.length)+s;if(t.has(o))return o}for(let s of Uf)if(t.has(n+s))return n+s;for(let s of Uf)if(t.has(`${n}/index${s}`))return`${n}/index${s}`;return}function Lc(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]!==`
120
- `)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 Pn(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var Nx=/(^|\/)(tsconfig[^/]*|jsconfig[^/]*)\.json$/;function _n(e){let t=gn.dirname(e);return t==="."?"":t}function ct(e,t){return gn.normalize(e?`${e}/${t}`:t).replace(/^\.\//,"").replace(/^\.$/,"")}function fo(e,t){let n=e.read(t);if(n===void 0)return;let r=Lc(n);return Pn(r)?r:void 0}function Dx(e,t,n){if(e.startsWith(".")||e.startsWith("/")){let s=ct(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 Dc(e,t,n=new Set){if(n.has(t))return{};n.add(t);let r=fo(e,t);if(!r)return{};let s=_n(t),o={},a=r.extends;for(let l of typeof a==="string"?[a]:Array.isArray(a)?a:[]){if(typeof l!=="string")continue;let u=Dx(l,s,e);if(u)o={...o,...Dc(e,u,n)}}let c=Pn(r.compilerOptions)?r.compilerOptions:{};if(typeof c.baseUrl==="string")o.baseUrl=c.baseUrl,o.baseUrlFrom=s;if(Pn(c.paths)){let l={};for(let[u,d]of Object.entries(c.paths))if(Array.isArray(d))l[u]=d.filter((f)=>typeof f==="string");o.paths=l,o.pathsFrom=s}return o}function Fx(e,t){let n=fo(e,t)?.references;if(!Array.isArray(n))return[];let r=_n(t);return n.flatMap((s)=>{if(!Pn(s)||typeof s.path!=="string")return[];let o=ct(r,s.path);return[o.endsWith(".json")?o:`${o}/tsconfig.json`]})}function Lx(e,t,n){let r=t.baseUrl!==void 0?ct(t.baseUrlFrom??e,t.baseUrl):void 0,s=[];for(let o of[t,...n]){if(!o.paths)continue;let a=o.baseUrl!==void 0?ct(o.baseUrlFrom??e,o.baseUrl):o.pathsFrom??e;for(let[c,l]of Object.entries(o.paths)){if(s.some((u)=>u.pattern===c))continue;s.push({pattern:c,targets:l.map((u)=>ct(a,u))})}}return{dir:e,...r!==void 0?{baseUrl:r}:{},paths:s}}function jx(e){let t=new Map,n=[...e.paths].filter((r)=>Nx.test(r)&&!r.includes("node_modules/"));for(let r of["tsconfig.json","jsconfig.json"])for(let s of n){if(gn.basename(s)!==r)continue;let o=_n(s);if(t.has(o))continue;let a=Dc(e,s),c=a.paths?[]:Fx(e,s).map((l)=>Dc(e,l));t.set(o,Lx(o,a,c))}return t}function qf(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 Fc(e){let t=e.indexOf("*");return t===-1?1/0:t}function Ux(e,t,n){let r;for(let s of e){let o=qf(s.pattern,t);if(o===void 0)continue;if(!r||Fc(s.pattern)>Fc(r.rule.pattern))r={rule:s,capture:o}}if(!r)return;for(let s of r.rule.targets){let o=sn(s.replace("*",r.capture),n);if(o)return o}return}var Bx=["source","development","import","module","node","require","browser","default","types"];function lo(e){if(typeof e==="string")return e;if(Array.isArray(e)){for(let t of e){let n=lo(t);if(n)return n}return}if(!Pn(e))return;for(let t of Bx)if(t in e)return lo(e[t]);for(let t of Object.values(e)){let n=lo(t);if(n)return n}return}function Hf(e,t,n,r){let s;for(let[o,a]of Object.entries(e)){let c=qf(o,t);if(c===void 0)continue;let l=lo(a);if(!l)continue;let u=Fc(o);if(!s||u>s.len)s={target:l,capture:c,len:u}}if(!s)return;return Kf(ct(n,s.target.replaceAll("*",s.capture)),n,r)}function Kf(e,t,n){let r=sn(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 c=sn(ct(t,`${a}/${o[2]}`).replace(ki,""),n);if(c)return c}return}function qx(e){let t=new Map;for(let n of e.paths){if(gn.basename(n)!=="package.json"||n.includes("node_modules/"))continue;let r=fo(e,n);if(!r)continue;let s=[r.source,r.module,r.main,r.types,r.typings].filter((o)=>typeof o==="string");t.set(_n(n),{dir:_n(n),...typeof r.name==="string"?{name:r.name}:{},...Pn(r.imports)?{imports:r.imports}:{},...r.exports!==void 0?{exports:r.exports}:{},entry:s})}return t}function Hx(e,t){let n=new Set;for(let r of t.keys()){let s=fo(e,ct(r,"package.json"));for(let o of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let a=s?.[o];if(Pn(a))for(let c of Object.keys(a))n.add(c)}}return n}function Nc(e){let t=e.split("/");return e.startsWith("@")?t.slice(0,2).join("/"):t[0]}function Kx(e,t,n){let r=t?`./${t}`:".";if(e.exports!==void 0){let s=Pn(e.exports)&&Object.keys(e.exports).some((a)=>a.startsWith("."))?e.exports:{".":e.exports},o=Hf(s,r,e.dir,n);if(o)return o}if(!t){for(let s of e.entry){let o=Kf(ct(e.dir,s),e.dir,n);if(o)return o}return sn(ct(e.dir,"src/index"),n)??sn(ct(e.dir,"index"),n)}return sn(ct(e.dir,t),n)??sn(ct(e.dir,`src/${t}`),n)}var Wx=new Set(Cx);function Vx(e){let t=e.indexOf("/");if(t<=0)return;let n=e.slice(0,t);return/^[@~#$]/.test(n)?`${n}/`:void 0}class Wf{byLast=new Map;constructor(e){for(let t of e){if(!ki.test(t)||t.includes("node_modules/"))continue;let n=t.replace(ki,"");if(this.add(n),gn.basename(n)==="index")this.add(_n(n))}}add(e){if(!e)return;let t=gn.basename(e),n=this.byLast.get(t);if(n)n.push(e);else this.byLast.set(t,[e])}roots(e){let t=e.replace(ki,"").replace(/\/$/,""),n=this.byLast.get(gn.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 Gx=0.6,Bf=/^[@~#$]\/$/;function Vf(e){let t=Vx(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 zx(e,t,n){let r=new Map;for(let{from:a,spec:c}of e){let l=Vf(c);if(!l)continue;let u=n(a),d=`${u}\x00${l.prefix}`,f=r.get(d);if(!f)r.set(d,f={scope:u,...l,specs:new Set});f.specs.add(c)}let s=new Wf(t),o=[];for(let{scope:a,prefix:c,bare:l,specs:u}of r.values()){let d=new Map;for(let b of u)for(let g of s.roots(l?b:b.slice(c.length))){if(a&&g!==a&&!g.startsWith(`${a}/`))continue;d.set(g,(d.get(g)??0)+1)}let f=[...d].sort((b,g)=>g[1]-b[1]||b[0].length-g[0].length),[p,h]=f;if(!p)continue;let[y,v]=p;if(h&&h[1]===v)continue;if(v<Gx*u.size)continue;if(v<2&&!Bf.test(c))continue;if(!l&&!Bf.test(c)&&y==="")continue;o.push({scope:a,prefix:c,root:l?y+c:y,hits:v,total:u.size})}return o.sort((a,c)=>a.scope.localeCompare(c.scope)||a.prefix.localeCompare(c.prefix))}class jc{files;aliases;tsProjects;packages;workspaces=new Map;deps;nearestCache=new Map;constructor(e,t){this.files=e;this.tsProjects=jx(e),this.packages=qx(e);for(let r of this.packages.values())if(r.name)this.workspaces.set(r.name,r);this.deps=Hx(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=zx(n,e.paths,(r)=>this.nearest(r).pkg?.dir??"")}static create(e,t={}){return new jc(e,t)}isExternal(e){if(e.startsWith("node:")||Wx.has(Nc(e)))return!0;return this.deps.has(Nc(e))}resolve(e,t){if(e.startsWith(".")){let r=sn(ct(_n(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=_n(e),n=this.nearestCache.get(t);if(n)return n;let r,s;for(let a=t;;a=_n(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 c=Ux(n.paths,e,s);if(c)return{path:c,via:"tsconfig"}}if(e.startsWith("#")&&r?.imports){let c=Hf(r.imports,e,r.dir,s);if(c)return{path:c,via:"package-imports"}}let o=Nc(e),a=this.workspaces.get(o);if(a){let c=Kx(a,e.slice(o.length+1),s);if(c)return{path:c,via:"workspace"}}if(n?.baseUrl!==void 0&&!this.isExternal(e)){let c=sn(ct(n.baseUrl,e),s);if(c)return{path:c,via:"base-url"}}return}resolveInferred(e,t){let n=this.nearest(t).pkg?.dir??"",r=Vf(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=sn(s.root+e.slice(r.length),this.files.paths);return o?{path:o,via:"inferred"}:void 0}}function po(e,t){let n=e.filter((o)=>ki.test(o.path)),r=n.flatMap((o)=>o.externalImports.map((a)=>({from:o.path,spec:a}))),s=jc.create(t,{infer:r});for(let o of n){let a=[],c=new Set(o.imports);for(let l of o.externalImports){let u=s.resolve(l,o.path);if(u&&u.path!==o.path)c.add(u.path);else if(!u)a.push(l)}o.imports=[...c].sort(),o.externalImports=a}return s}gt();var A$=["node_modules/","/dist/","/build/","/.next/","/__snapshots__/",".min.js",".d.ts",".js.map","third-party/"],Oi=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$,...Ri].some((t)=>e.includes(t)||!t.startsWith("/")&&e.startsWith(t))}var I$=(e)=>Math.ceil(e.length/3.6);async function hp(e){let{repo:t,base:n,head:r}=e,s=e.budgetTokens??14000,o=Date.now(),a=(await se("git",["-C",t,"-c","diff.renames=true","diff","--name-only",`${n}..${r}`])).split(`
121
- `).map((T)=>T.trim()).filter(Boolean),c=new Set(a),l=await se("git",["-C",t,"ls-files","-s"]),u=l.split(`
122
- `).map((T)=>T.slice(T.indexOf("\t")+1).trim()).filter((T)=>T&&!C$(T)&&Mt(T)!==null),d=e.cacheDir?new Tc(e.cacheDir):null,f=d?jf(l,await se("git",["-C",t,"diff","--name-only"])):new Map;await Promise.resolve().then(() => Yc());let y,v=()=>y??=Ar.create().then(async(T)=>(await T.warmup(["typescript","tsx","cpp"]),T)),b=async(T,D)=>{let W=await Ct(pp.join(t,T)).catch(()=>null);return W===null?null:(await v()).parseRaw(W,T,D)},g=new Map,R=Date.now();for(let T of u){let D=Mt(T);if(!D)continue;try{let W=f.get(T),le=W?d?.get(W,D)??null:null;if(!le){if(le=await b(T,D),le&&W)d?.set(W,D,le)}if(le)g.set(T,Xc(le,T,t))}catch{}}let N=Date.now()-R;d?.prune();let I=po([...g.values()],uo(t)),_=new Map;for(let[T,D]of g)for(let W of D.imports??[]){if(!_.has(W))_.set(W,new Set);_.get(W).add(T)}let S=new Map;for(let[T,D]of g)for(let W of D.symbols??[]){if(W.kind==="variable"&&!W.exported)continue;let le=S.get(W.name);if(le){if(le.length<8)le.push(T)}else S.set(W.name,[T])}let O=await se("git",["-C",t,"-c","diff.renames=true","diff","-U0",`${n}..${r}`]),P=new Set;for(let{file:T,line:D}of rn(O)){if(!T||!Mt(T))continue;if(D.startsWith("+++ "))continue;if(!/^[+-]/.test(D))continue;for(let W of D.matchAll(/[A-Za-z_][A-Za-z0-9_]{3,}/g))P.add(W[0])}let C=await se("git",["-C",t,"-c","diff.renames=true","diff","-U4",`${n}..${r}`]),j=new Set;{let T=[...rn(C)];for(let D=0;D<T.length;D++){if(!T[D].line.startsWith("+")||T[D].line.startsWith("+++"))continue;if(!T[D].file||!Mt(T[D].file))continue;for(let W=Math.max(0,D-4);W<=Math.min(T.length-1,D+4);W++){if(T[W].file!==T[D].file)continue;let le=T[W].line;if(!le.startsWith(" "))continue;for(let w of le.matchAll(/[A-Za-z_][A-Za-z0-9_]{7,}/g)){let B=w[0];if(Oi.has(B.toLowerCase()))continue;if(!/[A-Z_]/.test(B))continue;if(c.size&&S.has(B))j.add(B)}}}}let H=new Map,U=new Map,q=(T,D,W)=>{if(!g.has(T)||c.has(T))return;if(H.set(T,(H.get(T)??0)+D),!U.has(T))U.set(T,new Set);U.get(T).add(W)};for(let T of a){for(let D of g.get(T)?.imports??[])q(D,6,"imported by a changed file");for(let D of _.get(T)??[])q(D,5,"imports a changed file")}let Ee=new Set;for(let T of a)for(let D of g.get(T)?.symbols??[])Ee.add(D.name);let we=new Map;if(j.size){let T=[...j];for(let[D]of g){if(c.has(D))continue;let W;try{W=await Ct(pp.join(t,D))}catch{continue}if(W.length>2000000)continue;let le=new Set(W.match(/[A-Za-z0-9_$]+/g)??[]);for(let w of T)if(le.has(w)){if(!we.has(D))we.set(D,new Set);we.get(D).add(w)}}}for(let[T,D]of we)for(let W of D){let le=[...we.values()].filter((w)=>w.has(W)).length;if(le>12)continue;q(T,le<=4?8:4,`also references \`${W}\``)}for(let T of P){if(T.length<6)continue;if(Oi.has(T)||Oi.has(T.toLowerCase()))continue;if(!/[A-Z_]/.test(T))continue;if(Ee.has(T))continue;let D=S.get(T);if(!D||D.length>3)continue;let W=D.length===1?4:2;for(let le of D)q(le,W,`defines \`${T}\``)}let ce=[...H.entries()].sort((T,D)=>D[1]-T[1]),Te=ce.map(([T])=>T);if(process.env.MAP_DEBUG)for(let[T,D]of ce.slice(0,30))console.error(String(D).padStart(4),T,"|",[...U.get(T)??[]].slice(0,4).join("; "));let qe=(T,D)=>{let W=g.get(T);if(!W)return"";let le=(W.symbols??[]).filter((de)=>de.exported||W.language==="cpp"||de.kind!=="variable"),w=le.slice(0,40).map((de)=>` ${de.line} ${de.kind} ${de.signature||de.name}`),B=le.length>40?` \u2026 ${le.length-40} more
123
- `:"";return`### ${T} (${W.lines} lines)${D}
120
+ `)){let o=s.indexOf("\t");if(o<0)continue;let[a,c,l]=s.slice(0,o).split(" "),u=s.slice(o+1);if(!c||a==="160000"||l!=="0"||n.has(u))continue;r.set(u,c)}return r}Fi();import{execFileSync as TS}from"child_process";import{builtinModules as FS}from"module";import{existsSync as NS,readFileSync as DS}from"fs";import{join as LS,posix as yn}from"path";function jS(e,t){return{paths:new Set(t),read(n){let r=LS(e,n);try{return NS(r)?DS(r,"utf8"):void 0}catch{return}}}}function ko(e){let t=TS("git",["-C",e,"ls-files"],{encoding:"utf8",maxBuffer:268435456});return jS(e,t.split(`
121
+ `).filter(Boolean))}var xp=[".ts",".tsx",".d.ts",".js",".jsx",".mts",".cts",".mjs",".cjs"],US={".js":[".ts",".tsx"],".jsx":[".tsx"],".mjs":[".mts"],".cjs":[".cts"]},Ui=/\.(?:d\.ts|tsx?|jsx?|mts|cts|mjs|cjs)$/;function cn(e,t){let n=yn.normalize(e).replace(/^\.\//,"");if(n.startsWith("../"))return;if(t.has(n))return n;let r=yn.extname(n);for(let s of US[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 al(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 Bn(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var BS=/(^|\/)(tsconfig[^/]*|jsconfig[^/]*)\.json$/;function bn(e){let t=yn.dirname(e);return t==="."?"":t}function ut(e,t){return yn.normalize(e?`${e}/${t}`:t).replace(/^\.\//,"").replace(/^\.$/,"")}function Eo(e,t){let n=e.read(t);if(n===void 0)return;let r=al(n);return Bn(r)?r:void 0}function qS(e,t,n){if(e.startsWith(".")||e.startsWith("/")){let s=ut(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 sl(e,t,n=new Set){if(n.has(t))return{};n.add(t);let r=Eo(e,t);if(!r)return{};let s=bn(t),o={},a=r.extends;for(let l of typeof a==="string"?[a]:Array.isArray(a)?a:[]){if(typeof l!=="string")continue;let u=qS(l,s,e);if(u)o={...o,...sl(e,u,n)}}let c=Bn(r.compilerOptions)?r.compilerOptions:{};if(typeof c.baseUrl==="string")o.baseUrl=c.baseUrl,o.baseUrlFrom=s;if(Bn(c.paths)){let l={};for(let[u,d]of Object.entries(c.paths))if(Array.isArray(d))l[u]=d.filter((f)=>typeof f==="string");o.paths=l,o.pathsFrom=s}return o}function HS(e,t){let n=Eo(e,t)?.references;if(!Array.isArray(n))return[];let r=bn(t);return n.flatMap((s)=>{if(!Bn(s)||typeof s.path!=="string")return[];let o=ut(r,s.path);return[o.endsWith(".json")?o:`${o}/tsconfig.json`]})}function KS(e,t,n){let r=t.baseUrl!==void 0?ut(t.baseUrlFrom??e,t.baseUrl):void 0,s=[];for(let o of[t,...n]){if(!o.paths)continue;let a=o.baseUrl!==void 0?ut(o.baseUrlFrom??e,o.baseUrl):o.pathsFrom??e;for(let[c,l]of Object.entries(o.paths)){if(s.some((u)=>u.pattern===c))continue;s.push({pattern:c,targets:l.map((u)=>ut(a,u))})}}return{dir:e,...r!==void 0?{baseUrl:r}:{},paths:s}}function WS(e){let t=new Map,n=[...e.paths].filter((r)=>BS.test(r)&&!r.includes("node_modules/"));for(let r of["tsconfig.json","jsconfig.json"])for(let s of n){if(yn.basename(s)!==r)continue;let o=bn(s);if(t.has(o))continue;let a=sl(e,s),c=a.paths?[]:HS(e,s).map((l)=>sl(e,l));t.set(o,KS(o,a,c))}return t}function Rp(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 ol(e){let t=e.indexOf("*");return t===-1?1/0:t}function VS(e,t,n){let r;for(let s of e){let o=Rp(s.pattern,t);if(o===void 0)continue;if(!r||ol(s.pattern)>ol(r.rule.pattern))r={rule:s,capture:o}}if(!r)return;for(let s of r.rule.targets){let o=cn(s.replace("*",r.capture),n);if(o)return o}return}var GS=["source","development","import","module","node","require","browser","default","types"];function $o(e){if(typeof e==="string")return e;if(Array.isArray(e)){for(let t of e){let n=$o(t);if(n)return n}return}if(!Bn(e))return;for(let t of GS)if(t in e)return $o(e[t]);for(let t of Object.values(e)){let n=$o(t);if(n)return n}return}function $p(e,t,n,r){let s;for(let[o,a]of Object.entries(e)){let c=Rp(o,t);if(c===void 0)continue;let l=$o(a);if(!l)continue;let u=ol(o);if(!s||u>s.len)s={target:l,capture:c,len:u}}if(!s)return;return kp(ut(n,s.target.replaceAll("*",s.capture)),n,r)}function kp(e,t,n){let r=cn(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 c=cn(ut(t,`${a}/${o[2]}`).replace(Ui,""),n);if(c)return c}return}function zS(e){let t=new Map;for(let n of e.paths){if(yn.basename(n)!=="package.json"||n.includes("node_modules/"))continue;let r=Eo(e,n);if(!r)continue;let s=[r.source,r.module,r.main,r.types,r.typings].filter((o)=>typeof o==="string");t.set(bn(n),{dir:bn(n),...typeof r.name==="string"?{name:r.name}:{},...Bn(r.imports)?{imports:r.imports}:{},...r.exports!==void 0?{exports:r.exports}:{},entry:s})}return t}function JS(e,t){let n=new Set;for(let r of t.keys()){let s=Eo(e,ut(r,"package.json"));for(let o of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let a=s?.[o];if(Bn(a))for(let c of Object.keys(a))n.add(c)}}return n}function il(e){let t=e.split("/");return e.startsWith("@")?t.slice(0,2).join("/"):t[0]}function XS(e,t,n){let r=t?`./${t}`:".";if(e.exports!==void 0){let s=Bn(e.exports)&&Object.keys(e.exports).some((a)=>a.startsWith("."))?e.exports:{".":e.exports},o=$p(s,r,e.dir,n);if(o)return o}if(!t){for(let s of e.entry){let o=kp(ut(e.dir,s),e.dir,n);if(o)return o}return cn(ut(e.dir,"src/index"),n)??cn(ut(e.dir,"index"),n)}return cn(ut(e.dir,t),n)??cn(ut(e.dir,`src/${t}`),n)}var YS=new Set(FS);function ZS(e){let t=e.indexOf("/");if(t<=0)return;let n=e.slice(0,t);return/^[@~#$]/.test(n)?`${n}/`:void 0}class Ep{byLast=new Map;constructor(e){for(let t of e){if(!Ui.test(t)||t.includes("node_modules/"))continue;let n=t.replace(Ui,"");if(this.add(n),yn.basename(n)==="index")this.add(bn(n))}}add(e){if(!e)return;let t=yn.basename(e),n=this.byLast.get(t);if(n)n.push(e);else this.byLast.set(t,[e])}roots(e){let t=e.replace(Ui,"").replace(/\/$/,""),n=this.byLast.get(yn.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 QS=0.6,Sp=/^[@~#$]\/$/;function Ap(e){let t=ZS(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 eR(e,t,n){let r=new Map;for(let{from:a,spec:c}of e){let l=Ap(c);if(!l)continue;let u=n(a),d=`${u}\x00${l.prefix}`,f=r.get(d);if(!f)r.set(d,f={scope:u,...l,specs:new Set});f.specs.add(c)}let s=new Ep(t),o=[];for(let{scope:a,prefix:c,bare:l,specs:u}of r.values()){let d=new Map;for(let y of u)for(let b of s.roots(l?y:y.slice(c.length))){if(a&&b!==a&&!b.startsWith(`${a}/`))continue;d.set(b,(d.get(b)??0)+1)}let f=[...d].sort((y,b)=>b[1]-y[1]||y[0].length-b[0].length),[p,h]=f;if(!p)continue;let[_,v]=p;if(h&&h[1]===v)continue;if(v<QS*u.size)continue;if(v<2&&!Sp.test(c))continue;if(!l&&!Sp.test(c)&&_==="")continue;o.push({scope:a,prefix:c,root:l?_+c:_,hits:v,total:u.size})}return o.sort((a,c)=>a.scope.localeCompare(c.scope)||a.prefix.localeCompare(c.prefix))}class cl{files;aliases;tsProjects;packages;workspaces=new Map;deps;nearestCache=new Map;constructor(e,t){this.files=e;this.tsProjects=WS(e),this.packages=zS(e);for(let r of this.packages.values())if(r.name)this.workspaces.set(r.name,r);this.deps=JS(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=eR(n,e.paths,(r)=>this.nearest(r).pkg?.dir??"")}static create(e,t={}){return new cl(e,t)}isExternal(e){if(e.startsWith("node:")||YS.has(il(e)))return!0;return this.deps.has(il(e))}resolve(e,t){if(e.startsWith(".")){let r=cn(ut(bn(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=bn(e),n=this.nearestCache.get(t);if(n)return n;let r,s;for(let a=t;;a=bn(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 c=VS(n.paths,e,s);if(c)return{path:c,via:"tsconfig"}}if(e.startsWith("#")&&r?.imports){let c=$p(r.imports,e,r.dir,s);if(c)return{path:c,via:"package-imports"}}let o=il(e),a=this.workspaces.get(o);if(a){let c=XS(a,e.slice(o.length+1),s);if(c)return{path:c,via:"workspace"}}if(n?.baseUrl!==void 0&&!this.isExternal(e)){let c=cn(ut(n.baseUrl,e),s);if(c)return{path:c,via:"base-url"}}return}resolveInferred(e,t){let n=this.nearest(t).pkg?.dir??"",r=Ap(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=cn(s.root+e.slice(r.length),this.files.paths);return o?{path:o,via:"inferred"}:void 0}}function Ao(e,t){let n=e.filter((o)=>Ui.test(o.path)),r=n.flatMap((o)=>o.externalImports.map((a)=>({from:o.path,spec:a}))),s=cl.create(t,{infer:r});for(let o of n){let a=[],c=new Set(o.imports);for(let l of o.externalImports){let u=s.resolve(l,o.path);if(u&&u.path!==o.path)c.add(u.path);else if(!u)a.push(l)}o.imports=[...c].sort(),o.externalImports=a}return s}wt();var TR=["node_modules/","/dist/","/build/","/.next/","/__snapshots__/",".min.js",".d.ts",".js.map","third-party/"],Wi=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 FR(e){return[...TR,...ji].some((t)=>e.includes(t)||!t.startsWith("/")&&e.startsWith(t))}var NR=(e)=>Math.ceil(e.length/3.6);async function Xp(e){let{repo:t,base:n,head:r}=e,s=e.budgetTokens??14000,o=Date.now(),a=(await le("git",["-C",t,"-c","diff.renames=true","diff","--name-only",`${n}..${r}`])).split(`
123
+ `).map((T)=>T.trim()).filter(Boolean),c=new Set(a),l=await le("git",["-C",t,"ls-files","-s"]),u=l.split(`
124
+ `).map((T)=>T.slice(T.indexOf("\t")+1).trim()).filter((T)=>T&&!FR(T)&&Ft(T)!==null),d=e.cacheDir?new rl(e.cacheDir):null,f=d?vp(l,await le("git",["-C",t,"diff","--name-only"])):new Map;await Promise.resolve().then(() => bl());let _,v=()=>_??=Wr.create().then(async(T)=>(await T.warmup(["typescript","tsx","cpp"]),T)),y=async(T,L)=>{let Z=await It(Jp.join(t,T)).catch(()=>null);return Z===null?null:(await v()).parseRaw(Z,T,L)},b=new Map,S=Date.now();for(let T of u){let L=Ft(T);if(!L)continue;try{let Z=f.get(T),ne=Z?d?.get(Z,L)??null:null;if(!ne){if(ne=await y(T,L),ne&&Z)d?.set(Z,L,ne)}if(ne)b.set(T,yl(ne,T,t))}catch{}}let O=Date.now()-S;d?.prune();let I=Ao([...b.values()],ko(t)),g=new Map;for(let[T,L]of b)for(let Z of L.imports??[]){if(!g.has(Z))g.set(Z,new Set);g.get(Z).add(T)}let R=new Map;for(let[T,L]of b)for(let Z of L.symbols??[]){if(Z.kind==="variable"&&!Z.exported)continue;let ne=R.get(Z.name);if(ne){if(ne.length<8)ne.push(T)}else R.set(Z.name,[T])}let P=await le("git",["-C",t,"-c","diff.renames=true","diff","-U0",`${n}..${r}`]),M=new Set;for(let{file:T,line:L}of an(P)){if(!T||!Ft(T))continue;if(L.startsWith("+++ "))continue;if(!/^[+-]/.test(L))continue;for(let Z of L.matchAll(/[A-Za-z_][A-Za-z0-9_]{3,}/g))M.add(Z[0])}let C=await le("git",["-C",t,"-c","diff.renames=true","diff","-U4",`${n}..${r}`]),N=new Set;{let T=[...an(C)];for(let L=0;L<T.length;L++){if(!T[L].line.startsWith("+")||T[L].line.startsWith("+++"))continue;if(!T[L].file||!Ft(T[L].file))continue;for(let Z=Math.max(0,L-4);Z<=Math.min(T.length-1,L+4);Z++){if(T[Z].file!==T[L].file)continue;let ne=T[Z].line;if(!ne.startsWith(" "))continue;for(let w of ne.matchAll(/[A-Za-z_][A-Za-z0-9_]{7,}/g)){let D=w[0];if(Wi.has(D.toLowerCase()))continue;if(!/[A-Z_]/.test(D))continue;if(c.size&&R.has(D))N.add(D)}}}}let H=new Map,q=new Map,K=(T,L,Z)=>{if(!b.has(T)||c.has(T))return;if(H.set(T,(H.get(T)??0)+L),!q.has(T))q.set(T,new Set);q.get(T).add(Z)};for(let T of a){for(let L of b.get(T)?.imports??[])K(L,6,"imported by a changed file");for(let L of g.get(T)??[])K(L,5,"imports a changed file")}let ge=new Set;for(let T of a)for(let L of b.get(T)?.symbols??[])ge.add(L.name);let $e=new Map;if(N.size){let T=[...N];for(let[L]of b){if(c.has(L))continue;let Z;try{Z=await It(Jp.join(t,L))}catch{continue}if(Z.length>2000000)continue;let ne=new Set(Z.match(/[A-Za-z0-9_$]+/g)??[]);for(let w of T)if(ne.has(w)){if(!$e.has(L))$e.set(L,new Set);$e.get(L).add(w)}}}for(let[T,L]of $e)for(let Z of L){let ne=[...$e.values()].filter((w)=>w.has(Z)).length;if(ne>12)continue;K(T,ne<=4?8:4,`also references \`${Z}\``)}for(let T of M){if(T.length<6)continue;if(Wi.has(T)||Wi.has(T.toLowerCase()))continue;if(!/[A-Z_]/.test(T))continue;if(ge.has(T))continue;let L=R.get(T);if(!L||L.length>3)continue;let Z=L.length===1?4:2;for(let ne of L)K(ne,Z,`defines \`${T}\``)}let ie=[...H.entries()].sort((T,L)=>L[1]-T[1]),Ne=ie.map(([T])=>T);if(process.env.MAP_DEBUG)for(let[T,L]of ie.slice(0,30))console.error(String(L).padStart(4),T,"|",[...q.get(T)??[]].slice(0,4).join("; "));let Ye=(T,L)=>{let Z=b.get(T);if(!Z)return"";let ne=(Z.symbols??[]).filter((de)=>de.exported||Z.language==="cpp"||de.kind!=="variable"),w=ne.slice(0,40).map((de)=>` ${de.line} ${de.kind} ${de.signature||de.name}`),D=ne.length>40?` \u2026 ${ne.length-40} more
125
+ `:"";return`### ${T} (${Z.lines} lines)${L}
124
126
  ${w.join(`
125
127
  `)}
126
- ${B}`},he=[],K=0,ye=(T,D=s)=>{let W=I$(T);if(K+W>D)return!1;return he.push(T),K+=W,!0},ve=new Map;for(let[T,D]of g){let W=T.split("/"),le=W.slice(0,Math.min(3,W.length-1)).join("/")||".",w=ve.get(le)??{files:0,symbols:0};w.files++,w.symbols+=(D.symbols??[]).length,ve.set(le,w)}let st=[...ve.entries()].sort((T,D)=>D[1].files-T[1].files).slice(0,45).map(([T,D])=>` ${T}/ ${D.files} files, ${D.symbols} symbols`).join(`
127
- `);ye(`# Repo map for this change
128
+ ${D}`},Ae=[],B=0,Te=(T,L=s)=>{let Z=NR(T);if(B+Z>L)return!1;return Ae.push(T),B+=Z,!0},Pe=new Map;for(let[T,L]of b){let Z=T.split("/"),ne=Z.slice(0,Math.min(3,Z.length-1)).join("/")||".",w=Pe.get(ne)??{files:0,symbols:0};w.files++,w.symbols+=(L.symbols??[]).length,Pe.set(ne,w)}let je=[...Pe.entries()].sort((T,L)=>L[1].files-T[1].files).slice(0,45).map(([T,L])=>` ${T}/ ${L.files} files, ${L.symbols} symbols`).join(`
129
+ `);Te(`# Repo map for this change
128
130
 
129
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.
130
- `),ye(`## Codebase layout (parsed source only, ${g.size} files, ${S.size} distinct symbol names)
132
+ `),Te(`## Codebase layout (parsed source only, ${b.size} files, ${R.size} distinct symbol names)
131
133
 
132
134
  \`\`\`
133
- ${st}
135
+ ${je}
134
136
  \`\`\`
135
- `);let Ae=Math.floor(s*0.5);ye(`## Changed files
136
- `,Ae);let Le=0;for(let T of a)if(g.has(T)&&ye(qe(T,""),Ae))Le++;ye(`
137
+ `);let Ce=Math.floor(s*0.5);Te(`## Changed files
138
+ `,Ce);let be=0;for(let T of a)if(b.has(T)&&Te(Ye(T,""),Ce))be++;Te(`
137
139
  ## Related files (not changed by this PR)
138
- `);let Qe=0;for(let T of Te){let D=` \u2014 ${[...U.get(T)??[]].slice(0,3).join("; ")}`;if(!ye(qe(T,D)))break;Qe++}return{markdown:he.join(`
139
- `),meta:{base:n,head:r,changedFiles:a.length,trackedParsed:g.size,symbolsIndexed:S.size,diffIdentifiers:P.size,candidatesScored:H.size,changedRendered:Le,relatedRendered:Qe,approxTokens:K,parseMs:N,totalMs:Date.now()-o,...d?{outlineCache:{hits:d.hits,misses:d.misses}}:{},inferredAliases:I.aliases.map((T)=>`${T.scope||"."}: ${T.prefix} -> ${T.root||"."}`)}}}gt();Pi();gt();async function lt(e){return await se("git",["-C",tt,"-c","diff.renames=true",...e])}async function yp(e,t,n){return(await lt(["diff","--unified=0",`${e}..${t}`,"--",...n])).split(`
140
+ `);let at=0;for(let T of Ne){let L=` \u2014 ${[...q.get(T)??[]].slice(0,3).join("; ")}`;if(!Te(Ye(T,L)))break;at++}return{markdown:Ae.join(`
141
+ `),meta:{base:n,head:r,changedFiles:a.length,trackedParsed:b.size,symbolsIndexed:R.size,diffIdentifiers:M.size,candidatesScored:H.size,changedRendered:be,relatedRendered:at,approxTokens:B,parseMs:O,totalMs:Date.now()-o,...d?{outlineCache:{hits:d.hits,misses:d.misses}}:{},inferredAliases:I.aliases.map((T)=>`${T.scope||"."}: ${T.prefix} -> ${T.root||"."}`)}}}wt();Gi();wt();async function dt(e){return await le("git",["-C",rt,"-c","diff.renames=true",...e])}var Rl=(e)=>le("gh",e);function Sl(e){return e instanceof Error?e.message:String(e)}async function nh(e,t,n){return(await dt(["diff","--unified=0",`${e}..${t}`,"--",...n])).split(`
140
142
  `).filter((s)=>s.startsWith("diff --git ")||s.startsWith("@@")).join(`
141
- `)}async function go(e,t,n,r,s){let o="",a="";if(t)try{let l=JSON.parse(await se("gh",["api",`repos/${e}/pulls/${t}`]));o=l.title??"",a=l.body??""}catch{}let c=await lt(["log","--format=%s%n%b%n---",`${n}..${r}`]);return{title:o,body:a,commits:c.trim(),...s?.trim()?{stated:s.trim()}:{}}}async function wp(e){return JSON.parse(await se("gh",["api","--paginate",e]))}function D$(e){return e.replace(/<!--[\s\S]*?-->/g,"").replace(/\n{3,}/g,`
143
+ `)}async function Po(e,t,n,r,s,o={}){let a=o.gh??Rl,c="",l="";if(t)try{let d=JSON.parse(await a(["api",`repos/${e}/pulls/${t}`]));c=d.title??"",l=d.body??""}catch(d){if(o.strict)throw Error(`reading the pull request description: ${Sl(d)}`,{cause:d})}let u=await dt(["log","--format=%s%n%b%n---",`${n}..${r}`]);return{title:c,body:l,commits:u.trim(),...s?.trim()?{stated:s.trim()}:{}}}async function th(e,t=Rl){return JSON.parse(await t(["api","--paginate",e]))}function qR(e){return Qp(e).replace(/<!--[\s\S]*?-->/g,"").replace(/\n{3,}/g,`
142
144
 
143
- `).trim()}async function bp(e,t){let n=process.env.PRIOR_FIXTURE;if(n)return await br(n);if(!t)return[];let r=[];try{let s=await wp(`repos/${e}/pulls/${t}/comments`),o=_p(s);for(let a of s){let c=mo(a.body??"",a.user?.type);r.push({id:a.id,file:a.path,line:a.line??a.original_line,author:a.user?.login??"?",body:a.body??"",resolved:!1,commit:a.original_commit_id,url:a.html_url,mine:c,...c?{fingerprint:Cr(a.body??"").find((l)=>l.fields.fp)?.fields.fp}:{},...o.has(a.id)?{addressed:!0}:{},...a.in_reply_to_id?{inReplyTo:a.in_reply_to_id}:{}})}}catch{}try{for(let s of await wp(`repos/${e}/issues/${t}/comments`)){let o=mo(s.body??"",s.user?.type,"summary");if(!o&&s.user?.type==="Bot")continue;let a=o?Number(Qc(s.body??"","summary")?.fields.runs??0):void 0,c=o?Cr(s.body??"").filter((l)=>l.kind==="summary-item"&&l.fields.fp).map((l)=>({fp:l.fields.fp,file:l.fields.file??"?",line:l.fields.line??"?"})):[];r.push({id:s.id,author:s.user?.login??"?",body:o?D$(s.body??""):s.body??"",resolved:!1,url:s.html_url,mine:o,...s.author_association?{association:s.author_association}:{},...a?{runs:a}:{},...c.length?{summaryClaims:c}:{}})}}catch{}return r}function F$(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 vp(e,t=""){if(e.length===0)return"";let n=e.filter((l)=>!l.mine&&l.file),r=e.filter((l)=>!l.mine&&!l.file&&!F$(l.body,t)),s=e.filter((l)=>l.mine&&l.file&&!l.addressed&&!l.inReplyTo),o=e.filter((l)=>l.mine&&!l.file),a=[],c=(l,u)=>{let d=l.file?`${l.file}${l.line?`:${l.line}`:""}`:"(conversation)",f=l.body.replace(/\s+/g," ").slice(0,u);a.push(`- id=${l.id} @${l.author} \`${d}\`${l.resolved?" [resolved]":""}: ${f}`)};if(n.length){a.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 l of n)c(l,400);a.push("")}if(r.length){a.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 l of r)c(l,600);a.push("")}if(s.length||o.length){a.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 l of s)c(l,300);if(o.length)for(let l of o){if(l.summaryClaims?.length){a.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 u of l.summaryClaims)a.push(`- \`${u.file}:${u.line}\``)}a.push("",`Your summary comment (id=${l.id}), conclusions only:`,""),a.push(l.body.slice(0,12000))}a.push("")}return a.join(`
145
+ `).trim()}async function rh(e,t,n={}){let r=process.env.PRIOR_FIXTURE;if(r)return await Dr(r);if(!t)return[];let s=n.gh??Rl,o=[];try{let a=await th(`repos/${e}/pulls/${t}/comments`,s),c=eh(a);for(let l of a){let u=Oo(l.body??"",l.user?.type);o.push({id:l.id,file:l.path,line:l.line??l.original_line,author:l.user?.login??"?",body:l.body??"",resolved:!1,commit:l.original_commit_id,url:l.html_url,mine:u,...u?{fingerprint:Vr(l.body??"").find((d)=>d.fields.fp)?.fields.fp}:{},...c.has(l.id)?{addressed:!0}:{},...l.in_reply_to_id?{inReplyTo:l.in_reply_to_id}:{}})}}catch(a){if(n.strict)throw Error(`reading the pull request's review comments: ${Sl(a)}`,{cause:a})}try{for(let a of await th(`repos/${e}/issues/${t}/comments`,s)){let c=Oo(a.body??"",a.user?.type,"summary");if(!c&&a.user?.type==="Bot")continue;let l=c?xl(a.body??"","summary"):void 0,u=c?Number(l?.fields.runs??0):void 0,d=l?.fields.head,f=c?Vr(a.body??"").filter((p)=>p.kind==="summary-item"&&p.fields.fp).map((p)=>({fp:p.fields.fp,file:p.fields.file??"?",line:p.fields.line??"?"})):[];o.push({id:a.id,author:a.user?.login??"?",body:c?qR(a.body??""):a.body??"",resolved:!1,url:a.html_url,mine:c,...a.author_association?{association:a.author_association}:{},...u?{runs:u}:{},...d&&/^[0-9a-f]{40}$/i.test(d)?{head:d.toLowerCase()}:{},...f.length?{summaryClaims:f}:{}})}}catch(a){if(n.strict)throw Error(`reading the pull request's comments: ${Sl(a)}`,{cause:a})}return o}function HR(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 ih(e,t=""){if(e.length===0)return"";let n=e.filter((l)=>!l.mine&&l.file),r=e.filter((l)=>!l.mine&&!l.file&&!HR(l.body,t)),s=e.filter((l)=>l.mine&&l.file&&!l.addressed&&!l.inReplyTo),o=e.filter((l)=>l.mine&&!l.file),a=[],c=(l,u)=>{let d=l.file?`${l.file}${l.line?`:${l.line}`:""}`:"(conversation)",f=l.body.replace(/\s+/g," ").slice(0,u);a.push(`- id=${l.id} @${l.author} \`${d}\`${l.resolved?" [resolved]":""}: ${f}`)};if(n.length){a.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 l of n)c(l,400);a.push("")}if(r.length){a.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 l of r)c(l,600);a.push("")}if(s.length||o.length){a.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 l of s)c(l,300);if(o.length)for(let l of o){if(l.summaryClaims?.length){a.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 u of l.summaryClaims)a.push(`- \`${u.file}:${u.line}\``)}a.push("",`Your summary comment (id=${l.id}), conclusions only:`,""),a.push(l.body.slice(0,12000))}a.push("")}return a.join(`
144
146
  `)+`
145
- `}vi();async function xp(e){let t=xi(e.diffU0),n=new Map;for(let{file:a,line:c}of rn(e.diffU0)){if(!a||!c.startsWith("+")||c.startsWith("+++ "))continue;let l=n.get(a)??new Set;for(let u of c.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g))l.add(u[0]);n.set(a,l)}await Promise.resolve().then(() => Yc());let s=await Ar.create(),o=[];for(let a of e.files){let c={path:a,imports:[],externalImports:[]},l=[];if(Mt(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)??[];c.imports=d.imports,c.externalImports=d.externalImports,l=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:c,defined:l})}return po(o.map((a)=>a.imports),e.source),o.map(({file:a,imports:c,defined:l})=>({file:a,tokens:e.fileTokens.get(a)??0,imports:c.imports,defined:[...new Set(l)],used:[...n.get(a)??[]]}))}var el=/\.(test|spec)(\.[cm]?[jt]sx?)$/,tl=/\.(h|hh|hpp)$/,nl=/\.(c|cc|cpp|cxx)$/;function Nt(e){let t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}function rl(e){return e.slice(e.lastIndexOf("/")+1).replace(el,"").replace(/\.[^.]+$/,"")}function L$(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 j$(e,t){if(rl(e)!==rl(t))return!1;let[n,r]=[Nt(e),Nt(t)];if(!(n===r||Nt(n)===r||Nt(r)===n))return!1;if(el.test(e)!==el.test(t))return!0;return tl.test(e)&&nl.test(t)||tl.test(t)&&nl.test(e)}function Rp(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(!L$(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},c=new Map,l=(d,f,p,h,y)=>{if(d===f)return;let v=d<f?`${d}\x00${f}`:`${f}\x00${d}`,b=c.get(v);if(!b){c.set(v,{from:d,to:f,kind:p,weight:h,...y?{names:[y]}:{}});return}if(b.weight+=h,a[p]<a[b.kind])b.kind=p,b.from=d,b.to=f;if(y&&!b.names?.includes(y))b.names=[...b.names??[],y]};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 y of p)l(d.file,y,"symbol",4/h,f)}for(let f of new Set(d.imports)){if(!n.has(f))continue;l(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(j$(p,h))l(p,h,"pair",3);else if(Nt(p)===Nt(h))l(p,h,"dir",0.25)}return U$([...c.values()])}function U$(e){return e.sort((t,n)=>n.weight-t.weight||t.from.localeCompare(n.from)||t.to.localeCompare(n.to))}function B$(e){if(!e.length)return"";let t=Nt(e[0]).split("/");for(let n of e.slice(1)){let r=Nt(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 $p(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function q$(e,t){let n=B$(e).split("/").filter(Boolean);if(e.length>1&&n.length>=3)return $p(n.slice(-2).join("-"));let r=[...e].sort((s,o)=>(t.get(o)??0)-(t.get(s)??0))[0];return $p(rl(r))||"files"}function Sp(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 kp=new Set(["symbol","pair"]);function Ep(e,t,n){let r=n.maxFiles??8,s=n.maxDirFiles??6,o=new Map(e.map((_)=>[_.file,_.tokens])),a=new Map(e.map((_,S)=>[_.file,S])),c=new Map(e.map((_,S)=>[S,new Set([_.file])])),l=new Map(e.map((_,S)=>[S,_.tokens])),u=(_,S)=>{let[O,P]=c.get(_).size>=c.get(S).size?[_,S]:[S,_];for(let C of c.get(P))a.set(C,O),c.get(O).add(C);l.set(O,l.get(O)+l.get(P)),c.delete(P),l.delete(P)},d=n.target??Math.round(n.budget*0.7),f=(_,S,O)=>l.get(_)+l.get(S)<=d&&c.get(_).size+c.get(S).size<=O,p=[[(_)=>kp.has(_.kind),r],[(_)=>_.kind==="import",r],[(_)=>_.kind==="dir",s]];for(let[_,S]of p)for(let O of t){if(!_(O))continue;let[P,C]=[a.get(O.from),a.get(O.to)];if(P===void 0||C===void 0||P===C||!f(P,C,S))continue;u(P,C)}let h=d/4,y=()=>[...c.keys()].sort((_,S)=>l.get(_)-l.get(S)||_-S);for(let _ of y()){if(!c.has(_)||l.get(_)>h||c.get(_).size>2)continue;let S;for(let O of c.keys()){if(O===_||!f(_,O,s))continue;let P=0;for(let C of c.get(_))for(let j of c.get(O))P=Math.max(P,Sp(Nt(C),Nt(j)));if(P>0&&(!S||P>S.depth))S={group:O,depth:P}}if(S)u(S.group,_)}H$(t,a,c,l,o,n.budget,r*2),W$(a,c,l,o);let v=(_,S=!1)=>{let O=new Map;for(let j of t){let[H,U]=[a.get(j.from),a.get(j.to)];if(H===U||H!==_&&U!==_)continue;let q=H===_?U:H;O.set(q,(O.get(q)??0)+j.weight)}let P=new Set([...c.get(_)].map(_o)),C;for(let j of c.keys()){if(j===_||l.get(_)+l.get(j)>n.budget)continue;let H=0;for(let we of c.get(_))for(let ce of c.get(j))H=Math.max(H,Sp(Nt(we),Nt(ce)));let U=O.get(j)??0,q=[...c.get(j)].some((we)=>P.has(_o(we)));if(S&&!q)continue;if(!C||U>C.weight||U===C.weight&&q&&!C.sameLanguage||U===C.weight&&q===C.sameLanguage&&H>C.depth||U===C.weight&&q===C.sameLanguage&&H===C.depth&&l.get(j)<l.get(C.group))C={group:j,weight:U,sameLanguage:q,depth:H}}return C?.group};while(n.maxGroups&&c.size>n.maxGroups){let _=y()[0],S=v(_);if(S===void 0)break;u(S,_)}if(n.foldSmall!==!1)for(let _ of y()){if(c.size<2)break;if(!c.has(_)||l.get(_)>h||c.get(_).size>2)continue;let S=v(_,!0);if(S!==void 0)u(S,_)}let b=[...c.values()].map((_)=>[..._].sort()).sort((_,S)=>Ir(S,o)-Ir(_,o)||_[0].localeCompare(S[0])),g=new Map,R=new Map,N=b.map((_,S)=>{for(let C of _)R.set(C,S);let O=q$(_,o),P=(g.get(O)??0)+1;return g.set(O,P),{id:P>1?`${O}-${P}`:O,files:_,tokens:Ir(_,o),links:[]}}),I=[];for(let _ of t){let[S,O]=[R.get(_.from),R.get(_.to)];if(S===void 0||O===void 0)continue;if(S===O)N[S].links.push(_);else if(_.kind!=="dir")I.push(_)}return{groups:N,cut:I}}function H$(e,t,n,r,s,o,a){let c=new Map;for(let u of e){if(!kp.has(u.kind))continue;for(let d of[u.from,u.to])c.set(d,[...c.get(d)??[],u])}let l=[...c.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 l){let p=t.get(f),h=new Map;for(let b of c.get(f)){let g=b.from===f?b.to:b.from,R=t.get(g);h.set(R,(h.get(R)??0)+b.weight)}let y=h.get(p)??0,v;for(let[b,g]of h){if(b===p||g<=y||v&&g<=v.weight)continue;if(r.get(b)+s.get(f)>o||n.get(b).size+1>a)continue;v={group:b,weight:g}}if(!v)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(v.group).add(f),r.set(v.group,r.get(v.group)+s.get(f)),t.set(f,v.group),d=!0}if(!d)break}}var K$=4;function _o(e){if(tl.test(e)||nl.test(e))return"cpp";if(/\.[cm]?[jt]sx?$/.test(e))return"js";return e.slice(e.lastIndexOf(".")+1)}function W$(e,t,n,r){let s=Math.max(-1,...t.keys())+1,o=(a,c)=>{let l=s++;t.set(l,new Set(c)),n.set(l,Ir(c,r));for(let u of c)t.get(a).delete(u),e.set(u,l);return n.set(a,n.get(a)-n.get(l)),l};for(let a of[...t.keys()]){let c=[...t.get(a)].sort();if(c.length<K$)continue;let l=new Map;for(let d of c)l.set(_o(d),[...l.get(_o(d))??[],d]);if(l.size<2||[...l.values()].some((d)=>d.length<2))continue;let[,...u]=[...l.values()].sort((d,f)=>Ir(f,r)-Ir(d,r));for(let d of u)o(a,d)}}function Ir(e,t){return e.reduce((n,r)=>n+(t.get(r)??0),0)}function tr(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 Ap(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(tr)}function Cp(e,t,n,r){let s=e.map((l)=>({id:l.id,files:[...l.files],tokens:l.tokens})),o=new Map(s.map((l)=>[l.id,l])),a=new Map;for(let l of t?.groups??[]){if(typeof l?.id!=="string"||!o.has(l.id))continue;a.set(l.id,{title:typeof l.title==="string"&&l.title.trim()?l.title.trim():void 0,rationale:typeof l.rationale==="string"&&l.rationale.trim()?l.rationale.trim():void 0,priority:typeof l.priority==="number"&&Number.isFinite(l.priority)?l.priority:void 0})}let c=[];for(let l of t?.moves??[]){if(typeof l?.file!=="string"||typeof l.to!=="string")continue;let u=s.find((p)=>p.files.includes(l.file)),d=o.get(l.to);if(!u||!d||u===d||u.files.length===1)continue;let f=r.get(l.file)??0;if(d.tokens+f>n)continue;u.files=u.files.filter((p)=>p!==l.file),u.tokens-=f,d.files=[...d.files,l.file].sort(),d.tokens+=f,c.push({file:l.file,from:u.id,to:d.id,reason:typeof l.reason==="string"?l.reason:""})}return{moves:c,units:s.map((l)=>{let u=a.get(l.id);return{id:l.id,title:u?.title??l.id,...u?.rationale?{rationale:u.rationale}:{},files:l.files,...u?.priority!==void 0?{priority:u.priority}:{}}})}}async function wo(e){let t=`${e.base}..${e.head}`,n=zn(await lt(["diff",t,"--",...e.files]),e.base),r=await lt(["diff","--stat",t]),s=new Map([...kf(n)].map(([u,d])=>[u,Math.ceil(d/Cf)])),o=await lt(["diff","--unified=0",t,"--",...e.files]),a=await xp({source:await e.source(e.files),diffU0:o,files:e.files,fileTokens:s}),c=Rp(a,Oi),l=Ep(a,c,{budget:In,maxGroups:Yn});return{wholeDiff:n,diffstat:r,diffU0:o,fileTokens:s,facts:a,links:c,grouping:l}}var V$=new Set(["if","for","while","switch","return","catch","function","new","await","typeof","sizeof"]);function G$(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 yo(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 rn(e)){if(!s||o.startsWith("+++ "))continue;let a=r(s),c=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@ ?(.*)$/.exec(o);if(c){let l=G$(c[2]);if(l&&!a.touches.some((u)=>u.name===l))a.touches.push({name:l,line:Number(c[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 bo(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 vo(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 c=new Set,l=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,y)=>o(y)-o(h))){let h=o(p);if(h>r||f+h>u||l+h>n)continue;c.add(p),f+=h,l+=h}}for(let d of s.filter((f)=>!c.has(f)).sort((f,p)=>o(f)-o(p))){let f=o(d);if(f>r||l+f>n)continue;c.add(d),l+=f}return{shown:s.filter((d)=>c.has(d)),sketched:s.filter((d)=>!c.has(d))}}function xo(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(tr)}function $o(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),c=r.get(o.to);if(!a||!c||a===c)continue;if(s.push(`${tr(o)} (${a} \u2192 ${c})`),s.length>=n)break}return s}So();import{randomBytes as Z$}from"crypto";import{existsSync as Q$,realpathSync as eS}from"fs";import tS from"os";import Lp from"path";function Np(e){try{return eS(e)}catch{return Lp.resolve(e)}}function Dp(e,t){return Np(e)===Np(t)}async function nS(e,t){await te("git",["-C",e,"worktree","remove","--force",t],{allowFail:!0}),await te("git",["-C",e,"worktree","prune"],{allowFail:!0})}async function Fp(e,t,n){if((await te("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 te("git",["-C",e,"fetch","-q","origin",`refs/pull/${t}/head`],{allowFail:!0}),(await te("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 jp(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=Lp.join(tS.tmpdir(),`code-review-subject-${n.slice(0,12)}-${process.pid}-${Z$(3).toString("hex")}`);return await Fp(e,t,n),await se("git",["-C",e,"worktree","add","--detach","-q",u,n]),{dir:u,release:()=>nS(e,u)}}let s=r,o=async()=>{},a=await te("git",["-C",s,"rev-parse","--show-toplevel"],{allowFail:!0}),l=a.code===0&&Dp(a.stdout.trim(),s)?await te("git",["-C",s,"rev-parse","HEAD"],{allowFail:!0}):{code:1,stdout:"",stderr:""};if(l.code===0&&l.stdout.trim().startsWith(n))return{dir:s,release:o};if(await Fp(e,t,n),l.code===0){let u=await te("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(Dp(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 te("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(Q$(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 se("git",["-C",e,"worktree","add","--detach","-q",s,n]),{dir:s,release:o}}import Up from"path";function Bp(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 Ro(e){if(process.env.GH_REPO)return process.env.GH_REPO;let t=await te("git",["-C",e,"remote","get-url","origin"],{allowFail:!0}),r=(t.code===0?t.stdout.trim():"").match(/github\.com[:/]+([^/]+)\/(.+?)(?:\.git)?$/);if(!r)return`local/${Up.basename(Up.resolve(e))}`;return`${r[1]}/${r[2]}`}Pi();gt();Mi();import Ve from"path";import{spawn as iS}from"child_process";import{readFileSync as sS}from"fs";import{chmod as oS,mkdir as aS,rm as cS}from"fs/promises";gt();class Dt extends Error{name="CancelledError";constructor(){super("review cancelled")}}var Ti=new Map,Hp=!1;function sl(e,t){if(e.pid===void 0)return;try{process.kill(-e.pid,t)}catch{}}function lS(){for(let e of Ti.keys())sl(e,"SIGKILL")}async function Mr(e=5000){let t=[...Ti];if(!t.length)return;for(let[r]of t)sl(r,"SIGTERM");let n=setTimeout(()=>{for(let[r]of t)if(Ti.has(r))sl(r,"SIGKILL")},e);await Promise.all(t.map(([,r])=>r)),clearTimeout(n)}function uS(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(`
146
- `)){let o=s.trim();if(!o.startsWith("{"))continue;let a;try{a=JSON.parse(o)}catch{continue}let c=a.part;if(!(c?.type==="step-finish"||c?.type==="step_finish"||a.type==="step_finish")||!c)continue;n+=1,t+=c.cost??0,r.input_tokens+=c.tokens?.input??0,r.output_tokens+=c.tokens?.output??0,r.reasoning_tokens+=c.tokens?.reasoning??0,r.cache_read_input_tokens+=c.tokens?.cache?.read??0,r.cache_creation_input_tokens+=c.tokens?.cache?.write??0}return{costUsd:t,numTurns:n,usage:r}}var dS=new Set(["read","tilth_tilth_read"]),fS=new Set(["grep","glob","tilth_tilth_search","tilth_tilth_files"]),pS=60;function hS(e,t=""){let n={},r=0,s=new Set,o=new Set,a=t?`${t.replace(/\/$/,"")}/`:"",c=(u)=>a&&u.startsWith(a)?u.slice(a.length):u,l=(u,d)=>{if(u.size<pS)u.add(d)};for(let u of e.split(`
147
- `)){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(dS.has(p.tool)){let y=Array.isArray(h.paths)?h.paths:[h.path??h.filePath],v=typeof h.section==="string"?`:${h.section}`:"";for(let b of y)if(typeof b==="string")l(s,c(b)+v)}else if(fS.has(p.tool)){let y=h.query??h.pattern;if(typeof y==="string")l(o,y)}}return{calls:n,failed:r,read:[...s],searched:[...o]}}var ol=new Map;function mS(e,t,n="repo",r){let s=`${e}\x00${t}`,o=`${n==="repo"?"shared":"no-tools"}${r?`-${r}`:""}`,a=ol.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 c=(async()=>{let l=Ve.join(ht,"oc",o),u=Ve.join(l,"config");return await fn(Ve.join(u,"opencode.json"),_S(e,t,n)),await Ye(Ve.join(u,"plugin","governor.ts"),await Ct(Ve.join(vr,"opencode","governor.ts"))),l})();return ol.set(o,{home:c,key:s}),c}function ko(){ol.clear()}function gS(e){return e.includes("/")?e:`${xc}/${e}`}function _S(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(so).length?{providers:so}:{},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:$c,system:t?`${e}
147
+ `}Fi();async function sh(e){let t=Ni(e.diffU0),n=new Map;for(let{file:a,line:c}of an(e.diffU0)){if(!a||!c.startsWith("+")||c.startsWith("+++ "))continue;let l=n.get(a)??new Set;for(let u of c.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g))l.add(u[0]);n.set(a,l)}await Promise.resolve().then(() => bl());let s=await Wr.create(),o=[];for(let a of e.files){let c={path:a,imports:[],externalImports:[]},l=[];if(Ft(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)??[];c.imports=d.imports,c.externalImports=d.externalImports,l=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:c,defined:l})}return Ao(o.map((a)=>a.imports),e.source),o.map(({file:a,imports:c,defined:l})=>({file:a,tokens:e.fileTokens.get(a)??0,imports:c.imports,defined:[...new Set(l)],used:[...n.get(a)??[]]}))}var $l=/\.(test|spec)(\.[cm]?[jt]sx?)$/,kl=/\.(h|hh|hpp)$/,El=/\.(c|cc|cpp|cxx)$/;function Dt(e){let t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}function Al(e){return e.slice(e.lastIndexOf("/")+1).replace($l,"").replace(/\.[^.]+$/,"")}function KR(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 WR(e,t){if(Al(e)!==Al(t))return!1;let[n,r]=[Dt(e),Dt(t)];if(!(n===r||Dt(n)===r||Dt(r)===n))return!1;if($l.test(e)!==$l.test(t))return!0;return kl.test(e)&&El.test(t)||kl.test(t)&&El.test(e)}function ch(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(!KR(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},c=new Map,l=(d,f,p,h,_)=>{if(d===f)return;let v=d<f?`${d}\x00${f}`:`${f}\x00${d}`,y=c.get(v);if(!y){c.set(v,{from:d,to:f,kind:p,weight:h,..._?{names:[_]}:{}});return}if(y.weight+=h,a[p]<a[y.kind])y.kind=p,y.from=d,y.to=f;if(_&&!y.names?.includes(_))y.names=[...y.names??[],_]};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 _ of p)l(d.file,_,"symbol",4/h,f)}for(let f of new Set(d.imports)){if(!n.has(f))continue;l(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(WR(p,h))l(p,h,"pair",3);else if(Dt(p)===Dt(h))l(p,h,"dir",0.25)}return VR([...c.values()])}function VR(e){return e.sort((t,n)=>n.weight-t.weight||t.from.localeCompare(n.from)||t.to.localeCompare(n.to))}function GR(e){if(!e.length)return"";let t=Dt(e[0]).split("/");for(let n of e.slice(1)){let r=Dt(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 oh(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function zR(e,t){let n=GR(e).split("/").filter(Boolean);if(e.length>1&&n.length>=3)return oh(n.slice(-2).join("-"));let r=[...e].sort((s,o)=>(t.get(o)??0)-(t.get(s)??0))[0];return oh(Al(r))||"files"}function ah(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 uh(e,t,n){let r=n.maxFiles??8,s=n.maxDirFiles??6,o=new Map(e.map((g)=>[g.file,g.tokens])),a=new Map(e.map((g,R)=>[g.file,R])),c=new Map(e.map((g,R)=>[R,new Set([g.file])])),l=new Map(e.map((g,R)=>[R,g.tokens])),u=(g,R)=>{let[P,M]=c.get(g).size>=c.get(R).size?[g,R]:[R,g];for(let C of c.get(M))a.set(C,P),c.get(P).add(C);l.set(P,l.get(P)+l.get(M)),c.delete(M),l.delete(M)},d=n.target??Math.round(n.budget*0.7),f=(g,R,P)=>l.get(g)+l.get(R)<=d&&c.get(g).size+c.get(R).size<=P,p=[[(g)=>lh.has(g.kind),r],[(g)=>g.kind==="import",r],[(g)=>g.kind==="dir",s]];for(let[g,R]of p)for(let P of t){if(!g(P))continue;let[M,C]=[a.get(P.from),a.get(P.to)];if(M===void 0||C===void 0||M===C||!f(M,C,R))continue;u(M,C)}let h=d/4,_=()=>[...c.keys()].sort((g,R)=>l.get(g)-l.get(R)||g-R);for(let g of _()){if(!c.has(g)||l.get(g)>h||c.get(g).size>2)continue;let R;for(let P of c.keys()){if(P===g||!f(g,P,s))continue;let M=0;for(let C of c.get(g))for(let N of c.get(P))M=Math.max(M,ah(Dt(C),Dt(N)));if(M>0&&(!R||M>R.depth))R={group:P,depth:M}}if(R)u(R.group,g)}JR(t,a,c,l,o,n.budget,r*2),YR(a,c,l,o);let v=(g,R=!1)=>{let P=new Map;for(let N of t){let[H,q]=[a.get(N.from),a.get(N.to)];if(H===q||H!==g&&q!==g)continue;let K=H===g?q:H;P.set(K,(P.get(K)??0)+N.weight)}let M=new Set([...c.get(g)].map(Mo)),C;for(let N of c.keys()){if(N===g||l.get(g)+l.get(N)>n.budget)continue;let H=0;for(let $e of c.get(g))for(let ie of c.get(N))H=Math.max(H,ah(Dt($e),Dt(ie)));let q=P.get(N)??0,K=[...c.get(N)].some(($e)=>M.has(Mo($e)));if(R&&!K)continue;if(!C||q>C.weight||q===C.weight&&K&&!C.sameLanguage||q===C.weight&&K===C.sameLanguage&&H>C.depth||q===C.weight&&K===C.sameLanguage&&H===C.depth&&l.get(N)<l.get(C.group))C={group:N,weight:q,sameLanguage:K,depth:H}}return C?.group};while(n.maxGroups&&c.size>n.maxGroups){let g=_()[0],R=v(g);if(R===void 0)break;u(R,g)}if(n.foldSmall!==!1)for(let g of _()){if(c.size<2)break;if(!c.has(g)||l.get(g)>h||c.get(g).size>2)continue;let R=v(g,!0);if(R!==void 0)u(R,g)}let y=[...c.values()].map((g)=>[...g].sort()).sort((g,R)=>Gr(R,o)-Gr(g,o)||g[0].localeCompare(R[0])),b=new Map,S=new Map,O=y.map((g,R)=>{for(let C of g)S.set(C,R);let P=zR(g,o),M=(b.get(P)??0)+1;return b.set(P,M),{id:M>1?`${P}-${M}`:P,files:g,tokens:Gr(g,o),links:[]}}),I=[];for(let g of t){let[R,P]=[S.get(g.from),S.get(g.to)];if(R===void 0||P===void 0)continue;if(R===P)O[R].links.push(g);else if(g.kind!=="dir")I.push(g)}return{groups:O,cut:I}}function JR(e,t,n,r,s,o,a){let c=new Map;for(let u of e){if(!lh.has(u.kind))continue;for(let d of[u.from,u.to])c.set(d,[...c.get(d)??[],u])}let l=[...c.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 l){let p=t.get(f),h=new Map;for(let y of c.get(f)){let b=y.from===f?y.to:y.from,S=t.get(b);h.set(S,(h.get(S)??0)+y.weight)}let _=h.get(p)??0,v;for(let[y,b]of h){if(y===p||b<=_||v&&b<=v.weight)continue;if(r.get(y)+s.get(f)>o||n.get(y).size+1>a)continue;v={group:y,weight:b}}if(!v)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(v.group).add(f),r.set(v.group,r.get(v.group)+s.get(f)),t.set(f,v.group),d=!0}if(!d)break}}var XR=4;function Mo(e){if(kl.test(e)||El.test(e))return"cpp";if(/\.[cm]?[jt]sx?$/.test(e))return"js";return e.slice(e.lastIndexOf(".")+1)}function YR(e,t,n,r){let s=Math.max(-1,...t.keys())+1,o=(a,c)=>{let l=s++;t.set(l,new Set(c)),n.set(l,Gr(c,r));for(let u of c)t.get(a).delete(u),e.set(u,l);return n.set(a,n.get(a)-n.get(l)),l};for(let a of[...t.keys()]){let c=[...t.get(a)].sort();if(c.length<XR)continue;let l=new Map;for(let d of c)l.set(Mo(d),[...l.get(Mo(d))??[],d]);if(l.size<2||[...l.values()].some((d)=>d.length<2))continue;let[,...u]=[...l.values()].sort((d,f)=>Gr(f,r)-Gr(d,r));for(let d of u)o(a,d)}}function Gr(e,t){return e.reduce((n,r)=>n+(t.get(r)??0),0)}function pr(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 dh(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(pr)}function fh(e,t,n,r){let s=e.map((l)=>({id:l.id,files:[...l.files],tokens:l.tokens})),o=new Map(s.map((l)=>[l.id,l])),a=new Map;for(let l of t?.groups??[]){if(typeof l?.id!=="string"||!o.has(l.id))continue;a.set(l.id,{title:typeof l.title==="string"&&l.title.trim()?l.title.trim():void 0,rationale:typeof l.rationale==="string"&&l.rationale.trim()?l.rationale.trim():void 0,priority:typeof l.priority==="number"&&Number.isFinite(l.priority)?l.priority:void 0})}let c=[];for(let l of t?.moves??[]){if(typeof l?.file!=="string"||typeof l.to!=="string")continue;let u=s.find((p)=>p.files.includes(l.file)),d=o.get(l.to);if(!u||!d||u===d||u.files.length===1)continue;let f=r.get(l.file)??0;if(d.tokens+f>n)continue;u.files=u.files.filter((p)=>p!==l.file),u.tokens-=f,d.files=[...d.files,l.file].sort(),d.tokens+=f,c.push({file:l.file,from:u.id,to:d.id,reason:typeof l.reason==="string"?l.reason:""})}return{moves:c,units:s.map((l)=>{let u=a.get(l.id);return{id:l.id,title:u?.title??l.id,...u?.rationale?{rationale:u.rationale}:{},files:l.files,...u?.priority!==void 0?{priority:u.priority}:{}}})}}async function To(e){let t=`${e.base}..${e.head}`,n=or(await dt(["diff",t,"--",...e.files]),e.base),r=await dt(["diff","--stat",t]),s=new Map([...cp(n)].map(([u,d])=>[u,Math.ceil(d/dp)])),o=await dt(["diff","--unified=0",t,"--",...e.files]),a=await sh({source:await e.source(e.files),diffU0:o,files:e.files,fileTokens:s}),c=ch(a,Wi),l=uh(a,c,{budget:jn,maxGroups:lr});return{wholeDiff:n,diffstat:r,diffU0:o,fileTokens:s,facts:a,links:c,grouping:l}}var ZR=new Set(["if","for","while","switch","return","catch","function","new","await","typeof","sizeof"]);function QR(e){for(let n of e.matchAll(/([A-Za-z_$~][\w$]*(?:::~?[A-Za-z_$][\w$]*)*)\s*(?:[(<]|=\s*(?:async\s*)?\()/g))if(!ZR.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 Fo(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 an(e)){if(!s||o.startsWith("+++ "))continue;let a=r(s),c=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@ ?(.*)$/.exec(o);if(c){let l=QR(c[2]);if(l&&!a.touches.some((u)=>u.name===l))a.touches.push({name:l,line:Number(c[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 No(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 Do(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 c=new Set,l=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,_)=>o(_)-o(h))){let h=o(p);if(h>r||f+h>u||l+h>n)continue;c.add(p),f+=h,l+=h}}for(let d of s.filter((f)=>!c.has(f)).sort((f,p)=>o(f)-o(p))){let f=o(d);if(f>r||l+f>n)continue;c.add(d),l+=f}return{shown:s.filter((d)=>c.has(d)),sketched:s.filter((d)=>!c.has(d))}}function Lo(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(pr)}function jo(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),c=r.get(o.to);if(!a||!c||a===c)continue;if(s.push(`${pr(o)} (${a} \u2192 ${c})`),s.length>=n)break}return s}Uo();import{randomBytes as i$}from"crypto";import{existsSync as s$,realpathSync as o$}from"fs";import a$ from"os";import vh from"path";function wh(e){try{return o$(e)}catch{return vh.resolve(e)}}function yh(e,t){return wh(e)===wh(t)}async function c$(e,t){await re("git",["-C",e,"worktree","remove","--force",t],{allowFail:!0}),await re("git",["-C",e,"worktree","prune"],{allowFail:!0})}async function bh(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 xh(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=vh.join(a$.tmpdir(),`code-review-subject-${n.slice(0,12)}-${process.pid}-${i$(3).toString("hex")}`);return await bh(e,t,n),await le("git",["-C",e,"worktree","add","--detach","-q",u,n]),{dir:u,release:()=>c$(e,u)}}let s=r,o=async()=>{},a=await re("git",["-C",s,"rev-parse","--show-toplevel"],{allowFail:!0}),l=a.code===0&&yh(a.stdout.trim(),s)?await re("git",["-C",s,"rev-parse","HEAD"],{allowFail:!0}):{code:1,stdout:"",stderr:""};if(l.code===0&&l.stdout.trim().startsWith(n))return{dir:s,release:o};if(await bh(e,t,n),l.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(yh(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(s$(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 le("git",["-C",e,"worktree","add","--detach","-q",s,n]),{dir:s,release:o}}import Sh from"path";function Rh(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 Bo(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/${Sh.basename(Sh.resolve(e))}`;return`${r[1]}/${r[2]}`}Gi();wt();zi();import Ve from"path";import{spawn as u$}from"child_process";import{readFileSync as d$}from"fs";import{chmod as f$,mkdir as p$,rm as h$}from"fs/promises";wt();class Lt extends Error{name="CancelledError";constructor(){super("review cancelled")}}var Ji=new Map,kh=!1;function Il(e,t){if(e.pid===void 0)return;try{process.kill(-e.pid,t)}catch{}}function m$(){for(let e of Ji.keys())Il(e,"SIGKILL")}async function Xr(e=5000){let t=[...Ji];if(!t.length)return;for(let[r]of t)Il(r,"SIGTERM");let n=setTimeout(()=>{for(let[r]of t)if(Ji.has(r))Il(r,"SIGKILL")},e);await Promise.all(t.map(([,r])=>r)),clearTimeout(n)}function g$(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(`
148
+ `)){let o=s.trim();if(!o.startsWith("{"))continue;let a;try{a=JSON.parse(o)}catch{continue}let c=a.part;if(!(c?.type==="step-finish"||c?.type==="step_finish"||a.type==="step_finish")||!c)continue;if(n+=1,n===1)r.first_step={input_tokens:c.tokens?.input??0,cache_read_input_tokens:c.tokens?.cache?.read??0,cache_creation_input_tokens:c.tokens?.cache?.write??0};t+=c.cost??0,r.input_tokens+=c.tokens?.input??0,r.output_tokens+=c.tokens?.output??0,r.reasoning_tokens+=c.tokens?.reasoning??0,r.cache_read_input_tokens+=c.tokens?.cache?.read??0,r.cache_creation_input_tokens+=c.tokens?.cache?.write??0}return{costUsd:t,numTurns:n,usage:r}}var _$=new Set(["read","tilth_tilth_read"]),w$=new Set(["grep","glob","tilth_tilth_search","tilth_tilth_files"]),y$=60;function b$(e,t=""){let n={},r=0,s=new Set,o=new Set,a=t?`${t.replace(/\/$/,"")}/`:"",c=(u)=>a&&u.startsWith(a)?u.slice(a.length):u,l=(u,d)=>{if(u.size<y$)u.add(d)};for(let u of e.split(`
149
+ `)){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(_$.has(p.tool)){let _=Array.isArray(h.paths)?h.paths:[h.path??h.filePath],v=typeof h.section==="string"?`:${h.section}`:"";for(let y of _)if(typeof y==="string")l(s,c(y)+v)}else if(w$.has(p.tool)){let _=h.query??h.pattern;if(typeof _==="string")l(o,_)}}return{calls:n,failed:r,read:[...s],searched:[...o]}}var Ol=new Map;function v$(e,t,n="repo",r){let s=`${e}\x00${t}`,o=`${n==="repo"?"shared":"no-tools"}${r?`-${r}`:""}`,a=Ol.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 c=(async()=>{let l=Ve.join(gt,"oc",o),u=Ve.join(l,"config");return await mn(Ve.join(u,"opencode.json"),S$(e,t,n)),await et(Ve.join(u,"plugin","governor.ts"),await It(Ve.join(Lr,"opencode","governor.ts"))),l})();return Ol.set(o,{home:c,key:s}),c}function qo(){Ol.clear()}function x$(e){return e.includes("/")?e:`${Wc}/${e}`}function S$(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(vo).length?{providers:vo}:{},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:Vc,system:t?`${e}
148
150
 
149
- ${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 wS(e,t){let n=t.tools??"repo",r=n==="repo"?await Ct(Ve.join(vr,"opencode","tools.md")):"",s=await mS(e,r,n,t.systemName),o=Ve.join(s,"config"),a=Ve.join(_e,"logs",`${t.tag}.usage.json`);await pn(Ve.dirname(a)),await Wt(a);let c=t.effort,l=gS(t.model);return{command:"opencode",args:["run","--standalone","--format","json","--agent","reviewer","--model",c&&!l.includes("#")?`${l}#${c}`:l,"--title",t.tag],cwd:tt,env:{PWD:tt,XDG_CONFIG_HOME:Ve.join(s,"xdg"),XDG_DATA_HOME:Ve.join(s,"data",t.tag),XDG_STATE_HOME:Ve.join(s,"state",t.tag),XDG_CACHE_HOME:Ve.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(Sc),REVIEW_GOVERNOR_OUT_FILE:t.outFile,REVIEW_GOVERNOR_LOG:Ve.join(_e,"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)=>yS(a)??uS(d),tools:(d)=>hS(d,tt)}}function yS(e){try{return JSON.parse(sS(e,"utf8"))}catch{return}}var bS=new Set(["write","edit","multiedit"]);function vS(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(`
150
- `)){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 c=a.part;if(a.type!=="tool_use"||c?.type!=="tool"||!bS.has(c.tool??""))continue;if(c.state?.status!=="completed")continue;let l=c.state.input?.path??c.state.input?.filePath;if(typeof l==="string")n.push(l)}if(t.length)return{kind:"provider",message:`the model provider returned an error (${t[0]})`};let r=n.filter((s)=>Ve.resolve(e.cwd,s)!==Ve.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(`
151
- `).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"}}async function wn(e,t){if(Sr?.aborted)throw new Dt;let n=t.system?.text??(await Ct(Ve.join(vr,"system.md"))).replaceAll("{{repo}}",mt),r=t.model??hn,s=t.effort??xr,o=await wS(n,{...t,model:r,effort:s,systemName:t.system?.name}),a={...process.env,...Ic,...o.env};for(let l of o.unsetEnv)delete a[l];let c=[o.env.XDG_DATA_HOME,o.env.XDG_STATE_HOME].filter((l)=>l!==void 0);try{return await $S(e,t,o,a)}finally{if(process.env.DIFFLOUPE_KEEP_SCRATCH!=="1")await Promise.all(c.map((l)=>cS(l,{recursive:!0,force:!0}).catch(()=>{})))}}async function xS(e,t){if(!oo||!t)return;await aS(t,{recursive:!0,mode:448}),await oS(t,448);let n=await te("opencode",["auth","import","--standalone"],{env:e,cwd:tt,input:oo,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 $S(e,t,n,r){if(Sr?.aborted)throw new Dt;if(await xS(r,n.env.XDG_DATA_HOME),Sr?.aborted)throw new Dt;if(!Hp)Hp=!0,process.on("exit",lS);let s=Date.now(),{stdout:o,stderr:a,exitCode:c}=await new Promise((h,y)=>{let v=iS(n.command,n.args,{cwd:n.cwd,env:r,stdio:["pipe","pipe","pipe"],detached:!0}),b=()=>{};Ti.set(v,new Promise((I)=>b=I));let g=()=>{Ti.delete(v),b()};v.stdin.on("error",y),v.stdin.end(e);let R=[],N=[];v.stdout.on("data",(I)=>R.push(I)),v.stderr.on("data",(I)=>N.push(I)),v.on("error",(I)=>{g(),y(I)}),v.on("close",(I,_)=>{g(),h({stdout:Buffer.concat(R).toString("utf8"),stderr:Buffer.concat(N).toString("utf8"),exitCode:I??(_?128:0)})})}),l=Date.now()-s;await Ye(Ve.join(_e,"logs",`${t.tag}.stderr.log`),a),await Ye(Ve.join(_e,"raw",`${t.tag}.${n.rawExt}`),o);let u=n.parse(o),d=n.tools?.(o),f=null,p;try{f=await br(t.outFile)}catch(h){let y=await yr(t.outFile)?h instanceof Error?h.message:String(h):void 0;p=vS({outFile:t.outFile,stdout:o,stderr:a,exitCode:c,cwd:n.cwd,parseError:y})}return{wallMs:l,exitCode:c,...u,tools:d,payload:f,failure:p}}import{createHash as ES}from"crypto";gt();Nr();function th(e){return new Map(e.filter((t)=>t.mine&&t.fingerprint&&!t.addressed).map((t)=>[t.fingerprint,t]))}var RS=4,eh=300;function nh(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,RS).map((n)=>n.length>eh?`${n.slice(0,eh-1)}\u2026`:n)}function rh(e,t){return Math.min(9,Math.max(t,0.22*e))}function ih(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)=>(yt[n.severity]?.rank??9)-(yt[r.severity]?.rank??9)||Ft[nt(n.file)]-Ft[nt(r.file)])}function sh(e,t){return e.length>0||t.some((n)=>n.mine&&n.file&&!n.addressed)}var Tn=10,al=5,Co=3,kS=/^\s*(cut for the )?cap\b/i;function cl(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",c=o.preexisting?t.maxPreexisting:t.maxNew;(s[a]<c?n:r).push(o),s[a]+=1}return{posted:n,overCap:r}}function oh(e,t,n){let r=[],s=[],o=[],a=new Set,c=new Map(n.map((l)=>[l.id,l]));for(let l of e.keep??[]){let u=t[l.id];if(!u)continue;if(a.has(l.id))continue;a.add(l.id);let d=new Set(u.cross_file_refs??[]);for(let h of l.merge_with??[]){let y=t[h];if(!y||a.has(h))continue;a.add(h),d.add(`${y.file}:${y.line}`);for(let v of y.cross_file_refs??[])d.add(v)}let f=l.repeat_of?c.get(l.repeat_of):void 0,p=f&&!f.mine&&f.file?l.repeat_of:void 0;if(l.repeat_of&&!p){let h=!f?"no such comment on this PR":f.mine?"the bot's own comment":"not a review comment, so it has no thread to reply into";console.error(` repeat_of ${l.repeat_of} on "${u.title}" ignored: ${h}`)}r.push({...u,severity:l.severity??u.severity,explanation:l.note?`${u.explanation}
151
+ ${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 R$(e,t){let n=t.tools??"repo",r=n==="repo"?await It(Ve.join(Lr,"opencode","tools.md")):"",s=await v$(e,r,n,t.systemName),o=Ve.join(s,"config"),a=Ve.join(we,"logs",`${t.tag}.usage.json`);await gn(Ve.dirname(a)),await Gt(a);let c=t.effort,l=x$(t.model);return{command:"opencode",args:["run","--standalone","--format","json","--agent","reviewer","--model",c&&!l.includes("#")?`${l}#${c}`:l,"--title",t.tag],cwd:rt,env:{PWD:rt,XDG_CONFIG_HOME:Ve.join(s,"xdg"),XDG_DATA_HOME:Ve.join(s,"data",t.tag),XDG_STATE_HOME:Ve.join(s,"state",t.tag),XDG_CACHE_HOME:Ve.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(Gc),REVIEW_GOVERNOR_OUT_FILE:t.outFile,REVIEW_GOVERNOR_LOG:Ve.join(we,"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)=>$$(a)??g$(d),tools:(d)=>b$(d,rt)}}function $$(e){try{return JSON.parse(d$(e,"utf8"))}catch{return}}var k$=new Set(["write","edit","multiedit"]);function E$(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(`
152
+ `)){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 c=a.part;if(a.type!=="tool_use"||c?.type!=="tool"||!k$.has(c.tool??""))continue;if(c.state?.status!=="completed")continue;let l=c.state.input?.path??c.state.input?.filePath;if(typeof l==="string")n.push(l)}if(t.length)return{kind:"provider",message:`the model provider returned an error (${t[0]})`};let r=n.filter((s)=>Ve.resolve(e.cwd,s)!==Ve.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(`
153
+ `).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"}}async function vn(e,t){if(Br?.aborted)throw new Lt;let n=t.system?.text??(await It(Ve.join(Lr,"system.md"))).replaceAll("{{repo}}",_t),r=t.model??_n,s=t.effort??jr,o=await R$(n,{...t,model:r,effort:s,systemName:t.system?.name}),a={...process.env,...Qc,...o.env};for(let l of o.unsetEnv)delete a[l];let c=[o.env.XDG_DATA_HOME,o.env.XDG_STATE_HOME].filter((l)=>l!==void 0);try{return await C$(e,t,o,a)}finally{if(process.env.DIFFLOUPE_KEEP_SCRATCH!=="1")await Promise.all(c.map((l)=>h$(l,{recursive:!0,force:!0}).catch(()=>{})))}}async function A$(e,t){if(!xo||!t)return;await p$(t,{recursive:!0,mode:448}),await f$(t,448);let n=await re("opencode",["auth","import","--standalone"],{env:e,cwd:rt,input:xo,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 C$(e,t,n,r){if(Br?.aborted)throw new Lt;if(await A$(r,n.env.XDG_DATA_HOME),Br?.aborted)throw new Lt;if(!kh)kh=!0,process.on("exit",m$);let s=Date.now(),{stdout:o,stderr:a,exitCode:c}=await new Promise((h,_)=>{let v=u$(n.command,n.args,{cwd:n.cwd,env:r,stdio:["pipe","pipe","pipe"],detached:!0}),y=()=>{};Ji.set(v,new Promise((I)=>y=I));let b=()=>{Ji.delete(v),y()};v.stdin.on("error",_),v.stdin.end(e);let S=[],O=[];v.stdout.on("data",(I)=>S.push(I)),v.stderr.on("data",(I)=>O.push(I)),v.on("error",(I)=>{b(),_(I)}),v.on("close",(I,g)=>{b(),h({stdout:Buffer.concat(S).toString("utf8"),stderr:Buffer.concat(O).toString("utf8"),exitCode:I??(g?128:0)})})}),l=Date.now()-s;await et(Ve.join(we,"logs",`${t.tag}.stderr.log`),a),await et(Ve.join(we,"raw",`${t.tag}.${n.rawExt}`),o);let u=n.parse(o),d=n.tools?.(o),f=null,p;try{f=await Dr(t.outFile)}catch(h){let _=await Nr(t.outFile)?h instanceof Error?h.message:String(h):void 0;p=E$({outFile:t.outFile,stdout:o,stderr:a,exitCode:c,cwd:n.cwd,parseError:_})}return{wallMs:l,exitCode:c,...u,tools:d,payload:f,failure:p}}import{createHash as M$}from"crypto";wt();Zr();function Lh(e){return new Map(e.filter((t)=>t.mine&&t.fingerprint&&!t.addressed).map((t)=>[t.fingerprint,t]))}var O$=4,Dh=300;function jh(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,O$).map((n)=>n.length>Dh?`${n.slice(0,Dh-1)}\u2026`:n)}function Uh(e,t){return Math.min(9,Math.max(t,0.22*e))}function Bh(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)=>(vt[n.severity]?.rank??9)-(vt[r.severity]?.rank??9)||jt[it(n.file)]-jt[it(r.file)])}function qh(e,t){return e.length>0||t.some((n)=>n.mine&&n.file&&!n.addressed)}var Hn=10,Pl=5,Wo=3,P$=/^\s*(cut for the )?cap\b/i;function Ml(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",c=o.preexisting?t.maxPreexisting:t.maxNew;(s[a]<c?n:r).push(o),s[a]+=1}return{posted:n,overCap:r}}function Hh(e,t,n){let r=[],s=[],o=[],a=new Set,c=new Map(n.map((l)=>[l.id,l]));for(let l of e.keep??[]){let u=t[l.id];if(!u)continue;if(a.has(l.id))continue;a.add(l.id);let d=new Set(u.cross_file_refs??[]);for(let h of l.merge_with??[]){let _=t[h];if(!_||a.has(h))continue;a.add(h),d.add(`${_.file}:${_.line}`);for(let v of _.cross_file_refs??[])d.add(v)}let f=l.repeat_of?c.get(l.repeat_of):void 0,p=f&&!f.mine&&f.file?l.repeat_of:void 0;if(l.repeat_of&&!p){let h=!f?"no such comment on this PR":f.mine?"the bot's own comment":"not a review comment, so it has no thread to reply into";console.error(` repeat_of ${l.repeat_of} on "${u.title}" ignored: ${h}`)}r.push({...u,severity:l.severity??u.severity,explanation:l.note?`${u.explanation}
152
154
 
153
- ${l.note}`:u.explanation,cross_file_refs:d.size?[...d]:void 0,repeat_of:p,preexisting:typeof l.preexisting==="boolean"?l.preexisting:u.preexisting})}for(let l of e.drop??[]){let u=t[l.id];if(u&&!a.has(l.id))if(a.add(l.id),kS.test(l.reason??""))o.push({...u,repeat_of:void 0});else s.push({title:u.title,reason:l.reason})}return t.forEach((l,u)=>{if(!a.has(u))s.push({title:l.title,reason:"coordinator did not rule on this finding"})}),{kept:r,dropped:s,capped:o}}var ah="cited line is outside the changed hunks",lh="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.",AS=`
155
+ ${l.note}`:u.explanation,cross_file_refs:d.size?[...d]:void 0,repeat_of:p,preexisting:typeof l.preexisting==="boolean"?l.preexisting:u.preexisting})}for(let l of e.drop??[]){let u=t[l.id];if(u&&!a.has(l.id))if(a.add(l.id),P$.test(l.reason??""))o.push({...u,repeat_of:void 0});else s.push({title:u.title,reason:l.reason})}return t.forEach((l,u)=>{if(!a.has(u))s.push({title:l.title,reason:"coordinator did not rule on this finding"})}),{kept:r,dropped:s,capped:o}}var Kh="cited line is outside the changed hunks",Vh="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.",T$=`
154
156
  Calibrated uncertainty \u2014 this matters as much as finding bugs:
155
157
  - 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.
156
158
  - 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.
157
159
  - 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.
158
- `.trim(),CS=`
160
+ `.trim(),F$=`
159
161
  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).
160
162
 
161
163
  Scope and priorities:
@@ -177,15 +179,15 @@ Do not report:
177
179
  - Missing defense in depth when the input is already validated or the case is already handled elsewhere.
178
180
  - 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.
179
181
  - Generic advice with no concrete defect behind it: "consider using library X", "consider adding error handling", "this could be refactored".
180
- `.trim();function uh(e){let t=e?.trim();return t?`
182
+ `.trim();function Gh(e){let t=e?.trim();return t?`
181
183
 
182
184
  ## Instructions for reviewing this repository
183
185
  The maintainers wrote these for this repository. Follow them; where they conflict with the general guidance above, they win.
184
186
 
185
- ${t}`:""}function ll(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 Dr(e,t){let n=e.stated?.trim().slice(0,t);return n?`
187
+ ${t}`:""}function Tl(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 Qr(e,t){let n=e.stated?.trim().slice(0,t);return n?`
186
188
 
187
189
  Stated by the requester:
188
- ${n}`:""}var ch={title:"t",goal:"g",expected_changes:["e"]};function ul(e){if(!e)return"";let t=e.expected_changes.map((n)=>`- ${n}`).join(`
190
+ ${n}`:""}var Wh={title:"t",goal:"g",expected_changes:["e"]};function Fl(e){if(!e)return"";let t=e.expected_changes.map((n)=>`- ${n}`).join(`
189
191
  `);return`## Inferred intent (drafted by a smaller model from the whole diff; it may be wrong, so check it against the code)
190
192
  Title: ${e.title}
191
193
  ${e.goal}${t?`
@@ -193,9 +195,9 @@ ${e.goal}${t?`
193
195
  Expected changes:
194
196
  ${t}`:""}
195
197
 
196
- `}var Io=`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.
198
+ `}var Vo=`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.
197
199
 
198
- You have no tools except writing your answer. Everything you need is in the message.`;function Oo(e){let t=e.branch?`Branch: ${e.branch}
200
+ You have no tools except writing your answer. Everything you need is in the message.`;function Go(e){let t=e.branch?`Branch: ${e.branch}
199
201
 
200
202
  `:"",n=e.otherFiles.length?`
201
203
 
@@ -204,7 +206,7 @@ ${e.otherFiles.map((r)=>`- ${r}`).join(`
204
206
  `)}`:"";return`${t}## Pull request description
205
207
  Title: ${e.intent.title||"(none)"}
206
208
 
207
- ${e.intent.body.slice(0,4000)||"(none)"}${Dr(e.intent,4000)}
209
+ ${e.intent.body.slice(0,4000)||"(none)"}${Qr(e.intent,4000)}
208
210
 
209
211
  ## Commit messages (oldest last)
210
212
  ${e.intent.commits.slice(0,6000)||"(none)"}
@@ -225,9 +227,9 @@ Write a single JSON object to \`${e.outFile}\` with the write tool, and do nothi
225
227
  "goal": "2-4 sentences: what the change is for and the main approach",
226
228
  "expected_changes": ["each distinct piece of work the change contains"]
227
229
  }
228
- \`\`\``}function dl(e){let t=e.unit.files.map((s)=>`\`${s}\``).join(", "),n=e.sinceLast?`
230
+ \`\`\``}function Nl(e){let t=e.unit.files.map((s)=>`\`${s}\``).join(", "),n=e.sinceLast?`
229
231
  ## Changes since the last review
230
- This change was reviewed before, and the earlier findings are listed above. ${lh}
232
+ This change was reviewed before, and the earlier findings are listed above. ${Vh}
231
233
  \`\`\`diff
232
234
  ${e.sinceLast}
233
235
  \`\`\`
@@ -235,11 +237,11 @@ ${e.sinceLast}
235
237
 
236
238
  These changed files are linked to files that another reviewer has. That reviewer is checking the other side, so check the contract from yours \u2014 that each name used here matches what the other file now defines, and each definition here suits how the other file uses it:
237
239
  ${e.crossLinks.map((s)=>`- ${s}`).join(`
238
- `)}`:"";return`You are reviewing one coherent part of a pull request in the ${mt} repository.
240
+ `)}`:"";return`You are reviewing one coherent part of a pull request in the ${_t} repository.
239
241
 
240
- ${CS}${uh(e.instructions)}
242
+ ${F$}${Gh(e.instructions)}
241
243
 
242
- ${AS}
244
+ ${T$}
243
245
 
244
246
  This is ONE SLICE of a larger pull request: **${e.unit.title}**. ${e.unit.rationale??""}
245
247
 
@@ -250,12 +252,12 @@ Other changed files in this pull request are being reviewed separately; do not c
250
252
  ## Pull request intent (as stated by the author)
251
253
  Title: ${e.intent.title}
252
254
 
253
- ${ll(e.intent,4000)}${Dr(e.intent,4000)}
255
+ ${Tl(e.intent,4000)}${Qr(e.intent,4000)}
254
256
 
255
257
  Commit messages:
256
258
  ${e.intent.commits.slice(0,3000)||"(none)"}
257
259
 
258
- ${ul(e.draft)}${e.mapNote}${e.registry?`
260
+ ${Fl(e.draft)}${e.mapNote}${e.registry?`
259
261
  ${e.registry}
260
262
  `:""}${e.prior?`
261
263
  ${e.prior}
@@ -265,10 +267,10 @@ ${e.prior}
265
267
  ${e.diff}
266
268
  \`\`\`
267
269
  ${n}
268
- Write your findings as JSON to \`${e.outFile}\`. Write the file even if you have no findings (use an empty array).`}function fl(e){let t=e.sinceLast?`
270
+ Write your findings as JSON to \`${e.outFile}\`. Write the file even if you have no findings (use an empty array).`}function Dl(e){let t=e.sinceLast?`
269
271
  ## This is a re-review
270
- This change was reviewed before. Only these files changed since then, and only they were reviewed again: ${e.sinceLast.map((r)=>`\`${r}\``).join(", ")}. ${lh} Earlier findings in files that did not change stay open on their own; do not close them out as resolved.
271
- `:"",n=e.findings.map((r,s)=>{let o=e.changedLines&&no(e.changedLines,r.file,r.line,r.end_line).kind!=="anchorable";return{...r,id:s,...o?{hint:ah}:{}}});return`You are the coordinator for a code review of a pull request in ${mt}. Independent reviewers each looked at one changed file. Your job is to turn their raw findings into the review that actually gets posted.${uh(e.instructions)}
272
+ This change was reviewed before. Only these files changed since then, and only they were reviewed again: ${e.sinceLast.map((r)=>`\`${r}\``).join(", ")}. ${Vh} Earlier findings in files that did not change stay open on their own; do not close them out as resolved.
273
+ `:"",n=e.findings.map((r,s)=>{let o=e.changedLines&&wo(e.changedLines,r.file,r.line,r.end_line).kind!=="anchorable";return{...r,id:s,...o?{hint:Kh}:{}}});return`You are the coordinator for a code review of a pull request in ${_t}. Independent reviewers each looked at one changed file. Your job is to turn their raw findings into the review that actually gets posted.${Gh(e.instructions)}
272
274
 
273
275
  ## Changed files
274
276
  ${e.files.map((r)=>`- ${r}`).join(`
@@ -277,12 +279,12 @@ ${e.files.map((r)=>`- ${r}`).join(`
277
279
  ## Pull request intent (as stated by the author)
278
280
  Title: ${e.intent.title}
279
281
 
280
- ${ll(e.intent,4000)}${Dr(e.intent,4000)}
282
+ ${Tl(e.intent,4000)}${Qr(e.intent,4000)}
281
283
 
282
284
  Commit messages:
283
285
  ${e.intent.commits.slice(0,3000)||"(none)"}
284
286
  ${e.draft?`
285
- ${ul(e.draft).trimEnd()}
287
+ ${Fl(e.draft).trimEnd()}
286
288
  `:""}${e.prior?`
287
289
  ${e.prior}
288
290
  `:""}${t}
@@ -312,9 +314,9 @@ Do all of the following:
312
314
 
313
315
  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.":""}
314
316
 
315
- 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": "${ah}"\`. 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.
317
+ 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": "${Kh}"\`. 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.
316
318
 
317
- 8. **Cap.** Keep at most ${e.maxNew??Tn} new findings on the change, and at most ${Co} 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.
319
+ 8. **Cap.** Keep at most ${e.maxNew??Hn} new findings on the change, and at most ${Wo} 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.
318
320
 
319
321
  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.
320
322
 
@@ -332,14 +334,14 @@ Write a single JSON object to \`${e.outFile}\`:
332
334
  }
333
335
  }
334
336
  \`\`\`
335
- \`severity\`, \`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. Write the file even if \`keep\` is empty.`}function dh(e){return ES("sha256").update(e).digest("hex").slice(0,12)}function fh(e){let t={title:"t",body:"b",commits:"c",stated:"s"},r=[e,dl({unit:{id:"u",title:"u",files:["f"]},diff:"d",intent:t,draft:ch,registry:"",prior:"",mapNote:"",outFile:"o"}),fl({findings:[],intent:t,draft:ch,files:["f"],prior:"",outFile:"o"}),Io,Oo({intent:t,diffstat:"s",diff:"d",otherFiles:[],outFile:"o"})].map((s)=>s.replaceAll(mt,"{{repo}}"));return dh(r.join("\x00"))}function ph(e){let t=e?.trim();return t?dh(t):void 0}function pl(e,t){let n=new Set,r=[];for(let o of e){let a=(o.files??[]).filter((c)=>t.includes(c)&&!n.has(c));for(let c of a)n.add(c);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 hh(e,t,n){let r=[];for(let s of e){let o=[...s.files].sort((c,l)=>(t.get(l)??0)-(t.get(c)??0)||c.localeCompare(l)),a=[];for(let c of o){let l=t.get(c)??0,u=a.find((d)=>d.tokens+l<=n);if(u)u.files.push(c),u.tokens+=l;else a.push({files:[c],tokens:l})}a.forEach((c,l)=>{r.push({unitId:s.id,title:a.length>1?`${s.title} (part ${l+1} of ${a.length})`:s.title,rationale:s.rationale,priority:s.priority,files:[...c.files].sort(),part:l+1,parts:a.length,tokens:c.tokens})})}return r}function mh(e){return`You are planning how to split up the review of a pull request in ${mt}. You are not reviewing anything and you are not looking for bugs. You are deciding which changed files each reviewer should see together.
337
+ \`severity\`, \`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. Write the file even if \`keep\` is empty.`}function zh(e){return M$("sha256").update(e).digest("hex").slice(0,12)}function Jh(e){let t={title:"t",body:"b",commits:"c",stated:"s"},r=[e,Nl({unit:{id:"u",title:"u",files:["f"]},diff:"d",intent:t,draft:Wh,registry:"",prior:"",mapNote:"",outFile:"o"}),Dl({findings:[],intent:t,draft:Wh,files:["f"],prior:"",outFile:"o"}),Vo,Go({intent:t,diffstat:"s",diff:"d",otherFiles:[],outFile:"o"})].map((s)=>s.replaceAll(_t,"{{repo}}"));return zh(r.join("\x00"))}function Xh(e){let t=e?.trim();return t?zh(t):void 0}function Ll(e,t){let n=new Set,r=[];for(let o of e){let a=(o.files??[]).filter((c)=>t.includes(c)&&!n.has(c));for(let c of a)n.add(c);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 Yh(e,t,n){let r=[];for(let s of e){let o=[...s.files].sort((c,l)=>(t.get(l)??0)-(t.get(c)??0)||c.localeCompare(l)),a=[];for(let c of o){let l=t.get(c)??0,u=a.find((d)=>d.tokens+l<=n);if(u)u.files.push(c),u.tokens+=l;else a.push({files:[c],tokens:l})}a.forEach((c,l)=>{r.push({unitId:s.id,title:a.length>1?`${s.title} (part ${l+1} of ${a.length})`:s.title,rationale:s.rationale,priority:s.priority,files:[...c.files].sort(),part:l+1,parts:a.length,tokens:c.tokens})})}return r}function Zh(e){return`You are planning how to split up the review of a pull request in ${_t}. You are not reviewing anything and you are not looking for bugs. You are deciding which changed files each reviewer should see together.
336
338
 
337
339
  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.
338
340
 
339
341
  ## Stated intent
340
342
  Title: ${e.intent.title}
341
343
 
342
- ${e.intent.body?.slice(0,2000)||"(no description)"}${Dr(e.intent,2000)}
344
+ ${e.intent.body?.slice(0,2000)||"(no description)"}${Qr(e.intent,2000)}
343
345
 
344
346
  ## Files changed
345
347
  ${e.diffstat}
@@ -367,15 +369,15 @@ Write only this JSON to \`${e.outFile}\`:
367
369
  { "review_units": [ { "id": "short-slug", "title": "a few words naming the mechanism, not the paths",
368
370
  "rationale": "one sentence the reviewer will read as their brief: what this group does and what would break",
369
371
  "files": ["..."], "priority": 1 } ] }
370
- \`\`\``}function gh(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)=>` - ${tr(a)}`);return[`### ${s.id} (${s.tokens} diff tokens)`,...s.files.map((a)=>`- ${a}`),...o.length?["Linked by:",...o]:[]].join(`
371
- `)}),r=e.links.filter((s)=>s.kind!=="dir"&&t.get(s.from)!==t.get(s.to)).slice(0,20).map((s)=>`- ${tr(s)} (${t.get(s.from)} \u2192 ${t.get(s.to)})`);return`You are preparing the review of a pull request in ${mt}. 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.
372
+ \`\`\``}function Qh(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)=>` - ${pr(a)}`);return[`### ${s.id} (${s.tokens} diff tokens)`,...s.files.map((a)=>`- ${a}`),...o.length?["Linked by:",...o]:[]].join(`
373
+ `)}),r=e.links.filter((s)=>s.kind!=="dir"&&t.get(s.from)!==t.get(s.to)).slice(0,20).map((s)=>`- ${pr(s)} (${t.get(s.from)} \u2192 ${t.get(s.to)})`);return`You are preparing the review of a pull request in ${_t}. 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.
372
374
 
373
375
  Work from what is below. **Do not read files from the repository.**
374
376
 
375
377
  ## Stated intent
376
378
  Title: ${e.intent.title}
377
379
 
378
- ${e.intent.body?.slice(0,2000)||"(no description)"}${Dr(e.intent,2000)}
380
+ ${e.intent.body?.slice(0,2000)||"(no description)"}${Qr(e.intent,2000)}
379
381
  ${e.registry?`
380
382
  ${e.registry}
381
383
  `:""}
@@ -405,18 +407,18 @@ Write only this JSON to \`${e.outFile}\`:
405
407
  \`\`\`json
406
408
  { "groups": [ { "id": "group id from above", "title": "...", "rationale": "...", "priority": 1 } ],
407
409
  "moves": [ { "file": "path", "to": "group id", "reason": "one sentence" } ] }
408
- \`\`\``}function IS(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(`
409
- `)}function Po(e){let t=e.findingIndex!==void 0;return`${t?`You are writing the reviewer's guide for a pull request in ${mt}: 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 ${mt}: 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.`}
410
+ \`\`\``}function N$(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(`
411
+ `)}function zo(e){let t=e.findingIndex!==void 0;return`${t?`You are writing the reviewer's guide for a pull request in ${_t}: 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 ${_t}: 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.`}
410
412
 
411
413
  ## Stated description (what the author says it does)
412
414
  Title: ${e.intent.title}
413
415
 
414
- ${ll(e.intent,4000)}${Dr(e.intent,4000)}
416
+ ${Tl(e.intent,4000)}${Qr(e.intent,4000)}
415
417
 
416
418
  Commit messages:
417
419
  ${e.intent.commits.slice(0,3000)||"(none)"}
418
420
 
419
- ${ul(e.draft)}## Files changed
421
+ ${Fl(e.draft)}## Files changed
420
422
  ${e.diffstat}
421
423
 
422
424
  ## ${t?"How the review was split up":"How the files are grouped"}
@@ -433,14 +435,14 @@ ${t?`## What the reviewers found
433
435
  ${e.findingIndex||"(nothing)"}
434
436
 
435
437
  `:""}${e.docsFiles.length?`## Documentation-only files (${t?"already excluded from review; ":""}cover them with one \`support\` group)
436
- ${IS(e.docsFiles)}
438
+ ${N$(e.docsFiles)}
437
439
  `:""}${e.registry?`
438
440
  ${e.registry}
439
441
  `:""}
440
442
  ## Diff
441
443
  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.
442
444
  \`\`\`diff
443
- ${Rf(e.diff)}
445
+ ${ap(e.diff)}
444
446
  \`\`\`
445
447
  ${e.sketches.length?`
446
448
  ## Changed files whose diff is not shown above (${e.sketches.length})
@@ -474,142 +476,161 @@ Write a single JSON object to \`${e.outFile}\`:
474
476
  }
475
477
  \`\`\`
476
478
 
477
- 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.`}Nr();import Di from"path";Pi();function Ni(e,t=""){let n=e.match(/`+/g)??[],r=Math.max(3,...n.map((o)=>o.length+1)),s="`".repeat(r);return`${s}${t}
479
+ 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.`}Zr();import Xi from"path";Gi();function ei(e,t=""){let n=e.match(/`+/g)??[],r=Math.max(3,...n.map((o)=>o.length+1)),s="`".repeat(r);return`${s}${t}
478
480
  ${e.replace(/\n$/,"")}
479
- ${s}`}function Fr(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}`}gt();Nr();Eo();var OS={high:"\uD83D\uDD34",moderate:"\uD83D\uDFE1",low:"\uD83D\uDFE2"};function PS(e){let t=e.repo??mt,n=(w,B)=>`https://github.com/${t}/blob/${e.head}/${w}${B?`#L${B}`:""}`,r=(w,B,de)=>{let F=de??`${w.split("/").pop()}${B?`:${B}`:""}`;if(!e.pr)return F.includes("`")?F:`\`${F}\``;return`[${F}](${n(w,B)})`},s=[...e.findings].sort((w,B)=>(yt[w.severity]?.rank??9)-(yt[B.severity]?.rank??9)||Ft[nt(w.file)]-Ft[nt(B.file)]||Tr.indexOf(w.confidence)-Tr.indexOf(B.confidence)),o=s.filter((w)=>w.repeat_of),a=s.filter((w)=>!w.repeat_of),c=a.filter((w)=>w._anchor?.kind!=="off-diff"),l=new Map((e.prior??[]).map((w)=>[w.id,w])),u=er("summary",{...e.pr?{pr:e.pr}:{},...e.runs?{runs:e.runs}:{}}),d=a.reduce((w,B)=>(w[B.severity]=(w[B.severity]??0)+1,w),{}),f=(w,B,de)=>{let F=[],xe=yt[w.severity]?.badge??w.severity,pe=Qp[w.category]??w.category,A=w.end_line&&w.end_line!==w.line?`-${w.end_line}`:"",X=B==="summary"?r(w.file,w.line,`${w.file}:${w.line}${A}`):`\`${w.file}:${w.line}${A}\``;if(F.push(`${B==="summary"?"#####":"####"} ${de??w.title}`),F.push(""),F.push([xe,pe,Yp[w.effort??""],`confidence: ${w.confidence}`,X,Xp[nt(w.file)],w.preexisting?"pre-existing":""].filter(Boolean).join(" \xB7 ")),B==="inline"&&w._anchor?.kind==="off-hunk")F.push(""),F.push(`> Posted here because GitHub only accepts comments on changed lines. The code this is about is at \`${w.file}:${w.line}${A}\`.`);if(F.push(""),F.push(w.impact?.trim()||Ao(w.explanation)),w.explanation)F.push(""),F.push("<details><summary>Why this is a problem</summary>"),F.push(""),F.push(w.explanation),F.push(""),F.push("</details>");if(w.evidence||w.cross_file_refs?.length){if(F.push(""),F.push("<details><summary>Evidence</summary>"),F.push(""),w.evidence)F.push(w.evidence);if(w.cross_file_refs?.length){F.push(""),F.push("Also read:");for(let V of w.cross_file_refs)F.push(`- \`${V}\``)}F.push(""),F.push("</details>")}if(w.suggested_code){if(w._original!==void 0){let Ne=w._original.replace(/\n$/,"").split(`
480
- `).map((He)=>`-${He}`),pt=w.suggested_code.replace(/\n$/,"").split(`
481
- `).map((He)=>`+${He}`);F.push(""),F.push("<details><summary>What this changes</summary>"),F.push(""),F.push(Ni([...Ne,...pt].join(`
482
- `),"diff")),F.push(""),F.push("</details>")}F.push("");let V=B==="inline"&&Zp(w);if(V)F.push("_Applying this commits it as written \u2014 read it first._"),F.push("");else if(B==="inline"){let Ne=w.end_line&&w.end_line!==w.line?`${w.line}-${w.end_line}`:`${w.line}`;F.push(`_Replaces ${Fr(`${w.file}:${Ne}`)}. Not offered as a committable suggestion because this comment is anchored elsewhere._`),F.push("")}F.push(Ni(w.suggested_code,V?"suggestion":""))}else if(w.suggestion)F.push(""),F.push(`_Suggested fix:_ ${w.suggestion}`);return F.push(""),F.push(B==="inline"?er("inline",{file:w.file,line:w.line,fp:Jt(w.file,w.title)}):er("summary-item",{file:w.file,line:w.line,fp:Jt(w.file,w.title)})),F.join(`
483
- `)},p=(w)=>w.replace(/\s+/g," ").trim(),h=Jp(e.changedFiles??[],a),y=(w)=>Ft[nt(w.file)]<=Ft[h],v=a.filter(y),b=a.filter((w)=>!y(w)),g=(e.inlineMode??"none")==="none"?[]:c.filter(y),R=new Set(g),N=[...v,...b],I=new Map;for(let w of N)I.set(w,I.size+1);let _=[];_.push(`### Review of \`${e.head.slice(0,12)}\``),_.push("");let S=e.unreviewed?.overCap??[],O=e.unreviewed?.failed??[],P=e.unreviewed?.budget??[],C=S.length+O.length+P.length>0;if(C){let w=[S.length?`${S.length} over the slice cap`:"",O.length?`${O.length} in a reviewer that failed`:"",P.length?`${P.length} skipped at the cost limit`:""].filter(Boolean),B=[...O,...P,...S],de=B.slice(0,5).map((xe)=>`\`${xe}\``).join(", "),F=B.length>5?`, and ${B.length-5} more`:"";_.push(`\u26A0\uFE0F **Partial review:** ${B.length} changed code ${B.length===1?"file was":"files were"} not reviewed (${w.join(", ")}): ${de}${F}.`),_.push("")}if(a.length===0)_.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.":C?"No new issues found in the reviewed files.":"No new issues found in the changed files.");else{let w=(B)=>`${OS[B.level]} **${B.label}** \u2014 ${B.detail}`;_.push(w(Vp(a))),_.push(""),_.push(w(Gp(a.map((B)=>({severity:B.severity,preexisting:B.preexisting,surface:nt(B.file)}))))),_.push(""),_.push(Object.entries(yt).filter(([B])=>d[B]).map(([B,de])=>`${de.badge}: ${d[B]}`).join(" \xB7 "))}_.push("");let j=e.walkthrough,H=j?.intent,U=e.intentAlignment,q={aligned:"\u2705 Matches the description",partial:"\u26A0\uFE0F Partly matches the description",misaligned:"\u274C Does not match the description"},Ee=[...H?.unstated??[],...U?.unstated??[]],we=[...H?.missing??[],...U?.missing??[]],ce=H?.alignment==="aligned"&&U?.summary?"partial":H?.alignment,Te=ce?q[ce]:void 0,qe=U?.summary??H?.mismatches?.[0],he=[],K=[];if(K.push(`# Review of \`${e.head.slice(0,12)}\`${e.pr?` \u2014 PR #${e.pr}`:""}`),K.push(""),K.push("Everything the summary comment links to rather than carries."),K.push(""),Te||qe||H?.inferred||Ee.length||we.length){if(he.push(`**Intent:** ${Te??"\u2139\uFE0F Not assessed"}${qe?` \u2014 ${qe}`:""}`),H?.inferred)he.push("",`**What it does:** ${Ao(H.inferred,320)}`);if(he.push(""),K.push("## What the change actually does, read from the code"),K.push(""),H?.inferred)K.push(H.inferred,"");if(H?.matches?.length){K.push("Description holds up on:");for(let w of H.matches)K.push(`- ${w}`);K.push("")}if(H?.mismatches?.length){K.push("Description does not hold up on:");for(let w of H.mismatches)K.push(`- ${w}`);K.push("")}if(Ee.length){K.push("In the diff but not in the description:");for(let w of Ee)K.push(`- ${w}`);K.push("")}if(we.length){K.push("Described but not accomplished:");for(let w of we)K.push(`- ${w}`);K.push("")}}if(j?.focus)he.push(`**What to focus on:** ${j.focus}`,"");let ye=j?.chapters??[],ve=ye.reduce((w,B)=>w+(B.stops?.length??0),0);if(j?.start_here?.length||ve){let w={bug:"\uD83D\uDC1B",wrench:"\uD83D\uDD27",path:"\uD83D\uDEE4\uFE0F",flask:"\uD83E\uDDEA",doc:"\uD83D\uDCC4",gear:"\u2699\uFE0F"},B={critical:" \uD83D\uDD34",normal:"",context:" _(context)_"};if(j?.start_here?.length){he.push("**Start here**"),he.push("");for(let F of j.start_here)he.push(`1. ${r(F.file,void 0,`\`${F.file}\``)} \u2014 ${F.why}`);he.push("")}if(ve||j?.support?.length)K.push(`## Guided walkthrough \u2014 ${ye.length} ${ye.length===1?"part":"parts"}, ${ve} ${ve===1?"stop":"stops"}`),K.push("");let de=0;for(let F of ye){if(K.push(`### ${w[F.icon??""]??"\u25B8"} ${F.title}`),F.blurb)K.push("",`_${F.blurb}_`);K.push("");for(let xe of F.stops??[]){if(de++,K.push(`**${de}. ${xe.title}**${B[xe.importance??"normal"]??""}`),xe.prose)K.push("",xe.prose);if(xe.locations?.length)K.push("",`\u21B3 ${xe.locations.map((pe)=>r(pe.file,pe.line,pe.label)).join(" \xB7 ")}`);K.push("")}}if(j?.support?.length){K.push("### Safe to skim"),K.push("");for(let F of j.support){let xe=F.files.map((pe)=>`\`${pe}\``).join(", ");K.push(`- ${xe} \u2014 ${F.reason}`)}K.push("")}}let st=(w)=>{let B=new Map;for(let F of w){let xe=B.get(F.file);if(xe)xe.push(F);else B.set(F.file,[F])}let de=[];for(let[F,xe]of B){de.push(`- \`${F}\``);for(let pe of xe){let A=yt[pe.severity]?.badge??pe.severity,X=pe._anchor?.kind==="off-diff"?`${r(pe.file,pe.line,`L${pe.line}`)} \uD83D\uDCCE outside the diff`:r(pe.file,pe.line,`L${pe.line}`),V=R.has(pe)?"":` ${er("summary-item",{file:pe.file,line:pe.line,fp:Jt(pe.file,pe.title)})}`;de.push(` - ${A} ${p(pe.title)} \u2014 ${X} \xB7 _[${I.get(pe)}]_${V}`)}}return de};if(v.length)_.push(`#### ${Wp[h]} (${v.length})`),_.push(""),_.push(...st(v)),_.push("");if(b.length)_.push(`<details><summary>Everything else (${b.length}) \u2014 lower-risk surfaces</summary>`),_.push(""),_.push(...st(b)),_.push(""),_.push("</details>"),_.push("");let Ae=e.overCap??[];if(Ae.length)_.push(`\u2795 ${Ae.length} more ${Ae.length===1?"finding":"findings"} past the ${Tn}-finding cap,`+" listed under \u201CPast the cap\u201D in the detail file."),_.push("");let Le=e.checked??[];if(_.push(...he),o.length){_.push(`<details><summary>Agreeing with ${o.length} existing review ${o.length===1?"comment":"comments"}</summary>`),_.push("");for(let w of o){let B=l.get(w.repeat_of),de=B?`@${B.author}`:"an earlier review comment",F=B?.url?`[${de}](${B.url})`:de,xe=yt[w.severity]?.badge??w.severity;_.push(`- ${xe} ${p(w.title)} \u2014 \`${w.file}:${w.line}\` _\u2014 agrees with ${F}_`)}_.push(""),_.push("</details>"),_.push("")}if(N.length){K.push("## Evidence and reasoning"),K.push(""),K.push("Numbered to match the bullets in the summary comment."),K.push("");for(let w of N)K.push(f(w,"summary",`[${I.get(w)}] ${p(w.title)}`)),K.push("")}if(Ae.length){K.push("## Past the cap"),K.push(""),K.push(`Findings the review kept but did not post, because a review posts at most ${Tn}. Ranked below the posted ones by severity, surface and confidence.`),K.push("");for(let w of Ae)K.push(f(w,"summary",p(w.title))),K.push("")}if(Le.length){K.push("## What the reviewers checked"),K.push(""),K.push("Claims each reviewer verified against the code and found correct."),K.push("");for(let w of Le)K.push(`- ${w}`);K.push("")}let Qe=process.env.GITHUB_RUN_ID,T=process.env.GITHUB_SERVER_URL??"https://github.com",D=e.detailFile??"review-detail.md";if(N.length||ve||Ae.length||Le.length>8)_.push(Qe?`\uD83D\uDCC4 **[Full review detail](${T}/${t}/actions/runs/${Qe})** \u2014 download the`+` \`ai-code-review-${e.pr}-${e.head.slice(0,9)}\` artifact and open \`${D}\` for the walkthrough and the evidence behind each finding. Artifacts expire 90 days after the run.`:`\uD83D\uDCC4 Full walkthrough and evidence: \`${e.detailPath??D}\`.`),_.push("");if(Le.length&&a.length<=2&&!e.noReviewers){_.push(`<details><summary>What the reviewers checked (${Le.length})</summary>`),_.push("");for(let w of Le.slice(0,8))_.push(`- ${w}`);if(Le.length>8)_.push(`- \u2026and ${Le.length-8} more in the detail file`);_.push(""),_.push("</details>"),_.push("")}if(e.dropped?.length){_.push("<details><summary>Findings considered and dropped during verification</summary>"),_.push("");for(let w of e.dropped)_.push(`- **${w.title}** \u2014 ${w.reason}`);_.push(""),_.push("</details>"),_.push("")}_.push("<details><summary>Review details</summary>"),_.push("");for(let[w,B]of Object.entries(e.stats))_.push(`- ${w}: ${B}`);if(_.push(""),e.pr&&!e.local)_.push("This comment is rewritten on each push rather than replaced. Reviewing pauses automatically once a branch has had several; comment `/ai-review resume` to restart it."),_.push("");_.push("</details>"),_.push(""),_.push(u);let W=g.map((w)=>f(w,"inline")),le=o.map((w)=>{let B=w.repeat_of,de=l.get(B),F=[];F.push(`Checked this against \`${e.head.slice(0,12)}\` \u2014 still open. ${yt[w.severity]?.badge??w.severity}`);let xe=w.impact?.trim()||Ao(w.explanation,240);if(xe)F.push("",xe);let pe=[w.explanation,w.evidence].filter(Boolean).join(`
484
-
485
- `);if(pe)F.push("","<details><summary>What I found</summary>","",pe,"","</details>");return F.push("",er("reply",{of:B,fp:Jt(w.file,w.title)})),{comment_id:B,author:de?.author,url:de?.url,finding:w,body:F.join(`
486
- `)}});for(let w of e.resolved??[]){let B=l.get(w.id);if(!B?.mine||!B.file)continue;let de=w.note?.trim();le.push({comment_id:w.id,author:B.author,url:B.url,body:[`\u2705 Fixed as of \`${e.head.slice(0,12)}\`.${de?` ${de}`:""}`,"",er("reply",{of:w.id,addressed:1})].join(`
487
- `)})}return{summary:TS(_.join(`
488
- `),u),detail:K.join(`
489
- `),inline:W,ordered:g,replies:le}}async function MS(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 se("git",["-C",e,"show",`${t}:${a.file}`])).split(`
481
+ ${s}`}function xn(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}`}wt();Zr();Ho();var D$={high:"\uD83D\uDD34",moderate:"\uD83D\uDFE1",low:"\uD83D\uDFE2"};function L$(e){let t=e.repo??_t,n=(w,D)=>`https://github.com/${t}/blob/${e.head}/${w}${D?`#L${D}`:""}`,r=(w,D,de)=>{let j=de??`${w.split("/").pop()}${D?`:${D}`:""}`;if(!e.pr)return j.includes("`")?j:`\`${j}\``;return`[${j}](${n(w,D)})`},s=[...e.findings].sort((w,D)=>(vt[w.severity]?.rank??9)-(vt[D.severity]?.rank??9)||jt[it(w.file)]-jt[it(D.file)]||Yr.indexOf(w.confidence)-Yr.indexOf(D.confidence)),o=s.filter((w)=>w.repeat_of),a=s.filter((w)=>!w.repeat_of),c=a.filter((w)=>w._anchor?.kind!=="off-diff"),l=new Map((e.prior??[]).map((w)=>[w.id,w])),u=fr("summary",{...e.pr?{pr:e.pr}:{},...e.runs?{runs:e.runs}:{},head:e.head}),d=a.reduce((w,D)=>(w[D.severity]=(w[D.severity]??0)+1,w),{}),f=(w,D,de)=>{let j=[],ye=vt[w.severity]?.badge??w.severity,he=Nh[w.category]??w.category,mt=w.end_line&&w.end_line!==w.line?`-${w.end_line}`:"",sn=D==="summary"?r(w.file,w.line,`${w.file}:${w.line}${mt}`):`\`${w.file}:${w.line}${mt}\``;if(j.push(`${D==="summary"?"#####":"####"} ${de??w.title}`),j.push(""),j.push([ye,he,Th[w.effort??""],`confidence: ${w.confidence}`,sn,Mh[it(w.file)],w.preexisting?"pre-existing":""].filter(Boolean).join(" \xB7 ")),D==="inline"&&w._anchor?.kind==="off-hunk")j.push(""),j.push(`> Posted here because GitHub only accepts comments on changed lines. The code this is about is at \`${w.file}:${w.line}${mt}\`.`);if(j.push(""),j.push(w.impact?.trim()||Ko(w.explanation)),w.explanation)j.push(""),j.push("<details><summary>Why this is a problem</summary>"),j.push(""),j.push(w.explanation),j.push(""),j.push("</details>");if(w.evidence||w.cross_file_refs?.length){if(j.push(""),j.push("<details><summary>Evidence</summary>"),j.push(""),w.evidence)j.push(w.evidence);if(w.cross_file_refs?.length){j.push(""),j.push("Also read:");for(let Mt of w.cross_file_refs)j.push(`- \`${Mt}\``)}j.push(""),j.push("</details>")}if(w.suggested_code){if(w._original!==void 0){let E=w._original.replace(/\n$/,"").split(`
482
+ `).map((Q)=>`-${Q}`),z=w.suggested_code.replace(/\n$/,"").split(`
483
+ `).map((Q)=>`+${Q}`);j.push(""),j.push("<details><summary>What this changes</summary>"),j.push(""),j.push(ei([...E,...z].join(`
484
+ `),"diff")),j.push(""),j.push("</details>")}j.push("");let Mt=D==="inline"&&Fh(w);if(Mt)j.push("_Applying this commits it as written \u2014 read it first._"),j.push("");else if(D==="inline"){let E=w.end_line&&w.end_line!==w.line?`${w.line}-${w.end_line}`:`${w.line}`;j.push(`_Replaces ${xn(`${w.file}:${E}`)}. Not offered as a committable suggestion because this comment is anchored elsewhere._`),j.push("")}j.push(ei(w.suggested_code,Mt?"suggestion":""))}else if(w.suggestion)j.push(""),j.push(`_Suggested fix:_ ${w.suggestion}`);return j.push(""),j.push(D==="inline"?fr("inline",{file:w.file,line:w.line,fp:Yt(w.file,w.title)}):fr("summary-item",{file:w.file,line:w.line,fp:Yt(w.file,w.title)})),j.join(`
485
+ `)},p=(w)=>w.replace(/\s+/g," ").trim(),h=Ph(e.changedFiles??[],a),_=(w)=>jt[it(w.file)]<=jt[h],v=a.filter(_),y=a.filter((w)=>!_(w)),b=(e.inlineMode??"none")==="none"?[]:c.filter(_),S=new Set(b),O=[...v,...y],I=new Map;for(let w of O)I.set(w,I.size+1);let g=[];g.push(`### Review of \`${e.head.slice(0,12)}\``),g.push("");let R=e.unreviewed?.overCap??[],P=e.unreviewed?.failed??[],M=e.unreviewed?.budget??[],C=R.length+P.length+M.length>0;if(C){let w=[R.length?`${R.length} over the slice cap`:"",P.length?`${P.length} in a reviewer that failed`:"",M.length?`${M.length} skipped at the cost limit`:""].filter(Boolean),D=[...P,...M,...R],de=D.slice(0,5).map((ye)=>`\`${ye}\``).join(", "),j=D.length>5?`, and ${D.length-5} more`:"";g.push(`\u26A0\uFE0F **Partial review:** ${D.length} changed code ${D.length===1?"file was":"files were"} not reviewed (${w.join(", ")}): ${de}${j}.`),g.push("")}if(a.length===0)g.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.":C?"No new issues found in the reviewed files.":"No new issues found in the changed files.");else{let w=(D)=>`${D$[D.level]} **${D.label}** \u2014 ${D.detail}`;g.push(w(Ch(a))),g.push(""),g.push(w(Ih(a.map((D)=>({severity:D.severity,preexisting:D.preexisting,surface:it(D.file)}))))),g.push(""),g.push(Object.entries(vt).filter(([D])=>d[D]).map(([D,de])=>`${de.badge}: ${d[D]}`).join(" \xB7 "))}g.push("");let N=e.walkthrough,H=N?.intent,q=e.intentAlignment,K={aligned:"\u2705 Matches the description",partial:"\u26A0\uFE0F Partly matches the description",misaligned:"\u274C Does not match the description"},ge=[...H?.unstated??[],...q?.unstated??[]],$e=[...H?.missing??[],...q?.missing??[]],ie=H?.alignment==="aligned"&&q?.summary?"partial":H?.alignment,Ne=ie?K[ie]:void 0,Ye=q?.summary??H?.mismatches?.[0],Ae=[],B=[];if(B.push(`# Review of \`${e.head.slice(0,12)}\`${e.pr?` \u2014 PR #${e.pr}`:""}`),B.push(""),B.push("Everything the summary comment links to rather than carries."),B.push(""),Ne||Ye||H?.inferred||ge.length||$e.length){if(Ae.push(`**Intent:** ${Ne??"\u2139\uFE0F Not assessed"}${Ye?` \u2014 ${Ye}`:""}`),H?.inferred)Ae.push("",`**What it does:** ${Ko(H.inferred,320)}`);if(Ae.push(""),B.push("## What the change actually does, read from the code"),B.push(""),H?.inferred)B.push(H.inferred,"");if(H?.matches?.length){B.push("Description holds up on:");for(let w of H.matches)B.push(`- ${w}`);B.push("")}if(H?.mismatches?.length){B.push("Description does not hold up on:");for(let w of H.mismatches)B.push(`- ${w}`);B.push("")}if(ge.length){B.push("In the diff but not in the description:");for(let w of ge)B.push(`- ${w}`);B.push("")}if($e.length){B.push("Described but not accomplished:");for(let w of $e)B.push(`- ${w}`);B.push("")}}if(N?.focus)Ae.push(`**What to focus on:** ${N.focus}`,"");let Te=N?.chapters??[],Pe=Te.reduce((w,D)=>w+(D.stops?.length??0),0);if(N?.start_here?.length||Pe){let w={bug:"\uD83D\uDC1B",wrench:"\uD83D\uDD27",path:"\uD83D\uDEE4\uFE0F",flask:"\uD83E\uDDEA",doc:"\uD83D\uDCC4",gear:"\u2699\uFE0F"},D={critical:" \uD83D\uDD34",normal:"",context:" _(context)_"};if(N?.start_here?.length){Ae.push("**Start here**"),Ae.push("");for(let j of N.start_here)Ae.push(`1. ${r(j.file,void 0,`\`${j.file}\``)} \u2014 ${j.why}`);Ae.push("")}if(Pe||N?.support?.length)B.push(`## Guided walkthrough \u2014 ${Te.length} ${Te.length===1?"part":"parts"}, ${Pe} ${Pe===1?"stop":"stops"}`),B.push("");let de=0;for(let j of Te){if(B.push(`### ${w[j.icon??""]??"\u25B8"} ${j.title}`),j.blurb)B.push("",`_${j.blurb}_`);B.push("");for(let ye of j.stops??[]){if(de++,B.push(`**${de}. ${ye.title}**${D[ye.importance??"normal"]??""}`),ye.prose)B.push("",ye.prose);if(ye.locations?.length)B.push("",`\u21B3 ${ye.locations.map((he)=>r(he.file,he.line,he.label)).join(" \xB7 ")}`);B.push("")}}if(N?.support?.length){B.push("### Safe to skim"),B.push("");for(let j of N.support){let ye=j.files.map((he)=>`\`${he}\``).join(", ");B.push(`- ${ye} \u2014 ${j.reason}`)}B.push("")}}let je=(w)=>{let D=new Map;for(let j of w){let ye=D.get(j.file);if(ye)ye.push(j);else D.set(j.file,[j])}let de=[];for(let[j,ye]of D){de.push(`- \`${j}\``);for(let he of ye){let mt=vt[he.severity]?.badge??he.severity,sn=he._anchor?.kind==="off-diff"?`${r(he.file,he.line,`L${he.line}`)} \uD83D\uDCCE outside the diff`:r(he.file,he.line,`L${he.line}`),Mt=S.has(he)?"":` ${fr("summary-item",{file:he.file,line:he.line,fp:Yt(he.file,he.title)})}`;de.push(` - ${mt} ${p(he.title)} \u2014 ${sn} \xB7 _[${I.get(he)}]_${Mt}`)}}return de};if(v.length)g.push(`#### ${Ah[h]} (${v.length})`),g.push(""),g.push(...je(v)),g.push("");if(y.length)g.push(`<details><summary>Everything else (${y.length}) \u2014 lower-risk surfaces</summary>`),g.push(""),g.push(...je(y)),g.push(""),g.push("</details>"),g.push("");let Ce=e.overCap??[];if(Ce.length)g.push(`\u2795 ${Ce.length} more ${Ce.length===1?"finding":"findings"} past the ${Hn}-finding cap,`+" listed under \u201CPast the cap\u201D in the detail file."),g.push("");let be=e.checked??[];if(g.push(...Ae),o.length){g.push(`<details><summary>Agreeing with ${o.length} existing review ${o.length===1?"comment":"comments"}</summary>`),g.push("");for(let w of o){let D=l.get(w.repeat_of),de=D?`@${D.author}`:"an earlier review comment",j=D?.url?`[${de}](${D.url})`:de,ye=vt[w.severity]?.badge??w.severity;g.push(`- ${ye} ${p(w.title)} \u2014 \`${w.file}:${w.line}\` _\u2014 agrees with ${j}_`)}g.push(""),g.push("</details>"),g.push("")}if(O.length){B.push("## Evidence and reasoning"),B.push(""),B.push("Numbered to match the bullets in the summary comment."),B.push("");for(let w of O)B.push(f(w,"summary",`[${I.get(w)}] ${p(w.title)}`)),B.push("")}if(Ce.length){B.push("## Past the cap"),B.push(""),B.push(`Findings the review kept but did not post, because a review posts at most ${Hn}. Ranked below the posted ones by severity, surface and confidence.`),B.push("");for(let w of Ce)B.push(f(w,"summary",p(w.title))),B.push("")}if(be.length){B.push("## What the reviewers checked"),B.push(""),B.push("Claims each reviewer verified against the code and found correct."),B.push("");for(let w of be)B.push(`- ${w}`);B.push("")}let at=process.env.GITHUB_RUN_ID,T=process.env.GITHUB_SERVER_URL??"https://github.com",L=e.detailFile??"review-detail.md";if(O.length||Pe||Ce.length||be.length>8)g.push(at?`\uD83D\uDCC4 **[Full review detail](${T}/${t}/actions/runs/${at})** \u2014 download the`+` \`${Yi(e.pr??"",e.head)}\` artifact and open \`${L}\` for the walkthrough and the evidence behind each finding. Artifacts expire 90 days after the run.`:`\uD83D\uDCC4 Full walkthrough and evidence: \`${e.detailPath??L}\`.`),g.push("");if(be.length&&a.length<=2&&!e.noReviewers){g.push(`<details><summary>What the reviewers checked (${be.length})</summary>`),g.push("");for(let w of be.slice(0,8))g.push(`- ${w}`);if(be.length>8)g.push(`- \u2026and ${be.length-8} more in the detail file`);g.push(""),g.push("</details>"),g.push("")}if(e.dropped?.length){g.push("<details><summary>Findings considered and dropped during verification</summary>"),g.push("");for(let w of e.dropped)g.push(`- **${w.title}** \u2014 ${w.reason}`);g.push(""),g.push("</details>"),g.push("")}g.push("<details><summary>Review details</summary>"),g.push("");for(let[w,D]of Object.entries(e.stats))g.push(`- ${w}: ${D}`);g.push(""),g.push("</details>"),g.push(""),g.push(u);let Z=b.map((w)=>f(w,"inline")),ne=o.map((w)=>{let D=w.repeat_of,de=l.get(D),j=[];j.push(`Checked this against \`${e.head.slice(0,12)}\` \u2014 still open. ${vt[w.severity]?.badge??w.severity}`);let ye=w.impact?.trim()||Ko(w.explanation,240);if(ye)j.push("",ye);let he=[w.explanation,w.evidence].filter(Boolean).join(`
486
+
487
+ `);if(he)j.push("","<details><summary>What I found</summary>","",he,"","</details>");return j.push("",fr("reply",{of:D,fp:Yt(w.file,w.title)})),{comment_id:D,author:de?.author,url:de?.url,finding:w,body:j.join(`
488
+ `)}});for(let w of e.resolved??[]){let D=l.get(w.id);if(!D?.mine||!D.file)continue;let de=w.note?.trim();ne.push({comment_id:w.id,author:D.author,url:D.url,body:[`\u2705 Fixed as of \`${e.head.slice(0,12)}\`.${de?` ${de}`:""}`,"",fr("reply",{of:w.id,addressed:1})].join(`
489
+ `)})}return{summary:U$(g.join(`
490
+ `),u),detail:B.join(`
491
+ `),inline:Z,ordered:b,replies:ne}}async function j$(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 le("git",["-C",e,"show",`${t}:${a.file}`])).split(`
490
492
  `))}catch{s.set(a.file,null)}let c=s.get(a.file),l=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(!c||u<1||l>c.length){o.push(a);continue}o.push({...a,_original:c.slice(u-1,l).join(`
491
- `)})}return o}var _h=65536;function TS(e,t){if(e.length<=_h)return e;let n=`
493
+ `)})}return o}var jl=65536;function U$(e,t){if(e.length<=jl)return e;let n=`
492
494
 
493
495
  ---
494
496
 
495
497
  _Truncated to fit GitHub's comment size limit. The full review is in the run artifact._
496
498
 
497
499
  `,r=`
498
- </details>`,s=((e.match(/<details/g)??[]).length+1)*r.length,o=_h-n.length-t.length-s-1,a=e.slice(0,o),c=a.lastIndexOf(`
500
+ </details>`,s=((e.match(/<details/g)??[]).length+1)*r.length,o=jl-n.length-t.length-s-1,a=e.slice(0,o),c=a.lastIndexOf(`
499
501
 
500
502
  `),l=a.slice(0,c>o/2?c:a.length),u=(l.match(/<details/g)??[]).length-(l.match(/<\/details>/g)??[]).length,d=u>0?`
501
- ${r.repeat(u)}`:"";return`${l}${d}${n}${t}`}async function hl(e){let t=e.findings,n=[];if(e.repoDir){t=await MS(e.repoDir,e.head,t);try{let f=await Sf(e.repoDir,e.base,e.head);n=[...f.keys()],t=t.map((h)=>({...h,_anchor:no(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:c,replies:l}=PS({pr:e.pr,detailFile:r,detailPath:Di.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,runs:e.runs,noReviewers:e.noReviewers,unreviewed:e.unreviewed,checked:e.checked,overCap:e.overCap,changedFiles:n,inlineMode:If,local:e.local}),u=e.local?Zc([s,...a.length?["","## Line comments","",...a.flatMap((f)=>[f,"","---",""])]:[]].join(`
503
+ ${r.repeat(u)}`:"";return`${l}${d}${n}${t}`}function Yi(e,t){return`ai-code-review-${e}-${t.slice(0,9)}`}var hr="findings.md",B$="<details><summary>Review details</summary>";function tm(e){return e?`download the \`${e}\` artifact and open \`${hr}\``:`see \`${hr}\` 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, ${tm(t)}._`}function rm(e,t,n={}){let r=n.limit??jl,s=typeof t==="string"?[t]:t;for(let c of s){let l=[Io,"<details><summary>Copy all findings as Markdown</summary>","",ei(c,"markdown"),"","</details>",Vi].join(`
504
+ `),u=em(e,l);if(u.length<=r)return u}let o=[Io,`_All findings as Markdown are too long for this comment: ${tm(n.artifact)}._`,Vi].join(`
505
+ `),a=em(e,o);return a.length<=r?a:e}function em(e,t){let n=e.lastIndexOf(B$);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}
506
+
507
+ ${t}
508
+
509
+ ${s}`:`${r}
510
+
511
+ ${t}`}async function Ul(e){let t=e.findings,n=[];if(e.repoDir){t=await j$(e.repoDir,e.head,t);try{let f=await op(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:c,replies:l}=L$({pr:e.pr,detailFile:r,detailPath:Xi.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,runs:e.runs,noReviewers:e.noReviewers,unreviewed:e.unreviewed,checked:e.checked,overCap:e.overCap,changedFiles:n,inlineMode:fp}),u=e.local?vl([s,...a.length?["","## Line comments","",...a.flatMap((f)=>[f,"","---",""])]:[]].join(`
502
512
  `))+`
503
513
  `:["# Summary comment","",s,"","---","","# Inline comments","",...c.map((f,p)=>[`<!-- inline ${p+1} of ${c.length} \u2014 ${f.file}:${f.line}${f._anchor&&f._anchor.line!==f.line?` (anchored at line ${f._anchor.line})`:""} -->`,"",a[p],"","---",""].join(`
504
514
  `)),...l.length?["# Replies to existing review comments","",...l.map((f,p)=>[`<!-- reply ${p+1} of ${l.length} \u2014 to ${f.author?`@${f.author}`:"comment"} ${f.comment_id}${f.finding?` on ${f.finding.file}:${f.finding.line}`:" \u2014 closing it out as fixed"} -->`,"",...f.url?[`In reply to ${f.url}`,""]:[],f.body,"","---",""].join(`
505
515
  `))]:[]].join(`
506
- `);if(await Ye(Di.join(e.dir,`${e.tag}.md`),u),await Ye(Di.join(e.dir,r),e.local?`${Zc(o)}
507
- `:o),!e.pr||e.local){if(await Wt(Di.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:c}}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:c.map((f,p)=>{let h=f._anchor,y=f.end_line!==void 0?Math.min(f.line,f.end_line):f.line,v=f.end_line!==void 0?Math.max(f.line,f.end_line):f.line,b=v!==y;return{path:f.file,line:h?.line??v,...h?h.start_line!==void 0?{start_line:h.start_line}:{}:b?{start_line:y}:{},side:"RIGHT",body:a[p]}})}},replies:l.map((f)=>({method:"POST",endpoint:`repos/${e.slug}/pulls/${e.pr}/comments/${f.comment_id}/replies`,body:{body:f.body}}))};return await fn(Di.join(e.dir,`${e.tag}.payloads.json`),d),{summary:s,inline:a,ordered:c}}gt();import{createHash as NS}from"crypto";import wh from"path";var DS=160000;function ml(e){return typeof e==="string"&&e.trim()?e.trim():void 0}function yh(e){if(typeof e!=="object"||e===null||Array.isArray(e))return;let t=e,n=ml(t.title),r=ml(t.goal);if(!n||!r)return;let s=Array.isArray(t.expected_changes)?t.expected_changes.map(ml).filter((o)=>o!==void 0):[];return{title:n,goal:r,expected_changes:s}}async function bh(e){let t=$r,n=Ef(e.diff,DS),r=wh.join(ht,`${e.tag}-intent.json`),s={branch:e.branch,intent:e.intent,diffstat:e.diffstat,diff:n,otherFiles:e.otherFiles},o=NS("sha256").update(Io).update(Oo({...s,outFile:""})).digest("hex").slice(0,16),a=wh.join(_e,"intents",`${e.cacheKey}.json`),c={model:t,diffChars:n.length};if(await yr(a))try{let f=await br(a),p=yh(f.draft);if(p&&f.model===t&&f.inputHash===o)return{...c,draft:p,costUsd:0,wallMs:0,cached:!0}}catch{}let l=await wn(Oo({...s,outFile:r}),{budget:kc,outFile:r,tag:`${e.tag}-intent`,model:t,effort:Vt,tools:"none",system:{name:"intent",text:Io}}),u={costUsd:l.costUsd,wallMs:l.wallMs,cached:!1},d=yh(l.payload);if(!d){let f=l.failure?.message??"the draft has no title or goal";return{...c,...u,failure:f}}return await fn(a,{draft:d,model:t,inputHash:o}),{...c,...u,draft:d}}gt();Mi();Nr();var FS=4;function LS(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>=FS&&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 vh(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 jS(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.`,...vh(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: ${et.join(_e,"raw",`${t}-sNN.stdout.ndjson`)}, logs in ${et.join(_e,"logs")}`].join(`
508
- `)}async function xh(e){if(e.config)ao(e.config);let{signal:t}=e;if(t?.aborted)throw new Dt;let n=()=>void Mr();if(t?.addEventListener("abort",n,{once:!0}),t)Rr({signal:t});try{return await US(e)}finally{t?.removeEventListener("abort",n),await Mr(),await io(),co(),ko()}}async function US(e){let t=(k)=>e.onProgress?.(k),{signal:n,maxCostUsd:r}=e,s=()=>{if(n?.aborted)throw new Dt},o=0,a=(k)=>{o+=k,t({type:"cost",totalUsd:o})};t({type:"stage",stage:"resolving_target"});let c=e.repo,{pr:l,base:u,head:d,slug:f}=e.target,p=Bp({pr:l,base:u,head:d}),h=e.tag,y=et.join(_e,"reviews",`${h}.md`);await pn(ht);for(let k of["runs","raw","logs","prompts","reviews","maps"])await pn(et.join(_e,k));await Ye(et.join(_e,".gitignore"),`*
509
- `);let v=await jp(c,l,d);Rr({subject:v.dir,releaseSubject:v.release});let b=Date.now();Rr({repoName:f});let g=await go(f,l,u,d,e.intent),R=[...await bp(f,l),...e.prior??[]],N=vp(R,g.body),I=Math.max(0,...R.filter((k)=>k.mine).map((k)=>k.runs??0));s();let _=(await lt(["diff","--name-only",`${u}..${d}`])).trim().split(`
510
- `).filter(Boolean),S={skip:[],docs:[],code:[]};for(let k of _)S[Pr(k)].push(k);let O=S.code;if(O.length===0)return console.error(` ${_.length} changed files, none reviewable \u2014 no review`),await hl({dir:et.join(_e,"reviews"),tag:h,slug:f,pr:l,base:u,head:d,findings:[],stats:{"changed files":String(_.length),reviewed:"nothing: no code files in this change"},repoDir:tt,local:e.local}),{record:null,units:[],byClass:S,findings:[],costUsd:0,wallMs:Date.now()-b,markdownPath:y};let P={kind:"full",files:O};if(e.priorHead){let k=e.priorHead===d?[]:await lt(["diff","--name-only",e.priorHead,d]).then((G)=>G.trim().split(`
511
- `).filter(Boolean),()=>null);P=LS(O,k),console.error(P.kind==="incremental"?` re-review: ${P.files.length} of ${O.length} code files changed since ${e.priorHead.slice(0,12)}`:` re-review in full: ${P.reason}`)}let C=P.kind==="incremental";t({type:"stage",stage:"grouping"});let{wholeDiff:j,diffstat:H,diffU0:U,fileTokens:q,facts:Ee,links:we,grouping:ce}=await wo({base:u,head:d,files:O,source:()=>uo(tt)}),Te=bh({tag:h,cacheKey:p,intent:g,diffstat:H,diff:j,otherFiles:S.docs}).catch((k)=>({model:$r,costUsd:0,wallMs:0,cached:!1,diffChars:0,failure:k instanceof Error?k.message:String(k)})),qe=await yp(u,d,O),he=Jn==="code"?ce:void 0,K=he?.groups.length===1;if(he){let k=Or(he.groups,(J)=>q.get(J)??0),G=he.groups.map((J,Pt)=>({id:J.id,title:K?g.title||J.id:k[Pt]??J.id,files:J.files,priority:Pt+1}));t({type:"units",units:G,byClass:S})}s(),t({type:"stage",stage:"checking_registry"});let ye=await Tf({repo:tt,base:u,head:d}),ve=Nf(ye.findings),st=et.join(_e,"maps",`${p}.md`),Ae="",Le=await yr(st);if(t({type:"stage",stage:"building_map"}),!Le)try{let k=await hp({repo:tt,base:u,head:d,cacheDir:et.join(_e,"outlines")});await Ye(st,k.markdown),await fn(et.join(_e,"maps",`${p}.meta.json`),k.meta),Le=!0}catch(k){console.error(`repo map unavailable, continuing without it: ${k}`)}if(Le)Ae=`A repository orientation map for this change is at \`${st}\`. 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.
512
- `;if(s(),!K)t({type:"stage",stage:"grouping"});let Qe=`${h}-part`,T=`${ht}/${Qe}.json`;await Wt(T);let D=he?gh({groups:he.groups,links:we,outline:qe,intent:g,registry:ve,outFile:T}):mh({diffstat:H,outline:qe,intent:g,codeFiles:O,registry:ve,outFile:T});await Ye(et.join(_e,"prompts",`${Qe}.txt`),D);let W={wallMs:0,costUsd:0,numTurns:0,payload:void 0};if(!K)W=await wn(D,{budget:Rc,outFile:T,tag:Qe,model:mn,effort:Vt}),a(W.costUsd);s();let le=[],w;if(he&&K)w=[{id:he.groups[0].id,title:g.title||he.groups[0].id,files:he.groups[0].files,priority:1}];else if(he){let k=Cp(he.groups,W.payload,In,q);le=k.moves,w=pl(k.units,O);for(let G of le)console.error(` moved ${G.file}: ${G.from} -> ${G.to} (${G.reason})`)}else{let k=W.payload??void 0;w=pl(k?.review_units??[],O)}let B=new Set(ye.findings.map((k)=>k.addedIn)),de=new Map(w.map((k)=>[k.id,k.files.reduce((G,J)=>G+(q.get(J)??0),0)])),F=[...w].sort((k,G)=>{let J=Number(k.files.some((gi)=>B.has(gi))),Pt=Number(G.files.some((gi)=>B.has(gi)));if(J!==Pt)return Pt-J;let ot=k.priority??5,En=G.priority??5;if(ot!==En)return ot-En;return(de.get(G.id)??0)-(de.get(k.id)??0)}),xe=new Map(F.map((k,G)=>[k.id,G])),pe=hh(F,q,In).sort((k,G)=>k.part-G.part||(xe.get(k.unitId)??0)-(xe.get(G.unitId)??0)),A=new Set(P.files),X=C?pe.map((k)=>{let G=k.files.filter((J)=>A.has(J));return{...k,files:G,tokens:G.reduce((J,Pt)=>J+(q.get(Pt)??0),0)}}).filter((k)=>k.files.length>0):pe,V=X.slice(0,Yn),Ne=pe.slice(0,Yn),pt=X.slice(Yn).flatMap((k)=>k.files),He=V.filter((k)=>k.tokens>In);console.error(`${l?`PR ${l} `:""}${u.slice(0,12)}..${d.slice(0,12)} \u2014 ${_.length} changed (${O.length} code, ${S.docs.length} docs, ${S.skip.length} skipped) -> ${w.length} units, ${V.length} slices${pt.length?`, ${pt.length} files over cap`:""}${He.length?`, ${He.length} over ${In} tokens`:""}, registry signals: ${ye.findings.length}, prior comments: ${R.length}`);for(let k of V)console.error(` slice ${k.unitId}${k.parts>1?` ${k.part}/${k.parts}`:""} (${k.tokens} tokens): ${k.files.join(", ")}`);let Ke=[],je=[],Fs=[],pr=await Te;s(),a(pr.costUsd);let di=pr.draft;t({type:"log",message:di?` intent draft${pr.cached?" (cached)":""}: ${di.title}`:` warning: no intent draft (${pr.failure??"unknown error"}); reviewing without it`}),t({type:"units",units:w,byClass:S}),t({type:"stage",stage:"reviewing"});let Ls=0,Ga=!1,za=[];async function Gb(k){while(!0){if(n?.aborted)return;if(r!==void 0&&o>=r&&Ls<V.length){let At=V.slice(Ls);Ls=V.length,Ga=!0,za=At.flatMap((Gs)=>Gs.files),console.error(` cost $${o.toFixed(2)} reached --max-cost $${r.toFixed(2)}: ${At.length} slice(s) not started`),t({type:"budget",totalUsd:o,limitUsd:r,skippedSlices:At.length});return}let G=Ls++;if(G>=V.length)return;let J=V[G],Pt={id:J.unitId,title:J.title,rationale:J.rationale,files:J.files,priority:J.priority},ot=`${h}-s${String(G).padStart(2,"0")}`,[En,gi]=await Promise.all([lt(["diff",`${u}..${d}`,"--",...J.files]),C&&e.priorHead?lt(["diff",e.priorHead,d,"--",...J.files]):void 0]),Ld=zn(En,u);if(!Ld.trim())continue;let ac=`${ht}/${ot}.json`;await Wt(ac);let jd=dl({unit:Pt,diff:Ld,intent:g,draft:di,registry:ve,prior:N,mapNote:Ae,outFile:ac,crossLinks:Ap(J.files,we),instructions:e.instructions,sinceLast:gi});await Ye(et.join(_e,"prompts",`${ot}.txt`),jd);let cc={type:"slice",index:G,total:V.length,title:J.title};t({...cc,status:"started"});let De;try{De=await wn(jd,{budget:Ec,outFile:ac,tag:ot}),a(De.costUsd)}catch(At){let Gs=At instanceof Error?At.message:String(At);console.error(` [w${k}] ${J.unitId} \u2014 failed to run: ${Gs}`);let tv={kind:"spawn",message:`failed to run: ${Gs}`};Ke.push({unit:J.unitId,part:J.part,parts:J.parts,tokens:J.tokens,files:J.files,tag:ot,wallMs:0,costUsd:0,numTurns:0,exitCode:-1,findingCount:0,ok:!1,failure:tv}),t({...cc,status:"failed"});continue}let lc=De.payload,Vs=Array.isArray(lc)?lc:lc?.findings??[],_i=(Array.isArray(Vs)?Vs:[]).filter((At)=>typeof At==="object"&&At!==null);if(_i.length!==(Array.isArray(Vs)?Vs.length:0))console.error(` [w${k}] ${J.unitId} \u2014 discarded malformed entries from the findings file`);for(let At of _i)At._slice=J.unitId,je.push(At);let Ud=nh(De.payload);Fs[G]=Ud,Ke.push({unit:J.unitId,part:J.part,parts:J.parts,tokens:J.tokens,files:J.files,tag:ot,wallMs:De.wallMs,costUsd:De.costUsd,numTurns:De.numTurns,usage:De.usage,tools:De.tools,checked:Ud,exitCode:De.exitCode,findingCount:_i.length,ok:De.payload!==null,...De.failure?{failure:De.failure}:{}}),console.error(` [w${k}] ${J.unitId}${J.parts>1?` ${J.part}/${J.parts}`:""} (${J.files.length}f ${J.tokens}t) \u2014 ${(De.wallMs/1000).toFixed(0)}s $${De.costUsd.toFixed(2)} ${De.numTurns}t ${_i.length} findings${De.failure?` \u2014 failed: ${De.failure.message}`:""}`),t({...cc,status:De.payload!==null?"ok":"failed",costUsd:De.costUsd,wallMs:De.wallMs,findings:_i.length})}}await Promise.all(Array.from({length:Math.min(Cc,V.length)},(k,G)=>Gb(G))),s();let js=Ke.filter((k)=>k.ok??k.exitCode===0),Us=Ke.filter((k)=>!js.includes(k));if(Ke.length>0&&js.length===0)throw Error(jS(Us,h,Ke.length));if(Us.length){console.error(` warning: ${Us.length} of ${Ke.length} slices failed`);for(let k of vh(Us,h))console.error(` ${k}`)}let kn=je;if(je.length>20)kn=je.filter((k)=>!(k.severity==="nice-to-have"&&k.confidence!=="high"));let Ja=je.length-kn.length,Xa=`${h}-merge`,Ya=`${ht}/${Xa}.json`;await Wt(Ya);let Ed=fl({findings:kn,intent:g,draft:di,files:O,prior:N,outFile:Ya,instructions:e.instructions,changedLines:xi(U),maxNew:C?al:Tn,sinceLast:C?P.files:void 0});await Ye(et.join(_e,"prompts",`${Xa}.txt`),Ed);let zb=rh(kn.length,Ac),Za=`${h}-walk`,Qa=`${ht}/${Za}.json`;await Wt(Qa);let Bs=F.filter((k)=>Ne.some((G)=>G.unitId===k.id)),Jb=new Set(Bs.flatMap((k)=>k.files)),Ad=pe.flatMap((k)=>k.files).filter((k)=>!Jb.has(k)),Xb=[...Bs,...Ad.length?[{files:[...new Set(Ad)]}]:[]],{shown:ec,sketched:hr}=vo(Xb,q,Si),Yb=ec.reduce((k,G)=>k+(q.get(G)??0),0),Zb=hr.length?zn(await lt(["diff",`${u}..${d}`,"--",...ec]),u):j;if(hr.length)console.error(` walkthrough sees ${ec.length} of ${O.length} files (${Yb} tokens), ${hr.length} given as sketches`);let Qb=yo(U,Ee),Cd=Po({diffstat:H,diff:Zb,sketches:hr.map((k)=>bo(Qb.get(k)??{file:k,added:0,removed:0,defines:[],touches:[]})),crossLinks:$o(Bs,we),intent:g,draft:di,findingIndex:kn.map((k)=>`- [${k.severity}] ${k.file}:${k.line} \u2014 ${k.title}`).join(`
513
- `),unitSummary:Bs.map((k)=>{let G=xo(k.files,we);return`**${k.title}** (${k.id})
514
- ${k.files.map((J)=>` - ${J}`).join(`
515
- `)}`+(G.length?`
516
- Links: ${G.join("; ")}`:"")}).join(`
517
-
518
- `),docsFiles:S.docs,registry:ve,outFile:Qa});await Ye(et.join(_e,"prompts",`${Za}.txt`),Cd);let Id=(k)=>(G)=>(console.error(` ${k} failed to run: ${G instanceof Error?G.message:String(G)}`),{wallMs:0,exitCode:-1,costUsd:0,numTurns:0,usage:null,payload:null}),ev={wallMs:0,exitCode:0,costUsd:0,numTurns:0,usage:null,payload:null},Od=C&&P.files.length===0,tc=Od||!sh(kn,R);if(Od)console.error(" coordinator skipped: no code changed since the last review");else if(tc)console.error(" coordinator skipped: no findings and no earlier comments to close out");t({type:"stage",stage:"coordinating"}),t({type:"stage",stage:"walkthrough"});let[Vn,fi]=await Promise.all([tc?Promise.resolve({...ev,payload:{keep:[]}}):wn(Ed,{budget:zb,outFile:Ya,tag:Xa,model:Xn,effort:Vt}).then((k)=>(a(k.costUsd),k)).catch(Id("coordinator")),wn(Cd,{budget:$i,outFile:Qa,tag:Za,model:mn,effort:Vt}).then((k)=>(a(k.costUsd),k)).catch(Id("walkthrough"))]);s();let qs=fi.payload??void 0,mr=Vn.payload??{},pi=[],nc=[],hi=tc?"nothing-to-merge":"coordinator",Pd=th(R),rc=(k)=>{if(!Pd.size)return k;return k.filter((G)=>{let J=Pd.get(Jt(G.file,G.title));if(!J)return!0;return nc.push({title:G.title,reason:`already posted on an earlier push (comment ${J.id})`}),console.error(` suppressed "${G.title}" \u2014 same claim as comment ${J.id}`),!1})},ic=new Set,Hs=[],Md={maxNew:C?al:Tn,maxPreexisting:Co};if(mr.keep){let k=oh(mr,kn,R);nc=k.dropped;let G=(ot,En)=>(yt[ot.severity]?.rank??9)-(yt[En.severity]?.rank??9)||Ft[nt(ot.file)]-Ft[nt(En.file)]||Tr.indexOf(ot.confidence)-Tr.indexOf(En.confidence),J=k.kept.sort(G);ic=new Set([...J,...k.capped].map((ot)=>Jt(ot.file,ot.title)));let Pt=cl(rc(J),Md);Hs=[...Pt.overCap,...rc(k.capped.sort(G))],pi=Pt.posted}if(!mr.keep){hi="deterministic-fallback";let k=ih(kn);ic=new Set(k.map((J)=>Jt(J.file,J.title)));let G=cl(rc(k).map((J)=>({...J,repeat_of:void 0})),Md);pi=G.posted,Hs=G.overCap}let Ks=(mr.resolved??[]).filter((k)=>{let G=R.find((J)=>J.id===k.id);if(!G?.mine)return!1;if(!G.file)return!1;return!(G.fingerprint&&ic.has(G.fingerprint))});if(Ks.length)console.error(` closing out ${Ks.length} earlier comments as fixed`);t({type:"stage",stage:"verifying"});let mi=[],Ws=[...nc];for(let k of pi){let G=et.join(tt,k.file),J=await bf(G);if(J===null){Ws.push({title:k.title,reason:`cited file does not exist: ${k.file}`});continue}if(k.line<1||k.line>J){Ws.push({title:k.title,reason:`cited line ${k.line} outside ${k.file} (${J} lines)`});continue}mi.push(k)}let Td={overCap:pt,failed:Ke.filter((k)=>!(k.ok??k.exitCode===0)).flatMap((k)=>k.files??[]),budget:za},Nd=Fs.flat().filter(Boolean),sc=Ke.reduce((k,G)=>k+G.costUsd,0)+Vn.costUsd+fi.costUsd+pr.costUsd,oc=Date.now()-b,Dd={"review units":V.length,"code files reviewed":V.reduce((k,G)=>k+G.files.length,0),"docs files not reviewed":S.docs.length,"generated files skipped":S.skip.length,"raw findings":je.length,"after merge":pi.length,"after verification":mi.length,"registry signals":ye.findings.length,"prior comments considered":R.length,...C?{"review scope":`${P.files.length} of ${O.length} code files changed since the last review`}:P.reason?{"review scope":`full: ${P.reason}`}:{},"wall time":`${(oc/60000).toFixed(1)} min`,cost:`$${sc.toFixed(2)}`,model:hn,...Xn!==hn?{"coordinator model":Xn}:{},"walkthrough model":mn,"walkthrough stops":qs?(qs.chapters??[]).reduce((k,G)=>k+(G.stops?.length??0),0):"none \u2014 the walkthrough produced no guide",...hr.length?{"walkthrough did not read":`${hr.length} of ${O.length} files`}:{},...pt.length?{"not reviewed (over cap)":pt.join(", ")}:{},...Ga?{"not reviewed (cost limit)":za.join(", ")}:{},...Ja?{"trimmed before merge":`${Ja} low-confidence nice-to-have`}:{},...js.length<Ke.length?{"slices that failed":`${Ke.length-js.length} of ${Ke.length} \u2014 this review is incomplete`}:{},...hi!=="coordinator"&&hi!=="nothing-to-merge"?{merging:`${hi} \u2014 findings are unverified`}:{}};t({type:"stage",stage:"writing"}),await hl({dir:et.join(_e,"reviews"),tag:h,slug:f,pr:l,base:u,head:d,findings:mi,intentAlignment:mr.intent_alignment,dropped:Ws,stats:Dd,walkthrough:qs,prior:R,resolved:Ks,runs:I+1,noReviewers:Ke.length===0,unreviewed:Td,checked:Nd,overCap:Hs,repoDir:tt,local:e.local});let Fd={pr:l,base:u,head:d,runner:Af,model:hn,effort:xr,effortAux:Vt,models:{review:hn,coordinator:Xn,walkthrough:mn,intent:$r},tag:h,wallMs:oc,totalCostUsd:sc,mergeMode:hi,preTrimmed:Ja,budgetStopped:Ga,sliceRuns:Ke,merge:{wallMs:Vn.wallMs,costUsd:Vn.costUsd,numTurns:Vn.numTurns,tools:"tools"in Vn?Vn.tools:void 0},walk:{model:mn,wallMs:fi.wallMs,costUsd:fi.costUsd,numTurns:fi.numTurns},walkthrough:qs??null,intentDraft:pr,grouping:Jn,groupMoves:le,reviewUnits:V,reviewScope:P.kind,reviewedFiles:V.reduce((k,G)=>k+G.files.length,0),...P.reason?{scopeReason:P.reason}:{},promptVersion:fh(await Ct(et.join(vr,"system.md"))),...e.instructions?.trim()?{instructionsHash:ph(e.instructions)}:{},registry:{meta:ye.meta,findings:ye.findings},priorComments:R.length,prior:R,rawFindings:je,mergedFindings:pi,verifiedFindings:mi,overCapFindings:Hs,checked:Nd,unreviewed:Td,resolved:Ks,runs:I+1,rejected:Ws,intentAlignment:mr.intent_alignment??null,stats:Dd};return await fn(et.join(_e,"runs",`${h}.json`),Fd),{record:Fd,units:w,byClass:S,findings:mi,costUsd:sc,wallMs:oc,markdownPath:y}}import Lr from"path";gt();Mi();import{spawn as BS}from"child_process";import{posix as qS}from"path";function Fi(e,t,n,r){return new Promise((s,o)=>{let a=BS("git",["-C",e,...t],{stdio:[n===void 0?"ignore":"pipe","pipe","pipe"],...r?{env:{...process.env,...r}}:{}}),c=[],l=[];if(a.stdout?.on("data",(u)=>c.push(u)),a.stderr?.on("data",(u)=>l.push(u)),a.on("error",o),a.on("close",(u)=>{if(u===0)s(Buffer.concat(c));else o(Error(`git ${t.join(" ")} exited ${u}
519
- ${Buffer.concat(l).toString("utf8").slice(0,2000)}`))}),n!==void 0)a.stdin?.on("error",()=>{}),a.stdin?.end(n)})}async function HS(e,t){let n=(await Fi(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,c]=s.slice(0,o).split(" ");if(a==="blob"&&c)r.set(s.slice(o+1),c)}return r}async function KS(e,t){if(t.length===0)return;let n=(await Fi(e,["config","--get","extensions.partialClone"]).catch(()=>Buffer.alloc(0))).toString("utf8").trim();if(!n)return;let s=(await Fi(e,["cat-file","--batch-check"],`${t.join(`
520
- `)}
521
- `,{GIT_NO_LAZY_FETCH:"1"})).toString("utf8").split(`
522
- `).flatMap((o)=>o.endsWith(" missing")?[o.slice(0,o.indexOf(" "))]:[]);if(s.length===0)return;await Fi(e,["-c","fetch.negotiationAlgorithm=noop","fetch","-q","--no-tags","--no-write-fetch-head","--recurse-submodules=no","--filter=blob:none","--stdin",n],`${s.join(`
523
- `)}
524
- `)}async function WS(e,t,n){let r=n.filter((c)=>!c.includes(`
525
- `)),s=new Map;if(r.length===0)return s;let o=await Fi(e,["cat-file","--batch"],r.map((c)=>`${t}:${c}
526
- `).join("")),a=0;for(let c of r){let l=o.indexOf(10,a);if(l<0)break;let u=o.subarray(a,l).toString("utf8");if(a=l+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(c,o.subarray(a,a+d).toString("utf8"));a+=d+1}return s}var VS=/^(?:(?:tsconfig|jsconfig).*\.json|package\.json)$/;async function $h(e,t,n){let r=await HS(e,t),s=new Set(r.keys()),o=[...s].filter((l)=>VS.test(qS.basename(l))),a=[...new Set([...n.filter((l)=>s.has(l)),...o])];await KS(e,a.map((l)=>r.get(l)??"").filter(Boolean));let c=await WS(e,t,a);return{paths:s,read:(l)=>c.get(l)}}So();async function Sh(e){if(e.config)ao(e.config);let{signal:t}=e;if(t?.aborted)throw new Dt;let n=()=>void Mr();t?.addEventListener("abort",n,{once:!0}),Rr({subject:e.repo,repoName:e.target.slug??Lr.basename(e.repo),...t?{signal:t}:{}});try{return await GS(e)}finally{t?.removeEventListener("abort",n),await Mr(),co(),ko()}}async function GS(e){let t=(ce)=>e.onProgress?.(ce),n=()=>{if(e.signal?.aborted)throw new Dt},r=Date.now(),{base:s,head:o,pr:a,slug:c}=e.target,l=`${s}..${o}`;t({type:"stage",stage:"grouping"});let u=(await lt(["diff","--name-only",l])).trim().split(`
527
- `).filter(Boolean),d={skip:[],docs:[],code:[]};for(let ce of u)d[Pr(ce)].push(ce);let f=(ce,Te=null,qe=0)=>({record:Te,units:ce,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:y,fileTokens:v,facts:b,links:g,grouping:R}=await wo({base:s,head:o,files:d.code,source:(ce)=>$h(e.repo,o,ce)}),N=Or(R.groups,(ce)=>v.get(ce)??0),I=R.groups.map((ce,Te)=>({id:ce.id,title:N[Te]??ce.id,files:ce.files,priority:Te+1}));if(t({type:"units",units:I,byClass:d}),n(),!e.walkthrough)return f(I);t({type:"stage",stage:"walkthrough"}),await pn(ht),await pn(Lr.join(_e,"prompts")),await pn(Lr.join(_e,"logs")),await Ye(Lr.join(_e,".gitignore"),`*
528
- `);let _=await go(c,a,s,o,e.intent),S=`${e.tag}-walk`,O=Lr.join(ht,`${S}.json`);await Wt(O);let{shown:P,sketched:C}=vo(I,v,Si),j=C.length?zn(await lt(["diff",l,"--",...P]),s):p,H=yo(y,b),U=Po({diffstat:h,diff:j,sketches:C.map((ce)=>bo(H.get(ce)??{file:ce,added:0,removed:0,defines:[],touches:[]})),crossLinks:$o(I,g),intent:_,unitSummary:I.map((ce)=>{let Te=xo(ce.files,g);return`**${ce.title}** (${ce.id})
529
- ${ce.files.map((qe)=>` - ${qe}`).join(`
530
- `)}`+(Te.length?`
531
- Links: ${Te.join("; ")}`:"")}).join(`
532
-
533
- `),docsFiles:d.docs,registry:"",outFile:O});await Ye(Lr.join(_e,"prompts",`${S}.txt`),U);let q=await wn(U,{budget:$i,outFile:O,tag:S,model:mn,effort:Vt,tools:"none"}).catch((ce)=>(n(),t({type:"log",message:` walkthrough failed: ${ce instanceof Error?ce.message:String(ce)}`}),{costUsd:0,payload:null}));n(),t({type:"cost",totalUsd:q.costUsd});let Ee=q.payload??void 0;if(!Ee)t({type:"log",message:" walkthrough returned no guide"});let we=Date.now()-r;return f(I,Ee?{walkthrough:Ee,wallMs:we,totalCostUsd:q.costUsd}:null,q.costUsd)}function Oh(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 Ph(e){return{type:"groups",groups:e.groups,files:e.files.map((t)=>({path:t.path,groupId:t.groupId,classification:t.classification}))}}import tA from"os";import Ze from"path";import{appendFile as bK,mkdir as nA,readdir as gs,readFile as nw,rm as tw,writeFile as rw}from"fs/promises";var Nn=(e)=>Array.isArray(e)?e:[e],Mh=(e,t)=>{let n=[[],[]];for(let r of e)if(t(r))n[0].push(r);else n[1].push(r);return n},No=Array,Lt=(e,t)=>e.includes(t),Th=(e,t=0)=>[...Array(e)].map((n,r)=>r+t),fe=(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},yn=(e,t)=>{if(t===void 0||t===null)return e??[];if(e===void 0||e===null)return Nn(t);return e.concat(t)},Nh=(...e)=>e.reduce(yn,[]),an=(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 Nn(t))if(!e.some((o)=>r(o,s)))e.push(s);return e},Dh=(e,t)=>e.reduce((n,r)=>{let s=r[t];return n[s]=fe(n[s],r),n},{}),bn=(e,t,n)=>e.length===t.length&&e.every(n?.isEqual?(r,s)=>n.isEqual(r,t[s]):(r,s)=>r===t[s]);var bt=(e,t)=>Ge(e)===t,Ge=(e)=>{let t=typeof e;return t==="object"?e===null?"null":"object":t==="function"?"object":t},vt={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},Fh={...vt,function:"a function"};class Lh extends Error{}var me=(e)=>nr(e,Lh),nr=(e,t=Error)=>{throw new t(e)};class ji extends Error{name="ParseError"}var E=(e)=>nr(e,ji),Xt=(e)=>` ${e}`,jh="\u200B";var ne=(e,t)=>{let n={},r=Array.isArray(e),s=!1;for(let[o,a]of Object.entries(e).entries()){let c=r?t(o,a[1]):t(...a,o);s||=typeof c[0]==="number";let l=Array.isArray(c[0])||c.length===0?c:[c];for(let[u,d]of l)if(typeof u==="object")n[u.group]=fe(n[u.group],d);else n[u]=d}return s?Object.values(n):n};var bl=Object.entries;var ze=(e,t)=>(e in t),Ur=(e,t)=>(t in e);class vl{constructor(e){Object.assign(this,e)}}var Uh=class{};class Ui extends Uh{}var JS=(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 Do=(e,t)=>JS(e,t)[1],cn=(e)=>Object.keys(e).length===0,rr=(e)=>[...Object.entries(e),...Object.getOwnPropertySymbols(e).map((t)=>[t,e[t]])],Bh=(e,t)=>Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)),qh=(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 xt=Xt(`unset${jh}`),Hh=(e)=>Object.values(e).filter((t)=>{if(typeof t==="number")return!0;return typeof e[t]!=="number"});var xl={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},$l=globalThis.File??Blob,Sl={ArrayBuffer,Blob,File:$l,FormData,Headers,Request,Response,URL},XS={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},ir={...xl,...Sl,...XS,String,Number,Boolean},Bi=(e)=>{let t=Object.getPrototypeOf(e);while(t?.constructor&&(!ze(t.constructor.name,ir)||!(e instanceof ir[t.constructor.name])))t=Object.getPrototypeOf(t);let n=t?.constructor?.name;if(n===void 0||n==="Object")return;return n},qi=(e)=>typeof e==="object"&&e!==null?Bi(e)??"object":Ge(e);var Se=Array.isArray,YS={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"},ZS={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"},QS={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"},Kh={...YS,...ZS,...QS},Hi=(e)=>{let t=Object(e).name??null;return t&&ze(t,ir)&&ir[t]===e?t:null};var Rl=(e,t)=>{let n=e.prototype;while(n!==null){if(n===t.prototype)return!0;n=Object.getPrototypeOf(n)}return!1};var Wh=(e)=>Vh(e,new Map),Vh=(e,t)=>{if(typeof e!=="object"||e===null)return e;if(t?.has(e))return t.get(e);let n=Hi(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=Vh(a.value,t)}}return Object.defineProperties(r,s),r};var eR=(e)=>{let t=xt;return()=>t===xt?t=e():t},Dn=(e)=>typeof e==="function"&&e.length===0;var Gh=class extends Function{constructor(...e){let t=e.slice(0,-1),n=e[e.length-1];try{super(...t,n)}catch(r){return me(`Encountered an unexpected error while compiling your definition:
516
+ `);if(await et(Xi.join(e.dir,`${e.tag}.md`),u),await et(Xi.join(e.dir,r),e.local?`${vl(o)}
517
+ `:o),!e.pr||e.local){if(await Gt(Xi.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:c}}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:c.map((f,p)=>{let h=f._anchor,_=f.end_line!==void 0?Math.min(f.line,f.end_line):f.line,v=f.end_line!==void 0?Math.max(f.line,f.end_line):f.line,y=v!==_;return{path:f.file,line:h?.line??v,...h?h.start_line!==void 0?{start_line:h.start_line}:{}:y?{start_line:_}:{},side:"RIGHT",body:a[p]}})}},replies:l.map((f)=>({method:"POST",endpoint:`repos/${e.slug}/pulls/${e.pr}/comments/${f.comment_id}/replies`,body:{body:f.body}}))};return await mn(Xi.join(e.dir,`${e.tag}.payloads.json`),d),{summary:s,inline:a,ordered:c}}wt();import{createHash as q$}from"crypto";import im from"path";var H$=160000;function Bl(e){return typeof e==="string"&&e.trim()?e.trim():void 0}function sm(e){if(typeof e!=="object"||e===null||Array.isArray(e))return;let t=e,n=Bl(t.title),r=Bl(t.goal);if(!n||!r)return;let s=Array.isArray(t.expected_changes)?t.expected_changes.map(Bl).filter((o)=>o!==void 0):[];return{title:n,goal:r,expected_changes:s}}async function om(e){let t=Ur,n=lp(e.diff,H$),r=im.join(gt,`${e.tag}-intent.json`),s={branch:e.branch,intent:e.intent,diffstat:e.diffstat,diff:n,otherFiles:e.otherFiles},o=q$("sha256").update(Vo).update(Go({...s,outFile:""})).digest("hex").slice(0,16),a=im.join(we,"intents",`${e.cacheKey}.json`),c={model:t,diffChars:n.length};if(await Nr(a))try{let f=await Dr(a),p=sm(f.draft);if(p&&f.model===t&&f.inputHash===o)return{...c,draft:p,costUsd:0,wallMs:0,cached:!0}}catch{}let l=await vn(Go({...s,outFile:r}),{budget:Jc,outFile:r,tag:`${e.tag}-intent`,model:t,effort:zt,tools:"none",system:{name:"intent",text:Vo}}),u={costUsd:l.costUsd,wallMs:l.wallMs,cached:!1,...l.usage?{usage:l.usage}:{}},d=sm(l.payload);if(!d){let f=l.failure?.message??"the draft has no title or goal";return{...c,...u,failure:f}}return await mn(a,{draft:d,model:t,inputHash:o}),{...c,...u,draft:d}}wt();zi();Zr();var K$=4;function W$(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>=K$&&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 am(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 V$(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.`,...am(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: ${nt.join(we,"raw",`${t}-sNN.stdout.ndjson`)}, logs in ${nt.join(we,"logs")}`].join(`
518
+ `)}async function cm(e){if(e.config)So(e.config);let{signal:t}=e;if(t?.aborted)throw new Lt;let n=()=>void Xr();if(t?.addEventListener("abort",n,{once:!0}),t)qr({signal:t});try{return await G$(e)}finally{t?.removeEventListener("abort",n),await Xr(),await bo(),Ro(),qo()}}async function G$(e){let t=(k)=>e.onProgress?.(k),{signal:n,maxCostUsd:r}=e,s=()=>{if(n?.aborted)throw new Lt},o=0,a=(k)=>{o+=k,t({type:"cost",totalUsd:o})};t({type:"stage",stage:"resolving_target"});let c=e.repo,{pr:l,base:u,head:d,slug:f}=e.target,p=Rh({pr:l,base:u,head:d}),h=e.tag,_=nt.join(we,"reviews",`${h}.md`);await gn(gt);for(let k of["runs","raw","logs","prompts","reviews","maps"])await gn(nt.join(we,k));await et(nt.join(we,".gitignore"),`*
519
+ `);let v=await xh(c,l,d);qr({subject:v.dir,releaseSubject:v.release});let y=Date.now();qr({repoName:f});let b=!e.local,S=await Po(f,l,u,d,e.intent,{strict:b}),O=[...await rh(f,l,{strict:b}),...e.prior??[]],I=ih(O,S.body),g=Math.max(0,...O.filter((k)=>k.mine).map((k)=>k.runs??0));s();let R=(await dt(["diff","--name-only",`${u}..${d}`])).trim().split(`
520
+ `).filter(Boolean),P={skip:[],docs:[],code:[]};for(let k of R)P[Jr(k)].push(k);let M=P.code;if(M.length===0)return console.error(` ${R.length} changed files, none reviewable \u2014 no review`),await Ul({dir:nt.join(we,"reviews"),tag:h,slug:f,pr:l,base:u,head:d,findings:[],stats:{"changed files":String(R.length),reviewed:"nothing: no code files in this change"},repoDir:rt,local:e.local}),{record:null,units:[],byClass:P,findings:[],costUsd:0,wallMs:Date.now()-y,markdownPath:_};let C={kind:"full",files:M};if(e.priorHead){let k=e.priorHead===d?[]:await dt(["diff","--name-only",e.priorHead,d]).then((W)=>W.trim().split(`
521
+ `).filter(Boolean),()=>null);C=W$(M,k),console.error(C.kind==="incremental"?` re-review: ${C.files.length} of ${M.length} code files changed since ${e.priorHead.slice(0,12)}`:` re-review in full: ${C.reason}`)}let N=C.kind==="incremental";t({type:"stage",stage:"grouping"});let{wholeDiff:H,diffstat:q,diffU0:K,fileTokens:ge,facts:$e,links:ie,grouping:Ne}=await To({base:u,head:d,files:M,source:()=>ko(rt)}),Ye=om({tag:h,cacheKey:p,intent:S,diffstat:q,diff:H,otherFiles:P.docs}).catch((k)=>({model:Ur,costUsd:0,wallMs:0,cached:!1,diffChars:0,failure:k instanceof Error?k.message:String(k)})),Ae=await nh(u,d,M),B=ar==="code"?Ne:void 0,Te=B?.groups.length===1;if(B){let k=zr(B.groups,(G)=>ge.get(G)??0),W=B.groups.map((G,Tt)=>({id:G.id,title:Te?S.title||G.id:k[Tt]??G.id,files:G.files,priority:Tt+1}));t({type:"units",units:W,byClass:P})}s(),t({type:"stage",stage:"checking_registry"});let Pe=await gp({repo:rt,base:u,head:d}),je=_p(Pe.findings),Ce=nt.join(we,"maps",`${p}.md`),be="",at=await Nr(Ce);if(t({type:"stage",stage:"building_map"}),!at)try{let k=await Xp({repo:rt,base:u,head:d,cacheDir:nt.join(we,"outlines")});await et(Ce,k.markdown),await mn(nt.join(we,"maps",`${p}.meta.json`),k.meta),at=!0}catch(k){console.error(`repo map unavailable, continuing without it: ${k}`)}if(at)be=`A repository orientation map for this change is at \`${Ce}\`. 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.
522
+ `;if(s(),!Te)t({type:"stage",stage:"grouping"});let T=`${h}-part`,L=`${gt}/${T}.json`;await Gt(L);let Z=B?Qh({groups:B.groups,links:ie,outline:Ae,intent:S,registry:je,outFile:L}):Zh({diffstat:q,outline:Ae,intent:S,codeFiles:M,registry:je,outFile:L});await et(nt.join(we,"prompts",`${T}.txt`),Z);let ne={wallMs:0,costUsd:0,numTurns:0,payload:void 0};if(!Te)ne=await vn(Z,{budget:zc,outFile:L,tag:T,model:wn,effort:zt}),a(ne.costUsd);s();let w=[],D;if(B&&Te)D=[{id:B.groups[0].id,title:S.title||B.groups[0].id,files:B.groups[0].files,priority:1}];else if(B){let k=fh(B.groups,ne.payload,jn,ge);w=k.moves,D=Ll(k.units,M);for(let W of w)console.error(` moved ${W.file}: ${W.from} -> ${W.to} (${W.reason})`)}else{let k=ne.payload??void 0;D=Ll(k?.review_units??[],M)}let de=new Set(Pe.findings.map((k)=>k.addedIn)),j=new Map(D.map((k)=>[k.id,k.files.reduce((W,G)=>W+(ge.get(G)??0),0)])),ye=[...D].sort((k,W)=>{let G=Number(k.files.some((Oi)=>de.has(Oi))),Tt=Number(W.files.some((Oi)=>de.has(Oi)));if(G!==Tt)return Tt-G;let ct=k.priority??5,Fn=W.priority??5;if(ct!==Fn)return ct-Fn;return(j.get(W.id)??0)-(j.get(k.id)??0)}),he=new Map(ye.map((k,W)=>[k.id,W])),mt=Yh(ye,ge,jn).sort((k,W)=>k.part-W.part||(he.get(k.unitId)??0)-(he.get(W.unitId)??0)),sn=new Set(C.files),Mt=N?mt.map((k)=>{let W=k.files.filter((G)=>sn.has(G));return{...k,files:W,tokens:W.reduce((G,Tt)=>G+(ge.get(Tt)??0),0)}}).filter((k)=>k.files.length>0):mt,E=Mt.slice(0,lr),z=mt.slice(0,lr),Q=Mt.slice(lr).flatMap((k)=>k.files),Ze=E.filter((k)=>k.tokens>jn);console.error(`${l?`PR ${l} `:""}${u.slice(0,12)}..${d.slice(0,12)} \u2014 ${R.length} changed (${M.length} code, ${P.docs.length} docs, ${P.skip.length} skipped) -> ${D.length} units, ${E.length} slices${Q.length?`, ${Q.length} files over cap`:""}${Ze.length?`, ${Ze.length} over ${jn} tokens`:""}, registry signals: ${Pe.findings.length}, prior comments: ${O.length}`);for(let k of E)console.error(` slice ${k.unitId}${k.parts>1?` ${k.part}/${k.parts}`:""} (${k.tokens} tokens): ${k.files.join(", ")}`);let De=[],Ue=[],nr=[],Ke=await Ye;s(),a(Ke.costUsd);let rr=Ke.draft;t({type:"log",message:rr?` intent draft${Ke.cached?" (cached)":""}: ${rr.title}`:` warning: no intent draft (${Ke.failure??"unknown error"}); reviewing without it`}),t({type:"units",units:D,byClass:P}),t({type:"stage",stage:"reviewing"});let eo=0,gc=!1,_c=[];async function Qv(k){while(!0){if(n?.aborted)return;if(r!==void 0&&o>=r&&eo<E.length){let Ct=E.slice(eo);eo=E.length,gc=!0,_c=Ct.flatMap((lo)=>lo.files),console.error(` cost $${o.toFixed(2)} reached --max-cost $${r.toFixed(2)}: ${Ct.length} slice(s) not started`),t({type:"budget",totalUsd:o,limitUsd:r,skippedSlices:Ct.length});return}let W=eo++;if(W>=E.length)return;let G=E[W],Tt={id:G.unitId,title:G.title,rationale:G.rationale,files:G.files,priority:G.priority},ct=`${h}-s${String(W).padStart(2,"0")}`,[Fn,Oi]=await Promise.all([dt(["diff",`${u}..${d}`,"--",...G.files]),N&&e.priorHead?dt(["diff",e.priorHead,d,"--",...G.files]):void 0]),vf=or(Fn,u);if(!vf.trim())continue;let Ic=`${gt}/${ct}.json`;await Gt(Ic);let xf=Nl({unit:Tt,diff:vf,intent:S,draft:rr,registry:je,prior:I,mapNote:be,outFile:Ic,crossLinks:dh(G.files,ie),instructions:e.instructions,sinceLast:Oi});await et(nt.join(we,"prompts",`${ct}.txt`),xf);let Oc={type:"slice",index:W,total:E.length,title:G.title};t({...Oc,status:"started"});let Le;try{Le=await vn(xf,{budget:Xc,outFile:Ic,tag:ct}),a(Le.costUsd)}catch(Ct){let lo=Ct instanceof Error?Ct.message:String(Ct);console.error(` [w${k}] ${G.unitId} \u2014 failed to run: ${lo}`);let ax={kind:"spawn",message:`failed to run: ${lo}`};De.push({unit:G.unitId,part:G.part,parts:G.parts,tokens:G.tokens,files:G.files,tag:ct,wallMs:0,costUsd:0,numTurns:0,exitCode:-1,findingCount:0,ok:!1,failure:ax}),t({...Oc,status:"failed"});continue}let Pc=Le.payload,co=Array.isArray(Pc)?Pc:Pc?.findings??[],Pi=(Array.isArray(co)?co:[]).filter((Ct)=>typeof Ct==="object"&&Ct!==null);if(Pi.length!==(Array.isArray(co)?co.length:0))console.error(` [w${k}] ${G.unitId} \u2014 discarded malformed entries from the findings file`);for(let Ct of Pi)Ct._slice=G.unitId,Ue.push(Ct);let Sf=jh(Le.payload);nr[W]=Sf,De.push({unit:G.unitId,part:G.part,parts:G.parts,tokens:G.tokens,files:G.files,tag:ct,wallMs:Le.wallMs,costUsd:Le.costUsd,numTurns:Le.numTurns,usage:Le.usage,tools:Le.tools,checked:Sf,exitCode:Le.exitCode,findingCount:Pi.length,ok:Le.payload!==null,...Le.failure?{failure:Le.failure}:{}}),console.error(` [w${k}] ${G.unitId}${G.parts>1?` ${G.part}/${G.parts}`:""} (${G.files.length}f ${G.tokens}t) \u2014 ${(Le.wallMs/1000).toFixed(0)}s $${Le.costUsd.toFixed(2)} ${Le.numTurns}t ${Pi.length} findings${Le.failure?` \u2014 failed: ${Le.failure.message}`:""}`),t({...Oc,status:Le.payload!==null?"ok":"failed",costUsd:Le.costUsd,wallMs:Le.wallMs,findings:Pi.length})}}await Promise.all(Array.from({length:Math.min(Zc,E.length)},(k,W)=>Qv(W))),s();let to=De.filter((k)=>k.ok??k.exitCode===0),no=De.filter((k)=>!to.includes(k));if(De.length>0&&to.length===0)throw Error(V$(no,h,De.length));if(no.length){console.error(` warning: ${no.length} of ${De.length} slices failed`);for(let k of am(no,h))console.error(` ${k}`)}let Mn=Ue;if(Ue.length>20)Mn=Ue.filter((k)=>!(k.severity==="nice-to-have"&&k.confidence!=="high"));let wc=Ue.length-Mn.length,yc=`${h}-merge`,bc=`${gt}/${yc}.json`;await Gt(bc);let uf=Dl({findings:Mn,intent:S,draft:rr,files:M,prior:I,outFile:bc,instructions:e.instructions,changedLines:Ni(K),maxNew:N?Pl:Hn,sinceLast:N?C.files:void 0});await et(nt.join(we,"prompts",`${yc}.txt`),uf);let ex=Uh(Mn.length,Yc),vc=`${h}-walk`,xc=`${gt}/${vc}.json`;await Gt(xc);let ro=ye.filter((k)=>z.some((W)=>W.unitId===k.id)),tx=new Set(ro.flatMap((k)=>k.files)),df=mt.flatMap((k)=>k.files).filter((k)=>!tx.has(k)),nx=[...ro,...df.length?[{files:[...new Set(df)]}]:[]],{shown:Sc,sketched:Ir}=Do(nx,ge,Li),rx=Sc.reduce((k,W)=>k+(ge.get(W)??0),0),ix=Ir.length?or(await dt(["diff",`${u}..${d}`,"--",...Sc]),u):H;if(Ir.length)console.error(` walkthrough sees ${Sc.length} of ${M.length} files (${rx} tokens), ${Ir.length} given as sketches`);let sx=Fo(K,$e),ff=zo({diffstat:q,diff:ix,sketches:Ir.map((k)=>No(sx.get(k)??{file:k,added:0,removed:0,defines:[],touches:[]})),crossLinks:jo(ro,ie),intent:S,draft:rr,findingIndex:Mn.map((k)=>`- [${k.severity}] ${k.file}:${k.line} \u2014 ${k.title}`).join(`
523
+ `),unitSummary:ro.map((k)=>{let W=Lo(k.files,ie);return`**${k.title}** (${k.id})
524
+ ${k.files.map((G)=>` - ${G}`).join(`
525
+ `)}`+(W.length?`
526
+ Links: ${W.join("; ")}`:"")}).join(`
527
+
528
+ `),docsFiles:P.docs,registry:je,outFile:xc});await et(nt.join(we,"prompts",`${vc}.txt`),ff);let pf=(k)=>(W)=>(console.error(` ${k} failed to run: ${W instanceof Error?W.message:String(W)}`),{wallMs:0,exitCode:-1,costUsd:0,numTurns:0,usage:null,payload:null}),ox={wallMs:0,exitCode:0,costUsd:0,numTurns:0,usage:null,payload:null},hf=N&&C.files.length===0,Rc=hf||!qh(Mn,O);if(hf)console.error(" coordinator skipped: no code changed since the last review");else if(Rc)console.error(" coordinator skipped: no findings and no earlier comments to close out");t({type:"stage",stage:"coordinating"}),t({type:"stage",stage:"walkthrough"});let[Tn,Or]=await Promise.all([Rc?Promise.resolve({...ox,payload:{keep:[]}}):vn(uf,{budget:ex,outFile:bc,tag:yc,model:cr,effort:zt}).then((k)=>(a(k.costUsd),k)).catch(pf("coordinator")),vn(ff,{budget:Di,outFile:xc,tag:vc,model:wn,effort:zt}).then((k)=>(a(k.costUsd),k)).catch(pf("walkthrough"))]);s();let io=Or.payload??void 0,Pr=Tn.payload??{},Ai=[],$c=[],Ci=Rc?"nothing-to-merge":"coordinator",mf=Lh(O),kc=(k)=>{if(!mf.size)return k;return k.filter((W)=>{let G=mf.get(Yt(W.file,W.title));if(!G)return!0;return $c.push({title:W.title,reason:`already posted on an earlier push (comment ${G.id})`}),console.error(` suppressed "${W.title}" \u2014 same claim as comment ${G.id}`),!1})},Ec=new Set,so=[],gf={maxNew:N?Pl:Hn,maxPreexisting:Wo};if(Pr.keep){let k=Hh(Pr,Mn,O);$c=k.dropped;let W=(ct,Fn)=>(vt[ct.severity]?.rank??9)-(vt[Fn.severity]?.rank??9)||jt[it(ct.file)]-jt[it(Fn.file)]||Yr.indexOf(ct.confidence)-Yr.indexOf(Fn.confidence),G=k.kept.sort(W);Ec=new Set([...G,...k.capped].map((ct)=>Yt(ct.file,ct.title)));let Tt=Ml(kc(G),gf);so=[...Tt.overCap,...kc(k.capped.sort(W))],Ai=Tt.posted}if(!Pr.keep){Ci="deterministic-fallback";let k=Bh(Mn);Ec=new Set(k.map((G)=>Yt(G.file,G.title)));let W=Ml(kc(k).map((G)=>({...G,repeat_of:void 0})),gf);Ai=W.posted,so=W.overCap}let oo=(Pr.resolved??[]).filter((k)=>{let W=O.find((G)=>G.id===k.id);if(!W?.mine)return!1;if(!W.file)return!1;return!(W.fingerprint&&Ec.has(W.fingerprint))});if(oo.length)console.error(` closing out ${oo.length} earlier comments as fixed`);t({type:"stage",stage:"verifying"});let Ii=[],ao=[...$c];for(let k of Ai){let W=nt.join(rt,k.file),G=await np(W);if(G===null){ao.push({title:k.title,reason:`cited file does not exist: ${k.file}`});continue}if(k.line<1||k.line>G){ao.push({title:k.title,reason:`cited line ${k.line} outside ${k.file} (${G} lines)`});continue}Ii.push(k)}let _f={overCap:Q,failed:De.filter((k)=>!(k.ok??k.exitCode===0)).flatMap((k)=>k.files??[]),budget:_c},wf=nr.flat().filter(Boolean),Ac=De.reduce((k,W)=>k+W.costUsd,0)+Tn.costUsd+Or.costUsd+Ke.costUsd,Cc=Date.now()-y,yf={"review units":E.length,"code files reviewed":E.reduce((k,W)=>k+W.files.length,0),"docs files not reviewed":P.docs.length,"generated files skipped":P.skip.length,"raw findings":Ue.length,"after merge":Ai.length,"after verification":Ii.length,"registry signals":Pe.findings.length,"prior comments considered":O.length,...N?{"review scope":`${C.files.length} of ${M.length} code files changed since the last review`}:C.reason?{"review scope":`full: ${C.reason}`}:{},"wall time":`${(Cc/60000).toFixed(1)} min`,cost:`$${Ac.toFixed(2)}`,model:_n,...cr!==_n?{"coordinator model":cr}:{},"walkthrough model":wn,"walkthrough stops":io?(io.chapters??[]).reduce((k,W)=>k+(W.stops?.length??0),0):"none \u2014 the walkthrough produced no guide",...Ir.length?{"walkthrough did not read":`${Ir.length} of ${M.length} files`}:{},...Q.length?{"not reviewed (over cap)":Q.join(", ")}:{},...gc?{"not reviewed (cost limit)":_c.join(", ")}:{},...wc?{"trimmed before merge":`${wc} low-confidence nice-to-have`}:{},...to.length<De.length?{"slices that failed":`${De.length-to.length} of ${De.length} \u2014 this review is incomplete`}:{},...Ci!=="coordinator"&&Ci!=="nothing-to-merge"?{merging:`${Ci} \u2014 findings are unverified`}:{}};t({type:"stage",stage:"writing"}),await Ul({dir:nt.join(we,"reviews"),tag:h,slug:f,pr:l,base:u,head:d,findings:Ii,intentAlignment:Pr.intent_alignment,dropped:ao,stats:yf,walkthrough:io,prior:O,resolved:oo,runs:g+1,noReviewers:De.length===0,unreviewed:_f,checked:wf,overCap:so,repoDir:rt,local:e.local});let bf={pr:l,base:u,head:d,runner:up,model:_n,effort:jr,effortAux:zt,models:{review:_n,coordinator:cr,walkthrough:wn,intent:Ur},tag:h,wallMs:Cc,totalCostUsd:Ac,mergeMode:Ci,preTrimmed:wc,budgetStopped:gc,sliceRuns:De,merge:{wallMs:Tn.wallMs,costUsd:Tn.costUsd,numTurns:Tn.numTurns,usage:Tn.usage,tools:"tools"in Tn?Tn.tools:void 0},walk:{model:wn,wallMs:Or.wallMs,costUsd:Or.costUsd,numTurns:Or.numTurns,usage:Or.usage},walkthrough:io??null,intentDraft:Ke,grouping:ar,groupMoves:w,reviewUnits:E,reviewScope:C.kind,reviewedFiles:E.reduce((k,W)=>k+W.files.length,0),...C.reason?{scopeReason:C.reason}:{},promptVersion:Jh(await It(nt.join(Lr,"system.md"))),...e.instructions?.trim()?{instructionsHash:Xh(e.instructions)}:{},registry:{meta:Pe.meta,findings:Pe.findings},priorComments:O.length,prior:O,rawFindings:Ue,mergedFindings:Ai,verifiedFindings:Ii,overCapFindings:so,checked:wf,unreviewed:_f,resolved:oo,runs:g+1,rejected:ao,intentAlignment:Pr.intent_alignment??null,stats:yf};return await mn(nt.join(we,"runs",`${h}.json`),bf),{record:bf,units:D,byClass:P,findings:Ii,costUsd:Ac,wallMs:Cc,markdownPath:_}}var Kn=(e)=>Array.isArray(e)?e:[e],fm=(e,t)=>{let n=[[],[]];for(let r of e)if(t(r))n[0].push(r);else n[1].push(r);return n},Yo=Array,Ut=(e,t)=>e.includes(t),pm=(e,t=0)=>[...Array(e)].map((n,r)=>r+t),fe=(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},Sn=(e,t)=>{if(t===void 0||t===null)return e??[];if(e===void 0||e===null)return Kn(t);return e.concat(t)},hm=(...e)=>e.reduce(Sn,[]),un=(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 Kn(t))if(!e.some((o)=>r(o,s)))e.push(s);return e},mm=(e,t)=>e.reduce((n,r)=>{let s=r[t];return n[s]=fe(n[s],r),n},{}),Rn=(e,t,n)=>e.length===t.length&&e.every(n?.isEqual?(r,s)=>n.isEqual(r,t[s]):(r,s)=>r===t[s]);var xt=(e,t)=>Ge(e)===t,Ge=(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"},gm={...St,function:"a function"};class _m extends Error{}var pe=(e)=>gr(e,_m),gr=(e,t=Error)=>{throw new t(e)};class Qi extends Error{name="ParseError"}var A=(e)=>gr(e,Qi),Zt=(e)=>` ${e}`,wm="\u200B";var se=(e,t)=>{let n={},r=Array.isArray(e),s=!1;for(let[o,a]of Object.entries(e).entries()){let c=r?t(o,a[1]):t(...a,o);s||=typeof c[0]==="number";let l=Array.isArray(c[0])||c.length===0?c:[c];for(let[u,d]of l)if(typeof u==="object")n[u.group]=fe(n[u.group],d);else n[u]=d}return s?Object.values(n):n};var Wl=Object.entries;var ze=(e,t)=>(e in t),ti=(e,t)=>(t in e);class Vl{constructor(e){Object.assign(this,e)}}var ym=class{};class es extends ym{}var J$=(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 Zo=(e,t)=>J$(e,t)[1],dn=(e)=>Object.keys(e).length===0,_r=(e)=>[...Object.entries(e),...Object.getOwnPropertySymbols(e).map((t)=>[t,e[t]])],bm=(e,t)=>Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)),vm=(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 Rt=Zt(`unset${wm}`),xm=(e)=>Object.values(e).filter((t)=>{if(typeof t==="number")return!0;return typeof e[t]!=="number"});var Gl={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},zl=globalThis.File??Blob,Jl={ArrayBuffer,Blob,File:zl,FormData,Headers,Request,Response,URL},X$={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},wr={...Gl,...Jl,...X$,String,Number,Boolean},ts=(e)=>{let t=Object.getPrototypeOf(e);while(t?.constructor&&(!ze(t.constructor.name,wr)||!(e instanceof wr[t.constructor.name])))t=Object.getPrototypeOf(t);let n=t?.constructor?.name;if(n===void 0||n==="Object")return;return n},ns=(e)=>typeof e==="object"&&e!==null?ts(e)??"object":Ge(e);var xe=Array.isArray,Y$={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"},Z$={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"},Q$={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"},Sm={...Y$,...Z$,...Q$},rs=(e)=>{let t=Object(e).name??null;return t&&ze(t,wr)&&wr[t]===e?t:null};var Xl=(e,t)=>{let n=e.prototype;while(n!==null){if(n===t.prototype)return!0;n=Object.getPrototypeOf(n)}return!1};var Rm=(e)=>$m(e,new Map),$m=(e,t)=>{if(typeof e!=="object"||e===null)return e;if(t?.has(e))return t.get(e);let n=rs(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=$m(a.value,t)}}return Object.defineProperties(r,s),r};var ek=(e)=>{let t=Rt;return()=>t===Rt?t=e():t},Wn=(e)=>typeof e==="function"&&e.length===0;var km=class extends Function{constructor(...e){let t=e.slice(0,-1),n=e[e.length-1];try{super(...t,n)}catch(r){return pe(`Encountered an unexpected error while compiling your definition:
534
529
  Message: ${r}
535
530
  Source: (${e.slice(0,-1)}) => {
536
531
  ${e[e.length-1]}
537
- }`)}}};class $t{constructor(e,...[t]){return Object.assign(Object.setPrototypeOf(e.bind(t?.bind??this),this.constructor.prototype),t?.attach)}}var zh=eR(()=>{try{return Function("return false")()}catch{return!0}});var KT=Xt("brand");var Jh=Xt("arkInferred");var GT=Xt("args");class rt{constructor(){}}var tR=()=>{try{return((Error().stack?.split(`
538
- `)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},nR=globalThis.process?.env??{},Xh={fileName:tR,env:nR};var Yh=(e)=>e[0].toUpperCase()+e.slice(1),Zh=(e)=>e[0].toLowerCase()+e.slice(1),kl=(e)=>new RegExp(rR(e),typeof e==="string"?"":e.flags);var rR=(e)=>`^(?:${typeof e==="string"?e:e.source})$`;var vn={negativeLookahead:(e)=>`(?!${e})`,nonCapturingGroup:(e)=>`(?:${e})`},sr="\\",Fn={" ":1,"\n":1,"\t":1};var iR=/^-0\.?0*$/.source,em=/[1-9]\d*/.source,sR=/\.\d+/.source,oR=/\.\d*[1-9]/.source,tm=(e)=>kl(vn.negativeLookahead(iR)+vn.nonCapturingGroup("-?"+vn.nonCapturingGroup(vn.nonCapturingGroup("0|"+em)+vn.nonCapturingGroup(e.decimalPattern)+"?")+(e.allowDecimalOnly?"|"+e.decimalPattern:"")+"?")),Qh=tm({decimalPattern:oR,allowDecimalOnly:!1}),aR=Qh.test.bind(Qh),Fo=tm({decimalPattern:sR,allowDecimalOnly:!0}),e1=Fo.test.bind(Fo),cR=/^-?\d*\.?\d*$/,lR=(e)=>e.length!==0&&cR.test(e),Ki=kl(vn.negativeLookahead("^-0$")+"-?"+vn.nonCapturingGroup(vn.nonCapturingGroup("0|"+em))),uR=Ki.test.bind(Ki),El=/^-?\d+$/,dR=El.test.bind(El),nm={number:"a number",bigint:"a bigint",integer:"an integer"},rm=(e,t)=>`'${e}' was parsed as ${nm[t]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,fR=(e,t)=>t==="number"?aR(e):uR(e),pR=(e,t)=>t==="number"?Number(e):Number.parseInt(e),hR=(e,t)=>t==="number"?lR(e):dR(e),im=(e,t)=>Al(e,"number",t),sm=(e,t)=>Al(e,"number",{...t,strict:!0}),om=(e,t)=>Al(e,"integer",t),Al=(e,t,n)=>{let r=pR(e,t);if(!Number.isNaN(r)){if(hR(e,t)){if(n?.strict)return fR(e,t)?r:E(rm(e,t));return r}}return n?.errorOnFail?E(n?.errorOnFail===!0?`Failed to parse ${nm[t]} from '${e}'`:n?.errorOnFail):void 0},am=(e)=>{if(e[e.length-1]!=="n")return;let t=e.slice(0,-1),n;try{n=BigInt(t)}catch{return}if(Ki.test(t))return n;if(El.test(t))return E(rm(e,"bigint"))};var mR="0.56.0",gR={version:mR,filename:Xh.fileName(),FileConstructor:$l},or=gR,cm=new Map,Cl=Object.create(null),Wi=(e)=>{let t=cm.get(e);if(t)return t;let n=_R(e);if(Cl[n])n=`${n}${Cl[n]++}`;else Cl[n]=1;return or[n]=e,cm.set(e,n),n},Ln=(e)=>/^[$A-Z_a-z][\w$]*$/.test(e),_R=(e)=>{switch(typeof e){case"object":{if(e===null)break;let t=Bi(e)??"object";return t[0].toLowerCase()+t.slice(1)}case"function":return Ln(e.name)?e.name:"fn";case"symbol":return e.description&&Ln(e.description)?e.description:"symbol"}return me(`Unexpected attempt to register serializable value of type ${Ge(e)}`)};var Vi=(e)=>typeof e==="string"?JSON.stringify(e):typeof e==="bigint"?`${e}n`:`${e}`;var lm=(e,t={})=>Gi(e,{onUndefined:"$ark.undefined",onBigInt:(n)=>`$ark.bigint-${n}`,...t},[]);var re=(e,t)=>{switch(Ge(e)){case"object":let n=e,r=n.constructor?.name??"Object";return r==="Object"||r==="Array"?t?.quoteKeys===!1?Lo(n,t?.indent??0,""):JSON.stringify(Gi(n,Br,[]),null,t?.indent):Lo(n,t?.indent??0,"");case"symbol":return Br.onSymbol(e);default:return Vi(e)}},Lo=(e,t,n)=>{if(typeof e==="function")return Br.onFunction(e);if(typeof e!=="object"||e===null)return Vi(e);let r=n+" ".repeat(t);if(Array.isArray(e)){if(e.length===0)return"[]";let o=e.map((a)=>Lo(a,t,r)).join(`,
532
+ }`)}}};class $t{constructor(e,...[t]){return Object.assign(Object.setPrototypeOf(e.bind(t?.bind??this),this.constructor.prototype),t?.attach)}}var Em=ek(()=>{try{return Function("return false")()}catch{return!0}});var rN=Zt("brand");var Am=Zt("arkInferred");var oN=Zt("args");class st{constructor(){}}var tk=()=>{try{return((Error().stack?.split(`
533
+ `)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},nk=globalThis.process?.env??{},Cm={fileName:tk,env:nk};var Im=(e)=>e[0].toUpperCase()+e.slice(1),Om=(e)=>e[0].toLowerCase()+e.slice(1),Yl=(e)=>new RegExp(rk(e),typeof e==="string"?"":e.flags);var rk=(e)=>`^(?:${typeof e==="string"?e:e.source})$`;var $n={negativeLookahead:(e)=>`(?!${e})`,nonCapturingGroup:(e)=>`(?:${e})`},yr="\\",Vn={" ":1,"\n":1,"\t":1};var ik=/^-0\.?0*$/.source,Mm=/[1-9]\d*/.source,sk=/\.\d+/.source,ok=/\.\d*[1-9]/.source,Tm=(e)=>Yl($n.negativeLookahead(ik)+$n.nonCapturingGroup("-?"+$n.nonCapturingGroup($n.nonCapturingGroup("0|"+Mm)+$n.nonCapturingGroup(e.decimalPattern)+"?")+(e.allowDecimalOnly?"|"+e.decimalPattern:"")+"?")),Pm=Tm({decimalPattern:ok,allowDecimalOnly:!1}),ak=Pm.test.bind(Pm),Qo=Tm({decimalPattern:sk,allowDecimalOnly:!0}),pN=Qo.test.bind(Qo),ck=/^-?\d*\.?\d*$/,lk=(e)=>e.length!==0&&ck.test(e),is=Yl($n.negativeLookahead("^-0$")+"-?"+$n.nonCapturingGroup($n.nonCapturingGroup("0|"+Mm))),uk=is.test.bind(is),Zl=/^-?\d+$/,dk=Zl.test.bind(Zl),Fm={number:"a number",bigint:"a bigint",integer:"an integer"},Nm=(e,t)=>`'${e}' was parsed as ${Fm[t]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,fk=(e,t)=>t==="number"?ak(e):uk(e),pk=(e,t)=>t==="number"?Number(e):Number.parseInt(e),hk=(e,t)=>t==="number"?lk(e):dk(e),Dm=(e,t)=>Ql(e,"number",t),Lm=(e,t)=>Ql(e,"number",{...t,strict:!0}),jm=(e,t)=>Ql(e,"integer",t),Ql=(e,t,n)=>{let r=pk(e,t);if(!Number.isNaN(r)){if(hk(e,t)){if(n?.strict)return fk(e,t)?r:A(Nm(e,t));return r}}return n?.errorOnFail?A(n?.errorOnFail===!0?`Failed to parse ${Fm[t]} from '${e}'`:n?.errorOnFail):void 0},Um=(e)=>{if(e[e.length-1]!=="n")return;let t=e.slice(0,-1),n;try{n=BigInt(t)}catch{return}if(is.test(t))return n;if(Zl.test(t))return A(Nm(e,"bigint"))};var mk="0.56.0",gk={version:mk,filename:Cm.fileName(),FileConstructor:zl},br=gk,Bm=new Map,eu=Object.create(null),ss=(e)=>{let t=Bm.get(e);if(t)return t;let n=_k(e);if(eu[n])n=`${n}${eu[n]++}`;else eu[n]=1;return br[n]=e,Bm.set(e,n),n},Gn=(e)=>/^[$A-Z_a-z][\w$]*$/.test(e),_k=(e)=>{switch(typeof e){case"object":{if(e===null)break;let t=ts(e)??"object";return t[0].toLowerCase()+t.slice(1)}case"function":return Gn(e.name)?e.name:"fn";case"symbol":return e.description&&Gn(e.description)?e.description:"symbol"}return pe(`Unexpected attempt to register serializable value of type ${Ge(e)}`)};var os=(e)=>typeof e==="string"?JSON.stringify(e):typeof e==="bigint"?`${e}n`:`${e}`;var qm=(e,t={})=>as(e,{onUndefined:"$ark.undefined",onBigInt:(n)=>`$ark.bigint-${n}`,...t},[]);var oe=(e,t)=>{switch(Ge(e)){case"object":let n=e,r=n.constructor?.name??"Object";return r==="Object"||r==="Array"?t?.quoteKeys===!1?ea(n,t?.indent??0,""):JSON.stringify(as(n,ni,[]),null,t?.indent):ea(n,t?.indent??0,"");case"symbol":return ni.onSymbol(e);default:return os(e)}},ea=(e,t,n)=>{if(typeof e==="function")return ni.onFunction(e);if(typeof e!=="object"||e===null)return os(e);let r=n+" ".repeat(t);if(Array.isArray(e)){if(e.length===0)return"[]";let o=e.map((a)=>ea(a,t,r)).join(`,
539
534
  `+r);return t?`[
540
535
  ${r}${o}
541
- ${n}]`:`[${o}]`}let s=e.constructor?.name??"Object";if(s==="Object"){let o=rr(e).map(([a,c])=>{let l=typeof a==="symbol"?Br.onSymbol(a):Ln(a)?a:JSON.stringify(a),u=Lo(c,t,r);return`${r}${l}: ${u}`});if(o.length===0)return"{}";return t?`{
536
+ ${n}]`:`[${o}]`}let s=e.constructor?.name??"Object";if(s==="Object"){let o=_r(e).map(([a,c])=>{let l=typeof a==="symbol"?ni.onSymbol(a):Gn(a)?a:JSON.stringify(a),u=ea(c,t,r);return`${r}${l}: ${u}`});if(o.length===0)return"{}";return t?`{
542
537
  ${o.join(`,
543
538
  `)}
544
- ${n}}`:`{${o.join(", ")}}`}if(e instanceof Date)return ar(e);if("expression"in e&&typeof e.expression==="string")return e.expression;return s},Br={onCycle:()=>"(cycle)",onSymbol:(e)=>`Symbol(${Wi(e)})`,onFunction:(e)=>`Function(${Wi(e)})`},Gi=(e,t,n)=>{switch(Ge(e)){case"object":{let r=e;if("toJSON"in r&&typeof r.toJSON==="function")return r.toJSON();if(typeof r==="function")return Br.onFunction(r);if(n.includes(r))return"(cycle)";let s=[...n,r];if(Array.isArray(r))return r.map((a)=>Gi(a,t,s));if(r instanceof Date)return r.toDateString();let o={};for(let a in r)o[a]=Gi(r[a],t,s);for(let a of Object.getOwnPropertySymbols(r))o[t.onSymbol?.(a)??a.toString()]=Gi(r[a],t,s);return o}case"symbol":return Br.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}},ar=(e)=>{let t=e.getFullYear(),n=e.getMonth(),r=e.getDate(),s=e.getHours(),o=e.getMinutes(),a=e.getSeconds(),c=e.getMilliseconds();if(n===0&&r===1&&s===0&&o===0&&a===0&&c===0)return`${t}`;let l=`${wR[n]} ${r}, ${t}`;if(s===0&&o===0&&a===0&&c===0)return l;let u=e.toLocaleTimeString(),d=u.endsWith(" AM")||u.endsWith(" PM")?u.slice(-3):"";if(d)u=u.slice(0,-d.length);if(c)u+=`.${bR(c,3)}`;else if(yR.test(u))u=u.slice(0,-3);return`${u+d}, ${l}`},wR=["January","February","March","April","May","June","July","August","September","October","November","December"],yR=/:\d\d:00$/,bR=(e,t)=>String(e).padStart(t,"0");var um=(e,t,...[n])=>{let r=n?.stringifySymbol??re,s=e;switch(typeof t){case"string":s=Ln(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 E(`${re(t)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return s},xn=(e,...t)=>e.reduce((n,r)=>um(n,r,...t),"");class zi extends No{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"?re(this[e]):this[e]);return this.cache.json}stringify(){if(this.cache.stringify)return this.cache.stringify;return this.cache.stringify=xn(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let e="",t=[e];for(let n of this)e=um(e,n),t.push(e);return this.cache.stringifyAncestors=t}}class Ji{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===sr)if(this.shift(),e(this,t))t+=this.shift();else if(this.lookahead===sr)t+=this.shift();else t+=`${sr}${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 Fn))}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 dm=(e,t)=>`Unmatched ${e}${t===""?"":` before ${t}`}`,jo=(e)=>`Missing ${e}`;var R1=Xt("implementedTraits");var Il="$ark",vR=2;while(Il in globalThis)Il=`$ark${vR++}`;var fm=Il;globalThis[fm]=or;var M=or,xR=(e)=>`${fm}.${e}`,Me=(e)=>xR(Wi(e));class Uo extends Ui{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 Ol(e,t)}index(e,t=!1){return pm(`${e}`,t)}line(e){return this.body+=`${" ".repeat(this.indentation)}${e}
539
+ ${n}}`:`{${o.join(", ")}}`}if(e instanceof Date)return vr(e);if("expression"in e&&typeof e.expression==="string")return e.expression;return s},ni={onCycle:()=>"(cycle)",onSymbol:(e)=>`Symbol(${ss(e)})`,onFunction:(e)=>`Function(${ss(e)})`},as=(e,t,n)=>{switch(Ge(e)){case"object":{let r=e;if("toJSON"in r&&typeof r.toJSON==="function")return r.toJSON();if(typeof r==="function")return ni.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 ni.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}},vr=(e)=>{let t=e.getFullYear(),n=e.getMonth(),r=e.getDate(),s=e.getHours(),o=e.getMinutes(),a=e.getSeconds(),c=e.getMilliseconds();if(n===0&&r===1&&s===0&&o===0&&a===0&&c===0)return`${t}`;let l=`${wk[n]} ${r}, ${t}`;if(s===0&&o===0&&a===0&&c===0)return l;let u=e.toLocaleTimeString(),d=u.endsWith(" AM")||u.endsWith(" PM")?u.slice(-3):"";if(d)u=u.slice(0,-d.length);if(c)u+=`.${bk(c,3)}`;else if(yk.test(u))u=u.slice(0,-3);return`${u+d}, ${l}`},wk=["January","February","March","April","May","June","July","August","September","October","November","December"],yk=/:\d\d:00$/,bk=(e,t)=>String(e).padStart(t,"0");var Hm=(e,t,...[n])=>{let r=n?.stringifySymbol??oe,s=e;switch(typeof t){case"string":s=Gn(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(`${oe(t)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return s},kn=(e,...t)=>e.reduce((n,r)=>Hm(n,r,...t),"");class cs extends Yo{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"?oe(this[e]):this[e]);return this.cache.json}stringify(){if(this.cache.stringify)return this.cache.stringify;return this.cache.stringify=kn(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let e="",t=[e];for(let n of this)e=Hm(e,n),t.push(e);return this.cache.stringifyAncestors=t}}class ls{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===yr)if(this.shift(),e(this,t))t+=this.shift();else if(this.lookahead===yr)t+=this.shift();else t+=`${yr}${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 Vn))}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 Km=(e,t)=>`Unmatched ${e}${t===""?"":` before ${t}`}`,ta=(e)=>`Missing ${e}`;var LN=Zt("implementedTraits");var tu="$ark",vk=2;while(tu in globalThis)tu=`$ark${vk++}`;var Wm=tu;globalThis[Wm]=br;var F=br,xk=(e)=>`${Wm}.${e}`,Me=(e)=>xk(ss(e));class na extends es{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 nu(e,t)}index(e,t=!1){return Vm(`${e}`,t)}line(e){return this.body+=`${" ".repeat(this.indentation)}${e}
545
540
  `,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(`
546
541
  `).map((n)=>" ".repeat(t)+`${n}`).join(`
547
- `):this.body} }`}compile(){return new Gh(...this.argNames,this.body)}}var Yt=(e)=>bt(e,"object")||typeof e==="symbol"?Me(e):Vi(e),Ol=(e,t=!1)=>{if(typeof e==="string"&&Ln(e))return`${t?"?":""}.${e}`;return pm($R(e),t)},$R=(e)=>typeof e==="symbol"?Me(e):JSON.stringify(e),pm=(e,t=!1)=>`${t?"?.":""}[${e}]`;class Xi extends Uo{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 Bo=(e)=>ne(e,(t,n)=>[t,Se(n)?[...n]:n]),ut=Xt("arkKind"),Z=(e,t)=>e?.[ut]===t,Re=(e)=>Z(e,"root")||Z(e,"constraint");var hm=["unit","proto","domain"],qr=["required","optional","index","sequence"],Pl=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],Ml=[...Pl,"structure","predicate"],qo=[...Ml,...qr],Hr=["alias","union","morph","unit","intersection","proto","domain"],SR=[...Hr,...qo],Ho=ne(qo,(e,t)=>[t,1]),mm=ne([...qr,"undeclared"],(e,t)=>[t,1]),gm=ne(SR,(e,t)=>[t,e]),Kr=(e)=>typeof e==="string"&&(e in gm);var Wr=(e)=>gm[e],Ko=(e)=>Hr.slice(Wr(e)+1),cN=[...Ko("union"),"alias"],lN=[...Ko("morph"),"alias"],jt=(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 Yt(e)},jn=(e)=>{let t="{ ";for(let[n,r]of Object.entries(e))t+=`${n}: ${Yt(r)}, `;return t+" }"},ie=(e)=>{let t=e;if(t.hasAssociatedError)t.defaults.expected??=(n)=>("description"in n)?n.description:t.defaults.description(n),t.defaults.actual??=(n)=>re(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 _m extends Error{name="ToJsonSchemaError";code;context;constructor(e,t){super(re(t,{quoteKeys:!1,indent:4}));this.code=e,this.context=t}hasCode(e){return this.code===e}}var RR={target:"draft-2020-12",dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:(e)=>Ce.throw("arrayObject",e),arrayPostfix:(e)=>Ce.throw("arrayPostfix",e),defaultValue:(e)=>Ce.throw("defaultValue",e),domain:(e)=>Ce.throw("domain",e),morph:(e)=>Ce.throw("morph",e),patternIntersection:(e)=>Ce.throw("patternIntersection",e),predicate:(e)=>Ce.throw("predicate",e),proto:(e)=>Ce.throw("proto",e),symbolKey:(e)=>Ce.throw("symbolKey",e),unit:(e)=>Ce.throw("unit",e),date:(e)=>Ce.throw("date",e)}},Ce={Error:_m,throw:(...e)=>{throw new Ce.Error(...e)},throwInternalOperandError:(e,t)=>me(`Unexpected JSON Schema input for ${e}: ${re(t)}`),defaultConfig:RR};M.config??={};var Yi=(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]=Tl(e.toJsonSchema,t.toJsonSchema);else if(Kr(r))n[r]={...e[r],...t[r]};else n[r]=t[r]}return n},kR={"draft-2020-12":"https://json-schema.org/draft/2020-12/schema","draft-07":"http://json-schema.org/draft-07/schema#"},Tl=(e,t)=>{if(!e)return wm(t??{},void 0);if(!t)return e;let n={...e},r;for(r in t)if(r==="fallback")n.fallback=ER(e.fallback,t.fallback);else n[r]=t[r];return wm(n,t)},wm=(e,t)=>{if(t?.dialect!==void 0)return e;if(t?.target!==void 0)return{...e,dialect:kR[t.target]};return e},ER=(e,t)=>{e=ym(e),t=ym(t);let n={},r;for(r in Ce.defaultConfig.fallback)n[r]=t[r]??t.default??e[r]??e.default??Ce.defaultConfig.fallback[r];return n},ym=(e)=>typeof e==="function"?{default:e}:e??{};class Un extends Ui{[ut]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:e,relativePath:t,...n},r){super();this.input=n,this.ctx=r,Bh(this,n);let s=r.data;if(n.code==="union")n.errors=n.errors.flatMap((a)=>{let c=a.hasCode("union")?a.errors:[a];if(!e&&!t)return c;return c.map((l)=>l.transform((u)=>({...u,path:Nh(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 zi(...o),this.data="data"in n?n.data:s}transform(e){return new Un(e({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(e){return this.code===e}get propString(){return xn(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 St extends No{[ut]="errors";ctx;constructor(e){super();this.ctx=e}byPath=Object.create(null);get flatByPath(){return ne(this.byPath,(e,t)=>[e,t.flat])}get flatProblemsByPath(){return ne(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 Nl(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 Un({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 St(this.ctx);for(let n of this)t.add(e(n));return t}merge(e){for(let t of e)this.add(new Un({...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(`
548
- `)}addAncestorPaths(e){for(let t of e.path.stringifyAncestors())this.byAncestorPath[t]=fe(this.byAncestorPath[t],e)}}class Nl extends Error{name="TraversalError";constructor(e){if(e.length===1)super(e.summary);else super(`
549
- `+e.map((t)=>` \u2022 ${AR(t)}`).join(`
550
- `));Object.defineProperty(this,"arkErrors",{value:e,enumerable:!1})}}var AR=(e)=>e.toString().split(`
542
+ `):this.body} }`}compile(){return new km(...this.argNames,this.body)}}var Qt=(e)=>xt(e,"object")||typeof e==="symbol"?Me(e):os(e),nu=(e,t=!1)=>{if(typeof e==="string"&&Gn(e))return`${t?"?":""}.${e}`;return Vm(Sk(e),t)},Sk=(e)=>typeof e==="symbol"?Me(e):JSON.stringify(e),Vm=(e,t=!1)=>`${t?"?.":""}[${e}]`;class us extends na{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 ra=(e)=>se(e,(t,n)=>[t,xe(n)?[...n]:n]),ft=Zt("arkKind"),X=(e,t)=>e?.[ft]===t,Se=(e)=>X(e,"root")||X(e,"constraint");var Gm=["unit","proto","domain"],ri=["required","optional","index","sequence"],ru=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],iu=[...ru,"structure","predicate"],ia=[...iu,...ri],ii=["alias","union","morph","unit","intersection","proto","domain"],Rk=[...ii,...ia],sa=se(ia,(e,t)=>[t,1]),zm=se([...ri,"undeclared"],(e,t)=>[t,1]),Jm=se(Rk,(e,t)=>[t,e]),si=(e)=>typeof e==="string"&&(e in Jm);var oi=(e)=>Jm[e],oa=(e)=>ii.slice(oi(e)+1),vD=[...oa("union"),"alias"],xD=[...oa("morph"),"alias"],Bt=(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 Qt(e)},zn=(e)=>{let t="{ ";for(let[n,r]of Object.entries(e))t+=`${n}: ${Qt(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)=>oe(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 Xm extends Error{name="ToJsonSchemaError";code;context;constructor(e,t){super(oe(t,{quoteKeys:!1,indent:4}));this.code=e,this.context=t}hasCode(e){return this.code===e}}var $k={target:"draft-2020-12",dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:(e)=>ke.throw("arrayObject",e),arrayPostfix:(e)=>ke.throw("arrayPostfix",e),defaultValue:(e)=>ke.throw("defaultValue",e),domain:(e)=>ke.throw("domain",e),morph:(e)=>ke.throw("morph",e),patternIntersection:(e)=>ke.throw("patternIntersection",e),predicate:(e)=>ke.throw("predicate",e),proto:(e)=>ke.throw("proto",e),symbolKey:(e)=>ke.throw("symbolKey",e),unit:(e)=>ke.throw("unit",e),date:(e)=>ke.throw("date",e)}},ke={Error:Xm,throw:(...e)=>{throw new ke.Error(...e)},throwInternalOperandError:(e,t)=>pe(`Unexpected JSON Schema input for ${e}: ${oe(t)}`),defaultConfig:$k};F.config??={};var ds=(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]=su(e.toJsonSchema,t.toJsonSchema);else if(si(r))n[r]={...e[r],...t[r]};else n[r]=t[r]}return n},kk={"draft-2020-12":"https://json-schema.org/draft/2020-12/schema","draft-07":"http://json-schema.org/draft-07/schema#"},su=(e,t)=>{if(!e)return Ym(t??{},void 0);if(!t)return e;let n={...e},r;for(r in t)if(r==="fallback")n.fallback=Ek(e.fallback,t.fallback);else n[r]=t[r];return Ym(n,t)},Ym=(e,t)=>{if(t?.dialect!==void 0)return e;if(t?.target!==void 0)return{...e,dialect:kk[t.target]};return e},Ek=(e,t)=>{e=Zm(e),t=Zm(t);let n={},r;for(r in ke.defaultConfig.fallback)n[r]=t[r]??t.default??e[r]??e.default??ke.defaultConfig.fallback[r];return n},Zm=(e)=>typeof e==="function"?{default:e}:e??{};class Jn extends es{[ft]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:e,relativePath:t,...n},r){super();this.input=n,this.ctx=r,bm(this,n);let s=r.data;if(n.code==="union")n.errors=n.errors.flatMap((a)=>{let c=a.hasCode("union")?a.errors:[a];if(!e&&!t)return c;return c.map((l)=>l.transform((u)=>({...u,path:hm(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 cs(...o),this.data="data"in n?n.data:s}transform(e){return new Jn(e({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(e){return this.code===e}get propString(){return kn(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 kt extends Yo{[ft]="errors";ctx;constructor(e){super();this.ctx=e}byPath=Object.create(null);get flatByPath(){return se(this.byPath,(e,t)=>[e,t.flat])}get flatProblemsByPath(){return se(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 ou(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 Jn({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 kt(this.ctx);for(let n of this)t.add(e(n));return t}merge(e){for(let t of e)this.add(new Jn({...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(`
543
+ `)}addAncestorPaths(e){for(let t of e.path.stringifyAncestors())this.byAncestorPath[t]=fe(this.byAncestorPath[t],e)}}class ou extends Error{name="TraversalError";constructor(e){if(e.length===1)super(e.summary);else super(`
544
+ `+e.map((t)=>` \u2022 ${Ak(t)}`).join(`
545
+ `));Object.defineProperty(this,"arkErrors",{value:e,enumerable:!1})}}var Ak=(e)=>e.toString().split(`
551
546
  `).join(`
552
- `);class Zt{path=[];errors=new St(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 xn(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 zi(...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 Un(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=Re(s),a=s(r===void 0?this.root:r[n],this);if(a instanceof Un){if(!this.errors.includes(a))this.errors.add(a);break}if(a instanceof St){if(!o)this.errors.merge(a);this.queuedMorphs=[];break}if(r===void 0)this.root=a;else r[n]=a;this.applyQueuedMorphs()}}}var Rt=(e,t,n)=>{if(!n)return t();n.path.push(e);let r=t();return n.path.pop(),r};class Qi extends $t{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)=>PR(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((c)=>vm(c,a))){this.flatRefs.push(a);for(let c of a.node.branches)if(c.hasKind("morph")||c.hasKind("intersection")&&c.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:a.path,propString:a.propString,node:c})}}}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 Zt(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 Zt(t,this.$.resolvedConfig);return this.traverseApply(t,r),r.finalize(n)};case"contextual":return(t,n)=>{let r=new Zt(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 Zt(t,this.$.resolvedConfig);return this.traverseApply(t,r),r.finalize(n)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,me(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=OR(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=Wr(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=Re(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)nr(`${this.kind} node was not of asserted kind ${e}`);return this}hasKindIn(...e){return e.includes(this.kind)}assertHasKindIn(...e){if(!Lt(e,this.kind))nr(`${this.kind} node was not one of asserted kinds ${e}`);return this}isBasis(){return Lt(hm,this.kind)}isConstraint(){return Lt(qo,this.kind)}isStructural(){return Lt(qr,this.kind)}isRefinement(){return Lt(Ml,this.kind)}isRoot(){return Lt(Hr,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=Zi.normalize(e);return this._select(t)}_select(e){let t=Zi.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 Zi.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=ne(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(Re(a))return r=a;let c=Object.keys(a);if((c.length===0||c.length===1&&c[0]==="meta")&&!cn(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in a))return t.undeclaredKeyHandling?{...a,value:M.intrinsic.unknown}:null;if(this.kind==="morph")a.in??=M.intrinsic.unknown;return r=n.node(this.kind,a,t.parseOptions)}configureReferences(e,t="references"){let n=Zi.normalize(t),r=typeof e==="string"?(c,l)=>({...l,meta:{...l.meta,description:e}}):typeof e==="function"?(c,l)=>({...l,meta:e(l.meta)}):(c,l)=>({...l,meta:{...l.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&&Nn(s),a=n.boundary==="child"?(c,l)=>l.root.children.includes(c):n.boundary==="shallow"?(c)=>c.kind!=="structure":()=>!0;return this.$.finalize(this.transform(r,{shouldTransform:a,selected:o}))}}var Zi={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)nr(bm(t,n));return e},find:(e)=>e[0],assertFind:(e,t,n)=>{if(e.length===0)nr(bm(t,n));return e[0]}},normalize:(e)=>typeof e==="function"?{boundary:"references",method:"filter",where:e}:typeof e==="string"?ze(e,Zi.applyBoundary)?{method:"filter",boundary:e}:{boundary:"references",method:"filter",kind:e}:{boundary:"references",method:"filter",...e}},bm=(e,t)=>`${e} had no references matching ${re(t)}.`,CR=(e)=>xn(e,{stringifyNonKey:(t)=>t.expression}),IR=/"(\$ark\.[^"]+)"/g,OR=(e)=>JSON.stringify(e).replace(IR,"$1"),Qt=(e,t)=>({path:e,node:t,propString:CR(e)}),vm=(e,t)=>e.propString===t.propString&&e.node.equals(t.node),Dl=(e,t)=>an(e,t,{isEqual:vm}),PR=(e,t)=>an(e,t,{isEqual:(n,r)=>n.equals(r)});class L extends Array{static init(e,t,n,r){return new L({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=xn(e);return Ll(`Intersection${r&&` at ${r}`} of ${xm(t,n)}`)}return`The following intersections result in unsatisfiable types:
553
- \u2022 ${this.map(({path:e,l:t,r:n})=>`${e}: ${xm(t,n)}`).join(`
554
- \u2022 `)}`}throw(){return E(this.describeReasons())}invert(){let e=this.map((t)=>({...t,l:t.r,r:t.l}));if(!(e instanceof L))return new L(...e);return e}withPrefixKey(e,t){return this.map((n)=>({...n,path:[e,...n.path],optional:n.optional||t==="optional"}))}toNeverIfDisjoint(){return M.intrinsic.never}}var xm=(e,t)=>`${Fl(e)} and ${Fl(t)}`,Fl=(e)=>Re(e)?e.expression:Se(e)?e.map(Fl).join(" | ")||"never":String(e),Ll=(e)=>`${e} results in an unsatisfiable type`;var Vr={},kt=(e,t,n)=>ke(e,t,{$:n,invert:!1,pipe:!1}),es=(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(Vr[s]!==void 0)return Vr[s];if(!n.pipe){let c=`${t.hash}${r}${e.hash}`;if(Vr[c]!==void 0){let l=Vr[c],u=l instanceof L?l.invert():l;return Vr[s]=u,u}}let o=!n.pipe||!e.includesTransform&&!t.includesTransform;if(o&&e.equals(t))return e;let a=o?jl(e,t,n):e.hasKindIn(...Hr)?MR(e,t,n):jl(e,t,n);if(Re(a)){if(e.equals(a))a=e;else if(t.equals(a))a=t}return Vr[s]=a,a},jl=(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 L)o=o.invert();return o}},MR=(e,t,n)=>e.includesTransform||t.includesTransform?n.invert?$m(t,e,n):$m(e,t,n):jl(e,t,n),$m=(e,t,n)=>e.distribute((r)=>TR(r,t,n),(r)=>{let s=r.filter(Re);if(s.length===0)return L.init("union",e.branches,t.branches);if(s.length<e.branches.length||!e.branches.every((c,l)=>c.rawIn.equals(s[l].rawIn)))return n.$.parseSchema(s);let o;if(s.length===1){let c=s[0];if(!o)return c;return n.$.node("morph",{...c.inner,in:c.rawIn.configure(o,"self")})}let a={branches:s};if(o)a.meta=o;return n.$.parseSchema(a)}),TR=(e,t,n)=>{if(e.hasKind("morph")){let s=[...e.morphs];if(e.lastMorphIfNode){let o=ke(e.lastMorphIfNode,t,n);if(o instanceof L)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 L)return s;return n.$.node("morph",{morphs:[t],in:s})}return n.$.node("morph",{morphs:[t],in:e})};class Ut extends Qi{constructor(e,t){super(e,t);Object.defineProperty(this,ut,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(e){return kt(this,e,this.$)}}class $n extends Ut{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 jn(this.errorContext)}}var it=(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},Gr=(e)=>{let t=e.r.shift();if(!t){let r=e.l.length===0&&e.kind==="structure"?M.intrinsic.unknown.internal:e.ctx.$.node(e.kind,Object.assign(e.baseInner,NR(e.l)),{prereduced:!0});for(let s of e.roots){if(r instanceof L)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 L)return s;if(s.isRoot())return e.roots.push(s),e.l.splice(r),Gr(e);if(!n)e.l[r]=s,n=!0;else if(!e.l.includes(s))return me(`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)an(e.r,r)}return Gr(e)},zr=(e)=>Object.entries(e).flatMap(([n,r])=>(n in Ho)?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),NR=(e)=>{let t={};for(let n of e)if(n.hasOpenIntersection())t[n.kind]=fe(t[n.kind],n);else{if(t[n.kind])return me(`Unexpected intersection of closed refinements of kind ${n.kind}`);t[n.kind]=n}return t},Sm=(...e)=>E(Rm(...e)),Rm=(e,t,n)=>{let r=n.hasKind("morph")?"a morph":n.isUnknown()?"unknown":n.exclude(t).defaultShortDescription;return`${Yh(e)} operand must be ${t.description} (was ${r})`};var km=(e,t,n)=>new Bn(e,t,n,n,null);class Wo extends $t{}class Bn extends $t{[ut]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(e,t,n,r,s){super((...o)=>{let a=ne(this.names,(c,l)=>{let u=this.arg$.parse(o[c]);if(!u.extends(this.constraints[c]))E(DR(l,this.constraints[c].expression,u.expression));return[l,u]});if(this.defIsLazy()){let c=this.bodyDef(a);return this.$.parse(c)}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 Wo}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:lm(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((e)=>typeof e==="string"?[e,M.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 DR=(e,t,n)=>`${e} must be assignable to ${t} (was ${n})`;var FR=ie({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 Em extends Ut{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=jn(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 Ul={implementation:FR,Node:Em};var LR=ie({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(e)=>Number.isInteger(e)?e:E(jR(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/UR(e.rule,t.rule))})},obviatesBasisDescription:!0});class Am extends $n{traverseAllows=(e)=>e%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=M.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(e){if(e.type="integer",this.rule===1)return e;return e.multipleOf=this.rule,e}}var Bl={implementation:LR,Node:Am};var jR=(e)=>`divisor must be an integer (was ${e})`,UR=(e,t)=>{let n,r=e,s=t;while(s!==0)n=s,s=r%s,r=n;return r};class Ot extends $n{boundOperandKind=KR[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=WR(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${BR[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?VR(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 BR={"<":">=","<=":">",">":"<=",">=":"<"},qR={min:"max",minLength:"maxLength",after:"before"},Vo={parse:(e)=>e||void 0},Go=(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},zo=(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},Jo=(e)=>typeof e==="string"||typeof e==="number"?new Date(e):e,HR=(e,t)=>`${e} bound must be a positive integer (was ${t})`,Jr=(e)=>(t)=>{if(!Number.isInteger(t)||t<0)E(HR(e,t));return t},KR={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},WR=(e,t)=>`${ze(e,qR)?">":"<"}${t?"":"="}`,VR=(e)=>typeof e==="string"?e:new Date(e).toLocaleString(),Cm=(e)=>`Bounded expression ${e} must be exactly one of number, string, Array, or Date`;var GR=ie({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Jo,serialize:(e)=>e.toISOString()}},normalize:zo("after"),defaults:{description:(e)=>`${e.collapsibleLimitString} or later`,actual:ar},intersections:{after:(e,t)=>e.isStricterThan(t)?e:t}});class Im extends Ot{impliedBasis=M.intrinsic.Date.internal;collapsibleLimitString=ar(this.rule);traverseAllows=(e)=>e>=this.rule;reduceJsonSchema(e,t){return t.fallback.date({code:"date",base:e,after:this.rule})}}var ql={implementation:GR,Node:Im};var zR=ie({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Jo,serialize:(e)=>e.toISOString()}},normalize:zo("before"),defaults:{description:(e)=>`${e.collapsibleLimitString} or earlier`,actual:ar},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:L.init("range",e,t)}});class Om extends Ot{collapsibleLimitString=ar(this.rule);traverseAllows=(e)=>e<=this.rule;impliedBasis=M.intrinsic.Date.internal;reduceJsonSchema(e,t){return t.fallback.date({code:"date",base:e,before:this.rule})}}var Hl={implementation:zR,Node:Om};var JR=ie({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:Jr("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)=>L.init("unit",n.$.node("unit",{unit:e.rule}),n.$.node("unit",{unit:t.rule}),{path:["length"]}),minLength:(e,t)=>e.rule>=t.rule?e:L.init("range",e,t),maxLength:(e,t)=>e.rule<=t.rule?e:L.init("range",e,t)}});class Pm extends $n{traverseAllows=(e)=>e.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=M.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 Ce.throwInternalOperandError("exactLength",e)}}}var Kl={implementation:JR,Node:Pm};var XR=ie({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:Vo},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:L.init("range",e,t)},obviatesBasisDescription:!0});class Mm extends Ot{impliedBasis=M.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 Wl={implementation:XR,Node:Mm};var YR=ie({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Jr("maxLength")}},reduce:(e,t)=>e.rule===0?t.node("exactLength",e):void 0,normalize:Go("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:L.init("range",e,t)}});class Tm extends Ot{impliedBasis=M.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 Ce.throwInternalOperandError("maxLength",e)}}}var Vl={implementation:YR,Node:Tm};var ZR=ie({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:Vo},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 Nm extends Ot{impliedBasis=M.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 Gl={implementation:ZR,Node:Nm};var QR=ie({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Jr("minLength")}},reduce:(e)=>e.rule===0?M.intrinsic.unknown:void 0,normalize:Go("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 Dm extends Ot{impliedBasis=M.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 Ce.throwInternalOperandError("minLength",e)}}}var zl={implementation:QR,Node:Dm};var Fm={min:Gl.implementation,max:Wl.implementation,minLength:zl.implementation,maxLength:Vl.implementation,exactLength:Kl.implementation,after:ql.implementation,before:Hl.implementation},Lm={min:Gl.Node,max:Wl.Node,minLength:zl.Node,maxLength:Vl.Node,exactLength:Kl.Node,after:ql.Node,before:Hl.Node};var ek=ie({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 jm extends $n{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=M.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 Jl={implementation:ek,Node:jm};var ts=(e,t)=>{let n=tk(e);if(t&&!t.includes(n))return E(`Root of kind ${n} should be one of ${t}`);return n},tk=(e)=>{if(Z(e,"root"))return e.kind;if(typeof e==="string")return e[0]==="$"?"alias":(e in vt)?"domain":"proto";if(typeof e==="function")return"proto";if(typeof e!=="object"||e===null)return E(Um(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 Ho)))return"intersection";if("proto"in e)return"proto";if("domain"in e)return"domain";return E(Um(e))},Um=(e)=>`${re(e)} is not a valid type schema`,Bm={},nk=(e)=>Se(e)?e.map((t)=>t.collapsibleJson):e.collapsibleJson,dt={};M.nodesByRegisteredId=dt;var Xl=(e)=>(Bm[e]??=0,`${e}${++Bm[e]}`),Yl=(e)=>{let t=Xr[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,c=bl(o).sort(([u],[d])=>Kr(u)?Kr(d)?Wr(u)-Wr(d):1:Kr(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 c){let d=u[0],f=t.keys[d];if(!f)return E(`Key ${d} is not valid on ${e.kind} schema`);let p=f.parse?f.parse(u[1],e):u[1];if(p!==xt&&(p!==void 0||f.preserveUndefined))r[d]=p}if(t.reduce&&!e.prereduced){let u=t.reduce(r,e.$);if(u){if(u instanceof L)return u.throw();return rk(u,a)}}return Zl({id:e.id,kind:e.kind,inner:r,meta:a,$:e.$})},Zl=({id:e,kind:t,inner:n,meta:r,$:s,ignoreCache:o})=>{let a=Xr[t],c=bl(n),l=[],u={};for(let[g,R]of c){let N=a.keys[g],I=N.serialize??(N.child?nk:jt);if(u[g]=I(R),N.child===!0){let _=R;if(Se(_))l.push(..._);else l.push(_)}else if(typeof N.child==="function")l.push(...N.child(R))}if(a.finalizeInnerJson)u=a.finalizeInnerJson(u);let d={...u},f={};if(!cn(r))f=ne(r,(g,R)=>[g,g==="examples"?R:jt(R)]),d.meta=Xo(f,"description",!0);u=Xo(u,a.collapsibleKey,!1);let p=JSON.stringify({kind:t,...u});d=Xo(d,a.collapsibleKey,!1);let h=Xo(d,a.collapsibleKey,!0),y=JSON.stringify({kind:t,...d});if(s.nodesByHash[y]&&!o)return s.nodesByHash[y];let v={id:e,kind:t,impl:a,inner:n,innerEntries:c,innerJson:u,innerHash:p,meta:r,metaJson:f,json:d,hash:y,collapsibleJson:h,children:l};if(t!=="intersection"){for(let g in n)if(g!=="in"&&g!=="out")v[g]=n[g]}let b=new Hm[t](v,s);return s.nodesByHash[y]=b},qm=(e,t)=>{if(e.id===t)return e;if(Re(dt[t]))me(`Unexpected attempt to overwrite node id ${t}`);return Zl({id:t,kind:e.kind,inner:e.inner,meta:e.meta,$:e.$,ignoreCache:!0})},rk=(e,t,n)=>{if(n&&Re(dt[n]))me(`Unexpected attempt to overwrite node id ${n}`);return Zl({id:n??Xl(t.alias??e.kind),kind:e.kind,inner:e.inner,meta:t,$:e.$})},Xo=(e,t,n)=>{let r=Object.keys(e);if(r.length===1&&r[0]===t){let s=e[t];if(n)return s;if(bt(s,"object")&&(Object.keys(s).length===1||Array.isArray(s)))return s}return e};var ns=(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 L)if(o==="optional")s=M.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:E(Ql(e.default,t.default)):e.default:t.hasDefault()?t.default:xt;return n.$.node("optional",{key:r,value:s,default:a})};class rs extends Ut{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=M.intrinsic.object.internal;serializedKey=Yt(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=fe(this.value.flatRefs.map((e)=>Qt([this.key,...e.path],e.node)),Qt([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 Rt(this.key,()=>this.value.traverseAllows(e[this.key],t),t);return this.optional};traverseApply=(e,t)=>{if(this.key in e)Rt(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 Ql=(e,t)=>`Invalid intersection of default values ${re(e)} & ${re(t)}`;var ik=ie({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:ns}});class Km extends rs{constructor(...e){super(...e);if("default"in this.inner)ss(this.value,this.inner.default,this.key)}get rawIn(){let e=super.rawIn;if(!this.hasDefault())return e;return this.$.node("optional",Do(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} = ${re(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=ok(this);defaultValueMorphRef=this.defaultValueMorph&&Me(this.defaultValueMorph)}var is={implementation:ik,Node:Km},sk={},ok=(e)=>{if(!e.hasDefault())return;let t=`{${e.compiledKey}: ${e.value.id} = ${jt(e.default)}}`;return sk[t]??=eu(e.key,e.value,e.default)},eu=(e,t,n)=>{if(typeof n==="function")return t.includesTransform?(s,o)=>(Rt(e,()=>t(s[e]=n(),o),o),s):(s)=>(s[e]=n(),s);let r=t.includesTransform?t.assert(n):n;return bt(r,"object")?(s,o)=>(Rt(e,()=>t(s[e]=n,o),o),s):(s)=>(s[e]=r,s)},ss=(e,t,n)=>{let r=Dn(t);if(bt(t,"object")&&!r)E(ak(n));let s=e.in(r?t():t);if(s instanceof St){if(n===null)E(`Default ${s.summary}`);let o=s.transform((a)=>a.transform((c)=>({...c,prefixPath:[n]})));E(`Default for ${o.summary}`)}return t},ak=(e)=>`Non-primitive default ${e===null?"":typeof e==="number"?`for value at [${e}] `:`for ${Yt(e)} `}must be specified as a function like () => ({my: 'object'})`;class Bt extends Qi{constructor(e,t){super(e,t);Object.defineProperty(this,ut,{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 St)return t;return{value:t}},jsonSchema:{input:(e)=>this.rawIn.toJsonSchema({target:Wm(e.target),...e.libraryOptions}),output:(e)=>this.rawOut.toJsonSchema({target:Wm(e.target),...e.libraryOptions})}}}as(){return this}brand(e){if(e==="")return E(ck);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=Tl(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=ne(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 L)return n;return this.$.finalize(n)}rawIntersect(e){return kt(this,e,this.$)}toNeverIfDisjoint(){return this}and(e){let t=this.intersect(e);return t instanceof L?t.throw():t}rawAnd(e){let t=this.rawIntersect(e);return t instanceof L?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(),M.intrinsic.unknown.internal);if(e.branches.length===0)E(Ll(`keyof ${this.expression}`));return this._keyof=this.$.finalize(e)}get props(){if(this.branches.length!==1)return E(uk(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(e){let t=this.$.parseDefinition(e);return this.$.schema(t.distribute((n)=>this.applyStructuralOperation("merge",[Vm(n)??E(Gm("merge",n.expression))])))}applyStructuralOperation(e,t){return this.distribute((n)=>{if(n.equals(M.intrinsic.object)&&e!=="merge")return n;let r=Vm(n);if(!r)E(Gm(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 L)}extends(e){if(this.isNever())return!0;let t=this.intersect(e);return!(t instanceof L)&&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 ss(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(Z(r,"root")?r:(s,o)=>{try{return r(s,o)}catch(a){return o.error({code:"predicate",predicate:r,actual:`aborted due to error:
547
+ `);class en{path=[];errors=new kt(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 kn(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 cs(...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 Jn(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=Se(s),a=s(r===void 0?this.root:r[n],this);if(a instanceof Jn){if(!this.errors.includes(a))this.errors.add(a);break}if(a instanceof kt){if(!o)this.errors.merge(a);this.queuedMorphs=[];break}if(r===void 0)this.root=a;else r[n]=a;this.applyQueuedMorphs()}}}var Et=(e,t,n)=>{if(!n)return t();n.path.push(e);let r=t();return n.path.pop(),r};class hs extends $t{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)=>Pk(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((c)=>eg(c,a))){this.flatRefs.push(a);for(let c of a.node.branches)if(c.hasKind("morph")||c.hasKind("intersection")&&c.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:a.path,propString:a.propString,node:c})}}}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 en(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 en(t,this.$.resolvedConfig);return this.traverseApply(t,r),r.finalize(n)};case"contextual":return(t,n)=>{let r=new en(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 en(t,this.$.resolvedConfig);return this.traverseApply(t,r),r.finalize(n)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,pe(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=Ok(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=oi(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]=xe(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=Se(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)gr(`${this.kind} node was not of asserted kind ${e}`);return this}hasKindIn(...e){return e.includes(this.kind)}assertHasKindIn(...e){if(!Ut(e,this.kind))gr(`${this.kind} node was not one of asserted kinds ${e}`);return this}isBasis(){return Ut(Gm,this.kind)}isConstraint(){return Ut(ia,this.kind)}isStructural(){return Ut(ri,this.kind)}isRefinement(){return Ut(iu,this.kind)}isRoot(){return Ut(ii,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=ps.normalize(e);return this._select(t)}_select(e){let t=ps.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 ps.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=se(this.inner,(u,d)=>{if(!this.impl.keys[u].child)return[u,d];let f=d;if(!xe(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(Se(a))return r=a;let c=Object.keys(a);if((c.length===0||c.length===1&&c[0]==="meta")&&!dn(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in a))return t.undeclaredKeyHandling?{...a,value:F.intrinsic.unknown}:null;if(this.kind==="morph")a.in??=F.intrinsic.unknown;return r=n.node(this.kind,a,t.parseOptions)}configureReferences(e,t="references"){let n=ps.normalize(t),r=typeof e==="string"?(c,l)=>({...l,meta:{...l.meta,description:e}}):typeof e==="function"?(c,l)=>({...l,meta:e(l.meta)}):(c,l)=>({...l,meta:{...l.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&&Kn(s),a=n.boundary==="child"?(c,l)=>l.root.children.includes(c):n.boundary==="shallow"?(c)=>c.kind!=="structure":()=>!0;return this.$.finalize(this.transform(r,{shouldTransform:a,selected:o}))}}var ps={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)gr(Qm(t,n));return e},find:(e)=>e[0],assertFind:(e,t,n)=>{if(e.length===0)gr(Qm(t,n));return e[0]}},normalize:(e)=>typeof e==="function"?{boundary:"references",method:"filter",where:e}:typeof e==="string"?ze(e,ps.applyBoundary)?{method:"filter",boundary:e}:{boundary:"references",method:"filter",kind:e}:{boundary:"references",method:"filter",...e}},Qm=(e,t)=>`${e} had no references matching ${oe(t)}.`,Ck=(e)=>kn(e,{stringifyNonKey:(t)=>t.expression}),Ik=/"(\$ark\.[^"]+)"/g,Ok=(e)=>JSON.stringify(e).replace(Ik,"$1"),tn=(e,t)=>({path:e,node:t,propString:Ck(e)}),eg=(e,t)=>e.propString===t.propString&&e.node.equals(t.node),au=(e,t)=>un(e,t,{isEqual:eg}),Pk=(e,t)=>un(e,t,{isEqual:(n,r)=>n.equals(r)});class U extends Array{static init(e,t,n,r){return new U({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=kn(e);return lu(`Intersection${r&&` at ${r}`} of ${tg(t,n)}`)}return`The following intersections result in unsatisfiable types:
548
+ \u2022 ${this.map(({path:e,l:t,r:n})=>`${e}: ${tg(t,n)}`).join(`
549
+ \u2022 `)}`}throw(){return A(this.describeReasons())}invert(){let e=this.map((t)=>({...t,l:t.r,r:t.l}));if(!(e instanceof U))return new U(...e);return e}withPrefixKey(e,t){return this.map((n)=>({...n,path:[e,...n.path],optional:n.optional||t==="optional"}))}toNeverIfDisjoint(){return F.intrinsic.never}}var tg=(e,t)=>`${cu(e)} and ${cu(t)}`,cu=(e)=>Se(e)?e.expression:xe(e)?e.map(cu).join(" | ")||"never":String(e),lu=(e)=>`${e} results in an unsatisfiable type`;var ai={},At=(e,t,n)=>Re(e,t,{$:n,invert:!1,pipe:!1}),ms=(e,t,n)=>Re(e,t,{$:n,invert:!1,pipe:!0}),Re=(e,t,n)=>{let r=n.pipe?"|>":"&",s=`${e.hash}${r}${t.hash}`;if(ai[s]!==void 0)return ai[s];if(!n.pipe){let c=`${t.hash}${r}${e.hash}`;if(ai[c]!==void 0){let l=ai[c],u=l instanceof U?l.invert():l;return ai[s]=u,u}}let o=!n.pipe||!e.includesTransform&&!t.includesTransform;if(o&&e.equals(t))return e;let a=o?uu(e,t,n):e.hasKindIn(...ii)?Mk(e,t,n):uu(e,t,n);if(Se(a)){if(e.equals(a))a=e;else if(t.equals(a))a=t}return ai[s]=a,a},uu=(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 U)o=o.invert();return o}},Mk=(e,t,n)=>e.includesTransform||t.includesTransform?n.invert?ng(t,e,n):ng(e,t,n):uu(e,t,n),ng=(e,t,n)=>e.distribute((r)=>Tk(r,t,n),(r)=>{let s=r.filter(Se);if(s.length===0)return U.init("union",e.branches,t.branches);if(s.length<e.branches.length||!e.branches.every((c,l)=>c.rawIn.equals(s[l].rawIn)))return n.$.parseSchema(s);let o;if(s.length===1){let c=s[0];if(!o)return c;return n.$.node("morph",{...c.inner,in:c.rawIn.configure(o,"self")})}let a={branches:s};if(o)a.meta=o;return n.$.parseSchema(a)}),Tk=(e,t,n)=>{if(e.hasKind("morph")){let s=[...e.morphs];if(e.lastMorphIfNode){let o=Re(e.lastMorphIfNode,t,n);if(o instanceof U)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=Re(e,t.rawIn,n);if(s instanceof U)return s;return n.$.node("morph",{morphs:[t],in:s})}return n.$.node("morph",{morphs:[t],in:e})};class qt extends hs{constructor(e,t){super(e,t);Object.defineProperty(this,ft,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(e){return At(this,e,this.$)}}class En extends qt{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 zn(this.errorContext)}}var ot=(e)=>(t,n)=>{if(xe(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},ci=(e)=>{let t=e.r.shift();if(!t){let r=e.l.length===0&&e.kind==="structure"?F.intrinsic.unknown.internal:e.ctx.$.node(e.kind,Object.assign(e.baseInner,Fk(e.l)),{prereduced:!0});for(let s of e.roots){if(r instanceof U)return r;r=Re(s,r,e.ctx)}return r}let n=!1;for(let r=0;r<e.l.length;r++){let s=Re(e.l[r],t,e.ctx);if(s===null)continue;if(s instanceof U)return s;if(s.isRoot())return e.roots.push(s),e.l.splice(r),ci(e);if(!n)e.l[r]=s,n=!0;else if(!e.l.includes(s))return pe(`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)un(e.r,r)}return ci(e)},li=(e)=>Object.entries(e).flatMap(([n,r])=>(n in sa)?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),Fk=(e)=>{let t={};for(let n of e)if(n.hasOpenIntersection())t[n.kind]=fe(t[n.kind],n);else{if(t[n.kind])return pe(`Unexpected intersection of closed refinements of kind ${n.kind}`);t[n.kind]=n}return t},rg=(...e)=>A(ig(...e)),ig=(e,t,n)=>{let r=n.hasKind("morph")?"a morph":n.isUnknown()?"unknown":n.exclude(t).defaultShortDescription;return`${Im(e)} operand must be ${t.description} (was ${r})`};var sg=(e,t,n)=>new Xn(e,t,n,n,null);class aa extends $t{}class Xn extends $t{[ft]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(e,t,n,r,s){super((...o)=>{let a=se(this.names,(c,l)=>{let u=this.arg$.parse(o[c]);if(!u.extends(this.constraints[c]))A(Nk(l,this.constraints[c].expression,u.expression));return[l,u]});if(this.defIsLazy()){let c=this.bodyDef(a);return this.$.parse(c)}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:qm(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((e)=>typeof e==="string"?[e,F.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 Nk=(e,t,n)=>`${e} must be assignable to ${t} (was ${n})`;var Dk=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 og extends qt{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=zn(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 du={implementation:Dk,Node:og};var Lk=ae({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(e)=>Number.isInteger(e)?e:A(jk(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/Uk(e.rule,t.rule))})},obviatesBasisDescription:!0});class ag extends En{traverseAllows=(e)=>e%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=F.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(e){if(e.type="integer",this.rule===1)return e;return e.multipleOf=this.rule,e}}var fu={implementation:Lk,Node:ag};var jk=(e)=>`divisor must be an integer (was ${e})`,Uk=(e,t)=>{let n,r=e,s=t;while(s!==0)n=s,s=r%s,r=n;return r};class Pt extends En{boundOperandKind=Kk[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=Wk(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${Bk[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?Vk(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 Bk={"<":">=","<=":">",">":"<=",">=":"<"},qk={min:"max",minLength:"maxLength",after:"before"},ca={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},ua=(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},da=(e)=>typeof e==="string"||typeof e==="number"?new Date(e):e,Hk=(e,t)=>`${e} bound must be a positive integer (was ${t})`,ui=(e)=>(t)=>{if(!Number.isInteger(t)||t<0)A(Hk(e,t));return t},Kk={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},Wk=(e,t)=>`${ze(e,qk)?">":"<"}${t?"":"="}`,Vk=(e)=>typeof e==="string"?e:new Date(e).toLocaleString(),cg=(e)=>`Bounded expression ${e} must be exactly one of number, string, Array, or Date`;var Gk=ae({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:da,serialize:(e)=>e.toISOString()}},normalize:ua("after"),defaults:{description:(e)=>`${e.collapsibleLimitString} or later`,actual:vr},intersections:{after:(e,t)=>e.isStricterThan(t)?e:t}});class lg extends Pt{impliedBasis=F.intrinsic.Date.internal;collapsibleLimitString=vr(this.rule);traverseAllows=(e)=>e>=this.rule;reduceJsonSchema(e,t){return t.fallback.date({code:"date",base:e,after:this.rule})}}var pu={implementation:Gk,Node:lg};var zk=ae({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:da,serialize:(e)=>e.toISOString()}},normalize:ua("before"),defaults:{description:(e)=>`${e.collapsibleLimitString} or earlier`,actual:vr},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:U.init("range",e,t)}});class ug extends Pt{collapsibleLimitString=vr(this.rule);traverseAllows=(e)=>e<=this.rule;impliedBasis=F.intrinsic.Date.internal;reduceJsonSchema(e,t){return t.fallback.date({code:"date",base:e,before:this.rule})}}var hu={implementation:zk,Node:ug};var Jk=ae({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:ui("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)=>U.init("unit",n.$.node("unit",{unit:e.rule}),n.$.node("unit",{unit:t.rule}),{path:["length"]}),minLength:(e,t)=>e.rule>=t.rule?e:U.init("range",e,t),maxLength:(e,t)=>e.rule<=t.rule?e:U.init("range",e,t)}});class dg extends En{traverseAllows=(e)=>e.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=F.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 ke.throwInternalOperandError("exactLength",e)}}}var mu={implementation:Jk,Node:dg};var Xk=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:U.init("range",e,t)},obviatesBasisDescription:!0});class fg extends Pt{impliedBasis=F.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 gu={implementation:Xk,Node:fg};var Yk=ae({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:ui("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:U.init("range",e,t)}});class pg extends Pt{impliedBasis=F.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 ke.throwInternalOperandError("maxLength",e)}}}var _u={implementation:Yk,Node:pg};var Zk=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 hg extends Pt{impliedBasis=F.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 wu={implementation:Zk,Node:hg};var Qk=ae({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:ui("minLength")}},reduce:(e)=>e.rule===0?F.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 mg extends Pt{impliedBasis=F.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 ke.throwInternalOperandError("minLength",e)}}}var yu={implementation:Qk,Node:mg};var gg={min:wu.implementation,max:gu.implementation,minLength:yu.implementation,maxLength:_u.implementation,exactLength:mu.implementation,after:pu.implementation,before:hu.implementation},_g={min:wu.Node,max:gu.Node,minLength:yu.Node,maxLength:_u.Node,exactLength:mu.Node,after:pu.Node,before:hu.Node};var eE=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 wg extends En{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=F.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 bu={implementation:eE,Node:wg};var gs=(e,t)=>{let n=tE(e);if(t&&!t.includes(n))return A(`Root of kind ${n} should be one of ${t}`);return n},tE=(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 A(yg(e));if("morphs"in e)return"morph";if("branches"in e||xe(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 sa)))return"intersection";if("proto"in e)return"proto";if("domain"in e)return"domain";return A(yg(e))},yg=(e)=>`${oe(e)} is not a valid type schema`,bg={},nE=(e)=>xe(e)?e.map((t)=>t.collapsibleJson):e.collapsibleJson,pt={};F.nodesByRegisteredId=pt;var vu=(e)=>(bg[e]??=0,`${e}${++bg[e]}`),xu=(e)=>{let t=di[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,c=Wl(o).sort(([u],[d])=>si(u)?si(d)?oi(u)-oi(d):1:si(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 c){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!==Rt&&(p!==void 0||f.preserveUndefined))r[d]=p}if(t.reduce&&!e.prereduced){let u=t.reduce(r,e.$);if(u){if(u instanceof U)return u.throw();return rE(u,a)}}return Su({id:e.id,kind:e.kind,inner:r,meta:a,$:e.$})},Su=({id:e,kind:t,inner:n,meta:r,$:s,ignoreCache:o})=>{let a=di[t],c=Wl(n),l=[],u={};for(let[b,S]of c){let O=a.keys[b],I=O.serialize??(O.child?nE:Bt);if(u[b]=I(S),O.child===!0){let g=S;if(xe(g))l.push(...g);else l.push(g)}else if(typeof O.child==="function")l.push(...O.child(S))}if(a.finalizeInnerJson)u=a.finalizeInnerJson(u);let d={...u},f={};if(!dn(r))f=se(r,(b,S)=>[b,b==="examples"?S:Bt(S)]),d.meta=fa(f,"description",!0);u=fa(u,a.collapsibleKey,!1);let p=JSON.stringify({kind:t,...u});d=fa(d,a.collapsibleKey,!1);let h=fa(d,a.collapsibleKey,!0),_=JSON.stringify({kind:t,...d});if(s.nodesByHash[_]&&!o)return s.nodesByHash[_];let v={id:e,kind:t,impl:a,inner:n,innerEntries:c,innerJson:u,innerHash:p,meta:r,metaJson:f,json:d,hash:_,collapsibleJson:h,children:l};if(t!=="intersection"){for(let b in n)if(b!=="in"&&b!=="out")v[b]=n[b]}let y=new xg[t](v,s);return s.nodesByHash[_]=y},vg=(e,t)=>{if(e.id===t)return e;if(Se(pt[t]))pe(`Unexpected attempt to overwrite node id ${t}`);return Su({id:t,kind:e.kind,inner:e.inner,meta:e.meta,$:e.$,ignoreCache:!0})},rE=(e,t,n)=>{if(n&&Se(pt[n]))pe(`Unexpected attempt to overwrite node id ${n}`);return Su({id:n??vu(t.alias??e.kind),kind:e.kind,inner:e.inner,meta:t,$:e.$})},fa=(e,t,n)=>{let r=Object.keys(e);if(r.length===1&&r[0]===t){let s=e[t];if(n)return s;if(xt(s,"object")&&(Object.keys(s).length===1||Array.isArray(s)))return s}return e};var _s=(e,t,n)=>{if(e.key!==t.key)return null;let r=e.key,s=Re(e.value,t.value,n),o=e.required||t.required?"required":"optional";if(s instanceof U)if(o==="optional")s=F.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(Ru(e.default,t.default)):e.default:t.hasDefault()?t.default:Rt;return n.$.node("optional",{key:r,value:s,default:a})};class ws extends qt{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=F.intrinsic.object.internal;serializedKey=Qt(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=fe(this.value.flatRefs.map((e)=>tn([this.key,...e.path],e.node)),tn([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 Et(this.key,()=>this.value.traverseAllows(e[this.key],t),t);return this.optional};traverseApply=(e,t)=>{if(this.key in e)Et(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 Ru=(e,t)=>`Invalid intersection of default values ${oe(e)} & ${oe(t)}`;var iE=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(te.undefined)},{prereduced:!0})}},defaults:{description:(e)=>`${e.compiledKey}?: ${e.value.description}`},intersections:{optional:_s}});class Sg extends ws{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",Zo(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} = ${oe(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=oE(this);defaultValueMorphRef=this.defaultValueMorph&&Me(this.defaultValueMorph)}var ys={implementation:iE,Node:Sg},sE={},oE=(e)=>{if(!e.hasDefault())return;let t=`{${e.compiledKey}: ${e.value.id} = ${Bt(e.default)}}`;return sE[t]??=$u(e.key,e.value,e.default)},$u=(e,t,n)=>{if(typeof n==="function")return t.includesTransform?(s,o)=>(Et(e,()=>t(s[e]=n(),o),o),s):(s)=>(s[e]=n(),s);let r=t.includesTransform?t.assert(n):n;return xt(r,"object")?(s,o)=>(Et(e,()=>t(s[e]=n,o),o),s):(s)=>(s[e]=r,s)},bs=(e,t,n)=>{let r=Wn(t);if(xt(t,"object")&&!r)A(aE(n));let s=e.in(r?t():t);if(s instanceof kt){if(n===null)A(`Default ${s.summary}`);let o=s.transform((a)=>a.transform((c)=>({...c,prefixPath:[n]})));A(`Default for ${o.summary}`)}return t},aE=(e)=>`Non-primitive default ${e===null?"":typeof e==="number"?`for value at [${e}] `:`for ${Qt(e)} `}must be specified as a function like () => ({my: 'object'})`;class Ht extends hs{constructor(e,t){super(e,t);Object.defineProperty(this,ft,{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 kt)return t;return{value:t}},jsonSchema:{input:(e)=>this.rawIn.toJsonSchema({target:Rg(e.target),...e.libraryOptions}),output:(e)=>this.rawOut.toJsonSchema({target:Rg(e.target),...e.libraryOptions})}}}as(){return this}brand(e){if(e==="")return A(cE);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=su(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=se(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 U)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 U?t.throw():t}rawAnd(e){let t=this.rawIntersect(e);return t instanceof U?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(),F.intrinsic.unknown.internal);if(e.branches.length===0)A(lu(`keyof ${this.expression}`));return this._keyof=this.$.finalize(e)}get props(){if(this.branches.length!==1)return A(uE(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(e){let t=this.$.parseDefinition(e);return this.$.schema(t.distribute((n)=>this.applyStructuralOperation("merge",[$g(n)??A(kg("merge",n.expression))])))}applyStructuralOperation(e,t){return this.distribute((n)=>{if(n.equals(F.intrinsic.object)&&e!=="merge")return n;let r=$g(n);if(!r)A(kg(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 U)}extends(e){if(this.isNever())return!0;let t=this.intersect(e);return!(t instanceof U)&&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:
555
550
  ${a}
556
- `})}}),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=es(this,e,this.$);if(t instanceof L)return t.throw();return t}rawPipeOnce(e){if(Z(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:me(`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 Sm(t,r.impliedBasis,this);let o=this.$.node("intersection",{[r.kind]:r}),a=e==="out"?es(this,o,this.$):kt(this,o,this.$);if(a instanceof L)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"?Do(s,{undeclared:1}):{...s,undeclared:t}:s,n?void 0:{shouldTransform:(r)=>!Lt(qr,r.kind)}))}hasEqualMorphs(e){if(!this.includesTransform&&!e.includesTransform)return!0;if(!bn(this.shallowMorphs,e.shallowMorphs))return!1;if(!bn(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",Yr(e))}lessThan(e){return this.constrain("max",Yr(e))}atLeastLength(e){return this.constrain("minLength",e)}atMostLength(e){return this.constrain("maxLength",e)}moreThanLength(e){return this.constrain("minLength",Yr(e))}lessThanLength(e){return this.constrain("maxLength",Yr(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",Yr(e))}earlierThan(e){return this.constrain("before",Yr(e))}}var ck="Expected a non-empty brand name after #",zm=["draft-2020-12","draft-07"],lk=(e)=>`JSONSchema target '${e}' is not supported (must be ${zm.map((t)=>`"${t}"`).join(" or ")})`,Wm=(e)=>{if(!Lt(zm,e))E(lk(e));return e},Yr=(e)=>typeof e==="object"&&!(e instanceof Date)?{...e,exclusive:!0}:{rule:e,exclusive:!0},os=(e,t)=>Z(t,"root")?Z(e,"root")?e.extends(t):t.allows(e):Z(e,"root")?e.hasUnit(t):t===e,Vm=(e)=>{if(e.hasKind("morph"))return null;if(e.hasKind("intersection"))return e.inner.structure??(e.basis?.domain==="object"?e.$.bindReference(M.intrinsic.emptyStructure):null);if(e.isBasis()&&e.domain==="object")return e.$.bindReference(M.intrinsic.emptyStructure);return null},uk=(e)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
557
- ${e}`,Gm=(e,t)=>`${e} operand must be an object (was ${t})`;var ln=(e,t)=>ne(Ko(e),(n,r)=>[r,t]);var dk=(e)=>typeof e==="string"?{reference:e}:e,Jm=(e)=>e instanceof L?M.intrinsic.never.internal:e,fk=ie({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(e)=>e.startsWith("$")?e:`$ark.${e}`},resolve:{}},normalize:dk,defaults:{description:(e)=>e.reference},intersections:{alias:(e,t,n)=>n.$.lazilyResolve(()=>Jm(ke(e.resolution,t.resolution,n)),`${e.reference}${n.pipe?"=>":"&"}${t.reference}`),...ln("alias",(e,t,n)=>{if(t.isUnknown())return e;if(t.isNever())return t;if(t.isBasis()&&!t.overlaps(M.intrinsic.object))return L.init("assignability",M.intrinsic.object,t);return n.$.lazilyResolve(()=>Jm(ke(e.resolution,t,n)),`${e.reference}${n.pipe?"=>":"&"}${t.id}`)})}});class Xm extends Bt{expression=this.reference;structure=void 0;get resolution(){let e=this._resolve();return dt[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=dt[e],n=[];while(Z(t,"context")){if(n.includes(t.id))return E(pk(t.id,n));n.push(t.id),t=dt[t.id]}if(!Z(t,"root"))return me(`Unexpected resolution for reference ${this.reference}
551
+ `})}}),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=ms(this,e,this.$);if(t instanceof U)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:pe(`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 rg(t,r.impliedBasis,this);let o=this.$.node("intersection",{[r.kind]:r}),a=e==="out"?ms(this,o,this.$):At(this,o,this.$);if(a instanceof U)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"?Zo(s,{undeclared:1}):{...s,undeclared:t}:s,n?void 0:{shouldTransform:(r)=>!Ut(ri,r.kind)}))}hasEqualMorphs(e){if(!this.includesTransform&&!e.includesTransform)return!0;if(!Rn(this.shallowMorphs,e.shallowMorphs))return!1;if(!Rn(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",fi(e))}lessThan(e){return this.constrain("max",fi(e))}atLeastLength(e){return this.constrain("minLength",e)}atMostLength(e){return this.constrain("maxLength",e)}moreThanLength(e){return this.constrain("minLength",fi(e))}lessThanLength(e){return this.constrain("maxLength",fi(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",fi(e))}earlierThan(e){return this.constrain("before",fi(e))}}var cE="Expected a non-empty brand name after #",Eg=["draft-2020-12","draft-07"],lE=(e)=>`JSONSchema target '${e}' is not supported (must be ${Eg.map((t)=>`"${t}"`).join(" or ")})`,Rg=(e)=>{if(!Ut(Eg,e))A(lE(e));return e},fi=(e)=>typeof e==="object"&&!(e instanceof Date)?{...e,exclusive:!0}:{rule:e,exclusive:!0},vs=(e,t)=>X(t,"root")?X(e,"root")?e.extends(t):t.allows(e):X(e,"root")?e.hasUnit(t):t===e,$g=(e)=>{if(e.hasKind("morph"))return null;if(e.hasKind("intersection"))return e.inner.structure??(e.basis?.domain==="object"?e.$.bindReference(F.intrinsic.emptyStructure):null);if(e.isBasis()&&e.domain==="object")return e.$.bindReference(F.intrinsic.emptyStructure);return null},uE=(e)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
552
+ ${e}`,kg=(e,t)=>`${e} operand must be an object (was ${t})`;var fn=(e,t)=>se(oa(e),(n,r)=>[r,t]);var dE=(e)=>typeof e==="string"?{reference:e}:e,Ag=(e)=>e instanceof U?F.intrinsic.never.internal:e,fE=ae({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(e)=>e.startsWith("$")?e:`$ark.${e}`},resolve:{}},normalize:dE,defaults:{description:(e)=>e.reference},intersections:{alias:(e,t,n)=>n.$.lazilyResolve(()=>Ag(Re(e.resolution,t.resolution,n)),`${e.reference}${n.pipe?"=>":"&"}${t.reference}`),...fn("alias",(e,t,n)=>{if(t.isUnknown())return e;if(t.isNever())return t;if(t.isBasis()&&!t.overlaps(F.intrinsic.object))return U.init("assignability",F.intrinsic.object,t);return n.$.lazilyResolve(()=>Ag(Re(e.resolution,t,n)),`${e.reference}${n.pipe?"=>":"&"}${t.id}`)})}});class Cg extends Ht{expression=this.reference;structure=void 0;get resolution(){let e=this._resolve();return pt[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=pt[e],n=[];while(X(t,"context")){if(n.includes(t.id))return A(pE(t.id,n));n.push(t.id),t=pt[t.id]}if(!X(t,"root"))return pe(`Unexpected resolution for reference ${this.reference}
558
553
  Seen: [${n.join("->")}]
559
- Resolution: ${re(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(Z(t,"root"))return t.id;return me(`Unexpected resolution for reference ${this.reference}: ${re(t)}`)}get defaultShortDescription(){return vt.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]=fe(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]=fe(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 pk=(e,t)=>`Alias '${e}' has a shallow resolution cycle: ${[...t,e].join("->")}`,as={implementation:fk,Node:Xm};class cr extends Bt{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 jn(this.errorContext)}compile(e){if(e.traversalKind==="Allows")e.return(this.compiledCondition);else e.if(this.compiledNegation,()=>e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}}var hk=ie({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(e)=>typeof e==="string"?{domain:e}:Ur(e,"numberAllowsNaN")&&e.domain!=="number"?E(Yo.writeBadAllowNanMessage(e.domain)):e,applyConfig:(e,t)=>e.numberAllowsNaN===void 0&&e.domain==="number"&&t.numberAllowsNaN?{...e,numberAllowsNaN:!0}:e,defaults:{description:(e)=>vt[e.domain],actual:(e)=>Number.isNaN(e)?"NaN":vt[Ge(e)]},intersections:{domain:(e,t)=>e.domain==="number"&&t.domain==="number"?e.numberAllowsNaN?t:e:L.init("domain",e,t)}});class Ym extends cr{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?(e)=>typeof e==="number"&&!Number.isNaN(e):(e)=>Ge(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 vt[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 Yo={implementation:hk,Node:Ym,writeBadAllowNanMessage:(e)=>`numberAllowsNaN may only be specified with domain "number" (was ${e})`};var mk=ie({kind:"intersection",hasAssociatedError:!0,normalize:(e)=>{if(Re(e))return e;let{structure:t,...n}=e,r=!!t,s=t??{},o=ne(n,(a,c)=>{if(ze(a,mm)){if(r)E(`Flattened structure key ${a} cannot be specified alongside a root 'structure' key.`);return s[a]=c,[]}return[a,c]});if(Z(s,"constraint")||!cn(s))o.structure=s;return o},finalizeInnerJson:({structure:e,...t})=>bt(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:it("divisor")},max:{child:!0,parse:it("max")},min:{child:!0,parse:it("min")},maxLength:{child:!0,parse:it("maxLength")},minLength:{child:!0,parse:it("minLength")},exactLength:{child:!0,parse:it("exactLength")},before:{child:!0,parse:it("before")},after:{child:!0,parse:it("after")},pattern:{child:!0,parse:it("pattern")},predicate:{child:!0,parse:it("predicate")}},reduce:(e,t)=>Zm({},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(`
554
+ Resolution: ${oe(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 pe(`Unexpected resolution for reference ${this.reference}: ${oe(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]=fe(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]=fe(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 pE=(e,t)=>`Alias '${e}' has a shallow resolution cycle: ${[...t,e].join("->")}`,xs={implementation:fE,Node:Cg};class xr extends Ht{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 zn(this.errorContext)}compile(e){if(e.traversalKind==="Allows")e.return(this.compiledCondition);else e.if(this.compiledNegation,()=>e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}}var hE=ae({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(e)=>typeof e==="string"?{domain:e}:ti(e,"numberAllowsNaN")&&e.domain!=="number"?A(pa.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[Ge(e)]},intersections:{domain:(e,t)=>e.domain==="number"&&t.domain==="number"?e.numberAllowsNaN?t:e:U.init("domain",e,t)}});class Ig extends xr{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?(e)=>typeof e==="number"&&!Number.isNaN(e):(e)=>Ge(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 pa={implementation:hE,Node:Ig,writeBadAllowNanMessage:(e)=>`numberAllowsNaN may only be specified with domain "number" (was ${e})`};var mE=ae({kind:"intersection",hasAssociatedError:!0,normalize:(e)=>{if(Se(e))return e;let{structure:t,...n}=e,r=!!t,s=t??{},o=se(n,(a,c)=>{if(ze(a,zm)){if(r)A(`Flattened structure key ${a} cannot be specified alongside a root 'structure' key.`);return s[a]=c,[]}return[a,c]});if(X(s,"constraint")||!dn(s))o.structure=s;return o},finalizeInnerJson:({structure:e,...t})=>xt(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:ot("divisor")},max:{child:!0,parse:ot("max")},min:{child:!0,parse:ot("min")},maxLength:{child:!0,parse:ot("maxLength")},minLength:{child:!0,parse:ot("minLength")},exactLength:{child:!0,parse:ot("exactLength")},before:{child:!0,parse:ot("before")},after:{child:!0,parse:ot("after")},pattern:{child:!0,parse:ot("pattern")},predicate:{child:!0,parse:ot("predicate")}},reduce:(e,t)=>Og({},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(`
560
555
  \u25E6 `)}`,problem:(e)=>`(${e.actual}) must be...
561
- ${e.expected}`},intersections:{intersection:(e,t,n)=>Zm(e.inner,t.inner,n),...ln("intersection",(e,t,n)=>{if(e.children.length===0)return t;let{domain:r,proto:s,...o}=e.inner,a=s??r,c=a?ke(a,t,n):t;return c instanceof L?c:e?.basis?.equals(c)?e:e.$.node("intersection",{...o,[c.kind]:c},{prereduced:!0})})}});class Qm extends Bt{basis=this.inner.domain??this.inner.proto??null;prestructurals=[];refinements=this.children.filter((e)=>{if(!e.isRefinement())return!1;if(Lt(Pl,e.kind))this.prestructurals.push(e);return!0});structure=this.inner.structure;expression=gk(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 tu={implementation:mk,Node:Qm},gk=(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"},Zm=(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 L)return a;if(a)r[a.kind]=a;return Gr({kind:"intersection",baseInner:r,l:zr(e),r:zr(t),roots:[],ctx:n})};var _k=ie({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(e,t)=>t.$.parseSchema(e)},morphs:{parse:Nn,serialize:(e)=>e.map((t)=>Z(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 E(wk(e.expression,t.expression));let r=ke(e.rawIn,t.rawIn,n);if(r instanceof L)return r;let s={morphs:e.morphs};if(e.declaredIn||t.declaredIn){let o=ke(e.rawIn,t.rawIn,n);if(o instanceof L)return o.throw();else s.declaredIn=o}if(e.declaredOut||t.declaredOut){let o=ke(e.rawOut,t.rawOut,n);if(o instanceof L)return o.throw();else s.declaredOut=o}return r.distribute((o)=>n.$.node("morph",{...s,in:o}),n.$.parseSchema)},...ln("morph",(e,t,n)=>{let r=e.inner.in?ke(e.inner.in,t,n):t;return r instanceof L?r:r.equals(e.inner.in)?e:n.$.node("morph",{...e.inner,in:r})})}});class eg extends Bt{serializedMorphs=this.morphs.map(Me);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs[this.inner.morphs.length-1];lastMorphIfNode=Z(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??M.intrinsic.unknown.internal}get rawOut(){return this.declaredOut??this.introspectableOut??M.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 bn(this.morphs,e.morphs,{isEqual:(t,n)=>t===n||Z(t,"root")&&Z(n,"root")&&t.equals(n)})}}var nu={implementation:_k,Node:eg},wk=(e,t)=>`The intersection of distinct morphs at a single path is indeterminate:
556
+ ${e.expected}`},intersections:{intersection:(e,t,n)=>Og(e.inner,t.inner,n),...fn("intersection",(e,t,n)=>{if(e.children.length===0)return t;let{domain:r,proto:s,...o}=e.inner,a=s??r,c=a?Re(a,t,n):t;return c instanceof U?c:e?.basis?.equals(c)?e:e.$.node("intersection",{...o,[c.kind]:c},{prereduced:!0})})}});class Pg extends Ht{basis=this.inner.domain??this.inner.proto??null;prestructurals=[];refinements=this.children.filter((e)=>{if(!e.isRefinement())return!1;if(Ut(ru,e.kind))this.prestructurals.push(e);return!0});structure=this.inner.structure;expression=gE(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 ku={implementation:mE,Node:Pg},gE=(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"},Og=(e,t,n)=>{let r={},s=e.proto??e.domain,o=t.proto??t.domain,a=s?o?Re(s,o,n):s:o;if(a instanceof U)return a;if(a)r[a.kind]=a;return ci({kind:"intersection",baseInner:r,l:li(e),r:li(t),roots:[],ctx:n})};var _E=ae({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(e,t)=>t.$.parseSchema(e)},morphs:{parse:Kn,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(wE(e.expression,t.expression));let r=Re(e.rawIn,t.rawIn,n);if(r instanceof U)return r;let s={morphs:e.morphs};if(e.declaredIn||t.declaredIn){let o=Re(e.rawIn,t.rawIn,n);if(o instanceof U)return o.throw();else s.declaredIn=o}if(e.declaredOut||t.declaredOut){let o=Re(e.rawOut,t.rawOut,n);if(o instanceof U)return o.throw();else s.declaredOut=o}return r.distribute((o)=>n.$.node("morph",{...s,in:o}),n.$.parseSchema)},...fn("morph",(e,t,n)=>{let r=e.inner.in?Re(e.inner.in,t,n):t;return r instanceof U?r:r.equals(e.inner.in)?e:n.$.node("morph",{...e.inner,in:r})})}});class Mg extends Ht{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??F.intrinsic.unknown.internal}get rawOut(){return this.declaredOut??this.introspectableOut??F.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 Rn(this.morphs,e.morphs,{isEqual:(t,n)=>t===n||X(t,"root")&&X(n,"root")&&t.equals(n)})}}var Eu={implementation:_E,Node:Mg},wE=(e,t)=>`The intersection of distinct morphs at a single path is indeterminate:
562
557
  Left: ${e}
563
- Right: ${t}`;var yk=ie({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(e)=>Hi(e)??jt(e)},dateAllowsInvalid:{}},normalize:(e)=>{let t=typeof e==="string"?{proto:ir[e]}:typeof e==="function"?Re(e)?e:{proto:e}:typeof e.proto==="string"?{...e,proto:ir[e.proto]}:e;if(typeof t.proto!=="function")E(cs.writeInvalidSchemaMessage(t.proto));if(Ur(t,"dateAllowsInvalid")&&t.proto!==Date)E(cs.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?Kh[e.builtinName]:`an instance of ${e.proto.name}`,actual:(e)=>e instanceof Date&&e.toString()==="Invalid Date"?"an invalid Date":qi(e)},intersections:{proto:(e,t)=>e.proto===Date&&t.proto===Date?e.dateAllowsInvalid?t:e:Rl(e.proto,t.proto)?e:Rl(t.proto,e.proto)?t:L.init("proto",e,t),domain:(e,t)=>t.domain==="object"?e:L.init("domain",M.intrinsic.object.internal,t)}});class tg extends cr{builtinName=Hi(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 cs={implementation:yk,Node:tg,writeBadInvalidDateMessage:(e)=>`dateAllowsInvalid may only be specified with constructor Date (was ${e.name})`,writeInvalidSchemaMessage:(e)=>`instanceOf operand must be a function (was ${Ge(e)})`};var bk=ie({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(e,t)=>{let n=[];for(let r of e){let s=Z(r,"root")?r.branches:t.$.parseSchema(r).branches;for(let o of s)if(o.hasKind("morph")){let a=n.findIndex((c)=>c.hasKind("morph")&&c.hasEqualMorphs(o));if(a===-1)n.push(o);else{let c=n[a];n[a]=t.$.node("morph",{...c.inner,in:c.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=Ik(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,Zr),expected:(e)=>{let t=Dh(e.errors,"propString"),n=Object.entries(t).map(([r,s])=>{let o=[];for(let l of s)an(o,l.expected);let a=Zr(o),c=s.every((l)=>l.actual===s[0].actual)?s[0].actual:re(s[0].data);return`${r&&`${r} `}must be ${a}${c&&` (was ${c})`}`});return Zr(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 L.init("presence",e,t);let r;if(e.ordered){if(t.ordered)E(Pk(e.expression,t.expression));if(r=ru(t.branches,e.branches,n),r instanceof L)r.invert()}else r=ru(e.branches,t.branches,n);if(r instanceof L)return r;return n.$.parseSchema(e.ordered||t.ordered?{branches:r,ordered:!0}:{branches:r})},...ln("union",(e,t,n)=>{let r=ru(e.branches,[t],n);if(r instanceof L)return r;if(r.length===1)return r[0];return n.$.parseSchema(e.ordered?{branches:r,ordered:!0}:{branches:r})})}});class ig extends Bt{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]=M.intrinsic.boolean;continue}e.push(n)}return e}unitBranches=this.branches.filter((e)=>e.rawIn.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?Ek(this.discriminant):null;expression=this.distribute((e)=>e.nestableExpression,Ck);createBranchedOptimisticRootApply(){return(e,t)=>{let n=this.traverseOptimistic(e);if(n!==xt)return n;let r=new Zt(e,this.$.resolvedConfig);return this.traverseApply(e,r),r.finalize(t)}}get shallowMorphs(){return this.branches.reduce((e,t)=>an(e,t.shallowMorphs),[])}get defaultShortDescription(){return this.distribute((e)=>e.defaultShortDescription,Zr)}innerToJsonSchema(e){if(this.branchGroups.length===1&&this.branchGroups[0].equals(M.intrinsic.boolean))return{type:"boolean"};let t=this.branchGroups.map((n)=>n.toJsonSchemaRecurse(e));if(t.every((n)=>Object.keys(n).length===1&&Ur(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 xt};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) : "${xt}"`;else p=`${e.invoke(d)} ? data : "${xt}"`;else p=e.invoke(d);e.line(`${f}: return ${p}`)}return e}),e.traversalKind==="Allows"){e.return(s?`"${xt}"`:!1);return}let o=Zr(this.discriminant.kind==="domain"?r.map((u)=>{let d=u.slice(1,-1);return d==="function"?vt.object:vt[d]}):r),a=this.discriminant.path.map((u)=>typeof u==="symbol"?Me(u):JSON.stringify(u)),c=JSON.stringify(o),l=this.discriminant.kind==="domain"?`${Rk}[${t}]`:`${kk}(${t})`;e.line(`ctx.errorFromNodeContext({
558
+ Right: ${t}`;var yE=ae({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(e)=>rs(e)??Bt(e)},dateAllowsInvalid:{}},normalize:(e)=>{let t=typeof e==="string"?{proto:wr[e]}:typeof e==="function"?Se(e)?e:{proto:e}:typeof e.proto==="string"?{...e,proto:wr[e.proto]}:e;if(typeof t.proto!=="function")A(Ss.writeInvalidSchemaMessage(t.proto));if(ti(t,"dateAllowsInvalid")&&t.proto!==Date)A(Ss.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?Sm[e.builtinName]:`an instance of ${e.proto.name}`,actual:(e)=>e instanceof Date&&e.toString()==="Invalid Date"?"an invalid Date":ns(e)},intersections:{proto:(e,t)=>e.proto===Date&&t.proto===Date?e.dateAllowsInvalid?t:e:Xl(e.proto,t.proto)?e:Xl(t.proto,e.proto)?t:U.init("proto",e,t),domain:(e,t)=>t.domain==="object"?e:U.init("domain",F.intrinsic.object.internal,t)}});class Tg extends xr{builtinName=rs(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 Ss={implementation:yE,Node:Tg,writeBadInvalidDateMessage:(e)=>`dateAllowsInvalid may only be specified with constructor Date (was ${e.name})`,writeInvalidSchemaMessage:(e)=>`instanceOf operand must be a function (was ${Ge(e)})`};var bE=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((c)=>c.hasKind("morph")&&c.hasEqualMorphs(o));if(a===-1)n.push(o);else{let c=n[a];n[a]=t.$.node("morph",{...c.inner,in:c.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)=>xe(e)?{branches:e}:e,reduce:(e,t)=>{let n=IE(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,pi),expected:(e)=>{let t=mm(e.errors,"propString"),n=Object.entries(t).map(([r,s])=>{let o=[];for(let l of s)un(o,l.expected);let a=pi(o),c=s.every((l)=>l.actual===s[0].actual)?s[0].actual:oe(s[0].data);return`${r&&`${r} `}must be ${a}${c&&` (was ${c})`}`});return pi(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 U.init("presence",e,t);let r;if(e.ordered){if(t.ordered)A(PE(e.expression,t.expression));if(r=Au(t.branches,e.branches,n),r instanceof U)r.invert()}else r=Au(e.branches,t.branches,n);if(r instanceof U)return r;return n.$.parseSchema(e.ordered||t.ordered?{branches:r,ordered:!0}:{branches:r})},...fn("union",(e,t,n)=>{let r=Au(e.branches,[t],n);if(r instanceof U)return r;if(r.length===1)return r[0];return n.$.parseSchema(e.ordered?{branches:r,ordered:!0}:{branches:r})})}});class Dg extends Ht{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]=F.intrinsic.boolean;continue}e.push(n)}return e}unitBranches=this.branches.filter((e)=>e.rawIn.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?EE(this.discriminant):null;expression=this.distribute((e)=>e.nestableExpression,CE);createBranchedOptimisticRootApply(){return(e,t)=>{let n=this.traverseOptimistic(e);if(n!==Rt)return n;let r=new en(e,this.$.resolvedConfig);return this.traverseApply(e,r),r.finalize(t)}}get shallowMorphs(){return this.branches.reduce((e,t)=>un(e,t.shallowMorphs),[])}get defaultShortDescription(){return this.distribute((e)=>e.defaultShortDescription,pi)}innerToJsonSchema(e){if(this.branchGroups.length===1&&this.branchGroups[0].equals(F.intrinsic.boolean))return{type:"boolean"};let t=this.branchGroups.map((n)=>n.toJsonSchemaRecurse(e));if(t.every((n)=>Object.keys(n).length===1&&ti(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 Rt};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) : "${Rt}"`;else p=`${e.invoke(d)} ? data : "${Rt}"`;else p=e.invoke(d);e.line(`${f}: return ${p}`)}return e}),e.traversalKind==="Allows"){e.return(s?`"${Rt}"`:!1);return}let o=pi(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)),c=JSON.stringify(o),l=this.discriminant.kind==="domain"?`${$E}[${t}]`:`${kE}(${t})`;e.line(`ctx.errorFromNodeContext({
564
559
  code: "predicate",
565
560
  expected: ${c},
566
561
  actual: ${l},
567
562
  relativePath: [${a}],
568
563
  meta: ${this.compiledMeta}
569
- })`)}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?`"${xt}"`:!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=ne(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 c=this.branches[a],l=kt(o.rawIn,c.rawIn,o.$);if(!(l instanceof L))continue;for(let u of l){if(!u.kind||u.optional)continue;let d,f;if(u.kind==="domain"){let{l:h,r:y}=u;d=`"${typeof h==="string"?h:h.domain}"`,f=`"${typeof y==="string"?y:y.domain}"`}else if(u.kind==="unit")d=u.l.serializedValue,f=u.r.serializedValue;else continue;let p=e.find((h)=>bn(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=an(p.cases[d].branchIndices,s);else p.cases[d]??={branchIndices:[s],condition:u.l};if(p.cases[f])p.cases[f].branchIndices=an(p.cases[f].branchIndices,a);else p.cases[f]??={branchIndices:[a],condition:u.r}}}}}let t=this.ordered?$k(e,this.branches):e;if(!t.length)return null;let n=vk(t,this),r={};for(let s in n.best.cases){let o=xk(n,s);if(o===null){r[s]=!0;continue}if(o.length===this.branches.length)return null;if(this.ordered)o.sort((l,u)=>l.originalIndex-u.originalIndex);let a=o.map((l)=>l.branch),c=a.length===1?a[0]:this.$.node("union",this.ordered?{branches:a,ordered:!0}:a);Object.assign(this.referencesById,c.referencesById),r[s]=c}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 vk=(e,t)=>{let r=e.sort((a,c)=>a.path.length===c.path.length?Object.keys(c.cases).length-Object.keys(a.cases).length:a.path.length-c.path.length)[0],s={kind:r.kind,path:r.path,optionallyChainedPropString:sg(r.path)},o=t.branches.map((a,c)=>({originalIndex:c,branch:a}));return{best:r,location:s,defaultEntries:o,node:t}},xk=(e,t)=>{let n=e.best.cases[t],r=Sk(n.condition,e.location.path,e.node.$),s=[],o=[];for(let a=0;a<e.defaultEntries.length;a++){let c=e.defaultEntries[a];if(n.branchIndices.includes(c.originalIndex)){let l=ng(e.node.branches[c.originalIndex],e.location);if(l===null)s=null;else s?.push({originalIndex:c.originalIndex,branch:l})}else if(c.branch.hasKind("alias")&&r.hasKind("domain")&&r.domain==="object")s?.push(c);else{if(c.branch.rawIn.overlaps(r)){let l=ng(c.branch,e.location);s?.push({originalIndex:c.originalIndex,branch:l})}o.push(c)}}return e.defaultEntries=o,s},$k=(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 c=o+1;c<s.length;c++){let l=s[c];for(let u of a)for(let d of l)if(u>d){if(t[u].overlaps(t[d]))return!1}}}return!0}),Sk=(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:[...Th(o).map((a)=>({})),r]}:{domain:"object",required:[{key:o,value:r}]})}return r},sg=(e)=>e.reduce((t,n)=>t+Ol(n,!0),"data"),Rk=Me(Fh),kk=Me(re),iu={implementation:bk,Node:ig},Ek=(e)=>({kind:e.kind,path:e.path.map((t)=>typeof t==="string"?t:Yt(t)),cases:ne(e.cases,(t,n)=>[t,n===!0?n:n.hasKind("union")&&n.discriminantJson?n.discriminantJson:n.json])}),Ak={delimiter:" | ",finalDelimiter:" | "},Ck=(e)=>Zr(e,Ak),Zr=(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((c)=>s[c]?!1:s[c]=!0),a=o.pop();return`${o.join(n)}${o.length?r:""}${a}`},ru=(e,t,n)=>{let r=t.map(()=>[]);for(let o=0;o<e.length;o++){let a={};for(let c=0;c<t.length;c++){if(r[c]===null)continue;if(e[o].equals(t[c])){r[c]=null,a={};break}let l=ke(e[o],t[c],n);if(l instanceof L)continue;if(l.equals(e[o])){r[c].push(e[o]),a={};break}if(l.equals(t[c]))r[c]=null;else a[c]=l}for(let c in a)r[c][o]=a[c]}let s=r.flatMap((o,a)=>o?.flatMap((c)=>c.branches)??t[a]);return s.length===0?L.init("union",e,t):s},Ik=({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=kt(e[r].rawIn,e[s].rawIn,e[0].$);if(o instanceof L)continue;if(!t)Ok(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])},Ok=(e,t)=>{if(!e.includesTransform&&!t.includesTransform)return;if(!bn(e.shallowMorphs,t.shallowMorphs))E(rg(e.expression,t.expression));if(!bn(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)}))E(rg(e.expression,t.expression))},ng=(e,t)=>e.transform((n,r)=>{if(n==="domain"||n==="unit")return null;return r},{shouldTransform:(n,r)=>{let s=sg(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"}}),rg=(e,t)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
564
+ })`)}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?`"${Rt}"`:!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=se(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 c=this.branches[a],l=At(o.rawIn,c.rawIn,o.$);if(!(l instanceof U))continue;for(let u of l){if(!u.kind||u.optional)continue;let d,f;if(u.kind==="domain"){let{l:h,r:_}=u;d=`"${typeof h==="string"?h:h.domain}"`,f=`"${typeof _==="string"?_:_.domain}"`}else if(u.kind==="unit")d=u.l.serializedValue,f=u.r.serializedValue;else continue;let p=e.find((h)=>Rn(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=un(p.cases[d].branchIndices,s);else p.cases[d]??={branchIndices:[s],condition:u.l};if(p.cases[f])p.cases[f].branchIndices=un(p.cases[f].branchIndices,a);else p.cases[f]??={branchIndices:[a],condition:u.r}}}}}let t=this.ordered?SE(e,this.branches):e;if(!t.length)return null;let n=vE(t,this),r={};for(let s in n.best.cases){let o=xE(n,s);if(o===null){r[s]=!0;continue}if(o.length===this.branches.length)return null;if(this.ordered)o.sort((l,u)=>l.originalIndex-u.originalIndex);let a=o.map((l)=>l.branch),c=a.length===1?a[0]:this.$.node("union",this.ordered?{branches:a,ordered:!0}:a);Object.assign(this.referencesById,c.referencesById),r[s]=c}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 vE=(e,t)=>{let r=e.sort((a,c)=>a.path.length===c.path.length?Object.keys(c.cases).length-Object.keys(a.cases).length:a.path.length-c.path.length)[0],s={kind:r.kind,path:r.path,optionallyChainedPropString:Lg(r.path)},o=t.branches.map((a,c)=>({originalIndex:c,branch:a}));return{best:r,location:s,defaultEntries:o,node:t}},xE=(e,t)=>{let n=e.best.cases[t],r=RE(n.condition,e.location.path,e.node.$),s=[],o=[];for(let a=0;a<e.defaultEntries.length;a++){let c=e.defaultEntries[a];if(n.branchIndices.includes(c.originalIndex)){let l=Fg(e.node.branches[c.originalIndex],e.location);if(l===null)s=null;else s?.push({originalIndex:c.originalIndex,branch:l})}else if(c.branch.hasKind("alias")&&r.hasKind("domain")&&r.domain==="object")s?.push(c);else{if(c.branch.rawIn.overlaps(r)){let l=Fg(c.branch,e.location);s?.push({originalIndex:c.originalIndex,branch:l})}o.push(c)}}return e.defaultEntries=o,s},SE=(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 c=o+1;c<s.length;c++){let l=s[c];for(let u of a)for(let d of l)if(u>d){if(t[u].overlaps(t[d]))return!1}}}return!0}),RE=(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:[...pm(o).map((a)=>({})),r]}:{domain:"object",required:[{key:o,value:r}]})}return r},Lg=(e)=>e.reduce((t,n)=>t+nu(n,!0),"data"),$E=Me(gm),kE=Me(oe),Cu={implementation:bE,Node:Dg},EE=(e)=>({kind:e.kind,path:e.path.map((t)=>typeof t==="string"?t:Qt(t)),cases:se(e.cases,(t,n)=>[t,n===!0?n:n.hasKind("union")&&n.discriminantJson?n.discriminantJson:n.json])}),AE={delimiter:" | ",finalDelimiter:" | "},CE=(e)=>pi(e,AE),pi=(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((c)=>s[c]?!1:s[c]=!0),a=o.pop();return`${o.join(n)}${o.length?r:""}${a}`},Au=(e,t,n)=>{let r=t.map(()=>[]);for(let o=0;o<e.length;o++){let a={};for(let c=0;c<t.length;c++){if(r[c]===null)continue;if(e[o].equals(t[c])){r[c]=null,a={};break}let l=Re(e[o],t[c],n);if(l instanceof U)continue;if(l.equals(e[o])){r[c].push(e[o]),a={};break}if(l.equals(t[c]))r[c]=null;else a[c]=l}for(let c in a)r[c][o]=a[c]}let s=r.flatMap((o,a)=>o?.flatMap((c)=>c.branches)??t[a]);return s.length===0?U.init("union",e,t):s},IE=({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 U)continue;if(!t)OE(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])},OE=(e,t)=>{if(!e.includesTransform&&!t.includesTransform)return;if(!Rn(e.shallowMorphs,t.shallowMorphs))A(Ng(e.expression,t.expression));if(!Rn(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(Ng(e.expression,t.expression))},Fg=(e,t)=>e.transform((n,r)=>{if(n==="domain"||n==="unit")return null;return r},{shouldTransform:(n,r)=>{let s=Lg(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"}}),Ng=(e,t)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
570
565
  Left: ${e}
571
- Right: ${t}`,Pk=(e,t)=>`The intersection of two ordered unions is indeterminate:
566
+ Right: ${t}`,PE=(e,t)=>`The intersection of two ordered unions is indeterminate:
572
567
  Left: ${e}
573
- Right: ${t}`;var Mk=ie({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(e)=>e instanceof Date?e.toISOString():jt(e)}},normalize:(e)=>e,defaults:{description:(e)=>re(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)=>L.init("unit",e,t),...ln("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:M.intrinsic.object;if(e.domain!==r.domain){let s=e.domain==="undefined"||e.domain==="null"||e.domain==="boolean"?e.domain:M.intrinsic[e.domain];return L.init("domain",s,r)}}return L.init("assignability",e,t.hasKind("intersection")?t.children.find((r)=>!r.allows(e.unit)):t)})}});class ag extends cr{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=og(this.unit,this.serializedValue);compiledNegation=og(this.unit,this.serializedValue,"negated");expression=re(this.unit);domain=Ge(this.unit);get defaultShortDescription(){return this.domain==="object"?vt.object:this.description}innerToJsonSchema(e){return this.unit===null?{type:"null"}:M.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 su={implementation:Mk,Node:ag},og=(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 Tk=ie({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(e,t)=>{let n=t.$.parseSchema(e);if(!n.extends(M.intrinsic.key))return E(Dk(n.expression));let r=n.branches.filter((s)=>s.hasKind("unit"));if(r.length)return E(Nk(r.map((s)=>re(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 L?M.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 cg extends Ut{impliedBasis=M.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=fe(this.value.flatRefs.map((e)=>Qt([this.signature,...e.path],e.node)),Qt([this.signature],this.value));traverseAllows=(e,t)=>rr(e).every((n)=>{if(this.signature.traverseAllows(n[0],t))return Rt(n[0],()=>this.value.traverseAllows(n[1],t),t);return!0});traverseApply=(e,t)=>{for(let n of rr(e))if(this.signature.traverseAllows(n[0],t))Rt(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 ou={implementation:Tk,Node:cg},Nk=(e)=>`Index keys ${e.join(", ")} should be specified as named props.`,Dk=(e)=>`Indexed key definition '${e}' must be a string or symbol`;var Fk=ie({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:ns,optional:ns}});class lg extends rs{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=jn(this.errorContext)}var au={implementation:Fk,Node:lg};var Lk=ie({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 ss(r,n[1],null),[r,n[1]]})},serialize:(e)=>e.map((t)=>[t[0].collapsibleJson,jt(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 E(qk);if(e.optionals?.length||e.defaultables?.length)return E(lu)}if(e.minVariadicLength&&!e.variadic)return E("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} = ${re(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=ls({l:e.tuple,r:t.tuple,disjoint:new L,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",ug(s[0].result)):n.$.node("union",s.map((o)=>({proto:Array,sequence:ug(o.result)})))}}});class fg extends Ut{impliedBasis=M.intrinsic.Array.internal;tuple=Bk(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=yn(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return Dl(this.flatRefs,this.prevariadic.flatMap((e,t)=>fe(e.node.flatRefs.map((n)=>Qt([`${t}`,...n.path],n.node)),Qt([`${t}`],e.node)))),Dl(this.flatRefs,this.variadicOrPostfix.flatMap((e)=>fe(e.flatRefs.map((t)=>Qt([M.intrinsic.nonNegativeIntegerString.internal,...t.path],t.node)),Qt([M.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=Uk(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??me(`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++)Rt(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(M.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=M.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 jk={},Uk=(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(eu(s,o,a)),n+=`${s}: ${o.id} = ${jt(a)}, `}return n+="]",jk[n]??=t},cu={implementation:Lk,Node:fg},Bk=(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},ug=(e)=>e.reduce((t,n)=>{if(n.kind==="variadic")t.variadic=n.node;else if(n.kind==="defaultables")t.defaultables=fe(t.defaultables,[[n.node,n.default]]);else t[n.kind]=fe(t[n.kind],n.node);return t},{}),lu="A postfix required element cannot follow an optional or defaultable element",qk="A postfix element requires a variadic element",ls=(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",c=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=ls({...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=ls({...e,fixedVariants:[],l:n.map((p)=>({...p,kind:"prefix"}))});if(f.disjoint.length===0)e.fixedVariants.push(f)}let l=ke(t.node,r.node,e.ctx);if(l instanceof L)if(c==="prefix"||c==="postfix")e.disjoint.push(...l.withPrefixKey(c==="prefix"?e.result.length:`-${n.length+1}`,dg(t)&&dg(r)?"required":"optional")),e.result=[...e.result,{kind:c,node:M.intrinsic.never.internal}];else if(c==="optionals"||c==="defaultables")return e;else return ls({...e,fixedVariants:[],l:n.map((f)=>({...f,kind:"prefix"})),r:n.map((f)=>({...f,kind:"prefix"}))});else if(c==="defaultables"){if(t.kind==="defaultables"&&r.kind==="defaultables"&&t.default!==r.default)E(Ql(t.default,r.default));e.result=[...e.result,{kind:c,node:l,default:t.kind==="defaultables"?t.default:r.kind==="defaultables"?r.default:me(`Unexpected defaultable intersection from ${t.kind} and ${r.kind} elements.`)}]}else e.result=[...e.result,{kind:c,node:l}];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 ls(e)},dg=(e)=>e.kind==="prefix"||e.kind==="postfix";var gg=(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??"{}"},Hk=gg("description"),Kk=gg("expression"),pg=(e,t,n)=>{let r=e.required?"required":"optional";if(!t.signature.allows(e.key))return null;let s=kt(e.value,t.value,n);if(s instanceof L)return r==="optional"?n.node("optional",{key:e.key,value:M.intrinsic.never.internal}):s.withPrefixKey(e.key,e.kind);return null},Wk=ie({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:it("required"),reduceIo:(e,t,n)=>{t.required=fe(t.required,n.map((r)=>e==="in"?r.rawIn:r.rawOut));return}},optional:{child:!0,parse:it("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]=fe(t[r.outProp.kind],r.outProp.rawOut)}},index:{child:!0,parse:it("index")},sequence:{child:!0,parse:it("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:Hk},intersections:{structure:(e,t,n)=>{let r={...e.inner},s={...t.inner},o=new L;if(e.undeclared){let l=e.keyof();for(let u of t.requiredKeys)if(!l.allows(u))o.add("presence",M.intrinsic.never.internal,t.propsByKey[u].value,{path:[u]});if(s.optional)s.optional=s.optional.filter((u)=>l.allows(u.key));if(s.index)s.index=s.index.flatMap((u)=>{if(u.signature.extends(l))return u;let d=kt(l,u.signature,n.$);if(d instanceof L)return[];let f=Zo(d,u.value,n.$);if(f.required)s.required=yn(s.required,f.required);if(f.optional)s.optional=yn(s.optional,f.optional);return f.index??[]})}if(t.undeclared){let l=t.keyof();for(let u of e.requiredKeys)if(!l.allows(u))o.add("presence",e.propsByKey[u].value,M.intrinsic.never.internal,{path:[u]});if(r.optional)r.optional=r.optional.filter((u)=>l.allows(u.key));if(r.index)r.index=r.index.flatMap((u)=>{if(u.signature.extends(l))return u;let d=kt(l,u.signature,n.$);if(d instanceof L)return[];let f=Zo(d,u.value,n.$);if(f.required)r.required=yn(r.required,f.required);if(f.optional)r.optional=yn(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 c=Gr({kind:"structure",baseInner:a,l:zr(r),r:zr(s),roots:[],ctx:n});if(c instanceof L)o.push(...c);if(o.length)return o;return c}},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)E(mg(a.key));if(n[a.key]=!0,e.index)for(let c of e.index){let l=pg(a,c,t);if(l instanceof L)return l}}if(e.optional)for(let o=0;o<e.optional.length;o++){let a=e.optional[o];if(a.key in n)E(mg(a.key));if(n[a.key]=!0,e.index)for(let c of e.index){let l=pg(a,c,t);if(l instanceof L)return l;if(l!==null)s[o]=l,r=!0}}if(r)return t.node("structure",{...e,optional:s},{prereduced:!0})}});class _g extends Ut{impliedBasis=M.intrinsic.object.internal;impliedSiblings=this.children.flatMap((e)=>e.impliedSiblings??[]);props=yn(this.required,this.optional);propsByKey=ne(this.props,(e,t)=>[t.key,t]);propsByKeyReference=Me(this.propsByKey);expression=Kk(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(Re(n)){if(n.kind!=="required"&&n.kind!=="optional")return E(`Map result must have kind "required" or "optional" (was ${n.kind})`);return t[n.kind]=fe(t[n.kind],n),t}let s=n.kind??r?.kind??"required",o=ne(n,(a,c)=>(a in is.implementation.keys)?[a,c]:[]);return t[s]=fe(t[s],this.$.node(s,o)),t},{}))}assertHasKeys(e){let t=e.filter((n)=>!os(n,this.keyof()));if(t.length)return E(hg(this.expression,t))}get(e,...t){let n,r=!1,s=Jk(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(os(s,a.signature))n=n?.and(a.value)??a.value}if(this.sequence&&os(s,M.intrinsic.nonNegativeIntegerString))if(Z(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 c=this.sequence.prevariadic[a].node;n=n?.and(c)??c,r||=a<this.sequence.prefixLength}else if(this.sequence.variadic){let c=this.$.node("union",this.sequence.variadicOrPostfix);n=n?.and(c)??c}}if(!n){if(this.sequence?.variadic&&Z(s,"root")&&s.extends(M.intrinsic.number))return E(Xk(s.expression,this.sequence.expression));return E(hg(this.expression,[s]))}let o=n.get(...t);return r?o:o.or(M.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=fe(t.required,e.required);if(e.optional)t.optional=fe(t.optional,e.optional);if(e.index)t.index=fe(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=Bo(this.inner),r=(s)=>{let o=t.some((a)=>os(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 c of this.index)if(c.signature.traverseAllows(a,n)){if(e==="Allows"){if(!Rt(a,()=>c.value.traverseAllows(t[a],n),n))return!1}else if(Rt(a,()=>c.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&&M.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",Gk(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(["),zk(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 Ce.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=M.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(M.intrinsic.string)){e.additionalProperties=r;continue}for(let s of n.signature.branches){if(!s.extends(M.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 me(`Unexpected index branch kind ${s.kind}.`);let{pattern:a}=s.inner;if(a){let c=Object.assign(o,{pattern:a[0].rule});for(let l=1;l<a.length;l++)o=t.fallback.patternIntersection({code:"patternIntersection",base:c,pattern:a[l].rule});e.patternProperties??={},e.patternProperties[c.pattern]=r}}}if(this.undeclared&&!e.additionalProperties)e.additionalProperties=!1;return e}}var uu={},Vk=(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},Gk=(e)=>{let t=Vk(e);if(!t)return;if(uu[t])return uu[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 uu[t]=n},zk=(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:c}=t.defaultable[o];s.if(`!(${a} in data)`,(l)=>l.line(`${c}${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")})},du={implementation:Wk,Node:_g},Jk=(e)=>{if(Z(e,"root")&&e.hasKind("unit"))e=e.unit;if(typeof e==="number")e=`${e}`;return e},Xk=(e,t)=>`${e} is not allowed as an array index on ${t}. Use the 'nonNegativeIntegerString' keyword instead.`,Zo=(e,t,n)=>{let[r,s]=Mh(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 c=n.node("required",{key:a.unit,value:t});o[c.kind]=fe(o[c.kind],c)}if(s.length)o.index=n.node("index",{signature:s,value:t});return o},Yk=(e)=>Z(e,"root")?e.expression:re(e),hg=(e,t)=>`Key${t.length===1?"":"s"} ${t.map(Yk).join(", ")} ${t.length===1?"does":"do"} not exist on ${e}`,mg=(e)=>`Duplicate key ${Yt(e)}`;var Xr={...Fm,alias:as.implementation,domain:Yo.implementation,unit:su.implementation,proto:cs.implementation,union:iu.implementation,morph:nu.implementation,intersection:tu.implementation,divisor:Bl.implementation,pattern:Jl.implementation,predicate:Ul.implementation,required:au.implementation,optional:is.implementation,index:ou.implementation,sequence:cu.implementation,structure:du.implementation};M.defaultConfig=qh(Object.assign(ne(Xr,(e,t)=>[e,t.defaults]),{jitless:zh(),clone:Wh,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:Ce.defaultConfig}));M.resolvedConfig=Yi(M.defaultConfig,M.config);var Hm={...Lm,alias:as.Node,domain:Yo.Node,unit:su.Node,proto:cs.Node,union:iu.Node,morph:nu.Node,intersection:tu.Node,divisor:Bl.Node,pattern:Jl.Node,predicate:Ul.Node,required:au.Node,optional:is.Node,index:ou.Node,sequence:cu.Node,structure:du.Node};class Qr extends vl{get[ut](){return"module"}}var fu=(e,t)=>new Qr(ne(e,(n,r)=>[n,Z(r,"module")?fu(r,t):t.bindReference(r)]));var Zk=(e)=>Se(e)?e:("branches"in e)&&Se(e.branches)?e.branches:void 0,Qk=(e,t)=>E(`Node of kind ${t} is not valid as a ${e} definition`),wg=(e)=>`#${e} duplicates public alias ${e}`,pu={};M.ambient??={};var yg,vg="function $",eE=(e)=>xg(e,$g(e)),xg=(e,t)=>{let n=t.write(vg,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}},$g=(e)=>new Uo().return(e.reduce((t,n)=>{let r=new Xi({kind:"Allows"}).indent();n.compile(r);let s=r.write(`${n.id}Allows`),o=new Xi({kind:"Apply"}).indent();n.compile(o);let a=o.write(`${n.id}Apply`),c=`${t}${s},
568
+ Right: ${t}`;var ME=ae({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(e)=>e instanceof Date?e.toISOString():Bt(e)}},normalize:(e)=>e,defaults:{description:(e)=>oe(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)=>U.init("unit",e,t),...fn("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:F.intrinsic.object;if(e.domain!==r.domain){let s=e.domain==="undefined"||e.domain==="null"||e.domain==="boolean"?e.domain:F.intrinsic[e.domain];return U.init("domain",s,r)}}return U.init("assignability",e,t.hasKind("intersection")?t.children.find((r)=>!r.allows(e.unit)):t)})}});class Ug extends xr{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=jg(this.unit,this.serializedValue);compiledNegation=jg(this.unit,this.serializedValue,"negated");expression=oe(this.unit);domain=Ge(this.unit);get defaultShortDescription(){return this.domain==="object"?St.object:this.description}innerToJsonSchema(e){return this.unit===null?{type:"null"}:F.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 Iu={implementation:ME,Node:Ug},jg=(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 TE=ae({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(e,t)=>{let n=t.$.parseSchema(e);if(!n.extends(F.intrinsic.key))return A(NE(n.expression));let r=n.branches.filter((s)=>s.hasKind("unit"));if(r.length)return A(FE(r.map((s)=>oe(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=Re(e.value,t.value,n),s=r instanceof U?F.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 Bg extends qt{impliedBasis=F.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=fe(this.value.flatRefs.map((e)=>tn([this.signature,...e.path],e.node)),tn([this.signature],this.value));traverseAllows=(e,t)=>_r(e).every((n)=>{if(this.signature.traverseAllows(n[0],t))return Et(n[0],()=>this.value.traverseAllows(n[1],t),t);return!0});traverseApply=(e,t)=>{for(let n of _r(e))if(this.signature.traverseAllows(n[0],t))Et(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 Ou={implementation:TE,Node:Bg},FE=(e)=>`Index keys ${e.join(", ")} should be specified as named props.`,NE=(e)=>`Indexed key definition '${e}' must be a string or symbol`;var DE=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:_s,optional:_s}});class qg extends ws{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=zn(this.errorContext)}var Pu={implementation:DE,Node:qg};var LE=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,Bt(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(qE);if(e.optionals?.length||e.defaultables?.length)return A(Tu)}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} = ${oe(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=Rs({l:e.tuple,r:t.tuple,disjoint:new U,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",Hg(s[0].result)):n.$.node("union",s.map((o)=>({proto:Array,sequence:Hg(o.result)})))}}});class Wg extends qt{impliedBasis=F.intrinsic.Array.internal;tuple=BE(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=Sn(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return au(this.flatRefs,this.prevariadic.flatMap((e,t)=>fe(e.node.flatRefs.map((n)=>tn([`${t}`,...n.path],n.node)),tn([`${t}`],e.node)))),au(this.flatRefs,this.variadicOrPostfix.flatMap((e)=>fe(e.flatRefs.map((t)=>tn([F.intrinsic.nonNegativeIntegerString.internal,...t.path],t.node)),tn([F.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=UE(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??pe(`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++)Et(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(F.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=F.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 jE={},UE=(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($u(s,o,a)),n+=`${s}: ${o.id} = ${Bt(a)}, `}return n+="]",jE[n]??=t},Mu={implementation:LE,Node:Wg},BE=(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},Hg=(e)=>e.reduce((t,n)=>{if(n.kind==="variadic")t.variadic=n.node;else if(n.kind==="defaultables")t.defaultables=fe(t.defaultables,[[n.node,n.default]]);else t[n.kind]=fe(t[n.kind],n.node);return t},{}),Tu="A postfix required element cannot follow an optional or defaultable element",qE="A postfix element requires a variadic element",Rs=(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",c=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=Rs({...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=Rs({...e,fixedVariants:[],l:n.map((p)=>({...p,kind:"prefix"}))});if(f.disjoint.length===0)e.fixedVariants.push(f)}let l=Re(t.node,r.node,e.ctx);if(l instanceof U)if(c==="prefix"||c==="postfix")e.disjoint.push(...l.withPrefixKey(c==="prefix"?e.result.length:`-${n.length+1}`,Kg(t)&&Kg(r)?"required":"optional")),e.result=[...e.result,{kind:c,node:F.intrinsic.never.internal}];else if(c==="optionals"||c==="defaultables")return e;else return Rs({...e,fixedVariants:[],l:n.map((f)=>({...f,kind:"prefix"})),r:n.map((f)=>({...f,kind:"prefix"}))});else if(c==="defaultables"){if(t.kind==="defaultables"&&r.kind==="defaultables"&&t.default!==r.default)A(Ru(t.default,r.default));e.result=[...e.result,{kind:c,node:l,default:t.kind==="defaultables"?t.default:r.kind==="defaultables"?r.default:pe(`Unexpected defaultable intersection from ${t.kind} and ${r.kind} elements.`)}]}else e.result=[...e.result,{kind:c,node:l}];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 Rs(e)},Kg=(e)=>e.kind==="prefix"||e.kind==="postfix";var Jg=(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??"{}"},HE=Jg("description"),KE=Jg("expression"),Vg=(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 U)return r==="optional"?n.node("optional",{key:e.key,value:F.intrinsic.never.internal}):s.withPrefixKey(e.key,e.kind);return null},WE=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:ot("required"),reduceIo:(e,t,n)=>{t.required=fe(t.required,n.map((r)=>e==="in"?r.rawIn:r.rawOut));return}},optional:{child:!0,parse:ot("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]=fe(t[r.outProp.kind],r.outProp.rawOut)}},index:{child:!0,parse:ot("index")},sequence:{child:!0,parse:ot("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:HE},intersections:{structure:(e,t,n)=>{let r={...e.inner},s={...t.inner},o=new U;if(e.undeclared){let l=e.keyof();for(let u of t.requiredKeys)if(!l.allows(u))o.add("presence",F.intrinsic.never.internal,t.propsByKey[u].value,{path:[u]});if(s.optional)s.optional=s.optional.filter((u)=>l.allows(u.key));if(s.index)s.index=s.index.flatMap((u)=>{if(u.signature.extends(l))return u;let d=At(l,u.signature,n.$);if(d instanceof U)return[];let f=ha(d,u.value,n.$);if(f.required)s.required=Sn(s.required,f.required);if(f.optional)s.optional=Sn(s.optional,f.optional);return f.index??[]})}if(t.undeclared){let l=t.keyof();for(let u of e.requiredKeys)if(!l.allows(u))o.add("presence",e.propsByKey[u].value,F.intrinsic.never.internal,{path:[u]});if(r.optional)r.optional=r.optional.filter((u)=>l.allows(u.key));if(r.index)r.index=r.index.flatMap((u)=>{if(u.signature.extends(l))return u;let d=At(l,u.signature,n.$);if(d instanceof U)return[];let f=ha(d,u.value,n.$);if(f.required)r.required=Sn(r.required,f.required);if(f.optional)r.optional=Sn(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 c=ci({kind:"structure",baseInner:a,l:li(r),r:li(s),roots:[],ctx:n});if(c instanceof U)o.push(...c);if(o.length)return o;return c}},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(zg(a.key));if(n[a.key]=!0,e.index)for(let c of e.index){let l=Vg(a,c,t);if(l instanceof U)return l}}if(e.optional)for(let o=0;o<e.optional.length;o++){let a=e.optional[o];if(a.key in n)A(zg(a.key));if(n[a.key]=!0,e.index)for(let c of e.index){let l=Vg(a,c,t);if(l instanceof U)return l;if(l!==null)s[o]=l,r=!0}}if(r)return t.node("structure",{...e,optional:s},{prereduced:!0})}});class Xg extends qt{impliedBasis=F.intrinsic.object.internal;impliedSiblings=this.children.flatMap((e)=>e.impliedSiblings??[]);props=Sn(this.required,this.optional);propsByKey=se(this.props,(e,t)=>[t.key,t]);propsByKeyReference=Me(this.propsByKey);expression=KE(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(Se(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]=fe(t[n.kind],n),t}let s=n.kind??r?.kind??"required",o=se(n,(a,c)=>(a in ys.implementation.keys)?[a,c]:[]);return t[s]=fe(t[s],this.$.node(s,o)),t},{}))}assertHasKeys(e){let t=e.filter((n)=>!vs(n,this.keyof()));if(t.length)return A(Gg(this.expression,t))}get(e,...t){let n,r=!1,s=JE(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(vs(s,a.signature))n=n?.and(a.value)??a.value}if(this.sequence&&vs(s,F.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 c=this.sequence.prevariadic[a].node;n=n?.and(c)??c,r||=a<this.sequence.prefixLength}else if(this.sequence.variadic){let c=this.$.node("union",this.sequence.variadicOrPostfix);n=n?.and(c)??c}}if(!n){if(this.sequence?.variadic&&X(s,"root")&&s.extends(F.intrinsic.number))return A(XE(s.expression,this.sequence.expression));return A(Gg(this.expression,[s]))}let o=n.get(...t);return r?o:o.or(F.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=fe(t.required,e.required);if(e.optional)t.optional=fe(t.optional,e.optional);if(e.index)t.index=fe(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=ra(this.inner),r=(s)=>{let o=t.some((a)=>vs(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 c of this.index)if(c.signature.traverseAllows(a,n)){if(e==="Allows"){if(!Et(a,()=>c.value.traverseAllows(t[a],n),n))return!1}else if(Et(a,()=>c.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&&F.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",GE(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(["),zE(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 ke.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=F.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(F.intrinsic.string)){e.additionalProperties=r;continue}for(let s of n.signature.branches){if(!s.extends(F.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 pe(`Unexpected index branch kind ${s.kind}.`);let{pattern:a}=s.inner;if(a){let c=Object.assign(o,{pattern:a[0].rule});for(let l=1;l<a.length;l++)o=t.fallback.patternIntersection({code:"patternIntersection",base:c,pattern:a[l].rule});e.patternProperties??={},e.patternProperties[c.pattern]=r}}}if(this.undeclared&&!e.additionalProperties)e.additionalProperties=!1;return e}}var Fu={},VE=(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+=te.nonNegativeIntegerString.id;else for(let n=0;n<e.sequence.tuple.length;n++)t+=n+" | ";t+=")"}return t},GE=(e)=>{let t=VE(e);if(!t)return;if(Fu[t])return Fu[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 Fu[t]=n},zE=(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:c}=t.defaultable[o];s.if(`!(${a} in data)`,(l)=>l.line(`${c}${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")})},Nu={implementation:WE,Node:Xg},JE=(e)=>{if(X(e,"root")&&e.hasKind("unit"))e=e.unit;if(typeof e==="number")e=`${e}`;return e},XE=(e,t)=>`${e} is not allowed as an array index on ${t}. Use the 'nonNegativeIntegerString' keyword instead.`,ha=(e,t,n)=>{let[r,s]=fm(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 c=n.node("required",{key:a.unit,value:t});o[c.kind]=fe(o[c.kind],c)}if(s.length)o.index=n.node("index",{signature:s,value:t});return o},YE=(e)=>X(e,"root")?e.expression:oe(e),Gg=(e,t)=>`Key${t.length===1?"":"s"} ${t.map(YE).join(", ")} ${t.length===1?"does":"do"} not exist on ${e}`,zg=(e)=>`Duplicate key ${Qt(e)}`;var di={...gg,alias:xs.implementation,domain:pa.implementation,unit:Iu.implementation,proto:Ss.implementation,union:Cu.implementation,morph:Eu.implementation,intersection:ku.implementation,divisor:fu.implementation,pattern:bu.implementation,predicate:du.implementation,required:Pu.implementation,optional:ys.implementation,index:Ou.implementation,sequence:Mu.implementation,structure:Nu.implementation};F.defaultConfig=vm(Object.assign(se(di,(e,t)=>[e,t.defaults]),{jitless:Em(),clone:Rm,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:ke.defaultConfig}));F.resolvedConfig=ds(F.defaultConfig,F.config);var xg={..._g,alias:xs.Node,domain:pa.Node,unit:Iu.Node,proto:Ss.Node,union:Cu.Node,morph:Eu.Node,intersection:ku.Node,divisor:fu.Node,pattern:bu.Node,predicate:du.Node,required:Pu.Node,optional:ys.Node,index:Ou.Node,sequence:Mu.Node,structure:Nu.Node};class hi extends Vl{get[ft](){return"module"}}var Du=(e,t)=>new hi(se(e,(n,r)=>[n,X(r,"module")?Du(r,t):t.bindReference(r)]));var ZE=(e)=>xe(e)?e:("branches"in e)&&xe(e.branches)?e.branches:void 0,QE=(e,t)=>A(`Node of kind ${t} is not valid as a ${e} definition`),Yg=(e)=>`#${e} duplicates public alias ${e}`,Lu={};F.ambient??={};var Zg,e_="function $",e0=(e)=>t_(e,n_(e)),t_=(e,t)=>{let n=t.write(e_,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}},n_=(e)=>new na().return(e.reduce((t,n)=>{let r=new us({kind:"Allows"}).indent();n.compile(r);let s=r.write(`${n.id}Allows`),o=new us({kind:"Apply"}).indent();n.compile(o);let a=o.write(`${n.id}Apply`),c=`${t}${s},
574
569
  ${a},
575
- `;if(!n.hasKind("union"))return c;let l=new Xi({kind:"Allows",optimistic:!0}).indent();n.compile(l);let u=l.write(`${n.id}Optimistic`);return`${c}${u},
570
+ `;if(!n.hasKind("union"))return c;let l=new us({kind:"Allows",optimistic:!0}).indent();n.compile(l);let u=l.write(`${n.id}Optimistic`);return`${c}${u},
576
571
  `},`{
577
- `)+"}");class Qo{config;resolvedConfig;name;get[ut](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(e,t){if(this.config=Yi(M.config,t),this.resolvedConfig=Yi(M.resolvedConfig,t),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(pu).length}`,this.name in pu)E(`A Scope already named ${this.name} already exists`);pu[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)E(wg(o));this.aliases[o]=s}else{if(o in this.aliases)E(wg(r));this.aliases[o]=s,this.exportedNames.push(o)}if(!Z(s,"module")&&!Z(s,"generic")&&!Dn(s)){let a=this.preparseOwnDefinitionFormat(s,{alias:o});this.resolutions[o]=Z(a,"root")?this.bindReference(a):this.createParseContext(a).id}}yg??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[yg.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=M.intrinsic?ne(M.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 Bn(e,r?new Wo(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(ts(e),e,t);preparseNode(e,t,n){let r=typeof e==="string"?e:ts(t,e);if(Re(t)&&t.kind===r)return t;if(r==="alias"&&!n?.prereduced){let{reference:a}=as.implementation.normalize(t,this);if(a.startsWith("$")){let c=this.resolveRoot(a.slice(1));t=c,r=c.kind}}else if(r==="union"&&bt(t,"object")){let a=Zk(t);if(a?.length===1)t=a[0],r=ts(t)}if(Re(t)&&t.kind===r)return t;let o=Xr[r].normalize?.(t,this)??t;if(Re(o))return o.kind===r?o:Qk(r,o.kind);return{...n,$:this,kind:r,def:o,prefix:n.alias??r}}bindReference(e){let t;if(Re(e))t=e.$===this?e:new e.constructor(e.attachments,this);else t=e.$===this?e:new Bn(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)??E(gu(e))}maybeResolveRoot(e){let t=this.maybeResolve(e);if(Z(t,"generic"))return;return t}maybeResolveSubalias(e){return hu(this.aliases,e)??hu(this.ambient,e)}get ambient(){return M.ambient}maybeResolve(e){let t=this.resolutions[e];if(t){if(typeof t!=="string")return this.bindReference(t);let r=dt[t];if(Z(r,"root"))return this.resolutions[e]=r;if(Z(r,"context")){if(r.phase==="resolving")return this.node("alias",{reference:`$${e}`},{prereduced:!0});if(r.phase==="resolved")return me(`Unexpected resolved context for was uncached by its scope: ${re(r)}`);r.phase="resolving";let s=this.bindReference(this.parseOwnDefinitionFormat(r.def,r));return r.phase="resolved",dt[s.id]=s,dt[r.id]=s,this.resolutions[e]=s}return me(`Unexpected nodesById entry for ${t}: ${re(r)}`)}let n=this.aliases[e]??this.ambient?.[e];if(!n)return this.maybeResolveSubalias(e);if(n=this.normalizeRootScopeValue(n),Z(n,"generic"))return this.resolutions[e]=this.bindReference(n);if(Z(n,"module")){if(!n.root)E(kg(e));return this.resolutions[e]=this.bindReference(n.root)}return this.resolutions[e]=this.parse(n,{alias:e})}createParseContext(e){let t=e.id??Xl(e.prefix);return dt[t]=Object.assign(e,{[ut]:"context",$:this,id:t,phase:"unresolved"})}traversal(e){return new Zt(e,this.resolvedConfig)}import(...e){return new Qr(ne(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]=Z(r,"module")?fu(r,this):bg(this.maybeResolve(n))}for(let n of this.lazyResolutions)n.resolution;if(this._exportedResolutions=Rg(this,this._exports),this._json=Sg(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let n=$g(this.references);this.precompilation=n.write(vg,4),xg(this.references,n)}this.resolved=!0}let t=e.length?e:this.exportedNames;return new Qr(ne(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(Re(r))return this.bindReference(r);let s=this.createParseContext(r),o=Yl(s),a=this.bindReference(o);return dt[s.id]=a};parse=(e,t={})=>this.finalize(this.parseDefinition(e,t));parseDefinition(e,t={}){if(Z(e,"root"))return this.bindReference(e);let n=this.preparseOwnDefinitionFormat(e,t);if(Z(n,"root"))return this.bindReference(n);let r=this.createParseContext(n);dt[r.id]=r;let s=this.bindReference(this.parseOwnDefinitionFormat(e,r));if(s.isCyclic)s=qm(s,r.id);return dt[r.id]=s,s}finalize(e){if(bg(e),!e.precompilation&&!this.resolvedConfig.jitless)eE(e.references);return e}}class mu extends Qo{parseOwnDefinitionFormat(e,t){return Yl(t)}preparseOwnDefinitionFormat(e,t){return this.preparseNode(ts(e),e,t)}preparseOwnAliasEntry(e,t){return[e,t]}normalizeRootScopeValue(e){return e}}var bg=(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},Sg=(e)=>ne(e,(t,n)=>[t,Z(n,"root")||Z(n,"generic")?n.json:Z(n,"module")?Sg(n):me(`Unexpected resolution ${re(n)}`)]),hu=(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(!Z(s,"module"))return E(tE(r));let o=t.slice(n+1),a=s[o];if(a===void 0)return hu(s,o);if(Z(a,"root")||Z(a,"generic"))return a;if(Z(a,"module"))return a.root??E(kg(t));me(`Unexpected resolution for alias '${t}': ${re(a)}`)},ea=(e,t)=>new mu(e,t),us=new mu({});var Rg=(e,t)=>{let n={};for(let r in t){let s=t[r];if(Z(s,"module")){let o=Rg(e,s),a=ne(o,(c,l)=>[`${r}.${c}`,l]);Object.assign(n,a)}else if(Z(s,"root")||Z(s,"generic"))n[r]=s;else me(`Unexpected scope resolution ${re(s)}`)}return n},gu=(e)=>`'${e}' is unresolvable`,tE=(e)=>`'${e}' must reference a module to be accessed using dot syntax`,kg=(e)=>`Reference to submodule '${e}' must specify an alias`;us.export();var{schema:ge,node:ei,defineSchema:mU,generic:qt}=us;var _u="^(?:0|[1-9]\\d*)$",nE=new RegExp(_u),wU=Me(nE);var Eg=ea({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();M.intrinsic={...Eg};var Ag=ea({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:_u}},{prereducedAliases:!0}).export();Object.assign(M.intrinsic,Ag);var rE=ea({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),ee={...Eg,...Ag,...rE,emptyStructure:ei("structure",{},{prereduced:!0})};M.intrinsic={...ee};var ta=(e,t)=>new RegExp(e,t);Object.assign(ta,{as:ta});var Ig=(e)=>typeof e==="string"&&e[0]==="d"&&(e[1]==="'"||e[1]==='"')&&e[e.length-1]===e[1],Cg=(e)=>e.toString()!=="Invalid Date",Og=(e)=>e.slice(2,-1),wu=(e)=>`'${e}' could not be parsed by the Date constructor`,Pg=(e,t)=>iE(e,t),iE=(e,t)=>{let n=new Date(e);if(Cg(n))return n;let r=im(e);if(r!==void 0){let s=new Date(r);if(Cg(s))return s}return t?E(t===!0?wu(e):t):void 0};var sE=ge({proto:"Array",sequence:"string",required:{key:"groups",value:["object",{unit:void 0}]}}),na=(e,t)=>{let n=e.scanner.shiftUntilEscapable(aE[Ng[t]]);if(e.scanner.lookahead==="")return e.error(lE(n,t));if(e.scanner.shift(),t in Tg){let r;try{r=new RegExp(n)}catch(s){E(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:sE})}else if(ze(t,yu))e.root=e.ctx.$.node("unit",{unit:n});else{let r=Pg(n,wu(n));e.root=e.ctx.$.node("unit",{meta:n,unit:r})}},yu={"'":1,'"':1},Mg={"/":1,"'":1,'"':1},oE={"d'":"'",'d"':'"',"'":"'",'"':'"'},Tg={"/":"/","x/":"/"},Ng={...oE,...Tg},aE={"'":(e)=>e.lookahead==="'",'"':(e)=>e.lookahead==='"',"/":(e)=>e.lookahead==="/"},cE={'"':"double-quote","'":"single-quote","/":"forward slash"},lE=(e,t)=>`${t}${e} requires a closing ${cE[Ng[t]]}`;var Dg=(e)=>`Private type references should not include '#'. Use '${e}' instead.`,ra="Optional definitions like 'string?' are only valid as properties in an object or tuple",ia="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var un={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...Fn};var Fg=(e,t)=>e===">"?t[0]==="="?t[1]==="=":t.trimStart()===""||ze(t.trimStart()[0],un):e==="="?t[0]!=="=":e===","||e==="?";var Lg=(e,t,n)=>jg(e,t,n,[]),jg=(e,t,n,r)=>{let s=n.parseUntilFinalizer();if(r.push(s.root),s.finalizer===">"){if(r.length!==t.params.length)return n.error(bu(e,t.names,r.map((o)=>o.expression)));return r}if(s.finalizer===",")return jg(e,t,n,r);return s.error(jo(">"))},bu=(e,t,n)=>`${e}<${t.join(", ")}> requires exactly ${t.length} args (got ${n.length}${n.length===0?"":`: ${n.join(", ")}`})`;var sa=(e)=>{let t=e.scanner.shiftUntilLookahead(un);if(t==="keyof")e.addPrefix("keyof");else e.root=dE(e,t)},uE=(e,t,n)=>{if(n.scanner.shiftUntilNonWhitespace(),n.scanner.shift()!=="<")return n.error(bu(e,t.names,[]));let s=Lg(e,t,n);return t(...s)},dE=(e,t)=>fE(e,t)??pE(e,t)??e.error(t===""?e.scanner.lookahead==="#"?Dg(e.shiftedBy(1).scanner.shiftUntilLookahead(un)):vu(e):gu(t)),fE=(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(Z(n,"root"))return n;if(n===void 0)return;if(Z(n,"generic"))return uE(t,n,e);return E(`Unexpected resolution ${re(n)}`)},pE=(e,t)=>{let n=sm(t);if(n!==void 0)return e.ctx.$.node("unit",{unit:n});let r=am(t);if(r!==void 0)return e.ctx.$.node("unit",{unit:r})},vu=(e)=>{let t=e.previousOperator();return t?xu(t,e.scanner.unscanned):hE(e.scanner.unscanned)},xu=(e,t="")=>`Token '${e}' requires a right operand${t?` before '${t}'`:""}`,hE=(e)=>`Expected an expression${e?` before '${e}'`:""}`;var $u=(e)=>e.scanner.lookahead===""?e.error(vu(e)):e.scanner.lookahead==="("?e.shiftedBy(1).reduceGroupOpen():e.scanner.lookaheadIsIn(Mg)?na(e,e.scanner.shift()):e.scanner.lookaheadIsIn(Fn)?$u(e.shiftedBy(1)):e.scanner.lookahead==="d"?e.scanner.nextLookahead in yu?na(e,`${e.scanner.shift()}${e.scanner.shift()}`):sa(e):e.scanner.lookahead==="x"?e.scanner.nextLookahead==="/"?e.shiftedBy(2)&&na(e,"x/"):sa(e):sa(e);var Ug={">":!0,">=":!0},Bg={"<":!0,"<=":!0};var ti={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},qg=(e,t)=>`Left bounds are only valid when paired with right bounds (try ...${t}${e})`,oa=(e)=>`Left-bounded expressions must specify their limits using < or <= (was ${e})`,Hg=(e,t,n,r)=>`An expression may have at most one left bound (parsed ${e}${ti[t]}, ${n}${ti[r]})`;var Wg=(e,t)=>{let n=mE(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 _E(e,n)},Vg={"<":1,">":1,"=":1},mE=(e,t)=>e.scanner.lookaheadIs("=")?`${t}${e.scanner.shift()}`:t;var Kg=(e,t,n,r)=>{if(n.extends(M.intrinsic.number)){if(typeof t!=="number")return E(Su(e,t,r));return e==="=="?["min","max"]:e[0]===">"?["min"]:["max"]}if(n.extends(M.intrinsic.lengthBoundable)){if(typeof t!=="number")return E(Su(e,t,r));return e==="=="?["exactLength"]:e[0]===">"?["minLength"]:["maxLength"]}if(n.extends(M.intrinsic.Date))return e==="=="?["after","before"]:e[0]===">"?["after"]:["before"];return E(Cm(n.expression))},gE=(e)=>({rule:Ig(e.limit)?Og(e.limit):e.limit,exclusive:e.comparator.length===1}),_E=(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(Su(t,o,"right"));let a=s.unit,c=t.length===1,l=Kg(t,typeof a==="number"?a:o,n,"right");for(let d of l)e.constrainRoot(d,t==="=="?{rule:a}:{rule:a,exclusive:c});if(!e.branches.leftBound)return;if(!ze(t,Bg))return e.error(oa(t));let u=Kg(e.branches.leftBound.comparator,e.branches.leftBound.limit,n,"left");e.constrainRoot(u[0],gE(e.branches.leftBound)),e.branches.leftBound=null},Su=(e,t,n)=>`Comparator ${n==="left"?ti[e]:e} must be ${n==="left"?"preceded":"followed"} by a corresponding literal (was ${t})`;var Gg=(e)=>{e.scanner.shiftUntilNonWhitespace();let t=e.scanner.shiftUntilLookahead(un);e.root=e.root.brand(t)};var Jg=(e)=>{e.scanner.shiftUntilNonWhitespace();let t=e.scanner.shiftUntilLookahead(un),n=om(t,{errorOnFail:zg(t)});if(n===0)e.error(zg(0));e.root=e.root.constrain("divisor",n)},zg=(e)=>`% operator must be followed by a non-zero integer literal (was ${e})`;var Ru=(e)=>{let t=e.scanner.shift();return t===""?e.finalize(""):t==="["?e.scanner.shift()==="]"?e.setRoot(e.root.array()):e.error(wE):t==="|"?e.scanner.lookahead===">"?e.shiftedBy(1).pushRootToBranch("|>"):e.pushRootToBranch(t):t==="&"?e.pushRootToBranch(t):t===")"?e.finalizeGroup():Fg(t,e.scanner.unscanned)?e.finalize(t):ze(t,Vg)?Wg(e,t):t==="%"?Jg(e):t==="#"?Gg(e):(t in Fn)?Ru(e):e.error(aa(t))},aa=(e,t="")=>`'${e}' is not allowed here${t&&` (should be ${t})`}`,wE="Missing expected ']'";var Xg=(e)=>{let t=e.unsetRoot();e.parseOperand();let n=e.unsetRoot();if(!n.hasKind("unit"))return e.error(yE(n.expression));let r=n.unit instanceof Date?()=>new Date(n.unit):n.unit;return[t,"=",r]},yE=(e)=>`Default value '${e}' must be a literal value`;var ku=(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 ni(new Ji(e),t),s=bE(r);if(r.finalizer===">")E(aa(">"));return s},bE=(e)=>{e.parseOperand();let t=ds(e).root;if(!t)return me(`Root was unexpectedly unset after parsing string '${e.scanner.scanned}'`);if(e.finalizer==="=")t=Xg(e);else if(e.finalizer==="?")t=[t,"?"];if(e.scanner.shiftUntilNonWhitespace(),e.scanner.lookahead)E(aa(e.scanner.lookahead));return t},ds=(e)=>{while(e.finalizer===void 0)vE(e);return e},vE=(e)=>e.hasRoot()?e.parseOperator():e.parseOperand();class ni{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 E(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(jo(")"));this.finalizeBranches(),this.finalizer=e}reduceLeftBound(e,t){let n=ti[t];if(!ze(n,Ug))return this.error(oa(t));if(this.branches.leftBound)return this.error(Hg(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(dm(")",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():me(`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 ds(new ni(this.scanner,this.ctx))}parseOperator(){return Ru(this)}parseOperand(){return $u(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(qg(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 xE="An empty string is not a valid generic parameter name",ca=(e,t,n)=>{e.shiftUntilNonWhitespace();let r=e.shiftUntilLookahead(un);if(r===""){if(e.lookahead===""&&t.length)return t;return E(xE)}return e.shiftUntilNonWhitespace(),$E(e,r,t,n)},Yg="extends ",$E=(e,t,n,r)=>{if(e.shiftUntilNonWhitespace(),e.unscanned.startsWith(Yg))e.jumpForward(Yg.length);else{if(e.lookahead===",")e.shift();return n.push(t),ca(e,n,r)}let s=ds(new ni(e,r));return n.push([t,s.root]),ca(e,n,r)};class Eu extends $t{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"),c=e.intrinsic.unknown;if(r!==-1){if(r!==n.length-2)return E(SE);c=e.parse(n[r+1])}return(l)=>new Zg(l,a,c)},{attach:t})}}class Zg extends $t{raw;params;returns;expression;constructor(e,t,n){let r=`typed ${e.name}`,s={[r]:(...a)=>{let c=t.assert(a),l=e(...c);return n.assert(l)}}[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 SE=`":" must be followed by exactly one return type e.g:
578
- fn("string", ":", "number")(s => s.length)`;class Au extends $t{$;constructor(e){super((...t)=>new ps(e)(...t),{bind:e});this.$=e}in(e){return new ps(this.$,e===void 0?void 0:this.$.parse(e))}at(e,t){return new ps(this.$).at(e,t)}case(e,t){return new ps(this.$).case(e,t)}}class ps extends $t{$;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)E(kE);if(this.branches.length)E(RE);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)E("default may only be specified as the last key of a switch definition");return this.default(r)}if(typeof r!=="function")return E(`Value for case "${n}" must be a function (was ${Ge(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:Qg};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:Qg},"self");return this.$.finalize(r)}}var Qg=(e)=>e.throw(),RE="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",kE="At most one key matcher may be specified per expression";var la=(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 ua(e,t)},e_="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",t_="Only required keys may specify default values, e.g. { value: 'number = 0' }";var n_=(e,t)=>{let n,r={},s=rr(e);for(let[a,c]of s){let l=CE(a);if(l.kind==="spread"){if(!cn(r))return E(AE);let h=t.$.parseOwnDefinitionFormat(c,t);if(h.equals(ee.object))continue;if(!h.hasKind("intersection")||!h.basis?.equals(ee.object))return E(IE(h.expression));n=h.structure;continue}if(l.kind==="undeclared"){if(c!=="reject"&&c!=="delete"&&c!=="ignore")E(EE(c));r.undeclared=c;continue}let u=la(c,t),d=l;if(l.kind==="required"){if(!Se(u))Cu(r,"required",{key:l.normalized,value:u},t);else Cu(r,"optional",u[1]==="="?{key:l.normalized,value:u[0],default:u[2]}:{key:l.normalized,value:u[0]},t);continue}if(Se(u)){if(u[1]==="?")E(e_);if(u[1]==="=")E(t_)}if(l.kind==="optional"){Cu(r,"optional",{key:l.normalized,value:u},t);continue}let f=t.$.parseOwnDefinitionFormat(d.normalized,t),p=Zo(f,u,t.$);if(p.index)r.index=fe(r.index,p.index);if(p.required)r.required=fe(r.required,p.required)}let o=t.$.node("structure",r);return t.$.parseSchema({domain:"object",structure:n?.merge(o)??o})},Cu=(e,t,n,r)=>{e[t]=fe(e[t],r.$.node(t,n))},EE=(e)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${re(e)})`,AE="Spread operator may only be used as the first key in an object",CE=(e)=>typeof e==="symbol"?{kind:"required",normalized:e}:e[e.length-1]==="?"?e[e.length-2]===sr?{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]===sr&&e[1]==="["&&e[e.length-1]==="]"?{kind:"required",normalized:e.slice(1)}:e==="..."?{kind:"spread"}:e==="+"?{kind:"undeclared"}:{kind:"required",normalized:e==="\\..."?"...":e==="\\+"?"+":e},IE=(e)=>`Spread operand must resolve to an object literal type (was ${e})`;var i_=(e,t)=>UE(e)?c_[e[0]](e,t):LE(e)?a_[e[1]](e,t):null,OE=(e,t)=>t.$.parseOwnDefinitionFormat(e[1],t).keyof(),Iu=(e,t)=>{if(e[2]===void 0)return E(xu(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]==="&"?kt(n,r,t.$):es(n,r,t.$);if(s instanceof L)return s.throw();return s},PE=(e,t)=>t.$.parseOwnDefinitionFormat(e[0],t).array(),ME=(e,t)=>{if(typeof e[2]!=="function")return E(s_("=>",e[2]));return t.$.parseOwnDefinitionFormat(e[0],t).pipe(e[2])},s_=(e,t)=>`${e===":"?"Narrow":"Morph"} expression requires a function following '${e}' (was ${typeof t})`,TE=(e,t)=>{if(typeof e[2]!=="function")return E(s_(":",e[2]));return t.$.parseOwnDefinitionFormat(e[0],t).constrain("predicate",e[2])},NE=(e,t)=>t.$.parseOwnDefinitionFormat(e[0],t).configure(e[2],e[3]),o_=(e)=>e,DE=o_({"[]":PE,"?":()=>E(ra)}),FE=o_({"|":Iu,"&":Iu,":":TE,"=>":ME,"|>":Iu,"@":NE,"=":()=>E(ia)}),a_={...DE,...FE},LE=(e)=>a_[e[1]]!==void 0,jE=(e)=>e,c_=jE({keyof:OE,instanceof:(e,t)=>{if(typeof e[1]!=="function")return E(r_(qi(e[1])));let n=e.slice(1).map((r)=>typeof r==="function"?t.$.node("proto",{proto:r}):E(r_(qi(r))));return n.length===1?n[0]:t.$.node("union",{branches:n})},"===":(e,t)=>t.$.units(e.slice(1))}),UE=(e)=>c_[e[0]]!==void 0,r_=(e)=>`Expected a constructor following 'instanceof' operator (was ${e})`;var d_=(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=la(e[r],t),[a,c,l]=!Se(o)?[o]:o;if(r++,s){if(!a.extends(M.intrinsic.Array))return E(HE(a.expression));n=n.flatMap((u)=>a.distribute((d)=>qE(Bo(u),d)))}else n=n.map((u)=>{if(c==="?")return f_(u,a);if(c==="=")return BE(u,a,l);return Ou(u,a)})}return t.$.parseSchema(n.map((s)=>cn(s)?{proto:Array,exactLength:0}:{proto:Array,sequence:s}))},Ou=(e,t)=>{if(e.defaultables||e.optionals)return E(e.variadic?lu:KE);if(e.variadic)e.postfix=fe(e.postfix,t);else e.prefix=fe(e.prefix,t);return e},f_=(e,t)=>{if(e.variadic)return E(p_);return e.optionals=fe(e.optionals,t),e},BE=(e,t,n)=>{if(e.variadic)return E(p_);if(e.optionals)return E(WE);return e.defaultables=fe(e.defaultables,[[t,n]]),e},l_=(e,t)=>{if(e.postfix)E(u_);if(e.variadic){if(!e.variadic.equals(t))E(u_)}else e.variadic=t.internal;return e},qE=(e,t)=>{let n=t.select({method:"find",kind:"sequence"});if(!n)return l_(e,M.intrinsic.unknown);if(n.prefix)for(let r of n.prefix)Ou(e,r);if(n.optionals)for(let r of n.optionals)f_(e,r);if(n.variadic)l_(e,n.variadic);if(n.postfix)for(let r of n.postfix)Ou(e,r);return e},HE=(e)=>`Spread element must be an array (was ${e})`,u_="A tuple may have at most one variadic element",KE="A required element may not follow an optional element",p_="An optional element may not follow a variadic element";var WE="A defaultable element may not follow an optional element without a default";var VE={},ua=(e,t)=>{if(typeof e==="string"){if(t.args&&Object.keys(t.args).some((r)=>e.includes(r)))return ku(e,t);let n=VE[t.$.name]??={};return n[e]??=ku(e,t)}return bt(e,"object")?GE(e,t):E(Pu(Ge(e)))},GE=(e,t)=>{let n=Bi(e);switch(n){case void 0:if(Z(e,"root"))return e;if("~standard"in e)return zE(e,t);return n_(e,t);case"Array":return JE(e,t);case"RegExp":return t.$.node("intersection",{domain:"string",pattern:e},{prereduced:!0});case"Function":{let r=Dn(e)?e():e;if(Z(r,"root"))return r;return E(Pu("Function"))}default:return E(Pu(n??re(e)))}},zE=(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:Zh(o),relativePath:a.map((c)=>typeof c==="object"?c.key:c)});else r.error({message:o});else r.error({message:o})}),JE=(e,t)=>i_(e,t)??d_(e,t),Pu=(e)=>`Type definitions must be strings or objects (was ${e})`;class Mu extends $t{constructor(e){let t=Object.assign({errors:St,hkt:rt,$: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 Bn(s,n[1],e,e,null)}return e.parse(n)},{attach:t})}}var ri=M;class da extends Qo{get ambientAttachments(){if(!ri.typeAttachments)return;return this.cacheGetter("ambientAttachments",ne(ri.typeAttachments,(e,t)=>[e,this.bindReference(t)]))}preparseOwnAliasEntry(e,t){let n=e.indexOf("<");if(n===-1){if(Z(t,"module")||Z(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]!==">")E("'>' 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 km(o,t,this)}]}parseGenericParams(e,t){return ca(new Ji(e),[],this.createParseContext({...t,def:e,prefix:"generic"}))}normalizeRootScopeValue(e){if(Dn(e)&&!Z(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=ua(e,t);if(Se(r)){if(r[1]==="=")return E(ia);if(r[1]==="?")return E(ra)}return r}unit=(e)=>this.units([e]);valueOf=(e)=>this.units(Hh(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 Eu(this);match=new Au(this);declare=()=>({type:this.type});define(e){return e}type=new Mu(this);static scope=(e,t={})=>new da(e,t);static module=(e,t={})=>this.scope(e,t).export()}var Tu=Object.assign(da.scope,{define:(e)=>e}),ue=da;class h_ extends rt{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var XE=qt(["base",ee.object],["props",ee.object])((e)=>e.base.merge(e.props),h_),m_=ue.module({Key:ee.key,Merge:XE});class g_ extends rt{}var YE=qt("element")((e)=>{let t=e.element.exclude(ee.Array),n=t.array();return t.rawOr(n).pipe(Nn).distribute((r)=>r.assertHasKind("morph").declareOut(n),ge)},g_),__=ue.module({root:ee.Array,readonly:"root",index:ee.nonNegativeIntegerString,liftFrom:YE},{name:"Array"});var Nu=ge(["string",or.FileConstructor]),ZE=Nu.rawOr(Nu.array()),w_=ge({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:ZE}}),y_=ue.module({root:["instanceof",FormData],value:Nu,parsed:w_,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 or.FileConstructor)t[n]=[s,r];else s.push(r)}else t[n]=r;return t},declaredOut:w_})},{name:"FormData"});var b_=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 QE={Boolean:1,Number:1,String:1},v_=ue.module({...ne({...xl,...Sl},(e,t)=>(e in QE)?[]:[e,["instanceof",t]]),Array:__,TypedArray:b_,FormData:y_});var e0=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"}),t0=ge({domain:"number",divisor:1}),fa=ue.module({root:ee.number,integer:t0,epoch:e0,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 Ie=(e,t,n)=>{let r={domain:"string",pattern:{rule:e.source,flags:e.flags,meta:t}};if(n)r.meta={format:n};return ei("intersection",r)},x_=Ie(Ki,"a well-formed integer string"),T_=ue.module({root:x_,parse:ge({in:x_,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"}),n0=Ie(/^[\dA-Fa-f]+$/,"hex characters only"),r0=ue.module({root:Ie(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:Ie(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),$_=Ie(/^[A-Z].*$/,"capitalized"),i0=ue.module({root:ge({in:"string",morphs:(e)=>e.charAt(0).toUpperCase()+e.slice(1),declaredOut:$_}),preformatted:$_},{name:"string.capitalize"}),s0=(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)},o0=/^(?: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}))$/,a0=ge({domain:"string",pattern:{meta:"a credit card number",rule:o0.source},predicate:{meta:"a credit card number",predicate:s0}});var c0=/^([+-]?\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 l0=(e)=>!Number.isNaN(new Date(e).valueOf()),S_=ge({domain:"string",predicate:{meta:"a parsable date",predicate:l0}}).assertHasKind("intersection"),R_=T_.root.internal.narrow((e,t)=>{let n=Number.parseInt(e),r=fa.epoch(n);if(r instanceof St)return t.errors.merge(r),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),u0=ue.module({root:R_,parse:ge({in:R_,morphs:(e)=>new Date(e),declaredOut:ee.Date})},{name:"string.date.epoch"}),k_=Ie(c0,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),d0=ue.module({root:k_,parse:ge({in:k_,morphs:(e)=>new Date(e),declaredOut:ee.Date})},{name:"string.date.iso"}),f0=ue.module({root:S_,parse:ge({declaredIn:S_,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:d0,epoch:u0},{name:"string.date"}),p0=Ie(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),E_="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",qn=`(${E_}[.]){3}${E_}`,h0=new RegExp(`^${qn}$`),Ue="(?:[0-9a-fA-F]{1,4})",m0=new RegExp(`^((?:${Ue}:){7}(?:${Ue}|:)|(?:${Ue}:){6}(?:${qn}|:${Ue}|:)|(?:${Ue}:){5}(?::${qn}|(:${Ue}){1,2}|:)|(?:${Ue}:){4}(?:(:${Ue}){0,1}:${qn}|(:${Ue}){1,3}|:)|(?:${Ue}:){3}(?:(:${Ue}){0,2}:${qn}|(:${Ue}){1,4}|:)|(?:${Ue}:){2}(?:(:${Ue}){0,3}:${qn}|(:${Ue}){1,5}|:)|(?:${Ue}:){1}(?:(:${Ue}){0,4}:${qn}|(:${Ue}){1,6}|:)|(?::((?::${Ue}){0,5}:${qn}|(?::${Ue}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),g0=ue.module({root:["v4 | v6","@","an IP address"],v4:Ie(h0,"an IPv4 address","ipv4"),v6:Ie(m0,"an IPv6 address","ipv6")},{name:"string.ip"}),ii="a JSON string",N_=(e)=>{if(!(e instanceof SyntaxError))throw e;return`must be ${ii} (${e})`},_0=ge({meta:ii,domain:"string",predicate:{meta:ii,predicate:(e,t)=>{try{return JSON.parse(e),!0}catch(n){return t.reject({code:"predicate",expected:ii,problem:N_(n)})}}}}),w0=(e,t)=>{if(e.length===0)return t.error({code:"predicate",expected:ii,actual:"empty"});try{return JSON.parse(e)}catch(n){return t.error({code:"predicate",expected:ii,problem:N_(n)})}},y0=ue.module({root:_0,parse:ge({meta:"safe JSON string parser",in:"string",morphs:w0,declaredOut:ee.jsonObject})},{name:"string.json"}),A_=Ie(/^[a-z]*$/,"only lowercase letters"),b0=ue.module({root:ge({in:"string",morphs:(e)=>e.toLowerCase(),declaredOut:A_}),preformatted:A_},{name:"string.lower"}),D_=["NFC","NFD","NFKC","NFKD"],hs=ne(D_,(e,t)=>[t,ge({domain:"string",predicate:(n)=>n.normalize(t)===n,meta:`${t}-normalized unicode`})]),pa=ne(D_,(e,t)=>[t,ge({in:"string",morphs:(n)=>n.normalize(t),declaredOut:hs[t]})]),v0=ue.module({root:pa.NFC,preformatted:hs.NFC},{name:"string.normalize.NFC"}),x0=ue.module({root:pa.NFD,preformatted:hs.NFD},{name:"string.normalize.NFD"}),$0=ue.module({root:pa.NFKC,preformatted:hs.NFKC},{name:"string.normalize.NFKC"}),S0=ue.module({root:pa.NFKD,preformatted:hs.NFKD},{name:"string.normalize.NFKD"}),R0=ue.module({root:"NFC",NFC:v0,NFD:x0,NFKC:$0,NFKD:S0},{name:"string.normalize"}),C_=Ie(Fo,"a well-formed numeric string"),k0=ue.module({root:C_,parse:ge({in:C_,morphs:(e)=>Number.parseFloat(e),declaredOut:ee.number})},{name:"string.numeric"}),I_="a regex pattern",E0=ge({domain:"string",predicate:{meta:I_,predicate:(e,t)=>{try{return new RegExp(e),!0}catch(n){return t.reject({code:"predicate",expected:I_,problem:String(n)})}}},meta:{format:"regex"}}),A0=/^(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-]+)*))?$/,C0=Ie(A0,"a semantic version (see https://semver.org/)"),O_=Ie(/^\S.*\S$|^\S?$/,"trimmed"),I0=ue.module({root:ge({in:"string",morphs:(e)=>e.trim(),declaredOut:O_}),preformatted:O_},{name:"string.trim"}),P_=Ie(/^[A-Z]*$/,"only uppercase letters"),O0=ue.module({root:ge({in:"string",morphs:(e)=>e.toUpperCase(),declaredOut:P_}),preformatted:P_},{name:"string.upper"}),P0=(e)=>URL.canParse(e),M_=ge({domain:"string",predicate:{meta:"a URL string",predicate:P0},meta:{format:"uri"}}),M0=ue.module({root:M_,parse:ge({declaredIn:M_,in:"string",morphs:(e,t)=>{try{return new URL(e)}catch{return t.error("a URL string")}},declaredOut:ge(URL)})},{name:"string.url"}),T0=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:Ie(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:Ie(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:Ie(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:Ie(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:Ie(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:Ie(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:Ie(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:Ie(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),F_=ue.module({root:ee.string,alpha:Ie(/^[A-Za-z]*$/,"only letters"),alphanumeric:Ie(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:n0,base64:r0,capitalize:i0,creditCard:a0,date:f0,digits:Ie(/^\d*$/,"only digits 0-9"),email:p0,integer:T_,ip:g0,json:y0,lower:b0,normalize:R0,numeric:k0,regex:E0,semver:C0,trim:I0,upper:O0,url:M0,uuid:T0},{name:"string"});var L_=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}),j_=ue.module({root:ee.unknown,any:ee.unknown},{name:"unknown"}),N0=ue.module({root:ee.jsonObject,stringify:ei("morph",{in:ee.jsonObject,morphs:(e)=>JSON.stringify(e),declaredOut:ee.string})},{name:"object.json"}),U_=ue.module({root:ee.object,json:N0},{name:"object"});class B_ extends rt{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var D0=qt(["K",ee.key],"V")((e)=>({domain:"object",index:{signature:e.K,value:e.V}}),B_);class q_ extends rt{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var F0=qt(["T",ee.object],["K",ee.key])((e)=>e.T.pick(e.K),q_);class H_ extends rt{description='omit a set of properties from an object like `Omit(User, "age")`'}var L0=qt(["T",ee.object],["K",ee.key])((e)=>e.T.omit(e.K),H_);class K_ extends rt{description="make all named properties of an object optional like `Partial(User)`"}var j0=qt(["T",ee.object])((e)=>e.T.partial(),K_);class W_ extends rt{description="make all named properties of an object required like `Required(User)`"}var U0=qt(["T",ee.object])((e)=>e.T.required(),W_);class V_ extends rt{description='exclude branches of a union like `Exclude("boolean", "true")`'}var B0=qt("T","U")((e)=>e.T.exclude(e.U),V_);class G_ extends rt{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var q0=qt("T","U")((e)=>e.T.extract(e.U),G_),z_=ue.module({Exclude:B0,Extract:q0,Omit:L0,Partial:j0,Pick:F0,Record:D0,Required:U0});var Sn=Tu({...L_,...z_,...v_,...m_,string:F_,number:fa,object:U_,unknown:j_},{prereducedAliases:!0,name:"ark"}),Je=Sn.export();Object.assign(ri.ambient,Je);ri.typeAttachments={string:Je.string.root,number:Je.number.root,bigint:Je.bigint,boolean:Je.boolean,symbol:Je.symbol,undefined:Je.undefined,null:Je.null,object:Je.object.root,unknown:Je.unknown.root,false:Je.false,true:Je.true,never:Je.never,arrayIndex:Je.Array.index,Key:Je.Key,Record:Je.Record,Array:Je.Array.root,Date:Je.Date};var ae=Object.assign(Sn.type,ri.typeAttachments),{match:H0,fn:K0,generic:W0,schema:XH,define:V0,declare:G0}=Sn;var ha=ae("'running' | 'complete' | 'failed' | 'cancelled'"),ma=ae({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"}),X_=ae("'additions' | 'deletions'"),z0=ae("'not-in-diff' | 'far-from-diff' | 'no-line' | 'deleted-file' | 'no-hunks'"),Y_=ae({file:"string",side:X_,kind:"'line' | 'nearby' | 'file'",line:"number","endLine?":"number",cited:{line:"number","endLine?":"number"},"text?":"string","reason?":z0}),J0=ae("'added' | 'removed' | 'modified' | 'renamed' | 'copied'"),Z_=ae("'product' | 'deploy' | 'tooling'"),X0=ae({path:"string","previousPath?":"string",status:J0,additions:"number",deletions:"number",isBinary:"boolean","blob?":"string",groupId:"string",classification:"'code' | 'docs' | 'skip'","surface?":Z_}),Y0=ae("'bug' | 'wrench' | 'path' | 'flask' | 'doc' | 'gear'"),Du=ae({id:"string","parentId?":"string",title:"string","summary?":"string","icon?":Y0,files:"string[]",findingIds:"string[]",stopIds:"string[]",critical:"boolean"}),Z0=ae({id:"string",chapterId:"string",index:"number",title:"string","prose?":"string",importance:"'critical' | 'normal' | 'context'",locations:Y_.and({"label?":"string"}).array()}),Q0=ae("'blocker' | 'should-fix' | 'nice-to-have' | 'question'"),J_=ae({id:"string",file:"string",anchor:Y_,severity:Q0,category:"string",title:"string",explanation:"string",evidence:"string","impact?":"string",confidence:"'high' | 'medium' | 'low'","effort?":"'quick' | 'moderate' | 'involved'","suggestion?":"string","suggestedCode?":"string","crossFileRefs?":ae({file:"string","line?":"number"}).array(),"repeatOf?":"number","carriedFrom?":"string","surface?":Z_,"preexisting?":"boolean"}),eA=ae({unit:"string",part:"number",parts:"number",status:"'ok' | 'failed'",costUsd:"number",wallMs:"number"}),ga=ae({root:"string","slug?":"string","remote?":"boolean"}),ms=ae("'review' | 'diff'");function Q_(e){return e.meta.kind??"review"}var ew=ae({schemaVersion:"1",id:"string",status:ha,createdAt:"string",repo:ga,target:ma,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:ae({file:"string",why:"string"}).array()},files:X0.array(),groups:Du.array(),stops:Z0.array(),findings:J_.array(),overCapFindings:J_.array(),resolved:ae({id:"string","note?":"string","title?":"string","file?":"string"}).array(),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?":ms,wallMs:"number",costUsd:"number",slices:eA.array(),rejectedCount:"number",coreSource:"string","mergeMode?":"'coordinator' | 'nothing-to-merge' | 'deterministic-fallback'","budgetStopped?":"boolean","reviewScope?":"'full' | 'incremental'","reviewedFiles?":"number","scopeReason?":"string","promptVersion?":"string","instructionsHash?":"string"},untrackedSkipped:"string[]","priorRunId?":"string","round?":"number","error?":"string"}),hK=ae({reviewedFiles:"string[]",findingStatus:ae.Record("string","'open' | 'accepted' | 'dismissed'"),comments:ae({id:"string",file:"string",side:X_,line:"number","endLine?":"number",body:"string"}).array(),"submitted?":{at:"string","url?":"string"}}),mK=ae({id:"string",status:ha,createdAt:"string",target:ma,repo:ga,"kind?":ms,findingCounts:{blocker:"number","should-fix":"number","nice-to-have":"number",question:"number"},costUsd:"number","invalid?":"string"});function en(){return Ze.join(process.env.XDG_DATA_HOME||Ze.join(tA.homedir(),".local","share"),"diffloupe")}function _s(){return Ze.join(en(),"runs")}function si(){return Ze.join(en(),"artifacts")}function Lu(e){let[t="",n=""]=e.toLowerCase().split("/");return Ze.join(en(),"repos",t,`${n}.git`)}function Et(e){if(!e||e.includes("/")||e.includes("\\")||e.startsWith("."))throw Error(`invalid run id: ${e}`);return Ze.join(_s(),e)}var iw={reviewedFiles:[],findingStatus:{},comments:[]};async function sw(e){let t=Et(e);return await nA(Ze.join(t,"raw"),{recursive:!0}),await rw(Ze.join(t,"state.json"),`${JSON.stringify(iw,null,2)}
579
- `),t}async function oi(e){await rw(Ze.join(Et(e.id),"run.json"),`${JSON.stringify(e,null,2)}
580
- `)}class Hn 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 tn(e){let t=JSON.parse(await nw(Ze.join(Et(e),"run.json"),"utf8")),n=ew(t);if(n instanceof ae.errors)throw new Hn(e,n.summary,t);return n}async function wa(e){try{return JSON.parse(await nw(Ze.join(Et(e),"state.json"),"utf8"))}catch{return iw}}function rA(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 Fu(e,t,n){let r=e(t);return r instanceof ae.errors?n:r}function ow(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:Fu(ha,t.status,"failed"),createdAt:typeof t.createdAt==="string"?t.createdAt:"",target:Fu(ma,t.target,{kind:"worktree"}),repo:Fu(ga,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 Ht(){let e;try{e=await gs(_s())}catch{return[]}let t=[];for(let n of e)try{let r=await tn(n);t.push({id:r.id,status:r.status,createdAt:r.createdAt,target:r.target,repo:r.repo,findingCounts:rA(r),costUsd:r.meta?.costUsd??0,...r.meta?.kind?{kind:r.meta.kind}:{}})}catch(r){if(r instanceof Hn)t.push(ow(r))}return t.sort((n,r)=>r.createdAt.localeCompare(n.createdAt))}function _a(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 aw(e,t,n){let r=_a(e,t);return(await Ht()).find((o)=>o.status==="complete"&&o.kind!=="diff"&&o.createdAt<n&&_a(o.repo,o.target)===r)?.id}function ws(){return Ze.join(en(),"scratch")}function ya(){let e=Ze.join(ws(),"oc","shared");return[Ze.join(e,"data"),Ze.join(e,"state")]}function iA(){let e=si();return[...["logs","prompts","raw","reviews","runs"].map((t)=>Ze.join(e,t)),ws(),...ya()]}async function sA(e,t){try{if((await te("git",["-C",e,"show-ref","--verify","--quiet",t],{allowFail:!0})).code!==0)return!1;return await se("git",["-C",e,"update-ref","-d",t]),!0}catch{return!1}}async function ys(e){let t=[],n=Et(e),r;try{r=(await tn(e)).repo.root}catch(s){if(s instanceof Hn)r=ow(s).repo.root||void 0}for(let s of iA()){let o;try{o=await gs(s)}catch{continue}for(let a of o)if(a.startsWith(`${e}-`)||a.startsWith(`${e}.`)){let c=Ze.join(s,a);await tw(c,{recursive:!0,force:!0}),t.push(c)}}if(r){for(let s of[`refs/diffloupe/${e}`,`refs/diffloupe/${e}-base`])if(await sA(r,s))t.push(s)}try{await gs(n),await tw(n,{recursive:!0,force:!0}),t.push(n)}catch{}return t}function cw(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 lw(){let e=[];try{e=await gs(_s())}catch{}let t=(await Ht()).filter((o)=>o.status==="running").map((o)=>o.id),n=(o,a)=>a.some((c)=>o.startsWith(`${c}-`)||o.startsWith(`${c}.`)),r=[],s=async(o,a)=>{let c;try{c=await gs(o)}catch{return}for(let l of c)if(!a(l))r.push(Ze.join(o,l))};await s(ws(),(o)=>!o.endsWith(".json")||n(o,e));for(let o of ya())await s(o,(a)=>n(a,t));return r}import{readFile as yA}from"fs/promises";gt();import{copyFile as oA,mkdir as aA,rm as cA,stat as pw}from"fs/promises";import lA from"os";import ai from"path";import{randomBytes as uA}from"crypto";function ju(e,t){if(!t)return e;let n=e;for(let r=2;t(n);r++)n=`${e}-${r}`;return n}var dA=1048576;class be extends Error{name="TargetError"}function bs(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 c=t.match(/^(?:https?:\/\/)?(?:www\.)?github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)(?:[/?#].*)?$/);if(!c?.[1]||!c[2]||!c[3])throw new be(`not a GitHub pull request URL: ${t}`);return{kind:"pr",pr:Number(c[3]),repo:`${c[1]}/${c[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 c=uw(a);if(c)return c}if(!o&&!t.startsWith("-")&&!/\s/.test(t))if(t.includes("..")){let c=uw(t);if(c)return c}else return{kind:"commit",rev:t};throw new be(`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 uw(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 Uu(e,t,n,r=new Date){let s=(l)=>String(l).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 hw(e,t,n={}){let r=bs(t),s=(I,_={})=>se("git",["-C",e,...I],_),o=async(I)=>{let _=await te("git",["-C",e,"rev-parse","--verify","--quiet",`${I}^{commit}`],{allowFail:!0});if(_.code!==0){let S=/^\d+$/.test(I)?` (for pull request ${I}, use #${I})`:"";throw new be(`unknown revision "${I}": not a commit in ${e}${S}`)}return _.stdout.trim()},a=async(I,_)=>(await s(["merge-base",I,_])).trim();if((await te("git",["-C",e,"rev-parse","--show-toplevel"],{allowFail:!0})).code!==0)throw new be(`${e} is not inside a git repository`+(r.kind==="pr"&&r.repo?". diffloupe diff can show this pull request without a clone.":""));let l=await Ro(e),u,d,f,p=[],h=!1,y;if(r.kind==="commit"&&mA(t)&&await gA(e,r.rev)){if(y=await fw(e).catch(()=>{return}),y){let I=await o(r.rev);if(await a(y,I)!==I)r={kind:"branch",branch:r.rev}}}switch(r.kind){case"pr":{if(r.repo&&!l.startsWith("local/")&&r.repo.toLowerCase()!==l.toLowerCase())throw new be(`pull request is in ${r.repo} but ${e} is a clone of ${l}. Run from a clone of ${r.repo} or pass -C. diffloupe diff can show it without a clone.`);f=await yw(e,r.pr,r.repo??(l.startsWith("local/")?void 0:l)),d=f.headRefOid,await dw(e,d,[`refs/pull/${r.pr}/head`]),await dw(e,f.baseRefOid,[f.baseRefName]),u=await a(f.baseRefOid,d);break}case"branch":{d=await o(r.branch),u=await a(y??await fw(e),d);break}case"range":{let I=await o(r.from);d=await o(r.to),u=r.mergeBase?await a(I,d):I;break}case"commit":{d=await o(r.rev);let I=await te("git",["-C",e,"rev-parse","--verify","--quiet",`${d}^`],{allowFail:!0});if(I.code!==0)throw new be(`${r.rev} is a root commit; use range: instead`);u=I.stdout.trim();break}case"staged":case"worktree":{let I=await o("HEAD"),_=r.kind==="staged"?await _A(e,I):await wA(e,I);d=_.commit,p=_.skipped,u=n.base?await a(await o(n.base),I):I,h=!0;break}}let v=l.split("/").pop()??ai.basename(e),b=ju(Uu(v,r,d,n.now),n.isTaken);if(h)await s(["update-ref",`refs/diffloupe/${b}`,d]);let g=await Bu(e,u,d),R=h?void 0:Number((await s(["rev-list","--count",`${u}..${d}`])).trim()),N={base:u,head:d,slug:l,...r.kind==="pr"?{pr:String(r.pr)}:{}};return{spec:r,target:N,tag:b,changes:g,...R!==void 0?{commits:R}:{},skippedUntracked:p,...f?{pullRequest:f}:{}}}async function mw(e,t,n,r,s={}){let o=await Promise.all([n,r].map((f)=>ba(e,f))),a=[n,r].filter((f,p)=>!o[p]);if(a.length)throw new be(`commit ${a[0]} is no longer in ${e}`);let c=await Ro(e),l=c.split("/").pop()??ai.basename(e),u=ju(Uu(l,t,r,s.now),s.isTaken);if(t.kind==="staged"||t.kind==="worktree")await se("git",["-C",e,"update-ref",`refs/diffloupe/${u}`,r]);let d={base:n,head:r,slug:c,...t.kind==="pr"?{pr:String(t.pr)}:{}};return{spec:t,target:d,tag:u,changes:await Bu(e,n,r),skippedUntracked:[]}}var fA=/^(?!\.{1,2}$)[\w.-]+$/;function pA(e){let t=e.split("/");return t.length===2&&t.every((n)=>fA.test(n))}async function gw(e,t){if(t.kind!=="pr"||!t.repo)return!1;if((await te("git",["-C",e,"rev-parse","--show-toplevel"],{allowFail:!0})).code!==0)return!0;let r=await Ro(e);return!r.startsWith("local/")&&r.toLowerCase()!==t.repo.toLowerCase()}async function _w(e,t,n=`https://github.com/${t}.git`){if(!pA(t))throw new be(`not a GitHub repository: ${t}`);let r=(...o)=>se("git",["-C",e,...o]);if(await pw(ai.join(e,"HEAD")).catch(()=>null))return;await aA(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 ww(e,t,n={}){let r=await yw(e,t.pr,t.repo),s=r.headRefOid,o=await te("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 hA(e,[a,s],[`refs/pull/${t.pr}/head`]);let c=t.repo.split("/").pop()??t.repo,l=ju(Uu(c,t,s,n.now),n.isTaken);return await se("git",["-C",e,"update-ref",`refs/diffloupe/${l}`,s]),await se("git",["-C",e,"update-ref",`refs/diffloupe/${l}-base`,a]),{spec:t,target:{base:a,head:s,slug:t.repo,pr:String(t.pr)},tag:l,changes:await Bu(e,a,s),skippedUntracked:[],pullRequest:r}}async function hA(e,t,n){let r=async()=>{let c=await Promise.all(t.map((l)=>ba(e,l)));return t.filter((l,u)=>!c[u])},s=(c)=>te("git",["-C",e,"fetch","-q","--depth=1","--filter=blob:none","--no-tags","origin",...c],{allowFail:!0}),o=await r();if(o.length===0)return;let a=await s(o);o=await r();for(let c of n){if(o.length===0)return;await s([c]),o=await r()}if(o.length)throw new be(`could not fetch ${o.map((c)=>c.slice(0,12)).join(", ")} from GitHub: ${a.stderr.trim()||"not found"}`)}async function yw(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 te("gh",s,{cwd:e,allowFail:!0});if(o.code!==0)throw new be(`gh pr view ${t} failed: ${o.stderr.trim()||`exit ${o.code}`}`);return JSON.parse(o.stdout)}async function ba(e,t){return(await te("git",["-C",e,"cat-file","-e",`${t}^{commit}`],{allowFail:!0,env:{...process.env,GIT_NO_LAZY_FETCH:"1"}})).code===0}async function dw(e,t,n){if(await ba(e,t))return;for(let r of n)if(await te("git",["-C",e,"fetch","-q","origin",r],{allowFail:!0}),await ba(e,t))return;throw new be(`commit ${t} is not in this clone and could not be fetched from origin`)}function mA(e){return!(e??"").trim().startsWith("commit:")}async function gA(e,t){return(await Promise.all([`refs/heads/${t}`,`refs/remotes/${t}`].map((r)=>te("git",["-C",e,"show-ref","--verify","--quiet",r],{allowFail:!0})))).some((r)=>r.code===0)}async function fw(e){let t=await te("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 te("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 te("git",["-C",e,"rev-parse","--verify","--quiet",`${o}^{commit}`],{allowFail:!0})).code===0)return o;throw new be("could not determine the default branch; use range:<base>..<branch> instead")}async function bw(e,t,n,r,s){let o=(await se("git",["-C",e,"rev-parse",`${n}^{tree}`])).trim();if(t===o)throw new be("no changes to review");return(await se("git",["-C",e,"commit-tree",t,"-p",n,"-m",r],s?{env:s}:{})).trim()}async function _A(e,t){let n=(await se("git",["-C",e,"write-tree"])).trim();return{commit:await bw(e,n,t,"diffloupe: staged changes"),skipped:[]}}async function wA(e,t){let n=(await se("git",["-C",e,"rev-parse","--show-toplevel"])).trim(),r=ai.resolve(n,(await se("git",["-C",n,"rev-parse","--git-path","index"])).trim()),s=ai.join(lA.tmpdir(),`diffloupe-index-${process.pid}-${uA(4).toString("hex")}`);try{await oA(r,s).catch(async()=>{await se("git",["-C",n,"read-tree",t],{env:{...process.env,GIT_INDEX_FILE:s}})});let o={...process.env,GIT_INDEX_FILE:s},a=(await se("git",["-C",n,"ls-files","--others","--exclude-standard","-z"])).split("\x00").filter(Boolean),c=[];for(let d of a){let f=await pw(ai.join(n,d)).catch(()=>null);if(f&&f.isFile()&&f.size>dA)c.push(d)}let l=c.map((d)=>`:(exclude,literal)${d}`);await se("git",["-C",n,"add","-A","--",".",...l],{env:o});let u=(await se("git",["-C",n,"write-tree"],{env:o})).trim();return{commit:await bw(n,u,t,"diffloupe: working tree",o),skipped:c}}finally{await cA(s,{force:!0})}}async function Bu(e,t,n){let r=await se("git",["-C",e,"diff","--numstat","--no-renames",t,n]),s={files:0,insertions:0,deletions:0};for(let o of r.split(`
581
- `)){if(!o.trim())continue;let[a,c]=o.split("\t");s.files++,s.insertions+=Number(a)||0,s.deletions+=Number(c)||0}return s}var bA=ae({"+":"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[]"});function vA(e,t){let n=bA(e);if(n instanceof ae.errors)throw new be(`invalid settings in ${t}: ${n.summary}`);for(let r of[...n.surfaces?.deploy??[],...n.surfaces?.tooling??[]])try{new RegExp(r)}catch(s){throw new be(`invalid surface pattern in ${t}: ${s instanceof Error?s.message:String(s)}`)}return n}async function va(e){let t;try{t=await yA(e,"utf8")}catch(r){throw new be(`cannot read settings file ${e}: ${r instanceof Error?r.message:String(r)}`)}let n;try{n=JSON.parse(t)}catch(r){throw new be(`settings file ${e} is not valid JSON: ${r instanceof Error?r.message:String(r)}`)}return vA(n,e)}function vw(e){let t={};if(e.surfaces)t.surfaces={deploy:e.surfaces.deploy??Zn.deploy,tooling:e.surfaces.tooling??Zn.tooling};if(e.extraExcludes)t.extraExcludes=e.extraExcludes;return t}function xw(e){let{instructions:t}=e;return(Array.isArray(t)?t.join(`
582
- `):t??"").trim()||void 0}var $w={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:["FIREWORKS_API_KEY"],opencode:["OPENCODE_API_KEY"]},Sw=new Set(["amazon-bedrock","google-vertex","google-vertex-anthropic","ollama","lmstudio","vllm"]);function vs(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Rw(e,t){let n=t?.[e],r=vs(n)&&Array.isArray(n.env)?n.env.filter((s)=>typeof s==="string"):[];return[...new Set([...r,...$w[e]??[]])]}function xA(e,t){let n=t?.[e];if(!vs(n))return!1;for(let r of[n.settings,n.options])if(vs(r)&&typeof r.apiKey==="string"&&r.apiKey)return!0;return!1}function kw(e){for(let t of e.providers.keys()){if(Sw.has(t))continue;if(Rw(t,e.userProviders).some((n)=>e.env[n]))continue;if(e.apiKeys?.[t])continue;return!0}return!1}function $A(e,t,n){let r=t.map((o)=>eo[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 Ew(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=Rw(n,e.userProviders),a=o.find((f)=>e.env[f]);if(a){s("env",a);continue}let c=e.apiKeys?.[n];if(c){let f=o[0];if(f)t.childEnv[f]=c;else t.imports.push({id:`cred_diffloupe_${n.replace(/[^\w-]/g,"_")}`,integrationID:n,label:"API key",active:!0,value:{type:"key",key:c}});s("config",`apiKeys.${n}`);continue}let l=(e.saved??[]).filter((f)=>f.integrationID===n),u=l.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=l.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(xA(n,e.userProviders)){s("providers",`providers.${n} in the OpenCode config`);continue}if(Sw.has(n)){s("ambient","credentials from the machine");continue}if(s("none",""),$w[n]||d)t.errors.push($A(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 Aw(e=process.env){try{let t=await te("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)=>vs(r)&&typeof r.id==="string"&&typeof r.integrationID==="string"&&vs(r.value))}catch{return}}function Cw(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}async function Iw(e=1e4){try{let t=await te("opencode",["api","GET","/api/model"],{allowFail:!0,timeoutMs:e});if(t.code!==0)return;let n=JSON.parse(t.stdout),r=Cw(n)&&Array.isArray(n.data)?n.data:void 0;if(!r)return;return r.filter((s)=>Cw(s)&&typeof s.id==="string"&&typeof s.providerID==="string")}catch{return}}function Ow(e,t,n=nn){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 c=a.find((f)=>f.id===o.id||f.modelID===o.id),l=(f)=>r.errors.push(`Model \`${o.model}\` is not available in OpenCode: ${f}. Set \`${eo[s]}\` in ~/.config/diffloupe/config.json or pass --model ${s}=<provider/model>.`);if(!c){l(`provider \`${o.provider}\` has no model \`${o.id}\``);continue}let u=c.variants?.map((f)=>f.id)??[];if(o.variant&&!u.includes(o.variant)){l(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=c.cost??[];if(d.length&&d.every((f)=>!f.input&&!f.output))r.zeroCost.push(s)}return r}import{readFileSync as SA}from"fs";import Mw from"os";import qu from"path";function RA(e=process.env,t=Mw.homedir()){let n=e.XDG_CONFIG_HOME?e.XDG_CONFIG_HOME:qu.join(t,".config"),r=qu.join(n,"opencode");return["opencode.jsonc","opencode.json"].map((s)=>qu.join(r,s))}function kA(e){let t=Bun.JSONC;if(t)try{return t.parse(e)}catch{return}return Lc(e)}function Pw(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function EA(e,t){if(!Pw(e))return{};let n=t?{path:t}:{};if(typeof e.model==="string"&&e.model.trim())n.model=e.model.trim();if(Pw(e.providers))n.providers=e.providers;return n}function Tw(e=process.env,t=Mw.homedir()){for(let n of RA(e,t)){let r;try{r=SA(n,"utf8")}catch{continue}return EA(kA(r),n)}return{}}async function xa(e){let t=e.env??process.env,n=e.openCodeUser??Tw(t),r=e.settings??{},s={env:t,...e.cli?{cli:e.cli}:{},settings:r,config:e.userConfig,...n.model?{openCodeModel:n.model}:{}},o=_f(s),a={providers:wf(o,e.stages),env:t,...e.userConfig.apiKeys?{apiKeys:e.userConfig.apiKeys}:{},...n.providers?{userProviders:n.providers}:{}},c=kw(a)?await(e.exportCredentials??(()=>Aw(t)))():void 0,l=Ew({...a,...c?{saved:c}:{}}),u=await(e.readCatalog??(()=>Iw()))();return{provider:vc(s),models:o,openCodeUser:n,credentials:l,...u?{catalog:Ow(o,u,e.stages)}:{}}}function Nw(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 Dw(e,t=nn){let n={};for(let r of t)n[r]={model:e.models[r].model,source:e.models[r].source};return n}var Ra={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`)"},fy={review:"model",coordinator:"modelMerge",walkthrough:"modelWalk",intent:"modelIntent"};function aC(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 fy))throw new be(`--model expects stage=model-id with stage one of ${Object.keys(fy).join(", ")}; got "${n}"`);t[s]=o}return t}async function ks(e){let t=e.intent?.trim();if(!t&&e.intentFile)t=(await hy(e.intentFile,"utf8")).trim();let n=aC(e.model??[]);return{...e.kind==="diff"?{kind:"diff"}:{},...e.kind==="diff"&&e.walkthrough?{walkthrough:!0}:{},repo:ft.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.config?{settingsFile:ft.resolve(e.config)}:{},...e.full?{full:!0}:{}}}function cC(e,t={}){let n=bs(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 be(["Missing required tools on PATH:",...o.map((a)=>` ${a}: ${Ra[a]??""}`)].join(`
583
- `))}function td(e){return e!==null&&/^2\./.test(e)}function lC(e){return/\d+\.\d+(?:\.\d+)?/.exec(e)?.[0]??null}async function uC(){let e=Bun.which("opencode",{PATH:process.env.PATH??""});if(!e)return;let t=await te(e,["--version"],{allowFail:!0}).catch(()=>null),n=t&&t.code===0?lC(t.stdout):null;if(td(n))return;throw new be(`DiffLoupe needs OpenCode 2.x, but the opencode on PATH (${e}) is ${n??"an unknown version"}.
584
- Install: ${Ra.opencode}`)}async function my(e,t,n,r={}){let s=e.kind??"review",o=s==="diff",a=o&&e.walkthrough===!0,c=e.fromRun,l=c?await tn(c).catch((W)=>{throw new be(`cannot start from run ${c}: ${W instanceof Error?W.message:String(W)}`)}):void 0,u=l?mC(l.target):void 0;if(l?.repo.remote&&!o)throw new be(`reviewing ${l.repo.slug??"this repository"} needs a local clone; run diffloupe review from a clone of it`);if(cC(u?u.kind==="pr"?`#${u.pr}`:"":e.target,{kind:s,walkthrough:a}),!o||a)await uC();let d=ft.resolve(e.repo??t),f=l?void 0:bs(e.target),p=o&&f?.kind==="pr"&&f.repo&&await gw(d,f)?{...f,repo:f.repo}:void 0;if(p)await _w(Lu(p.repo),p.repo);let h=l?l.repo.root:p?Lu(p.repo):d,y=p!==void 0||l?.repo.remote===!0,v=e.intent?.trim()||l?.intent.stated||void 0,b=await _r(),g=e.settingsFile?await va(ft.resolve(e.settingsFile)):{},R=o?a?["walkthrough"]:[]:nn,N=R.length?await(r.resolveSetup??xa)({cli:{...e.models?{models:e.models}:{},...e.effort?{effort:e.effort}:{}},settings:g,userConfig:b,stages:R}):void 0,I=N?[...N.credentials.errors,...N.catalog?.errors??[]]:[];if(I.length)throw new be(I.join(`
585
- `));let _={artifacts:si(),out:ft.join(en(),"scratch"),...vw(g),...N?Nw(N):{}},S=o?void 0:e.maxCostUsd??b.maxCostUsd,O=o?void 0:xw(g),P=l&&u?await mw(h,u,l.base,l.head,{isTaken:ed}):p?await ww(h,p,{isTaken:ed}):await hw(h,e.target,{...e.base?{base:e.base}:{},isTaken:ed}),{target:C,changes:j,tag:H}=P,U=P.pullRequest,q=o?"Diff of":"Reviewing";n(U?`${q} ${C.slug}#${U.number}: ${U.title}`:`${q} ${C.slug} (${gC(P.spec)})`);let Ee=P.commits===void 0?"":` (${P.commits} commit${P.commits===1?"":"s"})`;if(n(` ${C.base.slice(0,12)}..${C.head.slice(0,12)}${Ee}`),n(` ${j.files} file(s) changed, +${j.insertions} -${j.deletions}`),n(` run ${H}`),N){for(let W of R){let le=N.models[W];n(` ${W}: ${le.model} (${to(le.source)})`)}for(let W of N.credentials.warnings)n(` warning: ${W}`)}if(S!==void 0)n(N?.catalog?.zeroCost.includes("review")?" cost limit not enforced: models report no cost":` cost limit $${S.toFixed(2)}`);if(P.skippedUntracked.length){n(` skipped ${P.skippedUntracked.length} untracked file(s) over 1 MB:`);for(let W of P.skippedUntracked)n(` ${W}`)}let we=new Date().toISOString(),ce={root:h,...C.slug?{slug:C.slug}:{},...y?{remote:y}:{}},Te=l?l.target:await _C(h,P),qe=l?l.untrackedSkipped:P.skippedUntracked,he=await sw(H),K=await se("git",["-C",h,"diff","--no-color","--no-ext-diff","--full-index","-M",C.base,C.head]);await Sa(ft.join(he,"diff.patch"),K);let ye=o?void 0:await aw(ce,Te,we),ve=ye?await pC(h,ye,C.head):void 0;if(ve?.run.findings.length)n(` ${ve.run.findings.length} finding(s) from prior run ${ve.run.id}`);let st=e.full===!0,Ae=o?void 0:ve?await fC(ve.run)+1:1;if(Ae!==void 0&&Ae>1){if(n(st?` round ${Ae}, full review (--full)`:` round ${Ae}: reviewing what changed since ${ve?.run.head.slice(0,12)??"the last review"} (--full to review everything)`),Ae>dC)n(` warning: this change has been reviewed ${Ae-1} times; later rounds mostly find smaller problems`)}let Le=await hC(),Qe=N?Dw(N,R):void 0;await Promise.resolve().then(() => Zu());let D=dy({id:H,createdAt:we,repo:ce,target:Te,base:C.base,head:C.head,...v?{statedIntent:v}:{},patch:K,untrackedSkipped:qe,coreSource:Le,...ye?{priorRunId:ye}:{},...Ae!==void 0?{round:Ae}:{},...Qe?{models:Qe}:{},...o?{kind:s}:{}});return await oi(D),{id:H,kind:s,walkthrough:a,dir:he,createdAt:we,repo:h,target:C,reviewTarget:Te,config:_,...S!==void 0?{maxCostUsd:S}:{},...v?{intent:v}:{},...O?{instructions:O}:{},patch:K,...ye?{priorRunId:ye}:{},...ve?{previous:ve}:{},...Ae!==void 0?{round:Ae}:{},full:st,untrackedSkipped:qe,coreSource:Le,...Qe?{models:Qe}:{},pending:D}}async function gy(e,t){let{id:n,dir:r}=e;await Promise.resolve().then(() => Zu());let a=e.pending,c=Promise.resolve(),l=(f)=>{if(f.type!=="units"){t.onProgress(f);return}a=uy(py(e),f.units,f.byClass),t.onProgress(Ph(a));let p=a;c=c.then(()=>oi(p).catch((h)=>{t.log(` could not save the grouped run: ${h instanceof Error?h.message:String(h)}`)}))},u;try{u=e.kind==="diff"?await Sh({repo:e.repo,target:e.target,tag:n,config:e.config,walkthrough:e.walkthrough,signal:t.signal,...e.intent?{intent:e.intent}:{},onProgress:l}):await xh({repo:e.repo,target:e.target,tag:n,config:e.config,local:!0,signal:t.signal,...e.maxCostUsd!==void 0?{maxCostUsd:e.maxCostUsd}:{},...e.intent?{intent:e.intent}:{},...e.instructions?{instructions:e.instructions}:{},...e.previous?{prior:Ah(e.previous.run)}:{},...e.previous&&!e.full?{priorHead:e.previous.run.head}:{},onProgress:l})}catch(f){let p=t.signal.aborted;throw await c,await oi({...a,status:p?"cancelled":"failed",...p?{}:{error:f instanceof Error?f.message:String(f)}}),f}if(u.markdownPath){let f=e.config.artifacts??si();await Qu(ft.join(f,"runs",`${n}.json`),ft.join(r,"raw","record.json")),await Qu(u.markdownPath,ft.join(r,"raw","review.md")),await Qu(ft.join(f,"reviews",`${n}.payloads.json`),ft.join(r,"raw","payloads.json"))}else if(u.record)await Sa(ft.join(r,"raw","record.json"),`${JSON.stringify(u.record,null,2)}
586
- `);await Sa(ft.join(r,"raw","units.json"),`${JSON.stringify(u.units,null,2)}
587
- `),await Sa(ft.join(r,"raw","byClass.json"),`${JSON.stringify(u.byClass,null,2)}
588
- `);let d;await c;try{d=Yu({...py(e),result:u,...e.previous?{previous:e.previous}:{},log:t.log})}catch(f){let p=`building run.json: ${f instanceof Error?f.message:String(f)}`;throw await oi({...a,status:"failed",error:p}),Error(p,{cause:f})}if(await oi(d),e.kind==="review")t.log(` anchors: ${Mo(d)}`);return{run:d,reviewed:e.kind==="diff"||u.record!==null}}function py(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}:{}}}var dC=3;async function fC(e,t=tn){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 pC(e,t,n){try{let r=await tn(t),s=await wa(t),o=Object.entries(s.findingStatus).filter(([,l])=>l==="dismissed").map(([l])=>l),a=new Map,c=[...new Set(r.findings.map((l)=>l.file))];if(r.head!==n&&c.length)try{let l=await se("git",["-C",e,"diff","-U0","--no-color","--no-ext-diff",r.head,n,"--",...c]);a=Ch(l)}catch{}return{run:r,dismissed:o,lineMap:a}}catch{return}}async function Qu(e,t){try{await oC(e,t)}catch{}}var Rs;async function hC(){if(Rs)return Rs;try{Rs=`diffloupe@${(await se("git",["-C",import.meta.dir,"rev-parse","--short=12","HEAD"])).trim()}`}catch{Rs="diffloupe"}return Rs}var ed=(e)=>sC(Et(e));function mC(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 bs(`range:${e.spec}`);default:return{kind:e.kind}}}function gC(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 _C(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 se("git",["-C",e,"rev-parse","--abbrev-ref","HEAD"])).trim()||void 0}catch{}return{kind:n.kind,...s?{branch:s}:{}}}async function _y(e){try{return await hy(ft.join(e,"raw","review.md"),"utf8")}catch{return}}var nd=Js.engines.bun.replace(/^>=\s*/,"");function wy(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 bC(e){return/\d+\.\d+(?:\.\d+)?/.exec(e)?.[0]??null}function yy(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 ka(e,t,n,r){if(!e.which(t))return{name:t,status:n,detail:`not found on PATH. Install: ${Ra[t]??t}`};let s=await e.exec(t,["--version"]),o=s&&s.code===0?bC(s.output):null,a=r?.(o)??{status:"ok"},c=[o??"version unknown",a.note].filter(Boolean).join(", ");return{name:t,status:a.status,detail:c}}async function vC(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:wy(e.bunVersion,nd)?"ok":"fail",detail:wy(e.bunVersion,nd)?e.bunVersion:`${e.bunVersion}, needs ${nd} or newer`}),t.push(await ka(e,"git","fail")),t.push(await ka(e,"opencode","fail",(a)=>td(a)?{status:"ok"}:{status:"fail",note:"needs OpenCode 2.x (https://opencode.ai/v2/docs/)"})),t.push(await ka(e,"tilth","fail"));let n=await ka(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 nn){let c=r.models[a];t.push({name:`model: ${a}`,status:"ok",detail:`${c.model} (${to(c.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,c)=>a+c,0);return t.push({name:"data dir",status:"ok",detail:`${en()}: ${yy(o)} (${Object.entries(s).map(([a,c])=>`${a} ${yy(c)}`).join(", ")}). \`diffloupe runs prune\` removes old runs`}),t}async function Ea(e){let t=0,n;try{n=await wC(e,{withFileTypes:!0})}catch{return 0}for(let r of n){let s=by.join(e,r.name);if(r.isDirectory())t+=await Ea(s);else if(r.isFile())t+=await yC(s).then((o)=>o.size,()=>0)}return t}async function xC(e,t){try{let n=await te(e,t,{allowFail:!0,timeoutMs:20000});return{code:n.code,output:`${n.stdout}
589
- ${n.stderr}`}}catch{return null}}var $C={ok:Es.default.green("ok "),warn:Es.default.yellow("warn"),fail:Es.default.red("FAIL")};function vy(){return new Kt("doctor").description("Check tools, models, credentials and disk use").option("--config <file>","Per-repo review settings, as passed to review").action(async(e)=>{let t=await vC({platform:process.platform,bunVersion:Bun.version,which:(n)=>Bun.which(n),exec:xC,setup:async()=>{let n=e.config?await va(by.resolve(e.config)):{};return xa({settings:n,userConfig:await _r()})},dataSizes:async()=>({runs:await Ea(_s()),artifacts:await Ea(si()),scratch:await Ea(ws())})});for(let n of t)console.log(`${$C[n.status]} ${Es.default.bold(n.name)}: ${n.detail}`);if(t.some((n)=>n.status==="fail"))process.exit(1)})}import vI from"path";var dn=dc(Qs(),1);function As(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.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 SC from"path";import{appendFileSync as RC}from"fs";import{readFile as kC}from"fs/promises";function EC(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 Aa(e){return EC({prepare:(t,n)=>my(t,e,n),execute:gy})}class Ca extends Error{activeRunId;constructor(e){super(e?`run ${e} is still running`:"a run is starting");this.activeRunId=e;this.name="RunBusyError"}}function xy(e){return SC.join(Et(e),"events.jsonl")}async function $y(e){let t;try{t=await kC(xy(e),"utf8")}catch{return[]}let n=[];return t.split(`
590
- `).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 Cs{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 Ca(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:c})=>(o({type:"done",status:"complete",findings:a.findings.length,carriedOver:a.findings.filter((l)=>l.carriedFrom).length,costUsd:a.meta.costUsd,wallMs:a.meta.wallMs,...c?{}:{noChanges:!0},...a.meta.kind==="diff"?{kind:"diff",files:a.files.length}:{}}),{status:"complete",run:a,reviewed:c}),(a)=>{if(r.signal.aborted||a instanceof Dt)return o({type:"cancelled"}),{status:"cancelled"};let c=a instanceof Error?a.message:String(a);return o({type:"error",message:c}),{status:"failed",error:c}}).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=Oh(e.pending,t);let n={...t,seq:++e.seq,at:new Date().toISOString()};try{RC(xy(e.id),`${JSON.stringify(n)}
591
- `)}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{}}}function Kn(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 sd(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 AC(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 Ry(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} ${Kn(t.target)}`,t.kind==="diff"?` ${t.repo.slug??t.repo.root}${t.costUsd?` $${t.costUsd.toFixed(2)}`:""}`:` ${t.repo.slug??t.repo.root} ${AC(t.findingCounts)} $${t.costUsd.toFixed(2)}`].join(`
572
+ `)+"}");class ma{config;resolvedConfig;name;get[ft](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(e,t){if(this.config=ds(F.config,t),this.resolvedConfig=ds(F.resolvedConfig,t),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(Lu).length}`,this.name in Lu)A(`A Scope already named ${this.name} already exists`);Lu[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(Yg(o));this.aliases[o]=s}else{if(o in this.aliases)A(Yg(r));this.aliases[o]=s,this.exportedNames.push(o)}if(!X(s,"module")&&!X(s,"generic")&&!Wn(s)){let a=this.preparseOwnDefinitionFormat(s,{alias:o});this.resolutions[o]=X(a,"root")?this.bindReference(a):this.createParseContext(a).id}}Zg??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[Zg.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=F.intrinsic?se(F.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 Xn(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(gs(e),e,t);preparseNode(e,t,n){let r=typeof e==="string"?e:gs(t,e);if(Se(t)&&t.kind===r)return t;if(r==="alias"&&!n?.prereduced){let{reference:a}=xs.implementation.normalize(t,this);if(a.startsWith("$")){let c=this.resolveRoot(a.slice(1));t=c,r=c.kind}}else if(r==="union"&&xt(t,"object")){let a=ZE(t);if(a?.length===1)t=a[0],r=gs(t)}if(Se(t)&&t.kind===r)return t;let o=di[r].normalize?.(t,this)??t;if(Se(o))return o.kind===r?o:QE(r,o.kind);return{...n,$:this,kind:r,def:o,prefix:n.alias??r}}bindReference(e){let t;if(Se(e))t=e.$===this?e:new e.constructor(e.attachments,this);else t=e.$===this?e:new Xn(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(Bu(e))}maybeResolveRoot(e){let t=this.maybeResolve(e);if(X(t,"generic"))return;return t}maybeResolveSubalias(e){return ju(this.aliases,e)??ju(this.ambient,e)}get ambient(){return F.ambient}maybeResolve(e){let t=this.resolutions[e];if(t){if(typeof t!=="string")return this.bindReference(t);let r=pt[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 pe(`Unexpected resolved context for was uncached by its scope: ${oe(r)}`);r.phase="resolving";let s=this.bindReference(this.parseOwnDefinitionFormat(r.def,r));return r.phase="resolved",pt[s.id]=s,pt[r.id]=s,this.resolutions[e]=s}return pe(`Unexpected nodesById entry for ${t}: ${oe(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(s_(e));return this.resolutions[e]=this.bindReference(n.root)}return this.resolutions[e]=this.parse(n,{alias:e})}createParseContext(e){let t=e.id??vu(e.prefix);return pt[t]=Object.assign(e,{[ft]:"context",$:this,id:t,phase:"unresolved"})}traversal(e){return new en(e,this.resolvedConfig)}import(...e){return new hi(se(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")?Du(r,this):Qg(this.maybeResolve(n))}for(let n of this.lazyResolutions)n.resolution;if(this._exportedResolutions=i_(this,this._exports),this._json=r_(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let n=n_(this.references);this.precompilation=n.write(e_,4),t_(this.references,n)}this.resolved=!0}let t=e.length?e:this.exportedNames;return new hi(se(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(Se(r))return this.bindReference(r);let s=this.createParseContext(r),o=xu(s),a=this.bindReference(o);return pt[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);pt[r.id]=r;let s=this.bindReference(this.parseOwnDefinitionFormat(e,r));if(s.isCyclic)s=vg(s,r.id);return pt[r.id]=s,s}finalize(e){if(Qg(e),!e.precompilation&&!this.resolvedConfig.jitless)e0(e.references);return e}}class Uu extends ma{parseOwnDefinitionFormat(e,t){return xu(t)}preparseOwnDefinitionFormat(e,t){return this.preparseNode(gs(e),e,t)}preparseOwnAliasEntry(e,t){return[e,t]}normalizeRootScopeValue(e){return e}}var Qg=(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},r_=(e)=>se(e,(t,n)=>[t,X(n,"root")||X(n,"generic")?n.json:X(n,"module")?r_(n):pe(`Unexpected resolution ${oe(n)}`)]),ju=(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(t0(r));let o=t.slice(n+1),a=s[o];if(a===void 0)return ju(s,o);if(X(a,"root")||X(a,"generic"))return a;if(X(a,"module"))return a.root??A(s_(t));pe(`Unexpected resolution for alias '${t}': ${oe(a)}`)},ga=(e,t)=>new Uu(e,t),$s=new Uu({});var i_=(e,t)=>{let n={};for(let r in t){let s=t[r];if(X(s,"module")){let o=i_(e,s),a=se(o,(c,l)=>[`${r}.${c}`,l]);Object.assign(n,a)}else if(X(s,"root")||X(s,"generic"))n[r]=s;else pe(`Unexpected scope resolution ${oe(s)}`)}return n},Bu=(e)=>`'${e}' is unresolvable`,t0=(e)=>`'${e}' must reference a module to be accessed using dot syntax`,s_=(e)=>`Reference to submodule '${e}' must specify an alias`;$s.export();var{schema:me,node:mi,defineSchema:AB,generic:Kt}=$s;var qu="^(?:0|[1-9]\\d*)$",n0=new RegExp(qu),OB=Me(n0);var o_=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();F.intrinsic={...o_};var a_=ga({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:qu}},{prereducedAliases:!0}).export();Object.assign(F.intrinsic,a_);var r0=ga({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),te={...o_,...a_,...r0,emptyStructure:mi("structure",{},{prereduced:!0})};F.intrinsic={...te};var _a=(e,t)=>new RegExp(e,t);Object.assign(_a,{as:_a});var l_=(e)=>typeof e==="string"&&e[0]==="d"&&(e[1]==="'"||e[1]==='"')&&e[e.length-1]===e[1],c_=(e)=>e.toString()!=="Invalid Date",u_=(e)=>e.slice(2,-1),Hu=(e)=>`'${e}' could not be parsed by the Date constructor`,d_=(e,t)=>i0(e,t),i0=(e,t)=>{let n=new Date(e);if(c_(n))return n;let r=Dm(e);if(r!==void 0){let s=new Date(r);if(c_(s))return s}return t?A(t===!0?Hu(e):t):void 0};var s0=me({proto:"Array",sequence:"string",required:{key:"groups",value:["object",{unit:void 0}]}}),wa=(e,t)=>{let n=e.scanner.shiftUntilEscapable(a0[h_[t]]);if(e.scanner.lookahead==="")return e.error(l0(n,t));if(e.scanner.shift(),t in p_){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:s0})}else if(ze(t,Ku))e.root=e.ctx.$.node("unit",{unit:n});else{let r=d_(n,Hu(n));e.root=e.ctx.$.node("unit",{meta:n,unit:r})}},Ku={"'":1,'"':1},f_={"/":1,"'":1,'"':1},o0={"d'":"'",'d"':'"',"'":"'",'"':'"'},p_={"/":"/","x/":"/"},h_={...o0,...p_},a0={"'":(e)=>e.lookahead==="'",'"':(e)=>e.lookahead==='"',"/":(e)=>e.lookahead==="/"},c0={'"':"double-quote","'":"single-quote","/":"forward slash"},l0=(e,t)=>`${t}${e} requires a closing ${c0[h_[t]]}`;var m_=(e)=>`Private type references should not include '#'. Use '${e}' instead.`,ya="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 pn={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...Vn};var g_=(e,t)=>e===">"?t[0]==="="?t[1]==="=":t.trimStart()===""||ze(t.trimStart()[0],pn):e==="="?t[0]!=="=":e===","||e==="?";var __=(e,t,n)=>w_(e,t,n,[]),w_=(e,t,n,r)=>{let s=n.parseUntilFinalizer();if(r.push(s.root),s.finalizer===">"){if(r.length!==t.params.length)return n.error(Wu(e,t.names,r.map((o)=>o.expression)));return r}if(s.finalizer===",")return w_(e,t,n,r);return s.error(ta(">"))},Wu=(e,t,n)=>`${e}<${t.join(", ")}> requires exactly ${t.length} args (got ${n.length}${n.length===0?"":`: ${n.join(", ")}`})`;var va=(e)=>{let t=e.scanner.shiftUntilLookahead(pn);if(t==="keyof")e.addPrefix("keyof");else e.root=d0(e,t)},u0=(e,t,n)=>{if(n.scanner.shiftUntilNonWhitespace(),n.scanner.shift()!=="<")return n.error(Wu(e,t.names,[]));let s=__(e,t,n);return t(...s)},d0=(e,t)=>f0(e,t)??p0(e,t)??e.error(t===""?e.scanner.lookahead==="#"?m_(e.shiftedBy(1).scanner.shiftUntilLookahead(pn)):Vu(e):Bu(t)),f0=(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 u0(t,n,e);return A(`Unexpected resolution ${oe(n)}`)},p0=(e,t)=>{let n=Lm(t);if(n!==void 0)return e.ctx.$.node("unit",{unit:n});let r=Um(t);if(r!==void 0)return e.ctx.$.node("unit",{unit:r})},Vu=(e)=>{let t=e.previousOperator();return t?Gu(t,e.scanner.unscanned):h0(e.scanner.unscanned)},Gu=(e,t="")=>`Token '${e}' requires a right operand${t?` before '${t}'`:""}`,h0=(e)=>`Expected an expression${e?` before '${e}'`:""}`;var zu=(e)=>e.scanner.lookahead===""?e.error(Vu(e)):e.scanner.lookahead==="("?e.shiftedBy(1).reduceGroupOpen():e.scanner.lookaheadIsIn(f_)?wa(e,e.scanner.shift()):e.scanner.lookaheadIsIn(Vn)?zu(e.shiftedBy(1)):e.scanner.lookahead==="d"?e.scanner.nextLookahead in Ku?wa(e,`${e.scanner.shift()}${e.scanner.shift()}`):va(e):e.scanner.lookahead==="x"?e.scanner.nextLookahead==="/"?e.shiftedBy(2)&&wa(e,"x/"):va(e):va(e);var y_={">":!0,">=":!0},b_={"<":!0,"<=":!0};var gi={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},v_=(e,t)=>`Left bounds are only valid when paired with right bounds (try ...${t}${e})`,xa=(e)=>`Left-bounded expressions must specify their limits using < or <= (was ${e})`,x_=(e,t,n,r)=>`An expression may have at most one left bound (parsed ${e}${gi[t]}, ${n}${gi[r]})`;var R_=(e,t)=>{let n=m0(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 _0(e,n)},$_={"<":1,">":1,"=":1},m0=(e,t)=>e.scanner.lookaheadIs("=")?`${t}${e.scanner.shift()}`:t;var S_=(e,t,n,r)=>{if(n.extends(F.intrinsic.number)){if(typeof t!=="number")return A(Ju(e,t,r));return e==="=="?["min","max"]:e[0]===">"?["min"]:["max"]}if(n.extends(F.intrinsic.lengthBoundable)){if(typeof t!=="number")return A(Ju(e,t,r));return e==="=="?["exactLength"]:e[0]===">"?["minLength"]:["maxLength"]}if(n.extends(F.intrinsic.Date))return e==="=="?["after","before"]:e[0]===">"?["after"]:["before"];return A(cg(n.expression))},g0=(e)=>({rule:l_(e.limit)?u_(e.limit):e.limit,exclusive:e.comparator.length===1}),_0=(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(Ju(t,o,"right"));let a=s.unit,c=t.length===1,l=S_(t,typeof a==="number"?a:o,n,"right");for(let d of l)e.constrainRoot(d,t==="=="?{rule:a}:{rule:a,exclusive:c});if(!e.branches.leftBound)return;if(!ze(t,b_))return e.error(xa(t));let u=S_(e.branches.leftBound.comparator,e.branches.leftBound.limit,n,"left");e.constrainRoot(u[0],g0(e.branches.leftBound)),e.branches.leftBound=null},Ju=(e,t,n)=>`Comparator ${n==="left"?gi[e]:e} must be ${n==="left"?"preceded":"followed"} by a corresponding literal (was ${t})`;var k_=(e)=>{e.scanner.shiftUntilNonWhitespace();let t=e.scanner.shiftUntilLookahead(pn);e.root=e.root.brand(t)};var A_=(e)=>{e.scanner.shiftUntilNonWhitespace();let t=e.scanner.shiftUntilLookahead(pn),n=jm(t,{errorOnFail:E_(t)});if(n===0)e.error(E_(0));e.root=e.root.constrain("divisor",n)},E_=(e)=>`% operator must be followed by a non-zero integer literal (was ${e})`;var Xu=(e)=>{let t=e.scanner.shift();return t===""?e.finalize(""):t==="["?e.scanner.shift()==="]"?e.setRoot(e.root.array()):e.error(w0):t==="|"?e.scanner.lookahead===">"?e.shiftedBy(1).pushRootToBranch("|>"):e.pushRootToBranch(t):t==="&"?e.pushRootToBranch(t):t===")"?e.finalizeGroup():g_(t,e.scanner.unscanned)?e.finalize(t):ze(t,$_)?R_(e,t):t==="%"?A_(e):t==="#"?k_(e):(t in Vn)?Xu(e):e.error(Sa(t))},Sa=(e,t="")=>`'${e}' is not allowed here${t&&` (should be ${t})`}`,w0="Missing expected ']'";var C_=(e)=>{let t=e.unsetRoot();e.parseOperand();let n=e.unsetRoot();if(!n.hasKind("unit"))return e.error(y0(n.expression));let r=n.unit instanceof Date?()=>new Date(n.unit):n.unit;return[t,"=",r]},y0=(e)=>`Default value '${e}' must be a literal value`;var Yu=(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 _i(new ls(e),t),s=b0(r);if(r.finalizer===">")A(Sa(">"));return s},b0=(e)=>{e.parseOperand();let t=ks(e).root;if(!t)return pe(`Root was unexpectedly unset after parsing string '${e.scanner.scanned}'`);if(e.finalizer==="=")t=C_(e);else if(e.finalizer==="?")t=[t,"?"];if(e.scanner.shiftUntilNonWhitespace(),e.scanner.lookahead)A(Sa(e.scanner.lookahead));return t},ks=(e)=>{while(e.finalizer===void 0)v0(e);return e},v0=(e)=>e.hasRoot()?e.parseOperator():e.parseOperand();class _i{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(ta(")"));this.finalizeBranches(),this.finalizer=e}reduceLeftBound(e,t){let n=gi[t];if(!ze(n,y_))return this.error(xa(t));if(this.branches.leftBound)return this.error(x_(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(Km(")",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():pe(`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 ks(new _i(this.scanner,this.ctx))}parseOperator(){return Xu(this)}parseOperand(){return zu(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(v_(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 x0="An empty string is not a valid generic parameter name",Ra=(e,t,n)=>{e.shiftUntilNonWhitespace();let r=e.shiftUntilLookahead(pn);if(r===""){if(e.lookahead===""&&t.length)return t;return A(x0)}return e.shiftUntilNonWhitespace(),S0(e,r,t,n)},I_="extends ",S0=(e,t,n,r)=>{if(e.shiftUntilNonWhitespace(),e.unscanned.startsWith(I_))e.jumpForward(I_.length);else{if(e.lookahead===",")e.shift();return n.push(t),Ra(e,n,r)}let s=ks(new _i(e,r));return n.push([t,s.root]),Ra(e,n,r)};class Zu extends $t{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"),c=e.intrinsic.unknown;if(r!==-1){if(r!==n.length-2)return A(R0);c=e.parse(n[r+1])}return(l)=>new O_(l,a,c)},{attach:t})}}class O_ extends $t{raw;params;returns;expression;constructor(e,t,n){let r=`typed ${e.name}`,s={[r]:(...a)=>{let c=t.assert(a),l=e(...c);return n.assert(l)}}[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 R0=`":" must be followed by exactly one return type e.g:
573
+ fn("string", ":", "number")(s => s.length)`;class Qu extends $t{$;constructor(e){super((...t)=>new Es(e)(...t),{bind:e});this.$=e}in(e){return new Es(this.$,e===void 0?void 0:this.$.parse(e))}at(e,t){return new Es(this.$).at(e,t)}case(e,t){return new Es(this.$).case(e,t)}}class Es extends $t{$;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(k0);if(this.branches.length)A($0);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 ${Ge(r)})`);this.caseEntry(n,r)}return this}default(e){if(typeof e==="function")this.case(te.unknown,e);let t={branches:this.branches,ordered:!0};if(e==="never"||e==="assert")t.meta={onFail:P_};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:P_},"self");return this.$.finalize(r)}}var P_=(e)=>e.throw(),$0="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",k0="At most one key matcher may be specified per expression";var $a=(e,t)=>{if(xe(e)){if(e[1]==="=")return[t.$.parseOwnDefinitionFormat(e[0],t),"=",e[2]];if(e[1]==="?")return[t.$.parseOwnDefinitionFormat(e[0],t),"?"]}return ka(e,t)},M_="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",T_="Only required keys may specify default values, e.g. { value: 'number = 0' }";var F_=(e,t)=>{let n,r={},s=_r(e);for(let[a,c]of s){let l=C0(a);if(l.kind==="spread"){if(!dn(r))return A(A0);let h=t.$.parseOwnDefinitionFormat(c,t);if(h.equals(te.object))continue;if(!h.hasKind("intersection")||!h.basis?.equals(te.object))return A(I0(h.expression));n=h.structure;continue}if(l.kind==="undeclared"){if(c!=="reject"&&c!=="delete"&&c!=="ignore")A(E0(c));r.undeclared=c;continue}let u=$a(c,t),d=l;if(l.kind==="required"){if(!xe(u))ed(r,"required",{key:l.normalized,value:u},t);else ed(r,"optional",u[1]==="="?{key:l.normalized,value:u[0],default:u[2]}:{key:l.normalized,value:u[0]},t);continue}if(xe(u)){if(u[1]==="?")A(M_);if(u[1]==="=")A(T_)}if(l.kind==="optional"){ed(r,"optional",{key:l.normalized,value:u},t);continue}let f=t.$.parseOwnDefinitionFormat(d.normalized,t),p=ha(f,u,t.$);if(p.index)r.index=fe(r.index,p.index);if(p.required)r.required=fe(r.required,p.required)}let o=t.$.node("structure",r);return t.$.parseSchema({domain:"object",structure:n?.merge(o)??o})},ed=(e,t,n,r)=>{e[t]=fe(e[t],r.$.node(t,n))},E0=(e)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${oe(e)})`,A0="Spread operator may only be used as the first key in an object",C0=(e)=>typeof e==="symbol"?{kind:"required",normalized:e}:e[e.length-1]==="?"?e[e.length-2]===yr?{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]===yr&&e[1]==="["&&e[e.length-1]==="]"?{kind:"required",normalized:e.slice(1)}:e==="..."?{kind:"spread"}:e==="+"?{kind:"undeclared"}:{kind:"required",normalized:e==="\\..."?"...":e==="\\+"?"+":e},I0=(e)=>`Spread operand must resolve to an object literal type (was ${e})`;var D_=(e,t)=>U0(e)?B_[e[0]](e,t):L0(e)?U_[e[1]](e,t):null,O0=(e,t)=>t.$.parseOwnDefinitionFormat(e[1],t).keyof(),td=(e,t)=>{if(e[2]===void 0)return A(Gu(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.$):ms(n,r,t.$);if(s instanceof U)return s.throw();return s},P0=(e,t)=>t.$.parseOwnDefinitionFormat(e[0],t).array(),M0=(e,t)=>{if(typeof e[2]!=="function")return A(L_("=>",e[2]));return t.$.parseOwnDefinitionFormat(e[0],t).pipe(e[2])},L_=(e,t)=>`${e===":"?"Narrow":"Morph"} expression requires a function following '${e}' (was ${typeof t})`,T0=(e,t)=>{if(typeof e[2]!=="function")return A(L_(":",e[2]));return t.$.parseOwnDefinitionFormat(e[0],t).constrain("predicate",e[2])},F0=(e,t)=>t.$.parseOwnDefinitionFormat(e[0],t).configure(e[2],e[3]),j_=(e)=>e,N0=j_({"[]":P0,"?":()=>A(ya)}),D0=j_({"|":td,"&":td,":":T0,"=>":M0,"|>":td,"@":F0,"=":()=>A(ba)}),U_={...N0,...D0},L0=(e)=>U_[e[1]]!==void 0,j0=(e)=>e,B_=j0({keyof:O0,instanceof:(e,t)=>{if(typeof e[1]!=="function")return A(N_(ns(e[1])));let n=e.slice(1).map((r)=>typeof r==="function"?t.$.node("proto",{proto:r}):A(N_(ns(r))));return n.length===1?n[0]:t.$.node("union",{branches:n})},"===":(e,t)=>t.$.units(e.slice(1))}),U0=(e)=>B_[e[0]]!==void 0,N_=(e)=>`Expected a constructor following 'instanceof' operator (was ${e})`;var K_=(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=$a(e[r],t),[a,c,l]=!xe(o)?[o]:o;if(r++,s){if(!a.extends(F.intrinsic.Array))return A(H0(a.expression));n=n.flatMap((u)=>a.distribute((d)=>q0(ra(u),d)))}else n=n.map((u)=>{if(c==="?")return W_(u,a);if(c==="=")return B0(u,a,l);return nd(u,a)})}return t.$.parseSchema(n.map((s)=>dn(s)?{proto:Array,exactLength:0}:{proto:Array,sequence:s}))},nd=(e,t)=>{if(e.defaultables||e.optionals)return A(e.variadic?Tu:K0);if(e.variadic)e.postfix=fe(e.postfix,t);else e.prefix=fe(e.prefix,t);return e},W_=(e,t)=>{if(e.variadic)return A(V_);return e.optionals=fe(e.optionals,t),e},B0=(e,t,n)=>{if(e.variadic)return A(V_);if(e.optionals)return A(W0);return e.defaultables=fe(e.defaultables,[[t,n]]),e},q_=(e,t)=>{if(e.postfix)A(H_);if(e.variadic){if(!e.variadic.equals(t))A(H_)}else e.variadic=t.internal;return e},q0=(e,t)=>{let n=t.select({method:"find",kind:"sequence"});if(!n)return q_(e,F.intrinsic.unknown);if(n.prefix)for(let r of n.prefix)nd(e,r);if(n.optionals)for(let r of n.optionals)W_(e,r);if(n.variadic)q_(e,n.variadic);if(n.postfix)for(let r of n.postfix)nd(e,r);return e},H0=(e)=>`Spread element must be an array (was ${e})`,H_="A tuple may have at most one variadic element",K0="A required element may not follow an optional element",V_="An optional element may not follow a variadic element";var W0="A defaultable element may not follow an optional element without a default";var V0={},ka=(e,t)=>{if(typeof e==="string"){if(t.args&&Object.keys(t.args).some((r)=>e.includes(r)))return Yu(e,t);let n=V0[t.$.name]??={};return n[e]??=Yu(e,t)}return xt(e,"object")?G0(e,t):A(rd(Ge(e)))},G0=(e,t)=>{let n=ts(e);switch(n){case void 0:if(X(e,"root"))return e;if("~standard"in e)return z0(e,t);return F_(e,t);case"Array":return J0(e,t);case"RegExp":return t.$.node("intersection",{domain:"string",pattern:e},{prereduced:!0});case"Function":{let r=Wn(e)?e():e;if(X(r,"root"))return r;return A(rd("Function"))}default:return A(rd(n??oe(e)))}},z0=(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:Om(o),relativePath:a.map((c)=>typeof c==="object"?c.key:c)});else r.error({message:o});else r.error({message:o})}),J0=(e,t)=>D_(e,t)??K_(e,t),rd=(e)=>`Type definitions must be strings or objects (was ${e})`;class id extends $t{constructor(e){let t=Object.assign({errors:kt,hkt:st,$: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 Xn(s,n[1],e,e,null)}return e.parse(n)},{attach:t})}}var wi=F;class Ea extends ma{get ambientAttachments(){if(!wi.typeAttachments)return;return this.cacheGetter("ambientAttachments",se(wi.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 sg(o,t,this)}]}parseGenericParams(e,t){return Ra(new ls(e),[],this.createParseContext({...t,def:e,prefix:"generic"}))}normalizeRootScopeValue(e){if(Wn(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=ka(e,t);if(xe(r)){if(r[1]==="=")return A(ba);if(r[1]==="?")return A(ya)}return r}unit=(e)=>this.units([e]);valueOf=(e)=>this.units(xm(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 Zu(this);match=new Qu(this);declare=()=>({type:this.type});define(e){return e}type=new id(this);static scope=(e,t={})=>new Ea(e,t);static module=(e,t={})=>this.scope(e,t).export()}var sd=Object.assign(Ea.scope,{define:(e)=>e}),ue=Ea;class G_ extends st{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var X0=Kt(["base",te.object],["props",te.object])((e)=>e.base.merge(e.props),G_),z_=ue.module({Key:te.key,Merge:X0});class J_ extends st{}var Y0=Kt("element")((e)=>{let t=e.element.exclude(te.Array),n=t.array();return t.rawOr(n).pipe(Kn).distribute((r)=>r.assertHasKind("morph").declareOut(n),me)},J_),X_=ue.module({root:te.Array,readonly:"root",index:te.nonNegativeIntegerString,liftFrom:Y0},{name:"Array"});var od=me(["string",br.FileConstructor]),Z0=od.rawOr(od.array()),Y_=me({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:Z0}}),Z_=ue.module({root:["instanceof",FormData],value:od,parsed:Y_,parse:me({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 br.FileConstructor)t[n]=[s,r];else s.push(r)}else t[n]=r;return t},declaredOut:Y_})},{name:"FormData"});var Q_=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 Q0={Boolean:1,Number:1,String:1},ew=ue.module({...se({...Gl,...Jl},(e,t)=>(e in Q0)?[]:[e,["instanceof",t]]),Array:X_,TypedArray:Q_,FormData:Z_});var eA=me({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"}),tA=me({domain:"number",divisor:1}),Aa=ue.module({root:te.number,integer:tA,epoch:eA,safe:me({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 Ee=(e,t,n)=>{let r={domain:"string",pattern:{rule:e.source,flags:e.flags,meta:t}};if(n)r.meta={format:n};return mi("intersection",r)},tw=Ee(is,"a well-formed integer string"),pw=ue.module({root:tw,parse:me({in:tw,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:te.integer})},{name:"string.integer"}),nA=Ee(/^[\dA-Fa-f]+$/,"hex characters only"),rA=ue.module({root:Ee(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:Ee(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),nw=Ee(/^[A-Z].*$/,"capitalized"),iA=ue.module({root:me({in:"string",morphs:(e)=>e.charAt(0).toUpperCase()+e.slice(1),declaredOut:nw}),preformatted:nw},{name:"string.capitalize"}),sA=(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)},oA=/^(?: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}))$/,aA=me({domain:"string",pattern:{meta:"a credit card number",rule:oA.source},predicate:{meta:"a credit card number",predicate:sA}});var cA=/^([+-]?\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 lA=(e)=>!Number.isNaN(new Date(e).valueOf()),rw=me({domain:"string",predicate:{meta:"a parsable date",predicate:lA}}).assertHasKind("intersection"),iw=pw.root.internal.narrow((e,t)=>{let n=Number.parseInt(e),r=Aa.epoch(n);if(r instanceof kt)return t.errors.merge(r),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),uA=ue.module({root:iw,parse:me({in:iw,morphs:(e)=>new Date(e),declaredOut:te.Date})},{name:"string.date.epoch"}),sw=Ee(cA,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),dA=ue.module({root:sw,parse:me({in:sw,morphs:(e)=>new Date(e),declaredOut:te.Date})},{name:"string.date.iso"}),fA=ue.module({root:rw,parse:me({declaredIn:rw,in:"string",morphs:(e,t)=>{let n=new Date(e);if(Number.isNaN(n.valueOf()))return t.error("a parsable date");return n},declaredOut:te.Date}),iso:dA,epoch:uA},{name:"string.date"}),pA=Ee(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),ow="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",Yn=`(${ow}[.]){3}${ow}`,hA=new RegExp(`^${Yn}$`),Be="(?:[0-9a-fA-F]{1,4})",mA=new RegExp(`^((?:${Be}:){7}(?:${Be}|:)|(?:${Be}:){6}(?:${Yn}|:${Be}|:)|(?:${Be}:){5}(?::${Yn}|(:${Be}){1,2}|:)|(?:${Be}:){4}(?:(:${Be}){0,1}:${Yn}|(:${Be}){1,3}|:)|(?:${Be}:){3}(?:(:${Be}){0,2}:${Yn}|(:${Be}){1,4}|:)|(?:${Be}:){2}(?:(:${Be}){0,3}:${Yn}|(:${Be}){1,5}|:)|(?:${Be}:){1}(?:(:${Be}){0,4}:${Yn}|(:${Be}){1,6}|:)|(?::((?::${Be}){0,5}:${Yn}|(?::${Be}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),gA=ue.module({root:["v4 | v6","@","an IP address"],v4:Ee(hA,"an IPv4 address","ipv4"),v6:Ee(mA,"an IPv6 address","ipv6")},{name:"string.ip"}),yi="a JSON string",hw=(e)=>{if(!(e instanceof SyntaxError))throw e;return`must be ${yi} (${e})`},_A=me({meta:yi,domain:"string",predicate:{meta:yi,predicate:(e,t)=>{try{return JSON.parse(e),!0}catch(n){return t.reject({code:"predicate",expected:yi,problem:hw(n)})}}}}),wA=(e,t)=>{if(e.length===0)return t.error({code:"predicate",expected:yi,actual:"empty"});try{return JSON.parse(e)}catch(n){return t.error({code:"predicate",expected:yi,problem:hw(n)})}},yA=ue.module({root:_A,parse:me({meta:"safe JSON string parser",in:"string",morphs:wA,declaredOut:te.jsonObject})},{name:"string.json"}),aw=Ee(/^[a-z]*$/,"only lowercase letters"),bA=ue.module({root:me({in:"string",morphs:(e)=>e.toLowerCase(),declaredOut:aw}),preformatted:aw},{name:"string.lower"}),mw=["NFC","NFD","NFKC","NFKD"],As=se(mw,(e,t)=>[t,me({domain:"string",predicate:(n)=>n.normalize(t)===n,meta:`${t}-normalized unicode`})]),Ca=se(mw,(e,t)=>[t,me({in:"string",morphs:(n)=>n.normalize(t),declaredOut:As[t]})]),vA=ue.module({root:Ca.NFC,preformatted:As.NFC},{name:"string.normalize.NFC"}),xA=ue.module({root:Ca.NFD,preformatted:As.NFD},{name:"string.normalize.NFD"}),SA=ue.module({root:Ca.NFKC,preformatted:As.NFKC},{name:"string.normalize.NFKC"}),RA=ue.module({root:Ca.NFKD,preformatted:As.NFKD},{name:"string.normalize.NFKD"}),$A=ue.module({root:"NFC",NFC:vA,NFD:xA,NFKC:SA,NFKD:RA},{name:"string.normalize"}),cw=Ee(Qo,"a well-formed numeric string"),kA=ue.module({root:cw,parse:me({in:cw,morphs:(e)=>Number.parseFloat(e),declaredOut:te.number})},{name:"string.numeric"}),lw="a regex pattern",EA=me({domain:"string",predicate:{meta:lw,predicate:(e,t)=>{try{return new RegExp(e),!0}catch(n){return t.reject({code:"predicate",expected:lw,problem:String(n)})}}},meta:{format:"regex"}}),AA=/^(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-]+)*))?$/,CA=Ee(AA,"a semantic version (see https://semver.org/)"),uw=Ee(/^\S.*\S$|^\S?$/,"trimmed"),IA=ue.module({root:me({in:"string",morphs:(e)=>e.trim(),declaredOut:uw}),preformatted:uw},{name:"string.trim"}),dw=Ee(/^[A-Z]*$/,"only uppercase letters"),OA=ue.module({root:me({in:"string",morphs:(e)=>e.toUpperCase(),declaredOut:dw}),preformatted:dw},{name:"string.upper"}),PA=(e)=>URL.canParse(e),fw=me({domain:"string",predicate:{meta:"a URL string",predicate:PA},meta:{format:"uri"}}),MA=ue.module({root:fw,parse:me({declaredIn:fw,in:"string",morphs:(e,t)=>{try{return new URL(e)}catch{return t.error("a URL string")}},declaredOut:me(URL)})},{name:"string.url"}),TA=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:Ee(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:Ee(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:Ee(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:Ee(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:Ee(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:Ee(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:Ee(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:Ee(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),gw=ue.module({root:te.string,alpha:Ee(/^[A-Za-z]*$/,"only letters"),alphanumeric:Ee(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:nA,base64:rA,capitalize:iA,creditCard:aA,date:fA,digits:Ee(/^\d*$/,"only digits 0-9"),email:pA,integer:pw,ip:gA,json:yA,lower:bA,normalize:$A,numeric:kA,regex:EA,semver:CA,trim:IA,upper:OA,url:MA,uuid:TA},{name:"string"});var _w=ue.module({bigint:te.bigint,boolean:te.boolean,false:te.false,never:te.never,null:te.null,number:te.number,object:te.object,string:te.string,symbol:te.symbol,true:te.true,unknown:te.unknown,undefined:te.undefined}),ww=ue.module({root:te.unknown,any:te.unknown},{name:"unknown"}),FA=ue.module({root:te.jsonObject,stringify:mi("morph",{in:te.jsonObject,morphs:(e)=>JSON.stringify(e),declaredOut:te.string})},{name:"object.json"}),yw=ue.module({root:te.object,json:FA},{name:"object"});class bw extends st{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var NA=Kt(["K",te.key],"V")((e)=>({domain:"object",index:{signature:e.K,value:e.V}}),bw);class vw extends st{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var DA=Kt(["T",te.object],["K",te.key])((e)=>e.T.pick(e.K),vw);class xw extends st{description='omit a set of properties from an object like `Omit(User, "age")`'}var LA=Kt(["T",te.object],["K",te.key])((e)=>e.T.omit(e.K),xw);class Sw extends st{description="make all named properties of an object optional like `Partial(User)`"}var jA=Kt(["T",te.object])((e)=>e.T.partial(),Sw);class Rw extends st{description="make all named properties of an object required like `Required(User)`"}var UA=Kt(["T",te.object])((e)=>e.T.required(),Rw);class $w extends st{description='exclude branches of a union like `Exclude("boolean", "true")`'}var BA=Kt("T","U")((e)=>e.T.exclude(e.U),$w);class kw extends st{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var qA=Kt("T","U")((e)=>e.T.extract(e.U),kw),Ew=ue.module({Exclude:BA,Extract:qA,Omit:LA,Partial:jA,Pick:DA,Record:NA,Required:UA});var An=sd({..._w,...Ew,...ew,...z_,string:gw,number:Aa,object:yw,unknown:ww},{prereducedAliases:!0,name:"ark"}),Je=An.export();Object.assign(wi.ambient,Je);wi.typeAttachments={string:Je.string.root,number:Je.number.root,bigint:Je.bigint,boolean:Je.boolean,symbol:Je.symbol,undefined:Je.undefined,null:Je.null,object:Je.object.root,unknown:Je.unknown.root,false:Je.false,true:Je.true,never:Je.never,arrayIndex:Je.Array.index,Key:Je.Key,Record:Je.Record,Array:Je.Array.root,Date:Je.Date};var ee=Object.assign(An.type,wi.typeAttachments),{match:HA,fn:KA,generic:WA,schema:lW,define:VA,declare:GA}=An;var Ia=ee("'running' | 'complete' | 'failed' | 'cancelled'"),Oa=ee({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"}),Cw=ee("'additions' | 'deletions'"),zA=ee("'not-in-diff' | 'far-from-diff' | 'no-line' | 'deleted-file' | 'no-hunks'"),Iw=ee({file:"string",side:Cw,kind:"'line' | 'nearby' | 'file'",line:"number","endLine?":"number",cited:{line:"number","endLine?":"number"},"text?":"string","reason?":zA}),JA=ee("'added' | 'removed' | 'modified' | 'renamed' | 'copied'"),Ow=ee("'product' | 'deploy' | 'tooling'"),XA=ee({path:"string","previousPath?":"string",status:JA,additions:"number",deletions:"number",isBinary:"boolean","blob?":"string",groupId:"string",classification:"'code' | 'docs' | 'skip'","surface?":Ow}),YA=ee("'bug' | 'wrench' | 'path' | 'flask' | 'doc' | 'gear'"),cd=ee({id:"string","parentId?":"string",title:"string","summary?":"string","icon?":YA,files:"string[]",findingIds:"string[]",stopIds:"string[]",critical:"boolean"}),ZA=ee({id:"string",chapterId:"string",index:"number",title:"string","prose?":"string",importance:"'critical' | 'normal' | 'context'",locations:Iw.and({"label?":"string"}).array()}),QA=ee("'blocker' | 'should-fix' | 'nice-to-have' | 'question'"),Aw=ee({id:"string",file:"string",anchor:Iw,severity:QA,category:"string",title:"string",explanation:"string",evidence:"string","impact?":"string",confidence:"'high' | 'medium' | 'low'","effort?":"'quick' | 'moderate' | 'involved'","suggestion?":"string","suggestedCode?":"string","crossFileRefs?":ee({file:"string","line?":"number"}).array(),"repeatOf?":"number","carriedFrom?":"string","surface?":Ow,"preexisting?":"boolean"}),Pw=ee({input:"number",output:"number",reasoning:"number",cacheRead:"number",cacheWrite:"number","firstStep?":{input:"number",cacheRead:"number",cacheWrite:"number"}}),eC=ee({unit:"string",part:"number",parts:"number",status:"'ok' | 'failed'",costUsd:"number",wallMs:"number","usage?":Pw}),ad=ee({costUsd:"number",wallMs:"number","usage?":Pw}),Pa=ee({root:"string","slug?":"string","remote?":"boolean"}),Cs=ee("'review' | 'diff'");function Mw(e){return e.meta.kind??"review"}var tC=ee({id:"string",acted:"boolean",control:"boolean"}),Tw=ee({schemaVersion:"1",id:"string",status:Ia,createdAt:"string",repo:Pa,target:Oa,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:ee({file:"string",why:"string"}).array()},files:XA.array(),groups:cd.array(),stops:ZA.array(),findings:Aw.array(),overCapFindings:Aw.array(),resolved:ee({id:"string","note?":"string","title?":"string","file?":"string"}).array(),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?":Cs,wallMs:"number",costUsd:"number",slices:eC.array(),"stages?":{"coordinator?":ad,"walkthrough?":ad,"intent?":ad},rejectedCount:"number",coreSource:"string","mergeMode?":"'coordinator' | 'nothing-to-merge' | 'deterministic-fallback'","budgetStopped?":"boolean","reviewScope?":"'full' | 'incremental'","reviewedFiles?":"number","scopeReason?":"string","promptVersion?":"string","instructionsHash?":"string"},untrackedSkipped:"string[]","priorRunId?":"string","round?":"number","priorActedOn?":tC.array(),"error?":"string"}),ld=ee("'open' | 'accepted' | 'dismissed'"),ud=ee("'wrong' | 'not-worth-fixing' | 'already-handled' | 'duplicate' | 'other'"),Ma=["wrong","not-worth-fixing","already-handled","duplicate","other"],nC=ee({reason:ud,"note?":"string",at:"string"}),Fw=ee({reviewedFiles:ee.Record("string","string"),findingStatus:ee.Record("string",ld),"findingNotes?":ee.Record("string",nC),comments:ee({id:"string",file:"string",side:Cw,line:"number","endLine?":"number",body:"string"}).array(),"submitted?":{at:"string","url?":"string"}}),EW=ee({id:"string",status:Ia,createdAt:"string",target:Oa,repo:Pa,"kind?":Cs,findingCounts:{blocker:"number","should-fix":"number","nice-to-have":"number",question:"number"},costUsd:"number","invalid?":"string"});function Zn(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 gd(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 iC(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 Bw(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} ${Zn(t.target)}`,t.kind==="diff"?` ${t.repo.slug??t.repo.root}${t.costUsd?` $${t.costUsd.toFixed(2)}`:""}`:` ${t.repo.slug??t.repo.root} ${iC(t.findingCounts)} $${t.costUsd.toFixed(2)}`].join(`
592
574
  `)).join(`
593
575
 
594
- `)}function ky(e){let t=[e.preexisting&&"pre-existing",e.carriedFrom&&`open since ${e.carriedFrom}`].filter(Boolean);return t.length?` (${t.join(", ")})`:""}function rd(e){return` [${e.severity}] ${e.title}${ky(e)}
595
- ${sd(e.anchor)}`}function Ey(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?`
596
- ${t} ${n.note}`:""}`)]}function Ia(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 Ay(e){let t=[];if(t.push(`${e.id} ${e.status}`),t.push(`${Kn(e.target)} ${e.base.slice(0,12)}..${e.head.slice(0,12)}`),t.push(`${e.repo.slug??e.repo.root} ${e.createdAt}`),e.error)t.push(`error: ${e.error}`);if(e.priorRunId)t.push(`prior run: ${e.priorRunId}`);let n=Ia(e);if(n)t.push(n);if(e.overview.focus)t.push(`focus: ${e.overview.focus}`);if(e.intent.alignment)t.push(`intent: ${e.intent.alignment}`);let r=new Map(e.files.map((o)=>[o.path,o]));t.push(...Iy(e));let s=e.findings.filter((o)=>!r.has(o.file));if(s.length){t.push("",`Findings on files outside the diff (${s.length})`);for(let o of s)t.push(rd(o))}if(e.overCapFindings.length){t.push("",`Over the posting cap (${e.overCapFindings.length})`);for(let o of e.overCapFindings)t.push(rd(o))}if(t.push(...Ey(e," ")),e.stops.length){t.push("",`Walkthrough stops (${e.stops.length})`);for(let o of e.stops){t.push(` ${o.id} ${o.title}${o.importance==="normal"?"":` [${o.importance}]`}`);for(let a of o.locations)t.push(` ${sd(a)}`)}}if(e.untrackedSkipped.length)t.push("",`Untracked files skipped: ${e.untrackedSkipped.join(", ")}`);if(e.unreviewed.failed.length)t.push("",`Failed slices: ${e.unreviewed.failed.join(", ")}`);if(e.unreviewed.budget?.length)t.push("",`Not reviewed (cost limit): ${e.unreviewed.budget.join(", ")}`);if(Q_(e)==="diff")return t.push("",`${e.files.length} files${Cy(e)}, ${(e.meta.wallMs/1000).toFixed(1)}s`),t.join(`
597
- `);return t.push("",`${e.findings.length} findings, ${e.files.length} files, $${e.meta.costUsd.toFixed(2)}, ${Math.round(e.meta.wallMs/1000)}s`,`anchors: ${Mo(e)}`),t.join(`
598
- `)}function Cy(e){return e.meta.costUsd?`, $${e.meta.costUsd.toFixed(2)}`:""}function Iy(e){let t=[],n=new Map(e.findings.map((s)=>[s.id,s])),r=new Map(e.files.map((s)=>[s.path,s]));for(let s of e.groups){let o=!e.groups.some((c)=>c.parentId===s.id);if(!o||!s.parentId&&s.files.length===0){let c=o&&s.stopIds.length?` (stops ${s.stopIds.join(", ")}; files sit in other groups)`:"";t.push("",`${s.critical?"! ":""}${s.title}${c}`);continue}let a=s.parentId?" ":"";t.push(`${s.parentId?"":`
599
- `}${a}${s.critical?"! ":""}${s.title}`);for(let c of s.files){let l=r.get(c),u=l?` ${l.status} +${l.additions} -${l.deletions}${l.isBinary?" binary":""}`:"";t.push(`${a} ${c}${u}`);for(let d of s.findingIds){let f=n.get(d);if(f?.file===c)t.push(rd(f))}}}return t}function Oy(e){let t=[];if(t.push(`${Kn(e.target)} ${e.base.slice(0,12)}..${e.head.slice(0,12)}`),e.intent.inferred)t.push("",`What it does: ${id(e.intent.inferred,400)}`);if(t.push(...Iy(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}${Cy(e)}`),t.join(`
600
- `)}var Sy=["blocker","should-fix","question","nice-to-have"];function id(e,t=200){let n=e.trim().split(/(?<=[.!?])\s+/)[0]??"";return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function Py(e){let t=[];t.push(`${Kn(e.target)} ${e.base.slice(0,12)}..${e.head.slice(0,12)}`);let n=Ia(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: ${id(s.inferred,400)}`);if(e.overview.focus)t.push("",`Focus: ${e.overview.focus}`);let o=[...e.findings].sort((a,c)=>Number(a.preexisting??!1)-Number(c.preexisting??!1)||Sy.indexOf(a.severity)-Sy.indexOf(c.severity));t.push("",o.length?`Findings (${o.length})`:"No findings.");for(let a of o){t.push(` [${a.severity}] ${a.title}${ky(a)}`,` ${sd(a.anchor)}`);let c=id(a.impact??a.explanation);if(c&&c!==a.title)t.push(` ${c}`)}if(e.overCapFindings.length)t.push(` \u2026and ${e.overCapFindings.length} more over the cap (runs show)`);if(t.push(...Ey(e," ")),e.overview.startHere.length)t.push("","Start here"),e.overview.startHere.forEach((a,c)=>t.push(` ${c+1}. ${a.file} \u2014 ${a.why}`));return t.join(`
601
- `)}async function My(e){let t=(l)=>console.error(l),n=new Cs(Aa(process.cwd()));n.watch((l,u)=>{let d=As(u);if(d)t(d)});let r;try{r=await n.start(await ks(e))}catch(l){return t(`Error: ${l instanceof Error?l.message:String(l)}`),1}let s=Is(()=>{t(`
602
- Cancelling: stopping agents and removing the worktree (Ctrl+C again to exit now)...`),n.cancel(r.id)}),o=await r.done;s();let a=Et(r.id);if(o.status==="cancelled")return t(`Run saved as cancelled: ${a}`),130;if(o.status==="failed")return t(`Run saved as failed: ${a}`),1;if(t(`Run saved: ${a} (diffloupe runs show ${r.id})
603
- `),e.kind==="diff")return process.stdout.write(`${Oy(o.run)}
604
- `),0;if(!o.reviewed)return 0;let c=e.markdown?await _y(a):void 0;return process.stdout.write(c??`${Py(o.run)}
605
- `),0}function Is(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 CC from"os";import{existsSync as IC,readFileSync as OC}from"fs";var PC=new Set(["true","false","none",":","0","1"]);function MC(){if(process.platform!=="linux")return!1;if(CC.release().toLowerCase().includes("microsoft"))return!0;try{let e=OC("/proc/version","utf8").toLowerCase();return e.includes("microsoft")||e.includes("wsl")}catch{return!1}}function TC(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("/mnt/")||e.toLowerCase().endsWith(".exe")}function NC(e,t){let n=t.browser?.trim()&&!PC.has(t.browser.trim().toLowerCase())?t.browser.trim():void 0;if(t.wsl){if(!n)return["cmd.exe","/c","start","",e];if(TC(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 Ty(e){let t=MC(),n=NC(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"&&IC("/mnt/c")?{cwd:"/mnt/c"}:{}}).exited===0}catch{return!1}}var od=(e,t,n)=>(r,s)=>{let o=-1;return a(0);async function a(c){if(c<=o)throw Error("next() called multiple times");o=c;let l,u=!1,d;if(e[c])d=e[c][0][0],r.req.routeIndex=c;else d=c===e.length&&s||void 0;if(d)try{l=await d(r,()=>a(c+1))}catch(f){if(f instanceof Error&&t)r.error=f,l=await t(f,r),u=!0;else throw f}else if(r.finalized===!1&&n)l=await n(r);if(l&&(r.finalized===!1||u))r.res=l;return r}};var Ny=Symbol();var Dy=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,o=(e instanceof Oa?e.raw.headers:e.headers).get("Content-Type");if(o?.startsWith("multipart/form-data")||o?.startsWith("application/x-www-form-urlencoded"))return DC(e,{all:n,dot:r});return{}};async function DC(e,t){let n=await e.formData();if(n)return FC(n,t);return{}}function FC(e,t){let n=Object.create(null);if(e.forEach((r,s)=>{if(!(t.all||s.endsWith("[]")))n[s]=r;else LC(n,s,r)}),t.dot)Object.entries(n).forEach(([r,s])=>{if(r.includes("."))jC(n,r,s),delete n[r]});return n}var LC=(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]},jC=(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 cd=(e)=>{let t=e.split("/");if(t[0]==="")t.shift();return t},Fy=(e)=>{let{groups:t,path:n}=UC(e),r=cd(n);return BC(r,t)},UC=(e)=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(n,r)=>{let s=`@${r}`;return t.push([s,n]),s}),{groups:t,path:e}},BC=(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},Pa={},Ly=(e,t)=>{if(e==="*")return"*";let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;if(!Pa[r])if(n[2])Pa[r]=t&&t[0]!==":"&&t[0]!=="*"?[r,n[1],new RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],new RegExp(`^${n[2]}$`)];else Pa[r]=[e,n[1],!0];return Pa[r]}return null},Ma=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,(n)=>{try{return t(n)}catch{return n}})}},qC=(e)=>Ma(e,decodeURI),ld=(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 qC(a.includes("%25")?a.replace(/%25/g,"%2525"):a)}else if(s===63)break}return t.slice(n,r)};var jy=(e)=>{let t=ld(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},lr=(e,t,...n)=>{if(n.length)t=lr(t,...n);return`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`},Ta=(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)},ad=(e)=>{if(!/[%+]/.test(e))return e;if(e.indexOf("+")!==-1)e=e.replace(/\+/g," ");return e.indexOf("%")!==-1?Ma(e,ud):e},Uy=(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 c=e.charCodeAt(a+t.length+1);if(c===61){let l=a+t.length+2,u=e.indexOf("&",l);return ad(e.slice(l,u===-1?void 0:u))}else if(c==38||isNaN(c))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),c=e.indexOf("=",o);if(c>a&&a!==-1)c=-1;let l=e.slice(o+1,c===-1?a===-1?void 0:a:c);if(r)l=ad(l);if(o=a,l==="")continue;let u;if(c===-1)u="";else if(u=e.slice(c+1,a===-1?void 0:a),r)u=ad(u);if(n){if(!(s[l]&&Array.isArray(s[l])))s[l]=[];s[l].push(u)}else s[l]??=u}return t?s[t]:s},By=Uy,qy=(e,t)=>Uy(e,t,!0),ud=decodeURIComponent;var Hy=(e)=>Ma(e,ud),Oa=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)?Hy(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)?Hy(r):r}return e}#i(e){return this.#e[1]?this.#e[1][e]:e}query(e){return By(this.url,e)}queries(e){return qy(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 Dy(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[Ny](){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 Na={Stringify:1,BeforeStream:2,Stream:3},HC=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n};var Os=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((c)=>c({phase:t,buffer:s,context:r}))).then((c)=>Promise.all(c.filter(Boolean).map((l)=>Os(l,t,!1,r,s))).then(()=>s[0]));if(n)return HC(await a,o);else return a};var Ky="text/plain; charset=UTF-8",dd=(e,t)=>({"Content-Type":e,...t}),Wy=class{#t;#e;env={};#n;finalized=!1;error;#s;#i;#r;#u;#c;#l;#a;#d;#f;constructor(e,t){if(this.#t=e,t)this.#i=t.executionCtx,this.env=t.env,this.#l=t.notFoundHandler,this.#f=t.path,this.#d=t.matchResult}get req(){return this.#e??=new Oa(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.#c??=(t)=>this.html(t),this.#c(...e));setLayout=(e)=>this.#u=e;getLayout=()=>this.#u;setRenderer=(e)=>{this.#c=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,c]of o)if(a.toLowerCase()==="set-cookie")r.append(a,c);else r.set(a,c)}if(n)for(let[o,a]of Object.entries(n))if(typeof a==="string")r.set(o,a);else{r.delete(o);for(let c of a)r.append(o,c)}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,dd(Ky,n));json=(e,t,n)=>this.#o(JSON.stringify(e),t,dd("application/json",n));html=(e,t,n)=>{let r=(s)=>this.#o(s,t,dd("text/html; charset=UTF-8",n));return typeof e==="object"?Os(e,Na.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.#l??=()=>new Response,this.#l(this))};var Pe="ALL",Vy="all",Gy=["get","post","put","delete","options","patch"],Da="Can not add a route since the matcher is already built.",Fa=class extends Error{};var zy="__COMPOSED_HANDLER";var KC=(e)=>e.text("404 Not Found",404),Jy=(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)},Xy=class e{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...Gy,Vy].forEach((o)=>{this[o]=(a,...c)=>{if(typeof a==="string")this.#t=a;else this.#s(o,this.#t,a);return c.forEach((l)=>{this.#s(o,this.#t,l)}),this}}),this.on=(o,a,...c)=>{for(let l of[a].flat()){this.#t=l;for(let u of[o].flat())c.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((c)=>{this.#s(Pe,this.#t,c)}),this};let{strict:r,...s}=t;Object.assign(this,s),this.getPath=r??!0?t.getPath??ld:jy}#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=KC;errorHandler=Jy;route(t,n){let r=this.basePath(t);return n.routes.map((s)=>{let o;if(n.errorHandler===Jy)o=s.handler;else o=async(a,c)=>(await od([],n.errorHandler)(a,()=>s.handler(a,c))).res,o[zy]=s.handler;r.#s(s.method,s.path,o)}),this}basePath(t){let n=this.#e();return n._basePath=lr(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=(l)=>l;else s=r.replaceRequest;let a=o?(l)=>{let u=o(l);return Array.isArray(u)?u:[u]}:(l)=>{let u=void 0;try{u=l.executionCtx}catch{}return[l.env,u]};s||=(()=>{let l=lr(this._basePath,t),u=l==="/"?0:l.length;return(d)=>{let f=new URL(d.url);return f.pathname=f.pathname.slice(u)||"/",new Request(f,d)}})();let c=async(l,u)=>{let d=await n(s(l.req.raw),...a(l));if(d)return d;await u()};return this.#s(Pe,lr(t,"*"),c),this}#s(t,n,r){t=t.toUpperCase(),n=lr(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),c=new Wy(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](c,async()=>{c.res=await this.#n(c)})}catch(d){return this.#i(d,c)}return u instanceof Promise?u.then((d)=>d||(c.finalized?c.res:this.#n(c))).catch((d)=>this.#i(d,c)):u??this.#n(c)}let l=od(a[0],this.errorHandler,this.#n);return(async()=>{try{let u=await l(c);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,c)}})()}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${lr("/",t)}`,n),r,s)};fire=()=>{addEventListener("fetch",(t)=>{t.respondWith(this.#r(t.request,t,void 0,t.request.method))})}};var La=[];function fd(e,t){let n=this.buildAllMatchers(),r=(s,o)=>{let a=n[s]||n[Pe],c=a[2][o];if(c)return c;let l=o.match(a[0]);if(!l)return[[],La];let u=l.indexOf("",1);return[a[1][u],l]};return this.match=r,r(e,t)}var ja="[^/]+",Ps=".*",Ms="(?:|/.*)",ur=Symbol(),WC=new Set(".\\+*[^]$()");function VC(e,t){if(e.length===1)return t.length===1?e<t?-1:1:-1;if(t.length===1)return 1;if(e===Ps||e===Ms)return 1;else if(t===Ps||t===Ms)return-1;if(e===ja)return 1;else if(t===ja)return-1;return e.length===t.length?e<t?-1:1:t.length-e.length}var Yy=class e{#t;#e;#n=Object.create(null);insert(t,n,r,s,o){if(t.length===0){if(this.#t!==void 0)throw ur;if(o)return;this.#t=n;return}let[a,...c]=t,l=a==="*"?c.length===0?["","",Ps]:["","",ja]:a==="/*"?["","",Ms]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),u;if(l){let d=l[1],f=l[2]||ja;if(d&&l[2]){if(f===".*")throw ur;if(f=f.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(f))throw ur}if(u=this.#n[f],!u){if(Object.keys(this.#n).some((p)=>p!==Ps&&p!==Ms))throw ur;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!==Ps&&d!==Ms))throw ur;if(o)return;u=this.#n[a]=new e}u.insert(c,n,r,s,o)}buildRegExpStr(){let n=Object.keys(this.#n).sort(VC).map((r)=>{let s=this.#n[r];return(typeof s.#e==="number"?`(${r})@${s.#e}`:WC.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 Zy=class{#t={varIndex:0};#e=new Yy;insert(e,t,n){let r=[],s=[];for(let a=0;;){let c=!1;if(e=e.replace(/\{[^}]+\}/g,(l)=>{let u=`@\\${a}`;return s[a]=[u,l],a++,c=!0,u}),!c)break}let o=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let a=s.length-1;a>=0;a--){let[c]=s[a];for(let l=o.length-1;l>=0;l--)if(o[l].indexOf(c)!==-1){o[l]=o[l].replace(c,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 GC=[/^$/,[],Object.create(null)],Qy=Object.create(null);function eb(e){return Qy[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(t,n)=>n?`\\${n}`:"(?:|/.*)")}$`)}function zC(){Qy=Object.create(null)}function JC(e){let t=new Zy,n=[];if(e.length===0)return GC;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,y]=r[u];if(p)s[h]=[y.map(([b])=>[b,Object.create(null)]),La];else d++;let v;try{v=t.insert(h,d,p)}catch(b){throw b===ur?new Fa(h):b}if(p)continue;n[d]=y.map(([b,g])=>{let R=Object.create(null);g-=1;for(;g>=0;g--){let[N,I]=v[g];R[N]=I}return[b,R]})}let[o,a,c]=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 y=Object.keys(h);for(let v=0,b=y.length;v<b;v++)h[y[v]]=c[h[y[v]]]}let l=[];for(let u in a)l[u]=n[a[u]];return[o,l,s]}function li(e,t){if(!e)return;for(let n of Object.keys(e).sort((r,s)=>s.length-r.length))if(eb(n).test(t))return[...e[n]];return}var Ua=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[Pe]:Object.create(null)},this.#e={[Pe]:Object.create(null)}}add(e,t,n){let r=this.#t,s=this.#e;if(!r||!s)throw Error(Da);if(!r[e])[r,s].forEach((c)=>{c[e]=Object.create(null),Object.keys(c[Pe]).forEach((l)=>{c[e][l]=[...c[Pe][l]]})});if(t==="/*")t="*";let o=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let c=eb(t);if(e===Pe)Object.keys(r).forEach((l)=>{r[l][t]||=li(r[l],t)||li(r[Pe],t)||[]});else r[e][t]||=li(r[e],t)||li(r[Pe],t)||[];Object.keys(r).forEach((l)=>{if(e===Pe||e===l)Object.keys(r[l]).forEach((u)=>{c.test(u)&&r[l][u].push([n,o])})}),Object.keys(s).forEach((l)=>{if(e===Pe||e===l)Object.keys(s[l]).forEach((u)=>c.test(u)&&s[l][u].push([n,o]))});return}let a=Ta(t)||[t];for(let c=0,l=a.length;c<l;c++){let u=a[c];Object.keys(s).forEach((d)=>{if(e===Pe||e===d)s[d][u]||=[...li(r[d],u)||li(r[Pe],u)||[]],s[d][u].push([n,o-l+c+1])})}}match=fd;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,zC(),e}#n(e){let t=[],n=e===Pe;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!==Pe)t.push(...Object.keys(r[Pe]).map((o)=>[o,r[Pe][o]]))}),!n)return null;else return JC(t)}};var pd=class{name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,n){if(!this.#e)throw Error(Da);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 c=n[o];try{for(let l=0,u=r.length;l<u;l++)c.add(...r[l]);a=c.match(e,t)}catch(l){if(l instanceof Fa)continue;throw l}this.match=c.match.bind(c),this.#t=[c],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 Ts=Object.create(null),tb=class e{#t;#e;#n;#s=0;#i=Ts;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=Fy(n),a=[];for(let c=0,l=o.length;c<l;c++){let u=o[c],d=o[c+1],f=Ly(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((c,l,u)=>u.indexOf(c)===l),score:this.#s}}),s}#r(t,n,r,s){let o=[];for(let a=0,c=t.#t.length;a<c;a++){let l=t.#t[a],u=l[n]||l[Pe],d={};if(u!==void 0){if(u.params=Object.create(null),o.push(u),r!==Ts||s&&s!==Ts)for(let f=0,p=u.possibleKeys.length;f<p;f++){let h=u.possibleKeys[f],y=d[u.score];u.params[h]=s?.[h]&&!y?s[h]:r[h]??s?.[h],d[u.score]=!0}}}return o}search(t,n){let r=[];this.#i=Ts;let o=[this],a=cd(n),c=[];for(let l=0,u=a.length;l<u;l++){let d=a[l],f=l===u-1,p=[];for(let h=0,y=o.length;h<y;h++){let v=o[h],b=v.#e[d];if(b)if(b.#i=v.#i,f){if(b.#e["*"])r.push(...this.#r(b.#e["*"],t,v.#i));r.push(...this.#r(b,t,v.#i))}else p.push(b);for(let g=0,R=v.#n.length;g<R;g++){let N=v.#n[g],I=v.#i===Ts?{}:{...v.#i};if(N==="*"){let j=v.#e["*"];if(j)r.push(...this.#r(j,t,v.#i)),j.#i=I,p.push(j);continue}let[_,S,O]=N;if(!d&&!(O instanceof RegExp))continue;let P=v.#e[_],C=a.slice(l).join("/");if(O instanceof RegExp){let j=O.exec(C);if(j){if(I[S]=j[0],r.push(...this.#r(P,t,v.#i,I)),Object.keys(P.#e).length){P.#i=I;let H=j[0].match(/\//)?.length??0;(c[H]||=[]).push(P)}continue}}if(O===!0||O.test(d))if(I[S]=d,f){if(r.push(...this.#r(P,t,I,v.#i)),P.#e["*"])r.push(...this.#r(P.#e["*"],t,I,v.#i))}else P.#i=I,p.push(P)}}o=p.concat(c.shift()??[])}if(r.length>1)r.sort((l,u)=>l.score-u.score);return[r.map(({handler:l,params:u})=>[l,u])]}};var hd=class{name="TrieRouter";#t;constructor(){this.#t=new tb}add(e,t,n){let r=Ta(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 dr=class extends Xy{constructor(e={}){super(e);this.router=e.router??new pd({routers:[new Ua,new hd]})}};import{readdir as nb,rm as rb,stat as XC}from"fs/promises";import YC from"os";import ib from"path";async function ob(){if(!Bun.which("gh"))return{available:!1,authed:!1,message:"gh is not installed"};try{return(await te("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 ab(){let e=Bun.which("opencode");if(!e)return{path:null,version:null};try{let t=await te(e,["--version"],{allowFail:!0});return{path:e,version:t.code===0?t.stdout.trim()||null:null}}catch{return{path:e,version:null}}}var ZC=86400000,sb="code-review-subject-";function QC(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}async function cb(e,t){let n=YC.tmpdir(),r=[];try{r=await nb(n)}catch{}for(let o of r){if(!o.startsWith(sb))continue;let a=Number(o.slice(sb.length).split("-")[1]);if(!Number.isInteger(a)||a<=0||QC(a))continue;let c=ib.join(n,o);await rb(c,{recursive:!0,force:!0}).catch(()=>{}),t(`removed stale review worktree ${c}`)}if(e)await te("git",["-C",e,"worktree","prune"],{allowFail:!0}).catch(()=>{});let s=(await Ht()).filter((o)=>o.status==="running").map((o)=>o.id);for(let o of ya()){let a;try{a=await nb(o)}catch{continue}for(let c of a){let l=ib.join(o,c);try{if(!(s.some((d)=>c.startsWith(`${d}-`))&&Date.now()-(await XC(l)).mtimeMs<ZC))await rb(l,{recursive:!0,force:!0})}catch{}}}}import ub from"os";function lb(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 eI="DIFFLOUPE_ALLOWED_HOSTS",db=["localhost","127.0.0.1","::1"];function md(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 Ns(e){let t=e.replace(/^\[|\]$/g,"").toLowerCase();return db.includes(t)||t.startsWith("127.")||t.endsWith(".localhost")}function gd(e,t=process.env[eI]){let n=new Set(db);for(let r of(t??"").split(",")){let s=md(r);if(s)n.add(s)}if(!Ns(e)){let r=md(e.includes(":")&&!e.startsWith("[")?`[${e}]`:e);if(r)n.add(r);n.add(ub.hostname().toLowerCase());for(let s of Object.values(ub.networkInterfaces()))for(let o of s??[])n.add(o.address.toLowerCase())}return n}function fb(e){return async(t,n)=>{let r=md(t.req.header("host"));if(r===null||r!==void 0&&!e.has(r)&&!Ns(r))return t.json({error:"host not allowed"},403);await n()}}function pb(){return async(e,t)=>{let n=e.req.method;if(n!=="GET"&&n!=="HEAD"&&n!=="OPTIONS"){if(!lb(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 hb(e){let t=new dr;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 dI}from"fs/promises";import fI from"path";var _d=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+`
606
- `),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 Ba=()=>{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 Ba=()=>t,t};var mb=class extends _d{constructor(e,t){super(e,t)}async writeSSE(e){let n=(await Os(e.data,Na.Stringify,!1,{})).split(/\r\n|\r|\n/).map((s)=>`data: ${s}`).join(`
576
+ `)}function sC(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 qw(e,t){let n=[sC(e,t),e.preexisting&&"pre-existing",e.carriedFrom&&`open since ${e.carriedFrom}`].filter(Boolean);return n.length?` (${n.join(", ")})`:""}function hd(e,t){return` [${e.severity}] ${e.title}${qw(e,t)}
577
+ ${gd(e.anchor)} id ${e.id}`}function Hw(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?`
578
+ ${t} ${n.note}`:""}`)]}function Da(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 Kw(e,t){let n=[];if(n.push(`${e.id} ${e.status}`),n.push(`${Zn(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=Da(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((l)=>[l.path,l]));n.push(...Vw(e,t));let o=e.findings.filter((l)=>!s.has(l.file));if(o.length){n.push("",`Findings on files outside the diff (${o.length})`);for(let l of o)n.push(hd(l,t))}if(e.overCapFindings.length){n.push("",`Over the posting cap (${e.overCapFindings.length})`);for(let l of e.overCapFindings)n.push(hd(l,t))}if(n.push(...Hw(e," ")),e.stops.length){n.push("",`Walkthrough stops (${e.stops.length})`);for(let l of e.stops){n.push(` ${l.id} ${l.title}${l.importance==="normal"?"":` [${l.importance}]`}`);for(let u of l.locations)n.push(` ${gd(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(Mw(e)==="diff")return n.push("",`${e.files.length} files${Ww(e)}, ${(e.meta.wallMs/1000).toFixed(1)}s`),n.join(`
579
+ `);n.push("",`${e.findings.length} findings, ${e.files.length} files, $${e.meta.costUsd.toFixed(2)}, ${Math.round(e.meta.wallMs/1000)}s`,`anchors: ${Jo(e)}`);let a=Os(Is(e));if(a)n.push(`tokens: ${a}`);let c=t?oC(e,t):void 0;if(c)n.push(`triage: ${c}`);return n.join(`
580
+ `)}function oC(e,t){let n=new Set([...e.findings,...e.overCapFindings].map((l)=>l.id)),r=Object.entries(t.findingStatus).filter(([l])=>n.has(l)),s=r.filter(([,l])=>l==="accepted").length,o=r.filter(([,l])=>l==="dismissed").length,a=e.files.filter((l)=>(l.path in t.reviewedFiles)).length,c=[s&&`${s} accepted`,o&&`${o} dismissed`,a&&`${a} of ${e.files.length} files reviewed`].filter(Boolean);return c.length?c.join(", "):void 0}function Ww(e){return e.meta.costUsd?`, $${e.meta.costUsd.toFixed(2)}`:""}function Vw(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((l)=>l.parentId===o.id);if(!a||!o.parentId&&o.files.length===0){let l=a&&o.stopIds.length?` (stops ${o.stopIds.join(", ")}; files sit in other groups)`:"";n.push("",`${o.critical?"! ":""}${o.title}${l}`);continue}let c=o.parentId?" ":"";n.push(`${o.parentId?"":`
581
+ `}${c}${o.critical?"! ":""}${o.title}`);for(let l of o.files){let u=s.get(l),d=u?` ${u.status} +${u.additions} -${u.deletions}${u.isBinary?" binary":""}`:"";n.push(`${c} ${l}${d}`);for(let f of o.findingIds){let p=r.get(f);if(p?.file===l)n.push(hd(p,t))}}}return n}function Gw(e){let t=[];if(t.push(`${Zn(e.target)} ${e.base.slice(0,12)}..${e.head.slice(0,12)}`),e.intent.inferred)t.push("",`What it does: ${md(e.intent.inferred,400)}`);if(t.push(...Vw(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}${Ww(e)}`),t.join(`
582
+ `)}var Uw=["blocker","should-fix","question","nice-to-have"];function md(e,t=200){let n=e.trim().split(/(?<=[.!?])\s+/)[0]??"";return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function zw(e){let t=[];t.push(`${Zn(e.target)} ${e.base.slice(0,12)}..${e.head.slice(0,12)}`);let n=Da(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: ${md(s.inferred,400)}`);if(e.overview.focus)t.push("",`Focus: ${e.overview.focus}`);let o=[...e.findings].sort((a,c)=>Number(a.preexisting??!1)-Number(c.preexisting??!1)||Uw.indexOf(a.severity)-Uw.indexOf(c.severity));t.push("",o.length?`Findings (${o.length})`:"No findings.");for(let a of o){t.push(` [${a.severity}] ${a.title}${qw(a)}`,` ${gd(a.anchor)} id ${a.id}`);let c=md(a.impact??a.explanation);if(c&&c!==a.title)t.push(` ${c}`)}if(e.overCapFindings.length)t.push(` \u2026and ${e.overCapFindings.length} more over the cap (runs show)`);if(t.push(...Hw(e," ")),e.overview.startHere.length)t.push("","Start here"),e.overview.startHere.forEach((a,c)=>t.push(` ${c+1}. ${a.file} \u2014 ${a.why}`));return t.join(`
583
+ `)}var Cn=["blocker","should-fix","nice-to-have","question"],aC={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 cC(e){let t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return n>0?aC[t.slice(n+1).toLowerCase()]??"":""}function _d(e,t){return t&&t!==e?`${e}-${t}`:`${e}`}function Jw(e){let t=e.side==="deletions"?" (old)":"";if(e.kind==="file")return e.cited.line>0?`${e.file}:${_d(e.cited.line,e.cited.endLine)}`:e.file;if(e.kind==="nearby")return`${e.file}:${_d(e.cited.line,e.cited.endLine)}${t}`;return`${e.file}:${_d(e.line,e.endLine)}${t}`}function Xw(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 lC(e,t,n={}){let r=[`### [${e.severity}] ${e.title}${Xw(e,t)}`,`${xn(Jw(e.anchor))} \xB7 id ${xn(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.evidence.trim())r.push(`**Evidence:** ${e.evidence.trim()}`);if(e.suggestedCode){if(e.suggestion?.trim())r.push(`**Suggestion:** ${e.suggestion.trim()}`);r.push(ei(e.suggestedCode,cC(e.file)))}else if(e.suggestion?.trim())r.push(`**Suggestion:** ${e.suggestion.trim()}`);return r.join(`
584
+
585
+ `)}function wd(e){return[...e].sort((t,n)=>Cn.indexOf(t.severity)-Cn.indexOf(n.severity)||t.file.localeCompare(n.file)||t.anchor.line-n.anchor.line)}function uC(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=Cn.map((a)=>[a,e.filter((c)=>c.severity===a).length]).filter(([,a])=>a>0).map(([a,c])=>`${c} ${a}`),o=e.length;return`${o} finding${o===1?"":"s"}: ${s.join(", ")}.${r}`}function dC(e,t){return[`### [${e.severity}] ${e.title}${Xw(e,t)}`,`${xn(Jw(e.anchor))} \xB7 id ${xn(e.id)}`].join(`
586
+
587
+ `)}function Ps(e,t={}){let n=Da(e),r=[`# Review findings: ${Zn(e.target)}`,`Base ${xn(e.base.slice(0,12))}, head ${xn(e.head.slice(0,12))}${n?`. ${n}.`:""}`],{state:s}=t,o=(O)=>t.includeDismissed||s?.findingStatus[O.id]!=="dismissed",a=e.findings.filter(o),c=e.overCapFindings.filter(o),l=t.includeOverCap?c:[],u=a.filter((O)=>!O.preexisting),d=a.filter((O)=>O.preexisting),f=e.findings.length-a.length+e.overCapFindings.length-c.length;r.push(uC(u,d,c.length)+(f?` ${f} dismissed finding${f===1?"":"s"} left out.`:""));let p=[wd(u),wd(d),wd(l)],h=Math.min(t.shorten?.count??0,p.flat().length),_=new Set(h>0?p.flat().slice(-h):[]);if(h>0&&t.shorten)r.push(t.shorten.note);let v=(O)=>_.has(O)?dC(O,s):lC(O,s,t),[y=[],b=[],S=[]]=p;for(let O of y)r.push(v(O));if(b.length){r.push("## Pre-existing (not introduced by this change)");for(let O of b)r.push(v(O))}if(S.length){r.push(`## Over the posting cap (${S.length})`);for(let O of S)r.push(v(O))}return`${r.join(`
588
+
589
+ `)}
590
+ `}import bi from"path";wt();zi();import{spawn as fC}from"child_process";import{posix as pC}from"path";function Ms(e,t,n,r){return new Promise((s,o)=>{let a=fC("git",["-C",e,...t],{stdio:[n===void 0?"ignore":"pipe","pipe","pipe"],...r?{env:{...process.env,...r}}:{}}),c=[],l=[];if(a.stdout?.on("data",(u)=>c.push(u)),a.stderr?.on("data",(u)=>l.push(u)),a.on("error",o),a.on("close",(u)=>{if(u===0)s(Buffer.concat(c));else o(Error(`git ${t.join(" ")} exited ${u}
591
+ ${Buffer.concat(l).toString("utf8").slice(0,2000)}`))}),n!==void 0)a.stdin?.on("error",()=>{}),a.stdin?.end(n)})}async function hC(e,t){let n=(await Ms(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,c]=s.slice(0,o).split(" ");if(a==="blob"&&c)r.set(s.slice(o+1),c)}return r}async function mC(e,t){if(t.length===0)return;let n=(await Ms(e,["config","--get","extensions.partialClone"]).catch(()=>Buffer.alloc(0))).toString("utf8").trim();if(!n)return;let s=(await Ms(e,["cat-file","--batch-check"],`${t.join(`
592
+ `)}
593
+ `,{GIT_NO_LAZY_FETCH:"1"})).toString("utf8").split(`
594
+ `).flatMap((o)=>o.endsWith(" missing")?[o.slice(0,o.indexOf(" "))]:[]);if(s.length===0)return;await Ms(e,["-c","fetch.negotiationAlgorithm=noop","fetch","-q","--no-tags","--no-write-fetch-head","--recurse-submodules=no","--filter=blob:none","--stdin",n],`${s.join(`
595
+ `)}
596
+ `)}async function gC(e,t,n){let r=n.filter((c)=>!c.includes(`
597
+ `)),s=new Map;if(r.length===0)return s;let o=await Ms(e,["cat-file","--batch"],r.map((c)=>`${t}:${c}
598
+ `).join("")),a=0;for(let c of r){let l=o.indexOf(10,a);if(l<0)break;let u=o.subarray(a,l).toString("utf8");if(a=l+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(c,o.subarray(a,a+d).toString("utf8"));a+=d+1}return s}var _C=/^(?:(?:tsconfig|jsconfig).*\.json|package\.json)$/;async function Yw(e,t,n){let r=await hC(e,t),s=new Set(r.keys()),o=[...s].filter((l)=>_C.test(pC.basename(l))),a=[...new Set([...n.filter((l)=>s.has(l)),...o])];await mC(e,a.map((l)=>r.get(l)??"").filter(Boolean));let c=await gC(e,t,a);return{paths:s,read:(l)=>c.get(l)}}Uo();async function Zw(e){if(e.config)So(e.config);let{signal:t}=e;if(t?.aborted)throw new Lt;let n=()=>void Xr();t?.addEventListener("abort",n,{once:!0}),qr({subject:e.repo,repoName:e.target.slug??bi.basename(e.repo),...t?{signal:t}:{}});try{return await wC(e)}finally{t?.removeEventListener("abort",n),await Xr(),Ro(),qo()}}async function wC(e){let t=(ie)=>e.onProgress?.(ie),n=()=>{if(e.signal?.aborted)throw new Lt},r=Date.now(),{base:s,head:o,pr:a,slug:c}=e.target,l=`${s}..${o}`;t({type:"stage",stage:"grouping"});let u=(await dt(["diff","--name-only",l])).trim().split(`
599
+ `).filter(Boolean),d={skip:[],docs:[],code:[]};for(let ie of u)d[Jr(ie)].push(ie);let f=(ie,Ne=null,Ye=0)=>({record:Ne,units:ie,byClass:d,costUsd:Ye,wallMs:Date.now()-r});if(!d.code.length)return t({type:"units",units:[],byClass:d}),f([]);let{wholeDiff:p,diffstat:h,diffU0:_,fileTokens:v,facts:y,links:b,grouping:S}=await To({base:s,head:o,files:d.code,source:(ie)=>Yw(e.repo,o,ie)}),O=zr(S.groups,(ie)=>v.get(ie)??0),I=S.groups.map((ie,Ne)=>({id:ie.id,title:O[Ne]??ie.id,files:ie.files,priority:Ne+1}));if(t({type:"units",units:I,byClass:d}),n(),!e.walkthrough)return f(I);t({type:"stage",stage:"walkthrough"}),await gn(gt),await gn(bi.join(we,"prompts")),await gn(bi.join(we,"logs")),await et(bi.join(we,".gitignore"),`*
600
+ `);let g=await Po(c,a,s,o,e.intent),R=`${e.tag}-walk`,P=bi.join(gt,`${R}.json`);await Gt(P);let{shown:M,sketched:C}=Do(I,v,Li),N=C.length?or(await dt(["diff",l,"--",...M]),s):p,H=Fo(_,y),q=zo({diffstat:h,diff:N,sketches:C.map((ie)=>No(H.get(ie)??{file:ie,added:0,removed:0,defines:[],touches:[]})),crossLinks:jo(I,b),intent:g,unitSummary:I.map((ie)=>{let Ne=Lo(ie.files,b);return`**${ie.title}** (${ie.id})
601
+ ${ie.files.map((Ye)=>` - ${Ye}`).join(`
602
+ `)}`+(Ne.length?`
603
+ Links: ${Ne.join("; ")}`:"")}).join(`
604
+
605
+ `),docsFiles:d.docs,registry:"",outFile:P});await et(bi.join(we,"prompts",`${R}.txt`),q);let K=await vn(q,{budget:Di,outFile:P,tag:R,model:wn,effort:zt,tools:"none"}).catch((ie)=>(n(),t({type:"log",message:` walkthrough failed: ${ie instanceof Error?ie.message:String(ie)}`}),{costUsd:0,payload:null}));n(),t({type:"cost",totalUsd:K.costUsd});let ge=K.payload??void 0;if(!ge)t({type:"log",message:" walkthrough returned no guide"});let $e=Date.now()-r;return f(I,ge?{walkthrough:ge,wallMs:$e,totalCostUsd:K.costUsd}:null,K.costUsd)}function ny(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 ry(e){return{type:"groups",groups:e.groups,files:e.files.map((t)=>({path:t.path,groupId:t.groupId,classification:t.classification}))}}import bC from"os";import qe from"path";import{appendFile as o2,mkdir as vC,readdir as Ts,readFile as vd,rename as xC,rm as bd,writeFile as xd}from"fs/promises";class vi extends Error{constructor(e){super(e);this.name="StateOpError"}}function xi(){return{reviewedFiles:{},findingStatus:{},comments:[]}}function sy(e){let t=typeof e==="object"&&e!==null&&Array.isArray(e.reviewedFiles);return Fw(t?{...e,reviewedFiles:{}}:e)}var yC=/^0+$/;function iy(e,t,n){let r=t.filter((s)=>!n.has(s));if(r.length>0)throw new vi(`unknown ${e}: ${r.join(", ")}`)}function oy(e,t,n){if(t.op==="reviewed"){let c=new Map(n.files.map((u)=>[u.path,u]));iy(t.paths.length===1?"file":"files",t.paths,new Set(c.keys()));let l={...e.reviewedFiles};for(let u of t.paths){let d=c.get(u);if(!t.value)delete l[u];else l[u]=d?.status==="removed"||!d?.blob||yC.test(d.blob)?"":d.blob}return{...e,reviewedFiles:l}}if(t.ids.length===0)throw new vi("no finding ids given");let r=new Set([...n.findings,...n.overCapFindings].map((c)=>c.id));if(iy(t.ids.length===1?"finding":"findings",t.ids,r),t.status==="dismissed"&&!t.reason)throw new vi("dismissing a finding needs a reason");let s={...e.findingStatus},o={...e.findingNotes};for(let c of t.ids){if(delete o[c],t.status==="open")delete s[c];else s[c]=t.status;if(t.status==="dismissed"&&t.reason)o[c]={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 nn(){return qe.join(process.env.XDG_DATA_HOME||qe.join(bC.homedir(),".local","share"),"diffloupe")}function Ns(){return qe.join(nn(),"runs")}function Qn(){return qe.join(nn(),"artifacts")}function Sd(e){let[t="",n=""]=e.toLowerCase().split("/");return qe.join(nn(),"repos",t,`${n}.git`)}function Xe(e){if(!e||e.includes("/")||e.includes("\\")||e.startsWith("."))throw Error(`invalid run id: ${e}`);return qe.join(Ns(),e)}async function ay(e){let t=Xe(e);return await vC(qe.join(t,"raw"),{recursive:!0}),await xd(qe.join(t,"state.json"),`${JSON.stringify(xi(),null,2)}
606
+ `),t}async function Si(e){await xd(qe.join(Xe(e.id),"run.json"),`${JSON.stringify(e,null,2)}
607
+ `)}class On 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 ht(e){let t=JSON.parse(await vd(qe.join(Xe(e),"run.json"),"utf8")),n=Tw(t);if(n instanceof ee.errors)throw new On(e,n.summary,t);return n}async function Rd(e){let t=await ht(e);if(jw(t))return t;try{return Lw(t,JSON.parse(await vd(qe.join(Xe(e),"raw","record.json"),"utf8")))}catch{return t}}class Fs 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 cy(e){let t;try{t=await vd(qe.join(Xe(e),"state.json"),"utf8")}catch(s){if(s.code==="ENOENT")return xi();throw s}let n;try{n=JSON.parse(t)}catch(s){throw new Fs(e,s instanceof Error?s.message:String(s))}let r=sy(n);if(r instanceof ee.errors)throw new Fs(e,r.summary);return r}async function Sr(e){try{return await cy(e)}catch{return xi()}}async function SC(e,t){let n=qe.join(Xe(e),"state.json"),r=`${n}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;try{await xd(r,`${JSON.stringify(t,null,2)}
608
+ `),await xC(r,n)}catch(s){throw await bd(r,{force:!0}),s}}var La=new Map;async function $d(e,t){let r=(La.get(e)??Promise.resolve()).catch(()=>{return}).then(async()=>{let[s,o]=await Promise.all([ht(e),cy(e)]),a=oy(o,t,s);return await SC(e,a),a});La.set(e,r);try{return await r}finally{if(La.get(e)===r)La.delete(e)}}function ly(e,t,n,r={}){return $d(e,{op:"finding",ids:t,status:n,reason:r.reason,note:r.note,at:new Date().toISOString()})}function RC(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 yd(e,t,n){let r=e(t);return r instanceof ee.errors?n:r}function uy(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:yd(Ia,t.status,"failed"),createdAt:typeof t.createdAt==="string"?t.createdAt:"",target:yd(Oa,t.target,{kind:"worktree"}),repo:yd(Pa,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 Wt(){let e;try{e=await Ts(Ns())}catch{return[]}let t=[];for(let n of e)try{let r=await ht(n);t.push({id:r.id,status:r.status,createdAt:r.createdAt,target:r.target,repo:r.repo,findingCounts:RC(r),costUsd:r.meta?.costUsd??0,...r.meta?.kind?{kind:r.meta.kind}:{}})}catch(r){if(r instanceof On)t.push(uy(r))}return t.sort((n,r)=>r.createdAt.localeCompare(n.createdAt))}function ja(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 dy(e,t,n){let r=ja(e,t);return(await Wt()).find((o)=>o.status==="complete"&&o.kind!=="diff"&&o.createdAt<n&&ja(o.repo,o.target)===r)?.id}function Ds(){return qe.join(nn(),"scratch")}function Ua(){let e=qe.join(Ds(),"oc","shared");return[qe.join(e,"data"),qe.join(e,"state")]}function $C(){let e=Qn();return[...["logs","prompts","raw","reviews","runs"].map((t)=>qe.join(e,t)),Ds(),...Ua()]}async function kC(e,t){try{if((await re("git",["-C",e,"show-ref","--verify","--quiet",t],{allowFail:!0})).code!==0)return!1;return await le("git",["-C",e,"update-ref","-d",t]),!0}catch{return!1}}async function Ls(e){let t=[],n=Xe(e),r;try{r=(await ht(e)).repo.root}catch(s){if(s instanceof On)r=uy(s).repo.root||void 0}for(let s of $C()){let o;try{o=await Ts(s)}catch{continue}for(let a of o)if(a.startsWith(`${e}-`)||a.startsWith(`${e}.`)){let c=qe.join(s,a);await bd(c,{recursive:!0,force:!0}),t.push(c)}}if(r){for(let s of[`refs/diffloupe/${e}`,`refs/diffloupe/${e}-base`])if(await kC(r,s))t.push(s)}try{await Ts(n),await bd(n,{recursive:!0,force:!0}),t.push(n)}catch{}return t}function fy(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 py(){let e=[];try{e=await Ts(Ns())}catch{}let t=(await Wt()).filter((o)=>o.status==="running").map((o)=>o.id),n=(o,a)=>a.some((c)=>o.startsWith(`${c}-`)||o.startsWith(`${c}.`)),r=[],s=async(o,a)=>{let c;try{c=await Ts(o)}catch{return}for(let l of c)if(!a(l))r.push(qe.join(o,l))};await s(Ds(),(o)=>!o.endsWith(".json")||n(o,e));for(let o of Ua())await s(o,(a)=>n(a,t));return r}import{readFile as BC}from"fs/promises";wt();import{copyFile as EC,mkdir as AC,rm as CC,stat as gy}from"fs/promises";import IC from"os";import Ri from"path";import{randomBytes as OC}from"crypto";function Ed(e,t){if(!t)return e;let n=e;for(let r=2;t(n);r++)n=`${e}-${r}`;return n}var PC=1048576;class _e extends Error{name="TargetError"}function er(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 c=t.match(/^(?:https?:\/\/)?(?:www\.)?github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)(?:[/?#].*)?$/);if(!c?.[1]||!c[2]||!c[3])throw new _e(`not a GitHub pull request URL: ${t}`);return{kind:"pr",pr:Number(c[3]),repo:`${c[1]}/${c[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 c=hy(a);if(c)return c}if(!o&&!t.startsWith("-")&&!/\s/.test(t))if(t.includes("..")){let c=hy(t);if(c)return c}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 hy(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 Ad(e,t,n,r=new Date){let s=(l)=>String(l).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 _y(e,t,n={}){let r=er(t),s=(I,g={})=>le("git",["-C",e,...I],g),o=async(I)=>{let g=await re("git",["-C",e,"rev-parse","--verify","--quiet",`${I}^{commit}`],{allowFail:!0});if(g.code!==0){let R=/^\d+$/.test(I)?` (for pull request ${I}, use #${I})`:"";throw new _e(`unknown revision "${I}": not a commit in ${e}${R}`)}return g.stdout.trim()},a=async(I,g)=>(await s(["merge-base",I,g])).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 l=await Bo(e),u,d,f,p=[],h=!1,_;if(r.kind==="commit"&&DC(t)&&await LC(e,r.rev)){if(_=await my(e).catch(()=>{return}),_){let I=await o(r.rev);if(await a(_,I)!==I)r={kind:"branch",branch:r.rev}}}switch(r.kind){case"pr":{if(r.repo&&!l.startsWith("local/")&&r.repo.toLowerCase()!==l.toLowerCase())throw new _e(`pull request is in ${r.repo} but ${e} is a clone of ${l}. Run from a clone of ${r.repo} or pass -C. diffloupe diff can show it without a clone.`);if(f=await xy(e,r.pr,r.repo??(l.startsWith("local/")?void 0:l)),d=f.headRefOid,await kd(e,d,[`refs/pull/${r.pr}/head`]),n.head)d=await NC(e,r.pr,d,n.head);await kd(e,f.baseRefOid,[f.baseRefName]),u=await a(f.baseRefOid,d);break}case"branch":{d=await o(r.branch),u=await a(_??await my(e),d);break}case"range":{let I=await o(r.from);d=await o(r.to),u=r.mergeBase?await a(I,d):I;break}case"commit":{d=await o(r.rev);let I=await re("git",["-C",e,"rev-parse","--verify","--quiet",`${d}^`],{allowFail:!0});if(I.code!==0)throw new _e(`${r.rev} is a root commit; use range: instead`);u=I.stdout.trim();break}case"staged":case"worktree":{let I=await o("HEAD"),g=r.kind==="staged"?await jC(e,I):await UC(e,I);d=g.commit,p=g.skipped,u=n.base?await a(await o(n.base),I):I,h=!0;break}}let v=l.split("/").pop()??Ri.basename(e),y=Ed(Ad(v,r,d,n.now),n.isTaken);if(h)await s(["update-ref",`refs/diffloupe/${y}`,d]);let b=await Cd(e,u,d),S=h?void 0:Number((await s(["rev-list","--count",`${u}..${d}`])).trim()),O={base:u,head:d,slug:l,...r.kind==="pr"?{pr:String(r.pr)}:{}};return{spec:r,target:O,tag:y,changes:b,...S!==void 0?{commits:S}:{},skippedUntracked:p,...f?{pullRequest:f}:{}}}async function wy(e,t,n,r,s={}){let o=await Promise.all([n,r].map((f)=>Ba(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 c=await Bo(e),l=c.split("/").pop()??Ri.basename(e),u=Ed(Ad(l,t,r,s.now),s.isTaken);if(t.kind==="staged"||t.kind==="worktree")await le("git",["-C",e,"update-ref",`refs/diffloupe/${u}`,r]);let d={base:n,head:r,slug:c,...t.kind==="pr"?{pr:String(t.pr)}:{}};return{spec:t,target:d,tag:u,changes:await Cd(e,n,r),skippedUntracked:[]}}var MC=/^(?!\.{1,2}$)[\w.-]+$/;function TC(e){let t=e.split("/");return t.length===2&&t.every((n)=>MC.test(n))}async function yy(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 Bo(e);return!r.startsWith("local/")&&r.toLowerCase()!==t.repo.toLowerCase()}async function by(e,t,n=`https://github.com/${t}.git`){if(!TC(t))throw new _e(`not a GitHub repository: ${t}`);let r=(...o)=>le("git",["-C",e,...o]);if(await gy(Ri.join(e,"HEAD")).catch(()=>null))return;await AC(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 vy(e,t,n={}){let r=await xy(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 FC(e,[a,s],[`refs/pull/${t.pr}/head`]);let c=t.repo.split("/").pop()??t.repo,l=Ed(Ad(c,t,s,n.now),n.isTaken);return await le("git",["-C",e,"update-ref",`refs/diffloupe/${l}`,s]),await le("git",["-C",e,"update-ref",`refs/diffloupe/${l}-base`,a]),{spec:t,target:{base:a,head:s,slug:t.repo,pr:String(t.pr)},tag:l,changes:await Cd(e,a,s),skippedUntracked:[],pullRequest:r}}async function FC(e,t,n){let r=async()=>{let c=await Promise.all(t.map((l)=>Ba(e,l)));return t.filter((l,u)=>!c[u])},s=(c)=>re("git",["-C",e,"fetch","-q","--depth=1","--filter=blob:none","--no-tags","origin",...c],{allowFail:!0}),o=await r();if(o.length===0)return;let a=await s(o);o=await r();for(let c of n){if(o.length===0)return;await s([c]),o=await r()}if(o.length)throw new _e(`could not fetch ${o.map((c)=>c.slice(0,12)).join(", ")} from GitHub: ${a.stderr.trim()||"not found"}`)}async function xy(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 Ba(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 kd(e,t,n){if(await Ba(e,t))return;for(let r of n)if(await re("git",["-C",e,"fetch","-q","origin",r],{allowFail:!0}),await Ba(e,t))return;throw new _e(`commit ${t} is not in this clone and could not be fetched from origin`)}async function NC(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 kd(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 DC(e){return!(e??"").trim().startsWith("commit:")}async function LC(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 my(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 Sy(e,t,n,r,s){let o=(await le("git",["-C",e,"rev-parse",`${n}^{tree}`])).trim();if(t===o)throw new _e("no changes to review");return(await le("git",["-C",e,"commit-tree",t,"-p",n,"-m",r],s?{env:s}:{})).trim()}async function jC(e,t){let n=(await le("git",["-C",e,"write-tree"])).trim();return{commit:await Sy(e,n,t,"diffloupe: staged changes"),skipped:[]}}async function UC(e,t){let n=(await le("git",["-C",e,"rev-parse","--show-toplevel"])).trim(),r=Ri.resolve(n,(await le("git",["-C",n,"rev-parse","--git-path","index"])).trim()),s=Ri.join(IC.tmpdir(),`diffloupe-index-${process.pid}-${OC(4).toString("hex")}`);try{await EC(r,s).catch(async()=>{await le("git",["-C",n,"read-tree",t],{env:{...process.env,GIT_INDEX_FILE:s}})});let o={...process.env,GIT_INDEX_FILE:s},a=(await le("git",["-C",n,"ls-files","--others","--exclude-standard","-z"])).split("\x00").filter(Boolean),c=[];for(let d of a){let f=await gy(Ri.join(n,d)).catch(()=>null);if(f&&f.isFile()&&f.size>PC)c.push(d)}let l=c.map((d)=>`:(exclude,literal)${d}`);await le("git",["-C",n,"add","-A","--",".",...l],{env:o});let u=(await le("git",["-C",n,"write-tree"],{env:o})).trim();return{commit:await Sy(n,u,t,"diffloupe: working tree",o),skipped:c}}finally{await CC(s,{force:!0})}}async function Cd(e,t,n){let r=await le("git",["-C",e,"diff","--numstat","--no-renames",t,n]),s={files:0,insertions:0,deletions:0};for(let o of r.split(`
609
+ `)){if(!o.trim())continue;let[a,c]=o.split("\t");s.files++,s.insertions+=Number(a)||0,s.deletions+=Number(c)||0}return s}var qC=ee({"+":"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[]"});function HC(e,t){let n=qC(e);if(n instanceof ee.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 qa(e){let t;try{t=await BC(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 HC(n,e)}function Ry(e){let t={};if(e.surfaces)t.surfaces={deploy:e.surfaces.deploy??ur.deploy,tooling:e.surfaces.tooling??ur.tooling};if(e.extraExcludes)t.extraExcludes=e.extraExcludes;return t}function $y(e){let{instructions:t}=e;return(Array.isArray(t)?t.join(`
610
+ `):t??"").trim()||void 0}var ky={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:["FIREWORKS_API_KEY"],opencode:["OPENCODE_API_KEY"]},Ey=new Set(["amazon-bedrock","google-vertex","google-vertex-anthropic","ollama","lmstudio","vllm"]);function js(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Ay(e,t){let n=t?.[e],r=js(n)&&Array.isArray(n.env)?n.env.filter((s)=>typeof s==="string"):[];return[...new Set([...r,...ky[e]??[]])]}function KC(e,t){let n=t?.[e];if(!js(n))return!1;for(let r of[n.settings,n.options])if(js(r)&&typeof r.apiKey==="string"&&r.apiKey)return!0;return!1}function Cy(e){for(let t of e.providers.keys()){if(Ey.has(t))continue;if(Ay(t,e.userProviders).some((n)=>e.env[n]))continue;if(e.apiKeys?.[t])continue;return!0}return!1}function WC(e,t,n){let r=t.map((o)=>go[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 Iy(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=Ay(n,e.userProviders),a=o.find((f)=>e.env[f]);if(a){s("env",a);continue}let c=e.apiKeys?.[n];if(c){let f=o[0];if(f)t.childEnv[f]=c;else t.imports.push({id:`cred_diffloupe_${n.replace(/[^\w-]/g,"_")}`,integrationID:n,label:"API key",active:!0,value:{type:"key",key:c}});s("config",`apiKeys.${n}`);continue}let l=(e.saved??[]).filter((f)=>f.integrationID===n),u=l.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=l.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(KC(n,e.userProviders)){s("providers",`providers.${n} in the OpenCode config`);continue}if(Ey.has(n)){s("ambient","credentials from the machine");continue}if(s("none",""),ky[n]||d)t.errors.push(WC(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 Oy(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)=>js(r)&&typeof r.id==="string"&&typeof r.integrationID==="string"&&js(r.value))}catch{return}}function Py(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}async function My(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=Py(n)&&Array.isArray(n.data)?n.data:void 0;if(!r)return;return r.filter((s)=>Py(s)&&typeof s.id==="string"&&typeof s.providerID==="string")}catch{return}}function Ty(e,t,n=on){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 c=a.find((f)=>f.id===o.id||f.modelID===o.id),l=(f)=>r.errors.push(`Model \`${o.model}\` is not available in OpenCode: ${f}. Set \`${go[s]}\` in ~/.config/diffloupe/config.json or pass --model ${s}=<provider/model>.`);if(!c){l(`provider \`${o.provider}\` has no model \`${o.id}\``);continue}let u=c.variants?.map((f)=>f.id)??[];if(o.variant&&!u.includes(o.variant)){l(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=c.cost??[];if(d.length&&d.every((f)=>!f.input&&!f.output))r.zeroCost.push(s)}return r}import{readFileSync as VC}from"fs";import Ny from"os";import Id from"path";function GC(e=process.env,t=Ny.homedir()){let n=e.XDG_CONFIG_HOME?e.XDG_CONFIG_HOME:Id.join(t,".config"),r=Id.join(n,"opencode");return["opencode.jsonc","opencode.json"].map((s)=>Id.join(r,s))}function zC(e){let t=Bun.JSONC;if(t)try{return t.parse(e)}catch{return}return al(e)}function Fy(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function JC(e,t){if(!Fy(e))return{};let n=t?{path:t}:{};if(typeof e.model==="string"&&e.model.trim())n.model=e.model.trim();if(Fy(e.providers))n.providers=e.providers;return n}function Dy(e=process.env,t=Ny.homedir()){for(let n of GC(e,t)){let r;try{r=VC(n,"utf8")}catch{continue}return JC(zC(r),n)}return{}}async function Ha(e){let t=e.env??process.env,n=e.openCodeUser??Dy(t),r=e.settings??{},s={env:t,...e.cli?{cli:e.cli}:{},settings:r,config:e.userConfig,...n.model?{openCodeModel:n.model}:{}},o=Qf(s),a={providers:ep(o,e.stages),env:t,...e.userConfig.apiKeys?{apiKeys:e.userConfig.apiKeys}:{},...n.providers?{userProviders:n.providers}:{}},c=Cy(a)?await(e.exportCredentials??(()=>Oy(t)))():void 0,l=Iy({...a,...c?{saved:c}:{}}),u=await(e.readCatalog??(()=>My()))();return{provider:Kc(s),models:o,openCodeUser:n,credentials:l,...u?{catalog:Ty(o,u,e.stages)}:{}}}function Ly(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 jy(e,t=on){let n={};for(let r of t)n[r]={model:e.models[r].model,source:e.models[r].source};return n}var Ga={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`)"},_b={review:"model",coordinator:"modelMerge",walkthrough:"modelWalk",intent:"modelIntent"};function CI(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 _b))throw new _e(`--model expects stage=model-id with stage one of ${Object.keys(_b).join(", ")}; got "${n}"`);t[s]=o}return t}async function Hs(e){let t=e.intent?.trim();if(!t&&e.intentFile)t=(await Va(e.intentFile,"utf8")).trim();let n=CI(e.model??[]);return{...e.kind==="diff"?{kind:"diff"}:{},...e.kind==="diff"&&e.walkthrough?{walkthrough:!0}:{},repo:tt.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.config?{settingsFile:tt.resolve(e.config)}:{},...e.full?{full:!0}:{},...e.github?{github:!0}:{},...e.head?{head:e.head}:{}}}function II(e,t={}){let n=er(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}: ${Ga[a]??""}`)].join(`
611
+ `))}function Hd(e){return e!==null&&/^2\./.test(e)}function OI(e){return/\d+\.\d+(?:\.\d+)?/.exec(e)?.[0]??null}async function PI(){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?OI(t.stdout):null;if(Hd(n))return;throw new _e(`DiffLoupe needs OpenCode 2.x, but the opencode on PATH (${e}) is ${n??"an unknown version"}.
612
+ Install: ${Ga.opencode}`)}async function yb(e,t,n,r={}){let s=e.kind??"review",o=s==="diff",a=o&&e.walkthrough===!0,c=e.fromRun,l=c?await ht(c).catch((ne)=>{throw new _e(`cannot start from run ${c}: ${ne instanceof Error?ne.message:String(ne)}`)}):void 0,u=l?UI(l.target):void 0;if(l?.repo.remote&&!o)throw new _e(`reviewing ${l.repo.slug??"this repository"} needs a local clone; run diffloupe review from a clone of it`);for(let ne of["github","head"])if(e[ne]&&(o||l||er(e.target).kind!=="pr"))throw new _e(`--${ne} 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 PI();let d=tt.resolve(e.repo??t),f=l?void 0:er(e.target),p=o&&f?.kind==="pr"&&f.repo&&await yy(d,f)?{...f,repo:f.repo}:void 0;if(p)await by(Sd(p.repo),p.repo);let h=l?l.repo.root:p?Sd(p.repo):d,_=p!==void 0||l?.repo.remote===!0,v=e.intent?.trim()||l?.intent.stated||void 0,y=await Tr(),b=e.settingsFile?await qa(tt.resolve(e.settingsFile)):{},S=o?a?["walkthrough"]:[]:on,O=S.length?await(r.resolveSetup??Ha)({cli:{...e.models?{models:e.models}:{},...e.effort?{effort:e.effort}:{}},settings:b,userConfig:y,stages:S}):void 0,I=O?[...O.credentials.errors,...O.catalog?.errors??[]]:[];if(I.length)throw new _e(I.join(`
613
+ `));let g={artifacts:Qn(),out:tt.join(nn(),"scratch"),...Ry(b),...O?Ly(O):{}},R=o?void 0:e.maxCostUsd??y.maxCostUsd,P=o?void 0:$y(b),M=l&&u?await wy(h,u,l.base,l.head,{isTaken:qd}):p?await vy(h,p,{isTaken:qd}):await _y(h,e.target,{...e.base?{base:e.base}:{},...e.head?{head:e.head}:{},isTaken:qd}),{target:C,changes:N,tag:H}=M,q=M.pullRequest,K=o?"Diff of":"Reviewing";n(q?`${K} ${C.slug}#${q.number}: ${q.title}`:`${K} ${C.slug} (${BI(M.spec)})`);let ge=M.commits===void 0?"":` (${M.commits} commit${M.commits===1?"":"s"})`;if(n(` ${C.base.slice(0,12)}..${C.head.slice(0,12)}${ge}`),n(` ${N.files} file(s) changed, +${N.insertions} -${N.deletions}`),n(` run ${H}`),O){for(let ne of S){let w=O.models[ne];n(` ${ne}: ${w.model} (${_o(w.source)})`)}for(let ne of O.credentials.warnings)n(` warning: ${ne}`)}if(R!==void 0)n(O?.catalog?.zeroCost.includes("review")?" cost limit not enforced: models report no cost":` cost limit $${R.toFixed(2)}`);if(M.skippedUntracked.length){n(` skipped ${M.skippedUntracked.length} untracked file(s) over 1 MB:`);for(let ne of M.skippedUntracked)n(` ${ne}`)}let $e=new Date().toISOString(),ie={root:h,...C.slug?{slug:C.slug}:{},..._?{remote:_}:{}},Ne=l?l.target:await qI(h,M),Ye=l?l.untrackedSkipped:M.skippedUntracked,Ae=await ay(H),B=await le("git",["-C",h,"diff","--no-color","--no-ext-diff","--full-index","-M",C.base,C.head]);await Rr(tt.join(Ae,"diff.patch"),B);let Te=e.full===!0,Pe=e.github===!0,je=o||Pe?void 0:await dy(ie,Ne,$e),Ce=je?await DI(h,je,C.head):void 0;if(Ce?.run.findings.length)n(` ${Ce.run.findings.length} finding(s) from prior run ${Ce.run.id}`);let be=o?void 0:Ce?await NI(Ce.run)+1:1;if(be!==void 0&&be>1){if(n(Te?` round ${be}, full review (--full)`:` round ${be}: reviewing what changed since ${Ce?.run.head.slice(0,12)??"the last review"} (--full to review everything)`),be>FI)n(` warning: this change has been reviewed ${be-1} times; later rounds mostly find smaller problems`)}let at=await LI(),T=O?jy(O,S):void 0;await Promise.resolve().then(() => Ud());let Z=gb({id:H,createdAt:$e,repo:ie,target:Ne,base:C.base,head:C.head,...v?{statedIntent:v}:{},patch:B,untrackedSkipped:Ye,coreSource:at,...je?{priorRunId:je}:{},...be!==void 0?{round:be}:{},...T?{models:T}:{},...o?{kind:s}:{}});return await Si(Z),{id:H,kind:s,walkthrough:a,dir:Ae,createdAt:$e,repo:h,target:C,reviewTarget:Ne,config:g,...R!==void 0?{maxCostUsd:R}:{},...v?{intent:v}:{},...P?{instructions:P}:{},patch:B,...je?{priorRunId:je}:{},...Ce?{previous:Ce}:{},...be!==void 0?{round:be}:{},full:Te,github:Pe,untrackedSkipped:Ye,coreSource:at,...T?{models:T}:{},pending:Z}}async function bb(e,t){let{id:n,dir:r}=e;await Promise.resolve().then(() => Ud());let a=e.pending,c=Promise.resolve(),l=(p)=>{if(p.type!=="units"){t.onProgress(p);return}a=mb(wb(e),p.units,p.byClass),t.onProgress(ry(a));let h=a;c=c.then(()=>Si(h).catch((_)=>{t.log(` could not save the grouped run: ${_ instanceof Error?_.message:String(_)}`)}))},u;try{u=e.kind==="diff"?await Zw({repo:e.repo,target:e.target,tag:n,config:e.config,walkthrough:e.walkthrough,signal:t.signal,...e.intent?{intent:e.intent}:{},onProgress:l}):await cm({repo:e.repo,target:e.target,tag:n,config:e.config,signal:t.signal,...e.maxCostUsd!==void 0?{maxCostUsd:e.maxCostUsd}:{},...e.intent?{intent:e.intent}:{},...e.instructions?{instructions:e.instructions}:{},...TI(e),onProgress:l})}catch(p){let h=t.signal.aborted;throw await c,await Si({...a,status:h?"cancelled":"failed",...h?{}:{error:p instanceof Error?p.message:String(p)}}),p}if(u.markdownPath){let p=e.config.artifacts??Qn();await Bd(tt.join(p,"runs",`${n}.json`),tt.join(r,"raw","record.json")),await Bd(u.markdownPath,tt.join(r,"raw","review.md")),await Bd(tt.join(p,"reviews",`${n}.payloads.json`),tt.join(r,"raw","payloads.json"))}else if(u.record)await Rr(tt.join(r,"raw","record.json"),`${JSON.stringify(u.record,null,2)}
614
+ `);await Rr(tt.join(r,"raw","units.json"),`${JSON.stringify(u.units,null,2)}
615
+ `),await Rr(tt.join(r,"raw","byClass.json"),`${JSON.stringify(u.byClass,null,2)}
616
+ `);let d;await c;try{d=jd({...wb(e),result:u,...e.previous?{previous:e.previous}:{},log:t.log})}catch(p){let h=`building run.json: ${p instanceof Error?p.message:String(p)}`;throw await Si({...a,status:"failed",error:h}),Error(h,{cause:p})}await Si(d);let f=e.kind==="diff"||u.record!==null;if(e.kind==="review")t.log(` anchors: ${Jo(d)}`);if(e.github&&e.kind==="review"&&f)await MI(r,d);return{run:d,reviewed:f}}async function MI(e,t){let n=Ps(t,{includeOverCap:!0,github:!0});await Rr(tt.join(e,"raw",hr),n);let r=t.findings.length+t.overCapFindings.length;if(r===0)return;let s=tt.join(e,"raw","payloads.json"),o;try{o=JSON.parse(await Va(s,"utf8"))}catch{return}let a=o.summary?.body?.body;if(typeof a!=="string"||!o.summary?.body)return;let c=t.target.kind==="pr"?Yi(t.target.number,t.head):void 0;function*l(){yield n;for(let p=1;p<=r;p++)yield Ps(t,{includeOverCap:!0,github:!0,shorten:{count:p,note:nm(p,c)}})}let u=rm(a,l(),{artifact:c});o.summary.body.body=u,await Rr(s,`${JSON.stringify(o,null,2)}
617
+ `);let d=tt.join(e,"raw","review.md"),f=await Va(d,"utf8").catch(()=>{return});if(f?.includes(a))await Rr(d,f.replace(a,()=>u))}function wb(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 TI(e){return{local:!e.github,...e.previous?{prior:Qw(e.previous.run)}:{},...e.previous&&!e.full?{priorHead:e.previous.run.head}:{}}}var FI=3;async function NI(e,t=ht){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 DI(e,t,n){try{let r=await ht(t),s=await Sr(t),o=Object.entries(s.findingStatus).filter(([,l])=>l==="dismissed").map(([l])=>l),a=new Map,c=[...new Set(r.findings.map((l)=>l.file))];if(r.head!==n&&c.length)try{let l=await le("git",["-C",e,"diff","-U0","--no-color","--no-ext-diff",r.head,n,"--",...c]);a=ey(l)}catch{a=void 0}return{run:r,dismissed:o,...a?{lineMap:a}:{}}}catch{return}}async function Bd(e,t){try{await AI(e,t)}catch{}}var Wa;async function LI(){if(Wa)return Wa;return Wa=await jI(import.meta.dir),Wa}async function jI(e,t=Dn){if(e.split(/[\\/]/).includes("node_modules"))return`diffloupe@${t}`;try{let n=(await le("git",["-C",e,"rev-parse","--short=12","HEAD"])).trim();return`diffloupe@${t}+${n}`}catch{return`diffloupe@${t}`}}var qd=(e)=>EI(Xe(e));function UI(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 er(`range:${e.spec}`);default:return{kind:e.kind}}}function BI(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 qI(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 le("git",["-C",e,"rev-parse","--abbrev-ref","HEAD"])).trim()||void 0}catch{}return{kind:n.kind,...s?{branch:s}:{}}}async function vb(e){try{return await Va(tt.join(e,"raw","review.md"),"utf8")}catch{return}}var Kd=fo.engines.bun.replace(/^>=\s*/,"");function xb(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 WI(e){return/\d+\.\d+(?:\.\d+)?/.exec(e)?.[0]??null}function Sb(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 za(e,t,n,r){if(!e.which(t))return{name:t,status:n,detail:`not found on PATH. Install: ${Ga[t]??t}`};let s=await e.exec(t,["--version"]),o=s&&s.code===0?WI(s.output):null,a=r?.(o)??{status:"ok"},c=[o??"version unknown",a.note].filter(Boolean).join(", ");return{name:t,status:a.status,detail:c}}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:xb(e.bunVersion,Kd)?"ok":"fail",detail:xb(e.bunVersion,Kd)?e.bunVersion:`${e.bunVersion}, needs ${Kd} or newer`}),t.push(await za(e,"git","fail")),t.push(await za(e,"opencode","fail",(a)=>Hd(a)?{status:"ok"}:{status:"fail",note:"needs OpenCode 2.x (https://opencode.ai/v2/docs/)"})),t.push(await za(e,"tilth","fail"));let n=await za(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 on){let c=r.models[a];t.push({name:`model: ${a}`,status:"ok",detail:`${c.model} (${_o(c.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,c)=>a+c,0);return t.push({name:"data dir",status:"ok",detail:`${nn()}: ${Sb(o)} (${Object.entries(s).map(([a,c])=>`${a} ${Sb(c)}`).join(", ")}). \`diffloupe runs prune\` removes old runs`}),t}async function Ja(e){let t=0,n;try{n=await HI(e,{withFileTypes:!0})}catch{return 0}for(let r of n){let s=Rb.join(e,r.name);if(r.isDirectory())t+=await Ja(s);else if(r.isFile())t+=await KI(s).then((o)=>o.size,()=>0)}return t}async function GI(e,t){try{let n=await re(e,t,{allowFail:!0,timeoutMs:20000});return{code:n.code,output:`${n.stdout}
618
+ ${n.stderr}`}}catch{return null}}function zI(e,t){return e.some((n)=>n.status==="fail"||t&&n.status==="warn")}var JI={ok:Ks.default.green("ok "),warn:Ks.default.yellow("warn"),fail:Ks.default.red("FAIL")};function $b(){return new Vt("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:GI,setup:async()=>{let n=e.config?await qa(Rb.resolve(e.config)):{};return Ha({settings:n,userConfig:await Tr()})},dataSizes:async()=>({runs:await Ja(Ns()),artifacts:await Ja(Qn()),scratch:await Ja(Ds())})});if(e.json)console.log(JSON.stringify(t,null,2));else for(let n of t)console.log(`${JI[n.status]} ${Ks.default.bold(n.name)}: ${n.detail}`);if(zI(t,e.strict===!0))process.exit(1)})}import XO from"path";var rn=Tc(mo(),1);function Ws(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.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 Qa from"path";import XI from"path";import{appendFileSync as YI}from"fs";import{readFile as ZI}from"fs/promises";function QI(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 Xa(e){return QI({prepare:(t,n)=>yb(t,e,n),execute:bb})}class Ya extends Error{activeRunId;constructor(e){super(e?`run ${e} is still running`:"a run is starting");this.activeRunId=e;this.name="RunBusyError"}}function kb(e){return XI.join(Xe(e),"events.jsonl")}async function Eb(e){let t;try{t=await ZI(kb(e),"utf8")}catch{return[]}let n=[];return t.split(`
619
+ `).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 Vs{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 Ya(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:c})=>(o({type:"done",status:"complete",findings:a.findings.length,carriedOver:a.findings.filter((l)=>l.carriedFrom).length,costUsd:a.meta.costUsd,wallMs:a.meta.wallMs,...c?{}:{noChanges:!0},...a.meta.kind==="diff"?{kind:"diff",files:a.files.length}:{}}),{status:"complete",run:a,reviewed:c}),(a)=>{if(r.signal.aborted||a instanceof Lt)return o({type:"cancelled"}),{status:"cancelled"};let c=a instanceof Error?a.message:String(a);return o({type:"error",message:c}),{status:"failed",error:c}}).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=ny(e.pending,t);let n={...t,seq:++e.seq,at:new Date().toISOString()};try{YI(kb(e.id),`${JSON.stringify(n)}
620
+ `)}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 eO,mkdir as Cb,writeFile as tO}from"fs/promises";import Za from"path";function Ib(e,t){let n={blocker:0,"should-fix":0,"nice-to-have":0,question:0};for(let s of e?.findings??[])n[s.severity]++;let r=e?.target.kind==="pr"?e.target.number:null;return{id:t.id,status:t.status,reviewed:t.status==="complete",skipReason:t.skipReason??null,pr:r,base:e?.base??null,head:e?.head??null,runDir:t.runDir,outDir:t.outDir??null,payloads:t.payloads??null,artifactName:r!==null&&e?Yi(r,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,bySeverity:n},round:t.round??e?.round??1,incremental:e?.meta.reviewScope==="incremental",version:Dn}}var Ab=[["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/${hr}`,hr],["run.json","run.json"]];async function Ob(e,t,n={}){await Cb(t,{recursive:!0});let r=Xe(e),s=`${e}.detail.md`,a=[...(n.payloads===!1?Ab.filter(([,l])=>l!=="payloads.json"):Ab).map(([l,u])=>[Za.join(r,l),u]),[Za.join(Qn(),"reviews",s),s]];return(await Promise.all(a.map(async([l,u])=>{try{return await eO(l,Za.join(t,u)),u}catch(d){if(d.code!=="ENOENT")throw d;return null}}))).filter((l)=>l!==null)}async function Pb(e,t){await Cb(e,{recursive:!0}),await tO(Za.join(e,"result.json"),`${JSON.stringify(t,null,2)}
621
+ `)}function Mb(e,t){let n=Cn.indexOf(t);return e.findings.some((r)=>Cn.indexOf(r.severity)<=n)}async function Tb(e){let t=(f)=>console.error(f),n=new Vs(Xa(process.cwd())),r=0;n.watch((f,p)=>{if(p.type==="budget")r=p.skippedSlices;let h=Ws(p);if(h)t(h)});let s;try{s=await n.start(await Hs(e))}catch(f){return t(`Error: ${f instanceof Error?f.message:String(f)}`),2}let o=Gs(()=>{t(`
622
+ Cancelling: stopping agents and removing the worktree (Ctrl+C again to exit now)...`),n.cancel(s.id)}),a=await s.done;o();let c=Xe(s.id),l=a.status==="complete"?a.run:await ht(s.id).catch(()=>null),u=a.status==="complete"?a.reviewed?"complete":"skipped":a.status,d=await nO(s.id,l,u,r,e);if(e.json)process.stdout.write(`${JSON.stringify(d,null,2)}
623
+ `);if(a.status==="cancelled")return t(`Run saved as cancelled: ${c}`),130;if(a.status==="failed")return t(`Run saved as failed: ${c}`),1;if(t(`Run saved: ${c} (diffloupe runs show ${s.id})
624
+ `),!e.json){if(e.kind==="diff")process.stdout.write(`${Gw(a.run)}
625
+ `);else if(a.reviewed){let f=e.markdown?await vb(c):void 0;process.stdout.write(f??`${zw(a.run)}
626
+ `)}}if(e.failOn&&a.reviewed&&Mb(a.run,e.failOn))return t(`Failing: a finding is at or above ${e.failOn}`),3;return 0}async function nO(e,t,n,r,s){let o=Xe(e),a=s.out?Qa.resolve(s.out):null,c=n==="complete",l=Qa.join(o,"raw","payloads.json"),u=c&&await Bun.file(l).exists()?l:null;if(a)u=(await Ob(e,a,{payloads:c})).includes("payloads.json")?Qa.join(a,"payloads.json"):null;let d=Ib(t,{id:e,status:n,runDir:o,outDir:a,payloads:u,skippedSlices:r,...s.github?{round:await rO(o)}:{},...n==="skipped"?{skipReason:"no-code-files"}:{}});if(a)await Pb(a,d);return d}async function rO(e){try{let t=await Bun.file(Qa.join(e,"raw","record.json")).json();return typeof t.runs==="number"?t.runs:void 0}catch{return}}function Gs(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 iO from"os";import{existsSync as sO,readFileSync as oO}from"fs";var aO=new Set(["true","false","none",":","0","1"]);function cO(){if(process.platform!=="linux")return!1;if(iO.release().toLowerCase().includes("microsoft"))return!0;try{let e=oO("/proc/version","utf8").toLowerCase();return e.includes("microsoft")||e.includes("wsl")}catch{return!1}}function lO(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("/mnt/")||e.toLowerCase().endsWith(".exe")}function uO(e,t){let n=t.browser?.trim()&&!aO.has(t.browser.trim().toLowerCase())?t.browser.trim():void 0;if(t.wsl){if(!n)return["cmd.exe","/c","start","",e];if(lO(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 Fb(e){let t=cO(),n=uO(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"&&sO("/mnt/c")?{cwd:"/mnt/c"}:{}}).exited===0}catch{return!1}}var Wd=(e,t,n)=>(r,s)=>{let o=-1;return a(0);async function a(c){if(c<=o)throw Error("next() called multiple times");o=c;let l,u=!1,d;if(e[c])d=e[c][0][0],r.req.routeIndex=c;else d=c===e.length&&s||void 0;if(d)try{l=await d(r,()=>a(c+1))}catch(f){if(f instanceof Error&&t)r.error=f,l=await t(f,r),u=!0;else throw f}else if(r.finalized===!1&&n)l=await n(r);if(l&&(r.finalized===!1||u))r.res=l;return r}};var Nb=Symbol();var Db=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,o=(e instanceof ec?e.raw.headers:e.headers).get("Content-Type");if(o?.startsWith("multipart/form-data")||o?.startsWith("application/x-www-form-urlencoded"))return dO(e,{all:n,dot:r});return{}};async function dO(e,t){let n=await e.formData();if(n)return fO(n,t);return{}}function fO(e,t){let n=Object.create(null);if(e.forEach((r,s)=>{if(!(t.all||s.endsWith("[]")))n[s]=r;else pO(n,s,r)}),t.dot)Object.entries(n).forEach(([r,s])=>{if(r.includes("."))hO(n,r,s),delete n[r]});return n}var pO=(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]},hO=(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 Gd=(e)=>{let t=e.split("/");if(t[0]==="")t.shift();return t},Lb=(e)=>{let{groups:t,path:n}=mO(e),r=Gd(n);return gO(r,t)},mO=(e)=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(n,r)=>{let s=`@${r}`;return t.push([s,n]),s}),{groups:t,path:e}},gO=(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},tc={},jb=(e,t)=>{if(e==="*")return"*";let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;if(!tc[r])if(n[2])tc[r]=t&&t[0]!==":"&&t[0]!=="*"?[r,n[1],new RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],new RegExp(`^${n[2]}$`)];else tc[r]=[e,n[1],!0];return tc[r]}return null},nc=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,(n)=>{try{return t(n)}catch{return n}})}},_O=(e)=>nc(e,decodeURI),zd=(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 _O(a.includes("%25")?a.replace(/%25/g,"%2525"):a)}else if(s===63)break}return t.slice(n,r)};var Ub=(e)=>{let t=zd(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},$r=(e,t,...n)=>{if(n.length)t=$r(t,...n);return`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`},rc=(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)},Vd=(e)=>{if(!/[%+]/.test(e))return e;if(e.indexOf("+")!==-1)e=e.replace(/\+/g," ");return e.indexOf("%")!==-1?nc(e,Jd):e},Bb=(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 c=e.charCodeAt(a+t.length+1);if(c===61){let l=a+t.length+2,u=e.indexOf("&",l);return Vd(e.slice(l,u===-1?void 0:u))}else if(c==38||isNaN(c))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),c=e.indexOf("=",o);if(c>a&&a!==-1)c=-1;let l=e.slice(o+1,c===-1?a===-1?void 0:a:c);if(r)l=Vd(l);if(o=a,l==="")continue;let u;if(c===-1)u="";else if(u=e.slice(c+1,a===-1?void 0:a),r)u=Vd(u);if(n){if(!(s[l]&&Array.isArray(s[l])))s[l]=[];s[l].push(u)}else s[l]??=u}return t?s[t]:s},qb=Bb,Hb=(e,t)=>Bb(e,t,!0),Jd=decodeURIComponent;var Kb=(e)=>nc(e,Jd),ec=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)?Kb(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)?Kb(r):r}return e}#i(e){return this.#e[1]?this.#e[1][e]:e}query(e){return qb(this.url,e)}queries(e){return Hb(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 Db(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[Nb](){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 ic={Stringify:1,BeforeStream:2,Stream:3},wO=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n};var zs=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((c)=>c({phase:t,buffer:s,context:r}))).then((c)=>Promise.all(c.filter(Boolean).map((l)=>zs(l,t,!1,r,s))).then(()=>s[0]));if(n)return wO(await a,o);else return a};var Wb="text/plain; charset=UTF-8",Xd=(e,t)=>({"Content-Type":e,...t}),Vb=class{#t;#e;env={};#n;finalized=!1;error;#s;#i;#r;#u;#c;#l;#a;#d;#f;constructor(e,t){if(this.#t=e,t)this.#i=t.executionCtx,this.env=t.env,this.#l=t.notFoundHandler,this.#f=t.path,this.#d=t.matchResult}get req(){return this.#e??=new ec(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.#c??=(t)=>this.html(t),this.#c(...e));setLayout=(e)=>this.#u=e;getLayout=()=>this.#u;setRenderer=(e)=>{this.#c=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,c]of o)if(a.toLowerCase()==="set-cookie")r.append(a,c);else r.set(a,c)}if(n)for(let[o,a]of Object.entries(n))if(typeof a==="string")r.set(o,a);else{r.delete(o);for(let c of a)r.append(o,c)}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,Xd(Wb,n));json=(e,t,n)=>this.#o(JSON.stringify(e),t,Xd("application/json",n));html=(e,t,n)=>{let r=(s)=>this.#o(s,t,Xd("text/html; charset=UTF-8",n));return typeof e==="object"?zs(e,ic.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.#l??=()=>new Response,this.#l(this))};var Oe="ALL",Gb="all",zb=["get","post","put","delete","options","patch"],sc="Can not add a route since the matcher is already built.",oc=class extends Error{};var Jb="__COMPOSED_HANDLER";var yO=(e)=>e.text("404 Not Found",404),Xb=(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)},Yb=class e{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...zb,Gb].forEach((o)=>{this[o]=(a,...c)=>{if(typeof a==="string")this.#t=a;else this.#s(o,this.#t,a);return c.forEach((l)=>{this.#s(o,this.#t,l)}),this}}),this.on=(o,a,...c)=>{for(let l of[a].flat()){this.#t=l;for(let u of[o].flat())c.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((c)=>{this.#s(Oe,this.#t,c)}),this};let{strict:r,...s}=t;Object.assign(this,s),this.getPath=r??!0?t.getPath??zd:Ub}#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=yO;errorHandler=Xb;route(t,n){let r=this.basePath(t);return n.routes.map((s)=>{let o;if(n.errorHandler===Xb)o=s.handler;else o=async(a,c)=>(await Wd([],n.errorHandler)(a,()=>s.handler(a,c))).res,o[Jb]=s.handler;r.#s(s.method,s.path,o)}),this}basePath(t){let n=this.#e();return n._basePath=$r(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=(l)=>l;else s=r.replaceRequest;let a=o?(l)=>{let u=o(l);return Array.isArray(u)?u:[u]}:(l)=>{let u=void 0;try{u=l.executionCtx}catch{}return[l.env,u]};s||=(()=>{let l=$r(this._basePath,t),u=l==="/"?0:l.length;return(d)=>{let f=new URL(d.url);return f.pathname=f.pathname.slice(u)||"/",new Request(f,d)}})();let c=async(l,u)=>{let d=await n(s(l.req.raw),...a(l));if(d)return d;await u()};return this.#s(Oe,$r(t,"*"),c),this}#s(t,n,r){t=t.toUpperCase(),n=$r(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),c=new Vb(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](c,async()=>{c.res=await this.#n(c)})}catch(d){return this.#i(d,c)}return u instanceof Promise?u.then((d)=>d||(c.finalized?c.res:this.#n(c))).catch((d)=>this.#i(d,c)):u??this.#n(c)}let l=Wd(a[0],this.errorHandler,this.#n);return(async()=>{try{let u=await l(c);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,c)}})()}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${$r("/",t)}`,n),r,s)};fire=()=>{addEventListener("fetch",(t)=>{t.respondWith(this.#r(t.request,t,void 0,t.request.method))})}};var ac=[];function Yd(e,t){let n=this.buildAllMatchers(),r=(s,o)=>{let a=n[s]||n[Oe],c=a[2][o];if(c)return c;let l=o.match(a[0]);if(!l)return[[],ac];let u=l.indexOf("",1);return[a[1][u],l]};return this.match=r,r(e,t)}var cc="[^/]+",Js=".*",Xs="(?:|/.*)",kr=Symbol(),bO=new Set(".\\+*[^]$()");function vO(e,t){if(e.length===1)return t.length===1?e<t?-1:1:-1;if(t.length===1)return 1;if(e===Js||e===Xs)return 1;else if(t===Js||t===Xs)return-1;if(e===cc)return 1;else if(t===cc)return-1;return e.length===t.length?e<t?-1:1:t.length-e.length}var Zb=class e{#t;#e;#n=Object.create(null);insert(t,n,r,s,o){if(t.length===0){if(this.#t!==void 0)throw kr;if(o)return;this.#t=n;return}let[a,...c]=t,l=a==="*"?c.length===0?["","",Js]:["","",cc]:a==="/*"?["","",Xs]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),u;if(l){let d=l[1],f=l[2]||cc;if(d&&l[2]){if(f===".*")throw kr;if(f=f.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(f))throw kr}if(u=this.#n[f],!u){if(Object.keys(this.#n).some((p)=>p!==Js&&p!==Xs))throw kr;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!==Js&&d!==Xs))throw kr;if(o)return;u=this.#n[a]=new e}u.insert(c,n,r,s,o)}buildRegExpStr(){let n=Object.keys(this.#n).sort(vO).map((r)=>{let s=this.#n[r];return(typeof s.#e==="number"?`(${r})@${s.#e}`:bO.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 Qb=class{#t={varIndex:0};#e=new Zb;insert(e,t,n){let r=[],s=[];for(let a=0;;){let c=!1;if(e=e.replace(/\{[^}]+\}/g,(l)=>{let u=`@\\${a}`;return s[a]=[u,l],a++,c=!0,u}),!c)break}let o=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let a=s.length-1;a>=0;a--){let[c]=s[a];for(let l=o.length-1;l>=0;l--)if(o[l].indexOf(c)!==-1){o[l]=o[l].replace(c,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 xO=[/^$/,[],Object.create(null)],ev=Object.create(null);function tv(e){return ev[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(t,n)=>n?`\\${n}`:"(?:|/.*)")}$`)}function SO(){ev=Object.create(null)}function RO(e){let t=new Qb,n=[];if(e.length===0)return xO;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,_]=r[u];if(p)s[h]=[_.map(([y])=>[y,Object.create(null)]),ac];else d++;let v;try{v=t.insert(h,d,p)}catch(y){throw y===kr?new oc(h):y}if(p)continue;n[d]=_.map(([y,b])=>{let S=Object.create(null);b-=1;for(;b>=0;b--){let[O,I]=v[b];S[O]=I}return[y,S]})}let[o,a,c]=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 _=Object.keys(h);for(let v=0,y=_.length;v<y;v++)h[_[v]]=c[h[_[v]]]}let l=[];for(let u in a)l[u]=n[a[u]];return[o,l,s]}function ki(e,t){if(!e)return;for(let n of Object.keys(e).sort((r,s)=>s.length-r.length))if(tv(n).test(t))return[...e[n]];return}var lc=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[Oe]:Object.create(null)},this.#e={[Oe]:Object.create(null)}}add(e,t,n){let r=this.#t,s=this.#e;if(!r||!s)throw Error(sc);if(!r[e])[r,s].forEach((c)=>{c[e]=Object.create(null),Object.keys(c[Oe]).forEach((l)=>{c[e][l]=[...c[Oe][l]]})});if(t==="/*")t="*";let o=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let c=tv(t);if(e===Oe)Object.keys(r).forEach((l)=>{r[l][t]||=ki(r[l],t)||ki(r[Oe],t)||[]});else r[e][t]||=ki(r[e],t)||ki(r[Oe],t)||[];Object.keys(r).forEach((l)=>{if(e===Oe||e===l)Object.keys(r[l]).forEach((u)=>{c.test(u)&&r[l][u].push([n,o])})}),Object.keys(s).forEach((l)=>{if(e===Oe||e===l)Object.keys(s[l]).forEach((u)=>c.test(u)&&s[l][u].push([n,o]))});return}let a=rc(t)||[t];for(let c=0,l=a.length;c<l;c++){let u=a[c];Object.keys(s).forEach((d)=>{if(e===Oe||e===d)s[d][u]||=[...ki(r[d],u)||ki(r[Oe],u)||[]],s[d][u].push([n,o-l+c+1])})}}match=Yd;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,SO(),e}#n(e){let t=[],n=e===Oe;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!==Oe)t.push(...Object.keys(r[Oe]).map((o)=>[o,r[Oe][o]]))}),!n)return null;else return RO(t)}};var Zd=class{name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,n){if(!this.#e)throw Error(sc);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 c=n[o];try{for(let l=0,u=r.length;l<u;l++)c.add(...r[l]);a=c.match(e,t)}catch(l){if(l instanceof oc)continue;throw l}this.match=c.match.bind(c),this.#t=[c],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 Ys=Object.create(null),nv=class e{#t;#e;#n;#s=0;#i=Ys;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=Lb(n),a=[];for(let c=0,l=o.length;c<l;c++){let u=o[c],d=o[c+1],f=jb(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((c,l,u)=>u.indexOf(c)===l),score:this.#s}}),s}#r(t,n,r,s){let o=[];for(let a=0,c=t.#t.length;a<c;a++){let l=t.#t[a],u=l[n]||l[Oe],d={};if(u!==void 0){if(u.params=Object.create(null),o.push(u),r!==Ys||s&&s!==Ys)for(let f=0,p=u.possibleKeys.length;f<p;f++){let h=u.possibleKeys[f],_=d[u.score];u.params[h]=s?.[h]&&!_?s[h]:r[h]??s?.[h],d[u.score]=!0}}}return o}search(t,n){let r=[];this.#i=Ys;let o=[this],a=Gd(n),c=[];for(let l=0,u=a.length;l<u;l++){let d=a[l],f=l===u-1,p=[];for(let h=0,_=o.length;h<_;h++){let v=o[h],y=v.#e[d];if(y)if(y.#i=v.#i,f){if(y.#e["*"])r.push(...this.#r(y.#e["*"],t,v.#i));r.push(...this.#r(y,t,v.#i))}else p.push(y);for(let b=0,S=v.#n.length;b<S;b++){let O=v.#n[b],I=v.#i===Ys?{}:{...v.#i};if(O==="*"){let N=v.#e["*"];if(N)r.push(...this.#r(N,t,v.#i)),N.#i=I,p.push(N);continue}let[g,R,P]=O;if(!d&&!(P instanceof RegExp))continue;let M=v.#e[g],C=a.slice(l).join("/");if(P instanceof RegExp){let N=P.exec(C);if(N){if(I[R]=N[0],r.push(...this.#r(M,t,v.#i,I)),Object.keys(M.#e).length){M.#i=I;let H=N[0].match(/\//)?.length??0;(c[H]||=[]).push(M)}continue}}if(P===!0||P.test(d))if(I[R]=d,f){if(r.push(...this.#r(M,t,I,v.#i)),M.#e["*"])r.push(...this.#r(M.#e["*"],t,I,v.#i))}else M.#i=I,p.push(M)}}o=p.concat(c.shift()??[])}if(r.length>1)r.sort((l,u)=>l.score-u.score);return[r.map(({handler:l,params:u})=>[l,u])]}};var Qd=class{name="TrieRouter";#t;constructor(){this.#t=new nv}add(e,t,n){let r=rc(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 Er=class extends Yb{constructor(e={}){super(e);this.router=e.router??new Zd({routers:[new lc,new Qd]})}};import{readdir as rv,rm as iv,stat as $O}from"fs/promises";import kO from"os";import sv from"path";async function av(){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 cv(){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 EO=86400000,ov="code-review-subject-";function AO(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}async function lv(e,t){let n=kO.tmpdir(),r=[];try{r=await rv(n)}catch{}for(let o of r){if(!o.startsWith(ov))continue;let a=Number(o.slice(ov.length).split("-")[1]);if(!Number.isInteger(a)||a<=0||AO(a))continue;let c=sv.join(n,o);await iv(c,{recursive:!0,force:!0}).catch(()=>{}),t(`removed stale review worktree ${c}`)}if(e)await re("git",["-C",e,"worktree","prune"],{allowFail:!0}).catch(()=>{});let s=(await Wt()).filter((o)=>o.status==="running").map((o)=>o.id);for(let o of Ua()){let a;try{a=await rv(o)}catch{continue}for(let c of a){let l=sv.join(o,c);try{if(!(s.some((d)=>c.startsWith(`${d}-`))&&Date.now()-(await $O(l)).mtimeMs<EO))await iv(l,{recursive:!0,force:!0})}catch{}}}}import dv from"os";function uv(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 CO="DIFFLOUPE_ALLOWED_HOSTS",fv=["localhost","127.0.0.1","::1"];function ef(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 Zs(e){let t=e.replace(/^\[|\]$/g,"").toLowerCase();return fv.includes(t)||t.startsWith("127.")||t.endsWith(".localhost")}function tf(e,t=process.env[CO]){let n=new Set(fv);for(let r of(t??"").split(",")){let s=ef(r);if(s)n.add(s)}if(!Zs(e)){let r=ef(e.includes(":")&&!e.startsWith("[")?`[${e}]`:e);if(r)n.add(r);n.add(dv.hostname().toLowerCase());for(let s of Object.values(dv.networkInterfaces()))for(let o of s??[])n.add(o.address.toLowerCase())}return n}function pv(e){return async(t,n)=>{let r=ef(t.req.header("host"));if(r===null||r!==void 0&&!e.has(r)&&!Zs(r))return t.json({error:"host not allowed"},403);await n()}}function hv(){return async(e,t)=>{let n=e.req.method;if(n!=="GET"&&n!=="HEAD"&&n!=="OPTIONS"){if(!uv(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 mv(e){let t=new Er;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 UO}from"fs/promises";import BO from"path";var nf=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+`
627
+ `),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 uc=()=>{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 uc=()=>t,t};var gv=class extends nf{constructor(e,t){super(e,t)}async writeSSE(e){let n=(await zs(e.data,ic.Stringify,!1,{})).split(/\r\n|\r|\n/).map((s)=>`data: ${s}`).join(`
607
628
  `),r=[e.event&&`event: ${e.event}`,n,e.id&&`id: ${e.id}`,e.retry&&`retry: ${e.retry}`].filter(Boolean).join(`
608
629
  `)+`
609
630
 
610
- `;await this.write(r)}},tI=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()}},nI=new WeakMap,wd=(e,t,n)=>{let{readable:r,writable:s}=new TransformStream,o=new mb(s,r);if(Ba())e.req.raw.signal.addEventListener("abort",()=>{if(!o.closed)o.abort()});return nI.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"),tI(o,t,n),e.newResponse(o.responseReadable)};var iI=15000,sI=new Set(["done","cancelled","error"]);function oI(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 _b(e,t,n){e.header("Cache-Control","no-cache"),e.header("X-Accel-Buffering","no");let r=oI(e);return wd(e,async(s)=>{let o=r,a=null,c=[],l=!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)}),sI.has(h.type))l=!0},f=t.subscribe(n,(h)=>{if(a)a(h);else c.push(h)});s.onAbort(()=>{f?.unsubscribe(),l=!0,u?.()});for(let h of await $y(n))await d(h);for(let h of c.splice(0))await d(h);if(!f||l){await gb(s),f?.unsubscribe();return}let p=[];a=(h)=>{p.push(h),u?.()};while(!l&&!s.aborted){if(p.length===0){if(await new Promise((h)=>{let y=setTimeout(h,iI);u=()=>{clearTimeout(y),h()}}),u=null,p.length===0&&!l&&!s.aborted)await s.write(`: keepalive
631
+ `;await this.write(r)}},IO=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()}},OO=new WeakMap,rf=(e,t,n)=>{let{readable:r,writable:s}=new TransformStream,o=new gv(s,r);if(uc())e.req.raw.signal.addEventListener("abort",()=>{if(!o.closed)o.abort()});return OO.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"),IO(o,t,n),e.newResponse(o.responseReadable)};var MO=15000,TO=new Set(["done","cancelled","error"]);function FO(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 wv(e,t,n){e.header("Cache-Control","no-cache"),e.header("X-Accel-Buffering","no");let r=FO(e);return rf(e,async(s)=>{let o=r,a=null,c=[],l=!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)}),TO.has(h.type))l=!0},f=t.subscribe(n,(h)=>{if(a)a(h);else c.push(h)});s.onAbort(()=>{f?.unsubscribe(),l=!0,u?.()});for(let h of await Eb(n))await d(h);for(let h of c.splice(0))await d(h);if(!f||l){await _v(s),f?.unsubscribe();return}let p=[];a=(h)=>{p.push(h),u?.()};while(!l&&!s.aborted){if(p.length===0){if(await new Promise((h)=>{let _=setTimeout(h,MO);u=()=>{clearTimeout(_),h()}}),u=null,p.length===0&&!l&&!s.aborted)await s.write(`: keepalive
611
632
 
612
- `);continue}for(let h of p.splice(0))await d(h)}if(f.unsubscribe(),!s.aborted)await gb(s)})}async function gb(e){await e.writeSSE({event:"end",data:"{}"})}var wb=ae({"+":"reject","target?":"string","repo?":"string","base?":"string","intent?":"string","models?":{"+":"reject","review?":"string","coordinator?":"string","walkthrough?":"string","intent?":"string"},"effort?":"string","maxCostUsd?":"number > 0","settingsFile?":"string","kind?":ms,"walkthrough?":"boolean","fromRun?":"string","full?":"boolean"}),SG=ae({id:"string",url:"string"}),aI=ae("'resolving_target' | 'checking_registry' | 'building_map' | 'grouping' | 'reviewing' | 'coordinating' | 'walkthrough' | 'verifying' | 'writing'"),cI=ae({type:"'stage'",stage:aI}).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"}),lI=ae({type:"'groups'",groups:Du.array(),files:ae({path:"string",groupId:"string",classification:"'code' | 'docs' | 'skip'"}).array()}),uI=cI.or(lI).or({type:"'done'",status:"'complete'",findings:"number","carriedOver?":"number",costUsd:"number",wallMs:"number","noChanges?":"boolean","kind?":ms,"files?":"number"}).or({type:"'cancelled'"}).or({type:"'error'",message:"string"}),RG=uI.and({seq:"number",at:"string"}),kG=ae({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"}}),EG=ae({error:"string","activeRunId?":"string"});var pI=2097152;function yb(e){try{return Et(e),!0}catch{return!1}}function bb(e){let t=new dr;async function n(s){let o=e.runs.pendingRun(s);if(o)return o;if(!yb(s))return;try{return await tn(s)}catch(a){if(a instanceof Hn)return a;return}}let r=(s)=>({error:`no run ${s}`});return t.get("/",async(s)=>s.json(await Ht())),t.post("/",async(s)=>{let o;try{o=await s.req.json()}catch{return s.json({error:"request body must be JSON"},400)}let a=wb(o);if(a instanceof ae.errors)return s.json({error:a.summary},400);if(!a.repo&&!a.fromRun&&!e.defaultRepo)return s.json({error:"repo is required: the server was not started in a repository"},400);try{let{id:c}=await e.runs.start(a),l=new URL(`/runs/${c}`,s.req.url).href;return s.json({id:c,url:l},202)}catch(c){if(c instanceof Ca)return s.json({error:c.message,...c.activeRunId?{activeRunId:c.activeRunId}:{}},409);let l=c instanceof Error?c.message:String(c);return s.json({error:l},c instanceof be?400:500)}}),t.get("/:id",async(s)=>{let o=s.req.param("id"),a=await n(o);if(a instanceof Hn)return s.json({error:a.message},422);return a?s.json(a):s.json(r(o),404)}),t.get("/:id/diff",async(s)=>{let o=s.req.param("id");if(!yb(o))return s.json(r(o),404);try{let a=await dI(fI.join(Et(o),"diff.patch"),"utf8");return s.text(a,200,{"Content-Type":"text/plain; charset=utf-8"})}catch{return s.json(r(o),404)}}),t.get("/:id/file",async(s)=>{let o=s.req.param("id"),a=s.req.query("side"),c=s.req.query("path");if(a!=="base"&&a!=="head"||!c)return s.json({error:"side=base|head and path are required"},400);let l=await n(o);if(!l)return s.json(r(o),404);if(l instanceof Hn)return s.json({error:l.message},422);let u=l.files.find((v)=>v.path===c);if(!u)return s.json({error:`${c} is not part of run ${o}`},404);if(a==="base"&&u.status==="added"||a==="head"&&u.status==="removed")return s.json({error:`${c} does not exist on the ${a} side`},404);if(u.isBinary)return s.json({error:`${c} is a binary file`},415);let d=a==="base"?l.base:l.head,f=a==="base"?u.previousPath??u.path:u.path,p=`${d}:${f}`,h=await te("git",["-C",l.repo.root,"cat-file","-s",p],{allowFail:!0});if(h.code!==0)return s.json({error:`cannot read ${p}`},404);if(Number(h.stdout.trim())>pI)return s.json({error:`${f} is larger than 2 MB`},413);let y=await te("git",["-C",l.repo.root,"show",p],{allowFail:!0});if(y.code!==0)return s.json({error:`cannot read ${p}`},404);return s.text(y.stdout,200,{"Content-Type":"text/plain; charset=utf-8"})}),t.get("/:id/events",async(s)=>{let o=s.req.param("id");if(!e.runs.isActive(o)&&!await n(o))return s.json(r(o),404);return _b(s,e.runs,o)}),t.post("/:id/cancel",async(s)=>{let o=s.req.param("id");if(!e.runs.cancel(o))return s.json({error:`run ${o} is not running`},404);return s.json({id:o,cancelling:!0},202)}),t.delete("/:id",async(s)=>{let o=s.req.param("id");if(e.runs.isActive(o))return s.json({error:`run ${o} is still running`,activeRunId:o},409);if(!await n(o))return s.json(r(o),404);return s.json({removed:await ys(o)})}),t}import Rn from"path";import{existsSync as hI}from"fs";var vb=`<!doctype html>
633
+ `);continue}for(let h of p.splice(0))await d(h)}if(f.unsubscribe(),!s.aborted)await _v(s)})}async function _v(e){await e.writeSSE({event:"end",data:"{}"})}var yv=ee({"+":"reject","target?":"string","repo?":"string","base?":"string","intent?":"string","models?":{"+":"reject","review?":"string","coordinator?":"string","walkthrough?":"string","intent?":"string"},"effort?":"string","maxCostUsd?":"number > 0","settingsFile?":"string","kind?":Cs,"walkthrough?":"boolean","fromRun?":"string","full?":"boolean","github?":"boolean","head?":/^[0-9a-fA-F]{40}$/}),Rz=ee({id:"string",url:"string"}),bv=ee({status:ld,"reason?":ud,"note?":"string"}),vv=ee({path:"string",reviewed:"boolean"}),NO=ee("'resolving_target' | 'checking_registry' | 'building_map' | 'grouping' | 'reviewing' | 'coordinating' | 'walkthrough' | 'verifying' | 'writing'"),DO=ee({type:"'stage'",stage:NO}).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"}),LO=ee({type:"'groups'",groups:cd.array(),files:ee({path:"string",groupId:"string",classification:"'code' | 'docs' | 'skip'"}).array()}),jO=DO.or(LO).or({type:"'done'",status:"'complete'",findings:"number","carriedOver?":"number",costUsd:"number",wallMs:"number","noChanges?":"boolean","kind?":Cs,"files?":"number"}).or({type:"'cancelled'"}).or({type:"'error'",message:"string"}),$z=jO.and({seq:"number",at:"string"}),kz=ee({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"}}),Ez=ee({error:"string","activeRunId?":"string"});var qO=2097152;function xv(e){try{return Xe(e),!0}catch{return!1}}function Sv(e){let t=new Er;async function n(o){let a=e.runs.pendingRun(o);if(a)return a;if(!xv(o))return;try{return await ht(o)}catch(c){if(c instanceof On)return c;return}}let r=(o)=>({error:`no run ${o}`});t.get("/",async(o)=>o.json(await Wt())),t.post("/",async(o)=>{let a;try{a=await o.req.json()}catch{return o.json({error:"request body must be JSON"},400)}let c=yv(a);if(c instanceof ee.errors)return o.json({error:c.summary},400);if(!c.repo&&!c.fromRun&&!e.defaultRepo)return o.json({error:"repo is required: the server was not started in a repository"},400);try{let{id:l}=await e.runs.start(c),u=new URL(`/runs/${l}`,o.req.url).href;return o.json({id:l,url:u},202)}catch(l){if(l instanceof Ya)return o.json({error:l.message,...l.activeRunId?{activeRunId:l.activeRunId}:{}},409);let u=l instanceof Error?l.message:String(l);return o.json({error:u},l instanceof _e?400:500)}}),t.get("/:id",async(o)=>{let a=o.req.param("id"),c=await n(a);if(c instanceof On)return o.json({error:c.message},422);return c?o.json(c):o.json(r(a),404)}),t.get("/:id/diff",async(o)=>{let a=o.req.param("id");if(!xv(a))return o.json(r(a),404);try{let c=await UO(BO.join(Xe(a),"diff.patch"),"utf8");return o.text(c,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"),c=o.req.query("side"),l=o.req.query("path");if(c!=="base"&&c!=="head"||!l)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 On)return o.json({error:u.message},422);let d=u.files.find((y)=>y.path===l);if(!d)return o.json({error:`${l} is not part of run ${a}`},404);if(c==="base"&&d.status==="added"||c==="head"&&d.status==="removed")return o.json({error:`${l} does not exist on the ${c} side`},404);if(d.isBinary)return o.json({error:`${l} is a binary file`},415);let f=c==="base"?u.base:u.head,p=c==="base"?d.previousPath??d.path:d.path,h=`${f}:${p}`,_=await re("git",["-C",u.repo.root,"cat-file","-s",h],{allowFail:!0});if(_.code!==0)return o.json({error:`cannot read ${h}`},404);if(Number(_.stdout.trim())>qO)return o.json({error:`${p} is larger than 2 MB`},413);let v=await re("git",["-C",u.repo.root,"show",h],{allowFail:!0});if(v.code!==0)return o.json({error:`cannot read ${h}`},404);return o.text(v.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 wv(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(xi());return o.json(await Sr(a))});async function s(o,a,c){let l=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 ee.errors)return o.json({error:d.summary},400);if(e.runs.isActive(l))return o.json({error:`run ${l} is still running`,activeRunId:l},409);let f=await n(l);if(!f)return o.json(r(l),404);if(f instanceof On)return o.json({error:f.message},422);try{return o.json(await $d(l,c(d)))}catch(p){if(p instanceof vi)return o.json({error:p.message},400);if(p instanceof Fs)return o.json({error:p.message},422);throw p}}return t.put("/:id/state/findings/:fid",(o)=>s(o,bv,(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,vv,(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 Ls(a)})}),t}import Pn from"path";import{existsSync as HO}from"fs";var Rv=`<!doctype html>
613
634
  <html lang="en">
614
635
  <head>
615
636
  <meta charset="utf-8">
@@ -674,15 +695,10 @@ setInterval(loadRuns, 5000);
674
695
  </script>
675
696
  </body>
676
697
  </html>
677
- `;function xb(e=import.meta.dir){let t=process.env.DIFFLOUPE_WEB_DIR;if(t)return Rn.resolve(t);for(let n of[Rn.join(e,"web"),Rn.resolve(e,"../../dist/web")])if(hI(Rn.join(n,"index.html")))return n;return null}async function $b(e,t){if(!t)return e.html(vb,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=Rn.resolve(t),s=Rn.resolve(r,`.${n}`);if(s!==r&&!s.startsWith(r+Rn.sep))return e.text("not found",404);if(s!==r&&!n.endsWith("/")){let a=Bun.file(s);if(await a.exists()){let c=n.startsWith("/assets/");return new Response(a,{headers:{"Cache-Control":c?"public, max-age=31536000, immutable":"no-cache"}})}if(Rn.extname(n))return e.text("not found",404)}let o=Bun.file(Rn.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 fr=4517,Wn="127.0.0.1",mI=10;function gI(e,t=gd(Wn)){let n=new dr;return n.use("*",fb(t)),n.use("*",pb()),n.route("/api/health",hb(e)),n.route("/api/runs",bb(e)),n.all("/api/*",(r)=>r.json({error:"not found"},404)),n.get("*",(r)=>$b(r,e.webDir)),n}function _I(e){let t=e;return t?.code==="EADDRINUSE"||/address already in use|EADDRINUSE|port .* in use/i.test(t?.message??"")}function wI(e,t){if(Ns(e)||e==="0.0.0.0"||e==="::")return`http://localhost:${t}`;return`http://${e.includes(":")?`[${e}]`:e}:${t}`}async function yd(e){let t=e.host??Wn,n=e.port??fr,r=e.log??((f)=>console.error(f)),[s,o]=await Promise.all([ob(),ab()]);await cb(e.defaultRepo,r);let a={version:Xs,defaultRepo:e.defaultRepo,dataDir:en(),webDir:xb(),gh:s,opencode:o,runs:new Cs(Aa(e.defaultRepo??process.cwd()))},c=gd(t),l=gI(a,c),u=e.strictPort?n:Math.min(n+mI,65535),d;for(let f=n;f<=u;f++)try{let p=Bun.serve({hostname:t,port:f,fetch:l.fetch,idleTimeout:0});if(!Ns(t))r(`Warning: listening on ${t}; anyone who can reach this machine on port ${f} can start reviews.`);return{ctx:a,url:wI(t,f),port:f,stop:()=>p.stop(!0)}}catch(p){if(!_I(p))throw p;d=p}throw Error(`no free port in ${n}-${u}: ${d instanceof Error?d.message:String(d)}`)}async function yI(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 bd(e){let t=Array.from({length:11},(r,s)=>e+s).filter((r)=>r<=65535),n=await Promise.all(t.map(yI));return t.flatMap((r,s)=>{let o=n[s];return o?[{base:`http://localhost:${r}`,port:r,health:o}]:[]})}class qa extends Error{status;constructor(e,t){super(e);this.status=t;this.name="ServerRequestError"}}async function Sb(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 qa("error"in r?r.error:`HTTP ${n.status}`,n.status);return r}async function Rb(e,t){try{return(await fetch(`${e}/api/runs/${encodeURIComponent(t)}/cancel`,{method:"POST"})).ok}catch{return!1}}async function kb(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 c=!1;for await(let l of bI(a.body)){if(l.event==="end"){c=!0;break}if(!l.data)continue;let u=JSON.parse(l.data);if(s=u.seq,n(u),u.type==="done"||u.type==="cancelled"||u.type==="error")r=u}if(c)break}return r}async function*bI(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(`
698
+ `;function $v(e=import.meta.dir){let t=process.env.DIFFLOUPE_WEB_DIR;if(t)return Pn.resolve(t);for(let n of[Pn.join(e,"web"),Pn.resolve(e,"../../dist/web")])if(HO(Pn.join(n,"index.html")))return n;return null}async function kv(e,t){if(!t)return e.html(Rv,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=Pn.resolve(t),s=Pn.resolve(r,`.${n}`);if(s!==r&&!s.startsWith(r+Pn.sep))return e.text("not found",404);if(s!==r&&!n.endsWith("/")){let a=Bun.file(s);if(await a.exists()){let c=n.startsWith("/assets/");return new Response(a,{headers:{"Cache-Control":c?"public, max-age=31536000, immutable":"no-cache"}})}if(Pn.extname(n))return e.text("not found",404)}let o=Bun.file(Pn.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 Ar=4517,tr="127.0.0.1",KO=10;function WO(e,t=tf(tr)){let n=new Er;return n.use("*",pv(t)),n.use("*",hv()),n.route("/api/health",mv(e)),n.route("/api/runs",Sv(e)),n.all("/api/*",(r)=>r.json({error:"not found"},404)),n.get("*",(r)=>kv(r,e.webDir)),n}function VO(e){let t=e;return t?.code==="EADDRINUSE"||/address already in use|EADDRINUSE|port .* in use/i.test(t?.message??"")}function GO(e,t){if(Zs(e)||e==="0.0.0.0"||e==="::")return`http://localhost:${t}`;return`http://${e.includes(":")?`[${e}]`:e}:${t}`}async function sf(e){let t=e.host??tr,n=e.port??Ar,r=e.log??((f)=>console.error(f)),[s,o]=await Promise.all([av(),cv()]);await lv(e.defaultRepo,r);let a={version:Dn,defaultRepo:e.defaultRepo,dataDir:nn(),webDir:$v(),gh:s,opencode:o,runs:new Vs(Xa(e.defaultRepo??process.cwd()))},c=tf(t),l=WO(a,c),u=e.strictPort?n:Math.min(n+KO,65535),d;for(let f=n;f<=u;f++)try{let p=Bun.serve({hostname:t,port:f,fetch:l.fetch,idleTimeout:0});if(!Zs(t))r(`Warning: listening on ${t}; anyone who can reach this machine on port ${f} can start reviews.`);return{ctx:a,url:GO(t,f),port:f,stop:()=>p.stop(!0)}}catch(p){if(!VO(p))throw p;d=p}throw Error(`no free port in ${n}-${u}: ${d instanceof Error?d.message:String(d)}`)}async function zO(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 of(e){let t=Array.from({length:11},(r,s)=>e+s).filter((r)=>r<=65535),n=await Promise.all(t.map(zO));return t.flatMap((r,s)=>{let o=n[s];return o?[{base:`http://localhost:${r}`,port:r,health:o}]:[]})}class dc extends Error{status;constructor(e,t){super(e);this.status=t;this.name="ServerRequestError"}}async function Ev(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 dc("error"in r?r.error:`HTTP ${n.status}`,n.status);return r}async function Av(e,t){try{return(await fetch(`${e}/api/runs/${encodeURIComponent(t)}/cancel`,{method:"POST"})).ok}catch{return!1}}async function Cv(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 c=!1;for await(let l of JO(a.body)){if(l.event==="end"){c=!0;break}if(!l.data)continue;let u=JSON.parse(l.data);if(s=u.seq,n(u),u.type==="done"||u.type==="cancelled"||u.type==="error")r=u}if(c)break}return r}async function*JO(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(`
678
699
  `))>=0){let c=n.slice(0,a).replace(/\r$/,"");if(n=n.slice(a+1),c===""){if(s.length)yield{event:r,data:s.join(`
679
- `)};else if(r!=="message")yield{event:r,data:""};r="message",s=[]}else if(c.startsWith(":"))continue;else{let l=c.indexOf(":"),u=l<0?c:c.slice(0,l),d=l<0?"":c.slice(l+1).replace(/^ /,"");if(u==="event")r=d;else if(u==="data")s.push(d)}}}}var Eb=1e4;function Ab(e,t){return[...t,e]}function Ha(e){let t=Number(e);if(!Number.isInteger(t)||t<1||t>65535)throw new bi("must be a port number 1-65535");return t}function xI(e){let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new bi("must be a positive number of US dollars");return t}function Fe(e){console.error(e)}function Cb(e){let t=As(e);if(t)Fe(t)}async function Ib(e){let t=await te("git",["-C",e,"rev-parse","--show-toplevel"],{allowFail:!0}).catch(()=>null);return t&&t.code===0?t.stdout.trim():null}async function Ka(e){let t=await _r();return{host:e.host??t.host??Wn,port:e.port??t.port??fr}}async function Wa(e,t){if(t&&!await Ty(e))Fe(`Could not open a browser; visit ${e}`)}function Va(e,t){return`${e}/runs/${t}`}async function $I(e,t){let n;try{({id:n}=await Sb(e,await ks(t)))}catch(a){if(a instanceof qa&&a.status===409)return-1;return Fe(dn.default.red(`Error: ${a instanceof Error?a.message:String(a)}`)),1}let r=Va(e,n);Fe(`DiffLoupe ready at ${r} (running on the server already at ${e})`),await Wa(r,t.open);let s=Is(()=>{Fe(`
680
- Cancelling the run (Ctrl+C again to stop following it)...`),Rb(e,n)}),o=await kb(e,n,Cb);if(s(),o?.type==="done")return Fe(`Results: ${r}`),0;return o?.type==="cancelled"?130:1}async function SI(e){let t=await ks(e),{host:n,port:r}=await Ka(e),s;try{s=await yd({host:n,port:r,defaultRepo:await Ib(t.repo??process.cwd())??null,log:Fe})}catch(f){return Fe(dn.default.red(`Error starting server: ${f instanceof Error?f.message:String(f)}`)),1}let o=s.ctx.runs;o.watch((f,p)=>Cb(p));let a;try{a=await o.start(t)}catch(f){return Fe(dn.default.red(`Error: ${f instanceof Error?f.message:String(f)}`)),await s.stop(),1}let c=Va(s.url,a.id);Fe(dn.default.green(`DiffLoupe ready at ${c}`)),await Wa(c,e.open);let l=!0,u=!1;Is(()=>{if(!l)process.exit(0);u=!0,Fe(`
681
- 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(Eb)]).then(()=>process.exit(130))});let d=await a.done;if(l=!1,u)return new Promise(()=>{});if(d.status==="complete")Fe(`Results: ${c}`);else if(d.status==="failed")Fe(`Results (failed run): ${c}`);return Fe(dn.default.dim("Server still running. Press Ctrl+C to stop.")),new Promise(()=>{})}async function Ob(e,t){let n={...t,...e?{target:e}:{}};if(n.headless)process.exit(await My(n));let{port:r}=await Ka(n);for(let s of await bd(r)){if(s.health.activeRunId)continue;let o=await $I(s.base,n);if(o>=0)process.exit(o)}process.exit(await SI(n))}var Pb="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 Mb(){return new Kt("review").description("Review changes with the multi-agent reviewer (requires opencode, tilth, git; gh for PRs)").argument("[target]",Pb).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)",Ab,[]).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, 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)",xI).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: ${Wn})`).option("--port <port>",`Port for the server (default: ${fr}, or the next free one)`,Ha).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).action(Ob)}function Tb(){return new Kt("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]",Pb).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",Ab,[]).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: ${Wn})`).option("--port <port>",`Port for the server (default: ${fr}, or the next free one)`,Ha).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)=>Ob(e,{...t,kind:"diff"}))}function Nb(){return new Kt("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: ${Wn})`).option("--port <port>",`Port to look for a server on (default: ${fr})`,Ha).option("--open","Open the URL in a browser",!1).action(async(e,t)=>{let n=e;if(!n&&t.last){if(n=(await Ht())[0]?.id,!n)Fe("No saved runs."),process.exit(1)}let{host:r,port:s}=await Ka(t),o=(await bd(s))[0];if(o){let a=n?Va(o.base,n):o.base;console.log(a),await Wa(a,t.open),process.exit(0)}await Db({...t,host:r,port:s},n)})}async function Db(e,t){let n=vI.resolve(e.repo??process.cwd()),r;try{r=await yd({host:e.host,port:e.port,defaultRepo:await Ib(n),log:Fe})}catch(o){Fe(dn.default.red(`Error starting server: ${o instanceof Error?o.message:String(o)}`)),process.exit(1)}let s=t?Va(r.url,t):r.url;return Fe(dn.default.green(`DiffLoupe ready at ${s}`)),Fe(dn.default.dim("Press Ctrl+C to stop.")),r.ctx.runs.watch((o,a)=>{let c=As(a);if(c)Fe(`${dn.default.dim(o)} ${c}`)}),Is(()=>{let o=r.ctx.runs.activeRunId;if(!o)process.exit(0);Fe(`
682
- Cancelling the active run (Ctrl+C again to exit now)...`);let a=r.ctx.runs.cancel(o)??Promise.resolve();Promise.race([a,Bun.sleep(Eb)]).then(()=>process.exit(130))}),await Wa(s,e.open),r}function Fb(){return new Kt("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: ${Wn})`).option("--port <port>",`Port (default: ${fr}, or the next free one)`,Ha).option("--open","Open the server in a browser",!1).action(async(e)=>{await Db({...e,...await Ka(e)})})}import{rm as TI}from"fs/promises";import NI from"path";var ui=dc(Qs(),1);var Sd=["blocker","should-fix","nice-to-have","question"],RI={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 kI(e){let t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return n>0?RI[t.slice(n+1).toLowerCase()]??"":""}function vd(e,t){return t&&t!==e?`${e}-${t}`:`${e}`}function EI(e){let t=e.side==="deletions"?" (old)":"";if(e.kind==="file")return e.cited.line>0?`${e.file}:${vd(e.cited.line,e.cited.endLine)}`:e.file;if(e.kind==="nearby")return`${e.file}:${vd(e.cited.line,e.cited.endLine)}${t}`;return`${e.file}:${vd(e.line,e.endLine)}${t}`}function xd(e){let t=[`### [${e.severity}] ${e.title}`,Fr(EI(e.anchor))],n=[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(n.length)t.push(`_${n.join(" ")}_`);if(t.push(e.explanation.trim()),e.impact?.trim())t.push(`**Impact:** ${e.impact.trim()}`);if(e.evidence.trim())t.push(`**Evidence:** ${e.evidence.trim()}`);if(e.suggestedCode){if(e.suggestion?.trim())t.push(`**Suggestion:** ${e.suggestion.trim()}`);t.push(Ni(e.suggestedCode,kI(e.file)))}else if(e.suggestion?.trim())t.push(`**Suggestion:** ${e.suggestion.trim()}`);return t.join(`
683
-
684
- `)}function $d(e){return[...e].sort((t,n)=>Sd.indexOf(t.severity)-Sd.indexOf(n.severity)||t.file.localeCompare(n.file)||t.anchor.line-n.anchor.line)}function AI(e,t,n){let r=(n.length?` ${n.length} pre-existing.`:"")+(e.overCapFindings.length?` ${e.overCapFindings.length} more over the posting cap.`:"");if(t.length===0)return`${n.length?"No issues found in this change.":"No issues found."}${r}`;let s=Sd.map((a)=>[a,t.filter((c)=>c.severity===a).length]).filter(([,a])=>a>0).map(([a,c])=>`${c} ${a}`),o=t.length;return`${o} finding${o===1?"":"s"}: ${s.join(", ")}.${r}`}function Lb(e,t={}){let n=Ia(e),r=[`# Review findings: ${Kn(e.target)}`,`Base ${Fr(e.base.slice(0,12))}, head ${Fr(e.head.slice(0,12))}${n?`. ${n}.`:""}`],s=e.findings.filter((a)=>!a.preexisting),o=e.findings.filter((a)=>a.preexisting);r.push(AI(e,s,o));for(let a of $d(s))r.push(xd(a));if(o.length){r.push("## Pre-existing (not introduced by this change)");for(let a of $d(o))r.push(xd(a))}if(t.includeOverCap&&e.overCapFindings.length){r.push(`## Over the posting cap (${e.overCapFindings.length})`);for(let a of $d(e.overCapFindings))r.push(xd(a))}return`${r.join(`
685
-
686
- `)}
687
- `}var CI="unrecorded",II=()=>({blocker:0,"should-fix":0,"nice-to-have":0,question:0}),OI=(e)=>Object.values(e).reduce((t,n)=>t+n,0);function jb(e){let t=e.filter(({run:o})=>o.status==="complete"&&o.meta.kind!=="diff"),n=new Map(t.map((o)=>[o.run.id,o])),r=(o)=>{let a=new Set,c=o;while(c.run.priorRunId&&n.has(c.run.priorRunId)&&!a.has(c.run.id))a.add(c.run.id),c=n.get(c.run.priorRunId)??c;return c.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)=>PI(o.sort((a,c)=>a.run.createdAt.localeCompare(c.run.createdAt)),n)).sort((o,a)=>a.lastAt.localeCompare(o.lastAt))}function PI(e,t){let n=e[0]?.run,r=e.at(-1);if(!n||!r)throw Error("empty chain");let s=II(),o=0,a=0,c=0,l=new Set,u=e.map(({run:f,state:p},h)=>{let y=f.findings.filter((g)=>!g.carriedFrom);for(let g of y)if(g.preexisting)o++;else s[g.severity]++;let v=f.priorRunId?t.get(f.priorRunId)?.run:void 0,b=v?f.resolved:[];for(let g of b)if(a++,v?.findings.find((R)=>R.id===g.id)?.preexisting)c++;for(let[g,R]of Object.entries(p.findingStatus))if(R==="dismissed")l.add(g);return{id:f.id,round:f.round??h+1,createdAt:f.createdAt,new:y.length,newPreexisting:y.filter((g)=>g.preexisting).length,carried:f.findings.length-y.length,resolved:b.length,costUsd:f.meta.costUsd,...f.meta.reviewScope?{scope:f.meta.reviewScope}:{},...f.meta.promptVersion?{promptVersion:f.meta.promptVersion}:{}}}),d=new Set(Object.entries(r.state.findingStatus).flatMap(([f,p])=>p==="dismissed"?[f]:[]));return{key:_a(n.repo,n.target),repo:n.repo.slug??n.repo.root,target:Kn(n.target),rounds:u,raised:s,raisedPreexisting:o,fixed:a,fixedPreexisting:c,dismissed:l.size,open:r.run.findings.filter((f)=>!d.has(f.id)).length,costUsd:u.reduce((f,p)=>f+p.costUsd,0),lastAt:r.run.createdAt}}function kd(e){let t=e.reduce((s,o)=>s+OI(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),resolutionRate:t?n/t:null,costUsd:e.reduce((s,o)=>s+o.costUsd,0)}}function Ub(e){let t=e.filter(({run:o})=>o.status==="complete"&&o.meta.kind!=="diff"),n=new Map(t.map((o)=>[o.run.id,o.run])),r=new Map,s=(o)=>{let a=o.meta.promptVersion??CI,c=o.meta.instructionsHash??"none",l=`${a}/${c}`,u=r.get(l);if(!u)u={promptVersion:a,instructionsHash:c,runs:0,raised:0,raisedPreexisting:0,fixed:0,fixedPreexisting:0,costUsd:0},r.set(l,u);return u};for(let{run:o}of t){let a=s(o);a.runs++,a.costUsd+=o.meta.costUsd;for(let l of o.findings){if(l.carriedFrom)continue;if(l.preexisting)a.raisedPreexisting++;else a.raised++}let c=o.priorRunId?n.get(o.priorRunId):void 0;if(!c)continue;for(let l of o.resolved){let u=c.findings.find((p)=>p.id===l.id),d=n.get(u?.carriedFrom??c.id)??c,f=s(d);if(u?.preexisting)f.fixedPreexisting++;else f.fixed++}}return[...r.values()].sort((o,a)=>a.runs-o.runs)}var Rd=(e)=>e===null?"n/a":`${Math.round(e*100)}%`,Ds=(e)=>`$${e.toFixed(2)}`;function MI(e){let t=Object.entries(e).filter(([,n])=>n>0).map(([n,r])=>`${r} ${n}`);return t.length?t.join(", "):"none"}function Bb(e,t){if(e.length===0)return"No complete review runs match.";let n=[];for(let s of e){let o=s.rounds.length;n.push(`${s.target} ${s.repo} (${o} round${o===1?"":"s"}, ${Ds(s.costUsd)})`);for(let c of s.rounds){let l=c.newPreexisting?` (${c.newPreexisting} pre-existing)`:"",u=c.scope==="incremental"?", changes only":"";n.push(` round ${c.round} ${c.id} ${c.new} new${l}, ${c.carried} carried, ${c.resolved} fixed${u}, ${Ds(c.costUsd)}`)}let a=s.fixed?`, ${Ds(s.costUsd/s.fixed)} per fixed finding`:"";n.push(` raised: ${MI(s.raised)}${s.raisedPreexisting?`; ${s.raisedPreexisting} pre-existing`:""}`),n.push(` fixed ${s.fixed}, dismissed ${s.dismissed}, still open at last run ${s.open}${a}`),n.push("")}let r=kd(e);if(n.push(`${r.chains} chain${r.chains===1?"":"s"}, ${r.meanRounds.toFixed(1)} rounds on average, ${Rd(r.pastThreeRounds)} past three rounds`,`${r.raised} raised on the change, ${r.fixed} fixed, resolution rate ${Rd(r.resolutionRate)}, ${Ds(r.costUsd)} total`),t){n.push("","By prompt version / instructions:");for(let s of t){let o=s.raised?Rd(s.fixed/s.raised):"n/a";n.push(` ${s.promptVersion} / ${s.instructionsHash} ${s.runs} run${s.runs===1?"":"s"}, ${s.raised} raised (${s.raisedPreexisting} pre-existing), ${s.fixed} fixed, resolution rate ${o}, ${Ds(s.costUsd)}`)}}return n.join(`
688
- `)}async function DI(e){try{return await tn(e)}catch(t){console.error(ui.default.red(`No run.json for ${e}: ${t instanceof Error?t.message:String(t)}`)),process.exit(1)}}function Wb(){let e=new Kt("runs").description("List saved runs").enablePositionalOptions().option("--json","Print run headers as JSON",!1).option("--kind <kind>","Only review or diff runs",qb).action(async(t)=>{let n=Hb(await Ht(),t.kind);console.log(t.json?JSON.stringify(n,null,2):Ry(n))});return 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).action(async(t,n)=>{let r=await DI(t);if(n.markdown){process.stdout.write(Lb(r,{includeOverCap:n.overCap}));return}console.log(n.json?JSON.stringify(r,null,2):Ay(r))}),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(t)=>{let n=t.since===void 0?void 0:Kb(t.since);if(n===null)console.error(ui.default.red("--since takes a number with d, h, or w")),process.exit(1);let r=t.repo===void 0?void 0:NI.resolve(t.repo),s=(await Ht()).filter((d)=>!d.invalid&&d.status==="complete"&&d.kind!=="diff"&&(t.repo===void 0||d.repo.root===r||d.repo.slug===t.repo)),o=await Promise.all(s.map(async(d)=>({run:await tn(d.id),state:await wa(d.id)}))),a=n===void 0?void 0:new Date(Date.now()-n).toISOString(),c=jb(o).filter((d)=>a===void 0||d.lastAt>=a),l=new Set(c.flatMap((d)=>d.rounds.map((f)=>f.id))),u=t.byVersion?Ub(o.filter((d)=>l.has(d.run.id))):void 0;if(t.json){console.log(JSON.stringify({chains:c,totals:kd(c),...u?{versions:u}:{}},null,2));return}console.log(Bb(c,u))}),e.command("rm").description("Delete a saved run, its artifacts and the git refs that pin its commits").argument("<id>","Run id").action(async(t)=>{let n=await ys(t);if(n.length===0)console.error(ui.default.yellow(`Nothing found for ${t}`)),process.exit(1);for(let r of n)console.log(`removed ${r}`)}),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)",qb).option("--yes","Delete instead of listing",!1).action(async(t)=>{let n=Kb(t.olderThan),r=Number(t.keep);if(n===null||!Number.isInteger(r)||r<0)console.error(ui.default.red("--older-than takes a number with d, h, or w; --keep takes a whole number")),process.exit(1);let s=cw(Hb(await Ht(),t.kind),{olderThanMs:n,keep:r}),o=await lw();if(s.length===0&&o.length===0){console.log("Nothing to prune");return}if(!t.yes){for(let a of s)console.log(`would delete run ${a.id} (${a.createdAt})`);if(o.length>0)console.log(`would delete ${o.length} orphaned scratch entries`);console.log(ui.default.dim("Run again with --yes to delete."));return}for(let a of s)await ys(a.id),console.log(`deleted run ${a.id}`);for(let a of o)await TI(a,{recursive:!0,force:!0});if(o.length>0)console.log(`deleted ${o.length} orphaned scratch entries`)}),e}function qb(e){if(e!=="review"&&e!=="diff")throw new bi("must be review or diff");return e}function Hb(e,t){return t?e.filter((n)=>(n.kind??"review")===t):e}var FI={h:3600000,d:86400000,w:604800000};function Kb(e){let t=/^(\d+)([hdw])$/.exec(e.trim());return t?Number(t[1])*FI[t[2]]:null}function LI(){return new Kt().name("diffloupe").description("Grouped diffs and multi-agent code review for local changes and pull requests").version(Xs).enablePositionalOptions().addCommand(Mb()).addCommand(Tb()).addCommand(Nb()).addCommand(Fb()).addCommand(Wb()).addCommand(vy())}function Vb(){LI().parseAsync()}Vb();
700
+ `)};else if(r!=="message")yield{event:r,data:""};r="message",s=[]}else if(c.startsWith(":"))continue;else{let l=c.indexOf(":"),u=l<0?c:c.slice(0,l),d=l<0?"":c.slice(l+1).replace(/^ /,"");if(u==="event")r=d;else if(u==="data")s.push(d)}}}}var Iv=1e4;function Ov(e,t){return[...t,e]}function fc(e){let t=Number(e);if(!Number.isInteger(t)||t<1||t>65535)throw new sr("must be a port number 1-65535");return t}function YO(e){let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new sr("must be a positive number of US dollars");return t}function ZO(e){if(!Cn.includes(e))throw new sr(`must be one of ${Cn.join(", ")}`);return e}function Fe(e){console.error(e)}function Pv(e){let t=Ws(e);if(t)Fe(t)}async function Mv(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 pc(e){let t=await Tr();return{host:e.host??t.host??tr,port:e.port??t.port??Ar}}async function hc(e,t){if(t&&!await Fb(e))Fe(`Could not open a browser; visit ${e}`)}function mc(e,t){return`${e}/runs/${t}`}async function QO(e,t){let n;try{({id:n}=await Ev(e,await Hs(t)))}catch(a){if(a instanceof dc&&a.status===409)return-1;return Fe(rn.default.red(`Error: ${a instanceof Error?a.message:String(a)}`)),1}let r=mc(e,n);Fe(`DiffLoupe ready at ${r} (running on the server already at ${e})`),await hc(r,t.open);let s=Gs(()=>{Fe(`
701
+ Cancelling the run (Ctrl+C again to stop following it)...`),Av(e,n)}),o=await Cv(e,n,Pv);if(s(),o?.type==="done")return Fe(`Results: ${r}`),0;return o?.type==="cancelled"?130:1}async function eP(e){let t=await Hs(e),{host:n,port:r}=await pc(e),s;try{s=await sf({host:n,port:r,defaultRepo:await Mv(t.repo??process.cwd())??null,log:Fe})}catch(f){return Fe(rn.default.red(`Error starting server: ${f instanceof Error?f.message:String(f)}`)),1}let o=s.ctx.runs;o.watch((f,p)=>Pv(p));let a;try{a=await o.start(t)}catch(f){return Fe(rn.default.red(`Error: ${f instanceof Error?f.message:String(f)}`)),await s.stop(),1}let c=mc(s.url,a.id);Fe(rn.default.green(`DiffLoupe ready at ${c}`)),await hc(c,e.open);let l=!0,u=!1;Gs(()=>{if(!l)process.exit(0);u=!0,Fe(`
702
+ 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(Iv)]).then(()=>process.exit(130))});let d=await a.done;if(l=!1,u)return new Promise(()=>{});if(d.status==="complete")Fe(`Results: ${c}`);else if(d.status==="failed")Fe(`Results (failed run): ${c}`);return Fe(rn.default.dim("Server still running. Press Ctrl+C to stop.")),new Promise(()=>{})}function tP(e){if(e.github||e.head){let t=!1;try{t=er(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 Tv(e,t){let n={...t,...e?{target:e}:{}},r=tP(n);if(r)Fe(rn.default.red(`Error: ${r}`)),process.exit(2);if(n.headless)process.exit(await Tb(n));let{port:s}=await pc(n);for(let o of await of(s)){if(o.health.activeRunId)continue;let a=await QO(o.base,n);if(a>=0)process.exit(a)}process.exit(await eP(n))}var Fv="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 Nv(){return new Vt("review").description("Review changes with the multi-agent reviewer (requires opencode, tilth, git; gh for PRs)").argument("[target]",Fv).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)",Ov,[]).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, 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)",YO).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: ${tr})`).option("--port <port>",`Port for the server (default: ${Ar}, or the next free one)`,fc).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)",ZO).exitOverride((e)=>process.exit(e.exitCode===0?0:2)).action(Tv)}function Dv(){return new Vt("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]",Fv).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",Ov,[]).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: ${tr})`).option("--port <port>",`Port for the server (default: ${Ar}, or the next free one)`,fc).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)=>Tv(e,{...t,kind:"diff"}))}function Lv(){return new Vt("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: ${tr})`).option("--port <port>",`Port to look for a server on (default: ${Ar})`,fc).option("--open","Open the URL in a browser",!1).action(async(e,t)=>{let n=e;if(!n&&t.last){if(n=(await Wt())[0]?.id,!n)Fe("No saved runs."),process.exit(1)}let{host:r,port:s}=await pc(t),o=(await of(s))[0];if(o){let a=n?mc(o.base,n):o.base;console.log(a),await hc(a,t.open),process.exit(0)}await jv({...t,host:r,port:s},n)})}async function jv(e,t){let n=XO.resolve(e.repo??process.cwd()),r;try{r=await sf({host:e.host,port:e.port,defaultRepo:await Mv(n),log:Fe})}catch(o){Fe(rn.default.red(`Error starting server: ${o instanceof Error?o.message:String(o)}`)),process.exit(1)}let s=t?mc(r.url,t):r.url;return Fe(rn.default.green(`DiffLoupe ready at ${s}`)),Fe(rn.default.dim("Press Ctrl+C to stop.")),r.ctx.runs.watch((o,a)=>{let c=Ws(a);if(c)Fe(`${rn.default.dim(o)} ${c}`)}),Gs(()=>{let o=r.ctx.runs.activeRunId;if(!o)process.exit(0);Fe(`
703
+ Cancelling the active run (Ctrl+C again to exit now)...`);let a=r.ctx.runs.cancel(o)??Promise.resolve();Promise.race([a,Bun.sleep(Iv)]).then(()=>process.exit(130))}),await hc(s,e.open),r}function Uv(){return new Vt("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: ${tr})`).option("--port <port>",`Port (default: ${Ar}, or the next free one)`,fc).option("--open","Open the server in a browser",!1).action(async(e)=>{await jv({...e,...await pc(e)})})}import{rm as uP}from"fs/promises";import dP from"path";var Cr=Tc(mo(),1);var nP="unrecorded",cf=()=>({change:{measured:0,acted:0,control:0},preexisting:{measured:0,acted:0,control:0},stillListed:0});function Hv(e,t){if(!t||!e.priorActedOn)return[];let n=new Set(e.findings.map((r)=>In(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(In(r.id))}]})}function Kv(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 rP(e){let t=cf();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 iP(e){let t={};for(let n of e)t[n]=(t[n]??0)+1;return t}function sP(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 Bv(e){return Object.entries(e).filter(([,t])=>t>0).sort((t,n)=>n[1]-t[1]).map(([t,n])=>`${n} ${t}`).join(", ")}var oP=()=>({blocker:0,"should-fix":0,"nice-to-have":0,question:0}),aP=(e)=>Object.values(e).reduce((t,n)=>t+n,0);function Wv(e){let t=e.filter(({run:o})=>o.status==="complete"&&o.meta.kind!=="diff"),n=new Map(t.map((o)=>[o.run.id,o])),r=(o)=>{let a=new Set,c=o;while(c.run.priorRunId&&n.has(c.run.priorRunId)&&!a.has(c.run.id))a.add(c.run.id),c=n.get(c.run.priorRunId)??c;return c.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)=>cP(o.sort((a,c)=>a.run.createdAt.localeCompare(c.run.createdAt)),n)).sort((o,a)=>a.lastAt.localeCompare(o.lastAt))}function cP(e,t){let n=e[0]?.run,r=e.at(-1);if(!n||!r)throw Error("empty chain");let s=oP(),o=0,a=0,c=0,l=new Map,u=Fa(),d=cf(),f=e.map(({run:h,state:_},v)=>{let y=Is(h);Is(h,u);let b=y.calls?Na(y):null,S=h.findings.filter((g)=>!g.carriedFrom);for(let g of S)if(g.preexisting)o++;else s[g.severity]++;let O=h.priorRunId?t.get(h.priorRunId)?.run:void 0,I=O?h.resolved:[];for(let g of I)if(a++,O?.findings.find((R)=>R.id===g.id)?.preexisting)c++;for(let g of Hv(h,O))Kv(d,g);for(let[g,R]of Object.entries(_.findingStatus))if(R==="dismissed")l.set(g,_.findingNotes?.[g]?.reason??"unrecorded");return{id:h.id,round:h.round??v+1,createdAt:h.createdAt,new:S.length,newPreexisting:S.filter((g)=>g.preexisting).length,carried:h.findings.length-S.length,resolved:I.length,costUsd:h.meta.costUsd,...h.meta.reviewScope?{scope:h.meta.reviewScope}:{},...h.meta.promptVersion?{promptVersion:h.meta.promptVersion}:{},...b!==null?{cacheShare:b}:{}}}),p=new Set(Object.entries(r.state.findingStatus).flatMap(([h,_])=>_==="dismissed"?[h]:[]));return{key:ja(n.repo,n.target),repo:n.repo.slug??n.repo.root,target:Zn(n.target),rounds:f,raised:s,raisedPreexisting:o,fixed:a,fixedPreexisting:c,dismissed:l.size,dismissedBy:iP(l.values()),open:r.run.findings.filter((h)=>!p.has(h.id)).length,costUsd:f.reduce((h,_)=>h+_.costUsd,0),usage:u,acted:d,lastAt:r.run.createdAt}}function lf(e){let t=e.reduce((s,o)=>s+aP(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:sP(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),Fa()),acted:rP(e.map((s)=>s.acted))}}function Vv(e){let t=e.filter(({run:o})=>o.status==="complete"&&o.meta.kind!=="diff"),n=new Map(t.map((o)=>[o.run.id,o.run])),r=new Map,s=(o)=>{let a=o.meta.promptVersion??nP,c=o.meta.instructionsHash??"none",l=`${a}/${c}`,u=r.get(l);if(!u)u={promptVersion:a,instructionsHash:c,runs:0,raised:0,raisedPreexisting:0,fixed:0,fixedPreexisting:0,costUsd:0,acted:cf()},r.set(l,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 c=o.priorRunId?n.get(o.priorRunId):void 0;if(!c)continue;let l=(u)=>n.get(u?.carriedFrom??c.id)??c;for(let u of o.resolved){let d=c.findings.find((p)=>p.id===u.id),f=s(l(d));if(d?.preexisting)f.fixedPreexisting++;else f.fixed++}for(let u of Hv(o,c))Kv(s(l(u.finding)).acted,u)}return[...r.values()].sort((o,a)=>a.runs-o.runs)}var Ei=(e)=>e===null?"n/a":`${Math.round(e*100)}%`,Qs=(e)=>`$${e.toFixed(2)}`;function lP(e){let t=Object.entries(e).filter(([,n])=>n>0).map(([n,r])=>`${r} ${n}`);return t.length?t.join(", "):"none"}function qv(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 (${Ei(t)}), control ${Ei(n)}, ${r>=0?"+":""}${r} points`}function af(e){if(!e.change.measured&&!e.preexisting.measured)return null;let t=[e.change.measured?qv(e.change):"none on the change"];if(e.preexisting.measured)t.push(`pre-existing ${qv(e.preexisting)}`);if(e.stillListed)t.push(`${e.stillListed} edited but still listed`);return t.join("; ")}function Gv(e,t){if(e.length===0)return"No complete review runs match.";let n=[];for(let a of e){let c=a.rounds.length;n.push(`${a.target} ${a.repo} (${c} round${c===1?"":"s"}, ${Qs(a.costUsd)})`);for(let p of a.rounds){let h=p.newPreexisting?` (${p.newPreexisting} pre-existing)`:"",_=p.scope==="incremental"?", changes only":"",v=p.cacheShare===void 0?"":`, ${Ei(p.cacheShare)} cached`;n.push(` round ${p.round} ${p.id} ${p.new} new${h}, ${p.carried} carried, ${p.resolved} fixed${_}, ${Qs(p.costUsd)}${v}`)}let l=Os(a.usage);if(l)n.push(` tokens: ${l}`);let u=a.fixed?`, ${Qs(a.costUsd/a.fixed)} per fixed finding`:"";n.push(` raised: ${lP(a.raised)}${a.raisedPreexisting?`; ${a.raisedPreexisting} pre-existing`:""}`);let d=Bv(a.dismissedBy);n.push(` fixed ${a.fixed}, dismissed ${a.dismissed}${d?` (${d})`:""}, still open at last run ${a.open}${u}`);let f=af(a.acted);if(f)n.push(` acted on: ${f}`);n.push("")}let r=lf(e);if(n.push(`${r.chains} chain${r.chains===1?"":"s"}, ${r.meanRounds.toFixed(1)} rounds on average, ${Ei(r.pastThreeRounds)} past three rounds`,`${r.raised} raised on the change, ${r.fixed} fixed, resolution rate ${Ei(r.resolutionRate)}, ${Qs(r.costUsd)} total`),r.dismissed)n.push(`${r.dismissed} dismissed: ${Bv(r.dismissedBy)}`);let s=Os(r.usage);if(s)n.push(`tokens over ${r.usage.calls} agent calls: ${s}`);let o=af(r.acted);if(o)n.push(`prior findings acted on: ${o}`);if(t){n.push("","By prompt version / instructions:");for(let a of t){let c=a.raised?Ei(a.fixed/a.raised):"n/a";n.push(` ${a.promptVersion} / ${a.instructionsHash} ${a.runs} run${a.runs===1?"":"s"}, ${a.raised} raised (${a.raisedPreexisting} pre-existing), ${a.fixed} fixed, resolution rate ${c}, ${Qs(a.costUsd)}`);let l=af(a.acted);if(l)n.push(` acted on: ${l}`)}}return n.join(`
704
+ `)}async function fP(e,t=ht){try{return await t(e)}catch(n){console.error(Cr.default.red(`No run.json for ${e}: ${n instanceof Error?n.message:String(n)}`)),process.exit(1)}}function Yv(){let e=new Vt("runs").description("List saved runs").enablePositionalOptions().option("--json","Print run headers as JSON",!1).option("--kind <kind>","Only review or diff runs",zv).action(async(r)=>{let s=Jv(await Wt(),r.kind);console.log(r.json?JSON.stringify(s,null,2):Bw(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 fP(r,s.json||s.markdown?ht:Rd),a=await Sr(r);if(s.markdown){process.stdout.write(Ps(o,{includeOverCap:s.overCap,state:a,includeDismissed:s.dismissed}));return}console.log(s.json?JSON.stringify({...o,state:a},null,2):Kw(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 ly(r,s,o,a)}catch(l){console.error(Cr.default.red(l instanceof Error?l.message:String(l))),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: ${Ma.join(", ")}`,pP).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:Xv(r.since);if(s===null)console.error(Cr.default.red("--since takes a number with d, h, or w")),process.exit(1);let o=r.repo===void 0?void 0:dP.resolve(r.repo),a=(await Wt()).filter((p)=>!p.invalid&&p.status==="complete"&&p.kind!=="diff"&&(r.repo===void 0||p.repo.root===o||p.repo.slug===r.repo)),c=await Promise.all(a.map(async(p)=>({run:await Rd(p.id),state:await Sr(p.id)}))),l=s===void 0?void 0:new Date(Date.now()-s).toISOString(),u=Wv(c).filter((p)=>l===void 0||p.lastAt>=l),d=new Set(u.flatMap((p)=>p.rounds.map((h)=>h.id))),f=r.byVersion?Vv(c.filter((p)=>d.has(p.run.id))):void 0;if(r.json){console.log(JSON.stringify({chains:u,totals:lf(u),...f?{versions:f}:{}},null,2));return}console.log(Gv(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 Ls(r);if(s.length===0)console.error(Cr.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)",zv).option("--yes","Delete instead of listing",!1).action(async(r)=>{let s=Xv(r.olderThan),o=Number(r.keep);if(s===null||!Number.isInteger(o)||o<0)console.error(Cr.default.red("--older-than takes a number with d, h, or w; --keep takes a whole number")),process.exit(1);let a=fy(Jv(await Wt(),r.kind),{olderThanMs:s,keep:o}),c=await py();if(a.length===0&&c.length===0){console.log("Nothing to prune");return}if(!r.yes){for(let l of a)console.log(`would delete run ${l.id} (${l.createdAt})`);if(c.length>0)console.log(`would delete ${c.length} orphaned scratch entries`);console.log(Cr.default.dim("Run again with --yes to delete."));return}for(let l of a)await Ls(l.id),console.log(`deleted run ${l.id}`);for(let l of c)await uP(l,{recursive:!0,force:!0});if(c.length>0)console.log(`deleted ${c.length} orphaned scratch entries`)}),e}function pP(e){let t=Ma.find((n)=>n===e);if(!t)throw new sr(`must be one of ${Ma.join(", ")}`);return t}function zv(e){if(e!=="review"&&e!=="diff")throw new sr("must be review or diff");return e}function Jv(e,t){return t?e.filter((n)=>(n.kind??"review")===t):e}var hP={h:3600000,d:86400000,w:604800000};function Xv(e){let t=/^(\d+)([hdw])$/.exec(e.trim());return t?Number(t[1])*hP[t[2]]:null}function mP(){return new Vt().name("diffloupe").description("Grouped diffs and multi-agent code review for local changes and pull requests").version(Dn).enablePositionalOptions().addCommand(Nv()).addCommand(Dv()).addCommand(Lv()).addCommand(Uv()).addCommand(Yv()).addCommand($b())}function Zv(){mP().parseAsync()}Zv();