@acemarke/diffloupe 0.1.0 → 0.2.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/README.md +202 -135
- package/dist/index.js +596 -535
- package/dist/review-core/opencode/governor.ts +670 -0
- package/dist/review-core/opencode/tools.md +104 -0
- package/dist/review-core/system.md +52 -0
- package/dist/wasm/tree-sitter-cpp.wasm +0 -0
- package/dist/wasm/tree-sitter-tsx.wasm +0 -0
- package/dist/wasm/tree-sitter-typescript.wasm +0 -0
- package/dist/wasm/web-tree-sitter.wasm +0 -0
- package/dist/web/assets/arktype-bg7F_Ihs.js +34 -0
- package/dist/web/assets/diffs-D52k9AsX.js +157 -0
- package/dist/web/assets/index-Bh_riWuX.css +1 -0
- package/dist/web/assets/index-Bhh-mxRf.js +12 -0
- package/dist/web/assets/langs/c-B7uRR5me.js +1 -0
- package/dist/web/assets/langs/cmake-Bj61d0ZC.js +1 -0
- package/dist/web/assets/langs/cpp-CsVjRphN.js +1 -0
- package/dist/web/assets/langs/css-C8fQr_0Q.js +1 -0
- package/dist/web/assets/langs/diff-woXpYk--.js +1 -0
- package/dist/web/assets/langs/docker-IyjqRm3v.js +1 -0
- package/dist/web/assets/langs/glsl-D4jN2Gfq.js +1 -0
- package/dist/web/assets/langs/go-rLFTqkRN.js +1 -0
- package/dist/web/assets/langs/graphql-CraUZO0h.js +1 -0
- package/dist/web/assets/langs/html-DA4kSGiR.js +1 -0
- package/dist/web/assets/langs/ini-B5eOa1yu.js +1 -0
- package/dist/web/assets/langs/java-BXcb2rRD.js +1 -0
- package/dist/web/assets/langs/javascript-BgS3c2Ky.js +1 -0
- package/dist/web/assets/langs/json-qhed-kSA.js +1 -0
- package/dist/web/assets/langs/json5-BR5RXkoi.js +1 -0
- package/dist/web/assets/langs/jsonc-CYpm1nAK.js +1 -0
- package/dist/web/assets/langs/jsx-Bz0zcwM4.js +1 -0
- package/dist/web/assets/langs/make-Dixweg8N.js +1 -0
- package/dist/web/assets/langs/markdown-BYOwaDjH.js +1 -0
- package/dist/web/assets/langs/objective-cpp-BsSzOQcm.js +1 -0
- package/dist/web/assets/langs/plain-text-BONI54VU.js +1 -0
- package/dist/web/assets/langs/postcss-BXeXVLqQ.js +1 -0
- package/dist/web/assets/langs/powershell-QtSnmXcu.js +1 -0
- package/dist/web/assets/langs/python-gzcpVVnB.js +1 -0
- package/dist/web/assets/langs/regexp-Cw_s_VJJ.js +1 -0
- package/dist/web/assets/langs/rust-DpiIf5JO.js +1 -0
- package/dist/web/assets/langs/scss-CHVQqdPx.js +1 -0
- package/dist/web/assets/langs/shellscript-CLZ0U2zV.js +1 -0
- package/dist/web/assets/langs/sql-CEbI0hMM.js +1 -0
- package/dist/web/assets/langs/svelte-CfPQtCMR.js +1 -0
- package/dist/web/assets/langs/toml-CcmNWLt0.js +1 -0
- package/dist/web/assets/langs/tsx-udAQXfEw.js +1 -0
- package/dist/web/assets/langs/typescript-bsJCZSQ-.js +1 -0
- package/dist/web/assets/langs/vue-DEcQttJD.js +1 -0
- package/dist/web/assets/langs/xml-D5JPTzE5.js +1 -0
- package/dist/web/assets/langs/yaml-rwi0_p6S.js +1 -0
- package/dist/web/assets/react-jlQz0HNM.js +9 -0
- package/dist/web/assets/rolldown-runtime-hePW80VL.js +1 -0
- package/dist/web/assets/router-DvNvfdSS.js +2 -0
- package/dist/web/assets/shiki-CbbI7yl6.js +153 -0
- package/dist/web/assets/state-a-GRkbSP.js +1 -0
- package/dist/web/assets/themes/pierre-dark-CpLgRqie.js +1 -0
- package/dist/web/assets/themes/pierre-light-CoaEpmwp.js +1 -0
- package/dist/web/assets/unused-C8e4aDKx.js +1 -0
- package/dist/web/assets/worker-uPqQ0MJ1.js +164 -0
- package/dist/web/index.html +26 -0
- package/package.json +34 -15
package/dist/index.js
CHANGED
|
@@ -1,547 +1,608 @@
|
|
|
1
|
-
#!/usr/bin/env
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
1
|
+
#!/usr/bin/env -S bun --no-env-file
|
|
2
|
+
// @bun
|
|
3
|
+
var Jw=Object.create;var{getPrototypeOf:Xw,defineProperty:Ua,getOwnPropertyNames:Yw}=Object;var Ju=Object.prototype.hasOwnProperty;function Zw(e){return this[e]}var Qw,eb,Ba=(e,t,n)=>{var r=e!=null&&typeof e==="object";if(r){var s=t?Qw??=new WeakMap:eb??=new WeakMap,o=s.get(e);if(o)return o}n=e!=null?Jw(Xw(e)):{};let a=t||!e||!e.__esModule||!Ju.call(e,"default")?Ua(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let l of Yw(e))if(!Ju.call(a,l))Ua(a,l,{get:Zw.bind(e,l),enumerable:!0})}if(r)s.set(e,a);return a};var Vn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Ue=(e,t,n)=>()=>{if(e)try{t=e(e=0)}catch(r){n=[r]}if(n)throw n[0];return t};var tb=(e,t,n)=>{for(var r in t)Ua(e,r,{get:t[r],set:n[r],enumerable:!0,configurable:!0})},di=import.meta.require;var fi=Vn(function(nb){class qa 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 Xu extends qa{constructor(e){super(1,"commander.invalidArgument",e);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}nb.CommanderError=qa;nb.InvalidArgumentError=Xu});var Ds=Vn(function(ab){var{InvalidArgumentError:sb}=fi();class Yu{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 sb(`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 ob(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}ab.Argument=Yu;ab.humanReadableArgName=ob});var Ha=Vn(function(db){var{humanReadableArgName:ub}=Ds();class Zu{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)=>ub(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((n,r)=>Math.max(n,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(r)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,r)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(r)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,r)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(r)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,r)=>Math.max(n,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(r)))),0)}commandUsage(e){let t=e._name;if(e._aliases[0])t=t+"|"+e._aliases[0];let n="";for(let r=e.parent;r;r=r.parent)n=r.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices)t.push(`choices: ${e.argChoices.map((n)=>JSON.stringify(n)).join(", ")}`);if(e.defaultValue!==void 0){if(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==="boolean")t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`)}if(e.presetArg!==void 0&&e.optional)t.push(`preset: ${JSON.stringify(e.presetArg)}`);if(e.envVar!==void 0)t.push(`env: ${e.envVar}`);if(t.length>0){let n=`(${t.join(", ")})`;if(e.description)return`${e.description} ${n}`;return n}return e.description}argumentDescription(e){let t=[];if(e.argChoices)t.push(`choices: ${e.argChoices.map((n)=>JSON.stringify(n)).join(", ")}`);if(e.defaultValue!==void 0)t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`);if(t.length>0){let n=`(${t.join(", ")})`;if(e.description)return`${e.description} ${n}`;return n}return e.description}formatItemList(e,t,n){if(t.length===0)return[];return[n.styleTitle(e),...t,""]}groupItems(e,t,n){let r=new Map;return e.forEach((s)=>{let o=n(s);if(!r.has(o))r.set(o,[])}),t.forEach((s)=>{let o=n(s);if(!r.has(o))r.set(o,[]);r.get(o).push(s)}),r}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth??80;function s(d,f){return t.formatItem(d,n,f,t)}let o=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],a=t.commandDescription(e);if(a.length>0)o=o.concat([t.boxWrap(t.styleCommandDescription(a),r),""]);let l=t.visibleArguments(e).map((d)=>s(t.styleArgumentTerm(t.argumentTerm(d)),t.styleArgumentDescription(t.argumentDescription(d))));if(o=o.concat(this.formatItemList("Arguments:",l,t)),this.groupItems(e.options,t.visibleOptions(e),(d)=>d.helpGroupHeading??"Options:").forEach((d,f)=>{let p=d.map((h)=>s(t.styleOptionTerm(t.optionTerm(h)),t.styleOptionDescription(t.optionDescription(h))));o=o.concat(this.formatItemList(f,p,t))}),t.showGlobalOptions){let d=t.visibleGlobalOptions(e).map((f)=>s(t.styleOptionTerm(t.optionTerm(f)),t.styleOptionDescription(t.optionDescription(f))));o=o.concat(this.formatItemList("Global Options:",d,t))}return this.groupItems(e.commands,t.visibleCommands(e),(d)=>d.helpGroup()||"Commands:").forEach((d,f)=>{let p=d.map((h)=>s(t.styleSubcommandTerm(t.subcommandTerm(h)),t.styleSubcommandDescription(t.subcommandDescription(h))));o=o.concat(this.formatItemList(f,p,t))}),o.join(`
|
|
4
|
+
`)}displayWidth(e){return Qu(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map((t)=>{if(t==="[options]")return this.styleOptionText(t);if(t==="[command]")return this.styleSubcommandText(t);if(t[0]==="["||t[0]==="<")return this.styleArgumentText(t);return this.styleCommandText(t)}).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map((t)=>{if(t==="[options]")return this.styleOptionText(t);if(t[0]==="["||t[0]==="<")return this.styleArgumentText(t);return this.styleSubcommandText(t)}).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,r){let o=" ".repeat(2);if(!n)return o+e;let a=e.padEnd(t+e.length-r.displayWidth(e)),l=2,u=(this.helpWidth??80)-t-l-2,d;if(u<this.minWidthToWrap||r.preformatted(n))d=n;else d=r.boxWrap(n,u).replace(/\n/g,`
|
|
5
|
+
`+" ".repeat(t+l));return o+a+" ".repeat(l)+d.replace(/\n/g,`
|
|
6
|
+
${o}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),r=/[\s]*[^\s]+/g,s=[];return n.forEach((o)=>{let a=o.match(r);if(a===null){s.push("");return}let l=[a.shift()],c=this.displayWidth(l[0]);a.forEach((u)=>{let d=this.displayWidth(u);if(c+d<=t){l.push(u),c+=d;return}s.push(l.join(""));let f=u.trimStart();l=[f],c=this.displayWidth(f)}),s.push(l.join(""))}),s.join(`
|
|
7
|
+
`)}}function Qu(e){let t=/\x1b\[\d*(;\d*)*m/g;return e.replace(t,"")}db.Help=Zu;db.stripColor=Qu});var Ka=Vn(function(gb){var{InvalidArgumentError:hb}=fi();class td{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=mb(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 hb(`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 ed(this.name().replace(/^no-/,""));return ed(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 nd{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 ed(e){return e.split("-").reduce((t,n)=>t+n[0].toUpperCase()+n.slice(1))}function mb(e){let t,n,r=/^-[^-]$/,s=/^--[^-]/,o=e.split(/[ |,]+/).concat("guard");if(r.test(o[0]))t=o.shift();if(s.test(o[0]))n=o.shift();if(!t&&r.test(o[0]))t=o.shift();if(!t&&s.test(o[0]))t=n,n=o.shift();if(o[0].startsWith("-")){let a=o[0],l=`option creation failed due to '${a}' in option flags '${e}'`;if(/^-[^-][^-]/.test(a))throw Error(`${l}
|
|
7
8
|
- a short flag is a single dash and a single character
|
|
8
9
|
- either use a single dash and a single character (for a short flag)
|
|
9
|
-
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(
|
|
10
|
-
- too many short flags`);if(
|
|
11
|
-
- too many long flags`);throw
|
|
12
|
-
- unrecognised flag format`)}if(
|
|
13
|
-
(Did you mean one of ${
|
|
14
|
-
(Did you mean ${
|
|
15
|
-
- specify the name in Command constructor or using .name()`);if(
|
|
16
|
-
Expecting one of '${
|
|
17
|
-
- already used by option '${
|
|
18
|
-
- 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(
|
|
19
|
-
- if '${
|
|
10
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(r.test(a))throw Error(`${l}
|
|
11
|
+
- too many short flags`);if(s.test(a))throw Error(`${l}
|
|
12
|
+
- too many long flags`);throw Error(`${l}
|
|
13
|
+
- unrecognised flag format`)}if(t===void 0&&n===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}gb.Option=td;gb.DualOptions=nd});var rd=Vn(function(vb){function wb(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 bb(e,t){if(!t||t.length===0)return"";t=Array.from(new Set(t));let n=e.startsWith("--");if(n)e=e.slice(2),t=t.map((a)=>a.slice(2));let r=[],s=3,o=0.4;if(t.forEach((a)=>{if(a.length<=1)return;let l=wb(e,a),c=Math.max(e.length,a.length);if((c-l)/c>o){if(l<s)s=l,r=[a];else if(l===s)r.push(a)}}),r.sort((a,l)=>a.localeCompare(l)),n)r=r.map((a)=>`--${a}`);if(r.length>1)return`
|
|
14
|
+
(Did you mean one of ${r.join(", ")}?)`;if(r.length===1)return`
|
|
15
|
+
(Did you mean ${r[0]}?)`;return""}vb.suggestSimilar=bb});var ad=Vn(function(Cb){var kb=di("events").EventEmitter,mr=di("child_process"),We=di("path"),En=di("fs"),G=di("process"),{Argument:Rb,humanReadableArgName:$b}=Ds(),{CommanderError:Wa}=fi(),{Help:Sb,stripColor:Eb}=Ha(),{Option:id,DualOptions:Ab}=Ka(),{suggestSimilar:sd}=rd();class Ga extends kb{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)=>G.stdout.write(t),writeErr:(t)=>G.stderr.write(t),outputError:(t,n)=>n(t),getOutHelpWidth:()=>G.stdout.isTTY?G.stdout.columns:void 0,getErrHelpWidth:()=>G.stderr.isTTY?G.stderr.columns:void 0,getOutHasColors:()=>Va()??(G.stdout.isTTY&&G.stdout.hasColors?.()),getErrHasColors:()=>Va()??(G.stderr.isTTY&&G.stderr.hasColors?.()),stripColor:(t)=>Eb(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let r=t,s=n;if(typeof r==="object"&&r!==null)s=r,r=null;s=s||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(o);if(r)l.description(r),l._executableHandler=!0;if(s.isDefault)this._defaultCommandName=l._name;if(l._hidden=!!(s.noHelp||s.hidden),l._executableFile=s.executableFile||null,a)l.arguments(a);if(this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),r)return this;return l}createCommand(e){return new Ga(e)}createHelp(){return Object.assign(new Sb,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 Rb(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 Wa(e,t,n));G.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 id(e,t)}_callParseArg(e,t,n,r){try{return e.parseArg(t,n)}catch(s){if(s.code==="commander.invalidArgument"){let o=`${r} ${s.message}`;this.error(o,{exitCode:s.exitCode,code:s.code})}throw s}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
|
|
18
|
+
- already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=(r)=>[r.name()].concat(r.aliases()),n=t(e).find((r)=>this._findCommand(r));if(n){let r=t(this._findCommand(n)).join("|"),s=t(e).join("|");throw Error(`cannot add command '${s}' as already have command '${r}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let s=e.long.replace(/^--no-/,"--");if(!this._findOption(s))this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else if(e.defaultValue!==void 0)this.setOptionValueWithSource(n,e.defaultValue,"default");let r=(s,o,a)=>{if(s==null&&e.presetArg!==void 0)s=e.presetArg;let l=this.getOptionValue(n);if(s!==null&&e.parseArg)s=this._callParseArg(e,s,l,o);else if(s!==null&&e.variadic)s=e._collectValue(s,l);if(s==null)if(e.negate)s=!1;else if(e.isBoolean()||e.optional)s=!0;else s="";this.setOptionValueWithSource(n,s,a)};if(this.on("option:"+t,(s)=>{let o=`error: option '${e.flags}' argument '${s}' is invalid.`;r(s,o,"cli")}),e.envVar)this.on("optionEnv:"+t,(s)=>{let o=`error: option '${e.flags}' value '${s}' from env '${e.envVar}' is invalid.`;r(s,o,"env")});return this}_optionEx(e,t,n,r,s){if(typeof t==="object"&&t instanceof id)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,n);if(o.makeOptionMandatory(!!e.mandatory),typeof r==="function")o.default(s).argParser(r);else if(r instanceof RegExp){let a=r;r=(l,c)=>{let u=a.exec(l);return u?u[0]:c},o.default(s).argParser(r)}else o.default(r);return this.addOption(o)}option(e,t,n,r){return this._optionEx({},e,t,n,r)}requiredOption(e,t,n,r){return this._optionEx({mandatory:!0},e,t,n,r)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){if(this._storeOptionsAsProperties)return this[e];return this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){if(this._storeOptionsAsProperties)this[e]=t;else this._optionValues[e]=t;return this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach((n)=>{if(n.getOptionValueSource(e)!==void 0)t=n.getOptionValueSource(e)}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){if(G.versions?.electron)t.from="electron";let r=G.execArgv??[];if(r.includes("-e")||r.includes("--eval")||r.includes("-p")||r.includes("--print"))t.from="eval"}if(e===void 0)e=G.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(G.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(En.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
|
+
- if '${n}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
20
21
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
21
|
-
- ${
|
|
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=We.resolve(u,d);if(En.existsSync(f))return f;if(r.includes(We.extname(d)))return;let p=r.find((h)=>En.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=En.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=We.resolve(We.dirname(u),a)}if(a){let u=s(a,o);if(!u&&!e._executableFile&&this._scriptPath){let d=We.basename(this._scriptPath,We.extname(this._scriptPath));if(d!==this._name)u=s(a,`${d}-${e._name}`)}o=u||o}n=r.includes(We.extname(o));let l;if(G.platform!=="win32")if(n)t.unshift(o),t=od(G.execArgv).concat(t),l=mr.spawn(G.argv[0],t,{stdio:"inherit"});else l=mr.spawn(o,t,{stdio:"inherit"});else this._checkForMissingExecutable(o,a,e._name),t.unshift(o),t=od(G.execArgv).concat(t),l=mr.spawn(G.execPath,t,{stdio:"inherit"});if(!l.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((d)=>{G.on(d,()=>{if(l.killed===!1&&l.exitCode===null)l.kill(d)})});let c=this._exitCallback;l.on("close",(u)=>{if(u=u??1,!c)G.exit(u);else c(new Wa(u,"commander.executeSubCommandAsync","(close)"))}),l.on("error",(u)=>{if(u.code==="ENOENT")this._checkForMissingExecutable(o,a,e._name);else if(u.code==="EACCES")throw Error(`'${o}' not executable`);if(!c)G.exit(1);else{let d=new Wa(1,"commander.executeSubCommandAsync","(error)");d.nestedError=u,c(d)}}),this.runningCommand=l}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);if(!r)this.help({error:!0});r._prepareForParse();let s;return s=this._chainOrCallSubCommandHook(s,r,"preSubcommand"),s=this._chainOrCall(s,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),s}_dispatchHelpCommand(e){if(!e)this.help();let t=this._findCommand(e);if(t&&!t._executableHandler)t.help();return this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach((e,t)=>{if(e.required&&this.args[t]==null)this.missingArgument(e.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let e=(n,r,s)=>{let o=r;if(r!==null&&n.parseArg){let a=`error: command-argument value '${r}' is invalid for argument '${n.name()}'.`;o=this._callParseArg(n,r,s,a)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let s=n.defaultValue;if(n.variadic){if(r<this.args.length){if(s=this.args.slice(r),n.parseArg)s=s.reduce((o,a)=>e(n,a,o),n.defaultValue)}else if(s===void 0)s=[]}else if(r<this.args.length){if(s=this.args[r],n.parseArg)s=e(n,s,n.defaultValue)}t[r]=s}),this.processedArgs=t}_chainOrCall(e,t){if(e?.then&&typeof e.then==="function")return e.then(()=>t());return t()}_chainOrCallHooks(e,t){let n=e,r=[];if(this._getCommandAndAncestors().reverse().filter((s)=>s._lifeCycleHooks[t]!==void 0).forEach((s)=>{s._lifeCycleHooks[t].forEach((o)=>{r.push({hookedCommand:s,callback:o})})}),t==="postAction")r.reverse();return r.forEach((s)=>{n=this._chainOrCall(n,()=>s.callback(s.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;if(this._lifeCycleHooks[n]!==void 0)this._lifeCycleHooks[n].forEach((s)=>{r=this._chainOrCall(r,()=>s(this,t))});return r}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{if(n.unknown.length>0)this.unknownOption(n.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let o;if(o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent)o=this._chainOrCall(o,()=>{this.parent.emit(s,e,t)});return o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent?.listenerCount(s))r(),this._processArguments(),this.parent.emit(s,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);if(this.listenerCount("command:*"))this.emit("command:*",e,t);else if(this.commands.length)this.unknownCommand();else r(),this._processArguments()}else if(this.commands.length)r(),this.help({error:!0});else r(),this._processArguments()}_findCommand(e){if(!e)return;return this.commands.find((t)=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find((t)=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach((e)=>{e.options.forEach((t)=>{if(t.mandatory&&e.getOptionValue(t.attributeName())===void 0)e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter((n)=>{let r=n.attributeName();if(this.getOptionValue(r)===void 0)return!1;return this.getOptionValueSource(r)!=="default"});e.filter((n)=>n.conflictsWith.length>0).forEach((n)=>{let r=e.find((s)=>n.conflictsWith.includes(s.attributeName()));if(r)this._conflictingOption(n,r)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((e)=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t;function s(u){return u.length>1&&u[0]==="-"}let o=(u)=>{if(!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(u))return!1;return!this._getCommandAndAncestors().some((d)=>d.options.map((f)=>f.short).some((f)=>/^-\d$/.test(f)))},a=null,l=null,c=0;while(c<e.length||l){let u=l??e[c++];if(l=null,u==="--"){if(r===n)r.push(u);r.push(...e.slice(c));break}if(a&&(!s(u)||o(u))){this.emit(`option:${a.name()}`,u);continue}if(a=null,s(u)){let d=this._findOption(u);if(d){if(d.required){let f=e[c++];if(f===void 0)this.optionMissingArgument(d);this.emit(`option:${d.name()}`,f)}else if(d.optional){let f=null;if(c<e.length&&(!s(e[c])||o(e[c])))f=e[c++];this.emit(`option:${d.name()}`,f)}else this.emit(`option:${d.name()}`);a=d.variadic?d:null;continue}}if(u.length>2&&u[0]==="-"&&u[1]!=="-"){let d=this._findOption(`-${u[1]}`);if(d){if(d.required||d.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${d.name()}`,u.slice(2));else this.emit(`option:${d.name()}`),l=`-${u.slice(2)}`;continue}}if(/^--[^=]+=/.test(u)){let d=u.indexOf("="),f=this._findOption(u.slice(0,d));if(f&&(f.required||f.optional)){this.emit(`option:${f.name()}`,u.slice(d+1));continue}}if(r===t&&s(u)&&!(this.commands.length===0&&o(u)))r=n;if((this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(u)){t.push(u),n.push(...e.slice(c));break}else if(this._getHelpCommand()&&u===this._getHelpCommand().name()){t.push(u,...e.slice(c));break}else if(this._defaultCommandName){n.push(u,...e.slice(c));break}}if(this._passThroughOptions){r.push(u,...e.slice(c));break}r.push(u)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let r=this.options[n].attributeName();e[r]=r===this._versionOptionName?this._version:this[r]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){if(this._outputConfiguration.outputError(`${e}
|
|
22
23
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
23
24
|
`);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`
|
|
24
|
-
`),this.outputHelp({error:!0});let
|
|
25
|
-
`),this._exit(0,"commander.version",
|
|
26
|
-
Expecting one of '${
|
|
27
|
-
`)}),this}_outputHelpIfRequested(Z){let Y=this._getHelpOption();if(Y&&Z.find((Q)=>Y.is(Q)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function zX(Z){return Z.map((Y)=>{if(!Y.startsWith("--inspect"))return Y;let X,Q="127.0.0.1",$="9229",W;if((W=Y.match(/^(--inspect(-brk)?)$/))!==null)X=W[1];else if((W=Y.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(X=W[1],/^\d+$/.test(W[3]))$=W[3];else Q=W[3];else if((W=Y.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)X=W[1],Q=W[3],$=W[4];if(X&&$!=="0")return`${X}=${Q}:${parseInt($)+1}`;return Y})}function o8(){if(l.env.NO_COLOR||l.env.FORCE_COLOR==="0"||l.env.FORCE_COLOR==="false")return!1;if(l.env.FORCE_COLOR||l.env.CLICOLOR_FORCE!==void 0)return!0;return}MU.Command=n8;MU.useColor=o8});var GX=E1((AU)=>{var{Argument:qX}=l6(),{Command:a8}=VX(),{CommanderError:wU,InvalidArgumentError:UX}=L2(),{Help:DU}=d8(),{Option:HX}=c8();AU.program=new a8;AU.createCommand=(Z)=>new a8(Z);AU.createOption=(Z,Y)=>new HX(Z,Y);AU.createArgument=(Z,Y)=>new qX(Z,Y);AU.Command=a8;AU.Option=HX;AU.Argument=qX;AU.Help=DU;AU.CommanderError=wU;AU.InvalidArgumentError=UX;AU.InvalidOptionArgumentError=UX});var M2=E1((dD,r8)=>{var n6=process||{},BX=n6.argv||[],o6=n6.env||{},bU=!(!!o6.NO_COLOR||BX.includes("--no-color"))&&(!!o6.FORCE_COLOR||BX.includes("--color")||n6.platform==="win32"||(n6.stdout||{}).isTTY&&o6.TERM!=="dumb"||!!o6.CI),xU=(Z,Y,X=Z)=>(Q)=>{let $=""+Q,W=$.indexOf(Y,Z.length);return~W?Z+kU($,Y,X,W)+Y:Z+$+Y},kU=(Z,Y,X,Q)=>{let $="",W=0;do $+=Z.substring(W,Q)+X,W=Q+Y.length,Q=Z.indexOf(Y,W);while(~Q);return $+Z.substring(W)},LX=(Z=bU)=>{let Y=Z?xU:()=>String;return{isColorSupported:Z,reset:Y("\x1B[0m","\x1B[0m"),bold:Y("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:Y("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:Y("\x1B[3m","\x1B[23m"),underline:Y("\x1B[4m","\x1B[24m"),inverse:Y("\x1B[7m","\x1B[27m"),hidden:Y("\x1B[8m","\x1B[28m"),strikethrough:Y("\x1B[9m","\x1B[29m"),black:Y("\x1B[30m","\x1B[39m"),red:Y("\x1B[31m","\x1B[39m"),green:Y("\x1B[32m","\x1B[39m"),yellow:Y("\x1B[33m","\x1B[39m"),blue:Y("\x1B[34m","\x1B[39m"),magenta:Y("\x1B[35m","\x1B[39m"),cyan:Y("\x1B[36m","\x1B[39m"),white:Y("\x1B[37m","\x1B[39m"),gray:Y("\x1B[90m","\x1B[39m"),bgBlack:Y("\x1B[40m","\x1B[49m"),bgRed:Y("\x1B[41m","\x1B[49m"),bgGreen:Y("\x1B[42m","\x1B[49m"),bgYellow:Y("\x1B[43m","\x1B[49m"),bgBlue:Y("\x1B[44m","\x1B[49m"),bgMagenta:Y("\x1B[45m","\x1B[49m"),bgCyan:Y("\x1B[46m","\x1B[49m"),bgWhite:Y("\x1B[47m","\x1B[49m"),blackBright:Y("\x1B[90m","\x1B[39m"),redBright:Y("\x1B[91m","\x1B[39m"),greenBright:Y("\x1B[92m","\x1B[39m"),yellowBright:Y("\x1B[93m","\x1B[39m"),blueBright:Y("\x1B[94m","\x1B[39m"),magentaBright:Y("\x1B[95m","\x1B[39m"),cyanBright:Y("\x1B[96m","\x1B[39m"),whiteBright:Y("\x1B[97m","\x1B[39m"),bgBlackBright:Y("\x1B[100m","\x1B[49m"),bgRedBright:Y("\x1B[101m","\x1B[49m"),bgGreenBright:Y("\x1B[102m","\x1B[49m"),bgYellowBright:Y("\x1B[103m","\x1B[49m"),bgBlueBright:Y("\x1B[104m","\x1B[49m"),bgMagentaBright:Y("\x1B[105m","\x1B[49m"),bgCyanBright:Y("\x1B[106m","\x1B[49m"),bgWhiteBright:Y("\x1B[107m","\x1B[49m")}};r8.exports=LX();r8.exports.createColors=LX});var DX=E1((lD,wX)=>{var j9=1000,C9=j9*60,S9=C9*60,J9=S9*24,hU=J9*7,gU=J9*365.25;wX.exports=function(Z,Y){Y=Y||{};var X=typeof Z;if(X==="string"&&Z.length>0)return uU(Z);else if(X==="number"&&isFinite(Z))return Y.long?pU(Z):mU(Z);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(Z))};function uU(Z){if(Z=String(Z),Z.length>100)return;var Y=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(Z);if(!Y)return;var X=parseFloat(Y[1]),Q=(Y[2]||"ms").toLowerCase();switch(Q){case"years":case"year":case"yrs":case"yr":case"y":return X*gU;case"weeks":case"week":case"w":return X*hU;case"days":case"day":case"d":return X*J9;case"hours":case"hour":case"hrs":case"hr":case"h":return X*S9;case"minutes":case"minute":case"mins":case"min":case"m":return X*C9;case"seconds":case"second":case"secs":case"sec":case"s":return X*j9;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return X;default:return}}function mU(Z){var Y=Math.abs(Z);if(Y>=J9)return Math.round(Z/J9)+"d";if(Y>=S9)return Math.round(Z/S9)+"h";if(Y>=C9)return Math.round(Z/C9)+"m";if(Y>=j9)return Math.round(Z/j9)+"s";return Z+"ms"}function pU(Z){var Y=Math.abs(Z);if(Y>=J9)return t6(Z,Y,J9,"day");if(Y>=S9)return t6(Z,Y,S9,"hour");if(Y>=C9)return t6(Z,Y,C9,"minute");if(Y>=j9)return t6(Z,Y,j9,"second");return Z+" ms"}function t6(Z,Y,X,Q){var $=Y>=X*1.5;return Math.round(Z/X)+" "+Q+($?"s":"")}});var t8=E1((iD,AX)=>{function dU(Z){X.debug=X,X.default=X,X.coerce=V,X.disable=J,X.enable=$,X.enabled=z,X.humanize=DX(),X.destroy=q,Object.keys(Z).forEach((U)=>{X[U]=Z[U]}),X.names=[],X.skips=[],X.formatters={};function Y(U){let H=0;for(let G=0;G<U.length;G++)H=(H<<5)-H+U.charCodeAt(G),H|=0;return X.colors[Math.abs(H)%X.colors.length]}X.selectColor=Y;function X(U){let H,G=null,K,M;function E(...O){if(!E.enabled)return;let T=E,i=Number(new Date),g=i-(H||i);if(T.diff=g,T.prev=H,T.curr=i,H=i,O[0]=X.coerce(O[0]),typeof O[0]!=="string")O.unshift("%O");let Z1=0;O[0]=O[0].replace(/%([a-zA-Z%])/g,(W1,A0)=>{if(W1==="%%")return"%";Z1++;let z0=X.formatters[A0];if(typeof z0==="function"){let W9=O[Z1];W1=z0.call(T,W9),O.splice(Z1,1),Z1--}return W1}),X.formatArgs.call(T,O),(T.log||X.log).apply(T,O)}if(E.namespace=U,E.useColors=X.useColors(),E.color=X.selectColor(U),E.extend=Q,E.destroy=X.destroy,Object.defineProperty(E,"enabled",{enumerable:!0,configurable:!1,get:()=>{if(G!==null)return G;if(K!==X.namespaces)K=X.namespaces,M=X.enabled(U);return M},set:(O)=>{G=O}}),typeof X.init==="function")X.init(E);return E}function Q(U,H){let G=X(this.namespace+(typeof H==="undefined"?":":H)+U);return G.log=this.log,G}function $(U){X.save(U),X.namespaces=U,X.names=[],X.skips=[];let H=(typeof U==="string"?U:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let G of H)if(G[0]==="-")X.skips.push(G.slice(1));else X.names.push(G)}function W(U,H){let G=0,K=0,M=-1,E=0;while(G<U.length)if(K<H.length&&(H[K]===U[G]||H[K]==="*"))if(H[K]==="*")M=K,E=G,K++;else G++,K++;else if(M!==-1)K=M+1,E++,G=E;else return!1;while(K<H.length&&H[K]==="*")K++;return K===H.length}function J(){let U=[...X.names,...X.skips.map((H)=>"-"+H)].join(",");return X.enable(""),U}function z(U){for(let H of X.skips)if(W(U,H))return!1;for(let H of X.names)if(W(U,H))return!0;return!1}function V(U){if(U instanceof Error)return U.stack||U.message;return U}function q(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return X.enable(X.load()),X}AX.exports=dU});var OX=E1((EX,e6)=>{EX.formatArgs=lU;EX.save=iU;EX.load=oU;EX.useColors=cU;EX.storage=nU();EX.destroy=(()=>{let Z=!1;return()=>{if(!Z)Z=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}})();EX.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function cU(){if(typeof window!=="undefined"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let Z;return typeof document!=="undefined"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window!=="undefined"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator!=="undefined"&&navigator.userAgent&&(Z=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(Z[1],10)>=31||typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function lU(Z){if(Z[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+Z[0]+(this.useColors?"%c ":" ")+"+"+e6.exports.humanize(this.diff),!this.useColors)return;let Y="color: "+this.color;Z.splice(1,0,Y,"color: inherit");let X=0,Q=0;Z[0].replace(/%[a-zA-Z%]/g,($)=>{if($==="%%")return;if(X++,$==="%c")Q=X}),Z.splice(Q,0,Y)}EX.log=console.debug||console.log||(()=>{});function iU(Z){try{if(Z)EX.storage.setItem("debug",Z);else EX.storage.removeItem("debug")}catch(Y){}}function oU(){let Z;try{Z=EX.storage.getItem("debug")||EX.storage.getItem("DEBUG")}catch(Y){}if(!Z&&typeof process!=="undefined"&&"env"in process)Z=process.env.DEBUG;return Z}function nU(){try{return localStorage}catch(Z){}}e6.exports=t8()(EX);var{formatters:aU}=e6.exports;aU.j=function(Z){try{return JSON.stringify(Z)}catch(Y){return"[UnexpectedJSONParseError]: "+Y.message}}});var RX=E1((TX,Y4)=>{var QH=O0("tty"),Z4=O0("util");TX.init=UH;TX.log=zH;TX.formatArgs=WH;TX.save=VH;TX.load=qH;TX.useColors=$H;TX.destroy=Z4.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");TX.colors=[6,2,3,4,5,1];try{let Z=(()=>{throw new Error("Cannot require module "+"supports-color");})();if(Z&&(Z.stderr||Z).level>=2)TX.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221]}catch(Z){}TX.inspectOpts=Object.keys(process.env).filter((Z)=>{return/^debug_/i.test(Z)}).reduce((Z,Y)=>{let X=Y.substring(6).toLowerCase().replace(/_([a-z])/g,($,W)=>{return W.toUpperCase()}),Q=process.env[Y];if(/^(yes|on|true|enabled)$/i.test(Q))Q=!0;else if(/^(no|off|false|disabled)$/i.test(Q))Q=!1;else if(Q==="null")Q=null;else Q=Number(Q);return Z[X]=Q,Z},{});function $H(){return"colors"in TX.inspectOpts?Boolean(TX.inspectOpts.colors):QH.isatty(process.stderr.fd)}function WH(Z){let{namespace:Y,useColors:X}=this;if(X){let Q=this.color,$="\x1B[3"+(Q<8?Q:"8;5;"+Q),W=` ${$};1m${Y} \x1B[0m`;Z[0]=W+Z[0].split(`
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
`)
|
|
31
|
-
`).
|
|
32
|
-
`)}function
|
|
33
|
-
`)
|
|
34
|
-
`)
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
`);z=V[0],J=V[1]}yield{file:W,key:z,value:J}}}var u5,eH=D({"src/lib/responses/ConfigList.ts"(){_(),u5=class{constructor(){this.files=[],this.values=Object.create(null)}get all(){if(!this._all)this._all=this.files.reduce((Z,Y)=>{return Object.assign(Z,this.values[Y])},{});return this._all}addFile(Z){if(!(Z in this.values)){let Y=q9(this.files);this.values[Z]=Y?Object.create(this.values[Y]):{},this.files.push(Z)}return this.values[Z]}addValue(Z,Y,X){let Q=this.addFile(Z);if(!Object.hasOwn(Q,Y))Q[Y]=X;else if(Array.isArray(Q[Y]))Q[Y].push(X);else Q[Y]=[Q[Y],X];this._all=void 0}}}});function $Z(Z,Y){if(typeof Z==="string"&&Object.hasOwn(FZ,Z))return Z;return Y}function ZG(Z,Y,X,Q){let $=["config",`--${Q}`];if(X)$.push("--add");return $.push(Z,Y),{commands:$,format:"utf-8",parser(W){return W}}}function YG(Z,Y){let X=["config","--null","--show-origin","--get-all",Z];if(Y)X.splice(1,0,`--${Y}`);return{commands:X,format:"utf-8",parser(Q){return sH(Q,Z)}}}function XG(Z){let Y=["config","--list","--show-origin","--null"];if(Z)Y.push(`--${Z}`);return{commands:Y,format:"utf-8",parser(X){return rH(X)}}}function QG(){return{addConfig(Z,Y,...X){return this._runTask(ZG(Z,Y,X[0]===!0,$Z(X[1],"local")),z1(arguments))},getConfig(Z,Y){return this._runTask(YG(Z,$Z(Y,void 0)),z1(arguments))},listConfig(...Z){return this._runTask(XG($Z(Z[0],void 0)),z1(arguments))}}}var FZ,m5=D({"src/lib/tasks/config.ts"(){eH(),_(),FZ=((Z)=>{return Z.system="system",Z.global="global",Z.local="local",Z.worktree="worktree",Z})(FZ||{})}});function $G(Z){return p5.has(Z)}var WZ,p5,d5=D({"src/lib/tasks/diff-name-status.ts"(){WZ=((Z)=>{return Z.ADDED="A",Z.COPIED="C",Z.DELETED="D",Z.MODIFIED="M",Z.RENAMED="R",Z.CHANGED="T",Z.UNMERGED="U",Z.UNKNOWN="X",Z.BROKEN="B",Z})(WZ||{}),p5=new Set(Object.values(WZ))}});function WG(...Z){return new l5().param(...Z)}function JG(Z){let Y=new Set,X={};return TZ(Z,(Q)=>{let[$,W,J]=Q.split(b9);Y.add($),(X[$]=X[$]||[]).push({line:a(W),path:$,preview:J})}),{paths:Y,results:X}}function zG(){return{grep(Z){let Y=z1(arguments),X=y1(arguments);for(let $ of c5)if(X.includes($))return this._runTask(b1(`git.grep: use of "${$}" is not supported.`),Y);if(typeof Z==="string")Z=WG().param(Z);let Q=["grep","--null","-n","--full-name",...X,...Z];return this._runTask({commands:Q,format:"utf-8",parser($){return JG($)}},Y)}}}var c5,N2,bX,l5,i5=D({"src/lib/tasks/grep.ts"(){_(),U1(),c5=["-h"],N2=Symbol("grepQuery"),l5=class{constructor(){this[bX]=[]}*[(bX=N2,Symbol.iterator)](){for(let Z of this[N2])yield Z}and(...Z){return Z.length&&this[N2].push("--and","(",...w2(Z,"-e"),")"),this}param(...Z){return this[N2].push(...w2(Z,"-e")),this}}}}),o5={};H1(o5,{ResetMode:()=>$4,getResetMode:()=>qG,resetTask:()=>VG});function VG(Z,Y){let X=["reset"];if(n5(Z))X.push(`--${Z}`);return X.push(...Y),j1(X)}function qG(Z){if(n5(Z))return Z;switch(typeof Z){case"string":case"undefined":return"soft"}return}function n5(Z){return typeof Z==="string"&&a5.includes(Z)}var $4,a5,r5=D({"src/lib/tasks/reset.ts"(){_(),U1(),$4=((Z)=>{return Z.MIXED="mixed",Z.SOFT="soft",Z.HARD="hard",Z.MERGE="merge",Z.KEEP="keep",Z})($4||{}),a5=k9(Object.values($4))}});function UG(){return U4.default("simple-git")}function xX(Z,Y,X){if(!Y||!String(Y).replace(/\s*/,""))return!X?Z:(Q,...$)=>{Z(Q,...$),X(Q,...$)};return(Q,...$)=>{if(Z(`%s ${Q}`,Y,...$),X)X(Q,...$)}}function HG(Z,Y,{namespace:X}){if(typeof Z==="string")return Z;let Q=Y&&Y.namespace||"";if(Q.startsWith(X))return Q.substr(X.length+1);return Q||X}function kZ(Z,Y,X,Q=UG()){let $=Z&&`[${Z}]`||"",W=[],J=typeof Y==="string"?Q.extend(Y):Y,z=HG(l1(Y,D1),J,Q);return q(X);function V(U,H){return d(W,kZ(Z,z.replace(/^[^:]+/,U),H,Q))}function q(U){let H=U&&`[${U}]`||"",G=J&&xX(J,H)||U9,K=xX(Q,`${$} ${H}`,G);return Object.assign(J?G:K,{label:Z,sibling:V,info:K,step:q})}}var s5=D({"src/lib/git-logger.ts"(){_(),U4.default.formatters.L=(Z)=>String(F4(Z)?Z.length:"-"),U4.default.formatters.B=(Z)=>{if(Buffer.isBuffer(Z))return Z.toString("utf8");return P2(Z)}}}),t5,GG=D({"src/lib/runners/tasks-pending-queue.ts"(){m0(),s5(),t5=class Z{constructor(Y="GitExecutor"){this.logLabel=Y,this._queue=new Map}withProgress(Y){return this._queue.get(Y)}createProgress(Y){let X=Z.getName(Y.commands[0]),Q=kZ(this.logLabel,X);return{task:Y,logger:Q,name:X}}push(Y){let X=this.createProgress(Y);return X.logger("Adding task to the queue, commands = %o",Y.commands),this._queue.set(Y,X),X}fatal(Y){for(let[X,{logger:Q}]of Array.from(this._queue.entries())){if(X===Y.task)Q.info("Failed %o",Y),Q("Fatal exception, any as-yet un-started tasks run through this executor will not be attempted");else Q.info("A fatal exception occurred in a previous task, the queue has been purged: %o",Y.message);this.complete(X)}if(this._queue.size!==0)throw new Error(`Queue size should be zero after fatal: ${this._queue.size}`)}complete(Y){if(this.withProgress(Y))this._queue.delete(Y)}attempt(Y){let X=this.withProgress(Y);if(!X)throw new I0(void 0,"TasksPendingQueue: attempt called for an unknown task");return X.logger("Starting task"),X}static getName(Y="empty"){return`task:${Y}:${++Z.counter}`}static{this.counter=0}}}});function V9(Z,Y){return{method:B5(Z.commands)||"",commands:Y}}function BG(Z,Y){return(X)=>{Y("[ERROR] child process exception %o",X),Z.push(Buffer.from(String(X.stack),"ascii"))}}function kX(Z,Y,X,Q){return($)=>{X("%s received %L bytes",Y,$),Q("%B",$),Z.push($)}}var NZ,LG=D({"src/lib/runners/git-executor-chain.ts"(){m0(),U1(),_(),GG(),NZ=class{constructor(Z,Y,X){this._executor=Z,this._scheduler=Y,this._plugins=X,this._chain=Promise.resolve(),this._queue=new t5}get cwd(){return this._cwd||this._executor.cwd}set cwd(Z){this._cwd=Z}get env(){return this._executor.env}get outputHandler(){return this._executor.outputHandler}chain(){return this}push(Z){return this._queue.push(Z),this._chain=this._chain.then(()=>this.attemptTask(Z))}async attemptTask(Z){let Y=await this._scheduler.next(),X=()=>this._queue.complete(Z);try{let{logger:Q}=this._queue.attempt(Z);return await(k5(Z)?this.attemptEmptyTask(Z,Q):this.attemptRemoteTask(Z,Q))}catch(Q){throw this.onFatalException(Z,Q)}finally{X(),Y()}}onFatalException(Z,Y){let X=Y instanceof I0?Object.assign(Y,{task:Z}):new I0(Z,Y&&String(Y));return this._chain=Promise.resolve(),this._queue.fatal(X),X}async attemptRemoteTask(Z,Y){let X=this._plugins.exec("spawn.binary","",V9(Z,Z.commands)),Q=this._plugins.exec("spawn.args",[...Z.commands],V9(Z,Z.commands)),$=await this.gitResponse(Z,X,Q,this.outputHandler,Y.step("SPAWN")),W=await this.handleTaskData(Z,Q,$,Y.step("HANDLE"));if(Y("passing response to task's parser as a %s",Z.format),x5(Z))return BZ(Z.parser,W);return BZ(Z.parser,W.asStrings())}async attemptEmptyTask(Z,Y){return Y("empty task bypassing child process to call to task's parser"),Z.parser(this)}handleTaskData(Z,Y,X,Q){let{exitCode:$,rejection:W,stdOut:J,stdErr:z}=X;return new Promise((V,q)=>{Q("Preparing to handle process response exitCode=%d stdOut=",$);let{error:U}=this._plugins.exec("task.error",{error:W},{...V9(Z,Y),...X});if(U&&Z.onError)return Q.info("exitCode=%s handling with custom error handler"),Z.onError(X,U,(H)=>{Q.info("custom error handler treated as success"),Q("custom error returned a %s",P2(H)),V(new q4(Array.isArray(H)?Buffer.concat(H):H,Buffer.concat(z)))},q);if(U)return Q.info("handling as error: exitCode=%s stdErr=%s rejection=%o",$,z.length,W),q(U);Q.info("retrieving task output complete"),V(new q4(Buffer.concat(J),Buffer.concat(z)))})}async gitResponse(Z,Y,X,Q,$){let W=$.sibling("output"),J=this._plugins.exec("spawn.options",{cwd:this.cwd,env:this.env,windowsHide:!0},V9(Z,Z.commands));return new Promise((z)=>{let V=[],q=[];$.info("%s %o",Y,X),$("%O",J);let U=this._beforeSpawn(Z,X);if(U)return z({stdOut:V,stdErr:q,exitCode:9901,rejection:U});this._plugins.exec("spawn.before",void 0,{...V9(Z,X),kill(G){U=G||U}});let H=KG(Y,X,J);if(H.stdout.on("data",kX(V,"stdOut",$,W.step("stdOut"))),H.stderr.on("data",kX(q,"stdErr",$,W.step("stdErr"))),H.on("error",BG(q,$)),Q)$("Passing child process stdOut/stdErr to custom outputHandler"),Q(Y,H.stdout,H.stderr,[...X]);this._plugins.exec("spawn.after",void 0,{...V9(Z,X),spawned:H,close(G,K){z({stdOut:V,stdErr:q,exitCode:G,rejection:U||K})},kill(G){if(H.killed)return;U=G,H.kill("SIGINT")}})})}_beforeSpawn(Z,Y){let X;return this._plugins.exec("spawn.before",void 0,{...V9(Z,Y),kill(Q){X=Q||X}}),X}}}}),e5={};H1(e5,{GitExecutor:()=>ZQ});var ZQ,MG=D({"src/lib/runners/git-executor.ts"(){LG(),ZQ=class{constructor(Z,Y,X){this.cwd=Z,this._scheduler=Y,this._plugins=X,this._chain=new NZ(this,this._scheduler,this._plugins)}chain(){return new NZ(this,this._scheduler,this._plugins)}push(Z){return this._chain.push(Z)}}}});function FG(Z,Y,X=U9){let Q=(W)=>{X(null,W)},$=(W)=>{if(W?.task===Z)X(W instanceof E2?NG(W):W,void 0)};Y.then(Q,$)}function NG(Z){let Y=(Q)=>{console.warn(`simple-git deprecation notice: accessing GitResponseError.${Q} should be GitResponseError.git.${Q}, this will no longer be available in version 3`),Y=U9};return Object.create(Z,Object.getOwnPropertyNames(Z.git).reduce(X,{}));function X(Q,$){if($ in Z)return Q;return Q[$]={enumerable:!1,configurable:!1,get(){return Y($),Z.git[$]}},Q}}var wG=D({"src/lib/task-callback.ts"(){x9(),_()}});function vX(Z,Y){return y5((X)=>{if(!IZ(Z))throw new Error(`Git.cwd: cannot change to non-directory "${Z}"`);return(Y||X).cwd=Z})}var DG=D({"src/lib/tasks/change-working-directory.ts"(){_(),U1()}});function JZ(Z){let Y=["checkout",...Z];if(Y[1]==="-b"&&Y.includes("-B"))Y[1]=B4(Y,"-B");return j1(Y)}function AG(){return{checkout(){return this._runTask(JZ(y1(arguments,1)),z1(arguments))},checkoutBranch(Z,Y){return this._runTask(JZ(["-b",Z,Y,...y1(arguments)]),z1(arguments))},checkoutLocalBranch(Z){return this._runTask(JZ(["-b",Z,...y1(arguments)]),z1(arguments))}}}var EG=D({"src/lib/tasks/checkout.ts"(){_(),U1()}});function OG(){return{count:0,garbage:0,inPack:0,packs:0,prunePackable:0,size:0,sizeGarbage:0,sizePack:0}}function PG(){return{countObjects(){return this._runTask({commands:["count-objects","--verbose"],format:"utf-8",parser(Z){return x1(OG(),[YQ],Z)}})}}}var YQ,TG=D({"src/lib/tasks/count-objects.ts"(){_(),YQ=new k(/([a-z-]+): (\d+)$/,(Z,[Y,X])=>{let Q=F5(Y);if(Object.hasOwn(Z,Q))Z[Q]=a(X)})}});function IG(Z){return x1({author:null,branch:"",commit:"",root:!1,summary:{changes:0,insertions:0,deletions:0}},XQ,Z)}var XQ,RG=D({"src/lib/parsers/parse-commit.ts"(){_(),XQ=[new k(/^\[([^\s]+)( \([^)]+\))? ([^\]]+)/,(Z,[Y,X,Q])=>{Z.branch=Y,Z.commit=Q,Z.root=!!X}),new k(/\s*Author:\s(.+)/i,(Z,[Y])=>{let X=Y.split("<"),Q=X.pop();if(!Q||!Q.includes("@"))return;Z.author={email:Q.substr(0,Q.length-1),name:X.join("<").trim()}}),new k(/(\d+)[^,]*(?:,\s*(\d+)[^,]*)(?:,\s*(\d+))/g,(Z,[Y,X,Q])=>{Z.summary.changes=parseInt(Y,10)||0,Z.summary.insertions=parseInt(X,10)||0,Z.summary.deletions=parseInt(Q,10)||0}),new k(/^(\d+)[^,]*(?:,\s*(\d+)[^(]+\(([+-]))?/,(Z,[Y,X,Q])=>{Z.summary.changes=parseInt(Y,10)||0;let $=parseInt(X,10)||0;if(Q==="-")Z.summary.deletions=$;else if(Q==="+")Z.summary.insertions=$})]}});function jG(Z,Y,X){return{commands:["-c","core.abbrev=40","commit",...w2(Z,"-m"),...Y,...X],format:"utf-8",parser:IG}}function CG(){return{commit(Y,...X){let Q=z1(arguments),$=Z(Y)||jG(L0(Y),L0(l1(X[0],V4,[])),[...k9(l1(X[1],T2,[])),...y1(arguments,0,!0)]);return this._runTask($,Q)}};function Z(Y){return!V4(Y)&&b1("git.commit: requires the commit message to be supplied as a string/string[]")}}var SG=D({"src/lib/tasks/commit.ts"(){RG(),_(),U1()}});function _G(){return{firstCommit(){return this._runTask(j1(["rev-list","--max-parents=0","HEAD"],!0),z1(arguments))}}}var yG=D({"src/lib/tasks/first-commit.ts"(){_(),U1()}});function bG(Z,Y){let X=["hash-object",Z];if(Y)X.push("-w");return j1(X,!0)}var xG=D({"src/lib/tasks/hash-object.ts"(){U1()}});function kG(Z,Y,X){let Q=String(X).trim(),$;if($=QQ.exec(Q))return new W4(Z,Y,!1,$[1]);if($=$Q.exec(Q))return new W4(Z,Y,!0,$[1]);let W="",J=Q.split(" ");while(J.length)if(J.shift()==="in"){W=J.join(" ");break}return new W4(Z,Y,/^re/i.test(Q),W)}var W4,QQ,$Q,vG=D({"src/lib/responses/InitSummary.ts"(){W4=class{constructor(Z,Y,X,Q){this.bare=Z,this.path=Y,this.existing=X,this.gitDir=Q}},QQ=/^Init.+ repository in (.+)$/,$Q=/^Rein.+ in (.+)$/}});function fG(Z){return Z.includes(vZ)}function hG(Z=!1,Y,X){let Q=["init",...X];if(Z&&!fG(Q))Q.splice(1,0,vZ);return{commands:Q,format:"utf-8",parser($){return kG(Q.includes("--bare"),Y,$)}}}var vZ,gG=D({"src/lib/tasks/init.ts"(){vG(),vZ="--bare"}});function fZ(Z){for(let Y=0;Y<Z.length;Y++){let X=hZ.exec(Z[Y]);if(X)return`--${X[1]}`}return""}function uG(Z){return hZ.test(Z)}var hZ,I2=D({"src/lib/args/log-format.ts"(){hZ=/^--(stat|numstat|name-only|name-status)(=|$)/}}),WQ,mG=D({"src/lib/responses/DiffSummary.ts"(){WQ=class{constructor(){this.changed=0,this.deletions=0,this.insertions=0,this.files=[]}}}});function JQ(Z=""){let Y=zQ[Z];return(X)=>x1(new WQ,Y,X,!1)}var zZ,fX,hX,gX,zQ,VQ=D({"src/lib/parsers/parse-diff-summary.ts"(){I2(),mG(),d5(),_(),zZ=[new k(/^(.+)\s+\|\s+(\d+)(\s+[+\-]+)?$/,(Z,[Y,X,Q=""])=>{Z.files.push({file:Y.trim(),changes:a(X),insertions:Q.replace(/[^+]/g,"").length,deletions:Q.replace(/[^-]/g,"").length,binary:!1})}),new k(/^(.+) \|\s+Bin ([0-9.]+) -> ([0-9.]+) ([a-z]+)/,(Z,[Y,X,Q])=>{Z.files.push({file:Y.trim(),before:a(X),after:a(Q),binary:!0})}),new k(/(\d+) files? changed\s*((?:, \d+ [^,]+){0,2})/,(Z,[Y,X])=>{let Q=/(\d+) i/.exec(X),$=/(\d+) d/.exec(X);Z.changed=a(Y),Z.insertions=a(Q?.[1]),Z.deletions=a($?.[1])})],fX=[new k(/(\d+)\t(\d+)\t(.+)$/,(Z,[Y,X,Q])=>{let $=a(Y),W=a(X);Z.changed++,Z.insertions+=$,Z.deletions+=W,Z.files.push({file:Q,changes:$+W,insertions:$,deletions:W,binary:!1})}),new k(/-\t-\t(.+)$/,(Z,[Y])=>{Z.changed++,Z.files.push({file:Y,after:0,before:0,binary:!0})})],hX=[new k(/(.+)$/,(Z,[Y])=>{Z.changed++,Z.files.push({file:Y,changes:0,insertions:0,deletions:0,binary:!1})})],gX=[new k(/([ACDMRTUXB])([0-9]{0,3})\t(.[^\t]*)(\t(.[^\t]*))?$/,(Z,[Y,X,Q,$,W])=>{Z.changed++,Z.files.push({file:W??Q,changes:0,insertions:0,deletions:0,binary:!1,status:HZ($G(Y)&&Y),from:HZ(!!W&&Q!==W&&Q),similarity:a(X)})})],zQ={[""]:zZ,["--stat"]:zZ,["--numstat"]:fX,["--name-status"]:gX,["--name-only"]:hX}}});function pG(Z,Y){return Y.reduce((X,Q,$)=>{return X[Q]=Z[$]||"",X},Object.create({diff:null}))}function qQ(Z=mZ,Y=UQ,X=""){let Q=JQ(X);return function($){let W=O2($.trim(),!1,gZ).map(function(J){let z=J.split(uZ),V=pG(z[0].split(Z),Y);if(z.length>1&&!!z[1].trim())V.diff=Q(z[1]);return V});return{all:W,latest:W.length&&W[0]||null,total:W.length}}}var gZ,uZ,mZ,UQ,HQ=D({"src/lib/parsers/parse-list-log-summary.ts"(){_(),VQ(),I2(),gZ="òòòòòò ",uZ=" òò",mZ=" ò ",UQ=["hash","date","message","refs","author_name","author_email"]}}),GQ={};H1(GQ,{diffSummaryTask:()=>dG,validateLogFormatConfig:()=>D4});function dG(Z){let Y=fZ(Z),X=["diff"];if(Y==="")Y="--stat",X.push("--stat=4096");return X.push(...Z),D4(X)||{commands:X,format:"utf-8",parser:JQ(Y)}}function D4(Z){let Y=Z.filter(uG);if(Y.length>1)return b1(`Summary flags are mutually exclusive - pick one of ${Y.join(",")}`);if(Y.length&&Z.includes("-z"))return b1(`Summary flag ${Y} parsing is not compatible with null termination option '-z'`)}var pZ=D({"src/lib/tasks/diff.ts"(){I2(),VQ(),U1()}});function cG(Z,Y){let X=[],Q=[];return Object.keys(Z).forEach(($)=>{X.push($),Q.push(String(Z[$]))}),[X,Q.join(Y)]}function lG(Z){return Object.keys(Z).reduce((Y,X)=>{if(!(X in wZ))Y[X]=Z[X];return Y},{})}function KQ(Z={},Y=[]){let X=l1(Z.splitter,D1,mZ),Q=M4(Z.format)?Z.format:{hash:"%H",date:Z.strictDate===!1?"%ai":"%aI",message:"%s",refs:"%D",body:Z.multiLine?"%B":"%b",author_name:Z.mailMap!==!1?"%aN":"%an",author_email:Z.mailMap!==!1?"%aE":"%ae"},[$,W]=cG(Q,X),J=[],z=[`--pretty=format:${gZ}${W}${uZ}`,...Y],V=Z.n||Z["max-count"]||Z.maxCount;if(V)z.push(`--max-count=${V}`);if(Z.from||Z.to){let q=Z.symmetric!==!1?"...":"..";J.push(`${Z.from||""}${q}${Z.to||""}`)}if(D1(Z.file))z.push("--follow",SH(Z.file));return jZ(lG(Z),z),{fields:$,splitter:X,commands:[...z,...J]}}function iG(Z,Y,X){let Q=qQ(Z,Y,fZ(X));return{commands:["log",...X],format:"utf-8",parser:Q}}function oG(){return{log(...X){let Q=z1(arguments),$=KQ(CZ(arguments),k9(l1(arguments[0],T2,[]))),W=Y(...X)||D4($.commands)||Z($);return this._runTask(W,Q)}};function Z(X){return iG(X.splitter,X.fields,X.commands)}function Y(X,Q){return D1(X)&&D1(Q)&&b1("git.log(string, string) should be replaced with git.log({ from: string, to: string })")}}var wZ,BQ=D({"src/lib/tasks/log.ts"(){I2(),A2(),HQ(),_(),U1(),pZ(),wZ=((Z)=>{return Z[Z["--pretty"]=0]="--pretty",Z[Z["max-count"]=1]="max-count",Z[Z.maxCount=2]="maxCount",Z[Z.n=3]="n",Z[Z.file=4]="file",Z[Z.format=5]="format",Z[Z.from=6]="from",Z[Z.to=7]="to",Z[Z.splitter=8]="splitter",Z[Z.symmetric=9]="symmetric",Z[Z.mailMap=10]="mailMap",Z[Z.multiLine=11]="multiLine",Z[Z.strictDate=12]="strictDate",Z})(wZ||{})}}),J4,LQ,nG=D({"src/lib/responses/MergeSummary.ts"(){J4=class{constructor(Z,Y=null,X){this.reason=Z,this.file=Y,this.meta=X}toString(){return`${this.file}:${this.reason}`}},LQ=class{constructor(){this.conflicts=[],this.merges=[],this.result="success"}get failed(){return this.conflicts.length>0}get reason(){return this.result}toString(){if(this.conflicts.length)return`CONFLICTS: ${this.conflicts.join(", ")}`;return"OK"}}}}),DZ,MQ,aG=D({"src/lib/responses/PullSummary.ts"(){DZ=class{constructor(){this.remoteMessages={all:[]},this.created=[],this.deleted=[],this.files=[],this.deletions={},this.insertions={},this.summary={changes:0,deletions:0,insertions:0}}},MQ=class{constructor(){this.remote="",this.hash={local:"",remote:""},this.branch={local:"",remote:""},this.message=""}toString(){return this.message}}}});function VZ(Z){return Z.objects=Z.objects||{compressing:0,counting:0,enumerating:0,packReused:0,reused:{count:0,delta:0},total:{count:0,delta:0}}}function uX(Z){let Y=/^\s*(\d+)/.exec(Z),X=/delta (\d+)/i.exec(Z);return{count:a(Y&&Y[1]||"0"),delta:a(X&&X[1]||"0")}}var FQ,rG=D({"src/lib/parsers/parse-remote-objects.ts"(){_(),FQ=[new u0(/^remote:\s*(enumerating|counting|compressing) objects: (\d+),/i,(Z,[Y,X])=>{let Q=Y.toLowerCase(),$=VZ(Z.remoteMessages);Object.assign($,{[Q]:a(X)})}),new u0(/^remote:\s*(enumerating|counting|compressing) objects: \d+% \(\d+\/(\d+)\),/i,(Z,[Y,X])=>{let Q=Y.toLowerCase(),$=VZ(Z.remoteMessages);Object.assign($,{[Q]:a(X)})}),new u0(/total ([^,]+), reused ([^,]+), pack-reused (\d+)/i,(Z,[Y,X,Q])=>{let $=VZ(Z.remoteMessages);$.total=uX(Y),$.reused=uX(X),$.packReused=a(Q)})]}});function NQ(Z,Y){return x1({remoteMessages:new DQ},wQ,Y)}var wQ,DQ,AQ=D({"src/lib/parsers/parse-remote-messages.ts"(){_(),rG(),wQ=[new u0(/^remote:\s*(.+)$/,(Z,[Y])=>{return Z.remoteMessages.all.push(Y.trim()),!1}),...FQ,new u0([/create a (?:pull|merge) request/i,/\s(https?:\/\/\S+)$/],(Z,[Y])=>{Z.remoteMessages.pullRequestUrl=Y}),new u0([/found (\d+) vulnerabilities.+\(([^)]+)\)/i,/\s(https?:\/\/\S+)$/],(Z,[Y,X,Q])=>{Z.remoteMessages.vulnerabilities={count:a(Y),summary:X,url:Q}})],DQ=class{constructor(){this.all=[]}}}});function sG(Z,Y){let X=x1(new MQ,EQ,[Z,Y]);return X.message&&X}var mX,pX,dX,cX,EQ,lX,dZ,OQ=D({"src/lib/parsers/parse-pull.ts"(){aG(),_(),AQ(),mX=/^\s*(.+?)\s+\|\s+\d+\s*(\+*)(-*)/,pX=/(\d+)\D+((\d+)\D+\(\+\))?(\D+(\d+)\D+\(-\))?/,dX=/^(create|delete) mode \d+ (.+)/,cX=[new k(mX,(Z,[Y,X,Q])=>{if(Z.files.push(Y),X)Z.insertions[Y]=X.length;if(Q)Z.deletions[Y]=Q.length}),new k(pX,(Z,[Y,,X,,Q])=>{if(X!==void 0||Q!==void 0)return Z.summary.changes=+Y||0,Z.summary.insertions=+X||0,Z.summary.deletions=+Q||0,!0;return!1}),new k(dX,(Z,[Y,X])=>{d(Z.files,X),d(Y==="create"?Z.created:Z.deleted,X)})],EQ=[new k(/^from\s(.+)$/i,(Z,[Y])=>void(Z.remote=Y)),new k(/^fatal:\s(.+)$/,(Z,[Y])=>void(Z.message=Y)),new k(/([a-z0-9]+)\.\.([a-z0-9]+)\s+(\S+)\s+->\s+(\S+)$/,(Z,[Y,X,Q,$])=>{Z.branch.local=Q,Z.hash.local=Y,Z.branch.remote=$,Z.hash.remote=X})],lX=(Z,Y)=>{return x1(new DZ,cX,[Z,Y])},dZ=(Z,Y)=>{return Object.assign(new DZ,lX(Z,Y),NQ(Z,Y))}}}),iX,PQ,oX,tG=D({"src/lib/parsers/parse-merge.ts"(){nG(),_(),OQ(),iX=[new k(/^Auto-merging\s+(.+)$/,(Z,[Y])=>{Z.merges.push(Y)}),new k(/^CONFLICT\s+\((.+)\): Merge conflict in (.+)$/,(Z,[Y,X])=>{Z.conflicts.push(new J4(Y,X))}),new k(/^CONFLICT\s+\((.+\/delete)\): (.+) deleted in (.+) and/,(Z,[Y,X,Q])=>{Z.conflicts.push(new J4(Y,X,{deleteRef:Q}))}),new k(/^CONFLICT\s+\((.+)\):/,(Z,[Y])=>{Z.conflicts.push(new J4(Y,null))}),new k(/^Automatic merge failed;\s+(.+)$/,(Z,[Y])=>{Z.result=Y})],PQ=(Z,Y)=>{return Object.assign(oX(Z,Y),dZ(Z,Y))},oX=(Z)=>{return x1(new LQ,iX,Z)}}});function nX(Z){if(!Z.length)return b1("Git.merge requires at least one option");return{commands:["merge",...Z],format:"utf-8",parser(Y,X){let Q=PQ(Y,X);if(Q.failed)throw new E2(Q);return Q}}}var eG=D({"src/lib/tasks/merge.ts"(){x9(),tG(),U1()}});function ZK(Z,Y,X){let Q=X.includes("deleted"),$=X.includes("tag")||/^refs\/tags/.test(Z),W=!X.includes("new");return{deleted:Q,tag:$,branch:!$,new:!W,alreadyUpdated:W,local:Z,remote:Y}}var aX,TQ,rX,YK=D({"src/lib/parsers/parse-push.ts"(){_(),AQ(),aX=[new k(/^Pushing to (.+)$/,(Z,[Y])=>{Z.repo=Y}),new k(/^updating local tracking ref '(.+)'/,(Z,[Y])=>{Z.ref={...Z.ref||{},local:Y}}),new k(/^[=*-]\s+([^:]+):(\S+)\s+\[(.+)]$/,(Z,[Y,X,Q])=>{Z.pushed.push(ZK(Y,X,Q))}),new k(/^Branch '([^']+)' set up to track remote branch '([^']+)' from '([^']+)'/,(Z,[Y,X,Q])=>{Z.branch={...Z.branch||{},local:Y,remote:X,remoteName:Q}}),new k(/^([^:]+):(\S+)\s+([a-z0-9]+)\.\.([a-z0-9]+)$/,(Z,[Y,X,Q,$])=>{Z.update={head:{local:Y,remote:X},hash:{from:Q,to:$}}})],TQ=(Z,Y)=>{let X=rX(Z,Y),Q=NQ(Z,Y);return{...X,...Q}},rX=(Z,Y)=>{return x1({pushed:[]},aX,[Z,Y])}}}),IQ={};H1(IQ,{pushTagsTask:()=>XK,pushTask:()=>cZ});function XK(Z={},Y){return d(Y,"--tags"),cZ(Z,Y)}function cZ(Z={},Y){let X=["push",...Y];if(Z.branch)X.splice(1,0,Z.branch);if(Z.remote)X.splice(1,0,Z.remote);return B4(X,"-v"),d(X,"--verbose"),d(X,"--porcelain"),{commands:X,format:"utf-8",parser:TQ}}var RQ=D({"src/lib/tasks/push.ts"(){YK(),_()}});function QK(){return{showBuffer(){let Z=["show",...y1(arguments,1)];if(!Z.includes("--binary"))Z.splice(1,0,"--binary");return this._runTask(b5(Z),z1(arguments))},show(){let Z=["show",...y1(arguments,1)];return this._runTask(j1(Z),z1(arguments))}}}var $K=D({"src/lib/tasks/show.ts"(){_(),U1()}}),sX,jQ,WK=D({"src/lib/responses/FileStatusSummary.ts"(){sX=/^(.+)\0(.+)$/,jQ=class{constructor(Z,Y,X){if(this.path=Z,this.index=Y,this.working_dir=X,Y==="R"||X==="R"){let Q=sX.exec(Z)||[null,Z,Z];this.from=Q[2]||"",this.path=Q[1]||""}}}}});function tX(Z){let[Y,X]=Z.split(b9);return{from:X||Y,to:Y}}function c1(Z,Y,X){return[`${Z}${Y}`,X]}function qZ(Z,...Y){return Y.map((X)=>c1(Z,X,(Q,$)=>d(Q.conflicted,$)))}function JK(Z,Y){let X=Y.trim();switch(" "){case X.charAt(2):return Q(X.charAt(0),X.charAt(1),X.substr(3));case X.charAt(1):return Q(" ",X.charAt(0),X.substr(2));default:return}function Q($,W,J){let z=`${$}${W}`,V=CQ.get(z);if(V)V(Z,J);if(z!=="##"&&z!=="!!")Z.files.push(new jQ(J,$,W))}}var eX,CQ,SQ,zK=D({"src/lib/responses/StatusSummary.ts"(){_(),WK(),eX=class{constructor(){this.not_added=[],this.conflicted=[],this.created=[],this.deleted=[],this.ignored=void 0,this.modified=[],this.renamed=[],this.files=[],this.staged=[],this.ahead=0,this.behind=0,this.current=null,this.tracking=null,this.detached=!1,this.isClean=()=>{return!this.files.length}}},CQ=new Map([c1(" ","A",(Z,Y)=>d(Z.created,Y)),c1(" ","D",(Z,Y)=>d(Z.deleted,Y)),c1(" ","M",(Z,Y)=>d(Z.modified,Y)),c1("A"," ",(Z,Y)=>d(Z.created,Y)&&d(Z.staged,Y)),c1("A","M",(Z,Y)=>d(Z.created,Y)&&d(Z.staged,Y)&&d(Z.modified,Y)),c1("D"," ",(Z,Y)=>d(Z.deleted,Y)&&d(Z.staged,Y)),c1("M"," ",(Z,Y)=>d(Z.modified,Y)&&d(Z.staged,Y)),c1("M","M",(Z,Y)=>d(Z.modified,Y)&&d(Z.staged,Y)),c1("R"," ",(Z,Y)=>{d(Z.renamed,tX(Y))}),c1("R","M",(Z,Y)=>{let X=tX(Y);d(Z.renamed,X),d(Z.modified,X.to)}),c1("!","!",(Z,Y)=>{d(Z.ignored=Z.ignored||[],Y)}),c1("?","?",(Z,Y)=>d(Z.not_added,Y)),...qZ("A","A","U"),...qZ("D","D","U"),...qZ("U","A","D","U"),["##",(Z,Y)=>{let X=/ahead (\d+)/,Q=/behind (\d+)/,$=/^(.+?(?=(?:\.{3}|\s|$)))/,W=/\.{3}(\S*)/,J=/\son\s(\S+?)(?=\.{3}|$)/,z=X.exec(Y);if(Z.ahead=z&&+z[1]||0,z=Q.exec(Y),Z.behind=z&&+z[1]||0,z=$.exec(Y),Z.current=l1(z?.[1],D1,null),z=W.exec(Y),Z.tracking=l1(z?.[1],D1,null),z=J.exec(Y),z)Z.current=l1(z?.[1],D1,Z.current);Z.detached=/\(no branch\)/.test(Y)}]]),SQ=function(Z){let Y=Z.split(b9),X=new eX;for(let Q=0,$=Y.length;Q<$;){let W=Y[Q++].trim();if(!W)continue;if(W.charAt(0)==="R")W+=b9+(Y[Q++]||"");JK(X,W)}return X}}});function VK(Z){return{format:"utf-8",commands:["status","--porcelain","-b","-u","--null",...Z.filter((X)=>!_Q.includes(X))],parser(X){return SQ(X)}}}var _Q,qK=D({"src/lib/tasks/status.ts"(){zK(),_Q=["--null","-z"]}});function H4(Z=0,Y=0,X=0,Q="",$=!0){return Object.defineProperty({major:Z,minor:Y,patch:X,agent:Q,installed:$},"toString",{value(){return`${this.major}.${this.minor}.${this.patch}`},configurable:!1,enumerable:!1})}function UK(){return H4(0,0,0,"",!1)}function HK(){return{version(){return this._runTask({commands:["--version"],format:"utf-8",parser:GK,onError(Z,Y,X,Q){if(Z.exitCode===-2)return X(Buffer.from(lZ));Q(Y)}})}}}function GK(Z){if(Z===lZ)return UK();return x1(H4(0,0,0,Z),yQ,Z)}var lZ,yQ,KK=D({"src/lib/tasks/version.ts"(){_(),lZ="installed=false",yQ=[new k(/version (\d+)\.(\d+)\.(\d+)(?:\s*\((.+)\))?/,(Z,[Y,X,Q,$=""])=>{Object.assign(Z,H4(a(Y),a(X),a(Q),$))}),new k(/version (\d+)\.(\d+)\.(\D+)(.+)?$/,(Z,[Y,X,Q,$=""])=>{Object.assign(Z,H4(a(Y),a(X),Q,$))})]}}),bQ={};H1(bQ,{SimpleGitApi:()=>AZ});var AZ,BK=D({"src/lib/simple-git-api.ts"(){wG(),DG(),EG(),TG(),SG(),m5(),yG(),i5(),xG(),gG(),BQ(),eG(),RQ(),$K(),qK(),U1(),KK(),_(),AZ=class{constructor(Z){this._executor=Z}_runTask(Z,Y){let X=this._executor.chain(),Q=X.push(Z);if(Y)FG(Z,Q,Y);return Object.create(this,{then:{value:Q.then.bind(Q)},catch:{value:Q.catch.bind(Q)},_executor:{value:X}})}add(Z){return this._runTask(j1(["add",...L0(Z)]),z1(arguments))}cwd(Z){let Y=z1(arguments);if(typeof Z==="string")return this._runTask(vX(Z,this._executor),Y);if(typeof Z?.path==="string")return this._runTask(vX(Z.path,Z.root&&this._executor||void 0),Y);return this._runTask(b1("Git.cwd: workingDirectory must be supplied as a string"),Y)}hashObject(Z,Y){return this._runTask(bG(Z,Y===!0),z1(arguments))}init(Z){return this._runTask(hG(Z===!0,this._executor.cwd,y1(arguments)),z1(arguments))}merge(){return this._runTask(nX(y1(arguments)),z1(arguments))}mergeFromTo(Z,Y){if(!(D1(Z)&&D1(Y)))return this._runTask(b1("Git.mergeFromTo requires that the 'remote' and 'branch' arguments are supplied as strings"));return this._runTask(nX([Z,Y,...y1(arguments)]),z1(arguments,!1))}outputHandler(Z){return this._executor.outputHandler=Z,this}push(){let Z=cZ({remote:l1(arguments[0],D1),branch:l1(arguments[1],D1)},y1(arguments));return this._runTask(Z,z1(arguments))}stash(){return this._runTask(j1(["stash",...y1(arguments)]),z1(arguments))}status(){return this._runTask(VK(y1(arguments)),z1(arguments))}},Object.assign(AZ.prototype,AG(),CG(),QG(),PG(),_G(),zG(),oG(),QK(),HK())}}),xQ={};H1(xQ,{Scheduler:()=>vQ});var Z5,vQ,LK=D({"src/lib/runners/scheduler.ts"(){_(),s5(),Z5=(()=>{let Z=0;return()=>{Z++;let{promise:Y,done:X}=kQ.createDeferred();return{promise:Y,done:X,id:Z}}})(),vQ=class{constructor(Z=2){this.concurrency=Z,this.logger=kZ("","scheduler"),this.pending=[],this.running=[],this.logger("Constructed, concurrency=%s",Z)}schedule(){if(!this.pending.length||this.running.length>=this.concurrency){this.logger("Schedule attempt ignored, pending=%s running=%s concurrency=%s",this.pending.length,this.running.length,this.concurrency);return}let Z=d(this.running,this.pending.shift());this.logger("Attempting id=%s",Z.id),Z.done(()=>{this.logger("Completing id=",Z.id),B4(this.running,Z),this.schedule()})}next(){let{promise:Z,id:Y}=d(this.pending,Z5());return this.logger("Scheduling id=%s",Y),this.schedule(),Z}}}}),fQ={};H1(fQ,{applyPatchTask:()=>MK});function MK(Z,Y){return j1(["apply",...Y,...Z])}var FK=D({"src/lib/tasks/apply-patch.ts"(){U1()}});function NK(Z,Y){return{branch:Z,hash:Y,success:!0}}function wK(Z){return{branch:Z,hash:null,success:!1}}var hQ,DK=D({"src/lib/responses/BranchDeleteSummary.ts"(){hQ=class{constructor(){this.all=[],this.branches={},this.errors=[]}get success(){return!this.errors.length}}}});function gQ(Z,Y){return Y===1&&EZ.test(Z)}var Y5,EZ,X5,A4,AK=D({"src/lib/parsers/parse-branch-delete.ts"(){DK(),_(),Y5=/(\S+)\s+\(\S+\s([^)]+)\)/,EZ=/^error[^']+'([^']+)'/m,X5=[new k(Y5,(Z,[Y,X])=>{let Q=NK(Y,X);Z.all.push(Q),Z.branches[Y]=Q}),new k(EZ,(Z,[Y])=>{let X=wK(Y);Z.errors.push(X),Z.all.push(X),Z.branches[Y]=X})],A4=(Z,Y)=>{return x1(new hQ,X5,[Z,Y])}}}),uQ,EK=D({"src/lib/responses/BranchSummary.ts"(){uQ=class{constructor(){this.all=[],this.branches={},this.current="",this.detached=!1}push(Z,Y,X,Q,$){if(Z==="*")this.detached=Y,this.current=X;this.all.push(X),this.branches[X]={current:Z==="*",linkedWorkTree:Z==="+",name:X,commit:Q,label:$}}}}});function Q5(Z){return Z?Z.charAt(0):""}function mQ(Z,Y=!1){return x1(new uQ,Y?[dQ]:pQ,Z)}var pQ,dQ,OK=D({"src/lib/parsers/parse-branch.ts"(){EK(),_(),pQ=[new k(/^([*+]\s)?\((?:HEAD )?detached (?:from|at) (\S+)\)\s+([a-z0-9]+)\s(.*)$/,(Z,[Y,X,Q,$])=>{Z.push(Q5(Y),!0,X,Q,$)}),new k(/^([*+]\s)?(\S+)\s+([a-z0-9]+)\s?(.*)$/s,(Z,[Y,X,Q,$])=>{Z.push(Q5(Y),!1,X,Q,$)})],dQ=new k(/^(\S+)$/s,(Z,[Y])=>{Z.push("*",!1,Y,"","")})}}),cQ={};H1(cQ,{branchLocalTask:()=>TK,branchTask:()=>PK,containsDeleteBranchCommand:()=>lQ,deleteBranchTask:()=>RK,deleteBranchesTask:()=>IK});function lQ(Z){let Y=["-d","-D","--delete"];return Z.some((X)=>Y.includes(X))}function PK(Z){let Y=lQ(Z),X=Z.includes("--show-current"),Q=["branch",...Z];if(Q.length===1)Q.push("-a");if(!Q.includes("-v"))Q.splice(1,0,"-v");return{format:"utf-8",commands:Q,parser($,W){if(Y)return A4($,W).all[0];return mQ($,X)}}}function TK(){return{format:"utf-8",commands:["branch","-v"],parser(Z){return mQ(Z)}}}function IK(Z,Y=!1){return{format:"utf-8",commands:["branch","-v",Y?"-D":"-d",...Z],parser(X,Q){return A4(X,Q)},onError({exitCode:X,stdOut:Q},$,W,J){if(!gQ(String($),X))return J($);W(Q)}}}function RK(Z,Y=!1){let X={format:"utf-8",commands:["branch","-v",Y?"-D":"-d",Z],parser(Q,$){return A4(Q,$).branches[Z]},onError({exitCode:Q,stdErr:$,stdOut:W},J,z,V){if(!gQ(String(J),Q))return V(J);throw new E2(X.parser(D2(W),D2($)),String(J))}};return X}var jK=D({"src/lib/tasks/branch.ts"(){x9(),AK(),OK(),_()}});function SK(Z){let Y=Z.trim().replace(/^["']|["']$/g,"");return Y&&CK(Y)}var iQ,_K=D({"src/lib/responses/CheckIgnore.ts"(){iQ=(Z)=>{return Z.split(/\n/g).map(SK).filter(Boolean)}}}),oQ={};H1(oQ,{checkIgnoreTask:()=>yK});function yK(Z){return{commands:["check-ignore",...Z],format:"utf-8",parser:iQ}}var bK=D({"src/lib/tasks/check-ignore.ts"(){_K()}}),nQ={};H1(nQ,{cloneMirrorTask:()=>kK,cloneTask:()=>aQ});function xK(Z){return/^--upload-pack(=|$)/.test(Z)}function aQ(Z,Y,X){let Q=["clone",...X];if(D1(Z)&&Q.push(Z),D1(Y)&&Q.push(Y),Q.find(xK))return b1("git.fetch: potential exploit argument blocked.");return j1(Q)}function kK(Z,Y,X){return d(X,"--mirror"),aQ(Z,Y,X)}var vK=D({"src/lib/tasks/clone.ts"(){U1(),_()}});function fK(Z,Y){return x1({raw:Z,remote:null,branches:[],tags:[],updated:[],deleted:[]},rQ,[Z,Y])}var rQ,hK=D({"src/lib/parsers/parse-fetch.ts"(){_(),rQ=[new k(/From (.+)$/,(Z,[Y])=>{Z.remote=Y}),new k(/\* \[new branch]\s+(\S+)\s*-> (.+)$/,(Z,[Y,X])=>{Z.branches.push({name:Y,tracking:X})}),new k(/\* \[new tag]\s+(\S+)\s*-> (.+)$/,(Z,[Y,X])=>{Z.tags.push({name:Y,tracking:X})}),new k(/- \[deleted]\s+\S+\s*-> (.+)$/,(Z,[Y])=>{Z.deleted.push({tracking:Y})}),new k(/\s*([^.]+)\.\.(\S+)\s+(\S+)\s*-> (.+)$/,(Z,[Y,X,Q,$])=>{Z.updated.push({name:Q,tracking:$,to:X,from:Y})})]}}),sQ={};H1(sQ,{fetchTask:()=>uK});function gK(Z){return/^--upload-pack(=|$)/.test(Z)}function uK(Z,Y,X){let Q=["fetch",...X];if(Z&&Y)Q.push(Z,Y);if(Q.find(gK))return b1("git.fetch: potential exploit argument blocked.");return{commands:Q,format:"utf-8",parser:fK}}var mK=D({"src/lib/tasks/fetch.ts"(){hK(),U1()}});function pK(Z){return x1({moves:[]},tQ,Z)}var tQ,dK=D({"src/lib/parsers/parse-move.ts"(){_(),tQ=[new k(/^Renaming (.+) to (.+)$/,(Z,[Y,X])=>{Z.moves.push({from:Y,to:X})})]}}),eQ={};H1(eQ,{moveTask:()=>cK});function cK(Z,Y){return{commands:["mv","-v",...L0(Z),Y],format:"utf-8",parser:pK}}var lK=D({"src/lib/tasks/move.ts"(){dK(),_()}}),Z$={};H1(Z$,{pullTask:()=>iK});function iK(Z,Y,X){let Q=["pull",...X];if(Z&&Y)Q.splice(1,0,Z,Y);return{commands:Q,format:"utf-8",parser($,W){return dZ($,W)},onError($,W,J,z){let V=sG(D2($.stdOut),D2($.stdErr));if(V)return z(new E2(V));z(W)}}}var oK=D({"src/lib/tasks/pull.ts"(){x9(),OQ(),_()}});function nK(Z){let Y={};return Y$(Z,([X])=>Y[X]={name:X}),Object.values(Y)}function aK(Z){let Y={};return Y$(Z,([X,Q,$])=>{if(!Object.hasOwn(Y,X))Y[X]={name:X,refs:{fetch:"",push:""}};if($&&Q)Y[X].refs[$.replace(/[^a-z]/g,"")]=Q}),Object.values(Y)}function Y$(Z,Y){TZ(Z,(X)=>Y(X.split(/\s+/)))}var rK=D({"src/lib/responses/GetRemoteSummary.ts"(){_()}}),X$={};H1(X$,{addRemoteTask:()=>sK,getRemotesTask:()=>tK,listRemotesTask:()=>eK,remoteTask:()=>Z3,removeRemoteTask:()=>Y3});function sK(Z,Y,X){return j1(["remote","add",...X,Z,Y])}function tK(Z){let Y=["remote"];if(Z)Y.push("-v");return{commands:Y,format:"utf-8",parser:Z?aK:nK}}function eK(Z){let Y=[...Z];if(Y[0]!=="ls-remote")Y.unshift("ls-remote");return j1(Y)}function Z3(Z){let Y=[...Z];if(Y[0]!=="remote")Y.unshift("remote");return j1(Y)}function Y3(Z){return j1(["remote","remove",Z])}var X3=D({"src/lib/tasks/remote.ts"(){rK(),U1()}}),Q$={};H1(Q$,{stashListTask:()=>Q3});function Q3(Z={},Y){let X=KQ(Z),Q=["stash","list",...X.commands,...Y],$=qQ(X.splitter,X.fields,fZ(Q));return D4(Q)||{commands:Q,format:"utf-8",parser:$}}var $3=D({"src/lib/tasks/stash-list.ts"(){I2(),HQ(),pZ(),BQ()}}),$$={};H1($$,{addSubModuleTask:()=>W3,initSubModuleTask:()=>J3,subModuleTask:()=>E4,updateSubModuleTask:()=>z3});function W3(Z,Y){return E4(["add",Z,Y])}function J3(Z){return E4(["init",...Z])}function E4(Z){let Y=[...Z];if(Y[0]!=="submodule")Y.unshift("submodule");return j1(Y)}function z3(Z){return E4(["update",...Z])}var V3=D({"src/lib/tasks/sub-module.ts"(){U1()}});function q3(Z,Y){let X=Number.isNaN(Z),Q=Number.isNaN(Y);if(X!==Q)return X?1:-1;return X?W$(Z,Y):0}function W$(Z,Y){return Z===Y?0:Z>Y?1:-1}function U3(Z){return Z.trim()}function X4(Z){if(typeof Z==="string")return parseInt(Z.replace(/^\D+/g,""),10)||0;return 0}var $5,J$,H3=D({"src/lib/responses/TagList.ts"(){$5=class{constructor(Z,Y){this.all=Z,this.latest=Y}},J$=function(Z,Y=!1){let X=Z.split(`
|
|
38
|
-
`).map(U3).filter(Boolean);if(!Y)X.sort(function($,W){let J=$.split("."),z=W.split(".");if(J.length===1||z.length===1)return q3(X4(J[0]),X4(z[0]));for(let V=0,q=Math.max(J.length,z.length);V<q;V++){let U=W$(X4(J[V]),X4(z[V]));if(U)return U}return 0});let Q=Y?X[0]:[...X].reverse().find(($)=>$.indexOf(".")>=0);return new $5(X,Q)}}}),z$={};H1(z$,{addAnnotatedTagTask:()=>B3,addTagTask:()=>K3,tagListTask:()=>G3});function G3(Z=[]){let Y=Z.some((X)=>/^--sort=/.test(X));return{format:"utf-8",commands:["tag","-l",...Z],parser(X){return J$(X,Y)}}}function K3(Z){return{format:"utf-8",commands:["tag",Z],parser(){return{name:Z}}}}function B3(Z,Y){return{format:"utf-8",commands:["tag","-a","-m",Y,Z],parser(){return{name:Z}}}}var L3=D({"src/lib/tasks/tag.ts"(){H3()}}),M3=jH({"src/git.js"(Z,Y){var{GitExecutor:X}=(MG(),J1(e5)),{SimpleGitApi:Q}=(BK(),J1(bQ)),{Scheduler:$}=(LK(),J1(xQ)),{configurationErrorTask:W}=(U1(),J1(MZ)),{asArray:J,filterArray:z,filterPrimitives:V,filterString:q,filterStringOrStringArray:U,filterType:H,getTrailingOptions:G,trailingFunctionArgument:K,trailingOptionsArgument:M}=(_(),J1(O5)),{applyPatchTask:E}=(FK(),J1(fQ)),{branchTask:O,branchLocalTask:T,deleteBranchesTask:i,deleteBranchTask:g}=(jK(),J1(cQ)),{checkIgnoreTask:Z1}=(bK(),J1(oQ)),{checkIsRepoTask:$1}=(R5(),J1(P5)),{cloneTask:W1,cloneMirrorTask:A0}=(vK(),J1(nQ)),{cleanWithOptionsTask:z0,isCleanOptionsArray:W9}=(h5(),J1(v5)),{diffSummaryTask:u8}=(pZ(),J1(GQ)),{fetchTask:Nq}=(mK(),J1(sQ)),{moveTask:wq}=(lK(),J1(eQ)),{pullTask:Dq}=(oK(),J1(Z$)),{pushTagsTask:Aq}=(RQ(),J1(IQ)),{addRemoteTask:Eq,getRemotesTask:Oq,listRemotesTask:Pq,remoteTask:Tq,removeRemoteTask:Iq}=(X3(),J1(X$)),{getResetMode:Rq,resetTask:jq}=(r5(),J1(o5)),{stashListTask:Cq}=($3(),J1(Q$)),{addSubModuleTask:Sq,initSubModuleTask:_q,subModuleTask:yq,updateSubModuleTask:bq}=(V3(),J1($$)),{addAnnotatedTagTask:xq,addTagTask:kq,tagListTask:vq}=(L3(),J1(z$)),{straightThroughBufferTask:fq,straightThroughStringTask:B0}=(U1(),J1(MZ));function S(N,I){this._plugins=I,this._executor=new X(N.baseDir,new $(N.maxConcurrentProcesses),I),this._trimmed=N.trimmed}(S.prototype=Object.create(Q.prototype)).constructor=S,S.prototype.customBinary=function(N){return this._plugins.reconfigure("binary",N),this},S.prototype.env=function(N,I){if(arguments.length===1&&typeof N==="object")this._executor.env=N;else(this._executor.env=this._executor.env||{})[N]=I;return this},S.prototype.stashList=function(N){return this._runTask(Cq(M(arguments)||{},z(N)&&N||[]),K(arguments))};function a7(N,I,o,R1){if(typeof o!=="string")return W(`git.${N}() requires a string 'repoPath'`);return I(o,H(R1,q),G(arguments))}S.prototype.clone=function(){return this._runTask(a7("clone",W1,...arguments),K(arguments))},S.prototype.mirror=function(){return this._runTask(a7("mirror",A0,...arguments),K(arguments))},S.prototype.mv=function(N,I){return this._runTask(wq(N,I),K(arguments))},S.prototype.checkoutLatestTag=function(N){var I=this;return this.pull(function(){I.tags(function(o,R1){I.checkout(R1.latest,N)})})},S.prototype.pull=function(N,I,o,R1){return this._runTask(Dq(H(N,q),H(I,q),G(arguments)),K(arguments))},S.prototype.fetch=function(N,I){return this._runTask(Nq(H(N,q),H(I,q),G(arguments)),K(arguments))},S.prototype.silent=function(N){return console.warn("simple-git deprecation notice: git.silent: logging should be configured using the `debug` library / `DEBUG` environment variable, this will be an error in version 3"),this},S.prototype.tags=function(N,I){return this._runTask(vq(G(arguments)),K(arguments))},S.prototype.rebase=function(){return this._runTask(B0(["rebase",...G(arguments)]),K(arguments))},S.prototype.reset=function(N){return this._runTask(jq(Rq(N),G(arguments)),K(arguments))},S.prototype.revert=function(N){let I=K(arguments);if(typeof N!=="string")return this._runTask(W("Commit must be a string"),I);return this._runTask(B0(["revert",...G(arguments,0,!0),N]),I)},S.prototype.addTag=function(N){let I=typeof N==="string"?kq(N):W("Git.addTag requires a tag name");return this._runTask(I,K(arguments))},S.prototype.addAnnotatedTag=function(N,I){return this._runTask(xq(N,I),K(arguments))},S.prototype.deleteLocalBranch=function(N,I,o){return this._runTask(g(N,typeof I==="boolean"?I:!1),K(arguments))},S.prototype.deleteLocalBranches=function(N,I,o){return this._runTask(i(N,typeof I==="boolean"?I:!1),K(arguments))},S.prototype.branch=function(N,I){return this._runTask(O(G(arguments)),K(arguments))},S.prototype.branchLocal=function(N){return this._runTask(T(),K(arguments))},S.prototype.raw=function(N){let I=!Array.isArray(N),o=[].slice.call(I?arguments:N,0);for(let V0=0;V0<o.length&&I;V0++)if(!V(o[V0])){o.splice(V0,o.length-V0);break}o.push(...G(arguments,0,!0));var R1=K(arguments);if(!o.length)return this._runTask(W("Raw: must supply one or more command to execute"),R1);return this._runTask(B0(o,this._trimmed),R1)},S.prototype.submoduleAdd=function(N,I,o){return this._runTask(Sq(N,I),K(arguments))},S.prototype.submoduleUpdate=function(N,I){return this._runTask(bq(G(arguments,!0)),K(arguments))},S.prototype.submoduleInit=function(N,I){return this._runTask(_q(G(arguments,!0)),K(arguments))},S.prototype.subModule=function(N,I){return this._runTask(yq(G(arguments)),K(arguments))},S.prototype.listRemote=function(){return this._runTask(Pq(G(arguments)),K(arguments))},S.prototype.addRemote=function(N,I,o){return this._runTask(Eq(N,I,G(arguments)),K(arguments))},S.prototype.removeRemote=function(N,I){return this._runTask(Iq(N),K(arguments))},S.prototype.getRemotes=function(N,I){return this._runTask(Oq(N===!0),K(arguments))},S.prototype.remote=function(N,I){return this._runTask(Tq(G(arguments)),K(arguments))},S.prototype.tag=function(N,I){let o=G(arguments);if(o[0]!=="tag")o.unshift("tag");return this._runTask(B0(o),K(arguments))},S.prototype.updateServerInfo=function(N){return this._runTask(B0(["update-server-info"]),K(arguments))},S.prototype.pushTags=function(N,I){let o=Aq({remote:H(N,q)},G(arguments));return this._runTask(o,K(arguments))},S.prototype.rm=function(N){return this._runTask(B0(["rm","-f",...J(N)]),K(arguments))},S.prototype.rmKeepLocal=function(N){return this._runTask(B0(["rm","--cached",...J(N)]),K(arguments))},S.prototype.catFile=function(N,I){return this._catFile("utf-8",arguments)},S.prototype.binaryCatFile=function(){return this._catFile("buffer",arguments)},S.prototype._catFile=function(N,I){var o=K(I),R1=["cat-file"],V0=I[0];if(typeof V0==="string")return this._runTask(W("Git.catFile: options must be supplied as an array of strings"),o);if(Array.isArray(V0))R1.push.apply(R1,V0);let m8=N==="buffer"?fq(R1):B0(R1);return this._runTask(m8,o)},S.prototype.diff=function(N,I){let o=q(N)?W("git.diff: supplying options as a single string is no longer supported, switch to an array of strings"):B0(["diff",...G(arguments)]);return this._runTask(o,K(arguments))},S.prototype.diffSummary=function(){return this._runTask(u8(G(arguments,1)),K(arguments))},S.prototype.applyPatch=function(N){let I=!U(N)?W("git.applyPatch requires one or more string patches as the first argument"):E(J(N),G([].slice.call(arguments,1)));return this._runTask(I,K(arguments))},S.prototype.revparse=function(){let N=["rev-parse",...G(arguments,!0)];return this._runTask(B0(N,!0),K(arguments))},S.prototype.clean=function(N,I,o){let R1=W9(N),V0=R1&&N.join("")||H(N,q)||"",m8=G([].slice.call(arguments,R1?1:0));return this._runTask(z0(V0,m8),K(arguments))},S.prototype.exec=function(N){let I={commands:[],format:"utf-8",parser(){if(typeof N==="function")N()}};return this._runTask(I)},S.prototype.clearQueue=function(){return this},S.prototype.checkIgnore=function(N,I){return this._runTask(Z1(J(H(N,U,[]))),K(arguments))},S.prototype.checkIsRepo=function(N,I){return this._runTask($1(H(N,q)),K(arguments))},Y.exports=S}});A2();m0();var F3=class extends I0{constructor(Z,Y){super(void 0,Y);this.config=Z}};m0();m0();var T0=class extends I0{constructor(Z,Y,X){super(Z,X);this.task=Z,this.plugin=Y,Object.setPrototypeOf(this,new.target.prototype)}};x9();U5();R5();h5();m5();d5();i5();r5();function N3(Z){if(!Z)return;return[{type:"spawn.before",action(Q,$){if(Z.aborted)$.kill(new T0(void 0,"abort","Abort already signaled"))}},{type:"spawn.after",action(Q,$){function W(){$.kill(new T0(void 0,"abort","Abort signal received"))}Z.addEventListener("abort",W),$.spawned.on("close",()=>Z.removeEventListener("abort",W))}}]}function w3(Z){return typeof Z==="string"&&Z.trim().toLowerCase()==="-c"}function D3(Z,Y){if(!w3(Z))return;if(!/^\s*protocol(.[a-z]+)?.allow/.test(Y))return;throw new T0(void 0,"unsafe","Configuring protocol.allow is not permitted without enabling allowUnsafeExtProtocol")}function A3(Z,Y){if(/^\s*--(upload|receive)-pack/.test(Z))throw new T0(void 0,"unsafe","Use of --upload-pack or --receive-pack is not permitted without enabling allowUnsafePack");if(Y==="clone"&&/^\s*-u\b/.test(Z))throw new T0(void 0,"unsafe","Use of clone with option -u is not permitted without enabling allowUnsafePack");if(Y==="push"&&/^\s*--exec\b/.test(Z))throw new T0(void 0,"unsafe","Use of push with option --exec is not permitted without enabling allowUnsafePack")}function E3({allowUnsafeProtocolOverride:Z=!1,allowUnsafePack:Y=!1}={}){return{type:"spawn.args",action(X,Q){return X.forEach(($,W)=>{let J=W<X.length?X[W+1]:"";Z||D3($,J),Y||A3($,Q.method)}),X}}}_();function O3(Z){let Y=w2(Z,"-c");return{type:"spawn.args",action(X){return[...Y,...X]}}}_();var W5=y9.deferred().promise;function P3({onClose:Z=!0,onExit:Y=50}={}){function X(){let $=-1,W={close:y9.deferred(),closeTimeout:y9.deferred(),exit:y9.deferred(),exitTimeout:y9.deferred()},J=Promise.race([Z===!1?W5:W.closeTimeout.promise,Y===!1?W5:W.exitTimeout.promise]);return Q(Z,W.close,W.closeTimeout),Q(Y,W.exit,W.exitTimeout),{close(z){$=z,W.close.done()},exit(z){$=z,W.exit.done()},get exitCode(){return $},result:J}}function Q($,W,J){if($===!1)return;($===!0?W.promise:W.promise.then(()=>UZ($))).then(J.done)}return{type:"spawn.after",async action($,{spawned:W,close:J}){let z=X(),V=!0,q=()=>void(V=!1);W.stdout?.on("data",q),W.stderr?.on("data",q),W.on("error",q),W.on("close",(U)=>z.close(U)),W.on("exit",(U)=>z.exit(U));try{if(await z.result,V)await UZ(50);J(z.exitCode)}catch(U){J(z.exitCode,U)}}}}_();var T3="Invalid value supplied for custom binary, requires a single string or an array containing either one or two strings",J5="Invalid value supplied for custom binary, restricted characters must be removed or supply the unsafe.allowUnsafeCustomBinary option";function I3(Z){return!Z||!/^([a-z]:)?([a-z0-9/.\\_-]+)$/i.test(Z)}function z5(Z,Y){if(Z.length<1||Z.length>2)throw new T0(void 0,"binary",T3);if(Z.some(I3))if(Y)console.warn(J5);else throw new T0(void 0,"binary",J5);let[Q,$]=Z;return{binary:Q,prefix:$}}function R3(Z,Y=["git"],X=!1){let Q=z5(L0(Y),X);Z.on("binary",($)=>{Q=z5(L0($),X)}),Z.append("spawn.binary",()=>{return Q.binary}),Z.append("spawn.args",($)=>{return Q.prefix?[Q.prefix,...$]:$})}m0();function j3(Z){return!!(Z.exitCode&&Z.stdErr.length)}function C3(Z){return Buffer.concat([...Z.stdOut,...Z.stdErr])}function S3(Z=!1,Y=j3,X=C3){return(Q,$)=>{if(!Z&&Q||!Y($))return Q;return X($)}}function V5(Z){return{type:"task.error",action(Y,X){let Q=Z(Y.error,{stdErr:X.stdErr,stdOut:X.stdOut,exitCode:X.exitCode});if(Buffer.isBuffer(Q))return{error:new I0(void 0,Q.toString("utf-8"))};return{error:Q}}}}_();var y3=class{constructor(){this.plugins=new Set,this.events=new _3}on(Z,Y){this.events.on(Z,Y)}reconfigure(Z,Y){this.events.emit(Z,Y)}append(Z,Y){let X=d(this.plugins,{type:Z,action:Y});return()=>this.plugins.delete(X)}add(Z){let Y=[];return L0(Z).forEach((X)=>X&&this.plugins.add(d(Y,X))),()=>{Y.forEach((X)=>this.plugins.delete(X))}}exec(Z,Y,X){let Q=Y,$=Object.freeze(Object.create(X));for(let W of this.plugins)if(W.type===Z)Q=W.action(Q,$);return Q}};_();function b3(Z){let X=["checkout","clone","fetch","pull","push"];return[{type:"spawn.args",action(W,J){if(!X.includes(J.method))return W;return M5(W,"--progress")}},{type:"spawn.after",action(W,J){if(!J.commands.includes("--progress"))return;J.spawned.stderr?.on("data",(z)=>{let V=/^([\s\S]+?):\s*(\d+)% \((\d+)\/(\d+)\)/.exec(z.toString("utf8"));if(!V)return;Z({method:J.method,stage:x3(V[1]),progress:a(V[2]),processed:a(V[3]),total:a(V[4])})})}}]}function x3(Z){return String(Z.toLowerCase().split(" ",1))||"unknown"}_();function k3(Z){let Y=N5(Z,["uid","gid"]);return{type:"spawn.options",action(X){return{...Y,...X}}}}function v3({block:Z,stdErr:Y=!0,stdOut:X=!0}){if(Z>0)return{type:"spawn.after",action(Q,$){let W;function J(){W&&clearTimeout(W),W=setTimeout(V,Z)}function z(){$.spawned.stdout?.off("data",J),$.spawned.stderr?.off("data",J),$.spawned.off("exit",z),$.spawned.off("close",z),W&&clearTimeout(W)}function V(){z(),$.kill(new T0(void 0,"timeout","block timeout reached"))}X&&$.spawned.stdout?.on("data",J),Y&&$.spawned.stderr?.on("data",J),$.spawned.on("exit",z),$.spawned.on("close",z),J()}}}A2();function f3(){return{type:"spawn.args",action(Z){let Y=[],X;function Q($){(X=X||[]).push(...$)}for(let $=0;$<Z.length;$++){let W=Z[$];if(z4(W)){Q(yX(W));continue}if(W==="--"){Q(Z.slice($+1).flatMap((J)=>z4(J)&&yX(J)||J));break}Y.push(W)}return!X?Y:[...Y,"--",...X.map(String)]}}}_();var h3=M3();function g3(Z,Y){let X=new y3,Q=A5(Z&&(typeof Z==="string"?{baseDir:Z}:Z)||{},Y);if(!IZ(Q.baseDir))throw new F3(Q,"Cannot use simple-git on a directory that does not exist");if(Array.isArray(Q.config))X.add(O3(Q.config));return X.add(E3(Q.unsafe)),X.add(f3()),X.add(P3(Q.completion)),Q.abort&&X.add(N3(Q.abort)),Q.progress&&X.add(b3(Q.progress)),Q.timeout&&X.add(v3(Q.timeout)),Q.spawnOptions&&X.add(k3(Q.spawnOptions)),X.add(V5(S3(!0))),Q.errors&&X.add(V5(Q.errors)),R3(X,Q.binary,Q.unsafe?.allowUnsafeCustomBinary),new h3(Q,X)}x9();var O4=g3;class O1 extends Error{code;constructor(Z,Y){super(Z);this.code=Y;this.name="GitError"}}function u3(Z){if(Z==="staged")return{args:["--cached"],description:"staged changes"};if(Z==="unstaged")return{args:[],description:"unstaged changes"};if(Z==="HEAD")return{args:["HEAD"],description:"all uncommitted changes"};if(Z.startsWith("branch:")){let Y=Z.slice(7);if(!Y)throw new O1("Branch name required","INVALID_TARGET");return{args:[Y],description:`changes vs ${Y}`}}if(Z.startsWith("commit:")){let Y=Z.slice(7);if(!Y)throw new O1("Commit hash required","INVALID_TARGET");return{args:[`${Y}^`,Y],description:`commit ${Y}`}}if(Z.startsWith("range:")){let Y=Z.slice(6),X=Y.match(/^([^.]+)\.\.([^.]+)$/);if(!X||!X[1]||!X[2])throw new O1("Invalid range format. Use range:abc123..def456","INVALID_TARGET");return{args:[X[1],X[2]],description:`range ${Y}`}}throw new O1(`Unknown target format: ${Z}. Use staged, unstaged, HEAD, branch:name, commit:hash, or range:a..b`,"INVALID_TARGET")}async function V$(Z){let Y=O4(Z);if(!await Y.checkIsRepo())throw new O1("Not a git repository","NOT_A_REPO");return Y}async function P4(Z="staged",Y){let X=await V$(Y),{args:Q}=u3(Z);try{let $=await X.diff(Q);return{diff:$,target:Z,hasChanges:$.trim().length>0}}catch($){let W=$ instanceof Error?$.message:String($);if(W.includes("unknown revision")||W.includes("bad revision")){if(Z.startsWith("branch:"))throw new O1(`Branch not found: ${Z.slice(7)}`,"BRANCH_NOT_FOUND");if(Z.startsWith("commit:")||Z.startsWith("range:"))throw new O1(`Commit not found in: ${Z}`,"COMMIT_NOT_FOUND")}throw new O1(`Git error: ${W}`,"GIT_ERROR")}}async function q$(Z,Y){let X=await V$(Y);try{return(await X.show([Z,"--format=%s%n%n%b","-s"])).trim()}catch(Q){let $=Q instanceof Error?Q.message:String(Q);if($.includes("unknown revision")||$.includes("bad revision"))throw new O1(`Commit not found: ${Z}`,"COMMIT_NOT_FOUND");throw new O1(`Git error: ${$}`,"GIT_ERROR")}}function v9(Z){if(!Z||Z.trim().length===0)return{files:[]};let Y=[],X=Z.split(`
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
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 G.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()}`,G.env[e.envVar]);else this.emit(`optionEnv:${e.name()}`)}})}_parseOptionsImplied(){let e=new Ab(this.options),t=(n)=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter((n)=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach((n)=>{Object.keys(n.implied).filter((r)=>!t(r)).forEach((r)=>{this.setOptionValueWithSource(r,n.implied[r],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let n=(o)=>{let a=o.attributeName(),l=this.getOptionValue(a),c=this.options.find((d)=>d.negate&&a===d.attributeName()),u=this.options.find((d)=>!d.negate&&a===d.attributeName());if(c&&(c.presetArg===void 0&&l===!1||c.presetArg!==void 0&&l===c.presetArg))return c;return u||o},r=(o)=>{let a=n(o),l=a.attributeName();if(this.getOptionValueSource(l)==="env")return`environment variable '${a.envVar}'`;return`option '${a.flags}'`},s=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let r=[],s=this;do{let o=s.createHelp().visibleOptions(s).filter((a)=>a.long).map((a)=>a.long);r=r.concat(o),s=s.parent}while(s&&!s._enablePositionalOptions);t=sd(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=sd(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)=>$b(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=We.basename(e,We.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(G.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
|
+
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 od(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 Va(){if(G.env.NO_COLOR||G.env.FORCE_COLOR==="0"||G.env.FORCE_COLOR==="false")return!1;if(G.env.FORCE_COLOR||G.env.CLICOLOR_FORCE!==void 0)return!0;return}Cb.Command=Ga;Cb.useColor=Va});var Bs=Vn(function(kC,Xa){var Us=process||{},xd=Us.argv||[],js=Us.env||{},Nb=!(!!js.NO_COLOR||xd.includes("--no-color"))&&(!!js.FORCE_COLOR||xd.includes("--color")||Us.platform==="win32"||(Us.stdout||{}).isTTY&&js.TERM!=="dumb"||!!js.CI),Db=(e,t,n=e)=>(r)=>{let s=""+r,o=s.indexOf(t,e.length);return~o?e+Fb(s,t,n,o)+t:e+s+t},Fb=(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)},kd=(e=Nb)=>{let t=e?Db:()=>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")}};Xa.exports=kd();Xa.exports.createColors=kd});import{extname as Vb}from"path";function jt(e){return Gb[Vb(e).toLowerCase()]??null}var Gb;var hi=Ue(()=>{Gb={".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 Qb}from"fs";import ev from"os";import Ws from"path";function Qt(e,t){let n=process.env[e]?.trim();if(n===void 0||n==="")return t;let r=Number(n);if(!Number.isFinite(r)||r<=0)throw Error(`${e} must be a positive number, got "${process.env[e]}"`);return r}function Js(e){if(e.provider!==void 0)Qa=e.provider;if(e.model!==void 0){if(fn=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)pn=e.modelWalk;if(e.effort!==void 0){if(yr=e.effort,e.effortAux===void 0&&process.env.REVIEW_EFFORT_AUX===void 0)dn=e.effort}if(e.effortAux!==void 0)dn=e.effortAux;if(e.sliceBudget!==void 0)rl=e.sliceBudget;if(e.mergeBudget!==void 0)il=e.mergeBudget;if(e.walkBudget!==void 0)mi=e.walkBudget;if(e.partBudget!==void 0)nl=e.partBudget;if(e.pool!==void 0)sl=e.pool;if(e.maxSlices!==void 0)wr=e.maxSlices;if(e.maxSliceTokens!==void 0)Cn=e.maxSliceTokens;if(e.walkDiffTokens!==void 0)gi=e.walkDiffTokens;if(e.maxSteps!==void 0)el=e.maxSteps;if(e.deadlineMs!==void 0)tl=e.deadlineMs;if(e.grouping!==void 0)Jn=e.grouping;if(e.artifacts!==void 0)Re=e.artifacts;if(e.out!==void 0)Et=e.out;if(e.extraExcludes!==void 0)_i=e.extraExcludes;if(e.surfaces!==void 0)Yn=e.surfaces;if(e.providers!==void 0)yi=e.providers;if(e.childEnv!==void 0)ol=e.childEnv;if(e.authImport!==void 0)zs=e.authImport}function vr(e){if(e.subject!==void 0)Ye=e.subject;if(e.releaseSubject!==void 0)Gs=e.releaseSubject;if(e.repoName!==void 0)vt=e.repoName;if(e.signal!==void 0)br=e.signal}function Xs(){Ye=process.cwd(),Gs=async()=>{},vt="this repository",br=void 0}var Vs,Ye,Gs=async()=>{},Re,Nd="opencode",Qa,el,tl,fn,yr,pn,Xn,dn,mi,nl,Jn,rl,il,sl,wr,Dd=2.4,Cn,gi,Fd,Et,vt="this repository",Yn,_i,yi,ol,zs="",br;var xt=Ue(()=>{Vs=Qb(Ws.join(import.meta.dir,"system.md"))?import.meta.dir:Ws.join(import.meta.dir,"review-core"),Ye=process.cwd(),Re=process.env.CODE_REVIEW_ARTIFACTS??Ws.join(process.cwd(),".code-review"),Qa=process.env.REVIEW_PROVIDER??"anthropic",el=Qt("REVIEW_MAX_STEPS",80),tl=Qt("REVIEW_DEADLINE_S",900)*1000,fn=process.env.REVIEW_MODEL??"claude-opus-5-5",yr=process.env.REVIEW_EFFORT??"medium",pn=process.env.REVIEW_MODEL_WALK??"claude-sonnet-5-5",Xn=process.env.REVIEW_MODEL_MERGE??fn,dn=process.env.REVIEW_EFFORT_AUX??yr;mi=Qt("WALK_BUDGET_USD",2),nl=Qt("PART_BUDGET",0.6),Jn=process.env.REVIEW_GROUPING??"code";if(Jn!=="code"&&Jn!=="model")throw Error(`REVIEW_GROUPING must be "code" or "model", got "${Jn}"`);rl=Qt("SLICE_BUDGET_USD",3),il=Qt("MERGE_BUDGET_USD",3),sl=Qt("SLICE_POOL",6),wr=Qt("MAX_SLICES",16),Cn=Qt("MAX_SLICE_TOKENS",42000),gi=Qt("WALK_DIFF_TOKENS",1e5),Fd=process.env.INLINE_MODE==="tier"?"tier":"none",Et=process.env.CODE_REVIEW_SCRATCH??Ws.join(ev.tmpdir(),"code-review-out"),Yn={deploy:[],tooling:["^docs/","(^|/)[^/]*\\.config\\.[cm]?[jt]s$"]},_i=[],yi={},ol={}});function xr(e){if(e!==On)throw Error("Illegal constructor")}function vi(e){return!!e&&typeof e.row==="number"&&typeof e.column==="number"}function Zd(e){m=e}function gl(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 ml(e,t,n,r,s){for(let o=0,a=s.length;o<a;o++){let l=m.getValue(n,"i32");n+=J;let c=Ie(t,n);n+=ct,s[o]={patternIndex:r,name:e.captureNames[l],node:c}}return n}function oe(e,t=0){let n=V+t*ct;m.setValue(n,e.id,"i32"),n+=J,m.setValue(n,e.startIndex,"i32"),n+=J,m.setValue(n,e.startPosition.row,"i32"),n+=J,m.setValue(n,e.startPosition.column,"i32"),n+=J,m.setValue(n,e[0],"i32")}function Ie(e,t=V){let n=m.getValue(t,"i32");if(t+=J,n===0)return null;let r=m.getValue(t,"i32");t+=J;let s=m.getValue(t,"i32");t+=J;let o=m.getValue(t,"i32");t+=J;let a=m.getValue(t,"i32");return new Fv(On,{id:n,tree:e,startIndex:r,startPosition:{row:s,column:o},other:a})}function be(e,t=V){m.setValue(t+0*J,e[0],"i32"),m.setValue(t+1*J,e[1],"i32"),m.setValue(t+2*J,e[2],"i32"),m.setValue(t+3*J,e[3],"i32")}function kt(e){e[0]=m.getValue(V+0*J,"i32"),e[1]=m.getValue(V+1*J,"i32"),e[2]=m.getValue(V+2*J,"i32"),e[3]=m.getValue(V+3*J,"i32")}function At(e,t){m.setValue(e,t.row,"i32"),m.setValue(e+J,t.column,"i32")}function Zn(e){return{row:m.getValue(e,"i32")>>>0,column:m.getValue(e+J,"i32")>>>0}}function Qd(e,t){At(e,t.startPosition),e+=tn,At(e,t.endPosition),e+=tn,m.setValue(e,t.startIndex,"i32"),e+=J,m.setValue(e,t.endIndex,"i32"),e+=J}function to(e){let t={};return t.startPosition=Zn(e),e+=tn,t.endPosition=Zn(e),e+=tn,t.startIndex=m.getValue(e,"i32")>>>0,e+=J,t.endIndex=m.getValue(e,"i32")>>>0,t}function ef(e,t=V){At(t,e.startPosition),t+=tn,At(t,e.oldEndPosition),t+=tn,At(t,e.newEndPosition),t+=tn,m.setValue(t,e.startIndex,"i32"),t+=J,m.setValue(t,e.oldEndIndex,"i32"),t+=J,m.setValue(t,e.newEndIndex,"i32"),t+=J}function tf(e){let t=m.getValue(e,"i32"),n=m.getValue(e+=J,"i32"),r=m.getValue(e+=J,"i32");return{major_version:t,minor_version:n,patch_version:r}}async function nf(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_=_((e,t)=>{throw t},"quit_"),_scriptName=import.meta.url,scriptDirectory="";function locateFile(e){if(Module.locateFile)return Module.locateFile(e,scriptDirectory);return scriptDirectory+e}_(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=_((e)=>{e=isFileURI(e)?new URL(e):e;var t=fs.readFileSync(e);return t},"readBinary"),readAsync=_(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_=_((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=_((e)=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)},"readBinary");readAsync=_(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=_((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()}_(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()}_(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)}_(preRun,"preRun");function initRuntime(){runtimeInitialized=!0,callRuntimeCallbacks(__RELOC_FUNCS__),wasmExports.__wasm_call_ctors(),callRuntimeCallbacks(onPostCtors)}_(initRuntime,"initRuntime");function preMain(){}_(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)}_(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}_(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}_(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"}_(getBinarySync,"getBinarySync");async function getWasmBinary(e){if(!wasmBinary)try{var t=await readAsync(e);return new Uint8Array(t)}catch{}return getBinarySync(e)}_(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)}}_(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)}_(instantiateAsync,"instantiateAsync");function getWasmImports(){return{env:wasmImports,wasi_snapshot_preview1:wasmImports,"GOT.mem":new Proxy(wasmImports,GOTHandler),"GOT.func":new Proxy(wasmImports,GOTHandler)}}_(getWasmImports,"getWasmImports");async function createWasm(){function e(o,a){wasmExports=o.exports,wasmExports=relocateExports(wasmExports,1024);var l=getDylinkMetadata(a);if(l.neededDynlibs)dynamicLibraries=l.neededDynlibs.concat(dynamicLibraries);return mergeLibSymbols(wasmExports,"main"),LDSO.init(),loadDylibs(),__RELOC_FUNCS__.push(wasmExports.__wasm_apply_data_relocs),assignWasmExports(wasmExports),wasmExports}_(e,"receiveInstance");function t(o){return e(o.instance,o.module)}_(t,"receiveInstantiationResult");var n=getWasmImports();if(Module.instantiateWasm)return new Promise((o,a)=>{Module.instantiateWasm(n,(l,c)=>{o(e(l,c))})});wasmBinaryFile??=findWasmBinary();var r=await instantiateAsync(wasmBinary,wasmBinaryFile,n),s=t(r);return s}_(createWasm,"createWasm");class ExitStatus{static{_(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=_((e)=>HEAP_DATA_VIEW.getFloat32(e,!0),"LE_HEAP_LOAD_F32"),LE_HEAP_LOAD_F64=_((e)=>HEAP_DATA_VIEW.getFloat64(e,!0),"LE_HEAP_LOAD_F64"),LE_HEAP_LOAD_I16=_((e)=>HEAP_DATA_VIEW.getInt16(e,!0),"LE_HEAP_LOAD_I16"),LE_HEAP_LOAD_I32=_((e)=>HEAP_DATA_VIEW.getInt32(e,!0),"LE_HEAP_LOAD_I32"),LE_HEAP_LOAD_I64=_((e)=>HEAP_DATA_VIEW.getBigInt64(e,!0),"LE_HEAP_LOAD_I64"),LE_HEAP_LOAD_U32=_((e)=>HEAP_DATA_VIEW.getUint32(e,!0),"LE_HEAP_LOAD_U32"),LE_HEAP_STORE_F32=_((e,t)=>HEAP_DATA_VIEW.setFloat32(e,t,!0),"LE_HEAP_STORE_F32"),LE_HEAP_STORE_F64=_((e,t)=>HEAP_DATA_VIEW.setFloat64(e,t,!0),"LE_HEAP_STORE_F64"),LE_HEAP_STORE_I16=_((e,t)=>HEAP_DATA_VIEW.setInt16(e,t,!0),"LE_HEAP_STORE_I16"),LE_HEAP_STORE_I32=_((e,t)=>HEAP_DATA_VIEW.setInt32(e,t,!0),"LE_HEAP_STORE_I32"),LE_HEAP_STORE_I64=_((e,t)=>HEAP_DATA_VIEW.setBigInt64(e,t,!0),"LE_HEAP_STORE_I64"),LE_HEAP_STORE_U32=_((e,t)=>HEAP_DATA_VIEW.setUint32(e,t,!0),"LE_HEAP_STORE_U32"),callRuntimeCallbacks=_((e)=>{while(e.length>0)e.shift()(Module)},"callRuntimeCallbacks"),onPostRuns=[],addOnPostRun=_((e)=>onPostRuns.push(e),"addOnPostRun"),onPreRuns=[],addOnPreRun=_((e)=>onPreRuns.push(e),"addOnPreRun"),UTF8Decoder=typeof TextDecoder<"u"?new TextDecoder:void 0,findStringEnd=_((e,t,n,r)=>{var s=t+n;if(r)return s;while(e[t]&&!(t>=s))++t;return t},"findStringEnd"),UTF8ArrayToString=_((e,t=0,n,r)=>{var s=findStringEnd(e,t,n,r);if(s-t>16&&e.buffer&&UTF8Decoder)return UTF8Decoder.decode(e.subarray(t,s));var o="";while(t<s){var a=e[t++];if(!(a&128)){o+=String.fromCharCode(a);continue}var l=e[t++]&63;if((a&224)==192){o+=String.fromCharCode((a&31)<<6|l);continue}var c=e[t++]&63;if((a&240)==224)a=(a&15)<<12|l<<6|c;else a=(a&7)<<18|l<<12|c<<6|e[t++]&63;if(a<65536)o+=String.fromCharCode(a);else{var u=a-65536;o+=String.fromCharCode(55296|u>>10,56320|u&1023)}}return o},"UTF8ArrayToString"),getDylinkMetadata=_((e)=>{var t=0,n=0;function r(){return e[t++]}_(r,"getU8");function s(){var L=0,H=1;while(!0){var ge=e[t++];if(L+=(ge&127)*H,H*=128,!(ge&128))break}return L}_(s,"getLEB");function o(){var L=s();return t+=L,UTF8ArrayToString(e,t-L,L)}_(o,"getString");function a(){var L=s(),H=[];while(L--)H.push(o());return H}_(a,"getStringList");function l(L,H){if(L)throw Error(H)}if(_(l,"failIf"),e instanceof WebAssembly.Module){var c=WebAssembly.Module.customSections(e,"dylink.0");l(c.length===0,"need dylink section"),e=new Uint8Array(c[0]),n=e.length}else{var u=new Uint32Array(new Uint8Array(e.subarray(0,24)).buffer),d=u[0]==1836278016||u[0]==6386541;l(!d,"need to see wasm magic number"),l(e[8]!==0,"need the dylink section to be first"),t=9;var f=s();n=t+f;var p=o();l(p!=="dylink.0")}var h={neededDynlibs:[],tlsExports:new Set,weakImports:new Set,runtimePaths:[]},x=1,R=2,w=3,v=4,y=5,P=256,D=3,g=1;while(t<n){var k=r(),C=s();if(k===x)h.memorySize=s(),h.memoryAlign=s(),h.tableSize=s(),h.tableAlign=s();else if(k===R)h.neededDynlibs=a();else if(k===w){var M=s();while(M--){var I=o(),F=s();if(F&P)h.tlsExports.add(I)}}else if(k===v){var M=s();while(M--){var B=o(),I=o(),F=s();if((F&D)==g)h.weakImports.add(I)}}else if(k===y)h.runtimePaths=a();else t+=C}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}`)}}_(getValue,"getValue");var newDSO=_((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=_((e,t)=>Math.ceil(e/t)*t,"alignMemory"),getMemory=_((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=_((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=_((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=_((e)=>uleb128EncodeWithLen(Array.from(e,(t)=>{var n=wasmTypeCodes[t];return n})),"generateTypePack"),convertJsFunctionToWasm=_((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=_((e)=>{var t=wasmTableMirror[e];if(!t)wasmTableMirror[e]=t=wasmTable.get(e);return t},"getWasmTableEntry"),updateTableMap=_((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=_((e)=>{if(!functionsInTableMap)functionsInTableMap=new WeakMap,updateTableMap(0,wasmTable.length);return functionsInTableMap.get(e)||0},"getFunctionAddress"),freeTableIndexes=[],getEmptyTableSlot=_(()=>{if(freeTableIndexes.length)return freeTableIndexes.pop();return wasmTable.grow(1)},"getEmptyTableSlot"),setWasmTableEntry=_((e,t)=>{wasmTable.set(e,t),wasmTableMirror[e]=wasmTable.get(e)},"setWasmTableEntry"),addFunction=_((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=_((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=_((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=_((e)=>{var t=wasmImports[e];if(!t||t.stub)return!1;return!0},"isSymbolDefined"),dynCall=_((e,t,n=[],r=!1)=>{var s=getWasmTableEntry(t),o=s(...n);function a(l){return l}return _(a,"convert"),a(o)},"dynCall"),stackSave=_(()=>_emscripten_stack_get_current(),"stackSave"),stackRestore=_((e)=>__emscripten_stack_restore(e),"stackRestore"),createInvokeFunction=_((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=_((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=_((e)=>onPostCtors.push(e),"addOnPostCtor"),UTF8ToString=_((e,t,n)=>e?UTF8ArrayToString(HEAPU8,e,t,n):"","UTF8ToString"),loadWebAssemblyModule=_((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}_(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(_(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)}_(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(_(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(_(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=_((e,t)=>{for(var[n,r]of Object.entries(e)){let s=_((a)=>{if(!isSymbolDefined(a))wasmImports[a]=r},"setImport");s(n);let o="__main_argc_argv";if(n=="main")s(o);if(n==o)s("main")}},"mergeLibSymbols"),asyncLoad=_(async(e)=>{var t=await readAsync(e);return new Uint8Array(t)},"asyncLoad");function loadDynamicLibrary(e,t={global:!0,nodelete:!0},n,r){var s=LDSO.loadedLibsByName[e];if(s){if(!t.global){if(n)Object.assign(n,s.exports)}else if(!s.global)s.global=!0,mergeLibSymbols(s.exports,e);if(t.nodelete&&s.refcount!==1/0)s.refcount=1/0;if(s.refcount++,r)LDSO.loadedLibsByHandle[r]=s;return t.loadAsync?Promise.resolve(!0):!0}s=newDSO(e,r,"loading"),s.refcount=t.nodelete?1/0:1,s.global=t.global;function o(){if(r){var c=LE_HEAP_LOAD_U32((r+28>>2)*4),u=LE_HEAP_LOAD_U32((r+32>>2)*4);if(c&&u){var d=HEAP8.slice(c,c+u);return t.loadAsync?Promise.resolve(d):d}}var f=locateFile(e);if(t.loadAsync)return asyncLoad(f);if(!readBinary)throw Error(`${f}: file not found, and synchronous loading of external files is not available`);return readBinary(f)}_(o,"loadLibData");function a(){if(t.loadAsync)return o().then((c)=>loadWebAssemblyModule(c,t,e,n,r));return loadWebAssemblyModule(o(),t,e,n,r)}_(a,"getExports");function l(c){if(s.global)mergeLibSymbols(c,e);else if(n)Object.assign(n,c);s.exports=c}if(_(l,"moduleLoaded"),t.loadAsync)return a().then((c)=>(l(c),!0));return l(a()),!0}_(loadDynamicLibrary,"loadDynamicLibrary");var reportUndefinedSymbols=_(()=>{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=_((e)=>{if(runDependencies--,Module.monitorRunDependencies?.(runDependencies),runDependencies==0){if(dependenciesFulfilled){var t=dependenciesFulfilled;dependenciesFulfilled=null,t()}}},"removeRunDependency"),addRunDependency=_((e)=>{runDependencies++,Module.monitorRunDependencies?.(runDependencies)},"addRunDependency"),loadDylibs=_(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}`)}}_(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=_(()=>abort(""),"__abort_js");__abort_js.sig="v";var getHeapMax=_(()=>2147483648,"getHeapMax"),growMemory=_((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=_((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=_((e)=>52,"_fd_close");_fd_close.sig="ii";var INT53_MAX=9007199254740992,INT53_MIN=-9007199254740992,bigintToI53Checked=_((e)=>e<INT53_MIN||e>INT53_MAX?NaN:Number(e),"bigintToI53Checked");function _fd_seek(e,t,n,r){return t=bigintToI53Checked(t),70}_(_fd_seek,"_fd_seek"),_fd_seek.sig="iijip";var printCharBuffers=[null,[],[]],printChar=_((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=_((e,t,n,r)=>{var s=0;for(var o=0;o<n;o++){var a=LE_HEAP_LOAD_U32((t>>2)*4),l=LE_HEAP_LOAD_U32((t+4>>2)*4);t+=8;for(var c=0;c<l;c++)printChar(e,HEAPU8[a+c]);s+=l}return LE_HEAP_STORE_U32((r>>2)*4,s),0},"_fd_write");_fd_write.sig="iippp";function _tree_sitter_log_callback(e,t){if(Module.currentLogCallback){let n=UTF8ToString(t);Module.currentLogCallback(n,e!==0)}}_(_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")}_(_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}_(_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}_(_tree_sitter_query_progress_callback,"_tree_sitter_query_progress_callback");var runtimeKeepaliveCounter=0,keepRuntimeAlive=_(()=>noExitRuntime||runtimeKeepaliveCounter>0,"keepRuntimeAlive"),_proc_exit=_((e)=>{if(EXITSTATUS=e,!keepRuntimeAlive())Module.onExit?.(e),ABORT=!0;quit_(e,new ExitStatus(e))},"_proc_exit");_proc_exit.sig="vi";var exitJS=_((e,t)=>{EXITSTATUS=e,_proc_exit(e)},"exitJS"),handleException=_((e)=>{if(e instanceof ExitStatus||e=="unwind")return EXITSTATUS;quit_(1,e)},"handleException"),lengthBytesUTF8=_((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=_((e,t,n,r)=>{if(!(r>0))return 0;var s=n,o=n+r-1;for(var a=0;a<e.length;++a){var l=e.codePointAt(a);if(l<=127){if(n>=o)break;t[n++]=l}else if(l<=2047){if(n+1>=o)break;t[n++]=192|l>>6,t[n++]=128|l&63}else if(l<=65535){if(n+2>=o)break;t[n++]=224|l>>12,t[n++]=128|l>>6&63,t[n++]=128|l&63}else{if(n+3>=o)break;t[n++]=240|l>>18,t[n++]=128|l>>12&63,t[n++]=128|l>>6&63,t[n++]=128|l&63,a++}}return t[n]=0,n-s},"stringToUTF8Array"),stringToUTF8=_((e,t,n)=>stringToUTF8Array(e,HEAPU8,t,n),"stringToUTF8"),stackAlloc=_((e)=>__emscripten_stack_alloc(e),"stackAlloc"),stringToUTF8OnStack=_((e)=>{var t=lengthBytesUTF8(e)+1,n=stackAlloc(t);return stringToUTF8(e,n,t),n},"stringToUTF8OnStack"),AsciiToString=_((e)=>{var t="";while(!0){var n=HEAPU8[e++];if(!n)return t;t+=String.fromCharCode(n)}},"AsciiToString"),stringToUTF16=_((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}_(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}_(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)}}_(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(_(t,"doRun"),Module.setStatus)Module.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>Module.setStatus(""),1),t()},1);else t()}_(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 sf(e){return rf??=await jv(e)}function of(){return!!rf}function af(e,t,n,r){if(e.length!==3)throw Error(`Wrong number of arguments to \`#${n}\` predicate. Expected 2, got ${e.length-1}`);if(!Yd(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(Yd(e[2])){let a=e[1].name,l=e[2].name;r[t].push((c)=>{let u=[],d=[];for(let p of c){if(p.name===a)u.push(p.node);if(p.name===l)d.push(p.node)}let f=_((p,h,x)=>x?p.text===h.text:p.text!==h.text,"compare");return o?u.every((p)=>d.some((h)=>f(p,h,s))):u.some((p)=>d.some((h)=>f(p,h,s)))})}else{let a=e[1].name,l=e[2].value,c=_((d)=>d.text===l,"matches"),u=_((d)=>d.text!==l,"doesNotMatch");r[t].push((d)=>{let f=[];for(let h of d)if(h.name===a)f.push(h.node);let p=s?c:u;return o?f.every(p):f.some(p)})}}function lf(e,t,n,r){if(e.length!==3)throw Error(`Wrong number of arguments to \`#${n}\` predicate. Expected 2, got ${e.length-1}.`);if(e[1].type!=="capture")throw Error(`First argument of \`#${n}\` predicate must be a capture. Got "${e[1].value}".`);if(e[2].type!=="string")throw Error(`Second argument of \`#${n}\` predicate must be a string. Got @${e[2].name}.`);let s=n==="match?"||n==="any-match?",o=!n.startsWith("any-"),a=e[1].name,l=new RegExp(e[2].value);r[t].push((c)=>{let u=[];for(let f of c)if(f.name===a)u.push(f.node.text);let d=_((f,p)=>p?l.test(f):!l.test(f),"test");if(u.length===0)return!s;return o?u.every((f)=>d(f,s)):u.some((f)=>d(f,s))})}function cf(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(wl))throw Error(`Arguments to \`#${n}\` predicate must be strings.".`);let l=a.map((c)=>c.value);r[t].push((c)=>{let u=[];for(let d of c)if(d.name===o)u.push(d.node.text);if(u.length===0)return!s;return u.every((d)=>l.includes(d))===s})}function uf(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(wl))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 df(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(wl))throw Error('Arguments to `#set!` predicate must be strings.".');if(!n[t])n[t]={};n[t][e[1].value]=e[2]?.value??null}function ff(e,t,n,r,s,o,a,l,c,u,d){if(t===Uv){let f=r[n];o.push({type:"capture",name:f})}else if(t===Bv)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?":af(o,e,f,a);break;case"any-not-match?":case"not-match?":case"any-match?":case"match?":lf(o,e,f,a);break;case"not-any-of?":case"any-of?":cf(o,e,f,a);break;case"is?":case"is-not?":uf(o,e,f,u,d);break;case"set!":df(o,e,c);break;default:l[e].push({operator:f,operands:o.slice(1)})}o.length=0}}var Mv,_=(e,t)=>Mv(e,"name",{value:t,configurable:!0}),QC,Xd=2,J=4,fl,ct,tn,xi,lt,On,m,Tv,Nv,Dv,Fv,Lv,_l,jv,rf=null,V,pl,hl,yl,Uv=1,Bv=2,qv,eI,Yd,wl,Ut,bi,bl;var pf=Ue(()=>{Mv=Object.defineProperty,QC=class{static{_(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}},fl=4*J,ct=5*J,tn=2*J,xi=2*J+2*tn,lt={row:0,column:0},On=Symbol("INTERNAL");_(xr,"assertInternal");_(vi,"isPoint");_(Zd,"setModule");Tv=class{static{_(this,"LookaheadIterator")}[0]=0;language;constructor(e,t,n){xr(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:_(()=>{if(m._ts_lookahead_iterator_next(this[0]))return{done:!1,value:this.currentType};return{done:!0,value:""}},"next")}}};_(gl,"getText");Nv=class e{static{_(this,"Tree")}[0]=0;textCallback;language;constructor(t,n,r,s){xr(t),this[0]=n,this.language=r,this.textCallback=s}copy(){let t=m._ts_tree_copy(this[0]);return new e(On,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+ct;return m.setValue(r,t,"i32"),At(r+J,n),m._ts_tree_root_node_with_offset_wasm(this[0]),Ie(this)}edit(t){ef(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+J,"i32"),s=Array(n);if(n>0){let o=r;for(let a=0;a<n;a++)s[a]=to(o),o+=xi;m._free(r)}return s}getIncludedRanges(){m._ts_tree_included_ranges_wasm(this[0]);let t=m.getValue(V,"i32"),n=m.getValue(V+J,"i32"),r=Array(t);if(t>0){let s=n;for(let o=0;o<t;o++)r[o]=to(s),s+=xi;m._free(n)}return r}},Dv=class e{static{_(this,"TreeCursor")}[0]=0;[1]=0;[2]=0;[3]=0;tree;constructor(t,n){xr(t),this.tree=n,kt(this)}copy(){let t=new e(On,this.tree);return m._ts_tree_cursor_copy_wasm(this.tree[0]),kt(t),t}delete(){be(this),m._ts_tree_cursor_delete_wasm(this.tree[0]),this[0]=this[1]=this[2]=0}get currentNode(){return be(this),m._ts_tree_cursor_current_node_wasm(this.tree[0]),Ie(this.tree)}get currentFieldId(){return be(this),m._ts_tree_cursor_current_field_id_wasm(this.tree[0])}get currentFieldName(){return this.tree.language.fields[this.currentFieldId]}get currentDepth(){return be(this),m._ts_tree_cursor_current_depth_wasm(this.tree[0])}get currentDescendantIndex(){return be(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 be(this),m._ts_tree_cursor_current_node_type_id_wasm(this.tree[0])}get nodeStateId(){return be(this),m._ts_tree_cursor_current_node_state_id_wasm(this.tree[0])}get nodeId(){return be(this),m._ts_tree_cursor_current_node_id_wasm(this.tree[0])}get nodeIsNamed(){return be(this),m._ts_tree_cursor_current_node_is_named_wasm(this.tree[0])===1}get nodeIsMissing(){return be(this),m._ts_tree_cursor_current_node_is_missing_wasm(this.tree[0])===1}get nodeText(){be(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=Zn(V);return gl(this.tree,t,n,r)}get startPosition(){return be(this),m._ts_tree_cursor_start_position_wasm(this.tree[0]),Zn(V)}get endPosition(){return be(this),m._ts_tree_cursor_end_position_wasm(this.tree[0]),Zn(V)}get startIndex(){return be(this),m._ts_tree_cursor_start_index_wasm(this.tree[0])}get endIndex(){return be(this),m._ts_tree_cursor_end_index_wasm(this.tree[0])}gotoFirstChild(){be(this);let t=m._ts_tree_cursor_goto_first_child_wasm(this.tree[0]);return kt(this),t===1}gotoLastChild(){be(this);let t=m._ts_tree_cursor_goto_last_child_wasm(this.tree[0]);return kt(this),t===1}gotoParent(){be(this);let t=m._ts_tree_cursor_goto_parent_wasm(this.tree[0]);return kt(this),t===1}gotoNextSibling(){be(this);let t=m._ts_tree_cursor_goto_next_sibling_wasm(this.tree[0]);return kt(this),t===1}gotoPreviousSibling(){be(this);let t=m._ts_tree_cursor_goto_previous_sibling_wasm(this.tree[0]);return kt(this),t===1}gotoDescendant(t){be(this),m._ts_tree_cursor_goto_descendant_wasm(this.tree[0],t),kt(this)}gotoFirstChildForIndex(t){be(this),m.setValue(V+fl,t,"i32");let n=m._ts_tree_cursor_goto_first_child_for_index_wasm(this.tree[0]);return kt(this),n===1}gotoFirstChildForPosition(t){be(this),At(V+fl,t);let n=m._ts_tree_cursor_goto_first_child_for_position_wasm(this.tree[0]);return kt(this),n===1}reset(t){oe(t),be(this,V+ct),m._ts_tree_cursor_reset_wasm(this.tree[0]),kt(this)}resetTo(t){be(this,V),be(t,V+fl),m._ts_tree_cursor_reset_to_wasm(this.tree[0],t.tree[0]),kt(this)}},Fv=class{static{_(this,"Node")}[0]=0;_children;_namedChildren;constructor(e,{id:t,tree:n,startIndex:r,startPosition:s,other:o}){xr(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]),Zn(V)}get text(){return gl(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),Ie(this.tree)}namedChild(e){return oe(this),m._ts_node_named_child_wasm(this.tree[0],e),Ie(this.tree)}childForFieldId(e){return oe(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){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(V,"i32"),n=m.getValue(V+J,"i32"),r=Array(t);if(t>0){let s=n;for(let o=0;o<t;o++)r[o]=Ie(this.tree,s),s+=ct;m._free(n)}return r}firstChildForIndex(e){oe(this);let t=V+ct;return m.setValue(t,e,"i32"),m._ts_node_first_child_for_byte_wasm(this.tree[0]),Ie(this.tree)}firstNamedChildForIndex(e){oe(this);let t=V+ct;return m.setValue(t,e,"i32"),m._ts_node_first_named_child_for_byte_wasm(this.tree[0]),Ie(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(V,"i32"),t=m.getValue(V+J,"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+=ct;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(V,"i32"),t=m.getValue(V+J,"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+=ct;m._free(t)}}return this._namedChildren}descendantsOfType(e,t=lt,n=lt){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(J*r.length);for(let u=0,d=r.length;u<d;u++)m.setValue(o+u*J,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(V,"i32"),l=m.getValue(V+J,"i32"),c=Array(a);if(a>0){let u=l;for(let d=0;d<a;d++)c[d]=Ie(this.tree,u),u+=ct}return m._free(l),m._free(o),c}get nextSibling(){return oe(this),m._ts_node_next_sibling_wasm(this.tree[0]),Ie(this.tree)}get previousSibling(){return oe(this),m._ts_node_prev_sibling_wasm(this.tree[0]),Ie(this.tree)}get nextNamedSibling(){return oe(this),m._ts_node_next_named_sibling_wasm(this.tree[0]),Ie(this.tree)}get previousNamedSibling(){return oe(this),m._ts_node_prev_named_sibling_wasm(this.tree[0]),Ie(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]),Ie(this.tree)}childWithDescendant(e){return oe(this),oe(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");oe(this);let n=V+ct;return m.setValue(n,e,"i32"),m.setValue(n+J,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");oe(this);let n=V+ct;return m.setValue(n,e,"i32"),m.setValue(n+J,t,"i32"),m._ts_node_named_descendant_for_index_wasm(this.tree[0]),Ie(this.tree)}descendantForPosition(e,t=e){if(!vi(e)||!vi(t))throw Error("Arguments must be {row, column} objects");oe(this);let n=V+ct;return At(n,e),At(n+tn,t),m._ts_node_descendant_for_position_wasm(this.tree[0]),Ie(this.tree)}namedDescendantForPosition(e,t=e){if(!vi(e)||!vi(t))throw Error("Arguments must be {row, column} objects");oe(this);let n=V+ct;return At(n,e),At(n+tn,t),m._ts_node_named_descendant_for_position_wasm(this.tree[0]),Ie(this.tree)}walk(){return oe(this),m._ts_tree_cursor_new_wasm(this.tree[0]),new Dv(On,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}};_(ml,"unmarshalCaptures");_(oe,"marshalNode");_(Ie,"unmarshalNode");_(be,"marshalTreeCursor");_(kt,"unmarshalTreeCursor");_(At,"marshalPoint");_(Zn,"unmarshalPoint");_(Qd,"marshalRange");_(to,"unmarshalRange");_(ef,"marshalEdit");_(tf,"unmarshalLanguageMetadata");Lv=/^tree_sitter_\w+$/,_l=class e{static{_(this,"Language")}[0]=0;types;fields;constructor(t,n){xr(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 tf(V+J)}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+J,"i32"),r=Array(t);if(t>0){let s=n;for(let o=0;o<t;o++)r[o]=m.getValue(s,"i16"),s+=Xd}return r}subtypes(t){m._ts_language_subtypes_wasm(this[0],t);let n=m.getValue(V,"i32"),r=m.getValue(V+J,"i32"),s=Array(n);if(n>0){let o=r;for(let a=0;a<n;a++)s[a]=m.getValue(o,"i16"),o+=Xd}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 Tv(On,n,this);return null}static async load(t){let n;if(t instanceof Uint8Array)n=t;else if(globalThis.process?.versions.node){let l=await import("fs/promises");n=await l.readFile(t)}else{let l=await fetch(t);if(!l.ok){let u=await l.text();throw Error(`Language.load failed with status ${l.status}.
|
|
29
|
+
|
|
30
|
+
${u}`)}let c=l.clone();try{n=await WebAssembly.compileStreaming(l)}catch(u){console.error("wasm streaming compile failed:",u),console.error("falling back to ArrayBuffer instantiation"),n=new Uint8Array(await c.arrayBuffer())}}let r=await m.loadWebAssemblyModule(n,{loadAsync:!0}),s=Object.keys(r),o=s.find((l)=>Lv.test(l)&&!l.includes("external_scanner_"));if(!o)throw console.log(`Couldn't find language function in Wasm file. Symbols:
|
|
31
|
+
${JSON.stringify(s,null,2)}`),Error("Language.load failed: no language function found in Wasm file");let a=r[o]();return new e(On,a)}};_(nf,"Module");jv=nf;_(sf,"initializeBinding");_(of,"checkModule");yl=class{static{_(this,"Parser")}[0]=0;[1]=0;logCallback=null;language=null;static async init(e){Zd(await sf(e)),V=m._ts_init(),pl=m.getValue(V,"i32"),hl=m.getValue(V+J,"i32")}constructor(){this.initialize()}initialize(){if(!of())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+J,"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===_l){t=e[0];let n=m._ts_language_abi_version(t);if(n<hl||pl<n)throw Error(`Incompatible language version ${n}. Compatibility range ${hl} through ${pl}.`);this.language=e}else throw Error("Argument must be a Language");return m._ts_parser_set_language(this[0],t),this}parse(e,t,n){if(typeof e==="string")m.currentParseCallback=(l)=>e.slice(l);else if(typeof e==="function")m.currentParseCallback=e;else throw Error("Argument must be a string or a function");if(n?.progressCallback)m.currentProgressCallback=n.progressCallback;else m.currentProgressCallback=null;if(this.logCallback)m.currentLogCallback=this.logCallback,m._ts_parser_enable_logger_wasm(this[0],1);else m.currentLogCallback=null,m._ts_parser_enable_logger_wasm(this[0],0);let r=0,s=0;if(n?.includedRanges){r=n.includedRanges.length,s=m._calloc(r,xi);let l=s;for(let c=0;c<r;c++)Qd(l,n.includedRanges[c]),l+=xi}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 Nv(On,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+J,"i32"),n=Array(e);if(e>0){let r=t;for(let s=0;s<e;s++)n[s]=to(r),r+=xi;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}},qv=/[\w-]+/g,eI={Zero:0,ZeroOrOne:1,ZeroOrMore:2,One:3,OneOrMore:4},Yd=_((e)=>e.type==="capture","isCaptureStep"),wl=_((e)=>e.type==="string","isStringStep"),Ut={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{_(this,"QueryError")}static formatMessage(t,n){switch(t){case Ut.NodeName:return`Bad node name '${n.word}'`;case Ut.FieldName:return`Bad field name '${n.word}'`;case Ut.CaptureName:return`Bad capture name @${n.word}`;case Ut.PatternStructure:return`Bad pattern structure at offset ${n.suffix}`;case Ut.Syntax:return`Bad syntax at offset ${n.suffix}`}}};_(af,"parseAnyPredicate");_(lf,"parseMatchPredicate");_(cf,"parseAnyOfPredicate");_(uf,"parseIsPredicate");_(df,"parseSetDirective");_(ff,"parsePattern");bl=class{static{_(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+J);if(!s){let w=m.getValue(V+J,"i32"),v=m.getValue(V,"i32"),y=m.UTF8ToString(r,v).length,P=t.slice(y,y+100).split(`
|
|
32
|
+
`)[0],D=P.match(qv)?.[0]??"";switch(m._free(r),w){case Ut.Syntax:throw new bi(Ut.Syntax,{suffix:`${y}: '${P}'...`},y,0);case Ut.NodeName:throw new bi(w,{word:D},y,D.length);case Ut.FieldName:throw new bi(w,{word:D},y,D.length);case Ut.CaptureName:throw new bi(w,{word:D},y,D.length);case Ut.PatternStructure:throw new bi(w,{suffix:`${y}: '${P}'...`},y,0)}}let o=m._ts_query_string_count(s),a=m._ts_query_capture_count(s),l=m._ts_query_pattern_count(s),c=Array(a),u=Array(l),d=Array(o);for(let w=0;w<a;w++){let v=m._ts_query_capture_name_for_id(s,w,V),y=m.getValue(V,"i32");c[w]=m.UTF8ToString(v,y)}for(let w=0;w<l;w++){let v=Array(a);for(let y=0;y<a;y++){let P=m._ts_query_capture_quantifier_for_id(s,w,y);v[y]=P}u[w]=v}for(let w=0;w<o;w++){let v=m._ts_query_string_value_for_id(s,w,V),y=m.getValue(V,"i32");d[w]=m.UTF8ToString(v,y)}let f=Array(l),p=Array(l),h=Array(l),x=Array(l),R=Array(l);for(let w=0;w<l;w++){let v=m._ts_query_predicates_for_pattern(s,w,V),y=m.getValue(V,"i32");x[w]=[],R[w]=[];let P=[],D=v;for(let g=0;g<y;g++){let k=m.getValue(D,"i32");D+=J;let C=m.getValue(D,"i32");D+=J,ff(w,k,C,c,d,P,R,x,f,p,h)}Object.freeze(R[w]),Object.freeze(x[w]),Object.freeze(f[w]),Object.freeze(p[w]),Object.freeze(h[w])}m._free(r),this[0]=s,this.captureNames=c,this.captureQuantifiers=u,this.textPredicates=R,this.predicates=x,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??lt,r=t.endPosition??lt,s=t.startIndex??0,o=t.endIndex??0,a=t.startContainingPosition??lt,l=t.endContainingPosition??lt,c=t.startContainingIndex??0,u=t.endContainingIndex??0,d=t.matchLimit??4294967295,f=t.maxStartDepth??4294967295,p=t.progressCallback;if(typeof d!=="number")throw Error("Arguments must be numbers");if(this.matchLimit=d,o!==0&&s>o)throw Error("`startIndex` cannot be greater than `endIndex`");if(r!==lt&&(n.row>r.row||n.row===r.row&&n.column>r.column))throw Error("`startPosition` cannot be greater than `endPosition`");if(u!==0&&c>u)throw Error("`startContainingIndex` cannot be greater than `endContainingIndex`");if(l!==lt&&(a.row>l.row||a.row===l.row&&a.column>l.column))throw Error("`startContainingPosition` cannot be greater than `endContainingPosition`");if(p)m.currentQueryProgressCallback=p;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,l.row,l.column,c,u,d,f);let h=m.getValue(V,"i32"),x=m.getValue(V+J,"i32"),R=m.getValue(V+2*J,"i32"),w=Array(h);this.exceededMatchLimit=Boolean(R);let v=0,y=x;for(let P=0;P<h;P++){let D=m.getValue(y,"i32");y+=J;let g=m.getValue(y,"i32");y+=J;let k=Array(g);if(y=ml(this,e.tree,y,D,k),this.textPredicates[D].every((C)=>C(k))){w[v]={patternIndex:D,captures:k};let C=this.setProperties[D];w[v].setProperties=C;let M=this.assertedProperties[D];w[v].assertedProperties=M;let I=this.refutedProperties[D];w[v].refutedProperties=I,v++}}return w.length=v,m._free(x),m.currentQueryProgressCallback=null,w}captures(e,t={}){let n=t.startPosition??lt,r=t.endPosition??lt,s=t.startIndex??0,o=t.endIndex??0,a=t.startContainingPosition??lt,l=t.endContainingPosition??lt,c=t.startContainingIndex??0,u=t.endContainingIndex??0,d=t.matchLimit??4294967295,f=t.maxStartDepth??4294967295,p=t.progressCallback;if(typeof d!=="number")throw Error("Arguments must be numbers");if(this.matchLimit=d,o!==0&&s>o)throw Error("`startIndex` cannot be greater than `endIndex`");if(r!==lt&&(n.row>r.row||n.row===r.row&&n.column>r.column))throw Error("`startPosition` cannot be greater than `endPosition`");if(u!==0&&c>u)throw Error("`startContainingIndex` cannot be greater than `endContainingIndex`");if(l!==lt&&(a.row>l.row||a.row===l.row&&a.column>l.column))throw Error("`startContainingPosition` cannot be greater than `endContainingPosition`");if(p)m.currentQueryProgressCallback=p;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,l.row,l.column,c,u,d,f);let h=m.getValue(V,"i32"),x=m.getValue(V+J,"i32"),R=m.getValue(V+2*J,"i32"),w=[];this.exceededMatchLimit=Boolean(R);let v=[],y=x;for(let P=0;P<h;P++){let D=m.getValue(y,"i32");y+=J;let g=m.getValue(y,"i32");y+=J;let k=m.getValue(y,"i32");if(y+=J,v.length=g,y=ml(this,e.tree,y,D,v),this.textPredicates[D].every((C)=>C(v))){let C=v[k],M=this.setProperties[D];C.setProperties=M;let I=this.assertedProperties[D];C.assertedProperties=I;let F=this.refutedProperties[D];C.refutedProperties=F,w.push(C)}}return m._free(x),m.currentQueryProgressCallback=null,w}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 hf,readFileSync as Hv,statSync as Kv}from"fs";import{dirname as Wv,join as ki,posix as kr}from"path";function mf(e,t){let n=import.meta.dir;for(let s of[process.env.DIFFLOUPE_WASM_DIR,ki(n,"wasm")])if(s&&hf(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(hf(o))return o;let a=Wv(r);if(a===r)break;r=a}throw Error(`Could not locate ${e}/${t} in any parent node_modules of ${n}`)}class Rr{parser;loaded=new Map;constructor(e){this.parser=e}static async create(){return await yl.init({locateFile:(e)=>mf("web-tree-sitter",e)}),new Rr(new yl)}async load(e){let t=this.loaded.get(e);if(t)return t;let[n,r]=Xv[e],s=await _l.load(mf(n,r)),o=e==="cpp",a={language:s,definitions:new bl(s,o?zv:Vv),imports:new bl(s,o?Jv:Gv)};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=jt(t);if(!r)return null;let s;try{s=Hv(e,"utf-8")}catch{return null}return this.parseSource(s,t,n,r)}async parseSource(e,t,n,r){let s=r??jt(t);if(!s)return null;let{language:o,definitions:a,imports:l}=await this.load(s);this.parser.setLanguage(o);let c=this.parser.parse(e);if(!c)return null;try{let u=c.rootNode,d=tx(u,e,a,s),{resolved:f,external:p}=lx(u,e,l,t,n,s);return{path:t,language:s,lines:e.length===0?0:e.replace(/\n$/,"").split(`
|
|
33
|
+
`).length,symbols:d,imports:f,externalImports:p,parseError:u.hasError}}finally{c.delete()}}}function tx(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 v of u.captures){let y=v.node;if(v.name==="name")d=y;else if(v.name.startsWith("definition."))f=y,p=v.name.slice(11)}if(!d||!f||!p)continue;if(nx(f,r))continue;let h=d.text,x=f.startPosition.row+1,R=`${p}:${h}:${x}`;if(o.has(R))continue;o.add(R);let w=rx(f);a.push({name:h,kind:p,line:x,exported:sx(f,r),...w?{container:w}:{},signature:ox(f,t,r)})}let l=new Set(a.filter((u)=>u.kind!=="variable").map((u)=>`${u.name}:${u.line}`)),c=a.filter((u)=>u.kind!=="variable"||!l.has(`${u.name}:${u.line}`));return c.sort((u,d)=>u.line-d.line),c}function nx(e,t){if(t==="cpp")return!1;let n=e.parent;while(n){if(n.type==="object")return!0;if(Qv.has(n.type))return!1;n=n.parent}return!1}function rx(e){let t=e.parent;while(t){if(Yv.has(t.type)){let n=t.childForFieldName("name");if(n)return n.text}t=t.parent}return}function sx(e,t){let n=e;while(n){if(t==="cpp"){if(Zv.has(n.type)&&n!==e)return!1}else{if(ix.has(n.type)&&n!==e)return!1;if(n.type==="export_statement")return!0}n=n.parent}return t==="cpp"}function ox(e,t,n){let r=e;if(n==="cpp"&&e.type==="function_declarator"){let l=e.parent;while(l){if(ex.has(l.type)){r=l;break}l=l.parent}}if(r.type==="variable_declarator"){let l=r.parent?.text.trimStart().split(/\s/)[0]??"const",u=r.childForFieldName("value")?.childForFieldName("body"),d=u&&u.startIndex>r.startIndex?u.startIndex:r.endIndex;return gf(`${l} ${t.slice(r.startIndex,d)}`)}let s=r.childForFieldName("body"),o=s&&s.startIndex>r.startIndex?s.startIndex:r.endIndex,a=t.slice(r.startIndex,o);return gf(a)}function gf(e,t=160){let n=e.replace(/\/\*[\s\S]*?\*\//g," ").split(`
|
|
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 lx(e,t,n,r,s,o){let a=n.matches(e),l=new Set,c=new Set,u=kr.dirname(r.replace(/\\/g,"/"));for(let d of a)for(let f of d.captures){if(f.name!=="path")continue;let p=f.node.text.replace(/^["'<]|["'>]$/g,"");if(!p)continue;let h=o==="cpp"?dx(p,u,s):ux(p,u,s);if(h)l.add(h);else c.add(p)}return{resolved:[...l].sort(),external:[...c].sort()}}function cx(e){try{return Kv(e).isFile()}catch{return!1}}function vl(e,t){let n=kr.normalize(t.replace(/\\/g,"/"));if(n===".."||n.startsWith("../")||kr.isAbsolute(n))return null;if(typeof e==="string")return cx(ki(e,n))?n:null;return e.has(n)?n:null}function ux(e,t,n){if(!e.startsWith("."))return null;let r=kr.join(t,e);for(let s of ax){let o=vl(n,`${r}${s}`);if(o)return o}return null}function dx(e,t,n){if(e.startsWith("/"))return null;let r=t;for(;;){let s=vl(n,kr.join(r,e));if(s)return s;let o=kr.dirname(r);if(o===r||r==="."||r==="")break;r=o}return vl(n,e)}var Vv=`
|
|
36
|
+
(function_declaration name: (identifier) @name) @definition.function
|
|
37
|
+
(generator_function_declaration name: (identifier) @name) @definition.function
|
|
38
|
+
(function_signature name: (identifier) @name) @definition.function
|
|
39
|
+
|
|
40
|
+
(class_declaration name: (type_identifier) @name) @definition.class
|
|
41
|
+
(abstract_class_declaration name: (type_identifier) @name) @definition.class
|
|
42
|
+
|
|
43
|
+
(interface_declaration name: (type_identifier) @name) @definition.interface
|
|
44
|
+
(type_alias_declaration name: (type_identifier) @name) @definition.type
|
|
45
|
+
(enum_declaration name: (identifier) @name) @definition.enum
|
|
46
|
+
(internal_module name: (identifier) @name) @definition.module
|
|
47
|
+
|
|
48
|
+
(method_definition name: (property_identifier) @name) @definition.method
|
|
49
|
+
(method_signature name: (property_identifier) @name) @definition.method
|
|
50
|
+
(abstract_method_signature name: (property_identifier) @name) @definition.method
|
|
51
|
+
|
|
52
|
+
(variable_declarator
|
|
53
|
+
name: (identifier) @name
|
|
54
|
+
value: [(arrow_function) (function_expression)]) @definition.function
|
|
55
|
+
|
|
56
|
+
; Any other value binding. A registry in this codebase is usually an exported
|
|
57
|
+
; const object, which is exactly the shape the pattern above does not match, and
|
|
58
|
+
; the symbol index is what the map's "added here but not to its siblings" pass
|
|
59
|
+
; reads. Declarators bound to a function match both patterns; collectSymbols
|
|
60
|
+
; keeps the function one.
|
|
61
|
+
(variable_declarator name: (identifier) @name) @definition.variable
|
|
62
|
+
`,Gv=`
|
|
63
|
+
(import_statement source: (string) @path)
|
|
64
|
+
(export_statement source: (string) @path)
|
|
65
|
+
`,zv=`
|
|
66
|
+
(struct_specifier name: (type_identifier) @name body: (_)) @definition.class
|
|
67
|
+
; A body is required for the same reason struct_specifier requires one: without
|
|
68
|
+
; it, a forward declaration indexes as a definition, and the symbol index then
|
|
69
|
+
; attributes the class to every file that forward-declares it.
|
|
70
|
+
(class_specifier name: (type_identifier) @name body: (_)) @definition.class
|
|
71
|
+
(declaration type: (union_specifier name: (type_identifier) @name)) @definition.class
|
|
72
|
+
|
|
73
|
+
(function_declarator declarator: (identifier) @name) @definition.function
|
|
74
|
+
(function_declarator declarator: (field_identifier) @name) @definition.method
|
|
75
|
+
(function_declarator
|
|
76
|
+
declarator: (qualified_identifier
|
|
77
|
+
scope: (namespace_identifier)
|
|
78
|
+
name: (identifier) @name)) @definition.method
|
|
79
|
+
|
|
80
|
+
(type_definition declarator: (type_identifier) @name) @definition.type
|
|
81
|
+
(enum_specifier name: (type_identifier) @name) @definition.enum
|
|
82
|
+
(namespace_definition name: (namespace_identifier) @name) @definition.module
|
|
83
|
+
`,Jv=`
|
|
84
|
+
(preproc_include path: (string_literal) @path)
|
|
85
|
+
`,Xv,Yv,Zv,Qv,ex,ix,ax;var xl=Ue(()=>{hi();pf();Xv={typescript:["tree-sitter-typescript","tree-sitter-typescript.wasm"],tsx:["tree-sitter-typescript","tree-sitter-tsx.wasm"],cpp:["tree-sitter-cpp","tree-sitter-cpp.wasm"]};Yv=new Set(["class_declaration","abstract_class_declaration","interface_declaration","class_specifier","struct_specifier"]),Zv=new Set(["compound_statement"]),Qv=new Set(["class_body","interface_body","statement_block","program"]),ex=new Set(["field_declaration","declaration","function_definition","template_declaration"]);ix=new Set(["statement_block","arrow_function","function_expression"]);ax=["",".ts",".tsx",".d.ts",".js",".jsx","/index.ts","/index.tsx","/index.js"]});import{createHash as mx}from"crypto";function Bt(e,t){let n=t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim();return mx("sha1").update(`${e}\x00${n}`).digest("hex").slice(0,10)}function gx(e){return String(e).replace(/\s+/g,"_").replace(/-{2,}/g,"-").replace(/>/g,"_")}function Qn(e,t={}){let n=[`kind=${e}`];for(let[r,s]of Object.entries(t))n.push(`${r}=${gx(s)}`);return`<!-- ${wf} ${n.join(" ")} -->`}function kl(e){return e.replace(new RegExp(`[ \\t]*${bf.source}`,"g"),"").replace(/\n{3,}/g,`
|
|
86
|
+
|
|
87
|
+
`).trimEnd()}function yx(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(!_x.includes(n))return null;return delete t.kind,{kind:n,fields:t}}function $r(e){let t=[];for(let n of e.matchAll(bf)){let r=yx(n[1]);if(r)t.push(r)}return t}function Rl(e,t){return $r(e).find((n)=>n.kind===t)??null}function wx(e){return $r(e)[0]??null}function no(e,t,n){if(t!=null&&t!=="Bot")return!1;if(n!==void 0)return Rl(e,n)!==null;return $r(e).length>0}function vf(e){let t=new Set;for(let n of e){let r=n.body??"";if(!n.in_reply_to_id||!no(r,n.user?.type,"reply"))continue;let s=wx(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 wf="ai-review",bf,_x;var $i=Ue(()=>{bf=new RegExp(`<!--\\s*${wf}\\s+([^>]*?)\\s*-->`,"g");_x=["summary","summary-item","inline","reply"]});function Er(e){if(Fx.some((t)=>e.includes(t)))return"skip";if(Bf.test(e)||Bf.test(e.split("/").pop()??""))return"docs";return"code"}var Fx,Bf;var Si=Ue(()=>{Fx=["pnpm-lock.yaml","package-lock.json","bun.lock","yarn.lock","Cargo.lock","go.sum",".min.js",".min.css",".bundle.js",".map","__snapshots__/"],Bf=/\.(md|mdx|txt|rst)$|^LICENSE|^\.gitignore$|^\.gitattributes$/});function Vf(e){let t=e.filter((r)=>r.severity==="blocker").length,n=e.filter((r)=>r.severity==="should-fix").length;if(t)return{level:"high",label:"Merge risk: high",detail:`${t} ${t===1?"blocker":"blockers"} open.`};if(n)return{level:"moderate",label:"Merge risk: moderate",detail:`${n} should-fix ${n===1?"finding":"findings"} open.`};return{level:"low",label:"Merge risk: low",detail:"nothing found that should block this."}}function Gf(e){let t=e.filter((r)=>r.surface==="product"),n=t.filter(nk).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 zf(e){let t=new Set(e);return Kf.find((n)=>t.has(n))??"product"}var Ot,Kf,Wf,nk=(e)=>e.severity==="blocker"||e.severity==="should-fix";var po=Ue(()=>{Ot={product:0,deploy:1,tooling:2},Kf=["product","deploy","tooling"],Wf={product:"Prod risk",deploy:"Deploy risk",tooling:"Main findings \u2014 tooling"}});function Ze(e){if(/\.(test|spec)\.[cm]?[jt]sx?$/.test(e))return"tooling";if(Yn.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(Yn.tooling.some((t)=>new RegExp(t).test(e)))return"tooling";if(/^\./.test(e))return"tooling";if(!e.includes("/"))return"tooling";return"product"}function Jf(e,t){let n=e.length?e:t.map((r)=>r.file);return zf(n.map(Ze))}function Zf(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 ho(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 Xf,Cr,ut,Yf,Qf;var Ir=Ue(()=>{xt();po();po();Xf={product:"",deploy:"\uD83D\uDEA2 deploy",tooling:"\uD83D\uDD27 tooling"},Cr=["high","medium","low"],ut={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}},Yf={quick:"\u26A1 Quick fix",moderate:"\uD83D\uDD28 Some work",involved:"\uD83C\uDFD7\uFE0F Involved"};Qf={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"}});import{posix as Ml}from"path";function wp(e){let t=Ml.dirname(e);return t==="."?void 0:Ml.basename(t)}function bk(e){let t=Ml.basename(e);if(!mp.test(t))return t;let n=t.replace(mp,"").replace(/\.d$/,""),r=wp(e);return wk.has(n.toLowerCase())&&r?`${r}/${n}`:n}function vk(e){return e.replace(/[._-](?:test|spec)(\.[^./]+)$/,"$1")}function xk(e,t){let n=new Map;for(let r of e){let s=vk(r),o=n.get(s)??{path:s,label:bk(s),weight:0};o.weight+=t(r),n.set(s,o)}return[...n.values()].sort((r,s)=>s.weight-r.weight)}function gp(e){let t=wp(e.path);if(!t||e.label.includes("/"))return e.label;let n=`${t}/${e.label}`;return n.length<=yp?n:e.label}function _p(e,t){let[n,r]=e;if(!n)return"Files";let s=t?gp(n):n.label;if(e.length===1)return gp(n);if(e.length===2&&r){let o=`${s}, ${r.label}`;if(o.length<=yp)return o}return`${s} +${e.length-1}`}function go(e,t=()=>0){let n=e.map((c)=>xk(c.files,t)),r=n.map((c)=>_p(c,!1)),o=((c)=>{let u=new Map;for(let d of c)u.set(d,(u.get(d)??0)+1);return u})(r),a=r.map((c,u)=>(o.get(c)??0)>1?_p(n[u]??[],!0):c),l=new Map;return a.map((c)=>{let u=(l.get(c)??0)+1;return l.set(c,u),u===1?c:`${c} (${u})`})}var yp=24,mp,wk;var Tl=Ue(()=>{mp=/\.(?: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,wk=new Set(["__init__","common","constants","helpers","index","init","lib","main","mod","shared","types","util","utils"])});function _o(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 vp(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 xp(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 Oi(e,t,n){return{file:e,side:"additions",kind:"file",line:0,cited:t,...n?{reason:n}:{}}}function Nl(e,t,n,r,s,o){let a=vp(e,n).find((u)=>r>=u.start&&r<=u.end);if(!a)return null;let l=s!==void 0&&s>r?Math.min(s,a.end):void 0,c=xp(e,n,a,r);return{file:t,side:n,kind:"line",line:r,...l!==void 0&&l>r?{endLine:l}:{},cited:o,...c!==void 0?{text:c}:{}}}function yo(e,t,n,r,s={}){let o=n!==void 0&&Number.isFinite(n)&&n>0,a=o?r!==void 0&&r>0?Math.min(n,r):n:0,l=o&&r!==void 0&&r>0?Math.max(n,r):void 0,c={line:a,...l!==void 0&&l!==a?{endLine:l}:{}};if(!e)return Oi(t,c,"not-in-diff");if(!o)return Oi(t,c,"no-line");if(e.type==="deleted")return(s.deletionsFallback?Nl(e,t,"deletions",a,l,c):null)??Oi(t,c,"deleted-file");let u=vp(e,"additions");if(!u.length)return Oi(t,c,"no-hunks");let d=Nl(e,t,"additions",a,l,c)??(s.deletionsFallback?Nl(e,t,"deletions",a,l,c):null);if(d)return d;let f;for(let p of u){let h=a<p.start?p.start:p.end,x=Math.abs(h-a);if(!f||x<f.distance)f={line:h,range:p,distance:x}}if(f&&f.distance<=20){let p=xp(e,"additions",f.range,f.line);return{file:t,side:"additions",kind:"nearby",line:f.line,cited:c,...p!==void 0?{text:p}:{}}}return Oi(t,c,"far-from-diff")}function Mr(e){return e.replace(/-\d+$/,"")}function kp(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:Mr(t.id)}))}function Rp(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 $p(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 Qq,P_,ou,M_,T_,n0,eH,tH;var N_=Ue(()=>{Qq=(()=>{try{return!0}catch{return!1}})(),P_=/(?=^From [a-f0-9]+ .+$)/m,ou=/(?=^diff --git)/gm,M_=/^(---|\+\+\+)\s+([^\t\r\n]+)/,T_=/^index ([0-9a-f]+)\.\.([0-9a-f]+)(?: (\d+))?$/i,n0={hunkLineCount:50,lineHeight:20,diffHeaderHeight:44,spacing:8},eH={...n0,hunkLineCount:1},tH=Object.freeze({fromStart:0,fromEnd:0})});function ms(e,t){return e-(t===0?0:1)}function au(e,t){return ms(e,t)+t}var D_=()=>{};function lu(e,...t){return`ck1:${JSON.stringify([e,...t])}`}var F_=()=>{};function cu(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 L_=()=>{};function j_(){if(ni.length!==1024)ni=new Uint8Array(1024)}function je(e){if(e.length===0)return e;if(s0.test(e))return JSON.parse(JSON.stringify(e));let t=e.length*3;if(ni.length<t)ni=new Uint8Array(t);let{written:n}=r0.encodeInto(e,ni);return i0.decode(ni.subarray(0,n))}var r0,i0,s0,ni;var U_=Ue(()=>{r0=new TextEncoder,i0=new TextDecoder("utf-8",{ignoreBOM:!0}),s0=/[\uD800-\uDFFF]/,ni=new Uint8Array(1024)});function B_(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=a0[e[n+1]];if(s!=null){t+=s,n+=2;continue}let o=[];do{let a=l0(e,n+1);if(a==null)return;o.push(a),n+=4}while(e[n]==="\\"&&e[n+1]>="0"&&e[n+1]<="7");t+=o0.decode(new Uint8Array(o))}}function l0(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 o0,a0;var q_=Ue(()=>{o0=new TextDecoder("utf-8",{ignoreBOM:!0}),a0={'"':'"',"\\":"\\",a:"\x07",b:"\b",t:"\t",n:`
|
|
89
|
+
`,v:"\v",f:"\f",r:"\r"}});function K_(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=c0(e,r);if(s!=null)t.hunkContent.splice(n,1,...s),n+=s.length-1}}function c0(e,t){let{deletions:n,additions:r,deletionLineIndex:s,additionLineIndex:o}=t,a=Math.min(n,r),l=Math.abs(r-n);if(a===0||l===0||a*(l+1)>4096)return null;let c=[];for(let R=0;R<n;R++)c.push(H_(e.deletionLines[s+R]??""));let u=[];for(let R=0;R<r;R++)u.push(H_(e.additionLines[o+R]??""));let d=r>n,f=0,p=-1;for(let R=0;R<=l;R++){let w=0;for(let v=0;v<a;v++)w+=d0(c[v+(d?0:R)],u[v+(d?R:0)]);if(R===0)p=w+a*0.5;else if(w>p)p=w,f=R}if(f===0)return null;let h=[],x=(R,w,v,y)=>{if(R>0||w>0)h.push({type:"change",deletions:R,additions:w,deletionLineIndex:v,additionLineIndex:y})};if(d)x(0,f,s,o),x(a,a,s,o+f),x(0,r-a-f,s+a,o+f+a);else x(f,0,s,o),x(a,a,s+f,o),x(n-a-f,0,s+f+a,o+a);return h}function H_(e){return e.replace(u0,"")}function d0(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 u0;var W_=Ue(()=>{u0=/\s+/g});function p0(e,t,n=!1,r){let s=x0(e),o=s?g0(e):_0(e),a,l=[];for(let c of o){if(s&&!ou.test(c)){if(a==null)a=je(c);else if(n)throw Error("parsePatchContent: unknown file blob");else console.error("parsePatchContent: unknown file blob:",c);continue}else if(!s&&!y0(c)){if(a==null)a=je(c);else if(n)throw Error("parsePatchContent: unknown file blob");else console.error("parsePatchContent: unknown file blob:",c);continue}let u=h0(c,{cacheKey:t!=null?r==null?lu("patch-file",t,String(l.length)):lu("patch-file",t,String(r),String(l.length)):void 0,isGitDiff:s,throwOnError:n});if(u!=null)l.push(u)}return{patchMetadata:a,files:l}}function h0(e,{cacheKey:t,isGitDiff:n=ou.test(e),oldFile:r,newFile:s,throwOnError:o=!1}={}){let a=0,l=Q_(e,"@@ "),c,u=r==null||s==null,d=0,f=0;for(let p of l){let h=X_(p),x=h[0];if(x==null){if(o)throw Error("parsePatchContent: invalid hunk");else console.error("parsePatchContent: invalid hunk",p);continue}let R=Z_(x),w=0,v=0;if(R==null||c==null){if(c!=null){if(o)throw Error("parsePatchContent: Invalid hunk");else console.error("parsePatchContent: Invalid hunk",p);continue}if(c={name:"",type:"change",hunks:[],splitLineCount:0,unifiedLineCount:0,isPartial:u,additionLines:!u&&r!=null&&s!=null?V_(s.contents):[],deletionLines:!u&&r!=null&&s!=null?V_(r.contents):[],cacheKey:J_(t)},c.additionLines.length===1&&s?.contents==="")c.additionLines.length=0;if(c.deletionLines.length===1&&r?.contents==="")c.deletionLines.length=0;for(let I of h){if(I.startsWith("diff --git")){let B=I.trim().match(f0);if(B==null){if(o)throw Error("parsePatchContent: invalid git diff header");else console.error("parsePatchContent: invalid git diff header",I);continue}let L=gs(B[1],!0),H=gs(B[2],!0);if(c.name=je(H),L!==H)c.prevName=je(L);continue}let F=I.startsWith("---")||I.startsWith("+++")?I.match(M_):null;if(F!=null){let[,B,L]=F,H=gs(L,n);if(B==="---"&&H!=="/dev/null"){let ge=je(H);c.prevName=ge,c.name=ge}else if(B==="+++"&&H!=="/dev/null")c.name=je(H)}else if(n){if(I.startsWith("new mode "))c.mode=je(I.slice(8).trim());if(I.startsWith("old mode "))c.prevMode=je(I.slice(8).trim());if(I.startsWith("new file mode"))c.type="new",c.mode=je(I.slice(13).trim());if(I.startsWith("deleted file mode"))c.type="deleted",c.mode=je(I.slice(17).trim());if(I.startsWith("similarity index"))if(I.startsWith("similarity index 100%"))c.type="rename-pure";else c.type="rename-changed";if(I.startsWith("index ")){let[,B,L,H]=I.trim().match(T_)??[];if(B!=null)c.prevObjectId=je(B);if(L!=null)c.newObjectId=je(L);if(H!=null)c.mode=je(H)}if(I.startsWith("rename from ")||I.startsWith("copy from "))c.prevName=je(gs(I.slice(I.startsWith("rename")?12:10)));if(I.startsWith("rename to ")||I.startsWith("copy to "))c.name=je(gs(I.slice(I.startsWith("rename")?10:8)))}}continue}let y,P;while(h.length>0&&(h[h.length-1]===`
|
|
90
|
+
`||h[h.length-1]==="\r"||h[h.length-1]===`\r
|
|
91
|
+
`||h[h.length-1]===""))h.pop();let{additionStart:D,deletionStart:g}=R;d=u?d:g-1,f=u?f:D-1;let k={collapsedBefore:0,splitLineCount:0,splitLineStart:0,unifiedLineCount:0,unifiedLineStart:0,additionCount:R.additionCount,additionStart:D,additionLines:w,deletionCount:R.deletionCount,deletionStart:g,deletionLines:v,deletionLineIndex:d,additionLineIndex:f,hunkContent:[],hunkContext:J_(R.hunkContext),hunkSpecs:je(x),noEOFCRAdditions:!1,noEOFCRDeletions:!1},C=0,M=0;for(let I=1;I<h.length;I++){let F=h[I];if(C>=k.additionCount&&M>=k.deletionCount&&!F.startsWith("\\")){if(!(w0(F)&&!b0(F)))break;if(o)throw Error("parsePatchContent: hunk has more lines than expected")}let B=F[0];if(B!=="+"&&B!=="-"&&B!==" "&&B!=="\\"){if(o)throw Error("parsePatchContent: invalid hunk line");console.error(`parseLineType: Invalid firstChar: "${B}", full line: "${F}"`),console.error("processFile: invalid rawLine:",F);continue}let L=k0(B);if(L==="addition"){if(o&&C>=k.additionCount)throw Error("parsePatchContent: hunk has too many addition lines");let H=uu(F);if(y==null||y.type!=="change")y=du("change",d,f),k.hunkContent.push(y);if(f++,C++,u)c.additionLines.push(H);y.additions++,w++,P="addition"}else if(L==="deletion"){if(o&&M>=k.deletionCount)throw Error("parsePatchContent: hunk has too many deletion lines");let H=uu(F);if(y==null||y.type!=="change")y=du("change",d,f),k.hunkContent.push(y);if(d++,M++,u)c.deletionLines.push(H);y.deletions++,v++,P="deletion"}else if(L==="context"){if(o&&(M>=k.deletionCount||C>=k.additionCount))throw Error("parsePatchContent: hunk has too many context lines");let H=uu(F);if(y==null||y.type!=="context")y=du("context",d,f),k.hunkContent.push(y);if(f++,d++,C++,M++,u)c.deletionLines.push(H),c.additionLines.push(H);y.lines++,P="context"}else if(L==="metadata"&&y!=null){if(y.type==="context")k.noEOFCRAdditions=!0,k.noEOFCRDeletions=!0;else if(P==="deletion")k.noEOFCRDeletions=!0;else if(P==="addition")k.noEOFCRAdditions=!0;if(u&&(P==="addition"||P==="context")){let H=c.additionLines.length-1;if(H>=0)c.additionLines[H]=cu(c.additionLines[H])}if(u&&(P==="deletion"||P==="context")){let H=c.deletionLines.length-1;if(H>=0)c.deletionLines[H]=cu(c.deletionLines[H])}}}if(C!==k.additionCount||M!==k.deletionCount){if(o)throw Error("parsePatchContent: hunk line count mismatch");console.error(`parsePatchContent: hunk line count mismatch: "${x.trimEnd()}", declared old/new ${k.deletionCount}/${k.additionCount}, parsed old/new ${M}/${C}`);let I=ms(k.additionStart,k.additionCount)+(C===0?0:1),F=ms(k.deletionStart,k.deletionCount)+(M===0?0:1);if(!u){let B=I-k.additionStart,L=F-k.deletionStart;k.additionLineIndex+=B,k.deletionLineIndex+=L;for(let H of k.hunkContent)H.additionLineIndex+=B,H.deletionLineIndex+=L}k.additionStart=I,k.deletionStart=F,k.additionCount=C,k.deletionCount=M}k.additionLines=w,k.deletionLines=v,k.collapsedBefore=Math.max(ms(k.additionStart,k.additionCount)-a,0),c.hunks.push(k),a=au(k.additionStart,k.additionCount);for(let I of k.hunkContent)if(I.type==="context")k.splitLineCount+=I.lines,k.unifiedLineCount+=I.lines;else k.splitLineCount+=Math.max(I.additions,I.deletions),k.unifiedLineCount+=I.deletions+I.additions;k.splitLineStart=c.splitLineCount+k.collapsedBefore,k.unifiedLineStart=c.unifiedLineCount+k.collapsedBefore,c.splitLineCount+=k.collapsedBefore+k.splitLineCount,c.unifiedLineCount+=k.collapsedBefore+k.unifiedLineCount}if(c==null)return;if(o&&u&&!n&&c.hunks.length===0)throw Error("parsePatchContent: unified file has no hunks");if(c.hunks.length>0&&!u&&c.additionLines.length>0&&c.deletionLines.length>0){let p=c.hunks[c.hunks.length-1],h=au(p.additionStart,p.additionCount),x=c.additionLines.length,R=Math.max(x-h,0);c.splitLineCount+=R,c.unifiedLineCount+=R}if(!n){if(c.prevName!=null&&c.name!==c.prevName)if(c.hunks.length>0)c.type="rename-changed";else c.type="rename-pure";else if((r==null||r.contents==="")&&s!=null&&s.contents!=="")c.type="new";else if(r!=null&&r.contents!==""&&(s==null||s.contents===""))c.type="deleted"}if(c.type!=="rename-pure"&&c.type!=="rename-changed")c.prevName=void 0;return K_(c),c}function pu(e,t,n=!1){let r=[],s=m0(e)?e.split(P_):[e];for(let o of s)try{r.push(p0(o,t,n,t!=null?r.length:void 0))}catch(a){if(n)throw a;else console.error(a)}finally{j_()}return r}function gs(e,t=!1){let n=e.trim(),r=n.startsWith('"')?B_(n)?.fileName??n:n;return t&&(r.startsWith("a/")||r.startsWith("b/"))?r.slice(2):r}function m0(e){return e.startsWith("From ")||e.includes(`
|
|
92
|
+
From `)}function V_(e){let t=X_(e);for(let n=0;n<t.length;n++)t[n]=je(t[n]);return t}function X_(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 g0(e){return Q_(e,"diff --git")}function _0(e){if(e.length===0)return[""];let t=[],n=0,r=0,s=0,o=0,a=!1;while(r<e.length){let l=fu(e,r);if(s<=0&&o<=0){if(Y_(e,r)){if(r>n)t.push(e.slice(n,r));n=r,a=!0,r=fu(e,l);continue}if(a&&e.startsWith("@@ -",r)){let u=Z_(e.slice(r,l));if(u!=null)s=u.deletionCount,o=u.additionCount}r=l;continue}let c=e[r];if(c==="\\"){r=l;continue}if(c===" ")s=Math.max(s-1,0),o=Math.max(o-1,0);else if(c==="-")s=Math.max(s-1,0);else if(c==="+")o=Math.max(o-1,0);r=l}return t.push(e.slice(n)),t}function y0(e){return Y_(e,0)}function Y_(e,t){let n=fu(e,t);return G_(e,t,"---")&&G_(e,n,"+++")}function G_(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 fu(e,t){let n=e.indexOf(`
|
|
95
|
+
`,t);return n===-1?e.length:n+1}function w0(e){let t=e[0];return t==="+"||t==="-"||t===" "}function b0(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 Z_(e){if(!e.startsWith("@@ -"))return;let t=4,n=sa(e,t);if(n==null)return;let r=n.value;t=n.endIndex;let s=1;if(e[t]===","){let d=sa(e,t+1);if(d==null)return;s=d.value,t=d.endIndex}if(e[t]!==" "||e[t+1]!=="+")return;t+=2;let o=sa(e,t);if(o==null)return;let a=o.value;t=o.endIndex;let l=1;if(e[t]===","){let d=sa(e,t+1);if(d==null)return;l=d.value,t=d.endIndex}if(e[t]!==" "||e[t+1]!=="@"||e[t+2]!=="@")return;let c,u=t+3;if(e[u]===" ")c=v0(e.slice(u+1));return{additionCount:l,additionStart:a,deletionCount:s,deletionStart:r,hunkContext:c}}function sa(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 v0(e){if(e.endsWith(`\r
|
|
97
|
+
`))return e.slice(0,-2);if(e.endsWith(`
|
|
98
|
+
`))return e.slice(0,-1);return e}function x0(e){return e.startsWith("diff --git")||e.includes(`
|
|
99
|
+
diff --git`)}function Q_(e,t){if(e.length===0)return[""];let n=`
|
|
100
|
+
${t}`,r=e.startsWith(t)?0:z_(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=z_(e,n,o+1);if(a===-1)break;s.push(e.slice(o,a)),o=a}return s.push(e.slice(o)),s}function z_(e,t,n){let r=e.indexOf(t,n);return r===-1?-1:r+1}function J_(e){return e==null?e:je(e)}function k0(e){return e===" "?"context":e==="\\"?"metadata":e==="+"?"addition":"deletion"}function uu(e){let t=e.slice(1);return je(t===""?`
|
|
101
|
+
`:t)}function du(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 f0;var ey=Ue(()=>{N_();D_();F_();L_();U_();q_();W_();f0=/^diff --git ("a\/(?:[^"\\]|\\.)*"|a\/.+?) ("b\/(?:[^"\\]|\\.)*"|b\/.+?)$/});var ty=Ue(()=>{ey()});function A0(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 ry(e){return pu(e).flatMap((t)=>t.files)}function iy(e,t,n){let r=A0(t),s=new Map;for(let o of["skip","docs","code"])for(let a of n[o])s.set(a,o);return e.map((o)=>{let a=0,l=0;for(let c of o.hunks)a+=c.additionLines,l+=c.deletionLines;return{path:o.name,...o.prevName&&o.prevName!==o.name?{previousPath:o.prevName}:{},status:E0[o.type],additions:a,deletions:l,isBinary:r.has(o.name),...o.newObjectId?{blob:o.newObjectId}:{},groupId:"",classification:s.get(o.name)??Er(o.name),surface:Ze(o.name)}})}function C0(e){let t=e.match(/^(.+?):(\d+)(?:-\d+)?$/);return t?.[1]&&t[2]?{file:t[1],line:Number(t[2])}:{file:e}}function ny(e,t,n){return{id:t,file:e.file,anchor:yo(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(C0)}:{},...e.repeat_of!==void 0?{repeatOf:e.repeat_of}:{},surface:Ze(e.file)}}function _s(e){return[...new Set(e)]}function I0(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 O0(e,t){let n=new Map;for(let r of t){let s=Number(r.chapterId.slice(1))-1;for(let o of r.locations)if(!n.has(o.file))n.set(o.file,s)}return e.flatMap((r)=>{let s=r.files.flatMap((f)=>{let p=n.get(f);return p===void 0?[]:[{file:f,ci:p}]});if(!s.length)return[r];let o=new Map;for(let{ci:f}of s)o.set(f,(o.get(f)??0)+1);let a=0,l=0;for(let[f,p]of o)if(p>l||p===l&&f<a)a=f,l=p;let c=(f)=>{let p=f.replace(/\.(test|spec)(\.[^./]+)$/,"$2"),h=n.get(f)??n.get(p);if(h!==void 0)return h;if(p!==f){let R=p.slice(p.lastIndexOf("/")+1),w=[...n].find(([v])=>v.endsWith(`/${R}`)||v===R);if(w)return w[1]}let x;for(let R of s){let w=I0(f,R.file);if(w>0&&(!x||w>x.depth||w===x.depth&&R.ci<x.ci))x={depth:w,ci:R.ci}}return x?.ci??a},u=new Map;for(let f of r.files){let p=c(f);u.set(p,[...u.get(p)??[],f])}let d=u.size>1;return[...u].sort((f,p)=>f[0]-p[0]).map(([f,p])=>({id:d?`${r.id}-c${f+1}`:r.id,unit:r.unit,files:p,chapter:f}))})}function P0(e,t,n,r,s){let o=e.previous;if(!o)return{carried:[],resolved:t.map((h)=>({id:String(h.id),...h.note?{note:h.note}:{}}))};let a=o.run.findings,l=[],c=new Set;for(let h of t){let x=a[h.id-1];if(!x)continue;c.add(x.id),l.push({id:x.id,title:x.title,file:x.file,...h.note?{note:h.note}:{}})}let u=new Map(a.map((h)=>[Mr(h.id),h.carriedFrom??o.run.id]));for(let h of n){let x=u.get(Mr(h.id));if(x)h.carriedFrom=x}let d=new Set(n.map((h)=>Mr(h.id))),f=new Set(o.dismissed??[]),p=[];for(let h of a){if(c.has(h.id)||f.has(h.id)||d.has(Mr(h.id)))continue;let x=r.get(h.file);if(!x){s(` prior finding "${h.title}" dropped: ${h.file} is no longer in the diff`);continue}let R=o.lineMap?.get(h.file)??[],w=(v)=>v?$p(R,v):void 0;p.push({...h,anchor:yo(x,h.file,w(h.anchor.cited.line),w(h.anchor.cited.endLine)),carriedFrom:h.carriedFrom??o.run.id})}return{carried:p,resolved:l}}function hu(e){let t=e.log??((S)=>console.error(S)),n=e.result.record,r=n?.walkthrough??null,s=ry(e.patch),o=new Map(s.map((S)=>[S.name,S])),a=iy(s,e.patch,e.result.byClass),l=new Map(a.map((S)=>[S.path,S])),c=new Map,u=(S)=>{let K=Bt(S.file,S.title),Y=(c.get(K)??0)+1;return c.set(K,Y),Y===1?K:`${K}-${Y}`},d=(n?.verifiedFindings??[]).map((S)=>ny(S,u(S),o.get(S.file))),f=(n?.overCapFindings??[]).map((S)=>ny(S,u(S),o.get(S.file))),{carried:p,resolved:h}=P0(e,n?.resolved??[],[...d,...f],o,t);d.push(...p);let x=(S)=>{let K=S.endsWith("/")?S:`${S}/`;return!o.has(S)&&s.some((Y)=>Y.name.startsWith(K))},R=[],w=r?.chapters??[];w.forEach((S,K)=>{(S.stops??[]).forEach((Y,Ce)=>{let St=[];for(let Ke of Y.locations??[]){if(x(Ke.file)){t(` walkthrough: dropped directory location ${Ke.file} in "${Y.title}"`);continue}let si=yo(o.get(Ke.file),Ke.file,Ke.line,void 0,{deletionsFallback:!0});St.push({...si,...Ke.label?{label:Ke.label}:{}})}R.push({id:`c${K+1}-s${Ce+1}`,chapterId:`c${K+1}`,index:Ce,title:Y.title,...Y.prose?{prose:Y.prose}:{},importance:Y.importance??"normal",locations:St})})});let v=new Set,y=(S)=>{let K=[];for(let Y of S){if(!l.has(Y))continue;if(v.has(Y))continue;v.add(Y),K.push(Y)}return K},P=new Set((r?.start_here??[]).map((S)=>S.file)),D=[...e.result.units].sort((S,K)=>(S.priority??99)-(K.priority??99)),g=new Set,k=(S)=>{let K=`u-${S.id}`;for(let Ce=2;g.has(K);Ce++)K=`u-${S.id}-${Ce}`;g.add(K);let Y=S.files.filter((Ce)=>!l.has(Ce));if(Y.length)t(` unit "${S.title}": ${Y.length} file(s) not in the patch: ${Y.join(", ")}`);return{id:K,unit:S,files:y(S.files)}},C=O0(D.map(k).filter((S)=>S.files.length),R),M=new Map(C.flatMap((S)=>S.chapter===void 0?[]:[[S.id,S.chapter]])),I=(S)=>{let K=l.get(S);return K?K.additions+K.deletions:0},F=e.kind==="diff"?go(C,I):[],B=new Map(C.map((S,K)=>[S.id,F[K]??S.unit.title])),L=[],H=(S,K,Y,Ce={})=>({id:S,title:K,files:Y,findingIds:[],stopIds:[],critical:!1,...Ce}),ge=(S,K,Y={})=>H(S,K,[],Y),ke=(S,K)=>H(S.id,B.get(S.id)??S.unit.title,S.files,{...K?{parentId:K}:{},...S.unit.rationale?{summary:S.unit.rationale}:{}}),ie=(S)=>S.files.some((K)=>P.has(K));if(w.length){w.forEach((K,Y)=>{let Ce=`c${Y+1}`,St=K.icon;L.push(ge(Ce,K.title,{...K.blurb?{summary:K.blurb}:{},...St&&R0.has(St)?{icon:St}:{},stopIds:R.filter((tt)=>tt.chapterId===Ce).map((tt)=>tt.id)}));let Ke=C.filter((tt)=>M.get(tt.id)===Y),si=[...Ke.filter(ie),...Ke.filter((tt)=>!ie(tt))];for(let tt of si)L.push(ke(tt,Ce))});let S=C.filter((K)=>!M.has(K.id));if(S.length){let K=_s((r?.support??[]).map((Y)=>Y.reason).filter(Boolean));L.push(ge("supporting","Supporting changes",K.length?{summary:K.join(" ")}:{}));for(let Y of S)L.push(ke(Y,"supporting"))}}else for(let S of C)L.push(ke(S));let De=y(a.filter((S)=>S.classification==="docs").map((S)=>S.path)),Pe=y(a.filter((S)=>S.classification==="skip").map((S)=>S.path)),we=y(a.map((S)=>S.path));if(we.length)t(` ${we.length} file(s) in no review unit: ${we.join(", ")}`);let q=[...we.length?[H("remaining","Remaining changes",we)]:[],...De.length?[H("docs","Docs",De,{icon:"doc"})]:[],...Pe.length?[H("skipped","Generated and skipped",Pe,{icon:"gear"})]:[]],T=e.kind==="diff"?"Other changes":"Not reviewed in depth",[U]=q;if(q.length===1&&U)L.push(e.kind==="diff"?U:{...U,title:T});else if(q.length){L.push(ge("other",T));for(let S of q)L.push({...S,parentId:"other"})}let Z=new Map;for(let S of L)for(let K of S.files)Z.set(K,S);for(let S of a)S.groupId=Z.get(S.path)?.id??"";let fe=new Map(R.map((S)=>[S.id,S]));for(let S of L){if(!S.files.length)continue;let K=new Set(S.files);S.findingIds=d.filter((Y)=>K.has(Y.file)).map((Y)=>Y.id),S.stopIds=R.filter((Y)=>Y.locations.some((Ce)=>K.has(Ce.file))).map((Y)=>Y.id)}let ue=new Map(d.map((S)=>[S.id,S.severity])),Fe=(S)=>S.findingIds.some((K)=>S0.has(ue.get(K)??"question"))||S.stopIds.some((K)=>fe.get(K)?.importance==="critical");for(let S of L)if(S.files.length)S.critical=Fe(S);for(let S of L){if(S.files.length)continue;let K=L.filter((Y)=>Y.parentId===S.id);S.findingIds=_s(K.flatMap((Y)=>Y.findingIds)),S.critical=K.some((Y)=>Y.critical)||Fe(S)}let Xe=d.filter((S)=>!Z.has(S.file));if(Xe.length)t(` ${Xe.length} finding(s) name files outside the patch`);let Te=r?.intent,zt=n?.intentAlignment??void 0,Rn=_s([...Te?.unstated??[],...zt?.unstated??[]]),b=_s([...Te?.missing??[],...zt?.missing??[]]),W=_s([...zt?.summary?[zt.summary]:[],...Te?.mismatches??[]]),_e=Te?.alignment==="aligned"&&zt?.summary?"partial":Te?.alignment,N={...e.statedIntent?{stated:e.statedIntent}:{},...Te?.inferred?{inferred:Te.inferred}:{},..._e?{alignment:_e}:{},...Te?.matches?.length?{matches:Te.matches}:{},...W.length?{mismatches:W}:{},...Rn.length?{unstated:Rn}:{},...b.length?{missing:b}:{}},ye=(n?.sliceRuns??[]).map((S)=>({unit:S.unit,part:S.part,parts:S.parts,status:S.ok?"ok":"failed",costUsd:S.costUsd??0,wallMs:S.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:N,overview:{...r?.focus?{focus:r.focus}:{},...r?.change_type?{changeType:r.change_type}:{},startHere:r?.start_here??[]},files:a,groups:L,stops:R,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,rejectedCount:n?.rejected?.length??0,coreSource:e.coreSource,...pe&&$0.has(pe)?{mergeMode:pe}:{},...n?.budgetStopped?{budgetStopped:!0}:{}},untrackedSkipped:e.untrackedSkipped??[],...e.priorRunId?{priorRunId:e.priorRunId}:{}}}function sy(e,t,n){return{...hu({...e,result:{record:null,units:t,byClass:n,costUsd:0,wallMs:0},log:()=>{}}),status:"running"}}function oy(e){let t=iy(ry(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}:{}}}var R0,$0,S0,E0;var mu=Ue(()=>{ty();Si();Tl();$i();Ir();R0=new Set(["bug","wrench","path","flask","doc","gear"]),$0=new Set(["coordinator","nothing-to-merge","deterministic-fallback"]),S0=new Set(["blocker","should-fix"]),E0={new:"added",deleted:"removed",change:"modified","rename-pure":"renamed","rename-changed":"renamed"}});var Ja={};tb(Ja,{program:()=>dd,createCommand:()=>fd,createOption:()=>pd,createArgument:()=>hd,Command:()=>md,Option:()=>gd,Argument:()=>_d,Help:()=>yd,CommanderError:()=>wd,InvalidArgumentError:()=>bd,InvalidOptionArgumentError:()=>vd},{program:(lC)=>dd=lC,createCommand:(lC)=>fd=lC,createOption:(lC)=>pd=lC,createArgument:(lC)=>hd=lC,Command:(lC)=>md=lC,Option:(lC)=>gd=lC,Argument:(lC)=>_d=lC,Help:(lC)=>yd=lC,CommanderError:(lC)=>wd=lC,InvalidArgumentError:(lC)=>bd=lC,InvalidOptionArgumentError:(lC)=>vd=lC});var{Argument:ld}=Ds(),{Command:za}=ad(),{CommanderError:Pb,InvalidArgumentError:cd}=fi(),{Help:Mb}=Ha(),{Option:ud}=Ka();var dd=new za,fd=(e)=>new za(e),pd=(e,t)=>new ud(e,t),hd=(e,t)=>new ld(e,t),md=za,gd=ud,_d=ld,yd=Mb,wd=Pb,bd=cd,vd=cd;var{program:uC,createCommand:dC,createArgument:fC,createOption:pC,CommanderError:hC,InvalidArgumentError:pi,InvalidOptionArgumentError:mC,Command:Ft,Argument:gC,Option:_C,Help:yC}=Ja;var Fs={name:"@acemarke/diffloupe",version:"0.2.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 Ls=Fs.version;import{readdir as B0,stat as q0}from"fs/promises";import my from"path";var bs=Ba(Bs(),1);import{spawn as Lb}from"child_process";function te(e,t,n={}){return new Promise((r,s)=>{let o=Lb(e,t,{cwd:n.cwd,env:n.env??process.env,stdio:[n.input===void 0?"ignore":"pipe","pipe","pipe"]});if(n.input!==void 0)o.stdin?.on("error",()=>{}),o.stdin?.end(n.input);let a=n.timeoutMs?setTimeout(()=>o.kill("SIGKILL"),n.timeoutMs):void 0,l=[],c=[];o.stdout?.on("data",(u)=>l.push(u)),o.stderr?.on("data",(u)=>c.push(u)),o.on("error",(u)=>{clearTimeout(a),s(u)}),o.on("close",(u,d)=>{clearTimeout(a);let f={stdout:Buffer.concat(l).toString("utf8"),stderr:Buffer.concat(c).toString("utf8"),code:u??(d?128:0),...d?{signal:d}:{}};if(f.code!==0&&!n.allowFail){s(Error(`${e} ${t.join(" ")} ${d?`killed by ${d}`:`exited ${f.code}`}
|
|
102
|
+
`+f.stderr.slice(0,2000)));return}r(f)})})}async function le(e,t,n={}){return(await te(e,t,n)).stdout}var Xt=["review","coordinator","walkthrough"],Rd={review:"anthropic/claude-opus-5-5",coordinator:"anthropic/claude-opus-5-5",walkthrough:"anthropic/claude-sonnet-5-5"},qs={review:"models.review",coordinator:"models.coordinator",walkthrough:"models.walkthrough"};var jb={env:"REVIEW_* environment variable",cli:"--model",settings:"settings file",config:"~/.config/diffloupe/config.json",opencode:"OpenCode default model",default:"built-in default"};function Hs(e){return jb[e]}function at(e){let t=e?.trim();return t?t:void 0}function Ub(e){let t=at(e.REVIEW_MODEL),n=at(e.REVIEW_MODEL_MERGE)??t,r=at(e.REVIEW_MODEL_WALK);return{...t?{review:t}:{},...n?{coordinator:n}:{},...r?{walkthrough:r}:{}}}function Bb(e,t){let n=at(e.REVIEW_EFFORT);return t==="review"?n:at(e.REVIEW_EFFORT_AUX)??n}function qb(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),l=o===-1?r:r.slice(o+1);return{provider:a,id:l,...s?{variant:s}:{}}}function Ya(e){return at(e.env?.REVIEW_PROVIDER)??at(e.settings?.provider)??at(e.config?.provider)??"anthropic"}function $d(e){let t=e.env??{},n=Ya(e),r=e.config?.opencode?.useDefaultModel!==!1,s=Ub(t),o=r?at(e.openCodeModel):void 0,a={};for(let l of Xt){let c=[["env",s[l]],["cli",e.cli?.models?.[l]],["settings",e.settings?.models?.[l]],["config",e.config?.models?.[l]],["opencode",o],["default",Rd[l]]],u="default",d=Rd[l];for(let[x,R]of c){let w=at(R);if(w){u=x,d=w;break}}let f=qb(d,n),p=Bb(t,l)??at(e.cli?.effort)??at(e.settings?.effort)??at(e.config?.effort)??(u==="default"?"medium":void 0),h=f.variant??p;a[l]={model:`${f.provider}/${f.id}${h?`#${h}`:""}`,provider:f.provider,id:f.id,...h?{variant:h}:{},source:u}}return a}function Sd(e,t=Xt){let n=new Map;for(let r of t){let s=e[r].provider;n.set(s,[...n.get(s)??[],r])}return n}import ot from"path";import{existsSync as M0}from"fs";import{copyFile as T0,readFile as cy,writeFile as oa}from"fs/promises";import{join as Ed}from"path";import{homedir as Hb}from"os";function Kb(){let e=process.env.XDG_CONFIG_HOME||Ed(Hb(),".config");return Ed(e,"diffloupe","config.json")}var An=null;async function gr(){if(An!==null)return An;let e=Bun.file(Kb());if(!await e.exists())return An={},An;try{let t=await e.text();return An=JSON.parse(t),An}catch{return An={},An}}import rt from"path";import tv from"path";import{promises as _r}from"fs";import Wb from"path";async function Ad(e){try{return await _r.access(e),!0}catch{return!1}}function Yt(e){return _r.readFile(e,"utf8")}async function Ks(e){return JSON.parse(await Yt(e))}async function Ve(e,t){await _r.mkdir(Wb.dirname(e),{recursive:!0}),await _r.writeFile(e,t,"utf8")}async function Gn(e,t){await Ve(e,JSON.stringify(t,null,2))}async function Lt(e){await _r.rm(e,{force:!0})}async function un(e){await _r.mkdir(e,{recursive:!0})}async function Cd(e){try{let t=await Yt(e);if(t==="")return 0;return t.replace(/\n$/,"").split(`
|
|
103
|
+
`).length}catch{return null}}hi();async function Pd(e,t,n){return Za(await le("git",["-C",e,"-c","diff.renames=true","diff","--unified=0",`${t}..${n}`]))}function*Zt(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 l=o.slice(4).trim();t=l==="/dev/null"?void 0:l.replace(/^b\//,""),yield{file:t,line:o};continue}n=!1;let a=/^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(o);if(a)r=a[1]===void 0?1:Number(a[1]),s=a[2]===void 0?1:Number(a[2]);yield{file:t,line:o}}}function Md(e){let t=new Map,n,r;for(let s of e.split(`
|
|
105
|
+
`)){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 zb=40,Jb=30,Xb=/^(?: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(`
|
|
106
|
+
`),o=s.findIndex((d)=>d.startsWith("@@ "));if(o<0)return r;let a=s.slice(o+1).filter((d)=>d.startsWith("-"));if(a.length<=zb)return r;let l=/^--- (?:a\/)?(.+)$/m.exec(r)?.[1]??"",c=a.filter((d)=>Xb.test(d.slice(1))).slice(0,Jb),u=r.endsWith(`
|
|
107
|
+
`)?`
|
|
108
|
+
`:"";return[...s.slice(0,o),...c.length?[`@@ -1,${c.length} +0,0 @@`,...c]:[],`# Deleted file, ${a.length} lines. Only its top-level declarations are shown; read the rest with \`git show ${t.slice(0,12)}:${l}\`.`].join(`
|
|
109
|
+
`)+u}).join("")}function Za(e){let t=new Map;for(let{file:n,line:r}of Zt(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 Yb=20,Id=(e,t)=>e.some((n)=>t>=n.start&&t<=n.end),Zb=(e,t,n)=>e.some((r)=>t>=r.start&&t<=r.end&&n>=r.start&&n<=r.end);function Od(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 Td(e,t,n,r){let s=r??void 0,o=e.get(t);if(!o||o.length===0)return{kind:"off-diff"};if(!Number.isFinite(n)||s!==void 0&&!Number.isFinite(s))return{kind:"off-diff"};let a=s!==void 0?Math.min(n,s):n,l=s!==void 0?Math.max(n,s):n,c=l!==a;if(c&&Zb(o,a,l))return{kind:"anchorable",line:l,start_line:a};if(Id(o,l))return{kind:"anchorable",line:l};if(c&&Id(o,a))return{kind:"anchorable",line:a};let u=c&&o.find((h)=>h.start>=a&&h.end<=l);if(u)return{kind:"off-hunk",line:u.start};let d=Od(o,a),f=c?Od(o,l):d,p=!d?f:!f?d:f.distance<d.distance?f:d;if(!p||p.distance>Yb)return{kind:"off-diff"};return{kind:"off-hunk",line:p.line}}xt();var nv=["node_modules/","/dist/","/build/","/.next/","/__snapshots__/",".min.js",".d.ts",".js.map","third-party/"],rv=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"]),iv=(e)=>[...nv,..._i].some((t)=>e.includes(t)),sv=new Set([".yml",".yaml",".json",".jsonc",".toml",".ini",".env",".py",".rb",".go",".rs",".java",".kt",".sh",".bash",".tf",".tfvars",".sql",".proto",".graphql",".gql"]),ov=new Set(["Dockerfile","Makefile","Procfile"]);function av(e){if(jt(e))return!0;let t=e.slice(e.lastIndexOf("/")+1);if(ov.has(t))return!0;let n=t.lastIndexOf(".");return n>0&&sv.has(t.slice(n))}var lv=(e)=>e.replace(/[.*+?^${}()|[\]\\-]/g,"\\$&");function cv(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 Ld(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(rv.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 jd=25;function Ud(e){return e.trim().replace(/["'`][^"'`]*["'`]/g,"~").replace(/[A-Za-z_$][A-Za-z0-9_$]*/g,"X").replace(/\d+/g,"#").replace(/\s+/g,"")}function uv(e){let t=[],n=null,r=0;for(let{file:s,line:o}of Zt(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 Bd(e){try{return await dv(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 dv(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=uv(o),l=new Set(a.map((v)=>v.file)),c=new Map;for(let v of a)for(let y=0;y<v.lines.length;y++){let P=v.lines[y];if(P.kind!=="add")continue;let D=P.text.trim();if(D.length<8)continue;if(cv(D))continue;if(!/[,;]$/.test(D)&&!/^case\b/.test(D)&&!/:\s*\S+$/.test(D))continue;let g=Ud(P.text);if(g.length<4)continue;let k=Ld(P.text);if(k.length===0)continue;let C=new Set,M=0;for(let I=Math.max(0,y-5);I<=Math.min(v.lines.length-1,y+5);I++){if(I===y)continue;let F=v.lines[I];if(F.kind!=="ctx")continue;if(Ud(F.text)!==g)continue;M++;for(let B of Ld(F.text))if(!k.includes(B))C.add(B)}if(M<2||C.size<2)continue;for(let I of k){let F=`${I}@${v.file}`,B=c.get(F);if(B)for(let L of C)B.siblings.add(L);else c.set(F,{newEntry:I,file:v.file,line:P.newLine,siblings:new Set(C)})}}if(c.size===0)return{findings:[],meta:{hunks:a.length,candidates:0}};let d=(await le("git",["-C",s,"ls-files"])).trim().split(`
|
|
110
|
+
`).filter((v)=>v&&!iv(v)&&av(v)),f=new Set;for(let v of c.values()){f.add(v.newEntry);for(let y of v.siblings)f.add(y)}let p=new Map;for(let v of f)p.set(v,new Set);let h=new Map,x=new Map;for(let v of f){let y=/^[A-Za-z0-9_$]+$/.test(v);if(h.set(v,y),!y)x.set(v,new RegExp(`(?<![A-Za-z0-9_$-])${lv(v)}(?![A-Za-z0-9_$-])`))}let R=0;for(let v of d){let y;try{y=await Yt(tv.join(s,v))}catch{continue}if(y.length>2000000)continue;R++;let P=new Set(y.match(/[A-Za-z0-9_$]+/g)??[]);for(let D of f)if(h.get(D)?P.has(D):x.get(D).test(y))p.get(D).add(v)}let w=[];for(let v of c.values()){let y=[...v.siblings].filter((C)=>{let M=(p.get(C)??new Set).size;return M>0&&M<=jd});if(y.length<2)continue;if((p.get(v.newEntry)??new Set).size>jd)continue;let P=new Map;for(let C of y)for(let M of p.get(C)??[]){if(!P.has(M))P.set(M,[]);P.get(M).push(C)}let D=p.get(v.newEntry)??new Set,g=[],k=[];for(let[C,M]of P){if(M.length<2)continue;if(C===v.file)continue;if(D.has(C))k.push({file:C,siblingsPresent:M.sort()});else g.push({file:C,siblingsPresent:M.sort()})}if(g.length===0)continue;g.sort((C,M)=>M.siblingsPresent.length-C.siblingsPresent.length),k.sort((C,M)=>M.siblingsPresent.length-C.siblingsPresent.length),w.push({newEntry:v.newEntry,addedIn:v.file,addedAtLine:v.line,siblings:y.sort(),missingIn:g.slice(0,6),presentIn:k.slice(0,6)})}return w.sort((v,y)=>y.missingIn.length-v.missingIn.length),{findings:w,meta:{hunks:a.length,candidates:c.size,filesScanned:R,changedFiles:l.size}}}function qd(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(`
|
|
111
|
+
`)}import _f from"path";hi();import{execFileSync as fv}from"child_process";import{builtinModules as pv}from"module";import{existsSync as hv,readFileSync as mv}from"fs";import{join as gv,posix as hn}from"path";function _v(e,t){return{paths:new Set(t),read(n){let r=gv(e,n);try{return hv(r)?mv(r,"utf8"):void 0}catch{return}}}}function Zs(e){let t=fv("git",["-C",e,"ls-files"],{encoding:"utf8",maxBuffer:268435456});return _v(e,t.split(`
|
|
112
|
+
`).filter(Boolean))}var Hd=[".ts",".tsx",".d.ts",".js",".jsx",".mts",".cts",".mjs",".cjs"],yv={".js":[".ts",".tsx"],".jsx":[".tsx"],".mjs":[".mts"],".cjs":[".cts"]},wi=/\.(?:d\.ts|tsx?|jsx?|mts|cts|mjs|cjs)$/;function en(e,t){let n=hn.normalize(e).replace(/^\.\//,"");if(n.startsWith("../"))return;if(t.has(n))return n;let r=hn.extname(n);for(let s of yv[r]??[]){let o=n.slice(0,-r.length)+s;if(t.has(o))return o}for(let s of Hd)if(t.has(n+s))return n+s;for(let s of Hd)if(t.has(`${n}/index${s}`))return`${n}/index${s}`;return}function ul(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]!==`
|
|
113
|
+
`)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 In(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var wv=/(^|\/)(tsconfig[^/]*|jsconfig[^/]*)\.json$/;function mn(e){let t=hn.dirname(e);return t==="."?"":t}function nt(e,t){return hn.normalize(e?`${e}/${t}`:t).replace(/^\.\//,"").replace(/^\.$/,"")}function Qs(e,t){let n=e.read(t);if(n===void 0)return;let r=ul(n);return In(r)?r:void 0}function bv(e,t,n){if(e.startsWith(".")||e.startsWith("/")){let s=nt(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 ll(e,t,n=new Set){if(n.has(t))return{};n.add(t);let r=Qs(e,t);if(!r)return{};let s=mn(t),o={},a=r.extends;for(let c of typeof a==="string"?[a]:Array.isArray(a)?a:[]){if(typeof c!=="string")continue;let u=bv(c,s,e);if(u)o={...o,...ll(e,u,n)}}let l=In(r.compilerOptions)?r.compilerOptions:{};if(typeof l.baseUrl==="string")o.baseUrl=l.baseUrl,o.baseUrlFrom=s;if(In(l.paths)){let c={};for(let[u,d]of Object.entries(l.paths))if(Array.isArray(d))c[u]=d.filter((f)=>typeof f==="string");o.paths=c,o.pathsFrom=s}return o}function vv(e,t){let n=Qs(e,t)?.references;if(!Array.isArray(n))return[];let r=mn(t);return n.flatMap((s)=>{if(!In(s)||typeof s.path!=="string")return[];let o=nt(r,s.path);return[o.endsWith(".json")?o:`${o}/tsconfig.json`]})}function xv(e,t,n){let r=t.baseUrl!==void 0?nt(t.baseUrlFrom??e,t.baseUrl):void 0,s=[];for(let o of[t,...n]){if(!o.paths)continue;let a=o.baseUrl!==void 0?nt(o.baseUrlFrom??e,o.baseUrl):o.pathsFrom??e;for(let[l,c]of Object.entries(o.paths)){if(s.some((u)=>u.pattern===l))continue;s.push({pattern:l,targets:c.map((u)=>nt(a,u))})}}return{dir:e,...r!==void 0?{baseUrl:r}:{},paths:s}}function kv(e){let t=new Map,n=[...e.paths].filter((r)=>wv.test(r)&&!r.includes("node_modules/"));for(let r of["tsconfig.json","jsconfig.json"])for(let s of n){if(hn.basename(s)!==r)continue;let o=mn(s);if(t.has(o))continue;let a=ll(e,s),l=a.paths?[]:vv(e,s).map((c)=>ll(e,c));t.set(o,xv(o,a,l))}return t}function Wd(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 cl(e){let t=e.indexOf("*");return t===-1?1/0:t}function Rv(e,t,n){let r;for(let s of e){let o=Wd(s.pattern,t);if(o===void 0)continue;if(!r||cl(s.pattern)>cl(r.rule.pattern))r={rule:s,capture:o}}if(!r)return;for(let s of r.rule.targets){let o=en(s.replace("*",r.capture),n);if(o)return o}return}var $v=["source","development","import","module","node","require","browser","default","types"];function Ys(e){if(typeof e==="string")return e;if(Array.isArray(e)){for(let t of e){let n=Ys(t);if(n)return n}return}if(!In(e))return;for(let t of $v)if(t in e)return Ys(e[t]);for(let t of Object.values(e)){let n=Ys(t);if(n)return n}return}function Vd(e,t,n,r){let s;for(let[o,a]of Object.entries(e)){let l=Wd(o,t);if(l===void 0)continue;let c=Ys(a);if(!c)continue;let u=cl(o);if(!s||u>s.len)s={target:c,capture:l,len:u}}if(!s)return;return Gd(nt(n,s.target.replaceAll("*",s.capture)),n,r)}function Gd(e,t,n){let r=en(e,n);if(r)return r;let s=t?e.slice(t.length+1):e,o=/^(dist|lib|build|out|js)\/(.*)$/.exec(s);if(!o)return;for(let a of o[1]==="js"?["ts","src"]:["src"]){let l=en(nt(t,`${a}/${o[2]}`).replace(wi,""),n);if(l)return l}return}function Sv(e){let t=new Map;for(let n of e.paths){if(hn.basename(n)!=="package.json"||n.includes("node_modules/"))continue;let r=Qs(e,n);if(!r)continue;let s=[r.source,r.module,r.main,r.types,r.typings].filter((o)=>typeof o==="string");t.set(mn(n),{dir:mn(n),...typeof r.name==="string"?{name:r.name}:{},...In(r.imports)?{imports:r.imports}:{},...r.exports!==void 0?{exports:r.exports}:{},entry:s})}return t}function Ev(e,t){let n=new Set;for(let r of t.keys()){let s=Qs(e,nt(r,"package.json"));for(let o of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let a=s?.[o];if(In(a))for(let l of Object.keys(a))n.add(l)}}return n}function al(e){let t=e.split("/");return e.startsWith("@")?t.slice(0,2).join("/"):t[0]}function Av(e,t,n){let r=t?`./${t}`:".";if(e.exports!==void 0){let s=In(e.exports)&&Object.keys(e.exports).some((a)=>a.startsWith("."))?e.exports:{".":e.exports},o=Vd(s,r,e.dir,n);if(o)return o}if(!t){for(let s of e.entry){let o=Gd(nt(e.dir,s),e.dir,n);if(o)return o}return en(nt(e.dir,"src/index"),n)??en(nt(e.dir,"index"),n)}return en(nt(e.dir,t),n)??en(nt(e.dir,`src/${t}`),n)}var Cv=new Set(pv);function Iv(e){let t=e.indexOf("/");if(t<=0)return;let n=e.slice(0,t);return/^[@~#$]/.test(n)?`${n}/`:void 0}class zd{byLast=new Map;constructor(e){for(let t of e){if(!wi.test(t)||t.includes("node_modules/"))continue;let n=t.replace(wi,"");if(this.add(n),hn.basename(n)==="index")this.add(mn(n))}}add(e){if(!e)return;let t=hn.basename(e),n=this.byLast.get(t);if(n)n.push(e);else this.byLast.set(t,[e])}roots(e){let t=e.replace(wi,"").replace(/\/$/,""),n=this.byLast.get(hn.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 Ov=0.6,Kd=/^[@~#$]\/$/;function Jd(e){let t=Iv(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 Pv(e,t,n){let r=new Map;for(let{from:a,spec:l}of e){let c=Jd(l);if(!c)continue;let u=n(a),d=`${u}\x00${c.prefix}`,f=r.get(d);if(!f)r.set(d,f={scope:u,...c,specs:new Set});f.specs.add(l)}let s=new zd(t),o=[];for(let{scope:a,prefix:l,bare:c,specs:u}of r.values()){let d=new Map;for(let w of u)for(let v of s.roots(c?w:w.slice(l.length))){if(a&&v!==a&&!v.startsWith(`${a}/`))continue;d.set(v,(d.get(v)??0)+1)}let f=[...d].sort((w,v)=>v[1]-w[1]||w[0].length-v[0].length),[p,h]=f;if(!p)continue;let[x,R]=p;if(h&&h[1]===R)continue;if(R<Ov*u.size)continue;if(R<2&&!Kd.test(l))continue;if(!c&&!Kd.test(l)&&x==="")continue;o.push({scope:a,prefix:l,root:c?x+l:x,hits:R,total:u.size})}return o.sort((a,l)=>a.scope.localeCompare(l.scope)||a.prefix.localeCompare(l.prefix))}class dl{files;aliases;tsProjects;packages;workspaces=new Map;deps;nearestCache=new Map;constructor(e,t){this.files=e;this.tsProjects=kv(e),this.packages=Sv(e);for(let r of this.packages.values())if(r.name)this.workspaces.set(r.name,r);this.deps=Ev(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=Pv(n,e.paths,(r)=>this.nearest(r).pkg?.dir??"")}static create(e,t={}){return new dl(e,t)}isExternal(e){if(e.startsWith("node:")||Cv.has(al(e)))return!0;return this.deps.has(al(e))}resolve(e,t){if(e.startsWith(".")){let r=en(nt(mn(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=mn(e),n=this.nearestCache.get(t);if(n)return n;let r,s;for(let a=t;;a=mn(a))if(r??=this.tsProjects.get(a),s??=this.packages.get(a),r&&s||a==="")break;let o={...r?{ts:r}:{},...s?{pkg:s}:{}};return this.nearestCache.set(t,o),o}resolveConfigured(e,t){let{ts:n,pkg:r}=this.nearest(t),s=this.files.paths;if(n){let l=Rv(n.paths,e,s);if(l)return{path:l,via:"tsconfig"}}if(e.startsWith("#")&&r?.imports){let l=Vd(r.imports,e,r.dir,s);if(l)return{path:l,via:"package-imports"}}let o=al(e),a=this.workspaces.get(o);if(a){let l=Av(a,e.slice(o.length+1),s);if(l)return{path:l,via:"workspace"}}if(n?.baseUrl!==void 0&&!this.isExternal(e)){let l=en(nt(n.baseUrl,e),s);if(l)return{path:l,via:"base-url"}}return}resolveInferred(e,t){let n=this.nearest(t).pkg?.dir??"",r=Jd(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=en(s.root+e.slice(r.length),this.files.paths);return o?{path:o,via:"inferred"}:void 0}}function eo(e,t){let n=e.filter((o)=>wi.test(o.path)),r=n.flatMap((o)=>o.externalImports.map((a)=>({from:o.path,spec:a}))),s=dl.create(t,{infer:r});for(let o of n){let a=[],l=new Set(o.imports);for(let c of o.externalImports){let u=s.resolve(c,o.path);if(u&&u.path!==o.path)l.add(u.path);else if(!u)a.push(c)}o.imports=[...l].sort(),o.externalImports=a}return s}xt();var fx=["node_modules/","/dist/","/build/","/.next/","/__snapshots__/",".min.js",".d.ts",".js.map","third-party/"],Ri=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 px(e){return[...fx,..._i].some((t)=>e.includes(t)||!t.startsWith("/")&&e.startsWith(t))}var hx=(e)=>Math.ceil(e.length/3.6);async function yf(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(`
|
|
114
|
+
`).map((T)=>T.trim()).filter(Boolean),l=new Set(a),c=(await le("git",["-C",t,"ls-files"])).split(`
|
|
115
|
+
`).map((T)=>T.trim()).filter((T)=>T&&!px(T)&&jt(T)!==null);await Promise.resolve().then(() => xl());let d=await Rr.create();await d.warmup(["typescript","tsx","cpp"]);let f=new Map,p=Date.now();for(let T of c)try{let U=await d.parseFile(_f.join(t,T),T,t);if(U)f.set(T,U)}catch{}let h=Date.now()-p,x=eo([...f.values()],Zs(t)),R=new Map;for(let[T,U]of f)for(let Z of U.imports??[]){if(!R.has(Z))R.set(Z,new Set);R.get(Z).add(T)}let w=new Map;for(let[T,U]of f)for(let Z of U.symbols??[]){if(Z.kind==="variable"&&!Z.exported)continue;let fe=w.get(Z.name);if(fe){if(fe.length<8)fe.push(T)}else w.set(Z.name,[T])}let v=await le("git",["-C",t,"-c","diff.renames=true","diff","-U0",`${n}..${r}`]),y=new Set;for(let{file:T,line:U}of Zt(v)){if(!T||!jt(T))continue;if(U.startsWith("+++ "))continue;if(!/^[+-]/.test(U))continue;for(let Z of U.matchAll(/[A-Za-z_][A-Za-z0-9_]{3,}/g))y.add(Z[0])}let P=await le("git",["-C",t,"-c","diff.renames=true","diff","-U4",`${n}..${r}`]),D=new Set;{let T=[...Zt(P)];for(let U=0;U<T.length;U++){if(!T[U].line.startsWith("+")||T[U].line.startsWith("+++"))continue;if(!T[U].file||!jt(T[U].file))continue;for(let Z=Math.max(0,U-4);Z<=Math.min(T.length-1,U+4);Z++){if(T[Z].file!==T[U].file)continue;let fe=T[Z].line;if(!fe.startsWith(" "))continue;for(let ue of fe.matchAll(/[A-Za-z_][A-Za-z0-9_]{7,}/g)){let Fe=ue[0];if(Ri.has(Fe.toLowerCase()))continue;if(!/[A-Z_]/.test(Fe))continue;if(l.size&&w.has(Fe))D.add(Fe)}}}}let g=new Map,k=new Map,C=(T,U,Z)=>{if(!f.has(T)||l.has(T))return;if(g.set(T,(g.get(T)??0)+U),!k.has(T))k.set(T,new Set);k.get(T).add(Z)};for(let T of a){for(let U of f.get(T)?.imports??[])C(U,6,"imported by a changed file");for(let U of R.get(T)??[])C(U,5,"imports a changed file")}let M=new Set;for(let T of a)for(let U of f.get(T)?.symbols??[])M.add(U.name);let I=new Map;if(D.size){let T=[...D];for(let[U]of f){if(l.has(U))continue;let Z;try{Z=await Yt(_f.join(t,U))}catch{continue}if(Z.length>2000000)continue;let fe=new Set(Z.match(/[A-Za-z0-9_$]+/g)??[]);for(let ue of T)if(fe.has(ue)){if(!I.has(U))I.set(U,new Set);I.get(U).add(ue)}}}for(let[T,U]of I)for(let Z of U){let fe=[...I.values()].filter((ue)=>ue.has(Z)).length;if(fe>12)continue;C(T,fe<=4?8:4,`also references \`${Z}\``)}for(let T of y){if(T.length<6)continue;if(Ri.has(T)||Ri.has(T.toLowerCase()))continue;if(!/[A-Z_]/.test(T))continue;if(M.has(T))continue;let U=w.get(T);if(!U||U.length>3)continue;let Z=U.length===1?4:2;for(let fe of U)C(fe,Z,`defines \`${T}\``)}let F=[...g.entries()].sort((T,U)=>U[1]-T[1]),B=F.map(([T])=>T);if(process.env.MAP_DEBUG)for(let[T,U]of F.slice(0,30))console.error(String(U).padStart(4),T,"|",[...k.get(T)??[]].slice(0,4).join("; "));let L=(T,U)=>{let Z=f.get(T);if(!Z)return"";let fe=(Z.symbols??[]).filter((Xe)=>Xe.exported||Z.language==="cpp"||Xe.kind!=="variable"),ue=fe.slice(0,40).map((Xe)=>` ${Xe.line} ${Xe.kind} ${Xe.signature||Xe.name}`),Fe=fe.length>40?` \u2026 ${fe.length-40} more
|
|
116
|
+
`:"";return`### ${T} (${Z.lines} lines)${U}
|
|
117
|
+
${ue.join(`
|
|
118
|
+
`)}
|
|
119
|
+
${Fe}`},H=[],ge=0,ke=(T,U=s)=>{let Z=hx(T);if(ge+Z>U)return!1;return H.push(T),ge+=Z,!0},ie=new Map;for(let[T,U]of f){let Z=T.split("/"),fe=Z.slice(0,Math.min(3,Z.length-1)).join("/")||".",ue=ie.get(fe)??{files:0,symbols:0};ue.files++,ue.symbols+=(U.symbols??[]).length,ie.set(fe,ue)}let De=[...ie.entries()].sort((T,U)=>U[1].files-T[1].files).slice(0,45).map(([T,U])=>` ${T}/ ${U.files} files, ${U.symbols} symbols`).join(`
|
|
120
|
+
`);ke(`# Repo map for this change
|
|
121
|
+
|
|
122
|
+
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.
|
|
123
|
+
`),ke(`## Codebase layout (parsed source only, ${f.size} files, ${w.size} distinct symbol names)
|
|
124
|
+
|
|
125
|
+
\`\`\`
|
|
126
|
+
${De}
|
|
127
|
+
\`\`\`
|
|
128
|
+
`);let Pe=Math.floor(s*0.5);ke(`## Changed files
|
|
129
|
+
`,Pe);let we=0;for(let T of a)if(f.has(T)&&ke(L(T,""),Pe))we++;ke(`
|
|
130
|
+
## Related files (not changed by this PR)
|
|
131
|
+
`);let q=0;for(let T of B){let U=` \u2014 ${[...k.get(T)??[]].slice(0,3).join("; ")}`;if(!ke(L(T,U)))break;q++}return{markdown:H.join(`
|
|
132
|
+
`),meta:{base:n,head:r,changedFiles:a.length,trackedParsed:f.size,symbolsIndexed:w.size,diffIdentifiers:y.size,candidatesScored:g.size,changedRendered:we,relatedRendered:q,approxTokens:ge,parseMs:h,totalMs:Date.now()-o,inferredAliases:x.aliases.map((T)=>`${T.scope||"."}: ${T.prefix} -> ${T.root||"."}`)}}}xt();$i();xt();async function Rt(e){return await le("git",["-C",Ye,"-c","diff.renames=true",...e])}async function kf(e,t,n){return(await Rt(["diff","--unified=0",`${e}..${t}`,"--",...n])).split(`
|
|
133
|
+
`).filter((s)=>s.startsWith("diff --git ")||s.startsWith("@@")).join(`
|
|
134
|
+
`)}async function ro(e,t,n,r){let s="",o="";if(t)try{let l=JSON.parse(await le("gh",["api",`repos/${e}/pulls/${t}`]));s=l.title??"",o=l.body??""}catch{}let a=await Rt(["log","--format=%s%n%b%n---",`${n}..${r}`]);return{title:s,body:o,commits:a.trim()}}async function xf(e){return JSON.parse(await le("gh",["api","--paginate",e]))}function bx(e){return e.replace(/<!--[\s\S]*?-->/g,"").replace(/\n{3,}/g,`
|
|
135
|
+
|
|
136
|
+
`).trim()}async function Rf(e,t){let n=process.env.PRIOR_FIXTURE;if(n)return await Ks(n);if(!t)return[];let r=[];try{let s=await xf(`repos/${e}/pulls/${t}/comments`),o=vf(s);for(let a of s){let l=no(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:l,...l?{fingerprint:$r(a.body??"").find((c)=>c.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 xf(`repos/${e}/issues/${t}/comments`)){let o=no(s.body??"",s.user?.type,"summary");if(!o&&s.user?.type==="Bot")continue;let a=o?Number(Rl(s.body??"","summary")?.fields.runs??0):void 0,l=o?$r(s.body??"").filter((c)=>c.kind==="summary-item"&&c.fields.fp).map((c)=>({fp:c.fields.fp,file:c.fields.file??"?",line:c.fields.line??"?"})):[];r.push({id:s.id,author:s.user?.login??"?",body:o?bx(s.body??""):s.body??"",resolved:!1,url:s.html_url,mine:o,...s.author_association?{association:s.author_association}:{},...a?{runs:a}:{},...l.length?{summaryClaims:l}:{}})}}catch{}return r}function vx(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 $f(e,t=""){if(e.length===0)return"";let n=e.filter((c)=>!c.mine&&c.file),r=e.filter((c)=>!c.mine&&!c.file&&!vx(c.body,t)),s=e.filter((c)=>c.mine&&c.file&&!c.addressed&&!c.inReplyTo),o=e.filter((c)=>c.mine&&!c.file),a=[],l=(c,u)=>{let d=c.file?`${c.file}${c.line?`:${c.line}`:""}`:"(conversation)",f=c.body.replace(/\s+/g," ").slice(0,u);a.push(`- id=${c.id} @${c.author} \`${d}\`${c.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 c of n)l(c,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 c of r)l(c,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 c of s)l(c,300);if(o.length)for(let c of o){if(c.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 c.summaryClaims)a.push(`- \`${u.file}:${u.line}\``)}a.push("",`Your summary comment (id=${c.id}), conclusions only:`,""),a.push(c.body.slice(0,12000))}a.push("")}return a.join(`
|
|
43
137
|
`)+`
|
|
44
|
-
// ... truncated`:z;Q.push({path:W,content:K,lineCount:G?H:q,truncated:G}),$+=G?H:q}catch{}}return Q}function JB(Z){if(Z.length===0)return"";let Y=["## New Files (Full Source)",""];for(let X of Z){let Q=X.path.split(".").pop()||"",$=zB(Q),W=X.truncated?` (truncated, ${X.lineCount} lines shown)`:"";Y.push(`### ${X.path}${W}`),Y.push("```"+$),Y.push(X.content),Y.push("```"),Y.push("")}return Y.join(`
|
|
45
|
-
`)
|
|
46
|
-
`)
|
|
47
|
-
`)}class T4{#W=!0;#Y;#Z;#H;#X;#z;#Q;#V;#G=0;#B=5;#J=!1;#q=!1;#$=null;#K=()=>{this.debugLog("Connected to event bus"),this.#z=!0,this.#J=!1,this.debugLog("Emitting queued events",this.#X),this.#X.forEach((Z)=>this.emitEventToBus(Z)),this.#X=[],this.stopConnectLoop(),this.#Z().removeEventListener("tanstack-connect-success",this.#K)};#U=()=>{if(this.#G<this.#B){this.#G++,this.dispatchCustomEvent("tanstack-connect",{});return}this.#Z().removeEventListener("tanstack-connect",this.#U),this.#q=!0,this.debugLog("Max retries reached, giving up on connection"),this.stopConnectLoop()};#L=()=>{if(this.#J)return;this.#J=!0,this.#Z().addEventListener("tanstack-connect-success",this.#K),this.#U()};constructor({pluginId:Z,debug:Y=!1,enabled:X=!0,reconnectEveryMs:Q=300}){this.#Y=Z,this.#W=X,this.#Z=this.getGlobalTarget,this.#H=Y,this.debugLog(" Initializing event subscription for plugin",this.#Y),this.#X=[],this.#z=!1,this.#q=!1,this.#Q=null,this.#V=Q}startConnectLoop(){if(this.#Q!==null||this.#z)return;this.debugLog(`Starting connect loop (every ${this.#V}ms)`),this.#Q=setInterval(this.#U,this.#V)}stopConnectLoop(){if(this.#J=!1,this.#Q===null)return;clearInterval(this.#Q),this.#Q=null,this.#X=[],this.debugLog("Stopped connect loop")}debugLog(...Z){if(this.#H)console.log(`\uD83C\uDF34 [tanstack-devtools:${this.#Y}-plugin]`,...Z)}getGlobalTarget(){if(typeof globalThis!=="undefined"&&globalThis.__TANSTACK_EVENT_TARGET__)return this.debugLog("Using global event target"),globalThis.__TANSTACK_EVENT_TARGET__;if(typeof window!=="undefined"&&typeof window.addEventListener!=="undefined")return this.debugLog("Using window as event target"),window;let Z=typeof EventTarget!=="undefined"?new EventTarget:void 0;if(typeof Z==="undefined"||typeof Z.addEventListener==="undefined")return this.debugLog("No event mechanism available, running in non-web environment"),{addEventListener:()=>{},removeEventListener:()=>{},dispatchEvent:()=>!1};return this.debugLog("Using new EventTarget as fallback"),Z}getPluginId(){return this.#Y}dispatchCustomEventShim(Z,Y){try{let X=new Event(Z,{detail:Y});this.#Z().dispatchEvent(X)}catch(X){this.debugLog("Failed to dispatch shim event")}}dispatchCustomEvent(Z,Y){try{this.#Z().dispatchEvent(new CustomEvent(Z,{detail:Y}))}catch(X){this.dispatchCustomEventShim(Z,Y)}}emitEventToBus(Z){this.debugLog("Emitting event to client bus",Z),this.dispatchCustomEvent("tanstack-dispatch-event",Z)}createEventPayload(Z,Y){return{type:`${this.#Y}:${Z}`,payload:Y,pluginId:this.#Y}}emit(Z,Y){if(!this.#W){this.debugLog("Event bus client is disabled, not emitting event",Z,Y);return}if(this.#$)this.debugLog("Emitting event to internal event target",Z,Y),this.#$.dispatchEvent(new CustomEvent(`${this.#Y}:${Z}`,{detail:this.createEventPayload(Z,Y)}));if(this.#q){this.debugLog("Previously failed to connect, not emitting to bus");return}if(!this.#z){if(this.debugLog("Bus not available, will be pushed as soon as connected"),this.#X.push(this.createEventPayload(Z,Y)),typeof CustomEvent!=="undefined"&&!this.#J)this.#L(),this.startConnectLoop();return}return this.emitEventToBus(this.createEventPayload(Z,Y))}on(Z,Y,X){let Q=X?.withEventTarget??!1,$=`${this.#Y}:${Z}`;if(Q){if(!this.#$)this.#$=new EventTarget;this.#$.addEventListener($,(J)=>{Y(J.detail)})}if(!this.#W)return this.debugLog("Event bus client is disabled, not registering event",$),()=>{};let W=(J)=>{this.debugLog("Received event from bus",J.detail),Y(J.detail)};return this.#Z().addEventListener($,W),this.debugLog("Registered event to bus",$),()=>{if(Q)this.#$?.removeEventListener($,W);this.#Z().removeEventListener($,W)}}onAll(Z){if(!this.#W)return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let Y=(X)=>{let Q=X.detail;Z(Q)};return this.#Z().addEventListener("tanstack-devtools-global",Y),()=>this.#Z().removeEventListener("tanstack-devtools-global",Y)}onAllPluginEvents(Z){if(!this.#W)return this.debugLog("Event bus client is disabled, not registering event"),()=>{};let Y=(X)=>{let Q=X.detail;if(this.#Y&&Q.pluginId!==this.#Y)return;Z(Q)};return this.#Z().addEventListener("tanstack-devtools-global",Y),()=>this.#Z().removeEventListener("tanstack-devtools-global",Y)}}class B$ extends T4{constructor(){super({pluginId:"tanstack-ai-devtools"})}}var B1=new B$;async function L$(Z){let Y="";for await(let X of Z)if(X.type==="content"&&X.delta)Y+=X.delta;return Y}function qB(Z){return typeof Z==="object"&&Z!==null&&"~standard"in Z&&typeof Z["~standard"]==="object"&&Z["~standard"].version===1&&typeof Z["~standard"].jsonSchema==="object"&&typeof Z["~standard"].jsonSchema.input==="function"}function R0(Z){return typeof Z==="object"&&Z!==null&&"~standard"in Z&&typeof Z["~standard"]==="object"&&Z!==null&&Z["~standard"]!==null&&"version"in Z["~standard"]&&Z["~standard"].version===1&&"validate"in Z["~standard"]&&typeof Z["~standard"].validate==="function"}function j2(Z,Y=[]){let X={...Z};if(X.type==="object"&&X.properties){let Q={...X.properties},$=Object.keys(Q);for(let W of $){let J=Q[W],z=!Y.includes(W);if(J.type==="object"&&J.properties)Q[W]=j2(J,J.required||[]);else if(J.type==="array"&&J.items)Q[W]={...J,items:j2(J.items,J.items.required||[])};else if(z){if(J.type&&!Array.isArray(J.type))Q[W]={...J,type:[J.type,"null"]};else if(Array.isArray(J.type)&&!J.type.includes("null"))Q[W]={...J,type:[...J.type,"null"]}}}X.properties=Q,X.required=$,X.additionalProperties=!1}if(X.type==="array"&&X.items)X.items=j2(X.items,X.items.required||[]);return X}function I4(Z,Y={}){if(!Z)return;let{forStructuredOutput:X=!1}=Y;if(qB(Z)){let $=Z["~standard"].jsonSchema.input({target:"draft-07"});if(typeof $==="object"&&"$schema"in $){let{$schema:W,...J}=$;$=J}if(typeof $==="object"){if("properties"in $&&!$.type)$.type="object";if($.type==="object"&&!("properties"in $))$.properties={};if($.type==="object"&&!("required"in $))$.required=[];if(X)$=j2($,$.required||[])}return $}if(X&&typeof Z==="object")return j2(Z,Z.required||[]);return Z}function p0(Z,Y){if(!R0(Z))return Y;let X=Z["~standard"].validate(Y);if(X instanceof Promise)throw new Error("Schema validation returned a Promise. Use validateWithStandardSchema for async validation.");if(!X.issues)return X.value;let Q=X.issues.map(($)=>$.message||"Validation failed").join(", ");throw new Error(`Validation failed: ${Q}`)}class nZ{constructor(Z){this.toolCallsMap=new Map,this.tools=Z}addToolCallChunk(Z){let Y=Z.index,X=this.toolCallsMap.get(Y);if(!X){if(Z.toolCall.id&&Z.toolCall.function.name)this.toolCallsMap.set(Y,{id:Z.toolCall.id,type:"function",function:{name:Z.toolCall.function.name,arguments:Z.toolCall.function.arguments||""}})}else{if(Z.toolCall.function.name&&!X.function.name)X.function.name=Z.toolCall.function.name;if(Z.toolCall.function.arguments)X.function.arguments+=Z.toolCall.function.arguments}}hasToolCalls(){return this.getToolCalls().length>0}getToolCalls(){return Array.from(this.toolCallsMap.values()).filter((Z)=>Z.id&&Z.function.name&&Z.function.name.trim().length>0)}async*executeTools(Z){let Y=this.getToolCalls(),X=[];for(let Q of Y){let $=this.tools.find((J)=>J.name===Q.function.name),W;if($?.execute)try{let J;try{J=JSON.parse(Q.function.arguments)}catch(V){throw new Error(`Failed to parse tool arguments as JSON: ${Q.function.arguments}`)}if($.inputSchema&&R0($.inputSchema))try{J=p0($.inputSchema,J)}catch(V){let q=V instanceof Error?V.message:"Validation failed";throw new Error(`Input validation failed for tool ${$.name}: ${q}`)}let z=await $.execute(J);if($.outputSchema&&R0($.outputSchema)&&z!==void 0&&z!==null)try{z=p0($.outputSchema,z)}catch(V){let q=V instanceof Error?V.message:"Validation failed";throw new Error(`Output validation failed for tool ${$.name}: ${q}`)}W=typeof z==="string"?z:JSON.stringify(z)}catch(J){W=`Error executing tool: ${J instanceof Error?J.message:"Unknown error"}`}else W=`Tool ${Q.function.name} does not have an execute function`;yield{type:"tool_result",id:Z.id,model:Z.model,timestamp:Date.now(),toolCallId:Q.id,content:W},X.push({role:"tool",content:W,toolCallId:Q.id})}return X}clear(){this.toolCallsMap.clear()}}async function aZ(Z,Y,X=new Map,Q=new Map){let $=[],W=[],J=[],z=new Map;for(let V of Y)z.set(V.name,V);for(let V of Z){let q=z.get(V.function.name),U=V.function.name;if(!q){$.push({toolCallId:V.id,toolName:U,result:{error:`Unknown tool: ${U}`},state:"output-error"});continue}let H={},G=V.function.arguments.trim()||"{}";try{H=JSON.parse(G)}catch(M){throw new Error(`Failed to parse tool arguments as JSON: ${G}`)}if(q.inputSchema&&R0(q.inputSchema))try{H=p0(q.inputSchema,H)}catch(M){let E=M instanceof Error?M.message:"Validation failed";$.push({toolCallId:V.id,toolName:U,result:{error:`Input validation failed for tool ${q.name}: ${E}`},state:"output-error"});continue}if(!q.execute){if(q.needsApproval){let M=`approval_${V.id}`;if(X.has(M))if(X.get(M))if(Q.has(V.id))$.push({toolCallId:V.id,toolName:U,result:Q.get(V.id)});else J.push({toolCallId:V.id,toolName:U,input:H});else $.push({toolCallId:V.id,toolName:U,result:{error:"User declined tool execution"},state:"output-error"});else W.push({toolCallId:V.id,toolName:V.function.name,input:H,approvalId:M})}else if(Q.has(V.id))$.push({toolCallId:V.id,toolName:U,result:Q.get(V.id)});else J.push({toolCallId:V.id,toolName:U,input:H});continue}if(q.needsApproval){let M=`approval_${V.id}`;if(X.has(M))if(X.get(M)){let O=Date.now();try{let T=await q.execute(H),i=Date.now()-O;if(q.outputSchema&&R0(q.outputSchema)&&T!==void 0&&T!==null)T=p0(q.outputSchema,T);$.push({toolCallId:V.id,toolName:U,result:typeof T==="string"?JSON.parse(T):T||null,duration:i})}catch(T){let i=Date.now()-O,g=T instanceof Error?T.message:"Unknown error";$.push({toolCallId:V.id,toolName:U,result:{error:g},state:"output-error",duration:i})}}else $.push({toolCallId:V.id,toolName:U,result:{error:"User declined tool execution"},state:"output-error"});else W.push({toolCallId:V.id,toolName:U,input:H,approvalId:M});continue}let K=Date.now();try{let M=await q.execute(H),E=Date.now()-K;if(q.outputSchema&&R0(q.outputSchema)&&M!==void 0&&M!==null)M=p0(q.outputSchema,M);$.push({toolCallId:V.id,toolName:U,result:typeof M==="string"?JSON.parse(M):M||null,duration:E})}catch(M){let E=Date.now()-K,O=M instanceof Error?M.message:"Unknown error";$.push({toolCallId:V.id,toolName:U,result:{error:O},state:"output-error",duration:E})}}return{results:$,needsApproval:W,needsClientExecution:J}}function M$(Z){return({iterationCount:Y})=>Y<Z}class rZ{constructor(Z){this.iterationCount=0,this.lastFinishReason=null,this.streamStartTime=0,this.totalChunkCount=0,this.currentMessageId=null,this.accumulatedContent="",this.doneChunk=null,this.shouldEmitStreamEnd=!0,this.earlyTermination=!1,this.toolPhase="continue",this.cyclePhase="processText",this.adapter=Z.adapter,this.params=Z.params,this.systemPrompts=Z.params.systemPrompts||[],this.tools=Z.params.tools||[],this.loopStrategy=Z.params.agentLoopStrategy||M$(5),this.toolCallManager=new nZ(this.tools),this.initialMessageCount=Z.params.messages.length,this.messages=Z.params.messages,this.requestId=this.createId("chat"),this.streamId=this.createId("stream"),this.effectiveRequest=Z.params.abortController?{signal:Z.params.abortController.signal}:void 0,this.effectiveSignal=Z.params.abortController?.signal}getAccumulatedContent(){return this.accumulatedContent}getMessages(){return this.messages}async*run(){this.beforeRun();try{if((yield*this.checkForPendingToolCalls())==="wait")return;do{if(this.earlyTermination||this.isAborted())return;if(this.beginCycle(),this.cyclePhase==="processText")yield*this.streamModelResponse();else yield*this.processToolCalls();this.endCycle()}while(this.shouldContinue())}finally{this.afterRun()}}beforeRun(){this.streamStartTime=Date.now();let{model:Z,tools:Y,temperature:X,topP:Q,maxTokens:$,metadata:W,modelOptions:J,conversationId:z}=this.params,V={};if(X!==void 0)V.temperature=X;if(Q!==void 0)V.topP=Q;if($!==void 0)V.maxTokens=$;if(W!==void 0)V.metadata=W;B1.emit("text:started",{requestId:this.requestId,streamId:this.streamId,model:Z,provider:this.adapter.name,messageCount:this.initialMessageCount,hasTools:!!Y&&Y.length>0,streaming:!0,timestamp:Date.now(),clientId:z,toolNames:Y?.map((q)=>q.name),options:Object.keys(V).length>0?V:void 0,modelOptions:J}),B1.emit("stream:started",{streamId:this.streamId,model:Z,provider:this.adapter.name,timestamp:Date.now()})}afterRun(){if(!this.shouldEmitStreamEnd)return;let Z=Date.now();B1.emit("text:completed",{requestId:this.requestId,streamId:this.streamId,model:this.params.model,content:this.accumulatedContent,messageId:this.currentMessageId||void 0,finishReason:this.lastFinishReason||void 0,usage:this.doneChunk?.usage,timestamp:Z}),B1.emit("stream:ended",{requestId:this.requestId,streamId:this.streamId,totalChunks:this.totalChunkCount,duration:Z-this.streamStartTime,timestamp:Z})}beginCycle(){if(this.cyclePhase==="processText")this.beginIteration()}endCycle(){if(this.cyclePhase==="processText"){this.cyclePhase="executeToolCalls";return}this.cyclePhase="processText",this.iterationCount++}beginIteration(){this.currentMessageId=this.createId("msg"),this.accumulatedContent="",this.doneChunk=null}async*streamModelResponse(){let{temperature:Z,topP:Y,maxTokens:X,metadata:Q,modelOptions:$}=this.params,J=this.params.tools?.map((z)=>({...z,inputSchema:z.inputSchema?I4(z.inputSchema):void 0,outputSchema:z.outputSchema?I4(z.outputSchema):void 0}));for await(let z of this.adapter.chatStream({model:this.params.model,messages:this.messages,tools:J,temperature:Z,topP:Y,maxTokens:X,metadata:Q,request:this.effectiveRequest,modelOptions:$,systemPrompts:this.systemPrompts})){if(this.isAborted())break;if(this.totalChunkCount++,yield z,this.handleStreamChunk(z),this.earlyTermination)break}}handleStreamChunk(Z){switch(Z.type){case"content":this.handleContentChunk(Z);break;case"tool_call":this.handleToolCallChunk(Z);break;case"tool_result":this.handleToolResultChunk(Z);break;case"done":this.handleDoneChunk(Z);break;case"error":this.handleErrorChunk(Z);break;case"thinking":this.handleThinkingChunk(Z);break}}handleContentChunk(Z){this.accumulatedContent=Z.content,B1.emit("stream:chunk:content",{streamId:this.streamId,messageId:this.currentMessageId||void 0,content:Z.content,delta:Z.delta,timestamp:Date.now()})}handleToolCallChunk(Z){this.toolCallManager.addToolCallChunk(Z),B1.emit("stream:chunk:tool-call",{streamId:this.streamId,messageId:this.currentMessageId||void 0,toolCallId:Z.toolCall.id,toolName:Z.toolCall.function.name,index:Z.index,arguments:Z.toolCall.function.arguments,timestamp:Date.now()})}handleToolResultChunk(Z){B1.emit("stream:chunk:tool-result",{streamId:this.streamId,messageId:this.currentMessageId||void 0,toolCallId:Z.toolCallId,result:Z.content,timestamp:Date.now()})}handleDoneChunk(Z){if(this.doneChunk?.finishReason==="tool_calls"&&Z.finishReason==="stop"){if(this.lastFinishReason=Z.finishReason,B1.emit("stream:chunk:done",{streamId:this.streamId,messageId:this.currentMessageId||void 0,finishReason:Z.finishReason,usage:Z.usage,timestamp:Date.now()}),Z.usage)B1.emit("usage:tokens",{requestId:this.requestId,streamId:this.streamId,messageId:this.currentMessageId||void 0,model:this.params.model,usage:Z.usage,timestamp:Date.now()});return}if(this.doneChunk=Z,this.lastFinishReason=Z.finishReason,B1.emit("stream:chunk:done",{streamId:this.streamId,messageId:this.currentMessageId||void 0,finishReason:Z.finishReason,usage:Z.usage,timestamp:Date.now()}),Z.usage)B1.emit("usage:tokens",{requestId:this.requestId,streamId:this.streamId,messageId:this.currentMessageId||void 0,model:this.params.model,usage:Z.usage,timestamp:Date.now()})}handleErrorChunk(Z){B1.emit("stream:chunk:error",{streamId:this.streamId,messageId:this.currentMessageId||void 0,error:Z.error.message,timestamp:Date.now()}),this.earlyTermination=!0,this.shouldEmitStreamEnd=!1}handleThinkingChunk(Z){B1.emit("stream:chunk:thinking",{streamId:this.streamId,messageId:this.currentMessageId||void 0,content:Z.content,delta:Z.delta,timestamp:Date.now()})}async*checkForPendingToolCalls(){let Z=this.getPendingToolCallsFromMessages();if(Z.length===0)return"continue";let Y=this.createSyntheticDoneChunk();B1.emit("text:iteration",{requestId:this.requestId,streamId:this.streamId,iterationNumber:this.iterationCount+1,messageCount:this.messages.length,toolCallCount:Z.length,timestamp:Date.now()});let{approvals:X,clientToolResults:Q}=this.collectClientState(),$=await aZ(Z,this.tools,X,Q);if($.needsApproval.length>0||$.needsClientExecution.length>0){for(let J of this.emitApprovalRequests($.needsApproval,Y))yield J;for(let J of this.emitClientToolInputs($.needsClientExecution,Y))yield J;return this.shouldEmitStreamEnd=!1,"wait"}let W=this.emitToolResults($.results,Y);for(let J of W)yield J;return"continue"}async*processToolCalls(){if(!this.shouldExecuteToolPhase()){this.setToolPhase("stop");return}let Z=this.toolCallManager.getToolCalls(),Y=this.doneChunk;if(!Y||Z.length===0){this.setToolPhase("stop");return}B1.emit("text:iteration",{requestId:this.requestId,streamId:this.streamId,iterationNumber:this.iterationCount+1,messageCount:this.messages.length,toolCallCount:Z.length,timestamp:Date.now()}),this.addAssistantToolCallMessage(Z);let{approvals:X,clientToolResults:Q}=this.collectClientState(),$=await aZ(Z,this.tools,X,Q);if($.needsApproval.length>0||$.needsClientExecution.length>0){for(let J of this.emitApprovalRequests($.needsApproval,Y))yield J;for(let J of this.emitClientToolInputs($.needsClientExecution,Y))yield J;this.setToolPhase("wait");return}let W=this.emitToolResults($.results,Y);for(let J of W)yield J;this.toolCallManager.clear(),this.setToolPhase("continue")}shouldExecuteToolPhase(){return this.doneChunk?.finishReason==="tool_calls"&&this.tools.length>0&&this.toolCallManager.hasToolCalls()}addAssistantToolCallMessage(Z){this.messages=[...this.messages,{role:"assistant",content:this.accumulatedContent||null,toolCalls:Z}]}collectClientState(){let Z=new Map,Y=new Map;for(let X of this.messages)if(X.role==="assistant"&&X.parts){let Q=X.parts;for(let $ of Q){if($.type==="tool-call"&&$.state==="approval-responded"&&$.approval)Z.set($.approval.id,$.approval.approved);if($.type==="tool-call"&&$.output!==void 0&&!$.approval)Y.set($.id,$.output)}}return{approvals:Z,clientToolResults:Y}}emitApprovalRequests(Z,Y){let X=[];for(let Q of Z)B1.emit("stream:approval-requested",{streamId:this.streamId,messageId:this.currentMessageId||void 0,toolCallId:Q.toolCallId,toolName:Q.toolName,input:Q.input,approvalId:Q.approvalId,timestamp:Date.now()}),X.push({type:"approval-requested",id:Y.id,model:Y.model,timestamp:Date.now(),toolCallId:Q.toolCallId,toolName:Q.toolName,input:Q.input,approval:{id:Q.approvalId,needsApproval:!0}});return X}emitClientToolInputs(Z,Y){let X=[];for(let Q of Z)B1.emit("stream:tool-input-available",{streamId:this.streamId,messageId:this.currentMessageId||void 0,toolCallId:Q.toolCallId,toolName:Q.toolName,input:Q.input,timestamp:Date.now()}),X.push({type:"tool-input-available",id:Y.id,model:Y.model,timestamp:Date.now(),toolCallId:Q.toolCallId,toolName:Q.toolName,input:Q.input});return X}emitToolResults(Z,Y){let X=[];for(let Q of Z){B1.emit("tool:call-completed",{requestId:this.requestId,streamId:this.streamId,messageId:this.currentMessageId||void 0,toolCallId:Q.toolCallId,toolName:Q.toolName,result:Q.result,duration:Q.duration??0,timestamp:Date.now()});let $=JSON.stringify(Q.result),W={type:"tool_result",id:Y.id,model:Y.model,timestamp:Date.now(),toolCallId:Q.toolCallId,content:$};X.push(W),this.messages=[...this.messages,{role:"tool",content:$,toolCallId:Q.toolCallId}]}return X}getPendingToolCallsFromMessages(){let Z=new Set(this.messages.filter((X)=>X.role==="tool"&&X.toolCallId).map((X)=>X.toolCallId)),Y=[];for(let X of this.messages)if(X.role==="assistant"&&X.toolCalls){for(let Q of X.toolCalls)if(!Z.has(Q.id))Y.push(Q)}return Y}createSyntheticDoneChunk(){return{type:"done",id:this.createId("pending"),model:this.params.model,timestamp:Date.now(),finishReason:"tool_calls"}}shouldContinue(){if(this.cyclePhase==="executeToolCalls")return!0;return this.loopStrategy({iterationCount:this.iterationCount,messages:this.messages,finishReason:this.lastFinishReason})&&this.toolPhase==="continue"}isAborted(){return!!this.effectiveSignal?.aborted}setToolPhase(Z){if(this.toolPhase=Z,Z==="wait")this.shouldEmitStreamEnd=!1}createId(Z){return`${Z}-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}}function k1(Z){let{outputSchema:Y,stream:X}=Z;if(Y)return HB(Z);if(X===!1)return UB(Z);return F$(Z)}async function*F$(Z){let{adapter:Y,...X}=Z,Q=Y.model,$=new rZ({adapter:Y,params:{...X,model:Q}});for await(let W of $.run())yield W}function UB(Z){let Y=F$(Z);return L$(Y)}async function HB(Z){let{adapter:Y,outputSchema:X,...Q}=Z,$=Y.model;if(!X)throw new Error("outputSchema is required for structured output");let W=new rZ({adapter:Y,params:{...Q,model:$}});for await(let G of W.run());let J=W.getMessages(),{tools:z,agentLoopStrategy:V,...q}=Q,U=I4(X);if(!U)throw new Error("Failed to convert output schema to JSON Schema");let H=await Y.structuredOutput({chatOptions:{...q,model:$,messages:J},outputSchema:U});if(R0(X))return p0(X,H.data);return H.data}class R4{constructor(Z={},Y){this.kind="text",this.config=Z,this.model=Y}generateId(){return`${this.name}-${Date.now()}-${Math.random().toString(36).substring(7)}`}}function N$(Z){return Z.metadata}function w$(Z){return Z.metadata}function D$(Z){return Z.metadata}function A$(Z){let Y=Z.metadata||{},X=Z.inputSchema??{properties:{},required:[]},Q={type:"object",properties:X.properties||null,required:X.required||null};return{name:Z.name,type:"custom",description:Z.description,input_schema:Q,cache_control:Y.cacheControl||null}}function E$(Z){return{type:"memory_20250818",...Z.metadata}}function O$(Z){return{...Z.metadata}}function P$(Z){return{name:"web_fetch",type:"web_fetch_20250910",...Z.metadata}}function T$(Z){let Y=Z.metadata;return{name:"web_search",type:"web_search_20250305",allowed_domains:Y.allowedDomains,blocked_domains:Y.blockedDomains,max_uses:Y.maxUses,user_location:Y.userLocation,cache_control:Y.cacheControl||null}}function sZ(Z){return Z.map((Y)=>{switch(Y.name){case"bash":return N$(Y);case"code_execution":return w$(Y);case"computer":return D$(Y);case"memory":return E$(Y);case"str_replace_editor":return O$(Y);case"web_fetch":return P$(Y);case"web_search":return T$(Y);default:return A$(Y)}})}var GB=(Z)=>{if(Z.top_p!==void 0&&Z.temperature!==void 0)throw new Error("You should either set top_p or temperature, but not both.")},KB=(Z)=>{let Y=Z.thinking;if(Y&&Y.type==="enabled"){if(Y.budget_tokens<1024)throw new Error("thinking.budget_tokens must be at least 1024.");if(Y.budget_tokens>=Z.max_tokens)throw new Error("thinking.budget_tokens must be less than max_tokens.")}},BB=(Z)=>{if(Z.max_tokens<1)throw new Error("max_tokens must be at least 1.")},I$=(Z)=>{GB(Z),KB(Z),BB(Z)};function A(Z,Y,X,Q,$){if(Q==="m")throw new TypeError("Private method is not writable");if(Q==="a"&&!$)throw new TypeError("Private accessor was defined without a setter");if(typeof Y==="function"?Z!==Y||!$:!Y.has(Z))throw new TypeError("Cannot write private member to an object whose class did not declare it");return Q==="a"?$.call(Z,X):$?$.value=X:Y.set(Z,X),X}function B(Z,Y,X,Q){if(X==="a"&&!Q)throw new TypeError("Private accessor was defined without a getter");if(typeof Y==="function"?Z!==Y||!Q:!Y.has(Z))throw new TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?Q:X==="a"?Q.call(Z):Q?Q.value:Y.get(Z)}var tZ=function(){let{crypto:Z}=globalThis;if(Z?.randomUUID)return tZ=Z.randomUUID.bind(Z),Z.randomUUID();let Y=new Uint8Array(1),X=Z?()=>Z.getRandomValues(Y)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(Q)=>(+Q^X()&15>>+Q/4).toString(16))};function j0(Z){return typeof Z==="object"&&Z!==null&&(("name"in Z)&&Z.name==="AbortError"||("message"in Z)&&String(Z.message).includes("FetchRequestCanceledException"))}var C2=(Z)=>{if(Z instanceof Error)return Z;if(typeof Z==="object"&&Z!==null){try{if(Object.prototype.toString.call(Z)==="[object Error]"){let Y=new Error(Z.message,Z.cause?{cause:Z.cause}:{});if(Z.stack)Y.stack=Z.stack;if(Z.cause&&!Y.cause)Y.cause=Z.cause;if(Z.name)Y.name=Z.name;return Y}}catch{}try{return new Error(JSON.stringify(Z))}catch{}}return new Error(Z)};class R extends Error{}class L1 extends R{constructor(Z,Y,X,Q){super(`${L1.makeMessage(Z,Y,X)}`);this.status=Z,this.headers=Q,this.requestID=Q?.get("request-id"),this.error=Y}static makeMessage(Z,Y,X){let Q=Y?.message?typeof Y.message==="string"?Y.message:JSON.stringify(Y.message):Y?JSON.stringify(Y):X;if(Z&&Q)return`${Z} ${Q}`;if(Z)return`${Z} status code (no body)`;if(Q)return Q;return"(no status code or body)"}static generate(Z,Y,X,Q){if(!Z||!Q)return new H9({message:X,cause:C2(Y)});let $=Y;if(Z===400)return new _2(Z,$,X,Q);if(Z===401)return new y2(Z,$,X,Q);if(Z===403)return new b2(Z,$,X,Q);if(Z===404)return new x2(Z,$,X,Q);if(Z===409)return new k2(Z,$,X,Q);if(Z===422)return new v2(Z,$,X,Q);if(Z===429)return new f2(Z,$,X,Q);if(Z>=500)return new h2(Z,$,X,Q);return new L1(Z,$,X,Q)}}class P1 extends L1{constructor({message:Z}={}){super(void 0,void 0,Z||"Request was aborted.",void 0)}}class H9 extends L1{constructor({message:Z,cause:Y}){super(void 0,void 0,Z||"Connection error.",void 0);if(Y)this.cause=Y}}class S2 extends H9{constructor({message:Z}={}){super({message:Z??"Request timed out."})}}class _2 extends L1{}class y2 extends L1{}class b2 extends L1{}class x2 extends L1{}class k2 extends L1{}class v2 extends L1{}class f2 extends L1{}class h2 extends L1{}var MB=/^[a-z][a-z0-9+.-]*:/i,R$=(Z)=>{return MB.test(Z)},eZ=(Z)=>(eZ=Array.isArray,eZ(Z)),ZY=eZ;function j4(Z){if(typeof Z!=="object")return{};return Z??{}}function j$(Z){if(!Z)return!0;for(let Y in Z)return!1;return!0}function C$(Z,Y){return Object.prototype.hasOwnProperty.call(Z,Y)}var S$=(Z,Y)=>{if(typeof Y!=="number"||!Number.isInteger(Y))throw new R(`${Z} must be an integer`);if(Y<0)throw new R(`${Z} must be a positive integer`);return Y};var C4=(Z)=>{try{return JSON.parse(Z)}catch(Y){return}};var _$=(Z)=>new Promise((Y)=>setTimeout(Y,Z));var d0="0.71.2";var k$=()=>{return typeof window!=="undefined"&&typeof window.document!=="undefined"&&typeof navigator!=="undefined"};function FB(){if(typeof Deno!=="undefined"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime!=="undefined")return"edge";if(Object.prototype.toString.call(typeof globalThis.process!=="undefined"?globalThis.process:0)==="[object process]")return"node";return"unknown"}var NB=()=>{let Z=FB();if(Z==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":d0,"X-Stainless-OS":b$(Deno.build.os),"X-Stainless-Arch":y$(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime!=="undefined")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":d0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(Z==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":d0,"X-Stainless-OS":b$(globalThis.process.platform??"unknown"),"X-Stainless-Arch":y$(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Y=wB();if(Y)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":d0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${Y.browser}`,"X-Stainless-Runtime-Version":Y.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":d0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function wB(){if(typeof navigator==="undefined"||!navigator)return null;let Z=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:Y,pattern:X}of Z){let Q=X.exec(navigator.userAgent);if(Q){let $=Q[1]||0,W=Q[2]||0,J=Q[3]||0;return{browser:Y,version:`${$}.${W}.${J}`}}}return null}var y$=(Z)=>{if(Z==="x32")return"x32";if(Z==="x86_64"||Z==="x64")return"x64";if(Z==="arm")return"arm";if(Z==="aarch64"||Z==="arm64")return"arm64";if(Z)return`other:${Z}`;return"unknown"},b$=(Z)=>{if(Z=Z.toLowerCase(),Z.includes("ios"))return"iOS";if(Z==="android")return"Android";if(Z==="darwin")return"MacOS";if(Z==="win32")return"Windows";if(Z==="freebsd")return"FreeBSD";if(Z==="openbsd")return"OpenBSD";if(Z==="linux")return"Linux";if(Z)return`Other:${Z}`;return"Unknown"},x$,v$=()=>{return x$??(x$=NB())};function f$(){if(typeof fetch!=="undefined")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function YY(...Z){let Y=globalThis.ReadableStream;if(typeof Y==="undefined")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new Y(...Z)}function S4(Z){let Y=Symbol.asyncIterator in Z?Z[Symbol.asyncIterator]():Z[Symbol.iterator]();return YY({start(){},async pull(X){let{done:Q,value:$}=await Y.next();if(Q)X.close();else X.enqueue($)},async cancel(){await Y.return?.()}})}function g2(Z){if(Z[Symbol.asyncIterator])return Z;let Y=Z.getReader();return{async next(){try{let X=await Y.read();if(X?.done)Y.releaseLock();return X}catch(X){throw Y.releaseLock(),X}},async return(){let X=Y.cancel();return Y.releaseLock(),await X,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function h$(Z){if(Z===null||typeof Z!=="object")return;if(Z[Symbol.asyncIterator]){await Z[Symbol.asyncIterator]().return?.();return}let Y=Z.getReader(),X=Y.cancel();Y.releaseLock(),await X}var g$=({headers:Z,body:Y})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Y)}};function p$(Z){let Y=0;for(let $ of Z)Y+=$.length;let X=new Uint8Array(Y),Q=0;for(let $ of Z)X.set($,Q),Q+=$.length;return X}var u$;function u2(Z){let Y;return(u$??(Y=new globalThis.TextEncoder,u$=Y.encode.bind(Y)))(Z)}var m$;function XY(Z){let Y;return(m$??(Y=new globalThis.TextDecoder,m$=Y.decode.bind(Y)))(Z)}var i1,o1;class c0{constructor(){i1.set(this,void 0),o1.set(this,void 0),A(this,i1,new Uint8Array,"f"),A(this,o1,null,"f")}decode(Z){if(Z==null)return[];let Y=Z instanceof ArrayBuffer?new Uint8Array(Z):typeof Z==="string"?u2(Z):Z;A(this,i1,p$([B(this,i1,"f"),Y]),"f");let X=[],Q;while((Q=EB(B(this,i1,"f"),B(this,o1,"f")))!=null){if(Q.carriage&&B(this,o1,"f")==null){A(this,o1,Q.index,"f");continue}if(B(this,o1,"f")!=null&&(Q.index!==B(this,o1,"f")+1||Q.carriage)){X.push(XY(B(this,i1,"f").subarray(0,B(this,o1,"f")-1))),A(this,i1,B(this,i1,"f").subarray(B(this,o1,"f")),"f"),A(this,o1,null,"f");continue}let $=B(this,o1,"f")!==null?Q.preceding-1:Q.preceding,W=XY(B(this,i1,"f").subarray(0,$));X.push(W),A(this,i1,B(this,i1,"f").subarray(Q.index),"f"),A(this,o1,null,"f")}return X}flush(){if(!B(this,i1,"f").length)return[];return this.decode(`
|
|
48
|
-
`)}}
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
138
|
+
`}hi();async function Sf(e){let t=Za(e.diffU0),n=new Map;for(let{file:a,line:l}of Zt(e.diffU0)){if(!a||!l.startsWith("+")||l.startsWith("+++ "))continue;let c=n.get(a)??new Set;for(let u of l.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g))c.add(u[0]);n.set(a,c)}await Promise.resolve().then(() => xl());let s=await Rr.create(),o=[];for(let a of e.files){let l={path:a,imports:[],externalImports:[]},c=[];if(jt(a))try{let u=e.source.read(a),d=u===void 0?null:await s.parseSource(u,a,e.source.paths);if(d){let f=t.get(a)??[];l.imports=d.imports,l.externalImports=d.externalImports,c=d.symbols.filter((p)=>f.some((h)=>p.line>=h.start&&p.line<=h.end)).map((p)=>p.name)}}catch{}o.push({file:a,imports:l,defined:c})}return eo(o.map((a)=>a.imports),e.source),o.map(({file:a,imports:l,defined:c})=>({file:a,tokens:e.fileTokens.get(a)??0,imports:l.imports,defined:[...new Set(c)],used:[...n.get(a)??[]]}))}var $l=/\.(test|spec)(\.[cm]?[jt]sx?)$/,Sl=/\.(h|hh|hpp)$/,El=/\.(c|cc|cpp|cxx)$/;function Ct(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 xx(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 kx(e,t){if(Al(e)!==Al(t))return!1;let[n,r]=[Ct(e),Ct(t)];if(!(n===r||Ct(n)===r||Ct(r)===n))return!1;if($l.test(e)!==$l.test(t))return!0;return Sl.test(e)&&El.test(t)||Sl.test(t)&&El.test(e)}function Cf(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(!xx(f,t))continue;let p=r.get(f)??[];p.push(d.file),r.set(f,p)}let s=new Map;for(let d of e)for(let f of new Set(d.used))if(r.has(f))s.set(f,(s.get(f)??0)+1);let o=new Map;for(let d of e)for(let f of new Set(d.imports))if(n.has(f)&&f!==d.file)o.set(f,(o.get(f)??0)+1);let a={symbol:0,pair:1,import:2,dir:3},l=new Map,c=(d,f,p,h,x)=>{if(d===f)return;let R=d<f?`${d}\x00${f}`:`${f}\x00${d}`,w=l.get(R);if(!w){l.set(R,{from:d,to:f,kind:p,weight:h,...x?{names:[x]}:{}});return}if(w.weight+=h,a[p]<a[w.kind])w.kind=p,w.from=d,w.to=f;if(x&&!w.names?.includes(x))w.names=[...w.names??[],x]};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 x of p)c(d.file,x,"symbol",4/h,f)}for(let f of new Set(d.imports)){if(!n.has(f))continue;c(d.file,f,"import",2/Math.max(1,(o.get(f)??1)-1))}}let u=[...n].sort();for(let d=0;d<u.length;d++)for(let f=d+1;f<u.length;f++){let[p,h]=[u[d],u[f]];if(kx(p,h))c(p,h,"pair",3);else if(Ct(p)===Ct(h))c(p,h,"dir",0.25)}return Rx([...l.values()])}function Rx(e){return e.sort((t,n)=>n.weight-t.weight||t.from.localeCompare(n.from)||t.to.localeCompare(n.to))}function $x(e){if(!e.length)return"";let t=Ct(e[0]).split("/");for(let n of e.slice(1)){let r=Ct(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 Ef(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function Sx(e,t){let n=$x(e).split("/").filter(Boolean);if(e.length>1&&n.length>=3)return Ef(n.slice(-2).join("-"));let r=[...e].sort((s,o)=>(t.get(o)??0)-(t.get(s)??0))[0];return Ef(Al(r))||"files"}function Af(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 If=new Set(["symbol","pair"]);function Of(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,k)=>[g.file,k])),l=new Map(e.map((g,k)=>[k,new Set([g.file])])),c=new Map(e.map((g,k)=>[k,g.tokens])),u=(g,k)=>{let[C,M]=l.get(g).size>=l.get(k).size?[g,k]:[k,g];for(let I of l.get(M))a.set(I,C),l.get(C).add(I);c.set(C,c.get(C)+c.get(M)),l.delete(M),c.delete(M)},d=n.target??Math.round(n.budget*0.7),f=(g,k,C)=>c.get(g)+c.get(k)<=d&&l.get(g).size+l.get(k).size<=C,p=[[(g)=>If.has(g.kind),r],[(g)=>g.kind==="import",r],[(g)=>g.kind==="dir",s]];for(let[g,k]of p)for(let C of t){if(!g(C))continue;let[M,I]=[a.get(C.from),a.get(C.to)];if(M===void 0||I===void 0||M===I||!f(M,I,k))continue;u(M,I)}let h=d/4,x=()=>[...l.keys()].sort((g,k)=>c.get(g)-c.get(k)||g-k);for(let g of x()){if(!l.has(g)||c.get(g)>h||l.get(g).size>2)continue;let k;for(let C of l.keys()){if(C===g||!f(g,C,s))continue;let M=0;for(let I of l.get(g))for(let F of l.get(C))M=Math.max(M,Af(Ct(I),Ct(F)));if(M>0&&(!k||M>k.depth))k={group:C,depth:M}}if(k)u(k.group,g)}Ex(t,a,l,c,o,n.budget,r*2),Cx(a,l,c,o);let R=(g,k=!1)=>{let C=new Map;for(let F of t){let[B,L]=[a.get(F.from),a.get(F.to)];if(B===L||B!==g&&L!==g)continue;let H=B===g?L:B;C.set(H,(C.get(H)??0)+F.weight)}let M=new Set([...l.get(g)].map(io)),I;for(let F of l.keys()){if(F===g||c.get(g)+c.get(F)>n.budget)continue;let B=0;for(let ke of l.get(g))for(let ie of l.get(F))B=Math.max(B,Af(Ct(ke),Ct(ie)));let L=C.get(F)??0,H=[...l.get(F)].some((ke)=>M.has(io(ke)));if(k&&!H)continue;if(!I||L>I.weight||L===I.weight&&H&&!I.sameLanguage||L===I.weight&&H===I.sameLanguage&&B>I.depth||L===I.weight&&H===I.sameLanguage&&B===I.depth&&c.get(F)<c.get(I.group))I={group:F,weight:L,sameLanguage:H,depth:B}}return I?.group};while(n.maxGroups&&l.size>n.maxGroups){let g=x()[0],k=R(g);if(k===void 0)break;u(k,g)}if(n.foldSmall!==!1)for(let g of x()){if(l.size<2)break;if(!l.has(g)||c.get(g)>h||l.get(g).size>2)continue;let k=R(g,!0);if(k!==void 0)u(k,g)}let w=[...l.values()].map((g)=>[...g].sort()).sort((g,k)=>Sr(k,o)-Sr(g,o)||g[0].localeCompare(k[0])),v=new Map,y=new Map,P=w.map((g,k)=>{for(let I of g)y.set(I,k);let C=Sx(g,o),M=(v.get(C)??0)+1;return v.set(C,M),{id:M>1?`${C}-${M}`:C,files:g,tokens:Sr(g,o),links:[]}}),D=[];for(let g of t){let[k,C]=[y.get(g.from),y.get(g.to)];if(k===void 0||C===void 0)continue;if(k===C)P[k].links.push(g);else if(g.kind!=="dir")D.push(g)}return{groups:P,cut:D}}function Ex(e,t,n,r,s,o,a){let l=new Map;for(let u of e){if(!If.has(u.kind))continue;for(let d of[u.from,u.to])l.set(d,[...l.get(d)??[],u])}let c=[...l.keys()].sort((u,d)=>s.get(u)-s.get(d)||u.localeCompare(d));for(let u=0;u<3;u++){let d=!1;for(let f of c){let p=t.get(f),h=new Map;for(let w of l.get(f)){let v=w.from===f?w.to:w.from,y=t.get(v);h.set(y,(h.get(y)??0)+w.weight)}let x=h.get(p)??0,R;for(let[w,v]of h){if(w===p||v<=x||R&&v<=R.weight)continue;if(r.get(w)+s.get(f)>o||n.get(w).size+1>a)continue;R={group:w,weight:v}}if(!R)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(R.group).add(f),r.set(R.group,r.get(R.group)+s.get(f)),t.set(f,R.group),d=!0}if(!d)break}}var Ax=4;function io(e){if(Sl.test(e)||El.test(e))return"cpp";if(/\.[cm]?[jt]sx?$/.test(e))return"js";return e.slice(e.lastIndexOf(".")+1)}function Cx(e,t,n,r){let s=Math.max(-1,...t.keys())+1,o=(a,l)=>{let c=s++;t.set(c,new Set(l)),n.set(c,Sr(l,r));for(let u of l)t.get(a).delete(u),e.set(u,c);return n.set(a,n.get(a)-n.get(c)),c};for(let a of[...t.keys()]){let l=[...t.get(a)].sort();if(l.length<Ax)continue;let c=new Map;for(let d of l)c.set(io(d),[...c.get(io(d))??[],d]);if(c.size<2||[...c.values()].some((d)=>d.length<2))continue;let[,...u]=[...c.values()].sort((d,f)=>Sr(f,r)-Sr(d,r));for(let d of u)o(a,d)}}function Sr(e,t){return e.reduce((n,r)=>n+(t.get(r)??0),0)}function er(e){switch(e.kind){case"symbol":{let t=(e.names??[]).slice(0,3).map((n)=>`\`${n}\``).join(", ");return`\`${e.from}\` uses ${t}, added in \`${e.to}\``}case"pair":return`\`${e.from}\` and \`${e.to}\` are a test/source or header/source pair`;case"import":return`\`${e.from}\` imports \`${e.to}\``;case"dir":return`\`${e.from}\` and \`${e.to}\` share a directory`}}function Pf(e,t,n=8){let r=new Set(e),s={symbol:0,pair:1,import:2,dir:3};return t.filter((o)=>o.kind!=="dir"&&r.has(o.from)!==r.has(o.to)).sort((o,a)=>s[o.kind]-s[a.kind]||a.weight-o.weight).slice(0,n).map(er)}function Mf(e,t,n,r){let s=e.map((c)=>({id:c.id,files:[...c.files],tokens:c.tokens})),o=new Map(s.map((c)=>[c.id,c])),a=new Map;for(let c of t?.groups??[]){if(typeof c?.id!=="string"||!o.has(c.id))continue;a.set(c.id,{title:typeof c.title==="string"&&c.title.trim()?c.title.trim():void 0,rationale:typeof c.rationale==="string"&&c.rationale.trim()?c.rationale.trim():void 0,priority:typeof c.priority==="number"&&Number.isFinite(c.priority)?c.priority:void 0})}let l=[];for(let c of t?.moves??[]){if(typeof c?.file!=="string"||typeof c.to!=="string")continue;let u=s.find((p)=>p.files.includes(c.file)),d=o.get(c.to);if(!u||!d||u===d||u.files.length===1)continue;let f=r.get(c.file)??0;if(d.tokens+f>n)continue;u.files=u.files.filter((p)=>p!==c.file),u.tokens-=f,d.files=[...d.files,c.file].sort(),d.tokens+=f,l.push({file:c.file,from:u.id,to:d.id,reason:typeof c.reason==="string"?c.reason:""})}return{moves:l,units:s.map((c)=>{let u=a.get(c.id);return{id:c.id,title:u?.title??c.id,...u?.rationale?{rationale:u.rationale}:{},files:c.files,...u?.priority!==void 0?{priority:u.priority}:{}}})}}async function so(e){let t=`${e.base}..${e.head}`,n=zn(await Rt(["diff",t,"--",...e.files]),e.base),r=await Rt(["diff","--stat",t]),s=new Map([...Md(n)].map(([u,d])=>[u,Math.ceil(d/Dd)])),o=await Rt(["diff","--unified=0",t,"--",...e.files]),a=await Sf({source:await e.source(e.files),diffU0:o,files:e.files,fileTokens:s}),l=Cf(a,Ri),c=Of(a,l,{budget:Cn,maxGroups:wr});return{wholeDiff:n,diffstat:r,diffU0:o,fileTokens:s,facts:a,links:l,grouping:c}}var Ix=new Set(["if","for","while","switch","return","catch","function","new","await","typeof","sizeof"]);function Ox(e){for(let n of e.matchAll(/([A-Za-z_$~][\w$]*(?:::~?[A-Za-z_$][\w$]*)*)\s*(?:[(<]|=\s*(?:async\s*)?\()/g))if(!Ix.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 oo(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 Zt(e)){if(!s||o.startsWith("+++ "))continue;let a=r(s),l=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@ ?(.*)$/.exec(o);if(l){let c=Ox(l[2]);if(c&&!a.touches.some((u)=>u.name===c))a.touches.push({name:c,line:Number(l[1])})}else if(o.startsWith("+"))a.added++;else if(o.startsWith("-"))a.removed++}for(let s of t){let o=r(s.file);o.defines=s.defined,o.touches=o.touches.filter((a)=>!s.defined.includes(a.name))}return n}function ao(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 lo(e,t,n,r=Math.floor(n/4)){let s=e.flatMap((d)=>d.files),o=(d)=>t.get(d)??0;if(s.reduce((d,f)=>d+o(f),0)<=n)return{shown:s,sketched:[]};let l=new Set,c=0,u=Math.floor(n/Math.max(1,e.length));for(let d of e){let f=0;for(let p of[...d.files].sort((h,x)=>o(x)-o(h))){let h=o(p);if(h>r||f+h>u||c+h>n)continue;l.add(p),f+=h,c+=h}}for(let d of s.filter((f)=>!l.has(f)).sort((f,p)=>o(f)-o(p))){let f=o(d);if(f>r||c+f>n)continue;l.add(d),c+=f}return{shown:s.filter((d)=>l.has(d)),sketched:s.filter((d)=>!l.has(d))}}function co(e,t,n=3){let r=new Set(e);return t.filter((s)=>s.kind!=="dir"&&r.has(s.from)&&r.has(s.to)).slice(0,n).map(er)}function uo(e,t,n=20){let r=new Map;for(let o of e)for(let a of o.files)r.set(a,o.id);let s=[];for(let o of t){if(o.kind==="dir")continue;let a=r.get(o.from),l=r.get(o.to);if(!a||!l||a===l)continue;if(s.push(`${er(o)} (${a} \u2192 ${l})`),s.length>=n)break}return s}import{randomBytes as Px}from"crypto";import{existsSync as Mx,realpathSync as Tx}from"fs";import Nx from"os";import Ff from"path";function Tf(e){try{return Tx(e)}catch{return Ff.resolve(e)}}function Nf(e,t){return Tf(e)===Tf(t)}async function Dx(e,t){await te("git",["-C",e,"worktree","remove","--force",t],{allowFail:!0}),await te("git",["-C",e,"worktree","prune"],{allowFail:!0})}async function Df(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 Lf(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=Ff.join(Nx.tmpdir(),`code-review-subject-${n.slice(0,12)}-${process.pid}-${Px(3).toString("hex")}`);return await Df(e,t,n),await le("git",["-C",e,"worktree","add","--detach","-q",u,n]),{dir:u,release:()=>Dx(e,u)}}let s=r,o=async()=>{},a=await te("git",["-C",s,"rev-parse","--show-toplevel"],{allowFail:!0}),c=a.code===0&&Nf(a.stdout.trim(),s)?await te("git",["-C",s,"rev-parse","HEAD"],{allowFail:!0}):{code:1,stdout:"",stderr:""};if(c.code===0&&c.stdout.trim().startsWith(n))return{dir:s,release:o};if(await Df(e,t,n),c.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,10)}. Commit, stash or discard them, or point it somewhere else.`);if(Nf(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,10)}. 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,10)}: ${d.stderr.trim()||"checkout failed"}`);return{dir:s,release:o}}if(Mx(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 jf from"path";function Uf(e){return e.pr?`pr-${e.pr}-${e.head.slice(0,7)}`:`range-${e.base.slice(0,7)}-${e.head.slice(0,7)}`}async function fo(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/${jf.basename(jf.resolve(e))}`;return`${r[1]}/${r[2]}`}$i();xt();Si();import Je from"path";import{spawn as Lx}from"child_process";import{readFileSync as jx}from"fs";import{chmod as Ux,mkdir as Bx,rm as qx}from"fs/promises";xt();class It extends Error{name="CancelledError";constructor(){super("review cancelled")}}var Ei=new Map,qf=!1;function Cl(e,t){if(e.pid===void 0)return;try{process.kill(-e.pid,t)}catch{}}function Hx(){for(let e of Ei.keys())Cl(e,"SIGKILL")}async function Ar(e=5000){let t=[...Ei];if(!t.length)return;for(let[r]of t)Cl(r,"SIGTERM");let n=setTimeout(()=>{for(let[r]of t)if(Ei.has(r))Cl(r,"SIGKILL")},e);await Promise.all(t.map(([,r])=>r)),clearTimeout(n)}function Kx(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(`
|
|
139
|
+
`)){let o=s.trim();if(!o.startsWith("{"))continue;let a;try{a=JSON.parse(o)}catch{continue}let l=a.part;if(!(l?.type==="step-finish"||l?.type==="step_finish"||a.type==="step_finish")||!l)continue;n+=1,t+=l.cost??0,r.input_tokens+=l.tokens?.input??0,r.output_tokens+=l.tokens?.output??0,r.reasoning_tokens+=l.tokens?.reasoning??0,r.cache_read_input_tokens+=l.tokens?.cache?.read??0,r.cache_creation_input_tokens+=l.tokens?.cache?.write??0}return{costUsd:t,numTurns:n,usage:r}}var Wx=new Set(["read","tilth_tilth_read"]),Vx=new Set(["grep","glob","tilth_tilth_search","tilth_tilth_files"]),Gx=60;function zx(e,t=""){let n={},r=0,s=new Set,o=new Set,a=t?`${t.replace(/\/$/,"")}/`:"",l=(u)=>a&&u.startsWith(a)?u.slice(a.length):u,c=(u,d)=>{if(u.size<Gx)u.add(d)};for(let u of e.split(`
|
|
140
|
+
`)){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(Wx.has(p.tool)){let x=Array.isArray(h.paths)?h.paths:[h.path??h.filePath],R=typeof h.section==="string"?`:${h.section}`:"";for(let w of x)if(typeof w==="string")c(s,l(w)+R)}else if(Vx.has(p.tool)){let x=h.query??h.pattern;if(typeof x==="string")c(o,x)}}return{calls:n,failed:r,read:[...s],searched:[...o]}}var Hf=new Map;function Jx(e,t,n="repo"){let r=`${e}\x00${t}`,s=Hf.get(n);if(s&&s.key!==r)throw Error("openCodeConfig called with a different prompt after the config was written");let o=JSON.stringify(yi);if(s&&s.providers===o)return s.home;let a=(async()=>{let l=Je.join(Et,"oc",n==="repo"?"shared":"no-tools"),c=Je.join(l,"config");return await Gn(Je.join(c,"opencode.json"),Yx(e,t,n)),await Ve(Je.join(c,"plugin","governor.ts"),await Yt(Je.join(Vs,"opencode","governor.ts"))),l})();return Hf.set(n,{home:a,key:r,providers:o}),a}function Xx(e){return e.includes("/")?e:`${Qa}/${e}`}function Yx(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(yi).length?{providers:yi}:{},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:el,system:t?`${e}
|
|
141
|
+
|
|
142
|
+
${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 Zx(e,t){let n=t.tools??"repo",r=n==="repo"?await Yt(Je.join(Vs,"opencode","tools.md")):"",s=await Jx(e,r,n),o=Je.join(s,"config"),a=Je.join(Re,"logs",`${t.tag}.usage.json`);await un(Je.dirname(a)),await Lt(a);let l=t.effort,c=Xx(t.model);return{command:"opencode",args:["run","--standalone","--format","json","--agent","reviewer","--model",l&&!c.includes("#")?`${c}#${l}`:c,"--title",t.tag],cwd:Ye,env:{PWD:Ye,XDG_CONFIG_HOME:Je.join(s,"xdg"),XDG_DATA_HOME:Je.join(s,"data",t.tag),XDG_STATE_HOME:Je.join(s,"state",t.tag),XDG_CACHE_HOME:Je.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(tl),REVIEW_GOVERNOR_OUT_FILE:t.outFile,REVIEW_GOVERNOR_LOG:Je.join(Re,"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)=>Qx(a)??Kx(d),tools:(d)=>zx(d,Ye)}}function Qx(e){try{return JSON.parse(jx(e,"utf8"))}catch{return}}async function tr(e,t){if(br?.aborted)throw new It;let n=(await Yt(Je.join(Vs,"system.md"))).replaceAll("{{repo}}",vt),r=t.model??fn,s=t.effort??yr,o=await Zx(n,{...t,model:r,effort:s}),a={...process.env,...ol,...o.env};for(let c of o.unsetEnv)delete a[c];let l=[o.env.XDG_DATA_HOME,o.env.XDG_STATE_HOME].filter((c)=>c!==void 0);try{return await tk(e,t,o,a)}finally{if(process.env.DIFFLOUPE_KEEP_SCRATCH!=="1")await Promise.all(l.map((c)=>qx(c,{recursive:!0,force:!0}).catch(()=>{})))}}async function ek(e,t){if(!zs||!t)return;await Bx(t,{recursive:!0,mode:448}),await Ux(t,448);let n=await te("opencode",["auth","import","--standalone"],{env:e,cwd:Ye,input:zs,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 tk(e,t,n,r){if(br?.aborted)throw new It;if(await ek(r,n.env.XDG_DATA_HOME),br?.aborted)throw new It;if(!qf)qf=!0,process.on("exit",Hx);let s=Date.now(),{stdout:o,stderr:a,exitCode:l}=await new Promise((p,h)=>{let x=Lx(n.command,n.args,{cwd:n.cwd,env:r,stdio:["pipe","pipe","pipe"],detached:!0}),R=()=>{};Ei.set(x,new Promise((P)=>R=P));let w=()=>{Ei.delete(x),R()};x.stdin.on("error",h),x.stdin.end(e);let v=[],y=[];x.stdout.on("data",(P)=>v.push(P)),x.stderr.on("data",(P)=>y.push(P)),x.on("error",(P)=>{w(),h(P)}),x.on("close",(P,D)=>{w(),p({stdout:Buffer.concat(v).toString("utf8"),stderr:Buffer.concat(y).toString("utf8"),exitCode:P??(D?128:0)})})}),c=Date.now()-s;await Ve(Je.join(Re,"logs",`${t.tag}.stderr.log`),a),await Ve(Je.join(Re,"raw",`${t.tag}.${n.rawExt}`),o);let u=n.parse(o),d=n.tools?.(o),f=null;try{f=await Ks(t.outFile)}catch{}return{wallMs:c,exitCode:l,...u,tools:d,payload:f}}xt();Ir();function tp(e){return new Map(e.filter((t)=>t.mine&&t.fingerprint&&!t.addressed).map((t)=>[t.fingerprint,t]))}var rk=4,ep=300;function np(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,rk).map((n)=>n.length>ep?`${n.slice(0,ep-1)}\u2026`:n)}function rp(e,t){return Math.min(9,Math.max(t,0.22*e))}function ip(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)=>(ut[n.severity]?.rank??9)-(ut[r.severity]?.rank??9)||Ot[Ze(n.file)]-Ot[Ze(r.file)])}function sp(e,t){return e.length>0||t.some((n)=>n.mine&&n.file&&!n.addressed)}var nn=10,ik=/^\s*(cut for the )?cap\b/i;function op(e,t,n){let r=[],s=[],o=[],a=new Set,l=new Map(n.map((c)=>[c.id,c]));for(let c of e.keep??[]){let u=t[c.id];if(!u)continue;if(a.has(c.id))continue;a.add(c.id);let d=new Set(u.cross_file_refs??[]);for(let h of c.merge_with??[]){let x=t[h];if(!x||a.has(h))continue;a.add(h),d.add(`${x.file}:${x.line}`);for(let R of x.cross_file_refs??[])d.add(R)}let f=c.repeat_of?l.get(c.repeat_of):void 0,p=f&&!f.mine&&f.file?c.repeat_of:void 0;if(c.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 ${c.repeat_of} on "${u.title}" ignored: ${h}`)}r.push({...u,severity:c.severity??u.severity,explanation:c.note?`${u.explanation}
|
|
143
|
+
|
|
144
|
+
${c.note}`:u.explanation,cross_file_refs:d.size?[...d]:void 0,repeat_of:p})}for(let c of e.drop??[]){let u=t[c.id];if(u&&!a.has(c.id))if(a.add(c.id),ik.test(c.reason??""))o.push({...u,repeat_of:void 0});else s.push({title:u.title,reason:c.reason})}return t.forEach((c,u)=>{if(!a.has(u))s.push({title:c.title,reason:"coordinator did not rule on this finding"})}),{kept:r,dropped:s,capped:o}}var sk=`
|
|
145
|
+
Calibrated uncertainty \u2014 this matters as much as finding bugs:
|
|
146
|
+
- 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.
|
|
147
|
+
- 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.
|
|
148
|
+
- 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.
|
|
149
|
+
`.trim(),ok=`
|
|
150
|
+
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).
|
|
151
|
+
|
|
152
|
+
Scope and priorities:
|
|
153
|
+
- Correctness first, and production impact above all. A bug that reaches users or corrupts data outranks everything else.
|
|
154
|
+
- Weigh where the code runs. Shipped product code matters most. Deployment and infrastructure config can take production down. Developer tooling, build scripts and test harnesses cost one engineer time, not users \u2014 hold them to a higher bar: report them when they are broken, not when they are untidy.
|
|
155
|
+
- Architecture second. Say so if the change is in the wrong place or duplicates something that already exists.
|
|
156
|
+
- Nothing else. Do not comment on formatting, naming, import order, code style, or test coverage. Linters, formatters and the typechecker already cover all of it, and anything the typechecker catches is not your job.
|
|
157
|
+
|
|
158
|
+
Reducing noise:
|
|
159
|
+
- Do not report an issue you cannot point at. If you cannot cite a specific file and line, do not make the claim.
|
|
160
|
+
- Before asserting a bug, go read the code that would disprove it: the guard clause elsewhere, the existing helper, the sibling registration, the caller that already handles the case.
|
|
161
|
+
- Do not restate what the diff does. Do not praise. Do not suggest adding comments.
|
|
162
|
+
- Report nothing rather than padding with weak findings.
|
|
163
|
+
`.trim();function Il(e,t){let n=e.body?.slice(0,t);if(n)return n;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 ap(e){let t=e.unit.files.map((r)=>`\`${r}\``).join(", "),n=e.crossLinks?.length?`
|
|
164
|
+
|
|
165
|
+
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:
|
|
166
|
+
${e.crossLinks.map((r)=>`- ${r}`).join(`
|
|
167
|
+
`)}`:"";return`You are reviewing one coherent part of a pull request in the ${vt} repository.
|
|
168
|
+
|
|
169
|
+
${ok}
|
|
170
|
+
|
|
171
|
+
${sk}
|
|
172
|
+
|
|
173
|
+
This is ONE SLICE of a larger pull request: **${e.unit.title}**. ${e.unit.rationale??""}
|
|
174
|
+
|
|
175
|
+
Review the changes in these files, which were grouped together because they implement one thing: ${t}. Because they belong to one flow, look hard at how they fit together \u2014 a value written in one file and read in another, a name or key that must match across files, an ordering assumption between them. Cross-file inconsistency inside this group is exactly what you are best placed to catch, and no other reviewer is looking at this combination.
|
|
176
|
+
|
|
177
|
+
Other changed files in this pull request are being reviewed separately; do not comment on them. Because you see only part of the change, it is your job to establish the surrounding context yourself by reading the repository.${n}
|
|
178
|
+
|
|
179
|
+
## Pull request intent (as stated by the author)
|
|
180
|
+
Title: ${e.intent.title}
|
|
181
|
+
|
|
182
|
+
${Il(e.intent,4000)}
|
|
183
|
+
|
|
184
|
+
Commit messages:
|
|
185
|
+
${e.intent.commits.slice(0,3000)||"(none)"}
|
|
186
|
+
|
|
187
|
+
${e.mapNote}${e.registry?`
|
|
188
|
+
${e.registry}
|
|
189
|
+
`:""}${e.prior?`
|
|
190
|
+
${e.prior}
|
|
191
|
+
`:""}
|
|
192
|
+
## Diff for this slice
|
|
193
|
+
\`\`\`diff
|
|
194
|
+
${e.diff}
|
|
195
|
+
\`\`\`
|
|
196
|
+
|
|
197
|
+
Write your findings as JSON to \`${e.outFile}\`. Write the file even if you have no findings (use an empty array).`}function lp(e){return`You are the coordinator for a code review of a pull request in ${vt}. Independent reviewers each looked at one changed file. Your job is to turn their raw findings into the review that actually gets posted.
|
|
198
|
+
|
|
199
|
+
## Changed files
|
|
200
|
+
${e.files.map((t)=>`- ${t}`).join(`
|
|
201
|
+
`)}
|
|
202
|
+
|
|
203
|
+
## Pull request intent (as stated by the author)
|
|
204
|
+
Title: ${e.intent.title}
|
|
205
|
+
|
|
206
|
+
${Il(e.intent,4000)}
|
|
207
|
+
|
|
208
|
+
Commit messages:
|
|
209
|
+
${e.intent.commits.slice(0,3000)||"(none)"}
|
|
210
|
+
${e.prior?`
|
|
211
|
+
${e.prior}
|
|
212
|
+
`:""}
|
|
213
|
+
## Raw findings from the per-file reviewers
|
|
214
|
+
Each carries an \`id\`. You will refer to them by that id; you never retype their text.
|
|
215
|
+
The \`id\` is assigned here and overwrites anything a reviewer wrote, so it is always the
|
|
216
|
+
position in this list.
|
|
217
|
+
\`\`\`json
|
|
218
|
+
${JSON.stringify(e.findings.map((t,n)=>({...t,id:n})),null,2)}
|
|
219
|
+
\`\`\`
|
|
220
|
+
|
|
221
|
+
Do all of the following:
|
|
222
|
+
|
|
223
|
+
1. **Verify before keeping.** For each finding, open the cited file and line and confirm the code says what the finding claims. Drop any finding whose cited symbol, function, or line does not exist, or whose claim the surrounding code contradicts. This is the single most important thing you do \u2014 a confident wrong comment costs more than a missed bug.
|
|
224
|
+
|
|
225
|
+
2. **Deduplicate.** Several reviewers may report the same underlying problem from different files. Keep the one located at the best place to fix it and name the others in its \`merge_with\`; their locations get folded into its cross-file references automatically.
|
|
226
|
+
|
|
227
|
+
3. **Drop noise.** Remove anything about formatting, naming, style, import order, or test coverage. Remove anything a typechecker or linter would catch. Remove anything about comments themselves \u2014 a stale, empty, or missing comment is never a finding. Remove findings that only restate what the diff does. Remove speculative findings that require an unlikely precondition to matter.
|
|
228
|
+
|
|
229
|
+
4. **Reconcile with what has already been said.** If a finding makes the same claim as a comment in the "comments already on this pull request" section, keep it and set \`repeat_of\` to that comment's id \u2014 do not drop it. Corroborating a human reviewer has value on its own, and these are shown separately from the new findings, so they cost the reader nothing. Drop it only if the current code shows the comment has already been addressed.
|
|
230
|
+
|
|
231
|
+
The test for \`repeat_of\` is whether the two are the same claim, not whether they are about the same code. Same file, same function, same line, even the same variable is not enough. Ask what each one says is wrong: if fixing what the comment asks for would leave the finding's problem still there, they are different claims and the finding is new. A comment asking to rename a parameter and a finding that the same function drops an error are unrelated. Getting this wrong costs a real bug \u2014 a finding filed as \`repeat_of\` is not posted where it belongs, it is demoted into someone else's thread as agreement. When you are unsure, leave \`repeat_of\` off and let it stand on its own.
|
|
232
|
+
|
|
233
|
+
\`repeat_of\` points only at a human's comment. Never point it at one of your own comments from the "what you already told this author" section; you cannot corroborate yourself. Anything you already said is either dropped or reported fresh as a new development, per the instructions in that section.
|
|
234
|
+
|
|
235
|
+
5. **Close out what you fixed.** For each comment in the "what you already told this author" section, open the code it points at. If the current code no longer has the problem, put its id in \`resolved\` with one sentence naming what changed. Say nothing about it anywhere else. A point that quietly disappears reads as you losing track of it; saying it is fixed ends the thread and stops any later review from raising it again. Only put a comment in \`resolved\` when you have read the code and it is genuinely fixed \u2014 never to clear out a point you merely no longer believe.
|
|
236
|
+
|
|
237
|
+
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.
|
|
238
|
+
|
|
239
|
+
7. **Cap.** Keep at most ${nn} new findings. Anything carrying \`repeat_of\` is shown in a separate section and does not count against that 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.
|
|
240
|
+
|
|
241
|
+
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.
|
|
242
|
+
|
|
243
|
+
Write a single JSON object to \`${e.outFile}\`:
|
|
244
|
+
\`\`\`json
|
|
245
|
+
{
|
|
246
|
+
"keep": [ { "id": 0, "severity": "blocker|should-fix|question|nice-to-have",
|
|
247
|
+
"merge_with": [3, 7], "repeat_of": 123456, "note": "" } ],
|
|
248
|
+
"drop": [ { "id": 1, "reason": "why it did not survive verification" } ],
|
|
249
|
+
"resolved": [ { "id": 987654, "note": "the null check was added in this push" } ],
|
|
250
|
+
"intent_alignment": {
|
|
251
|
+
"summary": "one sentence, or empty string if the diff matches the description",
|
|
252
|
+
"unstated": ["behavior present in the diff that the description does not mention"],
|
|
253
|
+
"missing": ["stated goals the diff does not accomplish"]
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
\`\`\`
|
|
257
|
+
\`severity\`, \`merge_with\`, \`repeat_of\` 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 Ol(e,t){let n=new Set,r=[];for(let o of e){let a=(o.files??[]).filter((l)=>t.includes(l)&&!n.has(l));for(let l of a)n.add(l);if(a.length)r.push({...o,files:a})}let s=t.filter((o)=>!n.has(o));if(s.length)r.push({id:"unassigned",title:"Remaining changes",rationale:"These files were not grouped with any flow; review them on their own terms.",files:s,priority:9});return r}function cp(e,t,n){let r=[];for(let s of e){let o=[...s.files].sort((l,c)=>(t.get(c)??0)-(t.get(l)??0)||l.localeCompare(c)),a=[];for(let l of o){let c=t.get(l)??0,u=a.find((d)=>d.tokens+c<=n);if(u)u.files.push(l),u.tokens+=c;else a.push({files:[l],tokens:c})}a.forEach((l,c)=>{r.push({unitId:s.id,title:a.length>1?`${s.title} (part ${c+1} of ${a.length})`:s.title,rationale:s.rationale,priority:s.priority,files:[...l.files].sort(),part:c+1,parts:a.length,tokens:l.tokens})})}return r}function up(e){return`You are planning how to split up the review of a pull request in ${vt}. You are not reviewing anything and you are not looking for bugs. You are deciding which changed files each reviewer should see together.
|
|
258
|
+
|
|
259
|
+
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.
|
|
260
|
+
|
|
261
|
+
## Stated intent
|
|
262
|
+
Title: ${e.intent.title}
|
|
263
|
+
|
|
264
|
+
${e.intent.body?.slice(0,2000)||"(no description)"}
|
|
265
|
+
|
|
266
|
+
## Files changed
|
|
267
|
+
${e.diffstat}
|
|
268
|
+
|
|
269
|
+
## Files to partition \u2014 each must appear in exactly one unit
|
|
270
|
+
${e.codeFiles.map((t)=>`- ${t}`).join(`
|
|
271
|
+
`)}
|
|
272
|
+
${e.registry?`
|
|
273
|
+
${e.registry}
|
|
274
|
+
`:""}
|
|
275
|
+
## Where the change lands
|
|
276
|
+
Each line is one hunk: the file it sits in, and the function or class enclosing it.
|
|
277
|
+
\`\`\`diff
|
|
278
|
+
${e.outline}
|
|
279
|
+
\`\`\`
|
|
280
|
+
|
|
281
|
+
Partition the listed files into 1-6 review units. A unit is a *flow*, not a directory and not a file: the files that participate in one mechanism, so that a reviewer holding all of them at once can see a value written in one file and read in another, a key or name that must match across files, or an ordering assumption between them. Files that have to agree with each other belong in the same unit \u2014 that is the entire point of grouping. Split units when the mechanisms are genuinely independent, because a reviewer given unrelated files divides attention badly. A single-file unit is correct when that file stands alone.
|
|
282
|
+
|
|
283
|
+
Put the unit where the risk concentrates at \`priority\` 1.
|
|
284
|
+
|
|
285
|
+
Two things constrain the size. The units are reviewed **at the same time, in parallel**, so one oversized unit becomes the bottleneck for the whole review while the other reviewers sit idle \u2014 keep them roughly comparable in diff size. And a reviewer given more than about five files reads each of them less carefully. When a large group shares one mechanism but splits cleanly into layers that are checked differently \u2014 the cloud resources that define an identity, the chart that consumes it, the pipeline that deploys it \u2014 make them separate units and say in each \`rationale\` which names it must agree with, so each reviewer knows what to go look up.
|
|
286
|
+
|
|
287
|
+
Write only this JSON to \`${e.outFile}\`:
|
|
288
|
+
\`\`\`json
|
|
289
|
+
{ "review_units": [ { "id": "short-slug", "title": "a few words naming the mechanism, not the paths",
|
|
290
|
+
"rationale": "one sentence the reviewer will read as their brief: what this group does and what would break",
|
|
291
|
+
"files": ["..."], "priority": 1 } ] }
|
|
292
|
+
\`\`\``}function dp(e){let t=new Map(e.groups.flatMap((s)=>s.files.map((o)=>[o,s.id]))),n=e.groups.map((s)=>{let o=s.links.filter((a)=>a.kind!=="dir").slice(0,6).map((a)=>` - ${er(a)}`);return[`### ${s.id} (${s.tokens} diff tokens)`,...s.files.map((a)=>`- ${a}`),...o.length?["Linked by:",...o]:[]].join(`
|
|
293
|
+
`)}),r=e.links.filter((s)=>s.kind!=="dir"&&t.get(s.from)!==t.get(s.to)).slice(0,20).map((s)=>`- ${er(s)} (${t.get(s.from)} \u2192 ${t.get(s.to)})`);return`You are preparing the review of a pull request in ${vt}. 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.
|
|
294
|
+
|
|
295
|
+
Work from what is below. **Do not read files from the repository.**
|
|
296
|
+
|
|
297
|
+
## Stated intent
|
|
298
|
+
Title: ${e.intent.title}
|
|
299
|
+
|
|
300
|
+
${e.intent.body?.slice(0,2000)||"(no description)"}
|
|
301
|
+
${e.registry?`
|
|
302
|
+
${e.registry}
|
|
303
|
+
`:""}
|
|
304
|
+
## Groups
|
|
305
|
+
${n.join(`
|
|
306
|
+
|
|
307
|
+
`)}
|
|
308
|
+
|
|
309
|
+
## Links between groups
|
|
310
|
+
${r.length?r.join(`
|
|
311
|
+
`):"(none)"}
|
|
312
|
+
|
|
313
|
+
## Where the change lands
|
|
314
|
+
Each line is one hunk: the file it sits in, and the function or class enclosing it.
|
|
315
|
+
\`\`\`diff
|
|
316
|
+
${e.outline}
|
|
317
|
+
\`\`\`
|
|
318
|
+
|
|
319
|
+
For every group, write:
|
|
320
|
+
- \`title\`: a few words naming the mechanism, not the paths.
|
|
321
|
+
- \`rationale\`: one sentence the reviewer reads as their brief \u2014 what this group does and what would break. When a link to another group matters, name it.
|
|
322
|
+
- \`priority\`: 1 for the group where the risk concentrates, larger numbers for less.
|
|
323
|
+
|
|
324
|
+
You may also move a file to another group, but only when it plainly belongs with that group's mechanism and the links above missed it \u2014 for example, a config entry read only by code in another group. Leave the grouping alone otherwise. Moves that would make a group too large are ignored.
|
|
325
|
+
|
|
326
|
+
Write only this JSON to \`${e.outFile}\`:
|
|
327
|
+
\`\`\`json
|
|
328
|
+
{ "groups": [ { "id": "group id from above", "title": "...", "rationale": "...", "priority": 1 } ],
|
|
329
|
+
"moves": [ { "file": "path", "to": "group id", "reason": "one sentence" } ] }
|
|
330
|
+
\`\`\``}function ak(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(`
|
|
331
|
+
`)}function mo(e){let t=e.findingIndex!==void 0;return`${t?`You are writing the reviewer's guide for a pull request in ${vt}: 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 ${vt}: 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.`}
|
|
332
|
+
|
|
333
|
+
## Stated description (what the author says it does)
|
|
334
|
+
Title: ${e.intent.title}
|
|
335
|
+
|
|
336
|
+
${Il(e.intent,4000)}
|
|
337
|
+
|
|
338
|
+
Commit messages:
|
|
339
|
+
${e.intent.commits.slice(0,3000)||"(none)"}
|
|
340
|
+
|
|
341
|
+
## Files changed
|
|
342
|
+
${e.diffstat}
|
|
343
|
+
|
|
344
|
+
## ${t?"How the review was split up":"How the files are grouped"}
|
|
345
|
+
Files were grouped by how the code links them: a name used in one file and added in another, an import, a test beside its source. A group's links are the order its files are read in.
|
|
346
|
+
|
|
347
|
+
${e.unitSummary}
|
|
348
|
+
${e.crossLinks.length?`
|
|
349
|
+
### Links between groups
|
|
350
|
+
These cross from one group to another. A stop that follows one of them can name locations in both groups.
|
|
351
|
+
${e.crossLinks.map((r)=>`- ${r}`).join(`
|
|
53
352
|
`)}
|
|
54
|
-
|
|
55
|
-
${H}`)}return J},Y1=vB(r$);class i2 extends X1{list(Z={},Y){let{betas:X,...Q}=Z??{};return this._client.getAPIList("/v1/files",q0,{query:Q,...Y,headers:y([{"anthropic-beta":[...X??[],"files-api-2025-04-14"].toString()},Y?.headers])})}delete(Z,Y={},X){let{betas:Q}=Y??{};return this._client.delete(Y1`/v1/files/${Z}`,{...X,headers:y([{"anthropic-beta":[...Q??[],"files-api-2025-04-14"].toString()},X?.headers])})}download(Z,Y={},X){let{betas:Q}=Y??{};return this._client.get(Y1`/v1/files/${Z}/content`,{...X,headers:y([{"anthropic-beta":[...Q??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},X?.headers]),__binaryResponse:!0})}retrieveMetadata(Z,Y={},X){let{betas:Q}=Y??{};return this._client.get(Y1`/v1/files/${Z}`,{...X,headers:y([{"anthropic-beta":[...Q??[],"files-api-2025-04-14"].toString()},X?.headers])})}upload(Z,Y){let{betas:X,...Q}=Z;return this._client.post("/v1/files",h9({body:Q,...Y,headers:y([{"anthropic-beta":[...X??[],"files-api-2025-04-14"].toString()},Y?.headers])},this._client))}}class o2 extends X1{retrieve(Z,Y={},X){let{betas:Q}=Y??{};return this._client.get(Y1`/v1/models/${Z}?beta=true`,{...X,headers:y([{...Q?.toString()!=null?{"anthropic-beta":Q?.toString()}:void 0},X?.headers])})}list(Z={},Y){let{betas:X,...Q}=Z??{};return this._client.getAPIList("/v1/models?beta=true",q0,{query:Q,...Y,headers:y([{...X?.toString()!=null?{"anthropic-beta":X?.toString()}:void 0},Y?.headers])})}}var f4={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function UY(Z,Y,X){if(!Y||!("parse"in(Y.output_format??{})))return{...Z,content:Z.content.map((Q)=>{if(Q.type==="text"){let $=Object.defineProperty({...Q},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty($,"parsed",{get(){return X.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return Q}),parsed_output:null};return HY(Z,Y,X)}function HY(Z,Y,X){let Q=null,$=Z.content.map((W)=>{if(W.type==="text"){let J=gB(Y,W.text);if(Q===null)Q=J;let z=Object.defineProperty({...W},"parsed_output",{value:J,enumerable:!1});return Object.defineProperty(z,"parsed",{get(){return X.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),J},enumerable:!1})}return W});return{...Z,content:$,parsed_output:Q}}function gB(Z,Y){if(Z.output_format?.type!=="json_schema")return null;try{if("parse"in Z.output_format)return Z.output_format.parse(Y);return JSON.parse(Y)}catch(X){throw new R(`Failed to parse structured output: ${X}`)}}var uB=(Z)=>{let Y=0,X=[];while(Y<Z.length){let Q=Z[Y];if(Q==="\\"){Y++;continue}if(Q==="{"){X.push({type:"brace",value:"{"}),Y++;continue}if(Q==="}"){X.push({type:"brace",value:"}"}),Y++;continue}if(Q==="["){X.push({type:"paren",value:"["}),Y++;continue}if(Q==="]"){X.push({type:"paren",value:"]"}),Y++;continue}if(Q===":"){X.push({type:"separator",value:":"}),Y++;continue}if(Q===","){X.push({type:"delimiter",value:","}),Y++;continue}if(Q==='"'){let z="",V=!1;Q=Z[++Y];while(Q!=='"'){if(Y===Z.length){V=!0;break}if(Q==="\\"){if(Y++,Y===Z.length){V=!0;break}z+=Q+Z[Y],Q=Z[++Y]}else z+=Q,Q=Z[++Y]}if(Q=Z[++Y],!V)X.push({type:"string",value:z});continue}if(Q&&/\s/.test(Q)){Y++;continue}let W=/[0-9]/;if(Q&&W.test(Q)||Q==="-"||Q==="."){let z="";if(Q==="-")z+=Q,Q=Z[++Y];while(Q&&W.test(Q)||Q===".")z+=Q,Q=Z[++Y];X.push({type:"number",value:z});continue}let J=/[a-z]/i;if(Q&&J.test(Q)){let z="";while(Q&&J.test(Q)){if(Y===Z.length)break;z+=Q,Q=Z[++Y]}if(z=="true"||z=="false"||z==="null")X.push({type:"name",value:z});else{Y++;continue}continue}Y++}return X},g9=(Z)=>{if(Z.length===0)return Z;let Y=Z[Z.length-1];switch(Y.type){case"separator":return Z=Z.slice(0,Z.length-1),g9(Z);break;case"number":let X=Y.value[Y.value.length-1];if(X==="."||X==="-")return Z=Z.slice(0,Z.length-1),g9(Z);case"string":let Q=Z[Z.length-2];if(Q?.type==="delimiter")return Z=Z.slice(0,Z.length-1),g9(Z);else if(Q?.type==="brace"&&Q.value==="{")return Z=Z.slice(0,Z.length-1),g9(Z);break;case"delimiter":return Z=Z.slice(0,Z.length-1),g9(Z);break}return Z},mB=(Z)=>{let Y=[];if(Z.map((X)=>{if(X.type==="brace")if(X.value==="{")Y.push("}");else Y.splice(Y.lastIndexOf("}"),1);if(X.type==="paren")if(X.value==="[")Y.push("]");else Y.splice(Y.lastIndexOf("]"),1)}),Y.length>0)Y.reverse().map((X)=>{if(X==="}")Z.push({type:"brace",value:"}"});else if(X==="]")Z.push({type:"paren",value:"]"})});return Z},pB=(Z)=>{let Y="";return Z.map((X)=>{switch(X.type){case"string":Y+='"'+X.value+'"';break;default:Y+=X.value;break}}),Y},h4=(Z)=>JSON.parse(pB(mB(g9(uB(Z)))));var Z0,l0,u9,n2,g4,a2,r2,u4,s2,S0,t2,m4,p4,B9,d4,c4,e2,GY,s$,l4,KY,BY,LY,t$,e$="__json_buf";function ZW(Z){return Z.type==="tool_use"||Z.type==="server_tool_use"||Z.type==="mcp_tool_use"}class Z6{constructor(Z,Y){Z0.add(this),this.messages=[],this.receivedMessages=[],l0.set(this,void 0),u9.set(this,null),this.controller=new AbortController,n2.set(this,void 0),g4.set(this,()=>{}),a2.set(this,()=>{}),r2.set(this,void 0),u4.set(this,()=>{}),s2.set(this,()=>{}),S0.set(this,{}),t2.set(this,!1),m4.set(this,!1),p4.set(this,!1),B9.set(this,!1),d4.set(this,void 0),c4.set(this,void 0),e2.set(this,void 0),l4.set(this,(X)=>{if(A(this,m4,!0,"f"),j0(X))X=new P1;if(X instanceof P1)return A(this,p4,!0,"f"),this._emit("abort",X);if(X instanceof R)return this._emit("error",X);if(X instanceof Error){let Q=new R(X.message);return Q.cause=X,this._emit("error",Q)}return this._emit("error",new R(String(X)))}),A(this,n2,new Promise((X,Q)=>{A(this,g4,X,"f"),A(this,a2,Q,"f")}),"f"),A(this,r2,new Promise((X,Q)=>{A(this,u4,X,"f"),A(this,s2,Q,"f")}),"f"),B(this,n2,"f").catch(()=>{}),B(this,r2,"f").catch(()=>{}),A(this,u9,Z,"f"),A(this,e2,Y?.logger??console,"f")}get response(){return B(this,d4,"f")}get request_id(){return B(this,c4,"f")}async withResponse(){A(this,B9,!0,"f");let Z=await B(this,n2,"f");if(!Z)throw new Error("Could not resolve a `Response` object");return{data:this,response:Z,request_id:Z.headers.get("request-id")}}static fromReadableStream(Z){let Y=new Z6(null);return Y._run(()=>Y._fromReadableStream(Z)),Y}static createMessage(Z,Y,X,{logger:Q}={}){let $=new Z6(Y,{logger:Q});for(let W of Y.messages)$._addMessageParam(W);return A($,u9,{...Y,stream:!0},"f"),$._run(()=>$._createMessage(Z,{...Y,stream:!0},{...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"stream"}})),$}_run(Z){Z().then(()=>{this._emitFinal(),this._emit("end")},B(this,l4,"f"))}_addMessageParam(Z){this.messages.push(Z)}_addMessage(Z,Y=!0){if(this.receivedMessages.push(Z),Y)this._emit("message",Z)}async _createMessage(Z,Y,X){let Q=X?.signal,$;if(Q){if(Q.aborted)this.controller.abort();$=this.controller.abort.bind(this.controller),Q.addEventListener("abort",$)}try{B(this,Z0,"m",KY).call(this);let{response:W,data:J}=await Z.create({...Y,stream:!0},{...X,signal:this.controller.signal}).withResponse();this._connected(W);for await(let z of J)B(this,Z0,"m",BY).call(this,z);if(J.controller.signal?.aborted)throw new P1;B(this,Z0,"m",LY).call(this)}finally{if(Q&&$)Q.removeEventListener("abort",$)}}_connected(Z){if(this.ended)return;A(this,d4,Z,"f"),A(this,c4,Z?.headers.get("request-id"),"f"),B(this,g4,"f").call(this,Z),this._emit("connect")}get ended(){return B(this,t2,"f")}get errored(){return B(this,m4,"f")}get aborted(){return B(this,p4,"f")}abort(){this.controller.abort()}on(Z,Y){return(B(this,S0,"f")[Z]||(B(this,S0,"f")[Z]=[])).push({listener:Y}),this}off(Z,Y){let X=B(this,S0,"f")[Z];if(!X)return this;let Q=X.findIndex(($)=>$.listener===Y);if(Q>=0)X.splice(Q,1);return this}once(Z,Y){return(B(this,S0,"f")[Z]||(B(this,S0,"f")[Z]=[])).push({listener:Y,once:!0}),this}emitted(Z){return new Promise((Y,X)=>{if(A(this,B9,!0,"f"),Z!=="error")this.once("error",X);this.once(Z,Y)})}async done(){A(this,B9,!0,"f"),await B(this,r2,"f")}get currentMessage(){return B(this,l0,"f")}async finalMessage(){return await this.done(),B(this,Z0,"m",GY).call(this)}async finalText(){return await this.done(),B(this,Z0,"m",s$).call(this)}_emit(Z,...Y){if(B(this,t2,"f"))return;if(Z==="end")A(this,t2,!0,"f"),B(this,u4,"f").call(this);let X=B(this,S0,"f")[Z];if(X)B(this,S0,"f")[Z]=X.filter((Q)=>!Q.once),X.forEach(({listener:Q})=>Q(...Y));if(Z==="abort"){let Q=Y[0];if(!B(this,B9,"f")&&!X?.length)Promise.reject(Q);B(this,a2,"f").call(this,Q),B(this,s2,"f").call(this,Q),this._emit("end");return}if(Z==="error"){let Q=Y[0];if(!B(this,B9,"f")&&!X?.length)Promise.reject(Q);B(this,a2,"f").call(this,Q),B(this,s2,"f").call(this,Q),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",B(this,Z0,"m",GY).call(this))}async _fromReadableStream(Z,Y){let X=Y?.signal,Q;if(X){if(X.aborted)this.controller.abort();Q=this.controller.abort.bind(this.controller),X.addEventListener("abort",Q)}try{B(this,Z0,"m",KY).call(this),this._connected(null);let $=n1.fromReadableStream(Z,this.controller);for await(let W of $)B(this,Z0,"m",BY).call(this,W);if($.controller.signal?.aborted)throw new P1;B(this,Z0,"m",LY).call(this)}finally{if(X&&Q)X.removeEventListener("abort",Q)}}[(l0=new WeakMap,u9=new WeakMap,n2=new WeakMap,g4=new WeakMap,a2=new WeakMap,r2=new WeakMap,u4=new WeakMap,s2=new WeakMap,S0=new WeakMap,t2=new WeakMap,m4=new WeakMap,p4=new WeakMap,B9=new WeakMap,d4=new WeakMap,c4=new WeakMap,e2=new WeakMap,l4=new WeakMap,Z0=new WeakSet,GY=function Z(){if(this.receivedMessages.length===0)throw new R("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},s$=function Z(){if(this.receivedMessages.length===0)throw new R("stream ended without producing a Message with role=assistant");let Y=this.receivedMessages.at(-1).content.filter((X)=>X.type==="text").map((X)=>X.text);if(Y.length===0)throw new R("stream ended without producing a content block with type=text");return Y.join(" ")},KY=function Z(){if(this.ended)return;A(this,l0,void 0,"f")},BY=function Z(Y){if(this.ended)return;let X=B(this,Z0,"m",t$).call(this,Y);switch(this._emit("streamEvent",Y,X),Y.type){case"content_block_delta":{let Q=X.content.at(-1);switch(Y.delta.type){case"text_delta":{if(Q.type==="text")this._emit("text",Y.delta.text,Q.text||"");break}case"citations_delta":{if(Q.type==="text")this._emit("citation",Y.delta.citation,Q.citations??[]);break}case"input_json_delta":{if(ZW(Q)&&Q.input)this._emit("inputJson",Y.delta.partial_json,Q.input);break}case"thinking_delta":{if(Q.type==="thinking")this._emit("thinking",Y.delta.thinking,Q.thinking);break}case"signature_delta":{if(Q.type==="thinking")this._emit("signature",Q.signature);break}default:YW(Y.delta)}break}case"message_stop":{this._addMessageParam(X),this._addMessage(UY(X,B(this,u9,"f"),{logger:B(this,e2,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",X.content.at(-1));break}case"message_start":{A(this,l0,X,"f");break}case"content_block_start":case"message_delta":break}},LY=function Z(){if(this.ended)throw new R("stream has ended, this shouldn't happen");let Y=B(this,l0,"f");if(!Y)throw new R("request ended without sending any chunks");return A(this,l0,void 0,"f"),UY(Y,B(this,u9,"f"),{logger:B(this,e2,"f")})},t$=function Z(Y){let X=B(this,l0,"f");if(Y.type==="message_start"){if(X)throw new R(`Unexpected event order, got ${Y.type} before receiving "message_stop"`);return Y.message}if(!X)throw new R(`Unexpected event order, got ${Y.type} before "message_start"`);switch(Y.type){case"message_stop":return X;case"message_delta":if(X.container=Y.delta.container,X.stop_reason=Y.delta.stop_reason,X.stop_sequence=Y.delta.stop_sequence,X.usage.output_tokens=Y.usage.output_tokens,X.context_management=Y.context_management,Y.usage.input_tokens!=null)X.usage.input_tokens=Y.usage.input_tokens;if(Y.usage.cache_creation_input_tokens!=null)X.usage.cache_creation_input_tokens=Y.usage.cache_creation_input_tokens;if(Y.usage.cache_read_input_tokens!=null)X.usage.cache_read_input_tokens=Y.usage.cache_read_input_tokens;if(Y.usage.server_tool_use!=null)X.usage.server_tool_use=Y.usage.server_tool_use;return X;case"content_block_start":return X.content.push(Y.content_block),X;case"content_block_delta":{let Q=X.content.at(Y.index);switch(Y.delta.type){case"text_delta":{if(Q?.type==="text")X.content[Y.index]={...Q,text:(Q.text||"")+Y.delta.text};break}case"citations_delta":{if(Q?.type==="text")X.content[Y.index]={...Q,citations:[...Q.citations??[],Y.delta.citation]};break}case"input_json_delta":{if(Q&&ZW(Q)){let $=Q[e$]||"";$+=Y.delta.partial_json;let W={...Q};if(Object.defineProperty(W,e$,{value:$,enumerable:!1,writable:!0}),$)try{W.input=h4($)}catch(J){let z=new R(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${J}. JSON: ${$}`);B(this,l4,"f").call(this,z)}X.content[Y.index]=W}break}case"thinking_delta":{if(Q?.type==="thinking")X.content[Y.index]={...Q,thinking:Q.thinking+Y.delta.thinking};break}case"signature_delta":{if(Q?.type==="thinking")X.content[Y.index]={...Q,signature:Y.delta.signature};break}default:YW(Y.delta)}return X}case"content_block_stop":return X}},Symbol.asyncIterator)](){let Z=[],Y=[],X=!1;return this.on("streamEvent",(Q)=>{let $=Y.shift();if($)$.resolve(Q);else Z.push(Q)}),this.on("end",()=>{X=!0;for(let Q of Y)Q.resolve(void 0);Y.length=0}),this.on("abort",(Q)=>{X=!0;for(let $ of Y)$.reject(Q);Y.length=0}),this.on("error",(Q)=>{X=!0;for(let $ of Y)$.reject(Q);Y.length=0}),{next:async()=>{if(!Z.length){if(X)return{value:void 0,done:!0};return new Promise(($,W)=>Y.push({resolve:$,reject:W})).then(($)=>$?{value:$,done:!1}:{value:void 0,done:!0})}return{value:Z.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new n1(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function YW(Z){}var XW=1e5,QW=`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
Priority order if multiple steps remain
|
|
72
|
-
5. Context to Preserve
|
|
73
|
-
User preferences or style requirements
|
|
74
|
-
Domain-specific details that aren't obvious
|
|
75
|
-
Any promises made to the user
|
|
76
|
-
Be concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
|
|
77
|
-
Wrap your summary in <summary></summary> tags.`;var Y6,m9,L9,M1,X6,a1,_0,i0,Q6,$W,MY;function WW(){let Z,Y;return{promise:new Promise((Q,$)=>{Z=Q,Y=$}),resolve:Z,reject:Y}}class $6{constructor(Z,Y,X){Y6.add(this),this.client=Z,m9.set(this,!1),L9.set(this,!1),M1.set(this,void 0),X6.set(this,void 0),a1.set(this,void 0),_0.set(this,void 0),i0.set(this,void 0),Q6.set(this,0),A(this,M1,{params:{...Y,messages:structuredClone(Y.messages)}},"f"),A(this,X6,{...X,headers:y([{"x-stainless-helper":"BetaToolRunner"},X?.headers])},"f"),A(this,i0,WW(),"f")}async*[(m9=new WeakMap,L9=new WeakMap,M1=new WeakMap,X6=new WeakMap,a1=new WeakMap,_0=new WeakMap,i0=new WeakMap,Q6=new WeakMap,Y6=new WeakSet,$W=async function Z(){let Y=B(this,M1,"f").params.compactionControl;if(!Y||!Y.enabled)return!1;let X=0;if(B(this,a1,"f")!==void 0)try{let V=await B(this,a1,"f");X=V.usage.input_tokens+(V.usage.cache_creation_input_tokens??0)+(V.usage.cache_read_input_tokens??0)+V.usage.output_tokens}catch{return!1}let Q=Y.contextTokenThreshold??XW;if(X<Q)return!1;let $=Y.model??B(this,M1,"f").params.model,W=Y.summaryPrompt??QW,J=B(this,M1,"f").params.messages;if(J[J.length-1].role==="assistant"){let V=J[J.length-1];if(Array.isArray(V.content)){let q=V.content.filter((U)=>U.type!=="tool_use");if(q.length===0)J.pop();else V.content=q}}let z=await this.client.beta.messages.create({model:$,messages:[...J,{role:"user",content:[{type:"text",text:W}]}],max_tokens:B(this,M1,"f").params.max_tokens},{headers:{"x-stainless-helper":"compaction"}});if(z.content[0]?.type!=="text")throw new R("Expected text response for compaction");return B(this,M1,"f").params.messages=[{role:"user",content:z.content}],!0},Symbol.asyncIterator)](){var Z;if(B(this,m9,"f"))throw new R("Cannot iterate over a consumed stream");A(this,m9,!0,"f"),A(this,L9,!0,"f"),A(this,_0,void 0,"f");try{while(!0){let Y;try{if(B(this,M1,"f").params.max_iterations&&B(this,Q6,"f")>=B(this,M1,"f").params.max_iterations)break;A(this,L9,!1,"f"),A(this,_0,void 0,"f"),A(this,Q6,(Z=B(this,Q6,"f"),Z++,Z),"f"),A(this,a1,void 0,"f");let{max_iterations:X,compactionControl:Q,...$}=B(this,M1,"f").params;if($.stream)Y=this.client.beta.messages.stream({...$},B(this,X6,"f")),A(this,a1,Y.finalMessage(),"f"),B(this,a1,"f").catch(()=>{}),yield Y;else A(this,a1,this.client.beta.messages.create({...$,stream:!1},B(this,X6,"f")),"f"),yield B(this,a1,"f");if(!await B(this,Y6,"m",$W).call(this)){if(!B(this,L9,"f")){let{role:z,content:V}=await B(this,a1,"f");B(this,M1,"f").params.messages.push({role:z,content:V})}let J=await B(this,Y6,"m",MY).call(this,B(this,M1,"f").params.messages.at(-1));if(J)B(this,M1,"f").params.messages.push(J);else if(!B(this,L9,"f"))break}}finally{if(Y)Y.abort()}}if(!B(this,a1,"f"))throw new R("ToolRunner concluded without a message from the server");B(this,i0,"f").resolve(await B(this,a1,"f"))}catch(Y){throw A(this,m9,!1,"f"),B(this,i0,"f").promise.catch(()=>{}),B(this,i0,"f").reject(Y),A(this,i0,WW(),"f"),Y}}setMessagesParams(Z){if(typeof Z==="function")B(this,M1,"f").params=Z(B(this,M1,"f").params);else B(this,M1,"f").params=Z;A(this,L9,!0,"f"),A(this,_0,void 0,"f")}async generateToolResponse(){let Z=await B(this,a1,"f")??this.params.messages.at(-1);if(!Z)return null;return B(this,Y6,"m",MY).call(this,Z)}done(){return B(this,i0,"f").promise}async runUntilDone(){if(!B(this,m9,"f"))for await(let Z of this);return this.done()}get params(){return B(this,M1,"f").params}pushMessages(...Z){this.setMessagesParams((Y)=>({...Y,messages:[...Y.messages,...Z]}))}then(Z,Y){return this.runUntilDone().then(Z,Y)}}MY=async function Z(Y){if(B(this,_0,"f")!==void 0)return B(this,_0,"f");return A(this,_0,dB(B(this,M1,"f").params,Y),"f"),B(this,_0,"f")};async function dB(Z,Y=Z.messages.at(-1)){if(!Y||Y.role!=="assistant"||!Y.content||typeof Y.content==="string")return null;let X=Y.content.filter(($)=>$.type==="tool_use");if(X.length===0)return null;return{role:"user",content:await Promise.all(X.map(async($)=>{let W=Z.tools.find((J)=>("name"in J?J.name:J.mcp_server_name)===$.name);if(!W||!("run"in W))return{type:"tool_result",tool_use_id:$.id,content:`Error: Tool '${$.name}' not found`,is_error:!0};try{let J=$.input;if("parse"in W&&W.parse)J=W.parse(J);let z=await W.run(J);return{type:"tool_result",tool_use_id:$.id,content:z}}catch(J){return{type:"tool_result",tool_use_id:$.id,content:`Error: ${J instanceof Error?J.message:String(J)}`,is_error:!0}}}))}}class p9{constructor(Z,Y){this.iterator=Z,this.controller=Y}async*decoder(){let Z=new c0;for await(let Y of this.iterator)for(let X of Z.decode(Y))yield JSON.parse(X);for(let Y of Z.flush())yield JSON.parse(Y)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(Z,Y){if(!Z.body){if(Y.abort(),typeof globalThis.navigator!=="undefined"&&globalThis.navigator.product==="ReactNative")throw new R("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new R("Attempted to iterate over a response with no body")}return new p9(g2(Z.body),Y)}}class W6 extends X1{create(Z,Y){let{betas:X,...Q}=Z;return this._client.post("/v1/messages/batches?beta=true",{body:Q,...Y,headers:y([{"anthropic-beta":[...X??[],"message-batches-2024-09-24"].toString()},Y?.headers])})}retrieve(Z,Y={},X){let{betas:Q}=Y??{};return this._client.get(Y1`/v1/messages/batches/${Z}?beta=true`,{...X,headers:y([{"anthropic-beta":[...Q??[],"message-batches-2024-09-24"].toString()},X?.headers])})}list(Z={},Y){let{betas:X,...Q}=Z??{};return this._client.getAPIList("/v1/messages/batches?beta=true",q0,{query:Q,...Y,headers:y([{"anthropic-beta":[...X??[],"message-batches-2024-09-24"].toString()},Y?.headers])})}delete(Z,Y={},X){let{betas:Q}=Y??{};return this._client.delete(Y1`/v1/messages/batches/${Z}?beta=true`,{...X,headers:y([{"anthropic-beta":[...Q??[],"message-batches-2024-09-24"].toString()},X?.headers])})}cancel(Z,Y={},X){let{betas:Q}=Y??{};return this._client.post(Y1`/v1/messages/batches/${Z}/cancel?beta=true`,{...X,headers:y([{"anthropic-beta":[...Q??[],"message-batches-2024-09-24"].toString()},X?.headers])})}async results(Z,Y={},X){let Q=await this.retrieve(Z);if(!Q.results_url)throw new R(`No batch \`results_url\`; Has it finished processing? ${Q.processing_status} - ${Q.id}`);let{betas:$}=Y??{};return this._client.get(Q.results_url,{...X,headers:y([{"anthropic-beta":[...$??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},X?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((W,J)=>p9.fromResponse(J.response,J.controller))}}var JW={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026"};class M9 extends X1{constructor(){super(...arguments);this.batches=new W6(this._client)}create(Z,Y){let{betas:X,...Q}=Z;if(Q.model in JW)console.warn(`The model '${Q.model}' is deprecated and will reach end-of-life on ${JW[Q.model]}
|
|
78
|
-
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let $=this._client._options.timeout;if(!Q.stream&&$==null){let W=f4[Q.model]??void 0;$=this._client.calculateNonstreamingTimeout(Q.max_tokens,W)}return this._client.post("/v1/messages?beta=true",{body:Q,timeout:$??600000,...Y,headers:y([{...X?.toString()!=null?{"anthropic-beta":X?.toString()}:void 0},Y?.headers]),stream:Z.stream??!1})}parse(Z,Y){return Y={...Y,headers:y([{"anthropic-beta":[...Z.betas??[],"structured-outputs-2025-11-13"].toString()},Y?.headers])},this.create(Z,Y).then((X)=>HY(X,Z,{logger:this._client.logger??console}))}stream(Z,Y){return Z6.createMessage(this,Z,Y)}countTokens(Z,Y){let{betas:X,...Q}=Z;return this._client.post("/v1/messages/count_tokens?beta=true",{body:Q,...Y,headers:y([{"anthropic-beta":[...X??[],"token-counting-2024-11-01"].toString()},Y?.headers])})}toolRunner(Z,Y){return new $6(this._client,Z,Y)}}M9.Batches=W6;M9.BetaToolRunner=$6;class J6 extends X1{create(Z,Y={},X){let{betas:Q,...$}=Y??{};return this._client.post(Y1`/v1/skills/${Z}/versions?beta=true`,h9({body:$,...X,headers:y([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},X?.headers])},this._client))}retrieve(Z,Y,X){let{skill_id:Q,betas:$}=Y;return this._client.get(Y1`/v1/skills/${Q}/versions/${Z}?beta=true`,{...X,headers:y([{"anthropic-beta":[...$??[],"skills-2025-10-02"].toString()},X?.headers])})}list(Z,Y={},X){let{betas:Q,...$}=Y??{};return this._client.getAPIList(Y1`/v1/skills/${Z}/versions?beta=true`,c2,{query:$,...X,headers:y([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},X?.headers])})}delete(Z,Y,X){let{skill_id:Q,betas:$}=Y;return this._client.delete(Y1`/v1/skills/${Q}/versions/${Z}?beta=true`,{...X,headers:y([{"anthropic-beta":[...$??[],"skills-2025-10-02"].toString()},X?.headers])})}}class d9 extends X1{constructor(){super(...arguments);this.versions=new J6(this._client)}create(Z={},Y){let{betas:X,...Q}=Z??{};return this._client.post("/v1/skills?beta=true",h9({body:Q,...Y,headers:y([{"anthropic-beta":[...X??[],"skills-2025-10-02"].toString()},Y?.headers])},this._client))}retrieve(Z,Y={},X){let{betas:Q}=Y??{};return this._client.get(Y1`/v1/skills/${Z}?beta=true`,{...X,headers:y([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},X?.headers])})}list(Z={},Y){let{betas:X,...Q}=Z??{};return this._client.getAPIList("/v1/skills?beta=true",c2,{query:Q,...Y,headers:y([{"anthropic-beta":[...X??[],"skills-2025-10-02"].toString()},Y?.headers])})}delete(Z,Y={},X){let{betas:Q}=Y??{};return this._client.delete(Y1`/v1/skills/${Z}?beta=true`,{...X,headers:y([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},X?.headers])})}}d9.Versions=J6;class M0 extends X1{constructor(){super(...arguments);this.models=new o2(this._client),this.messages=new M9(this._client),this.files=new i2(this._client),this.skills=new d9(this._client)}}M0.Models=o2;M0.Messages=M9;M0.Files=i2;M0.Skills=d9;class c9 extends X1{create(Z,Y){let{betas:X,...Q}=Z;return this._client.post("/v1/complete",{body:Q,timeout:this._client._options.timeout??600000,...Y,headers:y([{...X?.toString()!=null?{"anthropic-beta":X?.toString()}:void 0},Y?.headers]),stream:Z.stream??!1})}}var Y0,o0,z6,i4,V6,q6,o4,U6,y0,H6,n4,a4,F9,r4,s4,FY,zW,NY,wY,DY,AY,VW,qW="__json_buf";function UW(Z){return Z.type==="tool_use"||Z.type==="server_tool_use"}class G6{constructor(){Y0.add(this),this.messages=[],this.receivedMessages=[],o0.set(this,void 0),this.controller=new AbortController,z6.set(this,void 0),i4.set(this,()=>{}),V6.set(this,()=>{}),q6.set(this,void 0),o4.set(this,()=>{}),U6.set(this,()=>{}),y0.set(this,{}),H6.set(this,!1),n4.set(this,!1),a4.set(this,!1),F9.set(this,!1),r4.set(this,void 0),s4.set(this,void 0),NY.set(this,(Z)=>{if(A(this,n4,!0,"f"),j0(Z))Z=new P1;if(Z instanceof P1)return A(this,a4,!0,"f"),this._emit("abort",Z);if(Z instanceof R)return this._emit("error",Z);if(Z instanceof Error){let Y=new R(Z.message);return Y.cause=Z,this._emit("error",Y)}return this._emit("error",new R(String(Z)))}),A(this,z6,new Promise((Z,Y)=>{A(this,i4,Z,"f"),A(this,V6,Y,"f")}),"f"),A(this,q6,new Promise((Z,Y)=>{A(this,o4,Z,"f"),A(this,U6,Y,"f")}),"f"),B(this,z6,"f").catch(()=>{}),B(this,q6,"f").catch(()=>{})}get response(){return B(this,r4,"f")}get request_id(){return B(this,s4,"f")}async withResponse(){A(this,F9,!0,"f");let Z=await B(this,z6,"f");if(!Z)throw new Error("Could not resolve a `Response` object");return{data:this,response:Z,request_id:Z.headers.get("request-id")}}static fromReadableStream(Z){let Y=new G6;return Y._run(()=>Y._fromReadableStream(Z)),Y}static createMessage(Z,Y,X){let Q=new G6;for(let $ of Y.messages)Q._addMessageParam($);return Q._run(()=>Q._createMessage(Z,{...Y,stream:!0},{...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"stream"}})),Q}_run(Z){Z().then(()=>{this._emitFinal(),this._emit("end")},B(this,NY,"f"))}_addMessageParam(Z){this.messages.push(Z)}_addMessage(Z,Y=!0){if(this.receivedMessages.push(Z),Y)this._emit("message",Z)}async _createMessage(Z,Y,X){let Q=X?.signal,$;if(Q){if(Q.aborted)this.controller.abort();$=this.controller.abort.bind(this.controller),Q.addEventListener("abort",$)}try{B(this,Y0,"m",wY).call(this);let{response:W,data:J}=await Z.create({...Y,stream:!0},{...X,signal:this.controller.signal}).withResponse();this._connected(W);for await(let z of J)B(this,Y0,"m",DY).call(this,z);if(J.controller.signal?.aborted)throw new P1;B(this,Y0,"m",AY).call(this)}finally{if(Q&&$)Q.removeEventListener("abort",$)}}_connected(Z){if(this.ended)return;A(this,r4,Z,"f"),A(this,s4,Z?.headers.get("request-id"),"f"),B(this,i4,"f").call(this,Z),this._emit("connect")}get ended(){return B(this,H6,"f")}get errored(){return B(this,n4,"f")}get aborted(){return B(this,a4,"f")}abort(){this.controller.abort()}on(Z,Y){return(B(this,y0,"f")[Z]||(B(this,y0,"f")[Z]=[])).push({listener:Y}),this}off(Z,Y){let X=B(this,y0,"f")[Z];if(!X)return this;let Q=X.findIndex(($)=>$.listener===Y);if(Q>=0)X.splice(Q,1);return this}once(Z,Y){return(B(this,y0,"f")[Z]||(B(this,y0,"f")[Z]=[])).push({listener:Y,once:!0}),this}emitted(Z){return new Promise((Y,X)=>{if(A(this,F9,!0,"f"),Z!=="error")this.once("error",X);this.once(Z,Y)})}async done(){A(this,F9,!0,"f"),await B(this,q6,"f")}get currentMessage(){return B(this,o0,"f")}async finalMessage(){return await this.done(),B(this,Y0,"m",FY).call(this)}async finalText(){return await this.done(),B(this,Y0,"m",zW).call(this)}_emit(Z,...Y){if(B(this,H6,"f"))return;if(Z==="end")A(this,H6,!0,"f"),B(this,o4,"f").call(this);let X=B(this,y0,"f")[Z];if(X)B(this,y0,"f")[Z]=X.filter((Q)=>!Q.once),X.forEach(({listener:Q})=>Q(...Y));if(Z==="abort"){let Q=Y[0];if(!B(this,F9,"f")&&!X?.length)Promise.reject(Q);B(this,V6,"f").call(this,Q),B(this,U6,"f").call(this,Q),this._emit("end");return}if(Z==="error"){let Q=Y[0];if(!B(this,F9,"f")&&!X?.length)Promise.reject(Q);B(this,V6,"f").call(this,Q),B(this,U6,"f").call(this,Q),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",B(this,Y0,"m",FY).call(this))}async _fromReadableStream(Z,Y){let X=Y?.signal,Q;if(X){if(X.aborted)this.controller.abort();Q=this.controller.abort.bind(this.controller),X.addEventListener("abort",Q)}try{B(this,Y0,"m",wY).call(this),this._connected(null);let $=n1.fromReadableStream(Z,this.controller);for await(let W of $)B(this,Y0,"m",DY).call(this,W);if($.controller.signal?.aborted)throw new P1;B(this,Y0,"m",AY).call(this)}finally{if(X&&Q)X.removeEventListener("abort",Q)}}[(o0=new WeakMap,z6=new WeakMap,i4=new WeakMap,V6=new WeakMap,q6=new WeakMap,o4=new WeakMap,U6=new WeakMap,y0=new WeakMap,H6=new WeakMap,n4=new WeakMap,a4=new WeakMap,F9=new WeakMap,r4=new WeakMap,s4=new WeakMap,NY=new WeakMap,Y0=new WeakSet,FY=function Z(){if(this.receivedMessages.length===0)throw new R("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},zW=function Z(){if(this.receivedMessages.length===0)throw new R("stream ended without producing a Message with role=assistant");let Y=this.receivedMessages.at(-1).content.filter((X)=>X.type==="text").map((X)=>X.text);if(Y.length===0)throw new R("stream ended without producing a content block with type=text");return Y.join(" ")},wY=function Z(){if(this.ended)return;A(this,o0,void 0,"f")},DY=function Z(Y){if(this.ended)return;let X=B(this,Y0,"m",VW).call(this,Y);switch(this._emit("streamEvent",Y,X),Y.type){case"content_block_delta":{let Q=X.content.at(-1);switch(Y.delta.type){case"text_delta":{if(Q.type==="text")this._emit("text",Y.delta.text,Q.text||"");break}case"citations_delta":{if(Q.type==="text")this._emit("citation",Y.delta.citation,Q.citations??[]);break}case"input_json_delta":{if(UW(Q)&&Q.input)this._emit("inputJson",Y.delta.partial_json,Q.input);break}case"thinking_delta":{if(Q.type==="thinking")this._emit("thinking",Y.delta.thinking,Q.thinking);break}case"signature_delta":{if(Q.type==="thinking")this._emit("signature",Q.signature);break}default:HW(Y.delta)}break}case"message_stop":{this._addMessageParam(X),this._addMessage(X,!0);break}case"content_block_stop":{this._emit("contentBlock",X.content.at(-1));break}case"message_start":{A(this,o0,X,"f");break}case"content_block_start":case"message_delta":break}},AY=function Z(){if(this.ended)throw new R("stream has ended, this shouldn't happen");let Y=B(this,o0,"f");if(!Y)throw new R("request ended without sending any chunks");return A(this,o0,void 0,"f"),Y},VW=function Z(Y){let X=B(this,o0,"f");if(Y.type==="message_start"){if(X)throw new R(`Unexpected event order, got ${Y.type} before receiving "message_stop"`);return Y.message}if(!X)throw new R(`Unexpected event order, got ${Y.type} before "message_start"`);switch(Y.type){case"message_stop":return X;case"message_delta":if(X.stop_reason=Y.delta.stop_reason,X.stop_sequence=Y.delta.stop_sequence,X.usage.output_tokens=Y.usage.output_tokens,Y.usage.input_tokens!=null)X.usage.input_tokens=Y.usage.input_tokens;if(Y.usage.cache_creation_input_tokens!=null)X.usage.cache_creation_input_tokens=Y.usage.cache_creation_input_tokens;if(Y.usage.cache_read_input_tokens!=null)X.usage.cache_read_input_tokens=Y.usage.cache_read_input_tokens;if(Y.usage.server_tool_use!=null)X.usage.server_tool_use=Y.usage.server_tool_use;return X;case"content_block_start":return X.content.push({...Y.content_block}),X;case"content_block_delta":{let Q=X.content.at(Y.index);switch(Y.delta.type){case"text_delta":{if(Q?.type==="text")X.content[Y.index]={...Q,text:(Q.text||"")+Y.delta.text};break}case"citations_delta":{if(Q?.type==="text")X.content[Y.index]={...Q,citations:[...Q.citations??[],Y.delta.citation]};break}case"input_json_delta":{if(Q&&UW(Q)){let $=Q[qW]||"";$+=Y.delta.partial_json;let W={...Q};if(Object.defineProperty(W,qW,{value:$,enumerable:!1,writable:!0}),$)W.input=h4($);X.content[Y.index]=W}break}case"thinking_delta":{if(Q?.type==="thinking")X.content[Y.index]={...Q,thinking:Q.thinking+Y.delta.thinking};break}case"signature_delta":{if(Q?.type==="thinking")X.content[Y.index]={...Q,signature:Y.delta.signature};break}default:HW(Y.delta)}return X}case"content_block_stop":return X}},Symbol.asyncIterator)](){let Z=[],Y=[],X=!1;return this.on("streamEvent",(Q)=>{let $=Y.shift();if($)$.resolve(Q);else Z.push(Q)}),this.on("end",()=>{X=!0;for(let Q of Y)Q.resolve(void 0);Y.length=0}),this.on("abort",(Q)=>{X=!0;for(let $ of Y)$.reject(Q);Y.length=0}),this.on("error",(Q)=>{X=!0;for(let $ of Y)$.reject(Q);Y.length=0}),{next:async()=>{if(!Z.length){if(X)return{value:void 0,done:!0};return new Promise(($,W)=>Y.push({resolve:$,reject:W})).then(($)=>$?{value:$,done:!1}:{value:void 0,done:!0})}return{value:Z.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new n1(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function HW(Z){}class K6 extends X1{create(Z,Y){return this._client.post("/v1/messages/batches",{body:Z,...Y})}retrieve(Z,Y){return this._client.get(Y1`/v1/messages/batches/${Z}`,Y)}list(Z={},Y){return this._client.getAPIList("/v1/messages/batches",q0,{query:Z,...Y})}delete(Z,Y){return this._client.delete(Y1`/v1/messages/batches/${Z}`,Y)}cancel(Z,Y){return this._client.post(Y1`/v1/messages/batches/${Z}/cancel`,Y)}async results(Z,Y){let X=await this.retrieve(Z);if(!X.results_url)throw new R(`No batch \`results_url\`; Has it finished processing? ${X.processing_status} - ${X.id}`);return this._client.get(X.results_url,{...Y,headers:y([{Accept:"application/binary"},Y?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((Q,$)=>p9.fromResponse($.response,$.controller))}}class N9 extends X1{constructor(){super(...arguments);this.batches=new K6(this._client)}create(Z,Y){if(Z.model in GW)console.warn(`The model '${Z.model}' is deprecated and will reach end-of-life on ${GW[Z.model]}
|
|
79
|
-
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let X=this._client._options.timeout;if(!Z.stream&&X==null){let Q=f4[Z.model]??void 0;X=this._client.calculateNonstreamingTimeout(Z.max_tokens,Q)}return this._client.post("/v1/messages",{body:Z,timeout:X??600000,...Y,stream:Z.stream??!1})}stream(Z,Y){return G6.createMessage(this,Z,Y)}countTokens(Z,Y){return this._client.post("/v1/messages/count_tokens",{body:Z,...Y})}}var GW={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026"};N9.Batches=K6;class l9 extends X1{retrieve(Z,Y={},X){let{betas:Q}=Y??{};return this._client.get(Y1`/v1/models/${Z}`,{...X,headers:y([{...Q?.toString()!=null?{"anthropic-beta":Q?.toString()}:void 0},X?.headers])})}list(Z={},Y){let{betas:X,...Q}=Z??{};return this._client.getAPIList("/v1/models",q0,{query:Q,...Y,headers:y([{...X?.toString()!=null?{"anthropic-beta":X?.toString()}:void 0},Y?.headers])})}}var B6=(Z)=>{if(typeof globalThis.process!=="undefined")return globalThis.process.env?.[Z]?.trim()??void 0;if(typeof globalThis.Deno!=="undefined")return globalThis.Deno.env?.get?.(Z)?.trim();return};var EY,OY,t4,KW,BW="\\n\\nHuman:",LW="\\n\\nAssistant:";class V1{constructor({baseURL:Z=B6("ANTHROPIC_BASE_URL"),apiKey:Y=B6("ANTHROPIC_API_KEY")??null,authToken:X=B6("ANTHROPIC_AUTH_TOKEN")??null,...Q}={}){EY.add(this),t4.set(this,void 0);let $={apiKey:Y,authToken:X,...Q,baseURL:Z||"https://api.anthropic.com"};if(!$.dangerouslyAllowBrowser&&k$())throw new R(`It looks like you're running in a browser-like environment.
|
|
80
|
-
|
|
81
|
-
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
82
|
-
If you understand the risks and have appropriate mitigations in place,
|
|
83
|
-
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
84
|
-
|
|
85
|
-
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
86
|
-
`);this.baseURL=$.baseURL,this.timeout=$.timeout??OY.DEFAULT_TIMEOUT,this.logger=$.logger??console;let W="warn";this.logLevel=W,this.logLevel=QY($.logLevel,"ClientOptions.logLevel",this)??QY(B6("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??W,this.fetchOptions=$.fetchOptions,this.maxRetries=$.maxRetries??2,this.fetch=$.fetch??f$(),A(this,t4,g$,"f"),this._options=$,this.apiKey=typeof Y==="string"?Y:null,this.authToken=X}withOptions(Z){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...Z})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:Z,nulls:Y}){if(Z.get("x-api-key")||Z.get("authorization"))return;if(this.apiKey&&Z.get("x-api-key"))return;if(Y.has("x-api-key"))return;if(this.authToken&&Z.get("authorization"))return;if(Y.has("authorization"))return;throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(Z){return y([await this.apiKeyAuth(Z),await this.bearerAuth(Z)])}async apiKeyAuth(Z){if(this.apiKey==null)return;return y([{"X-Api-Key":this.apiKey}])}async bearerAuth(Z){if(this.authToken==null)return;return y([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(Z){return Object.entries(Z).filter(([Y,X])=>typeof X!=="undefined").map(([Y,X])=>{if(typeof X==="string"||typeof X==="number"||typeof X==="boolean")return`${encodeURIComponent(Y)}=${encodeURIComponent(X)}`;if(X===null)return`${encodeURIComponent(Y)}=`;throw new R(`Cannot stringify type ${typeof X}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${d0}`}defaultIdempotencyKey(){return`stainless-node-retry-${tZ()}`}makeStatusError(Z,Y,X,Q){return L1.generate(Z,Y,X,Q)}buildURL(Z,Y,X){let Q=!B(this,EY,"m",KW).call(this)&&X||this.baseURL,$=R$(Z)?new URL(Z):new URL(Q+(Q.endsWith("/")&&Z.startsWith("/")?Z.slice(1):Z)),W=this.defaultQuery();if(!j$(W))Y={...W,...Y};if(typeof Y==="object"&&Y&&!Array.isArray(Y))$.search=this.stringifyQuery(Y);return $.toString()}_calculateNonstreamingTimeout(Z){if(3600*Z/128000>600)throw new R("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600000}async prepareOptions(Z){}async prepareRequest(Z,{url:Y,options:X}){}get(Z,Y){return this.methodRequest("get",Z,Y)}post(Z,Y){return this.methodRequest("post",Z,Y)}patch(Z,Y){return this.methodRequest("patch",Z,Y)}put(Z,Y){return this.methodRequest("put",Z,Y)}delete(Z,Y){return this.methodRequest("delete",Z,Y)}methodRequest(Z,Y,X){return this.request(Promise.resolve(X).then((Q)=>{return{method:Z,path:Y,...Q}}))}request(Z,Y=null){return new G9(this,this.makeRequest(Z,Y,void 0))}async makeRequest(Z,Y,X){let Q=await Z,$=Q.maxRetries??this.maxRetries;if(Y==null)Y=$;await this.prepareOptions(Q);let{req:W,url:J,timeout:z}=await this.buildRequest(Q,{retryCount:$-Y});await this.prepareRequest(W,{url:J,options:Q});let V="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),q=X===void 0?"":`, retryOf: ${X}`,U=Date.now();if(A1(this).debug(`[${V}] sending request`,C0({retryOfRequestLogID:X,method:Q.method,url:J,options:Q,headers:W.headers})),Q.signal?.aborted)throw new P1;let H=new AbortController,G=await this.fetchWithTimeout(J,W,z,H).catch(C2),K=Date.now();if(G instanceof globalThis.Error){let O=`retrying, ${Y} attempts remaining`;if(Q.signal?.aborted)throw new P1;let T=j0(G)||/timed? ?out/i.test(String(G)+("cause"in G?String(G.cause):""));if(Y)return A1(this).info(`[${V}] connection ${T?"timed out":"failed"} - ${O}`),A1(this).debug(`[${V}] connection ${T?"timed out":"failed"} (${O})`,C0({retryOfRequestLogID:X,url:J,durationMs:K-U,message:G.message})),this.retryRequest(Q,Y,X??V);if(A1(this).info(`[${V}] connection ${T?"timed out":"failed"} - error; no more retries left`),A1(this).debug(`[${V}] connection ${T?"timed out":"failed"} (error; no more retries left)`,C0({retryOfRequestLogID:X,url:J,durationMs:K-U,message:G.message})),T)throw new S2;throw new H9({cause:G})}let M=[...G.headers.entries()].filter(([O])=>O==="request-id").map(([O,T])=>", "+O+": "+JSON.stringify(T)).join(""),E=`[${V}${q}${M}] ${W.method} ${J} ${G.ok?"succeeded":"failed"} with status ${G.status} in ${K-U}ms`;if(!G.ok){let O=await this.shouldRetry(G);if(Y&&O){let W1=`retrying, ${Y} attempts remaining`;return await h$(G.body),A1(this).info(`${E} - ${W1}`),A1(this).debug(`[${V}] response error (${W1})`,C0({retryOfRequestLogID:X,url:G.url,status:G.status,headers:G.headers,durationMs:K-U})),this.retryRequest(Q,Y,X??V,G.headers)}let T=O?"error; no more retries left":"error; not retryable";A1(this).info(`${E} - ${T}`);let i=await G.text().catch((W1)=>C2(W1).message),g=C4(i),Z1=g?void 0:i;throw A1(this).debug(`[${V}] response error (${T})`,C0({retryOfRequestLogID:X,url:G.url,status:G.status,headers:G.headers,message:Z1,durationMs:Date.now()-U})),this.makeStatusError(G.status,g,Z1,G.headers)}return A1(this).info(E),A1(this).debug(`[${V}] response start`,C0({retryOfRequestLogID:X,url:G.url,status:G.status,headers:G.headers,durationMs:K-U})),{response:G,options:Q,controller:H,requestLogID:V,retryOfRequestLogID:X,startTime:U}}getAPIList(Z,Y,X){return this.requestAPIList(Y,{method:"get",path:Z,...X})}requestAPIList(Z,Y){let X=this.makeRequest(Y,null,void 0);return new k4(this,X,Z)}async fetchWithTimeout(Z,Y,X,Q){let{signal:$,method:W,...J}=Y||{};if($)$.addEventListener("abort",()=>Q.abort());let z=setTimeout(()=>Q.abort(),X),V=globalThis.ReadableStream&&J.body instanceof globalThis.ReadableStream||typeof J.body==="object"&&J.body!==null&&Symbol.asyncIterator in J.body,q={signal:Q.signal,...V?{duplex:"half"}:{},method:"GET",...J};if(W)q.method=W.toUpperCase();try{return await this.fetch.call(void 0,Z,q)}finally{clearTimeout(z)}}async shouldRetry(Z){let Y=Z.headers.get("x-should-retry");if(Y==="true")return!0;if(Y==="false")return!1;if(Z.status===408)return!0;if(Z.status===409)return!0;if(Z.status===429)return!0;if(Z.status>=500)return!0;return!1}async retryRequest(Z,Y,X,Q){let $,W=Q?.get("retry-after-ms");if(W){let z=parseFloat(W);if(!Number.isNaN(z))$=z}let J=Q?.get("retry-after");if(J&&!$){let z=parseFloat(J);if(!Number.isNaN(z))$=z*1000;else $=Date.parse(J)-Date.now()}if(!($&&0<=$&&$<60000)){let z=Z.maxRetries??this.maxRetries;$=this.calculateDefaultRetryTimeoutMillis(Y,z)}return await _$($),this.makeRequest(Z,Y-1,X)}calculateDefaultRetryTimeoutMillis(Z,Y){let $=Y-Z,W=Math.min(0.5*Math.pow(2,$),8),J=1-Math.random()*0.25;return W*J*1000}calculateNonstreamingTimeout(Z,Y){if(3600000*Z/128000>600000||Y!=null&&Z>Y)throw new R("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 600000}async buildRequest(Z,{retryCount:Y=0}={}){let X={...Z},{method:Q,path:$,query:W,defaultBaseURL:J}=X,z=this.buildURL($,W,J);if("timeout"in X)S$("timeout",X.timeout);X.timeout=X.timeout??this.timeout;let{bodyHeaders:V,body:q}=this.buildBody({options:X}),U=await this.buildHeaders({options:Z,method:Q,bodyHeaders:V,retryCount:Y});return{req:{method:Q,headers:U,...X.signal&&{signal:X.signal},...globalThis.ReadableStream&&q instanceof globalThis.ReadableStream&&{duplex:"half"},...q&&{body:q},...this.fetchOptions??{},...X.fetchOptions??{}},url:z,timeout:X.timeout}}async buildHeaders({options:Z,method:Y,bodyHeaders:X,retryCount:Q}){let $={};if(this.idempotencyHeader&&Y!=="get"){if(!Z.idempotencyKey)Z.idempotencyKey=this.defaultIdempotencyKey();$[this.idempotencyHeader]=Z.idempotencyKey}let W=y([$,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(Q),...Z.timeout?{"X-Stainless-Timeout":String(Math.trunc(Z.timeout/1000))}:{},...v$(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(Z),this._options.defaultHeaders,X,Z.headers]);return this.validateHeaders(W),W.values}buildBody({options:{body:Z,headers:Y}}){if(!Z)return{bodyHeaders:void 0,body:void 0};let X=y([Y]);if(ArrayBuffer.isView(Z)||Z instanceof ArrayBuffer||Z instanceof DataView||typeof Z==="string"&&X.values.has("content-type")||globalThis.Blob&&Z instanceof globalThis.Blob||Z instanceof FormData||Z instanceof URLSearchParams||globalThis.ReadableStream&&Z instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:Z};else if(typeof Z==="object"&&((Symbol.asyncIterator in Z)||(Symbol.iterator in Z)&&("next"in Z)&&typeof Z.next==="function"))return{bodyHeaders:void 0,body:S4(Z)};else return B(this,t4,"f").call(this,{body:Z,headers:X})}}OY=V1,t4=new WeakMap,EY=new WeakSet,KW=function Z(){return this.baseURL!=="https://api.anthropic.com"};V1.Anthropic=OY;V1.HUMAN_PROMPT=BW;V1.AI_PROMPT=LW;V1.DEFAULT_TIMEOUT=600000;V1.AnthropicError=R;V1.APIError=L1;V1.APIConnectionError=H9;V1.APIConnectionTimeoutError=S2;V1.APIUserAbortError=P1;V1.NotFoundError=x2;V1.ConflictError=k2;V1.RateLimitError=f2;V1.BadRequestError=_2;V1.AuthenticationError=y2;V1.InternalServerError=h2;V1.PermissionDeniedError=b2;V1.UnprocessableEntityError=v2;V1.toFile=v4;class b0 extends V1{constructor(){super(...arguments);this.completions=new c9(this),this.messages=new N9(this),this.models=new l9(this),this.beta=new M0(this)}}b0.Completions=c9;b0.Messages=N9;b0.Models=l9;b0.Beta=M0;function PY(Z){return new b0({apiKey:Z.apiKey})}function TY(){let Y=(typeof globalThis!=="undefined"&&globalThis.window?.env?globalThis.window.env:typeof process!=="undefined"?process.env:void 0)?.ANTHROPIC_API_KEY;if(!Y)throw new Error("ANTHROPIC_API_KEY is required. Please set it in your environment variables or use the factory function with an explicit API key.");return Y}function e4(Z){return`${Z}-${Date.now()}-${Math.random().toString(36).substring(7)}`}class IY extends R4{constructor(Z,Y){super({},Y);this.kind="text",this.name="anthropic",this.client=PY(Z)}async*chatStream(Z){try{let Y=this.mapCommonOptionsToAnthropic(Z),X=await this.client.beta.messages.create({...Y,stream:!0},{signal:Z.request?.signal,headers:Z.request?.headers});yield*this.processAnthropicStream(X,Z.model,()=>e4(this.name))}catch(Y){let X=Y;yield{type:"error",id:e4(this.name),model:Z.model,timestamp:Date.now(),error:{message:X.message||"Unknown error occurred",code:X.code||String(X.status)}}}}async structuredOutput(Z){let{chatOptions:Y,outputSchema:X}=Z,Q=this.mapCommonOptionsToAnthropic(Y),$={name:"structured_output",description:"Use this tool to provide your response in the required structured format.",input_schema:{type:"object",properties:X.properties??{},required:X.required??[]}};try{let W=await this.client.messages.create({...Q,stream:!1,tools:[$],tool_choice:{type:"tool",name:"structured_output"}},{signal:Y.request?.signal,headers:Y.request?.headers}),J=null,z="";for(let V of W.content)if(V.type==="tool_use"&&V.name==="structured_output"){J=V.input,z=JSON.stringify(V.input);break}if(J===null){z=W.content.map((V)=>{if(V.type==="text")return V.text;return""}).join("");try{J=JSON.parse(z)}catch{throw new Error(`Failed to extract structured output from response. Content: ${z.slice(0,200)}${z.length>200?"...":""}`)}}return{data:J,rawText:z}}catch(W){throw new Error(`Structured output generation failed: ${W.message||"Unknown error occurred"}`)}}mapCommonOptionsToAnthropic(Z){let Y=Z.modelOptions,X=this.formatMessages(Z.messages),Q=Z.tools?sZ(Z.tools):void 0,$={};if(Y){let q=["container","context_management","mcp_servers","service_tier","stop_sequences","system","thinking","tool_choice","top_k"];for(let U of q)if(U in Y){let H=Y[U];if(U==="tool_choice"&&typeof H==="string")$[U]={type:H};else $[U]=H}}let W=$.thinking?.type==="enabled"?$.thinking.budget_tokens:void 0,J=Z.maxTokens||1024,z=W&&W>=J?W+1:J,V={model:Z.model,max_tokens:z,temperature:Z.temperature,top_p:Z.topP,messages:X,system:Z.systemPrompts?.join(`
|
|
87
|
-
`),tools:Q,...$};return I$(V),V}convertContentPartToAnthropic(Z){switch(Z.type){case"text":{let Y=Z.metadata;return{type:"text",text:Z.content,...Y}}case"image":{let Y=Z.metadata,X=Z.source.type==="data"?{type:"base64",data:Z.source.value,media_type:Y?.mediaType??"image/jpeg"}:{type:"url",url:Z.source.value},{mediaType:Q,...$}=Y||{};return{type:"image",source:X,...$}}case"document":{let Y=Z.metadata;return{type:"document",source:Z.source.type==="data"?{type:"base64",data:Z.source.value,media_type:"application/pdf"}:{type:"url",url:Z.source.value},...Y}}case"audio":case"video":throw new Error(`Anthropic does not support ${Z.type} content directly`);default:throw new Error(`Unsupported content part type: ${Z.type}`)}}formatMessages(Z){let Y=[];for(let X of Z){let Q=X.role;if(Q==="tool"&&X.toolCallId){Y.push({role:"user",content:[{type:"tool_result",tool_use_id:X.toolCallId,content:typeof X.content==="string"?X.content:""}]});continue}if(Q==="assistant"&&X.toolCalls?.length){let $=[];if(X.content){let J={type:"text",text:typeof X.content==="string"?X.content:""};$.push(J)}for(let W of X.toolCalls){let J={};try{J=W.function.arguments?JSON.parse(W.function.arguments):{}}catch{J=W.function.arguments}let z={type:"tool_use",id:W.id,name:W.function.name,input:J};$.push(z)}Y.push({role:"assistant",content:$});continue}if(Q==="user"&&Array.isArray(X.content)){let $=X.content.map((W)=>this.convertContentPartToAnthropic(W));Y.push({role:"user",content:$});continue}Y.push({role:Q==="assistant"?"assistant":"user",content:typeof X.content==="string"?X.content:X.content?X.content.map(($)=>this.convertContentPartToAnthropic($)):""})}return Y}async*processAnthropicStream(Z,Y,X){let Q="",$="",W=Date.now(),J=new Map,z=-1;try{for await(let V of Z)if(V.type==="content_block_start"){if(V.content_block.type==="tool_use")z++,J.set(z,{id:V.content_block.id,name:V.content_block.name,input:""});else if(V.content_block.type==="thinking")$=""}else if(V.type==="content_block_delta"){if(V.delta.type==="text_delta"){let q=V.delta.text;Q+=q,yield{type:"content",id:X(),model:Y,timestamp:W,delta:q,content:Q,role:"assistant"}}else if(V.delta.type==="thinking_delta"){let q=V.delta.thinking;$+=q,yield{type:"thinking",id:X(),model:Y,timestamp:W,delta:q,content:$}}else if(V.delta.type==="input_json_delta"){let q=J.get(z);if(q)q.input+=V.delta.partial_json,yield{type:"tool_call",id:X(),model:Y,timestamp:W,toolCall:{id:q.id,type:"function",function:{name:q.name,arguments:V.delta.partial_json}},index:z}}}else if(V.type==="content_block_stop"){let q=J.get(z);if(q&&q.input==="")yield{type:"tool_call",id:X(),model:Y,timestamp:W,toolCall:{id:q.id,type:"function",function:{name:q.name,arguments:"{}"}},index:z}}else if(V.type==="message_stop")yield{type:"done",id:X(),model:Y,timestamp:W,finishReason:"stop"};else if(V.type==="message_delta"){if(V.delta.stop_reason)switch(V.delta.stop_reason){case"tool_use":{yield{type:"done",id:X(),model:Y,timestamp:W,finishReason:"tool_calls",usage:{promptTokens:V.usage.input_tokens||0,completionTokens:V.usage.output_tokens||0,totalTokens:(V.usage.input_tokens||0)+(V.usage.output_tokens||0)}};break}case"max_tokens":{yield{type:"error",id:X(),model:Y,timestamp:W,error:{message:"The response was cut off because the maximum token limit was reached.",code:"max_tokens"}};break}default:yield{type:"done",id:X(),model:Y,timestamp:W,finishReason:"stop",usage:{promptTokens:V.usage.input_tokens||0,completionTokens:V.usage.output_tokens||0,totalTokens:(V.usage.input_tokens||0)+(V.usage.output_tokens||0)}}}}}catch(V){let q=V;yield{type:"error",id:X(),model:Y,timestamp:W,error:{message:q.message||"Unknown error occurred",code:q.code||String(q.status)}}}}}function MW(Z,Y,X){return new IY({apiKey:Y,...X},Z)}function C1(Z,Y){let X=TY();return MW(Z,X,Y)}var n0=(Z)=>Array.isArray(Z)?Z:[Z],FW=(Z,Y)=>{let X=[[],[]];for(let Q of Z)if(Y(Q))X[0].push(Q);else X[1].push(Q);return X},Z8=Array,X0=(Z,Y)=>Z.includes(Y),NW=(Z,Y=0)=>[...new Array(Z)].map((X,Q)=>Q+Y),h=(Z,Y,X)=>{if(Z===void 0)return Y===void 0?[]:Array.isArray(Y)?Y:[Y];if(X?.prepend)if(Array.isArray(Y))Z.unshift(...Y);else Z.unshift(Y);else if(Array.isArray(Y))Z.push(...Y);else Z.push(Y);return Z},x0=(Z,Y)=>{if(Y===void 0||Y===null)return Z??[];if(Z===void 0||Z===null)return n0(Y);return Z.concat(Y)},wW=(...Z)=>Z.reduce(x0,[]),F0=(Z,Y,X)=>{if(Z===void 0)return Array.isArray(Y)?Y:[Y];let Q=X?.isEqual??(($,W)=>$===W);for(let $ of n0(Y))if(!Z.some((W)=>Q(W,$)))Z.push($);return Z},DW=(Z,Y)=>Z.reduce((X,Q)=>{let $=Q[Y];return X[$]=h(X[$],Q),X},{}),k0=(Z,Y,X)=>Z.length===Y.length&&Z.every(X?.isEqual?(Q,$)=>X.isEqual(Q,Y[$]):(Q,$)=>Q===Y[$]);var v1=(Z,Y)=>F1(Z)===Y,F1=(Z)=>{let Y=typeof Z;return Y==="object"?Z===null?"null":"object":Y==="function"?"object":Y},f1={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},AW={...f1,function:"a function"};class EW extends Error{}var u=(Z)=>w9(Z,EW),w9=(Z,Y=Error)=>{throw new Y(Z)};class L6 extends Error{name="ParseError"}var L=(Z)=>w9(Z,L6),U0=(Z)=>` ${Z}`,OW="";var b=(Z,Y)=>{let X={},Q=Array.isArray(Z),$=!1;for(let[W,J]of Object.entries(Z).entries()){let z=Q?Y(W,J[1]):Y(...J,W);$||=typeof z[0]==="number";let V=Array.isArray(z[0])||z.length===0?z:[z];for(let[q,U]of V)if(typeof q==="object")X[q.group]=h(X[q.group],U);else X[q]=U}return $?Object.values(X):X};var RY=Object.entries;var N1=(Z,Y)=>(Z in Y),i9=(Z,Y)=>(Y in Z);class jY{constructor(Z){Object.assign(this,Z)}}var PW=class{};class M6 extends PW{}var rB=(Z,Y)=>{let X={},Q={},$;for($ in Z)if($ in Y)X[$]=Z[$];else Q[$]=Z[$];return[X,Q]};var Y8=(Z,Y)=>rB(Z,Y)[1],N0=(Z)=>Object.keys(Z).length===0,D9=(Z)=>[...Object.entries(Z),...Object.getOwnPropertySymbols(Z).map((Y)=>[Y,Z[Y]])],TW=(Z,Y)=>Object.defineProperties(Z,Object.getOwnPropertyDescriptors(Y)),IW=(Z)=>{let Y=Object.keys(Z).sort(),X={};for(let Q=0;Q<Y.length;Q++)X[Y[Q]]=Z[Y[Q]];return X};var h1=U0(`unset${OW}`),RW=(Z)=>Object.values(Z).filter((Y)=>{if(typeof Y==="number")return!0;return typeof Z[Y]!=="number"});var CY={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},SY=globalThis.File??Blob,_Y={ArrayBuffer,Blob,File:SY,FormData,Headers,Request,Response,URL},sB={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},A9={...CY,..._Y,...sB,String,Number,Boolean},F6=(Z)=>{let Y=Object.getPrototypeOf(Z);while(Y?.constructor&&(!N1(Y.constructor.name,A9)||!(Z instanceof A9[Y.constructor.name])))Y=Object.getPrototypeOf(Y);let X=Y?.constructor?.name;if(X===void 0||X==="Object")return;return X},N6=(Z)=>typeof Z==="object"&&Z!==null?F6(Z)??"object":F1(Z);var n=Array.isArray,tB={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"},eB={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"},ZL={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"},jW={...tB,...eB,...ZL},w6=(Z)=>{let Y=Object(Z).name??null;return Y&&N1(Y,A9)&&A9[Y]===Z?Y:null};var yY=(Z,Y)=>{let X=Z.prototype;while(X!==null){if(X===Y.prototype)return!0;X=Object.getPrototypeOf(X)}return!1};var CW=(Z)=>SW(Z,new Map),SW=(Z,Y)=>{if(typeof Z!=="object"||Z===null)return Z;if(Y?.has(Z))return Y.get(Z);let X=w6(Z.constructor);if(X==="Date")return new Date(Z.getTime());if(X&&X!=="Array")return Z;let Q=Array.isArray(Z)?Z.slice():Object.create(Object.getPrototypeOf(Z)),$=Object.getOwnPropertyDescriptors(Z);if(Y){Y.set(Z,Q);for(let W in $){let J=$[W];if("get"in J||"set"in J)continue;J.value=SW(J.value,Y)}}return Object.defineProperties(Q,$),Q};var YL=(Z)=>{let Y=h1;return()=>Y===h1?Y=Z():Y},a0=(Z)=>typeof Z==="function"&&Z.length===0;var _W=class extends Function{constructor(...Z){let Y=Z.slice(0,-1),X=Z[Z.length-1];try{super(...Y,X)}catch(Q){return u(`Encountered an unexpected error while compiling your definition:
|
|
88
|
-
Message: ${Q}
|
|
89
|
-
Source: (${Z.slice(0,-1)}) => {
|
|
90
|
-
${Z[Z.length-1]}
|
|
91
|
-
}`)}}};class g1{constructor(Z,...[Y]){return Object.assign(Object.setPrototypeOf(Z.bind(Y?.bind??this),this.constructor.prototype),Y?.attach)}}var yW=YL(()=>{try{return new Function("return false")()}catch{return!0}});var FI=U0("brand");var bW=U0("arkInferred");var DI=U0("args");class T1{constructor(){}}var XL=()=>{try{return((new Error().stack?.split(`
|
|
92
|
-
`)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},QL=globalThis.process?.env??{},xW={fileName:XL,env:QL};var kW=(Z)=>Z[0].toUpperCase()+Z.slice(1),vW=(Z)=>Z[0].toLowerCase()+Z.slice(1),bY=(Z)=>new RegExp($L(Z),typeof Z==="string"?"":Z.flags);var $L=(Z)=>{return`^(?:${typeof Z==="string"?Z:Z.source})$`};var v0={negativeLookahead:(Z)=>`(?!${Z})`,nonCapturingGroup:(Z)=>`(?:${Z})`},E9="\\",r0={" ":1,"\n":1,"\t":1};var WL=/^-0\.?0*$/.source,hW=/[1-9]\d*/.source,JL=/\.\d+/.source,zL=/\.\d*[1-9]/.source,gW=(Z)=>bY(v0.negativeLookahead(WL)+v0.nonCapturingGroup("-?"+v0.nonCapturingGroup(v0.nonCapturingGroup("0|"+hW)+v0.nonCapturingGroup(Z.decimalPattern)+"?")+(Z.allowDecimalOnly?"|"+Z.decimalPattern:"")+"?")),fW=gW({decimalPattern:zL,allowDecimalOnly:!1}),VL=fW.test.bind(fW),X8=gW({decimalPattern:JL,allowDecimalOnly:!0}),RI=X8.test.bind(X8),qL=/^-?\d*\.?\d*$/,UL=(Z)=>Z.length!==0&&qL.test(Z),D6=bY(v0.negativeLookahead("^-0$")+"-?"+v0.nonCapturingGroup(v0.nonCapturingGroup("0|"+hW))),HL=D6.test.bind(D6),xY=/^-?\d+$/,GL=xY.test.bind(xY),uW={number:"a number",bigint:"a bigint",integer:"an integer"},mW=(Z,Y)=>`'${Z}' was parsed as ${uW[Y]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,KL=(Z,Y)=>Y==="number"?VL(Z):HL(Z),BL=(Z,Y)=>Y==="number"?Number(Z):Number.parseInt(Z),LL=(Z,Y)=>Y==="number"?UL(Z):GL(Z),pW=(Z,Y)=>kY(Z,"number",Y),dW=(Z,Y)=>kY(Z,"number",{...Y,strict:!0}),cW=(Z,Y)=>kY(Z,"integer",Y),kY=(Z,Y,X)=>{let Q=BL(Z,Y);if(!Number.isNaN(Q)){if(LL(Z,Y)){if(X?.strict)return KL(Z,Y)?Q:L(mW(Z,Y));return Q}}return X?.errorOnFail?L(X?.errorOnFail===!0?`Failed to parse ${uW[Y]} from '${Z}'`:X?.errorOnFail):void 0},lW=(Z)=>{if(Z[Z.length-1]!=="n")return;let Y=Z.slice(0,-1),X;try{X=BigInt(Y)}catch{return}if(D6.test(Y))return X;if(xY.test(Y))return L(mW(Z,"bigint"))};var ML="0.56.0",FL={version:ML,filename:xW.fileName(),FileConstructor:SY},O9=FL,iW=new Map,vY=Object.create(null),A6=(Z)=>{let Y=iW.get(Z);if(Y)return Y;let X=NL(Z);if(vY[X])X=`${X}${vY[X]++}`;else vY[X]=1;return O9[X]=Z,iW.set(Z,X),X},s0=(Z)=>/^[$A-Z_a-z][\w$]*$/.test(Z),NL=(Z)=>{switch(typeof Z){case"object":{if(Z===null)break;let Y=F6(Z)??"object";return Y[0].toLowerCase()+Y.slice(1)}case"function":return s0(Z.name)?Z.name:"fn";case"symbol":return Z.description&&s0(Z.description)?Z.description:"symbol"}return u(`Unexpected attempt to register serializable value of type ${F1(Z)}`)};var E6=(Z)=>typeof Z==="string"?JSON.stringify(Z):typeof Z==="bigint"?`${Z}n`:`${Z}`;var oW=(Z,Y={})=>O6(Z,{onUndefined:"$ark.undefined",onBigInt:(X)=>`$ark.bigint-${X}`,...Y},[]);var x=(Z,Y)=>{switch(F1(Z)){case"object":let X=Z,Q=X.constructor?.name??"Object";return Q==="Object"||Q==="Array"?Y?.quoteKeys===!1?Q8(X,Y?.indent??0,""):JSON.stringify(O6(X,o9,[]),null,Y?.indent):Q8(X,Y?.indent??0,"");case"symbol":return o9.onSymbol(Z);default:return E6(Z)}},Q8=(Z,Y,X)=>{if(typeof Z==="function")return o9.onFunction(Z);if(typeof Z!=="object"||Z===null)return E6(Z);let Q=X+" ".repeat(Y);if(Array.isArray(Z)){if(Z.length===0)return"[]";let W=Z.map((J)=>Q8(J,Y,Q)).join(`,
|
|
93
|
-
`+Q);return Y?`[
|
|
94
|
-
${Q}${W}
|
|
95
|
-
${X}]`:`[${W}]`}let $=Z.constructor?.name??"Object";if($==="Object"){let W=D9(Z).map(([J,z])=>{let V=typeof J==="symbol"?o9.onSymbol(J):s0(J)?J:JSON.stringify(J),q=Q8(z,Y,Q);return`${Q}${V}: ${q}`});if(W.length===0)return"{}";return Y?`{
|
|
96
|
-
${W.join(`,
|
|
353
|
+
`:""}
|
|
354
|
+
${t?`## What the reviewers found
|
|
355
|
+
${e.findingIndex||"(nothing)"}
|
|
356
|
+
|
|
357
|
+
`:""}${e.docsFiles.length?`## Documentation-only files (${t?"already excluded from review; ":""}cover them with one \`support\` group)
|
|
358
|
+
${ak(e.docsFiles)}
|
|
359
|
+
`:""}${e.registry?`
|
|
360
|
+
${e.registry}
|
|
361
|
+
`:""}
|
|
362
|
+
## Diff
|
|
363
|
+
\`\`\`diff
|
|
364
|
+
${e.diff}
|
|
365
|
+
\`\`\`
|
|
366
|
+
${e.sketches.length?`
|
|
367
|
+
## Changed files whose diff is not shown above (${e.sketches.length})
|
|
368
|
+
The diff was too large to include whole, so the budget was shared across the groups and these files are given as sketches instead: lines added and removed, the names each one adds, and the functions its edits fall in, with the first changed line as \`name@line\`. You have not read their code. A stop may name one of these files when its sketch, the group it belongs to, or the findings above say enough to explain why it matters; use a \`name@line\` from its sketch as the location. Cover the rest with \`support\` groups, naming directories rather than files.
|
|
369
|
+
${e.sketches.join(`
|
|
97
370
|
`)}
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
371
|
+
`:""}
|
|
372
|
+
Produce two things.
|
|
373
|
+
**1. Inferred intent.** Read the diff and state what it actually does, independently of the description. Then compare the two. \`alignment\` is "aligned" if the diff does what the description says and nothing surprising beyond it, "partial" if it does the stated work plus unstated behavior changes or omits part of what was promised, "misaligned" if the diff's actual effect differs from the description. \`inferred\` is two to four sentences describing the change as you understand it from the code alone \u2014 write it for someone who has not read the description. \`matches\`, \`mismatches\`, \`unstated\` and \`missing\` are short bullet strings; leave them empty rather than padding.
|
|
374
|
+
|
|
375
|
+
**2. A guided walkthrough.**
|
|
376
|
+
- \`start_here\`: the 2-4 files a reviewer should open first, each with a one-line reason. Order matters. Pick the files where understanding the change begins or where the risk concentrates \u2014 not the largest files.
|
|
377
|
+
- \`chapters\`: 1-6 conceptual groups in reading order. A chapter is an idea, not a file. \`title\` is 1-2 words, at most 16 characters ("Runtime", "CLI", "Tests", "Cleanup"). \`icon\` is one of bug, wrench, path, flask, doc, gear. \`blurb\` is one sentence.
|
|
378
|
+
- \`chapters[].stops\`: one review *idea* per stop. \`title\` is 2-6 words, semantic and never a filename \u2014 "Prevent duplicate payments", not "update payments.ts". \`prose\` is 1-3 sentences on why this stop matters and what to check. \`importance\` is "critical" if a reviewer must understand it, "normal" for the main path, "context" for supporting detail. \`locations\` are the file/line pairs to read for this stop, cross-file allowed, in reading order. Total stops across all chapters: 1-3 for a small change, 5-9 for a medium one, 7-12 for a large one. Never exceed 14.
|
|
379
|
+
- \`support\`: changed files deliberately kept off the main path \u2014 generated output, lockfiles, snapshots, mechanical repeats, anything you did not read \u2014 grouped with a reason. A reviewer should be able to skip everything here. **At most 8 groups.** An entry in \`files\` may be a directory path ending in \`/\`, which means every changed file under it that no stop names; prefer that to listing files. Name a file outright only when it is alone in its directory or the reason applies to it and not its neighbours.
|
|
380
|
+
|
|
381
|
+
Account for every changed file: each one should be reachable either from a stop or from a \`support\` entry, where a directory entry covers everything beneath it. Do not enumerate files to prove coverage \u2014 a directory that covers forty files is a better answer than forty filenames, and the guide is read by a human who will not read a list that long. Do not invent files, directories, or lines.
|
|
382
|
+
|
|
383
|
+
Write a single JSON object to \`${e.outFile}\`:
|
|
384
|
+
\`\`\`json
|
|
385
|
+
{
|
|
386
|
+
"focus": "one or two sentences on what reviewing this change is really about",
|
|
387
|
+
"change_type": "fix|feature|refactor|test|docs|mixed",
|
|
388
|
+
"intent": { "inferred": "...", "alignment": "aligned|partial|misaligned",
|
|
389
|
+
"matches": [], "mismatches": [], "unstated": [], "missing": [] },
|
|
390
|
+
"start_here": [ { "file": "...", "why": "..." } ],
|
|
391
|
+
"chapters": [ { "title": "Runtime", "icon": "bug", "blurb": "...",
|
|
392
|
+
"stops": [ { "title": "...", "importance": "critical", "prose": "...",
|
|
393
|
+
"locations": [ { "file": "...", "line": 123, "label": "..." } ] } ] } ],
|
|
394
|
+
"support": [ { "files": ["path/to/dir/", "standalone-file.ts"], "reason": "..." } ]
|
|
395
|
+
}
|
|
396
|
+
\`\`\`
|
|
397
|
+
|
|
398
|
+
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.`}Ir();import Ci from"path";$i();function Ai(e,t=""){let n=e.match(/`+/g)??[],r=Math.max(3,...n.map((o)=>o.length+1)),s="`".repeat(r);return`${s}${t}
|
|
399
|
+
${e.replace(/\n$/,"")}
|
|
400
|
+
${s}`}function Or(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}`}xt();Ir();po();var lk={high:"\uD83D\uDD34",moderate:"\uD83D\uDFE1",low:"\uD83D\uDFE2"};function ck(e){let t=e.repo??vt,n=(b,W)=>`https://github.com/${t}/blob/${e.head}/${b}${W?`#L${W}`:""}`,r=(b,W,_e)=>{let N=_e??`${b.split("/").pop()}${W?`:${W}`:""}`;if(!e.pr)return N.includes("`")?N:`\`${N}\``;return`[${N}](${n(b,W)})`},s=[...e.findings].sort((b,W)=>(ut[b.severity]?.rank??9)-(ut[W.severity]?.rank??9)||Ot[Ze(b.file)]-Ot[Ze(W.file)]||Cr.indexOf(b.confidence)-Cr.indexOf(W.confidence)),o=s.filter((b)=>b.repeat_of),a=s.filter((b)=>!b.repeat_of),l=a.filter((b)=>b._anchor?.kind!=="off-diff"),c=new Map((e.prior??[]).map((b)=>[b.id,b])),u=Qn("summary",{...e.pr?{pr:e.pr}:{},...e.runs?{runs:e.runs}:{}}),d=a.reduce((b,W)=>(b[W.severity]=(b[W.severity]??0)+1,b),{}),f=(b,W,_e)=>{let N=[],ye=ut[b.severity]?.badge??b.severity,pe=Qf[b.category]??b.category,S=b.end_line&&b.end_line!==b.line?`-${b.end_line}`:"",K=W==="summary"?r(b.file,b.line,`${b.file}:${b.line}${S}`):`\`${b.file}:${b.line}${S}\``;if(N.push(`${W==="summary"?"#####":"####"} ${_e??b.title}`),N.push(""),N.push([ye,pe,Yf[b.effort??""],`confidence: ${b.confidence}`,K,Xf[Ze(b.file)]].filter(Boolean).join(" \xB7 ")),W==="inline"&&b._anchor?.kind==="off-hunk")N.push(""),N.push(`> Posted here because GitHub only accepts comments on changed lines. The code this is about is at \`${b.file}:${b.line}${S}\`.`);if(N.push(""),N.push(b.impact?.trim()||ho(b.explanation)),b.explanation)N.push(""),N.push("<details><summary>Why this is a problem</summary>"),N.push(""),N.push(b.explanation),N.push(""),N.push("</details>");if(b.evidence||b.cross_file_refs?.length){if(N.push(""),N.push("<details><summary>Evidence</summary>"),N.push(""),b.evidence)N.push(b.evidence);if(b.cross_file_refs?.length){N.push(""),N.push("Also read:");for(let Y of b.cross_file_refs)N.push(`- \`${Y}\``)}N.push(""),N.push("</details>")}if(b.suggested_code){if(b._original!==void 0){let Ce=b._original.replace(/\n$/,"").split(`
|
|
401
|
+
`).map((Ke)=>`-${Ke}`),St=b.suggested_code.replace(/\n$/,"").split(`
|
|
402
|
+
`).map((Ke)=>`+${Ke}`);N.push(""),N.push("<details><summary>What this changes</summary>"),N.push(""),N.push(Ai([...Ce,...St].join(`
|
|
403
|
+
`),"diff")),N.push(""),N.push("</details>")}N.push("");let Y=W==="inline"&&Zf(b);if(Y)N.push("_Applying this commits it as written \u2014 read it first._"),N.push("");else if(W==="inline"){let Ce=b.end_line&&b.end_line!==b.line?`${b.line}-${b.end_line}`:`${b.line}`;N.push(`_Replaces ${Or(`${b.file}:${Ce}`)}. Not offered as a committable suggestion because this comment is anchored elsewhere._`),N.push("")}N.push(Ai(b.suggested_code,Y?"suggestion":""))}else if(b.suggestion)N.push(""),N.push(`_Suggested fix:_ ${b.suggestion}`);return N.push(""),N.push(W==="inline"?Qn("inline",{file:b.file,line:b.line,fp:Bt(b.file,b.title)}):Qn("summary-item",{file:b.file,line:b.line,fp:Bt(b.file,b.title)})),N.join(`
|
|
404
|
+
`)},p=(b)=>b.replace(/\s+/g," ").trim(),h=Jf(e.changedFiles??[],a),x=(b)=>Ot[Ze(b.file)]<=Ot[h],R=a.filter(x),w=a.filter((b)=>!x(b)),v=(e.inlineMode??"none")==="none"?[]:l.filter(x),y=new Set(v),P=[...R,...w],D=new Map;for(let b of P)D.set(b,D.size+1);let g=[];g.push(`### Review of \`${e.head.slice(0,10)}\``),g.push("");let k=e.unreviewed?.overCap??[],C=e.unreviewed?.failed??[],M=e.unreviewed?.budget??[],I=k.length+C.length+M.length>0;if(I){let b=[k.length?`${k.length} over the slice cap`:"",C.length?`${C.length} in a reviewer that failed`:"",M.length?`${M.length} skipped at the cost limit`:""].filter(Boolean),W=[...C,...M,...k],_e=W.slice(0,5).map((ye)=>`\`${ye}\``).join(", "),N=W.length>5?`, and ${W.length-5} more`:"";g.push(`\u26A0\uFE0F **Partial review:** ${W.length} changed code ${W.length===1?"file was":"files were"} not reviewed (${b.join(", ")}): ${_e}${N}.`),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.":I?"No new issues found in the reviewed files.":"No new issues found in the changed files.");else{let b=(W)=>`${lk[W.level]} **${W.label}** \u2014 ${W.detail}`;g.push(b(Vf(a))),g.push(""),g.push(b(Gf(a.map((W)=>({severity:W.severity,surface:Ze(W.file)}))))),g.push(""),g.push(Object.entries(ut).filter(([W])=>d[W]).map(([W,_e])=>`${_e.badge}: ${d[W]}`).join(" \xB7 "))}g.push("");let F=e.walkthrough,B=F?.intent,L=e.intentAlignment,H={aligned:"\u2705 Matches the description",partial:"\u26A0\uFE0F Partly matches the description",misaligned:"\u274C Does not match the description"},ge=[...B?.unstated??[],...L?.unstated??[]],ke=[...B?.missing??[],...L?.missing??[]],ie=B?.alignment==="aligned"&&L?.summary?"partial":B?.alignment,De=ie?H[ie]:void 0,Pe=L?.summary??B?.mismatches?.[0],we=[],q=[];if(q.push(`# Review of \`${e.head.slice(0,10)}\`${e.pr?` \u2014 PR #${e.pr}`:""}`),q.push(""),q.push("Everything the summary comment links to rather than carries."),q.push(""),De||Pe||B?.inferred||ge.length||ke.length){if(we.push(`**Intent:** ${De??"\u2139\uFE0F Not assessed"}${Pe?` \u2014 ${Pe}`:""}`),B?.inferred)we.push("",`**What it does:** ${ho(B.inferred,320)}`);if(we.push(""),q.push("## What the change actually does, read from the code"),q.push(""),B?.inferred)q.push(B.inferred,"");if(B?.matches?.length){q.push("Description holds up on:");for(let b of B.matches)q.push(`- ${b}`);q.push("")}if(B?.mismatches?.length){q.push("Description does not hold up on:");for(let b of B.mismatches)q.push(`- ${b}`);q.push("")}if(ge.length){q.push("In the diff but not in the description:");for(let b of ge)q.push(`- ${b}`);q.push("")}if(ke.length){q.push("Described but not accomplished:");for(let b of ke)q.push(`- ${b}`);q.push("")}}if(F?.focus)we.push(`**What to focus on:** ${F.focus}`,"");let T=F?.chapters??[],U=T.reduce((b,W)=>b+(W.stops?.length??0),0);if(F?.start_here?.length||U){let b={bug:"\uD83D\uDC1B",wrench:"\uD83D\uDD27",path:"\uD83D\uDEE4\uFE0F",flask:"\uD83E\uDDEA",doc:"\uD83D\uDCC4",gear:"\u2699\uFE0F"},W={critical:" \uD83D\uDD34",normal:"",context:" _(context)_"};if(F?.start_here?.length){we.push("**Start here**"),we.push("");for(let N of F.start_here)we.push(`1. ${r(N.file,void 0,`\`${N.file}\``)} \u2014 ${N.why}`);we.push("")}if(U||F?.support?.length)q.push(`## Guided walkthrough \u2014 ${T.length} ${T.length===1?"part":"parts"}, ${U} ${U===1?"stop":"stops"}`),q.push("");let _e=0;for(let N of T){if(q.push(`### ${b[N.icon??""]??"\u25B8"} ${N.title}`),N.blurb)q.push("",`_${N.blurb}_`);q.push("");for(let ye of N.stops??[]){if(_e++,q.push(`**${_e}. ${ye.title}**${W[ye.importance??"normal"]??""}`),ye.prose)q.push("",ye.prose);if(ye.locations?.length)q.push("",`\u21B3 ${ye.locations.map((pe)=>r(pe.file,pe.line,pe.label)).join(" \xB7 ")}`);q.push("")}}if(F?.support?.length){q.push("### Safe to skim"),q.push("");for(let N of F.support){let ye=N.files.map((pe)=>`\`${pe}\``).join(", ");q.push(`- ${ye} \u2014 ${N.reason}`)}q.push("")}}let Z=(b)=>{let W=new Map;for(let N of b){let ye=W.get(N.file);if(ye)ye.push(N);else W.set(N.file,[N])}let _e=[];for(let[N,ye]of W){_e.push(`- \`${N}\``);for(let pe of ye){let S=ut[pe.severity]?.badge??pe.severity,K=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}`),Y=y.has(pe)?"":` ${Qn("summary-item",{file:pe.file,line:pe.line,fp:Bt(pe.file,pe.title)})}`;_e.push(` - ${S} ${p(pe.title)} \u2014 ${K} \xB7 _[${D.get(pe)}]_${Y}`)}}return _e};if(R.length)g.push(`#### ${Wf[h]} (${R.length})`),g.push(""),g.push(...Z(R)),g.push("");if(w.length)g.push(`<details><summary>Everything else (${w.length}) \u2014 lower-risk surfaces</summary>`),g.push(""),g.push(...Z(w)),g.push(""),g.push("</details>"),g.push("");let fe=e.overCap??[];if(fe.length)g.push(`\u2795 ${fe.length} more ${fe.length===1?"finding":"findings"} past the ${nn}-finding cap,`+" listed under \u201CPast the cap\u201D in the detail file."),g.push("");let ue=e.checked??[];if(g.push(...we),o.length){g.push(`<details><summary>Agreeing with ${o.length} existing review ${o.length===1?"comment":"comments"}</summary>`),g.push("");for(let b of o){let W=c.get(b.repeat_of),_e=W?`@${W.author}`:"an earlier review comment",N=W?.url?`[${_e}](${W.url})`:_e,ye=ut[b.severity]?.badge??b.severity;g.push(`- ${ye} ${p(b.title)} \u2014 \`${b.file}:${b.line}\` _\u2014 agrees with ${N}_`)}g.push(""),g.push("</details>"),g.push("")}if(P.length){q.push("## Evidence and reasoning"),q.push(""),q.push("Numbered to match the bullets in the summary comment."),q.push("");for(let b of P)q.push(f(b,"summary",`[${D.get(b)}] ${p(b.title)}`)),q.push("")}if(fe.length){q.push("## Past the cap"),q.push(""),q.push(`Findings the review kept but did not post, because a review posts at most ${nn}. Ranked below the posted ones by severity, surface and confidence.`),q.push("");for(let b of fe)q.push(f(b,"summary",p(b.title))),q.push("")}if(ue.length){q.push("## What the reviewers checked"),q.push(""),q.push("Claims each reviewer verified against the code and found correct."),q.push("");for(let b of ue)q.push(`- ${b}`);q.push("")}let Fe=process.env.GITHUB_RUN_ID,Xe=process.env.GITHUB_SERVER_URL??"https://github.com",Te=e.detailFile??"review-detail.md";if(P.length||U||fe.length||ue.length>8)g.push(Fe?`\uD83D\uDCC4 **[Full review detail](${Xe}/${t}/actions/runs/${Fe})** \u2014 download the`+` \`ai-code-review-${e.pr}-${e.head.slice(0,9)}\` artifact and open \`${Te}\` for the walkthrough and the evidence behind each finding. Artifacts expire 90 days after the run.`:`\uD83D\uDCC4 Full walkthrough and evidence: \`${e.detailPath??Te}\`.`),g.push("");if(ue.length&&a.length<=2&&!e.noReviewers){g.push(`<details><summary>What the reviewers checked (${ue.length})</summary>`),g.push("");for(let b of ue.slice(0,8))g.push(`- ${b}`);if(ue.length>8)g.push(`- \u2026and ${ue.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 b of e.dropped)g.push(`- **${b.title}** \u2014 ${b.reason}`);g.push(""),g.push("</details>"),g.push("")}g.push("<details><summary>Review details</summary>"),g.push("");for(let[b,W]of Object.entries(e.stats))g.push(`- ${b}: ${W}`);if(g.push(""),e.pr&&!e.local)g.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."),g.push("");g.push("</details>"),g.push(""),g.push(u);let zt=v.map((b)=>f(b,"inline")),Rn=o.map((b)=>{let W=b.repeat_of,_e=c.get(W),N=[];N.push(`Checked this against \`${e.head.slice(0,10)}\` \u2014 still open. ${ut[b.severity]?.badge??b.severity}`);let ye=b.impact?.trim()||ho(b.explanation,240);if(ye)N.push("",ye);let pe=[b.explanation,b.evidence].filter(Boolean).join(`
|
|
405
|
+
|
|
406
|
+
`);if(pe)N.push("","<details><summary>What I found</summary>","",pe,"","</details>");return N.push("",Qn("reply",{of:W,fp:Bt(b.file,b.title)})),{comment_id:W,author:_e?.author,url:_e?.url,finding:b,body:N.join(`
|
|
407
|
+
`)}});for(let b of e.resolved??[]){let W=c.get(b.id);if(!W?.mine||!W.file)continue;let _e=b.note?.trim();Rn.push({comment_id:b.id,author:W.author,url:W.url,body:[`\u2705 Fixed as of \`${e.head.slice(0,10)}\`.${_e?` ${_e}`:""}`,"",Qn("reply",{of:b.id,addressed:1})].join(`
|
|
408
|
+
`)})}return{summary:dk(g.join(`
|
|
409
|
+
`),u),detail:q.join(`
|
|
410
|
+
`),inline:zt,ordered:v,replies:Rn}}async function uk(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(`
|
|
411
|
+
`))}catch{s.set(a.file,null)}let l=s.get(a.file),c=a.end_line!==void 0?Math.max(a.line,a.end_line):a.line,u=a.end_line!==void 0?Math.min(a.line,a.end_line):a.line;if(!l||u<1||c>l.length){o.push(a);continue}o.push({...a,_original:l.slice(u-1,c).join(`
|
|
412
|
+
`)})}return o}var fp=65536;function dk(e,t){if(e.length<=fp)return e;let n=`
|
|
413
|
+
|
|
414
|
+
---
|
|
415
|
+
|
|
416
|
+
_Truncated to fit GitHub's comment size limit. The full review is in the run artifact._
|
|
417
|
+
|
|
418
|
+
`,r=`
|
|
419
|
+
</details>`,s=((e.match(/<details/g)??[]).length+1)*r.length,o=fp-n.length-t.length-s-1,a=e.slice(0,o),l=a.lastIndexOf(`
|
|
420
|
+
|
|
421
|
+
`),c=a.slice(0,l>o/2?l:a.length),u=(c.match(/<details/g)??[]).length-(c.match(/<\/details>/g)??[]).length,d=u>0?`
|
|
422
|
+
${r.repeat(u)}`:"";return`${c}${d}${n}${t}`}async function Pl(e){let t=e.findings,n=[];if(e.repoDir){t=await uk(e.repoDir,e.head,t);try{let f=await Pd(e.repoDir,e.base,e.head);n=[...f.keys()],t=t.map((h)=>({...h,_anchor:Td(f,h.file,h.line,h.end_line)}));let p=t.filter((h)=>h._anchor?.kind!=="anchorable");for(let h of p)console.error(` anchor: ${h.file}:${h.line} is ${h._anchor?.kind}`+(h._anchor?.line?` \u2192 line ${h._anchor.line}`:" \u2192 summary comment"))}catch(f){console.warn(` could not read diff for anchoring, using model line numbers: ${f}`)}}let r=`${e.tag}.detail.md`,{summary:s,detail:o,inline:a,ordered:l,replies:c}=ck({pr:e.pr,detailFile:r,detailPath:Ci.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:Fd,local:e.local}),u=e.local?kl([s,...a.length?["","## Line comments","",...a.flatMap((f)=>[f,"","---",""])]:[]].join(`
|
|
423
|
+
`))+`
|
|
424
|
+
`:["# Summary comment","",s,"","---","","# Inline comments","",...l.map((f,p)=>[`<!-- inline ${p+1} of ${l.length} \u2014 ${f.file}:${f.line}${f._anchor&&f._anchor.line!==f.line?` (anchored at line ${f._anchor.line})`:""} -->`,"",a[p],"","---",""].join(`
|
|
425
|
+
`)),...c.length?["# Replies to existing review comments","",...c.map((f,p)=>[`<!-- reply ${p+1} of ${c.length} \u2014 to ${f.author?`@${f.author}`:"comment"} ${f.comment_id}${f.finding?` on ${f.finding.file}:${f.finding.line}`:" \u2014 closing it out as fixed"} -->`,"",...f.url?[`In reply to ${f.url}`,""]:[],f.body,"","---",""].join(`
|
|
426
|
+
`))]:[]].join(`
|
|
427
|
+
`);if(await Ve(Ci.join(e.dir,`${e.tag}.md`),u),await Ve(Ci.join(e.dir,r),e.local?`${kl(o)}
|
|
428
|
+
`:o),!e.pr||e.local){if(await Lt(Ci.join(e.dir,`${e.tag}.payloads.json`)),!e.local)console.error(" local review: no pull request, so no API payloads written");return{summary:s,inline:a,ordered:l}}let d={summary:{method:"POST",endpoint:`repos/${e.slug}/issues/${e.pr}/comments`,body:{body:s}},review:{method:"POST",endpoint:`repos/${e.slug}/pulls/${e.pr}/reviews`,body:{commit_id:e.head,event:"COMMENT",comments:l.map((f,p)=>{let h=f._anchor,x=f.end_line!==void 0?Math.min(f.line,f.end_line):f.line,R=f.end_line!==void 0?Math.max(f.line,f.end_line):f.line,w=R!==x;return{path:f.file,line:h?.line??R,...h?h.start_line!==void 0?{start_line:h.start_line}:{}:w?{start_line:x}:{},side:"RIGHT",body:a[p]}})}},replies:c.map((f)=>({method:"POST",endpoint:`repos/${e.slug}/pulls/${e.pr}/comments/${f.comment_id}/replies`,body:{body:f.body}}))};return await Gn(Ci.join(e.dir,`${e.tag}.payloads.json`),d),{summary:s,inline:a,ordered:l}}xt();Si();Ir();async function pp(e){if(e.config)Js(e.config);let{signal:t}=e;if(t?.aborted)throw new It;let n=()=>void Ar();if(t?.addEventListener("abort",n,{once:!0}),t)vr({signal:t});try{return await fk(e)}finally{t?.removeEventListener("abort",n),await Ar(),await Gs(),Xs()}}async function fk(e){let t=(A)=>e.onProgress?.(A),{signal:n,maxCostUsd:r}=e,s=()=>{if(n?.aborted)throw new It},o=0,a=(A)=>{o+=A,t({type:"cost",totalUsd:o})};t({type:"stage",stage:"resolving_target"});let l=e.repo,{pr:c,base:u,head:d,slug:f}=e.target,p=Uf({pr:c,base:u,head:d}),h=e.tag,x=rt.join(Re,"reviews",`${h}.md`);await un(Et);for(let A of["runs","raw","logs","prompts","reviews","maps"])await un(rt.join(Re,A));await Ve(rt.join(Re,".gitignore"),`*
|
|
429
|
+
`);let R=await Lf(l,c,d);vr({subject:R.dir,releaseSubject:R.release});let w=Date.now();vr({repoName:f});let v=await ro(f,c,u,d);if(e.intent)v.body=v.body?`${v.body}
|
|
430
|
+
|
|
431
|
+
${e.intent}`:e.intent;let y=[...await Rf(f,c),...e.prior??[]],P=$f(y,v.body),D=Math.max(0,...y.filter((A)=>A.mine).map((A)=>A.runs??0));s(),t({type:"stage",stage:"checking_registry"});let g=await Bd({repo:Ye,base:u,head:d}),k=qd(g.findings),C=rt.join(Re,"maps",`${p}.md`),M="",I=await Ad(C);if(t({type:"stage",stage:"building_map"}),!I)try{let A=await yf({repo:Ye,base:u,head:d});await Ve(C,A.markdown),await Gn(rt.join(Re,"maps",`${p}.meta.json`),A.meta),I=!0}catch(A){console.error(`repo map unavailable, continuing without it: ${A}`)}if(I)M=`A repository orientation map for this change is at \`${C}\`. 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.
|
|
432
|
+
`;s();let F=(await Rt(["diff","--name-only",`${u}..${d}`])).trim().split(`
|
|
433
|
+
`).filter(Boolean),B={skip:[],docs:[],code:[]};for(let A of F)B[Er(A)].push(A);let L=B.code;if(L.length===0)return console.error(` ${F.length} changed files, none reviewable \u2014 no review`),await Pl({dir:rt.join(Re,"reviews"),tag:h,slug:f,pr:c,base:u,head:d,findings:[],stats:{"changed files":String(F.length),reviewed:"nothing: no code files in this change"},repoDir:Ye,local:e.local}),{record:null,units:[],byClass:B,findings:[],costUsd:0,wallMs:Date.now()-w,markdownPath:x};t({type:"stage",stage:"grouping"});let H=`${h}-part`,ge=`${Et}/${H}.json`;await Lt(ge);let{wholeDiff:ke,diffstat:ie,diffU0:De,fileTokens:Pe,facts:we,links:q,grouping:T}=await so({base:u,head:d,files:L,source:()=>Zs(Ye)}),U=await kf(u,d,L),Z=Jn==="code"?T:void 0,fe=Z?dp({groups:Z.groups,links:q,outline:U,intent:v,registry:k,outFile:ge}):up({diffstat:ie,outline:U,intent:v,codeFiles:L,registry:k,outFile:ge});await Ve(rt.join(Re,"prompts",`${H}.txt`),fe);let ue=Z?.groups.length===1,Fe={wallMs:0,costUsd:0,numTurns:0,payload:void 0};if(!ue)Fe=await tr(fe,{budget:nl,outFile:ge,tag:H,model:pn,effort:dn}),a(Fe.costUsd);s();let Xe=[],Te;if(Z&&ue)Te=[{id:Z.groups[0].id,title:v.title||Z.groups[0].id,files:Z.groups[0].files,priority:1}];else if(Z){let A=Mf(Z.groups,Fe.payload,Cn,Pe);Xe=A.moves,Te=Ol(A.units,L);for(let X of Xe)console.error(` moved ${X.file}: ${X.from} -> ${X.to} (${X.reason})`)}else{let A=Fe.payload??void 0;Te=Ol(A?.review_units??[],L)}let zt=new Set(g.findings.map((A)=>A.addedIn)),Rn=new Map(Te.map((A)=>[A.id,A.files.reduce((X,ee)=>X+(Pe.get(ee)??0),0)])),b=[...Te].sort((A,X)=>{let ee=Number(A.files.some((cn)=>zt.has(cn))),Kn=Number(X.files.some((cn)=>zt.has(cn)));if(ee!==Kn)return Kn-ee;let Jt=A.priority??5,Sn=X.priority??5;if(Jt!==Sn)return Jt-Sn;return(Rn.get(X.id)??0)-(Rn.get(A.id)??0)}),W=new Map(b.map((A,X)=>[A.id,X])),_e=cp(b,Pe,Cn).sort((A,X)=>A.part-X.part||(W.get(A.unitId)??0)-(W.get(X.unitId)??0)),N=_e.slice(0,wr),ye=_e.slice(wr).flatMap((A)=>A.files),pe=N.filter((A)=>A.tokens>Cn);console.error(`${c?`PR ${c} `:""}${u.slice(0,8)}..${d.slice(0,8)} \u2014 ${F.length} changed (${L.length} code, ${B.docs.length} docs, ${B.skip.length} skipped) -> ${Te.length} units, ${N.length} slices${ye.length?`, ${ye.length} files over cap`:""}${pe.length?`, ${pe.length} over ${Cn} tokens`:""}, registry signals: ${g.findings.length}, prior comments: ${y.length}`);for(let A of N)console.error(` slice ${A.unitId}${A.parts>1?` ${A.part}/${A.parts}`:""} (${A.tokens} tokens): ${A.files.join(", ")}`);let S=[],K=[],Y=[];t({type:"units",units:Te,byClass:B}),t({type:"stage",stage:"reviewing"});let Ce=0,St=!1,Ke=[];async function si(A){while(!0){if(n?.aborted)return;if(r!==void 0&&o>=r&&Ce<N.length){let bt=N.slice(Ce);Ce=N.length,St=!0,Ke=bt.flatMap((zw)=>zw.files),console.error(` cost $${o.toFixed(2)} reached --max-cost $${r.toFixed(2)}: ${bt.length} slice(s) not started`),t({type:"budget",totalUsd:o,limitUsd:r,skippedSlices:bt.length});return}let X=Ce++;if(X>=N.length)return;let ee=N[X],Kn={id:ee.unitId,title:ee.title,rationale:ee.rationale,files:ee.files,priority:ee.priority},Jt=`${h}-s${String(X).padStart(2,"0")}`,Sn=zn(await Rt(["diff",`${u}..${d}`,"--",...ee.files]),u);if(!Sn.trim())continue;let cn=`${Et}/${Jt}.json`;await Lt(cn);let wt=ap({unit:Kn,diff:Sn,intent:v,registry:k,prior:P,mapNote:M,outFile:cn,crossLinks:Pf(ee.files,q)});await Ve(rt.join(Re,"prompts",`${Jt}.txt`),wt);let Wn={type:"slice",index:X,total:N.length,title:ee.title};t({...Wn,status:"started"});let ze;try{ze=await tr(wt,{budget:rl,outFile:cn,tag:Jt}),a(ze.costUsd)}catch(bt){console.error(` [w${A}] ${ee.unitId} \u2014 failed to run: ${bt instanceof Error?bt.message:String(bt)}`),S.push({unit:ee.unitId,part:ee.part,parts:ee.parts,tokens:ee.tokens,files:ee.files,tag:Jt,wallMs:0,costUsd:0,numTurns:0,exitCode:-1,findingCount:0,ok:!1}),t({...Wn,status:"failed"});continue}let ja=ze.payload,Ns=Array.isArray(ja)?ja:ja?.findings??[],ui=(Array.isArray(Ns)?Ns:[]).filter((bt)=>typeof bt==="object"&&bt!==null);if(ui.length!==(Array.isArray(Ns)?Ns.length:0))console.error(` [w${A}] ${ee.unitId} \u2014 discarded malformed entries from the findings file`);for(let bt of ui)bt._slice=ee.unitId,K.push(bt);let zu=np(ze.payload);Y[X]=zu,S.push({unit:ee.unitId,part:ee.part,parts:ee.parts,tokens:ee.tokens,files:ee.files,tag:Jt,wallMs:ze.wallMs,costUsd:ze.costUsd,numTurns:ze.numTurns,usage:ze.usage,tools:ze.tools,checked:zu,exitCode:ze.exitCode,findingCount:ui.length,ok:ze.payload!==null}),console.error(` [w${A}] ${ee.unitId}${ee.parts>1?` ${ee.part}/${ee.parts}`:""} (${ee.files.length}f ${ee.tokens}t) \u2014 ${(ze.wallMs/1000).toFixed(0)}s $${ze.costUsd.toFixed(2)} ${ze.numTurns}t ${ui.length} findings`),t({...Wn,status:ze.payload!==null?"ok":"failed",costUsd:ze.costUsd,wallMs:ze.wallMs,findings:ui.length})}}await Promise.all(Array.from({length:Math.min(sl,N.length)},(A,X)=>si(X))),s();let tt=S.filter((A)=>A.ok??A.exitCode===0);if(S.length>0&&tt.length===0)throw Error(`all ${S.length} review slices failed \u2014 no review was produced. `+`Run \`diffloupe doctor\` to check credentials, and see the agent output in ${rt.join(Re,"raw")} and ${rt.join(Re,"logs")}`);if(tt.length<S.length)console.error(` warning: ${S.length-tt.length} of ${S.length} slices failed`);let $n=K;if(K.length>20)$n=K.filter((A)=>!(A.severity==="nice-to-have"&&A.confidence!=="high"));let Ea=K.length-$n.length,Aa=`${h}-merge`,Ca=`${Et}/${Aa}.json`;await Lt(Ca);let ju=lp({findings:$n,intent:v,files:L,prior:P,outFile:Ca});await Ve(rt.join(Re,"prompts",`${Aa}.txt`),ju);let Bw=rp($n.length,il),Ia=`${h}-walk`,Oa=`${Et}/${Ia}.json`;await Lt(Oa);let Is=b.filter((A)=>N.some((X)=>X.unitId===A.id)),qw=new Set(Is.flatMap((A)=>A.files)),Uu=_e.flatMap((A)=>A.files).filter((A)=>!qw.has(A)),Hw=[...Is,...Uu.length?[{files:[...new Set(Uu)]}]:[]],{shown:Pa,sketched:pr}=lo(Hw,Pe,gi),Kw=Pa.reduce((A,X)=>A+(Pe.get(X)??0),0),Ww=pr.length?zn(await Rt(["diff",`${u}..${d}`,"--",...Pa]),u):ke;if(pr.length)console.error(` walkthrough sees ${Pa.length} of ${L.length} files (${Kw} tokens), ${pr.length} given as sketches`);let Vw=oo(De,we),Bu=mo({diffstat:ie,diff:Ww,sketches:pr.map((A)=>ao(Vw.get(A)??{file:A,added:0,removed:0,defines:[],touches:[]})),crossLinks:uo(Is,q),intent:v,findingIndex:$n.map((A)=>`- [${A.severity}] ${A.file}:${A.line} \u2014 ${A.title}`).join(`
|
|
434
|
+
`),unitSummary:Is.map((A)=>{let X=co(A.files,q);return`**${A.title}** (${A.id})
|
|
435
|
+
${A.files.map((ee)=>` - ${ee}`).join(`
|
|
436
|
+
`)}`+(X.length?`
|
|
437
|
+
Links: ${X.join("; ")}`:"")}).join(`
|
|
438
|
+
|
|
439
|
+
`),docsFiles:B.docs,registry:k,outFile:Oa});await Ve(rt.join(Re,"prompts",`${Ia}.txt`),Bu);let qu=(A)=>(X)=>(console.error(` ${A} failed to run: ${X instanceof Error?X.message:String(X)}`),{wallMs:0,exitCode:-1,costUsd:0,numTurns:0,usage:null,payload:null}),Gw={wallMs:0,exitCode:0,costUsd:0,numTurns:0,usage:null,payload:null},Ma=!sp($n,y);if(Ma)console.error(" coordinator skipped: no findings and no earlier comments to close out");t({type:"stage",stage:"coordinating"}),t({type:"stage",stage:"walkthrough"});let[Hn,oi]=await Promise.all([Ma?Promise.resolve({...Gw,payload:{keep:[]}}):tr(ju,{budget:Bw,outFile:Ca,tag:Aa,model:Xn,effort:dn}).then((A)=>(a(A.costUsd),A)).catch(qu("coordinator")),tr(Bu,{budget:mi,outFile:Oa,tag:Ia,model:pn,effort:dn}).then((A)=>(a(A.costUsd),A)).catch(qu("walkthrough"))]);s();let Os=oi.payload??void 0,hr=Hn.payload??{},ai=[],Ta=[],li=Ma?"nothing-to-merge":"coordinator",Hu=tp(y),Na=(A)=>{if(!Hu.size)return A;return A.filter((X)=>{let ee=Hu.get(Bt(X.file,X.title));if(!ee)return!0;return Ta.push({title:X.title,reason:`already posted on an earlier push (comment ${ee.id})`}),console.error(` suppressed "${X.title}" \u2014 same claim as comment ${ee.id}`),!1})},Da=new Set,Ps=[];if(hr.keep){let A=op(hr,$n,y);Ta=A.dropped;let X=(wt,Wn)=>(ut[wt.severity]?.rank??9)-(ut[Wn.severity]?.rank??9)||Ot[Ze(wt.file)]-Ot[Ze(Wn.file)]||Cr.indexOf(wt.confidence)-Cr.indexOf(Wn.confidence),ee=A.kept.sort(X);Da=new Set([...ee,...A.capped].map((wt)=>Bt(wt.file,wt.title)));let Kn=Na(ee),Jt=Kn.filter((wt)=>wt.repeat_of),Sn=Kn.filter((wt)=>!wt.repeat_of),cn=Sn.slice(0,nn);Ps=[...Sn.slice(nn),...Na(A.capped.sort(X))],ai=[...cn,...Jt].sort(X)}if(!hr.keep){li="deterministic-fallback";let A=ip($n);Da=new Set(A.map((ee)=>Bt(ee.file,ee.title)));let X=Na(A).map((ee)=>({...ee,repeat_of:void 0}));ai=X.slice(0,nn),Ps=X.slice(nn)}let Ms=(hr.resolved??[]).filter((A)=>{let X=y.find((ee)=>ee.id===A.id);if(!X?.mine)return!1;if(!X.file)return!1;return!(X.fingerprint&&Da.has(X.fingerprint))});if(Ms.length)console.error(` closing out ${Ms.length} earlier comments as fixed`);t({type:"stage",stage:"verifying"});let ci=[],Ts=[...Ta];for(let A of ai){let X=rt.join(Ye,A.file),ee=await Cd(X);if(ee===null){Ts.push({title:A.title,reason:`cited file does not exist: ${A.file}`});continue}if(A.line<1||A.line>ee){Ts.push({title:A.title,reason:`cited line ${A.line} outside ${A.file} (${ee} lines)`});continue}ci.push(A)}let Ku={overCap:ye,failed:S.filter((A)=>!(A.ok??A.exitCode===0)).flatMap((A)=>A.files??[]),budget:Ke},Wu=Y.flat().filter(Boolean),Fa=S.reduce((A,X)=>A+X.costUsd,0)+Hn.costUsd+oi.costUsd,La=Date.now()-w,Vu={"review units":N.length,"code files reviewed":N.reduce((A,X)=>A+X.files.length,0),"docs files not reviewed":B.docs.length,"generated files skipped":B.skip.length,"raw findings":K.length,"after merge":ai.length,"after verification":ci.length,"registry signals":g.findings.length,"prior comments considered":y.length,"wall time":`${(La/60000).toFixed(1)} min`,cost:`$${Fa.toFixed(2)}`,model:fn,...Xn!==fn?{"coordinator model":Xn}:{},"walkthrough model":pn,"walkthrough stops":Os?(Os.chapters??[]).reduce((A,X)=>A+(X.stops?.length??0),0):"none \u2014 the walkthrough produced no guide",...pr.length?{"walkthrough did not read":`${pr.length} of ${L.length} files`}:{},...ye.length?{"not reviewed (over cap)":ye.join(", ")}:{},...St?{"not reviewed (cost limit)":Ke.join(", ")}:{},...Ea?{"trimmed before merge":`${Ea} low-confidence nice-to-have`}:{},...tt.length<S.length?{"slices that failed":`${S.length-tt.length} of ${S.length} \u2014 this review is incomplete`}:{},...li!=="coordinator"&&li!=="nothing-to-merge"?{merging:`${li} \u2014 findings are unverified`}:{}};t({type:"stage",stage:"writing"}),await Pl({dir:rt.join(Re,"reviews"),tag:h,slug:f,pr:c,base:u,head:d,findings:ci,intentAlignment:hr.intent_alignment,dropped:Ts,stats:Vu,walkthrough:Os,prior:y,resolved:Ms,runs:D+1,noReviewers:S.length===0,unreviewed:Ku,checked:Wu,overCap:Ps,repoDir:Ye,local:e.local});let Gu={pr:c,base:u,head:d,runner:Nd,model:fn,effort:yr,effortAux:dn,models:{review:fn,coordinator:Xn,walkthrough:pn},tag:h,wallMs:La,totalCostUsd:Fa,mergeMode:li,preTrimmed:Ea,budgetStopped:St,sliceRuns:S,merge:{wallMs:Hn.wallMs,costUsd:Hn.costUsd,numTurns:Hn.numTurns,tools:"tools"in Hn?Hn.tools:void 0},walk:{model:pn,wallMs:oi.wallMs,costUsd:oi.costUsd,numTurns:oi.numTurns},walkthrough:Os??null,grouping:Jn,groupMoves:Xe,reviewUnits:N,registry:{meta:g.meta,findings:g.findings},priorComments:y.length,prior:y,rawFindings:K,mergedFindings:ai,verifiedFindings:ci,overCapFindings:Ps,checked:Wu,unreviewed:Ku,resolved:Ms,runs:D+1,rejected:Ts,intentAlignment:hr.intent_alignment??null,stats:Vu};return await Gn(rt.join(Re,"runs",`${h}.json`),Gu),{record:Gu,units:Te,byClass:B,findings:ci,costUsd:Fa,wallMs:La,markdownPath:x}}import Pr from"path";xt();Si();import{spawn as pk}from"child_process";import{posix as hk}from"path";function Ii(e,t,n,r){return new Promise((s,o)=>{let a=pk("git",["-C",e,...t],{stdio:[n===void 0?"ignore":"pipe","pipe","pipe"],...r?{env:{...process.env,...r}}:{}}),l=[],c=[];if(a.stdout?.on("data",(u)=>l.push(u)),a.stderr?.on("data",(u)=>c.push(u)),a.on("error",o),a.on("close",(u)=>{if(u===0)s(Buffer.concat(l));else o(Error(`git ${t.join(" ")} exited ${u}
|
|
440
|
+
${Buffer.concat(c).toString("utf8").slice(0,2000)}`))}),n!==void 0)a.stdin?.on("error",()=>{}),a.stdin?.end(n)})}async function mk(e,t){let n=(await Ii(e,["ls-tree","-r","-z",t])).toString("utf8"),r=new Map;for(let s of n.split("\x00")){let o=s.indexOf("\t");if(o<0)continue;let[,a,l]=s.slice(0,o).split(" ");if(a==="blob"&&l)r.set(s.slice(o+1),l)}return r}async function gk(e,t){if(t.length===0)return;let n=(await Ii(e,["config","--get","extensions.partialClone"]).catch(()=>Buffer.alloc(0))).toString("utf8").trim();if(!n)return;let s=(await Ii(e,["cat-file","--batch-check"],`${t.join(`
|
|
441
|
+
`)}
|
|
442
|
+
`,{GIT_NO_LAZY_FETCH:"1"})).toString("utf8").split(`
|
|
443
|
+
`).flatMap((o)=>o.endsWith(" missing")?[o.slice(0,o.indexOf(" "))]:[]);if(s.length===0)return;await Ii(e,["-c","fetch.negotiationAlgorithm=noop","fetch","-q","--no-tags","--no-write-fetch-head","--recurse-submodules=no","--filter=blob:none","--stdin",n],`${s.join(`
|
|
444
|
+
`)}
|
|
445
|
+
`)}async function _k(e,t,n){let r=n.filter((l)=>!l.includes(`
|
|
446
|
+
`)),s=new Map;if(r.length===0)return s;let o=await Ii(e,["cat-file","--batch"],r.map((l)=>`${t}:${l}
|
|
447
|
+
`).join("")),a=0;for(let l of r){let c=o.indexOf(10,a);if(c<0)break;let u=o.subarray(a,c).toString("utf8");if(a=c+1,u.endsWith(" missing")||u.endsWith(" ambiguous"))continue;let d=Number(u.split(" ")[2]);if(!Number.isFinite(d))break;if(u.split(" ")[1]==="blob")s.set(l,o.subarray(a,a+d).toString("utf8"));a+=d+1}return s}var yk=/^(?:(?:tsconfig|jsconfig).*\.json|package\.json)$/;async function hp(e,t,n){let r=await mk(e,t),s=new Set(r.keys()),o=[...s].filter((c)=>yk.test(hk.basename(c))),a=[...new Set([...n.filter((c)=>s.has(c)),...o])];await gk(e,a.map((c)=>r.get(c)??"").filter(Boolean));let l=await _k(e,t,a);return{paths:s,read:(c)=>l.get(c)}}Tl();async function bp(e){if(e.config)Js(e.config);let{signal:t}=e;if(t?.aborted)throw new It;let n=()=>void Ar();t?.addEventListener("abort",n,{once:!0}),vr({subject:e.repo,repoName:e.target.slug??Pr.basename(e.repo),...t?{signal:t}:{}});try{return await kk(e)}finally{t?.removeEventListener("abort",n),await Ar(),Xs()}}async function kk(e){let t=(ie)=>e.onProgress?.(ie),n=()=>{if(e.signal?.aborted)throw new It},r=Date.now(),{base:s,head:o,pr:a,slug:l}=e.target,c=`${s}..${o}`;t({type:"stage",stage:"grouping"});let u=(await Rt(["diff","--name-only",c])).trim().split(`
|
|
448
|
+
`).filter(Boolean),d={skip:[],docs:[],code:[]};for(let ie of u)d[Er(ie)].push(ie);let f=(ie,De=null,Pe=0)=>({record:De,units:ie,byClass:d,costUsd:Pe,wallMs:Date.now()-r});if(!d.code.length)return t({type:"units",units:[],byClass:d}),f([]);let{wholeDiff:p,diffstat:h,diffU0:x,fileTokens:R,facts:w,links:v,grouping:y}=await so({base:s,head:o,files:d.code,source:(ie)=>hp(e.repo,o,ie)}),P=go(y.groups,(ie)=>R.get(ie)??0),D=y.groups.map((ie,De)=>({id:ie.id,title:P[De]??ie.id,files:ie.files,priority:De+1}));if(t({type:"units",units:D,byClass:d}),n(),!e.walkthrough)return f(D);t({type:"stage",stage:"walkthrough"}),await un(Et),await un(Pr.join(Re,"prompts")),await un(Pr.join(Re,"logs")),await Ve(Pr.join(Re,".gitignore"),`*
|
|
449
|
+
`);let g=await ro(l,a,s,o);if(e.intent)g.body=g.body?`${g.body}
|
|
450
|
+
|
|
451
|
+
${e.intent}`:e.intent;let k=`${e.tag}-walk`,C=Pr.join(Et,`${k}.json`);await Lt(C);let{shown:M,sketched:I}=lo(D,R,gi),F=I.length?zn(await Rt(["diff",c,"--",...M]),s):p,B=oo(x,w),L=mo({diffstat:h,diff:F,sketches:I.map((ie)=>ao(B.get(ie)??{file:ie,added:0,removed:0,defines:[],touches:[]})),crossLinks:uo(D,v),intent:g,unitSummary:D.map((ie)=>{let De=co(ie.files,v);return`**${ie.title}** (${ie.id})
|
|
452
|
+
${ie.files.map((Pe)=>` - ${Pe}`).join(`
|
|
453
|
+
`)}`+(De.length?`
|
|
454
|
+
Links: ${De.join("; ")}`:"")}).join(`
|
|
455
|
+
|
|
456
|
+
`),docsFiles:d.docs,registry:"",outFile:C});await Ve(Pr.join(Re,"prompts",`${k}.txt`),L);let H=await tr(L,{budget:mi,outFile:C,tag:k,model:pn,effort:dn,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:H.costUsd});let ge=H.payload??void 0;if(!ge)t({type:"log",message:" walkthrough returned no guide"});let ke=Date.now()-r;return f(D,ge?{walkthrough:ge,wallMs:ke,totalCostUsd:H.costUsd}:null,H.costUsd)}function Sp(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 Ep(e){return{type:"groups",groups:e.groups,files:e.files.map((t)=>({path:t.path,groupId:t.groupId,classification:t.classification}))}}import IE from"os";import Ge from"path";import{appendFile as bq,mkdir as OE,readdir as ls,readFile as Zg,rm as Xg,writeFile as Qg}from"fs/promises";var Pn=(e)=>Array.isArray(e)?e:[e],Ap=(e,t)=>{let n=[[],[]];for(let r of e)if(t(r))n[0].push(r);else n[1].push(r);return n},wo=Array,Pt=(e,t)=>e.includes(t),Cp=(e,t=0)=>[...Array(e)].map((n,r)=>r+t),de=(e,t,n)=>{if(e===void 0)return t===void 0?[]:Array.isArray(t)?t:[t];if(n?.prepend)if(Array.isArray(t))e.unshift(...t);else e.unshift(t);else if(Array.isArray(t))e.push(...t);else e.push(t);return e},gn=(e,t)=>{if(t===void 0||t===null)return e??[];if(e===void 0||e===null)return Pn(t);return e.concat(t)},Ip=(...e)=>e.reduce(gn,[]),rn=(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 Pn(t))if(!e.some((o)=>r(o,s)))e.push(s);return e},Op=(e,t)=>e.reduce((n,r)=>{let s=r[t];return n[s]=de(n[s],r),n},{}),_n=(e,t,n)=>e.length===t.length&&e.every(n?.isEqual?(r,s)=>n.isEqual(r,t[s]):(r,s)=>r===t[s]);var dt=(e,t)=>Be(e)===t,Be=(e)=>{let t=typeof e;return t==="object"?e===null?"null":"object":t==="function"?"object":t},ft={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},Pp={...ft,function:"a function"};class Mp extends Error{}var he=(e)=>nr(e,Mp),nr=(e,t=Error)=>{throw new t(e)};class Pi extends Error{name="ParseError"}var E=(e)=>nr(e,Pi),qt=(e)=>` ${e}`,Tp="\u200B";var ne=(e,t)=>{let n={},r=Array.isArray(e),s=!1;for(let[o,a]of Object.entries(e).entries()){let l=r?t(o,a[1]):t(...a,o);s||=typeof l[0]==="number";let c=Array.isArray(l[0])||l.length===0?l:[l];for(let[u,d]of c)if(typeof u==="object")n[u.group]=de(n[u.group],d);else n[u]=d}return s?Object.values(n):n};var Fl=Object.entries;var qe=(e,t)=>(e in t),Tr=(e,t)=>(t in e);class Ll{constructor(e){Object.assign(this,e)}}var Np=class{};class Mi extends Np{}var Rk=(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 bo=(e,t)=>Rk(e,t)[1],sn=(e)=>Object.keys(e).length===0,rr=(e)=>[...Object.entries(e),...Object.getOwnPropertySymbols(e).map((t)=>[t,e[t]])],Dp=(e,t)=>Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)),Fp=(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 pt=qt(`unset${Tp}`),Lp=(e)=>Object.values(e).filter((t)=>{if(typeof t==="number")return!0;return typeof e[t]!=="number"});var jl={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},Ul=globalThis.File??Blob,Bl={ArrayBuffer,Blob,File:Ul,FormData,Headers,Request,Response,URL},$k={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},ir={...jl,...Bl,...$k,String,Number,Boolean},Ti=(e)=>{let t=Object.getPrototypeOf(e);while(t?.constructor&&(!qe(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},Ni=(e)=>typeof e==="object"&&e!==null?Ti(e)??"object":Be(e);var ve=Array.isArray,Sk={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"},Ek={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"},Ak={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"},jp={...Sk,...Ek,...Ak},Di=(e)=>{let t=Object(e).name??null;return t&&qe(t,ir)&&ir[t]===e?t:null};var ql=(e,t)=>{let n=e.prototype;while(n!==null){if(n===t.prototype)return!0;n=Object.getPrototypeOf(n)}return!1};var Up=(e)=>Bp(e,new Map),Bp=(e,t)=>{if(typeof e!=="object"||e===null)return e;if(t?.has(e))return t.get(e);let n=Di(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=Bp(a.value,t)}}return Object.defineProperties(r,s),r};var Ck=(e)=>{let t=pt;return()=>t===pt?t=e():t},Mn=(e)=>typeof e==="function"&&e.length===0;var qp=class extends Function{constructor(...e){let t=e.slice(0,-1),n=e[e.length-1];try{super(...t,n)}catch(r){return he(`Encountered an unexpected error while compiling your definition:
|
|
457
|
+
Message: ${r}
|
|
458
|
+
Source: (${e.slice(0,-1)}) => {
|
|
459
|
+
${e[e.length-1]}
|
|
460
|
+
}`)}}};class ht{constructor(e,...[t]){return Object.assign(Object.setPrototypeOf(e.bind(t?.bind??this),this.constructor.prototype),t?.attach)}}var Hp=Ck(()=>{try{return Function("return false")()}catch{return!0}});var KP=qt("brand");var Kp=qt("arkInferred");var GP=qt("args");class Qe{constructor(){}}var Ik=()=>{try{return((Error().stack?.split(`
|
|
461
|
+
`)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},Ok=globalThis.process?.env??{},Wp={fileName:Ik,env:Ok};var Vp=(e)=>e[0].toUpperCase()+e.slice(1),Gp=(e)=>e[0].toLowerCase()+e.slice(1),Hl=(e)=>new RegExp(Pk(e),typeof e==="string"?"":e.flags);var Pk=(e)=>`^(?:${typeof e==="string"?e:e.source})$`;var yn={negativeLookahead:(e)=>`(?!${e})`,nonCapturingGroup:(e)=>`(?:${e})`},sr="\\",Tn={" ":1,"\n":1,"\t":1};var Mk=/^-0\.?0*$/.source,Jp=/[1-9]\d*/.source,Tk=/\.\d+/.source,Nk=/\.\d*[1-9]/.source,Xp=(e)=>Hl(yn.negativeLookahead(Mk)+yn.nonCapturingGroup("-?"+yn.nonCapturingGroup(yn.nonCapturingGroup("0|"+Jp)+yn.nonCapturingGroup(e.decimalPattern)+"?")+(e.allowDecimalOnly?"|"+e.decimalPattern:"")+"?")),zp=Xp({decimalPattern:Nk,allowDecimalOnly:!1}),Dk=zp.test.bind(zp),vo=Xp({decimalPattern:Tk,allowDecimalOnly:!0}),eM=vo.test.bind(vo),Fk=/^-?\d*\.?\d*$/,Lk=(e)=>e.length!==0&&Fk.test(e),Fi=Hl(yn.negativeLookahead("^-0$")+"-?"+yn.nonCapturingGroup(yn.nonCapturingGroup("0|"+Jp))),jk=Fi.test.bind(Fi),Kl=/^-?\d+$/,Uk=Kl.test.bind(Kl),Yp={number:"a number",bigint:"a bigint",integer:"an integer"},Zp=(e,t)=>`'${e}' was parsed as ${Yp[t]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,Bk=(e,t)=>t==="number"?Dk(e):jk(e),qk=(e,t)=>t==="number"?Number(e):Number.parseInt(e),Hk=(e,t)=>t==="number"?Lk(e):Uk(e),Qp=(e,t)=>Wl(e,"number",t),eh=(e,t)=>Wl(e,"number",{...t,strict:!0}),th=(e,t)=>Wl(e,"integer",t),Wl=(e,t,n)=>{let r=qk(e,t);if(!Number.isNaN(r)){if(Hk(e,t)){if(n?.strict)return Bk(e,t)?r:E(Zp(e,t));return r}}return n?.errorOnFail?E(n?.errorOnFail===!0?`Failed to parse ${Yp[t]} from '${e}'`:n?.errorOnFail):void 0},nh=(e)=>{if(e[e.length-1]!=="n")return;let t=e.slice(0,-1),n;try{n=BigInt(t)}catch{return}if(Fi.test(t))return n;if(Kl.test(t))return E(Zp(e,"bigint"))};var Kk="0.56.0",Wk={version:Kk,filename:Wp.fileName(),FileConstructor:Ul},or=Wk,rh=new Map,Vl=Object.create(null),Li=(e)=>{let t=rh.get(e);if(t)return t;let n=Vk(e);if(Vl[n])n=`${n}${Vl[n]++}`;else Vl[n]=1;return or[n]=e,rh.set(e,n),n},Nn=(e)=>/^[$A-Z_a-z][\w$]*$/.test(e),Vk=(e)=>{switch(typeof e){case"object":{if(e===null)break;let t=Ti(e)??"object";return t[0].toLowerCase()+t.slice(1)}case"function":return Nn(e.name)?e.name:"fn";case"symbol":return e.description&&Nn(e.description)?e.description:"symbol"}return he(`Unexpected attempt to register serializable value of type ${Be(e)}`)};var ji=(e)=>typeof e==="string"?JSON.stringify(e):typeof e==="bigint"?`${e}n`:`${e}`;var ih=(e,t={})=>Ui(e,{onUndefined:"$ark.undefined",onBigInt:(n)=>`$ark.bigint-${n}`,...t},[]);var re=(e,t)=>{switch(Be(e)){case"object":let n=e,r=n.constructor?.name??"Object";return r==="Object"||r==="Array"?t?.quoteKeys===!1?xo(n,t?.indent??0,""):JSON.stringify(Ui(n,Nr,[]),null,t?.indent):xo(n,t?.indent??0,"");case"symbol":return Nr.onSymbol(e);default:return ji(e)}},xo=(e,t,n)=>{if(typeof e==="function")return Nr.onFunction(e);if(typeof e!=="object"||e===null)return ji(e);let r=n+" ".repeat(t);if(Array.isArray(e)){if(e.length===0)return"[]";let o=e.map((a)=>xo(a,t,r)).join(`,
|
|
462
|
+
`+r);return t?`[
|
|
463
|
+
${r}${o}
|
|
464
|
+
${n}]`:`[${o}]`}let s=e.constructor?.name??"Object";if(s==="Object"){let o=rr(e).map(([a,l])=>{let c=typeof a==="symbol"?Nr.onSymbol(a):Nn(a)?a:JSON.stringify(a),u=xo(l,t,r);return`${r}${c}: ${u}`});if(o.length===0)return"{}";return t?`{
|
|
465
|
+
${o.join(`,
|
|
466
|
+
`)}
|
|
467
|
+
${n}}`:`{${o.join(", ")}}`}if(e instanceof Date)return ar(e);if("expression"in e&&typeof e.expression==="string")return e.expression;return s},Nr={onCycle:()=>"(cycle)",onSymbol:(e)=>`Symbol(${Li(e)})`,onFunction:(e)=>`Function(${Li(e)})`},Ui=(e,t,n)=>{switch(Be(e)){case"object":{let r=e;if("toJSON"in r&&typeof r.toJSON==="function")return r.toJSON();if(typeof r==="function")return Nr.onFunction(r);if(n.includes(r))return"(cycle)";let s=[...n,r];if(Array.isArray(r))return r.map((a)=>Ui(a,t,s));if(r instanceof Date)return r.toDateString();let o={};for(let a in r)o[a]=Ui(r[a],t,s);for(let a of Object.getOwnPropertySymbols(r))o[t.onSymbol?.(a)??a.toString()]=Ui(r[a],t,s);return o}case"symbol":return Nr.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(),l=e.getMilliseconds();if(n===0&&r===1&&s===0&&o===0&&a===0&&l===0)return`${t}`;let c=`${Gk[n]} ${r}, ${t}`;if(s===0&&o===0&&a===0&&l===0)return c;let u=e.toLocaleTimeString(),d=u.endsWith(" AM")||u.endsWith(" PM")?u.slice(-3):"";if(d)u=u.slice(0,-d.length);if(l)u+=`.${Jk(l,3)}`;else if(zk.test(u))u=u.slice(0,-3);return`${u+d}, ${c}`},Gk=["January","February","March","April","May","June","July","August","September","October","November","December"],zk=/:\d\d:00$/,Jk=(e,t)=>String(e).padStart(t,"0");var sh=(e,t,...[n])=>{let r=n?.stringifySymbol??re,s=e;switch(typeof t){case"string":s=Nn(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},wn=(e,...t)=>e.reduce((n,r)=>sh(n,r,...t),"");class Bi extends wo{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=wn(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let e="",t=[e];for(let n of this)e=sh(e,n),t.push(e);return this.cache.stringifyAncestors=t}}class qi{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 Tn))}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 oh=(e,t)=>`Unmatched ${e}${t===""?"":` before ${t}`}`,ko=(e)=>`Missing ${e}`;var $M=qt("implementedTraits");var Gl="$ark",Xk=2;while(Gl in globalThis)Gl=`$ark${Xk++}`;var ah=Gl;globalThis[ah]=or;var O=or,Yk=(e)=>`${ah}.${e}`,Me=(e)=>Yk(Li(e));class Ro extends Mi{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 zl(e,t)}index(e,t=!1){return lh(`${e}`,t)}line(e){return this.body+=`${" ".repeat(this.indentation)}${e}
|
|
468
|
+
`,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(`
|
|
469
|
+
`).map((n)=>" ".repeat(t)+`${n}`).join(`
|
|
470
|
+
`):this.body} }`}compile(){return new qp(...this.argNames,this.body)}}var Ht=(e)=>dt(e,"object")||typeof e==="symbol"?Me(e):ji(e),zl=(e,t=!1)=>{if(typeof e==="string"&&Nn(e))return`${t?"?":""}.${e}`;return lh(Zk(e),t)},Zk=(e)=>typeof e==="symbol"?Me(e):JSON.stringify(e),lh=(e,t=!1)=>`${t?"?.":""}[${e}]`;class Hi extends Ro{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 $o=(e)=>ne(e,(t,n)=>[t,ve(n)?[...n]:n]),it=qt("arkKind"),z=(e,t)=>e?.[it]===t,$e=(e)=>z(e,"root")||z(e,"constraint");var ch=["unit","proto","domain"],Dr=["required","optional","index","sequence"],Jl=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],Xl=[...Jl,"structure","predicate"],So=[...Xl,...Dr],Fr=["alias","union","morph","unit","intersection","proto","domain"],Qk=[...Fr,...So],Eo=ne(So,(e,t)=>[t,1]),uh=ne([...Dr,"undeclared"],(e,t)=>[t,1]),dh=ne(Qk,(e,t)=>[t,e]),Lr=(e)=>typeof e==="string"&&(e in dh);var jr=(e)=>dh[e],Ao=(e)=>Fr.slice(jr(e)+1),lT=[...Ao("union"),"alias"],cT=[...Ao("morph"),"alias"],Mt=(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 Ht(e)},Dn=(e)=>{let t="{ ";for(let[n,r]of Object.entries(e))t+=`${n}: ${Ht(r)}, `;return t+" }"},se=(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 fh 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 eR={target:"draft-2020-12",dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:(e)=>Ee.throw("arrayObject",e),arrayPostfix:(e)=>Ee.throw("arrayPostfix",e),defaultValue:(e)=>Ee.throw("defaultValue",e),domain:(e)=>Ee.throw("domain",e),morph:(e)=>Ee.throw("morph",e),patternIntersection:(e)=>Ee.throw("patternIntersection",e),predicate:(e)=>Ee.throw("predicate",e),proto:(e)=>Ee.throw("proto",e),symbolKey:(e)=>Ee.throw("symbolKey",e),unit:(e)=>Ee.throw("unit",e),date:(e)=>Ee.throw("date",e)}},Ee={Error:fh,throw:(...e)=>{throw new Ee.Error(...e)},throwInternalOperandError:(e,t)=>he(`Unexpected JSON Schema input for ${e}: ${re(t)}`),defaultConfig:eR};O.config??={};var Ki=(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]=Yl(e.toJsonSchema,t.toJsonSchema);else if(Lr(r))n[r]={...e[r],...t[r]};else n[r]=t[r]}return n},tR={"draft-2020-12":"https://json-schema.org/draft/2020-12/schema","draft-07":"http://json-schema.org/draft-07/schema#"},Yl=(e,t)=>{if(!e)return ph(t??{},void 0);if(!t)return e;let n={...e},r;for(r in t)if(r==="fallback")n.fallback=nR(e.fallback,t.fallback);else n[r]=t[r];return ph(n,t)},ph=(e,t)=>{if(t?.dialect!==void 0)return e;if(t?.target!==void 0)return{...e,dialect:tR[t.target]};return e},nR=(e,t)=>{e=hh(e),t=hh(t);let n={},r;for(r in Ee.defaultConfig.fallback)n[r]=t[r]??t.default??e[r]??e.default??Ee.defaultConfig.fallback[r];return n},hh=(e)=>typeof e==="function"?{default:e}:e??{};class Fn extends Mi{[it]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:e,relativePath:t,...n},r){super();this.input=n,this.ctx=r,Dp(this,n);let s=r.data;if(n.code==="union")n.errors=n.errors.flatMap((a)=>{let l=a.hasCode("union")?a.errors:[a];if(!e&&!t)return l;return l.map((c)=>c.transform((u)=>({...u,path:Ip(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 Bi(...o),this.data="data"in n?n.data:s}transform(e){return new Fn(e({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(e){return this.code===e}get propString(){return wn(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 mt extends wo{[it]="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 Zl(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 Fn({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 mt(this.ctx);for(let n of this)t.add(e(n));return t}merge(e){for(let t of e)this.add(new Fn({...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(`
|
|
471
|
+
`)}addAncestorPaths(e){for(let t of e.path.stringifyAncestors())this.byAncestorPath[t]=de(this.byAncestorPath[t],e)}}class Zl extends Error{name="TraversalError";constructor(e){if(e.length===1)super(e.summary);else super(`
|
|
472
|
+
`+e.map((t)=>` \u2022 ${rR(t)}`).join(`
|
|
473
|
+
`));Object.defineProperty(this,"arkErrors",{value:e,enumerable:!1})}}var rR=(e)=>e.toString().split(`
|
|
105
474
|
`).join(`
|
|
106
|
-
`);class G0{path=[];errors=new u1(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(Z,Y){this.root=Z,this.config=Y}get data(){let Z=this.root;for(let Y of this.path)Z=Z?.[Y];return Z}get propString(){return f0(this.path)}reject(Z){return this.error(Z),!1}mustBe(Z){return this.error(Z),!1}error(Z){let Y=typeof Z==="object"?Z.code?Z:{...Z,code:"predicate"}:{code:"predicate",expected:Z};return this.errorFromContext(Y)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches[this.branches.length-1]}queueMorphs(Z){let Y={path:new P6(...this.path),morphs:Z};if(this.currentBranch)this.currentBranch.queuedMorphs.push(Y);else this.queuedMorphs.push(Y)}finalize(Z){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 Z?Z(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(Z){return this.errorFromContext(Z)}errorFromContext(Z){let Y=new e0(Z,this);if(this.currentBranch)this.currentBranch.error=Y;else this.errors.add(Y);return Y}applyQueuedMorphs(){while(this.queuedMorphs.length){let Z=this.queuedMorphs;this.queuedMorphs=[];for(let{path:Y,morphs:X}of Z){if(this.errors.affectsPath(Y))continue;this.applyMorphsAtPath(Y,X)}}}applyMorphsAtPath(Z,Y){let X=Z[Z.length-1],Q;if(X!==void 0){Q=this.root;for(let $=0;$<Z.length-1;$++)Q=Q[Z[$]]}for(let $ of Y){this.path=[...Z];let W=r($),J=$(Q===void 0?this.root:Q[X],this);if(J instanceof e0){if(!this.errors.includes(J))this.errors.add(J);break}if(J instanceof u1){if(!W)this.errors.merge(J);this.queuedMorphs=[];break}if(Q===void 0)this.root=J;else Q[X]=J;this.applyQueuedMorphs()}}}var m1=(Z,Y,X)=>{if(!X)return Y();X.path.push(Z);let Q=Y();return X.path.pop(),Q};class C6 extends g1{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(Z,Y){super((Q,$,W=this.onFail)=>{if($)return this.traverseApply(Q,$),$.hasError()?$.errors:$.data;return this.rootApply(Q,W)},{attach:Z});this.attachments=Z,this.$=Y,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((Q,$)=>bL(Q,$.shallowReferences),[this]);let X=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let Q=0;Q<this.children.length;Q++){if(this.includesTransform||=this.children[Q].includesTransform,this.includesContextualPredicate||=this.children[Q].includesContextualPredicate,this.isCyclic||=this.children[Q].isCyclic,!X){let $=this.children[Q].flatRefs;for(let W=0;W<$.length;W++){let J=$[W];if(!this.flatRefs.some((z)=>WJ(z,J))){this.flatRefs.push(J);for(let z of J.node.branches)if(z.hasKind("morph")||z.hasKind("intersection")&&z.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:J.path,propString:J.propString,node:z})}}}Object.assign(this.referencesById,this.children[Q].referencesById)}this.flatRefs.sort((Q,$)=>Q.path.length>$.path.length?1:Q.path.length<$.path.length?-1:Q.propString>$.propString?1:Q.propString<$.propString?-1:Q.node.expression<$.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((Q)=>Q.length===1||Q.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((Q)=>Q.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(Q)=>this.traverseAllows(Q,new G0(Q,this.$.resolvedConfig)):(Q)=>this.traverseAllows(Q)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(Y,X)=>{if(this.allows(Y))return Y;let Q=new G0(Y,this.$.resolvedConfig);return this.traverseApply(Y,Q),Q.finalize(X)};case"contextual":return(Y,X)=>{let Q=new G0(Y,this.$.resolvedConfig);return this.traverseApply(Y,Q),Q.finalize(X)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let Z=this.$.resolvedConfig.clone;return(Y,X)=>{if(this.allows(Y))return this.contextFreeMorph(Z&&(typeof Y==="object"&&Y!==null||typeof Y==="function")?Z(Y):Y);let Q=new G0(Y,this.$.resolvedConfig);return this.traverseApply(Y,Q),Q.finalize(X)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,u(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=yL(this.metaJson);cacheGetter(Z,Y){return Object.defineProperty(this,Z,{value:Y}),Y}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=s9(this.kind);precompilation;assert=(Z,Y)=>this(Z,Y,(X)=>X.throw());traverse(Z,Y){return this(Z,Y,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(Z){if(!this.includesTransform)return this;let Y={};for(let[X,Q]of this.innerEntries){let $=this.impl.keys[X];if($.reduceIo)$.reduceIo(Z,Y,Q);else if($.child){let W=Q;Y[X]=n(W)?W.map((J)=>Z==="in"?J.rawIn:J.rawOut):Z==="in"?W.rawIn:W.rawOut}else Y[X]=Q}return this.$.node(this.kind,Y)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(Z){let Y=r(Z)?Z:this.$.parseDefinition(Z);return this.innerHash===Y.innerHash}ifEquals(Z){return this.equals(Z)?this:void 0}hasKind(Z){return this.kind===Z}assertHasKind(Z){if(this.kind!==Z)w9(`${this.kind} node was not of asserted kind ${Z}`);return this}hasKindIn(...Z){return Z.includes(this.kind)}assertHasKindIn(...Z){if(!X0(Z,this.kind))w9(`${this.kind} node was not one of asserted kinds ${Z}`);return this}isBasis(){return X0(tW,this.kind)}isConstraint(){return X0(z8,this.kind)}isStructural(){return X0(n9,this.kind)}isRefinement(){return X0(uY,this.kind)}isRoot(){return X0(a9,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(Z){return this.hasKind("unit")&&this.allows(Z)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(Z){let Y=j6.normalize(Z);return this._select(Y)}_select(Z){let Y=j6.applyBoundary[Z.boundary??"references"](this);if(Z.kind)Y=Y.filter((X)=>X.kind===Z.kind);if(Z.where)Y=Y.filter(Z.where);return j6.applyMethod[Z.method??"filter"](Y,this,Z)}transform(Z,Y){return this._transform(Z,this._createTransformContext(Y))}_createTransformContext(Z){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:Z?.prereduced??!1},undeclaredKeyHandling:void 0,...Z}}_transform(Z,Y){let X=Y.bindScope??this.$;if(Y.seen[this.id])return this.$.lazilyResolve(Y.seen[this.id]);if(Y.shouldTransform?.(this,Y)===!1)return this;let Q;if(Y.seen[this.id]=()=>Q,this.hasKind("structure")&&this.undeclared!==Y.undeclaredKeyHandling)Y={...Y,undeclaredKeyHandling:this.undeclared};let $=b(this.inner,(q,U)=>{if(!this.impl.keys[q].child)return[q,U];let H=U;if(!n(H)){let K=H._transform(Z,Y);return K?[q,K]:[]}if(H.length===0)return[q,U];let G=H.flatMap((K)=>{return K._transform(Z,Y)??[]});return G.length?[q,G]:[]});delete Y.seen[this.id];let W=Object.assign($,{meta:this.meta}),J=Y.selected&&!Y.selected.includes(this)?W:Z(this.kind,W,Y);if(J===null)return null;if(r(J))return Q=J;let z=Object.keys(J);if((z.length===0||z.length===1&&z[0]==="meta")&&!N0(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in J))return Y.undeclaredKeyHandling?{...J,value:F.intrinsic.unknown}:null;if(this.kind==="morph")J.in??=F.intrinsic.unknown;return Q=X.node(this.kind,J,Y.parseOptions)}configureReferences(Z,Y="references"){let X=j6.normalize(Y),Q=typeof Z==="string"?(z,V)=>({...V,meta:{...V.meta,description:Z}}):typeof Z==="function"?(z,V)=>({...V,meta:Z(V.meta)}):(z,V)=>({...V,meta:{...V.meta,...Z}});if(X.boundary==="self")return this.$.node(this.kind,Q(this.kind,{...this.inner,meta:this.meta}));let $=this._select(X),W=$&&n0($),J=X.boundary==="child"?(z,V)=>V.root.children.includes(z):X.boundary==="shallow"?(z)=>z.kind!=="structure":()=>!0;return this.$.finalize(this.transform(Q,{shouldTransform:J,selected:W}))}}var j6={applyBoundary:{self:(Z)=>[Z],child:(Z)=>[...Z.children],shallow:(Z)=>[...Z.shallowReferences],references:(Z)=>[...Z.references]},applyMethod:{filter:(Z)=>Z,assertFilter:(Z,Y,X)=>{if(Z.length===0)w9($J(Y,X));return Z},find:(Z)=>Z[0],assertFind:(Z,Y,X)=>{if(Z.length===0)w9($J(Y,X));return Z[0]}},normalize:(Z)=>typeof Z==="function"?{boundary:"references",method:"filter",where:Z}:typeof Z==="string"?N1(Z,j6.applyBoundary)?{method:"filter",boundary:Z}:{boundary:"references",method:"filter",kind:Z}:{boundary:"references",method:"filter",...Z}},$J=(Z,Y)=>`${Z} had no references matching ${x(Y)}.`,SL=(Z)=>f0(Z,{stringifyNonKey:(Y)=>Y.expression}),_L=/"(\$ark\.[^"]+)"/g,yL=(Z)=>JSON.stringify(Z).replace(_L,"$1"),K0=(Z,Y)=>({path:Z,node:Y,propString:SL(Z)}),WJ=(Z,Y)=>Z.propString===Y.propString&&Z.node.equals(Y.node),dY=(Z,Y)=>F0(Z,Y,{isEqual:WJ}),bL=(Z,Y)=>F0(Z,Y,{isEqual:(X,Q)=>X.equals(Q)});class w extends Array{static init(Z,Y,X,Q){return new w({kind:Z,l:Y,r:X,path:Q?.path??[],optional:Q?.optional??!1})}add(Z,Y,X,Q){return this.push({kind:Z,l:Y,r:X,path:Q?.path??[],optional:Q?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:Z,l:Y,r:X}=this[0],Q=f0(Z);return lY(`Intersection${Q&&` at ${Q}`} of ${JJ(Y,X)}`)}return`The following intersections result in unsatisfiable types:
|
|
107
|
-
|
|
108
|
-
• `)}`}throw(){return L(this.describeReasons())}invert(){let Z=this.map((Y)=>({...Y,l:Y.r,r:Y.l}));if(!(Z instanceof w))return new w(...Z);return Z}withPrefixKey(Z,Y){return this.map((X)=>({...X,path:[Z,...X.path],optional:X.optional||Y==="optional"}))}toNeverIfDisjoint(){return F.intrinsic.never}}var JJ=(Z,Y)=>`${cY(Z)} and ${cY(Y)}`,cY=(Z)=>r(Z)?Z.expression:n(Z)?Z.map(cY).join(" | ")||"never":String(Z),lY=(Z)=>`${Z} results in an unsatisfiable type`;var t9={},p1=(Z,Y,X)=>s(Z,Y,{$:X,invert:!1,pipe:!1}),S6=(Z,Y,X)=>s(Z,Y,{$:X,invert:!1,pipe:!0}),s=(Z,Y,X)=>{let Q=X.pipe?"|>":"&",$=`${Z.hash}${Q}${Y.hash}`;if(t9[$]!==void 0)return t9[$];if(!X.pipe){let z=`${Y.hash}${Q}${Z.hash}`;if(t9[z]!==void 0){let V=t9[z],q=V instanceof w?V.invert():V;return t9[$]=q,q}}let W=!X.pipe||!Z.includesTransform&&!Y.includesTransform;if(W&&Z.equals(Y))return Z;let J=W?iY(Z,Y,X):Z.hasKindIn(...a9)?xL(Z,Y,X):iY(Z,Y,X);if(r(J)){if(Z.equals(J))J=Z;else if(Y.equals(J))J=Y}return t9[$]=J,J},iY=(Z,Y,X)=>{let Q=Z.precedence<Y.precedence?Z.kind:Y.kind,$=Z.impl.intersections[Y.kind]??Y.impl.intersections[Z.kind];if($===void 0)return null;else if(Q===Z.kind)return $(Z,Y,X);else{let W=$(Y,Z,{...X,invert:!X.invert});if(W instanceof w)W=W.invert();return W}},xL=(Z,Y,X)=>Z.includesTransform||Y.includesTransform?X.invert?zJ(Y,Z,X):zJ(Z,Y,X):iY(Z,Y,X),zJ=(Z,Y,X)=>Z.distribute((Q)=>kL(Q,Y,X),(Q)=>{let $=Q.filter(r);if($.length===0)return w.init("union",Z.branches,Y.branches);if($.length<Z.branches.length||!Z.branches.every((z,V)=>z.rawIn.equals($[V].rawIn)))return X.$.parseSchema($);let W;if($.length===1){let z=$[0];if(!W)return z;return X.$.node("morph",{...z.inner,in:z.rawIn.configure(W,"self")})}let J={branches:$};if(W)J.meta=W;return X.$.parseSchema(J)}),kL=(Z,Y,X)=>{if(Z.hasKind("morph")){let $=[...Z.morphs];if(Z.lastMorphIfNode){let W=s(Z.lastMorphIfNode,Y,X);if(W instanceof w)return W;$[$.length-1]=W}else $.push(Y);return X.$.node("morph",{morphs:$,in:Z.inner.in})}if(Y.hasKind("morph")){let $=s(Z,Y.rawIn,X);if($ instanceof w)return $;return X.$.node("morph",{morphs:[Y],in:$})}return X.$.node("morph",{morphs:[Y],in:Z})};class $0 extends C6{constructor(Z,Y){super(Z,Y);Object.defineProperty(this,S1,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(Z){return p1(this,Z,this.$)}}class h0 extends $0{traverseApply=(Z,Y)=>{if(!this.traverseAllows(Z,Y))Y.errorFromNodeContext(this.errorContext)};compile(Z){if(Z.traversalKind==="Allows")Z.return(this.compiledCondition);else Z.if(this.compiledNegation,()=>Z.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return t0(this.errorContext)}}var I1=(Z)=>(Y,X)=>{if(n(Y)){if(Y.length===0)return;let $=Y.map((W)=>X.$.node(Z,W));if(Z==="predicate")return $;return $.sort((W,J)=>W.hash<J.hash?-1:1)}let Q=X.$.node(Z,Y);return Q.hasOpenIntersection()?[Q]:Q},e9=(Z)=>{let Y=Z.r.shift();if(!Y){let Q=Z.l.length===0&&Z.kind==="structure"?F.intrinsic.unknown.internal:Z.ctx.$.node(Z.kind,Object.assign(Z.baseInner,vL(Z.l)),{prereduced:!0});for(let $ of Z.roots){if(Q instanceof w)return Q;Q=s($,Q,Z.ctx)}return Q}let X=!1;for(let Q=0;Q<Z.l.length;Q++){let $=s(Z.l[Q],Y,Z.ctx);if($===null)continue;if($ instanceof w)return $;if($.isRoot())return Z.roots.push($),Z.l.splice(Q),e9(Z);if(!X)Z.l[Q]=$,X=!0;else if(!Z.l.includes($))return u(`Unexpectedly encountered multiple distinct intersection results for refinement ${Y}`)}if(!X)Z.l.push(Y);if(Z.kind==="intersection"){if(Y.impliedSiblings)for(let Q of Y.impliedSiblings)F0(Z.r,Q)}return e9(Z)},Z2=(Z)=>{return Object.entries(Z).flatMap(([X,Q])=>(X in V8)?Q:[]).sort((X,Q)=>X.precedence<Q.precedence?-1:X.precedence>Q.precedence?1:X.kind==="predicate"&&Q.kind==="predicate"?0:X.hash<Q.hash?-1:1)},vL=(Z)=>{let Y={};for(let X of Z)if(X.hasOpenIntersection())Y[X.kind]=h(Y[X.kind],X);else{if(Y[X.kind])return u(`Unexpected intersection of closed refinements of kind ${X.kind}`);Y[X.kind]=X}return Y},VJ=(...Z)=>L(qJ(...Z)),qJ=(Z,Y,X)=>{let Q=X.hasKind("morph")?"a morph":X.isUnknown()?"unknown":X.exclude(Y).defaultShortDescription;return`${kW(Z)} operand must be ${Y.description} (was ${Q})`};var UJ=(Z,Y,X)=>new Z9(Z,Y,X,X,null);class U8 extends g1{}class Z9 extends g1{[S1]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(Z,Y,X,Q,$){super((...W)=>{let J=b(this.names,(z,V)=>{let q=this.arg$.parse(W[z]);if(!q.extends(this.constraints[z]))L(fL(V,this.constraints[z].expression,q.expression));return[V,q]});if(this.defIsLazy()){let z=this.bodyDef(J);return this.$.parse(z)}return this.$.parse(Y,{args:J})});this.paramDefs=Z,this.bodyDef=Y,this.$=X,this.arg$=Q,this.hkt=$,this.description=$?new $().description??`a generic type for ${$.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof U8}cacheGetter(Z,Y){return Object.defineProperty(this,Z,{value:Y}),Y}get json(){return this.cacheGetter("json",{params:this.params.map((Z)=>Z[1].isUnknown()?Z[0]:[Z[0],Z[1].json]),body:oW(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((Z)=>typeof Z==="string"?[Z,F.intrinsic.unknown]:[Z[0],this.$.parse(Z[1])]))}get names(){return this.cacheGetter("names",this.params.map((Z)=>Z[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map((Z)=>Z[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}var fL=(Z,Y,X)=>`${Z} must be assignable to ${Y} (was ${X})`;var hL=v({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:(Z)=>typeof Z==="function"?{predicate:Z}:Z,defaults:{description:(Z)=>`valid according to ${Z.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class HJ extends $0{serializedPredicate=Q1(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=t0(this.errorContext);traverseApply=(Z,Y)=>{let X=Y.currentErrorCount;if(!this.predicate(Z,Y.external)&&Y.currentErrorCount===X)Y.errorFromNodeContext(this.errorContext)};compile(Z){if(Z.traversalKind==="Allows"){Z.return(this.compiledCondition);return}Z.initializeErrorCount(),Z.if(`${this.compiledNegation} && ctx.currentErrorCount === errorCount`,()=>Z.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(Z,Y){return Y.fallback.predicate({code:"predicate",base:Z,predicate:this.predicate})}}var oY={implementation:hL,Node:HJ};var gL=v({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(Z)=>Number.isInteger(Z)?Z:L(uL(Z))}},normalize:(Z)=>typeof Z==="number"?{rule:Z}:Z,hasAssociatedError:!0,defaults:{description:(Z)=>Z.rule===1?"an integer":Z.rule===2?"even":`a multiple of ${Z.rule}`},intersections:{divisor:(Z,Y,X)=>X.$.node("divisor",{rule:Math.abs(Z.rule*Y.rule/mL(Z.rule,Y.rule))})},obviatesBasisDescription:!0});class GJ extends h0{traverseAllows=(Z)=>Z%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=F.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(Z){if(Z.type="integer",this.rule===1)return Z;return Z.multipleOf=this.rule,Z}}var nY={implementation:gL,Node:GJ};var uL=(Z)=>`divisor must be an integer (was ${Z})`,mL=(Z,Y)=>{let X,Q=Z,$=Y;while($!==0)X=$,$=Q%$,Q=X;return Q};class r1 extends h0{boundOperandKind=lL[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=iL(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${pL[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?oL(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator["0"]==="<"?"upper":"lower";isStricterThan(Z){return(this.limitKind==="upper"?this.numericLimit<Z.numericLimit:this.numericLimit>Z.numericLimit)||this.numericLimit===Z.numericLimit&&this.exclusive===!0&&!Z.exclusive}overlapsRange(Z){if(this.isStricterThan(Z))return!1;if(this.numericLimit===Z.numericLimit&&(this.exclusive||Z.exclusive))return!1;return!0}overlapIsUnit(Z){return this.numericLimit===Z.numericLimit&&!this.exclusive&&!Z.exclusive}}var pL={"<":">=","<=":">",">":"<=",">=":"<"},dL={min:"max",minLength:"maxLength",after:"before"},H8={parse:(Z)=>Z||void 0},G8=(Z)=>(Y)=>{if(typeof Y==="number")return{rule:Y};let{exclusive:X,...Q}=Y;return X?{...Q,rule:Z==="minLength"?Q.rule+1:Q.rule-1}:Q},K8=(Z)=>(Y)=>{if(typeof Y==="number"||typeof Y==="string"||Y instanceof Date)return{rule:Y};let{exclusive:X,...Q}=Y;if(!X)return Q;let $=typeof Q.rule==="number"?Q.rule:typeof Q.rule==="string"?new Date(Q.rule).valueOf():Q.rule.valueOf();return X?{...Q,rule:Z==="after"?$+1:$-1}:Q},B8=(Z)=>typeof Z==="string"||typeof Z==="number"?new Date(Z):Z,cL=(Z,Y)=>`${Z} bound must be a positive integer (was ${Y})`,Y2=(Z)=>(Y)=>{if(!Number.isInteger(Y)||Y<0)L(cL(Z,Y));return Y},lL={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},iL=(Z,Y)=>`${N1(Z,dL)?">":"<"}${Y?"":"="}`,oL=(Z)=>typeof Z==="string"?Z:new Date(Z).toLocaleString(),KJ=(Z)=>`Bounded expression ${Z} must be exactly one of number, string, Array, or Date`;var nL=v({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:B8,serialize:(Z)=>Z.toISOString()}},normalize:K8("after"),defaults:{description:(Z)=>`${Z.collapsibleLimitString} or later`,actual:P9},intersections:{after:(Z,Y)=>Z.isStricterThan(Y)?Z:Y}});class BJ extends r1{impliedBasis=F.intrinsic.Date.internal;collapsibleLimitString=P9(this.rule);traverseAllows=(Z)=>Z>=this.rule;reduceJsonSchema(Z,Y){return Y.fallback.date({code:"date",base:Z,after:this.rule})}}var aY={implementation:nL,Node:BJ};var aL=v({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:B8,serialize:(Z)=>Z.toISOString()}},normalize:K8("before"),defaults:{description:(Z)=>`${Z.collapsibleLimitString} or earlier`,actual:P9},intersections:{before:(Z,Y)=>Z.isStricterThan(Y)?Z:Y,after:(Z,Y,X)=>Z.overlapsRange(Y)?Z.overlapIsUnit(Y)?X.$.node("unit",{unit:Z.rule}):null:w.init("range",Z,Y)}});class LJ extends r1{collapsibleLimitString=P9(this.rule);traverseAllows=(Z)=>Z<=this.rule;impliedBasis=F.intrinsic.Date.internal;reduceJsonSchema(Z,Y){return Y.fallback.date({code:"date",base:Z,before:this.rule})}}var rY={implementation:aL,Node:LJ};var rL=v({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:Y2("exactLength")}},normalize:(Z)=>typeof Z==="number"?{rule:Z}:Z,hasAssociatedError:!0,defaults:{description:(Z)=>`exactly length ${Z.rule}`,actual:(Z)=>`${Z.length}`},intersections:{exactLength:(Z,Y,X)=>w.init("unit",X.$.node("unit",{unit:Z.rule}),X.$.node("unit",{unit:Y.rule}),{path:["length"]}),minLength:(Z,Y)=>Z.rule>=Y.rule?Z:w.init("range",Z,Y),maxLength:(Z,Y)=>Z.rule<=Y.rule?Z:w.init("range",Z,Y)}});class MJ extends h0{traverseAllows=(Z)=>Z.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=F.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(Z){switch(Z.type){case"string":return Z.minLength=this.rule,Z.maxLength=this.rule,Z;case"array":return Z.minItems=this.rule,Z.maxItems=this.rule,Z;default:return t.throwInternalOperandError("exactLength",Z)}}}var sY={implementation:rL,Node:MJ};var sL=v({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:H8},normalize:(Z)=>typeof Z==="number"?{rule:Z}:Z,defaults:{description:(Z)=>{if(Z.rule===0)return Z.exclusive?"negative":"non-positive";return`${Z.exclusive?"less than":"at most"} ${Z.rule}`}},intersections:{max:(Z,Y)=>Z.isStricterThan(Y)?Z:Y,min:(Z,Y,X)=>Z.overlapsRange(Y)?Z.overlapIsUnit(Y)?X.$.node("unit",{unit:Z.rule}):null:w.init("range",Z,Y)},obviatesBasisDescription:!0});class FJ extends r1{impliedBasis=F.intrinsic.number.internal;traverseAllows=this.exclusive?(Z)=>Z<this.rule:(Z)=>Z<=this.rule;reduceJsonSchema(Z){if(this.exclusive)Z.exclusiveMaximum=this.rule;else Z.maximum=this.rule;return Z}}var tY={implementation:sL,Node:FJ};var tL=v({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Y2("maxLength")}},reduce:(Z,Y)=>Z.rule===0?Y.node("exactLength",Z):void 0,normalize:G8("maxLength"),defaults:{description:(Z)=>`at most length ${Z.rule}`,actual:(Z)=>`${Z.length}`},intersections:{maxLength:(Z,Y)=>Z.isStricterThan(Y)?Z:Y,minLength:(Z,Y,X)=>Z.overlapsRange(Y)?Z.overlapIsUnit(Y)?X.$.node("exactLength",{rule:Z.rule}):null:w.init("range",Z,Y)}});class NJ extends r1{impliedBasis=F.intrinsic.lengthBoundable.internal;traverseAllows=(Z)=>Z.length<=this.rule;reduceJsonSchema(Z){switch(Z.type){case"string":return Z.maxLength=this.rule,Z;case"array":return Z.maxItems=this.rule,Z;default:return t.throwInternalOperandError("maxLength",Z)}}}var eY={implementation:tL,Node:NJ};var eL=v({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:H8},normalize:(Z)=>typeof Z==="number"?{rule:Z}:Z,defaults:{description:(Z)=>{if(Z.rule===0)return Z.exclusive?"positive":"non-negative";return`${Z.exclusive?"more than":"at least"} ${Z.rule}`}},intersections:{min:(Z,Y)=>Z.isStricterThan(Y)?Z:Y},obviatesBasisDescription:!0});class wJ extends r1{impliedBasis=F.intrinsic.number.internal;traverseAllows=this.exclusive?(Z)=>Z>this.rule:(Z)=>Z>=this.rule;reduceJsonSchema(Z){if(this.exclusive)Z.exclusiveMinimum=this.rule;else Z.minimum=this.rule;return Z}}var Z7={implementation:eL,Node:wJ};var ZM=v({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Y2("minLength")}},reduce:(Z)=>Z.rule===0?F.intrinsic.unknown:void 0,normalize:G8("minLength"),defaults:{description:(Z)=>Z.rule===1?"non-empty":`at least length ${Z.rule}`,actual:(Z)=>Z.length===0?"":`${Z.length}`},intersections:{minLength:(Z,Y)=>Z.isStricterThan(Y)?Z:Y}});class DJ extends r1{impliedBasis=F.intrinsic.lengthBoundable.internal;traverseAllows=(Z)=>Z.length>=this.rule;reduceJsonSchema(Z){switch(Z.type){case"string":return Z.minLength=this.rule,Z;case"array":return Z.minItems=this.rule,Z;default:return t.throwInternalOperandError("minLength",Z)}}}var Y7={implementation:ZM,Node:DJ};var AJ={min:Z7.implementation,max:tY.implementation,minLength:Y7.implementation,maxLength:eY.implementation,exactLength:sY.implementation,after:aY.implementation,before:rY.implementation},EJ={min:Z7.Node,max:tY.Node,minLength:Y7.Node,maxLength:eY.Node,exactLength:sY.Node,after:aY.Node,before:rY.Node};var YM=v({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:(Z)=>typeof Z==="string"?{rule:Z}:Z instanceof RegExp?Z.flags?{rule:Z.source,flags:Z.flags}:{rule:Z.source}:Z,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:(Z)=>`matched by ${Z.rule}`},intersections:{pattern:()=>null}});class OJ extends h0{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(Z,Y){if(Z.pattern)return Y.fallback.patternIntersection({code:"patternIntersection",base:Z,pattern:this.rule});return Z.pattern=this.rule,Z}}var X7={implementation:YM,Node:OJ};var _6=(Z,Y)=>{let X=XM(Z);if(Y&&!Y.includes(X))return L(`Root of kind ${X} should be one of ${Y}`);return X},XM=(Z)=>{if(P(Z,"root"))return Z.kind;if(typeof Z==="string")return Z[0]==="$"?"alias":(Z in f1)?"domain":"proto";if(typeof Z==="function")return"proto";if(typeof Z!=="object"||Z===null)return L(PJ(Z));if("morphs"in Z)return"morph";if("branches"in Z||n(Z))return"union";if("unit"in Z)return"unit";if("reference"in Z)return"alias";let Y=Object.keys(Z);if(Y.length===0||Y.some((X)=>(X in V8)))return"intersection";if("proto"in Z)return"proto";if("domain"in Z)return"domain";return L(PJ(Z))},PJ=(Z)=>`${x(Z)} is not a valid type schema`,TJ={},QM=(Z)=>n(Z)?Z.map((Y)=>Y.collapsibleJson):Z.collapsibleJson,_1={};F.nodesByRegisteredId=_1;var Q7=(Z)=>{return TJ[Z]??=0,`${Z}${++TJ[Z]}`},$7=(Z)=>{let Y=X2[Z.kind],X=Y.applyConfig?.(Z.def,Z.$.resolvedConfig)??Z.def,Q={},{meta:$,...W}=X,J=$===void 0?{}:typeof $==="string"?{description:$}:$,z=RY(W).sort(([q],[U])=>r9(q)?r9(U)?s9(q)-s9(U):1:r9(U)?-1:q<U?-1:1).filter(([q,U])=>{if(q.startsWith("meta.")){let H=q.slice(5);return J[H]=U,!1}return!0});for(let q of z){let U=q[0],H=Y.keys[U];if(!H)return L(`Key ${U} is not valid on ${Z.kind} schema`);let G=H.parse?H.parse(q[1],Z):q[1];if(G!==h1&&(G!==void 0||H.preserveUndefined))Q[U]=G}if(Y.reduce&&!Z.prereduced){let q=Y.reduce(Q,Z.$);if(q){if(q instanceof w)return q.throw();return $M(q,J)}}return W7({id:Z.id,kind:Z.kind,inner:Q,meta:J,$:Z.$})},W7=({id:Z,kind:Y,inner:X,meta:Q,$,ignoreCache:W})=>{let J=X2[Y],z=RY(X),V=[],q={};for(let[T,i]of z){let g=J.keys[T],Z1=g.serialize??(g.child?QM:Q0);if(q[T]=Z1(i),g.child===!0){let $1=i;if(n($1))V.push(...$1);else V.push($1)}else if(typeof g.child==="function")V.push(...g.child(i))}if(J.finalizeInnerJson)q=J.finalizeInnerJson(q);let U={...q},H={};if(!N0(Q))H=b(Q,(T,i)=>[T,T==="examples"?i:Q0(i)]),U.meta=L8(H,"description",!0);q=L8(q,J.collapsibleKey,!1);let G=JSON.stringify({kind:Y,...q});U=L8(U,J.collapsibleKey,!1);let K=L8(U,J.collapsibleKey,!0),M=JSON.stringify({kind:Y,...U});if($.nodesByHash[M]&&!W)return $.nodesByHash[M];let E={id:Z,kind:Y,impl:J,inner:X,innerEntries:z,innerJson:q,innerHash:G,meta:Q,metaJson:H,json:U,hash:M,collapsibleJson:K,children:V};if(Y!=="intersection"){for(let T in X)if(T!=="in"&&T!=="out")E[T]=X[T]}let O=new RJ[Y](E,$);return $.nodesByHash[M]=O},IJ=(Z,Y)=>{if(Z.id===Y)return Z;if(r(_1[Y]))u(`Unexpected attempt to overwrite node id ${Y}`);return W7({id:Y,kind:Z.kind,inner:Z.inner,meta:Z.meta,$:Z.$,ignoreCache:!0})},$M=(Z,Y,X)=>{if(X&&r(_1[X]))u(`Unexpected attempt to overwrite node id ${X}`);return W7({id:X??Q7(Y.alias??Z.kind),kind:Z.kind,inner:Z.inner,meta:Y,$:Z.$})},L8=(Z,Y,X)=>{let Q=Object.keys(Z);if(Q.length===1&&Q[0]===Y){let $=Z[Y];if(X)return $;if(v1($,"object")&&(Object.keys($).length===1||Array.isArray($)))return $}return Z};var y6=(Z,Y,X)=>{if(Z.key!==Y.key)return null;let Q=Z.key,$=s(Z.value,Y.value,X),W=Z.required||Y.required?"required":"optional";if($ instanceof w)if(W==="optional")$=F.intrinsic.never.internal;else return $.withPrefixKey(Z.key,Z.required&&Y.required?"required":"optional");if(W==="required")return X.$.node("required",{key:Q,value:$});let J=Z.hasDefault()?Y.hasDefault()?Z.default===Y.default?Z.default:L(J7(Z.default,Y.default)):Z.default:Y.hasDefault()?Y.default:h1;return X.$.node("optional",{key:Q,value:$,default:J})};class b6 extends $0{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=F.intrinsic.object.internal;serializedKey=H0(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=h(this.value.flatRefs.map((Z)=>K0([this.key,...Z.path],Z.node)),K0([this.key],this.value));_transform(Z,Y){Y.path.push(this.key);let X=super._transform(Z,Y);return Y.path.pop(),X}hasDefault(){return"default"in this.inner}traverseAllows=(Z,Y)=>{if(this.key in Z)return m1(this.key,()=>this.value.traverseAllows(Z[this.key],Y),Y);return this.optional};traverseApply=(Z,Y)=>{if(this.key in Z)m1(this.key,()=>this.value.traverseApply(Z[this.key],Y),Y);else if(this.hasKind("required"))Y.errorFromNodeContext(this.errorContext)};compile(Z){if(Z.if(`${this.serializedKey} in data`,()=>Z.traverseKey(this.serializedKey,`data${Z.prop(this.key)}`,this.value)),this.hasKind("required"))Z.else(()=>Z.traversalKind==="Apply"?Z.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):Z.return(!1));if(Z.traversalKind==="Allows")Z.return(!0)}}var J7=(Z,Y)=>`Invalid intersection of default values ${x(Z)} & ${x(Y)}`;var WM=v({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(Z,Y)=>Y.$.parseSchema(Z)},default:{preserveUndefined:!0}},normalize:(Z)=>Z,reduce:(Z,Y)=>{if(Y.resolvedConfig.exactOptionalPropertyTypes===!1){if(!Z.value.allows(void 0))return Y.node("optional",{...Z,value:Z.value.or(C.undefined)},{prereduced:!0})}},defaults:{description:(Z)=>`${Z.compiledKey}?: ${Z.value.description}`},intersections:{optional:y6}});class jJ extends b6{constructor(...Z){super(...Z);if("default"in this.inner)k6(this.value,this.inner.default,this.key)}get rawIn(){let Z=super.rawIn;if(!this.hasDefault())return Z;return this.$.node("optional",Y8(Z.inner,{default:!0}),{prereduced:!0})}get outProp(){if(!this.hasDefault())return this;let{default:Z,...Y}=this.inner;return this.cacheGetter("outProp",this.$.node("required",Y,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${x(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=zM(this);defaultValueMorphRef=this.defaultValueMorph&&Q1(this.defaultValueMorph)}var x6={implementation:WM,Node:jJ},JM={},zM=(Z)=>{if(!Z.hasDefault())return;let Y=`{${Z.compiledKey}: ${Z.value.id} = ${Q0(Z.default)}}`;return JM[Y]??=z7(Z.key,Z.value,Z.default)},z7=(Z,Y,X)=>{if(typeof X==="function")return Y.includesTransform?($,W)=>{return m1(Z,()=>Y($[Z]=X(),W),W),$}:($)=>{return $[Z]=X(),$};let Q=Y.includesTransform?Y.assert(X):X;return v1(Q,"object")?($,W)=>{return m1(Z,()=>Y($[Z]=X,W),W),$}:($)=>{return $[Z]=Q,$}},k6=(Z,Y,X)=>{let Q=a0(Y);if(v1(Y,"object")&&!Q)L(VM(X));let $=Z.in(Q?Y():Y);if($ instanceof u1){if(X===null)L(`Default ${$.summary}`);let W=$.transform((J)=>J.transform((z)=>({...z,prefixPath:[X]})));L(`Default for ${W.summary}`)}return Y},VM=(Z)=>{return`Non-primitive default ${Z===null?"":typeof Z==="number"?`for value at [${Z}] `:`for ${H0(Z)} `}must be specified as a function like () => ({my: 'object'})`};class W0 extends C6{constructor(Z,Y){super(Z,Y);Object.defineProperty(this,S1,{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:(Z)=>{let Y=this(Z);if(Y instanceof u1)return Y;return{value:Y}},jsonSchema:{input:(Z)=>this.rawIn.toJsonSchema({target:CJ(Z.target),...Z.libraryOptions}),output:(Z)=>this.rawOut.toJsonSchema({target:CJ(Z.target),...Z.libraryOptions})}}}as(){return this}brand(Z){if(Z==="")return L(qM);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(Z,Y){let X=this.branches.map(Z);return Y?.(X)??X}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(Z={}){let Y=mY(this.$.resolvedConfig.toJsonSchema,Z);Y.useRefs||=this.isCyclic;let X=typeof Y.dialect==="string"?{$schema:Y.dialect}:{};if(Object.assign(X,this.toJsonSchemaRecurse(Y)),Y.useRefs){let Q=b(this.references,($,W)=>W.isRoot()&&!W.alwaysExpandJsonSchema?[W.id,W.toResolvedJsonSchema(Y)]:[]);if(Y.target==="draft-07")Object.assign(X,{definitions:Q});else X.$defs=Q}return X}toJsonSchemaRecurse(Z){if(Z.useRefs&&!this.alwaysExpandJsonSchema)return{$ref:`#/${Z.target==="draft-07"?"definitions":"$defs"}/${this.id}`};return this.toResolvedJsonSchema(Z)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(Z){let Y=this.innerToJsonSchema(Z);return Object.assign(Y,this.metaJson)}intersect(Z){let Y=this.$.parseDefinition(Z),X=this.rawIntersect(Y);if(X instanceof w)return X;return this.$.finalize(X)}rawIntersect(Z){return p1(this,Z,this.$)}toNeverIfDisjoint(){return this}and(Z){let Y=this.intersect(Z);return Y instanceof w?Y.throw():Y}rawAnd(Z){let Y=this.rawIntersect(Z);return Y instanceof w?Y.throw():Y}or(Z){let Y=this.$.parseDefinition(Z);return this.$.finalize(this.rawOr(Y))}rawOr(Z){let Y=[...this.branches,...Z.branches];return this.$.node("union",Y)}map(Z){return this.$.schema(this.applyStructuralOperation("map",[Z]))}pick(...Z){return this.$.schema(this.applyStructuralOperation("pick",Z))}omit(...Z){return this.$.schema(this.applyStructuralOperation("omit",Z))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let Z=this.applyStructuralOperation("keyof",[]).reduce((Y,X)=>Y.intersect(X).toNeverIfDisjoint(),F.intrinsic.unknown.internal);if(Z.branches.length===0)L(lY(`keyof ${this.expression}`));return this._keyof=this.$.finalize(Z)}get props(){if(this.branches.length!==1)return L(HM(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(Z){let Y=this.$.parseDefinition(Z);return this.$.schema(Y.distribute((X)=>this.applyStructuralOperation("merge",[SJ(X)??L(_J("merge",X.expression))])))}applyStructuralOperation(Z,Y){return this.distribute((X)=>{if(X.equals(F.intrinsic.object)&&Z!=="merge")return X;let Q=SJ(X);if(!Q)L(_J(Z,X.expression));if(Z==="keyof")return Q.keyof();if(Z==="get")return Q.get(...Y);if(Z==="props")return Q.props;let $=Z==="required"?"require":Z==="partial"?"optionalize":Z;return this.$.node("intersection",{domain:"object",structure:Q[$](...Y)})})}get(...Z){if(Z[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",Z))}extract(Z){let Y=this.$.parseDefinition(Z);return this.$.schema(this.branches.filter((X)=>X.extends(Y)))}exclude(Z){let Y=this.$.parseDefinition(Z);return this.$.schema(this.branches.filter((X)=>!X.extends(Y)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(Z){return!(this.intersect(Z)instanceof w)}extends(Z){if(this.isNever())return!0;let Y=this.intersect(Z);return!(Y instanceof w)&&this.equals(Y)}ifExtends(Z){return this.extends(Z)?this:void 0}subsumes(Z){return this.$.parseDefinition(Z).extends(this)}configure(Z,Y="shallow"){return this.configureReferences(Z,Y)}describe(Z,Y="shallow"){return this.configure({description:Z},Y)}optional(){return[this,"?"]}default(Z){return k6(this,Z,null),[this,"=",Z]}from(Z){return this.assert(Z)}_pipe(...Z){let Y=Z.reduce((X,Q)=>X.rawPipeOnce(Q),this);return this.$.finalize(Y)}tryPipe(...Z){let Y=Z.reduce((X,Q)=>X.rawPipeOnce(P(Q,"root")?Q:($,W)=>{try{return Q($,W)}catch(J){return W.error({code:"predicate",predicate:Q,actual:`aborted due to error:
|
|
109
|
-
${
|
|
110
|
-
`})}}),this);return this.$.finalize(
|
|
111
|
-
${
|
|
112
|
-
Seen: [${
|
|
113
|
-
Resolution: ${
|
|
114
|
-
|
|
115
|
-
${
|
|
116
|
-
Left: ${
|
|
117
|
-
Right: ${
|
|
475
|
+
`);class Kt{path=[];errors=new mt(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 wn(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 Bi(...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 Fn(e,this);if(this.currentBranch)this.currentBranch.error=t;else this.errors.add(t);return t}applyQueuedMorphs(){while(this.queuedMorphs.length){let e=this.queuedMorphs;this.queuedMorphs=[];for(let{path:t,morphs:n}of e){if(this.errors.affectsPath(t))continue;this.applyMorphsAtPath(t,n)}}}applyMorphsAtPath(e,t){let n=e[e.length-1],r;if(n!==void 0){r=this.root;for(let s=0;s<e.length-1;s++)r=r[e[s]]}for(let s of t){this.path=[...e];let o=$e(s),a=s(r===void 0?this.root:r[n],this);if(a instanceof Fn){if(!this.errors.includes(a))this.errors.add(a);break}if(a instanceof mt){if(!o)this.errors.merge(a);this.queuedMorphs=[];break}if(r===void 0)this.root=a;else r[n]=a;this.applyQueuedMorphs()}}}var gt=(e,t,n)=>{if(!n)return t();n.path.push(e);let r=t();return n.path.pop(),r};class Vi extends ht{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)=>aR(r,s.shallowReferences),[this]);let n=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let r=0;r<this.children.length;r++){if(this.includesTransform||=this.children[r].includesTransform,this.includesContextualPredicate||=this.children[r].includesContextualPredicate,this.isCyclic||=this.children[r].isCyclic,!n){let s=this.children[r].flatRefs;for(let o=0;o<s.length;o++){let a=s[o];if(!this.flatRefs.some((l)=>gh(l,a))){this.flatRefs.push(a);for(let l of a.node.branches)if(l.hasKind("morph")||l.hasKind("intersection")&&l.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:a.path,propString:a.propString,node:l})}}}Object.assign(this.referencesById,this.children[r].referencesById)}this.flatRefs.sort((r,s)=>r.path.length>s.path.length?1:r.path.length<s.path.length?-1:r.propString>s.propString?1:r.propString<s.propString?-1:r.node.expression<s.node.expression?-1:1),this.allowsRequiresContext=this.includesContextualPredicate||this.isCyclic,this.rootApplyStrategy=!this.allowsRequiresContext&&this.flatMorphs.length===0?this.shallowMorphs.length===0?"allows":this.shallowMorphs.every((r)=>r.length===1||r.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((r)=>r.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(r)=>this.traverseAllows(r,new Kt(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 Kt(t,this.$.resolvedConfig);return this.traverseApply(t,r),r.finalize(n)};case"contextual":return(t,n)=>{let r=new Kt(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 Kt(t,this.$.resolvedConfig);return this.traverseApply(t,r),r.finalize(n)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,he(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=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=jr(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]=ve(o)?o.map((a)=>e==="in"?a.rawIn:a.rawOut):e==="in"?o.rawIn:o.rawOut}else t[n]=r}return this.$.node(this.kind,t)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(e){let t=$e(e)?e:this.$.parseDefinition(e);return this.innerHash===t.innerHash}ifEquals(e){return this.equals(e)?this:void 0}hasKind(e){return this.kind===e}assertHasKind(e){if(this.kind!==e)nr(`${this.kind} node was not of asserted kind ${e}`);return this}hasKindIn(...e){return e.includes(this.kind)}assertHasKindIn(...e){if(!Pt(e,this.kind))nr(`${this.kind} node was not one of asserted kinds ${e}`);return this}isBasis(){return Pt(ch,this.kind)}isConstraint(){return Pt(So,this.kind)}isStructural(){return Pt(Dr,this.kind)}isRefinement(){return Pt(Xl,this.kind)}isRoot(){return Pt(Fr,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=Wi.normalize(e);return this._select(t)}_select(e){let t=Wi.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 Wi.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(!ve(f)){let h=f._transform(e,t);return h?[u,h]:[]}if(f.length===0)return[u,d];let p=f.flatMap((h)=>h._transform(e,t)??[]);return p.length?[u,p]:[]});delete t.seen[this.id];let o=Object.assign(s,{meta:this.meta}),a=t.selected&&!t.selected.includes(this)?o:e(this.kind,o,t);if(a===null)return null;if($e(a))return r=a;let l=Object.keys(a);if((l.length===0||l.length===1&&l[0]==="meta")&&!sn(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in a))return t.undeclaredKeyHandling?{...a,value:O.intrinsic.unknown}:null;if(this.kind==="morph")a.in??=O.intrinsic.unknown;return r=n.node(this.kind,a,t.parseOptions)}configureReferences(e,t="references"){let n=Wi.normalize(t),r=typeof e==="string"?(l,c)=>({...c,meta:{...c.meta,description:e}}):typeof e==="function"?(l,c)=>({...c,meta:e(c.meta)}):(l,c)=>({...c,meta:{...c.meta,...e}});if(n.boundary==="self")return this.$.node(this.kind,r(this.kind,{...this.inner,meta:this.meta}));let s=this._select(n),o=s&&Pn(s),a=n.boundary==="child"?(l,c)=>c.root.children.includes(l):n.boundary==="shallow"?(l)=>l.kind!=="structure":()=>!0;return this.$.finalize(this.transform(r,{shouldTransform:a,selected:o}))}}var Wi={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(mh(t,n));return e},find:(e)=>e[0],assertFind:(e,t,n)=>{if(e.length===0)nr(mh(t,n));return e[0]}},normalize:(e)=>typeof e==="function"?{boundary:"references",method:"filter",where:e}:typeof e==="string"?qe(e,Wi.applyBoundary)?{method:"filter",boundary:e}:{boundary:"references",method:"filter",kind:e}:{boundary:"references",method:"filter",...e}},mh=(e,t)=>`${e} had no references matching ${re(t)}.`,iR=(e)=>wn(e,{stringifyNonKey:(t)=>t.expression}),sR=/"(\$ark\.[^"]+)"/g,oR=(e)=>JSON.stringify(e).replace(sR,"$1"),Wt=(e,t)=>({path:e,node:t,propString:iR(e)}),gh=(e,t)=>e.propString===t.propString&&e.node.equals(t.node),Ql=(e,t)=>rn(e,t,{isEqual:gh}),aR=(e,t)=>rn(e,t,{isEqual:(n,r)=>n.equals(r)});class j extends Array{static init(e,t,n,r){return new j({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=wn(e);return tc(`Intersection${r&&` at ${r}`} of ${_h(t,n)}`)}return`The following intersections result in unsatisfiable types:
|
|
476
|
+
\u2022 ${this.map(({path:e,l:t,r:n})=>`${e}: ${_h(t,n)}`).join(`
|
|
477
|
+
\u2022 `)}`}throw(){return E(this.describeReasons())}invert(){let e=this.map((t)=>({...t,l:t.r,r:t.l}));if(!(e instanceof j))return new j(...e);return e}withPrefixKey(e,t){return this.map((n)=>({...n,path:[e,...n.path],optional:n.optional||t==="optional"}))}toNeverIfDisjoint(){return O.intrinsic.never}}var _h=(e,t)=>`${ec(e)} and ${ec(t)}`,ec=(e)=>$e(e)?e.expression:ve(e)?e.map(ec).join(" | ")||"never":String(e),tc=(e)=>`${e} results in an unsatisfiable type`;var Ur={},_t=(e,t,n)=>Se(e,t,{$:n,invert:!1,pipe:!1}),Gi=(e,t,n)=>Se(e,t,{$:n,invert:!1,pipe:!0}),Se=(e,t,n)=>{let r=n.pipe?"|>":"&",s=`${e.hash}${r}${t.hash}`;if(Ur[s]!==void 0)return Ur[s];if(!n.pipe){let l=`${t.hash}${r}${e.hash}`;if(Ur[l]!==void 0){let c=Ur[l],u=c instanceof j?c.invert():c;return Ur[s]=u,u}}let o=!n.pipe||!e.includesTransform&&!t.includesTransform;if(o&&e.equals(t))return e;let a=o?nc(e,t,n):e.hasKindIn(...Fr)?lR(e,t,n):nc(e,t,n);if($e(a)){if(e.equals(a))a=e;else if(t.equals(a))a=t}return Ur[s]=a,a},nc=(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 j)o=o.invert();return o}},lR=(e,t,n)=>e.includesTransform||t.includesTransform?n.invert?yh(t,e,n):yh(e,t,n):nc(e,t,n),yh=(e,t,n)=>e.distribute((r)=>cR(r,t,n),(r)=>{let s=r.filter($e);if(s.length===0)return j.init("union",e.branches,t.branches);if(s.length<e.branches.length||!e.branches.every((l,c)=>l.rawIn.equals(s[c].rawIn)))return n.$.parseSchema(s);let o;if(s.length===1){let l=s[0];if(!o)return l;return n.$.node("morph",{...l.inner,in:l.rawIn.configure(o,"self")})}let a={branches:s};if(o)a.meta=o;return n.$.parseSchema(a)}),cR=(e,t,n)=>{if(e.hasKind("morph")){let s=[...e.morphs];if(e.lastMorphIfNode){let o=Se(e.lastMorphIfNode,t,n);if(o instanceof j)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=Se(e,t.rawIn,n);if(s instanceof j)return s;return n.$.node("morph",{morphs:[t],in:s})}return n.$.node("morph",{morphs:[t],in:e})};class Tt extends Vi{constructor(e,t){super(e,t);Object.defineProperty(this,it,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(e){return _t(this,e,this.$)}}class bn extends Tt{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 Dn(this.errorContext)}}var et=(e)=>(t,n)=>{if(ve(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},Br=(e)=>{let t=e.r.shift();if(!t){let r=e.l.length===0&&e.kind==="structure"?O.intrinsic.unknown.internal:e.ctx.$.node(e.kind,Object.assign(e.baseInner,uR(e.l)),{prereduced:!0});for(let s of e.roots){if(r instanceof j)return r;r=Se(s,r,e.ctx)}return r}let n=!1;for(let r=0;r<e.l.length;r++){let s=Se(e.l[r],t,e.ctx);if(s===null)continue;if(s instanceof j)return s;if(s.isRoot())return e.roots.push(s),e.l.splice(r),Br(e);if(!n)e.l[r]=s,n=!0;else if(!e.l.includes(s))return he(`Unexpectedly encountered multiple distinct intersection results for refinement ${t}`)}if(!n)e.l.push(t);if(e.kind==="intersection"){if(t.impliedSiblings)for(let r of t.impliedSiblings)rn(e.r,r)}return Br(e)},qr=(e)=>Object.entries(e).flatMap(([n,r])=>(n in Eo)?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),uR=(e)=>{let t={};for(let n of e)if(n.hasOpenIntersection())t[n.kind]=de(t[n.kind],n);else{if(t[n.kind])return he(`Unexpected intersection of closed refinements of kind ${n.kind}`);t[n.kind]=n}return t},wh=(...e)=>E(bh(...e)),bh=(e,t,n)=>{let r=n.hasKind("morph")?"a morph":n.isUnknown()?"unknown":n.exclude(t).defaultShortDescription;return`${Vp(e)} operand must be ${t.description} (was ${r})`};var vh=(e,t,n)=>new Ln(e,t,n,n,null);class Co extends ht{}class Ln extends ht{[it]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(e,t,n,r,s){super((...o)=>{let a=ne(this.names,(l,c)=>{let u=this.arg$.parse(o[l]);if(!u.extends(this.constraints[l]))E(dR(c,this.constraints[l].expression,u.expression));return[c,u]});if(this.defIsLazy()){let l=this.bodyDef(a);return this.$.parse(l)}return this.$.parse(t,{args:a})});this.paramDefs=e,this.bodyDef=t,this.$=n,this.arg$=r,this.hkt=s,this.description=s?new s().description??`a generic type for ${s.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof Co}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:ih(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((e)=>typeof e==="string"?[e,O.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=se({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 xh extends Tt{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=Dn(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 rc={implementation:fR,Node:xh};var pR=se({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(e)=>Number.isInteger(e)?e:E(hR(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/mR(e.rule,t.rule))})},obviatesBasisDescription:!0});class kh extends bn{traverseAllows=(e)=>e%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=O.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(e){if(e.type="integer",this.rule===1)return e;return e.multipleOf=this.rule,e}}var ic={implementation:pR,Node:kh};var hR=(e)=>`divisor must be an integer (was ${e})`,mR=(e,t)=>{let n,r=e,s=t;while(s!==0)n=s,s=r%s,r=n;return r};class $t extends bn{boundOperandKind=wR[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=bR(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${gR[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 gR={"<":">=","<=":">",">":"<=",">=":"<"},_R={min:"max",minLength:"maxLength",after:"before"},Io={parse:(e)=>e||void 0},Oo=(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},Po=(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},Mo=(e)=>typeof e==="string"||typeof e==="number"?new Date(e):e,yR=(e,t)=>`${e} bound must be a positive integer (was ${t})`,Hr=(e)=>(t)=>{if(!Number.isInteger(t)||t<0)E(yR(e,t));return t},wR={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},bR=(e,t)=>`${qe(e,_R)?">":"<"}${t?"":"="}`,vR=(e)=>typeof e==="string"?e:new Date(e).toLocaleString(),Rh=(e)=>`Bounded expression ${e} must be exactly one of number, string, Array, or Date`;var xR=se({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Mo,serialize:(e)=>e.toISOString()}},normalize:Po("after"),defaults:{description:(e)=>`${e.collapsibleLimitString} or later`,actual:ar},intersections:{after:(e,t)=>e.isStricterThan(t)?e:t}});class $h extends $t{impliedBasis=O.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 sc={implementation:xR,Node:$h};var kR=se({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Mo,serialize:(e)=>e.toISOString()}},normalize:Po("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:j.init("range",e,t)}});class Sh extends $t{collapsibleLimitString=ar(this.rule);traverseAllows=(e)=>e<=this.rule;impliedBasis=O.intrinsic.Date.internal;reduceJsonSchema(e,t){return t.fallback.date({code:"date",base:e,before:this.rule})}}var oc={implementation:kR,Node:Sh};var RR=se({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:Hr("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)=>j.init("unit",n.$.node("unit",{unit:e.rule}),n.$.node("unit",{unit:t.rule}),{path:["length"]}),minLength:(e,t)=>e.rule>=t.rule?e:j.init("range",e,t),maxLength:(e,t)=>e.rule<=t.rule?e:j.init("range",e,t)}});class Eh extends bn{traverseAllows=(e)=>e.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=O.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(e){switch(e.type){case"string":return e.minLength=this.rule,e.maxLength=this.rule,e;case"array":return e.minItems=this.rule,e.maxItems=this.rule,e;default:return Ee.throwInternalOperandError("exactLength",e)}}}var ac={implementation:RR,Node:Eh};var $R=se({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:Io},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:j.init("range",e,t)},obviatesBasisDescription:!0});class Ah extends $t{impliedBasis=O.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 lc={implementation:$R,Node:Ah};var SR=se({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Hr("maxLength")}},reduce:(e,t)=>e.rule===0?t.node("exactLength",e):void 0,normalize:Oo("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:j.init("range",e,t)}});class Ch extends $t{impliedBasis=O.intrinsic.lengthBoundable.internal;traverseAllows=(e)=>e.length<=this.rule;reduceJsonSchema(e){switch(e.type){case"string":return e.maxLength=this.rule,e;case"array":return e.maxItems=this.rule,e;default:return Ee.throwInternalOperandError("maxLength",e)}}}var cc={implementation:SR,Node:Ch};var ER=se({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:Io},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 Ih extends $t{impliedBasis=O.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 uc={implementation:ER,Node:Ih};var AR=se({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Hr("minLength")}},reduce:(e)=>e.rule===0?O.intrinsic.unknown:void 0,normalize:Oo("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 Oh extends $t{impliedBasis=O.intrinsic.lengthBoundable.internal;traverseAllows=(e)=>e.length>=this.rule;reduceJsonSchema(e){switch(e.type){case"string":return e.minLength=this.rule,e;case"array":return e.minItems=this.rule,e;default:return Ee.throwInternalOperandError("minLength",e)}}}var dc={implementation:AR,Node:Oh};var Ph={min:uc.implementation,max:lc.implementation,minLength:dc.implementation,maxLength:cc.implementation,exactLength:ac.implementation,after:sc.implementation,before:oc.implementation},Mh={min:uc.Node,max:lc.Node,minLength:dc.Node,maxLength:cc.Node,exactLength:ac.Node,after:sc.Node,before:oc.Node};var CR=se({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 Th extends bn{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=O.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 fc={implementation:CR,Node:Th};var zi=(e,t)=>{let n=IR(e);if(t&&!t.includes(n))return E(`Root of kind ${n} should be one of ${t}`);return n},IR=(e)=>{if(z(e,"root"))return e.kind;if(typeof e==="string")return e[0]==="$"?"alias":(e in ft)?"domain":"proto";if(typeof e==="function")return"proto";if(typeof e!=="object"||e===null)return E(Nh(e));if("morphs"in e)return"morph";if("branches"in e||ve(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 Eo)))return"intersection";if("proto"in e)return"proto";if("domain"in e)return"domain";return E(Nh(e))},Nh=(e)=>`${re(e)} is not a valid type schema`,Dh={},OR=(e)=>ve(e)?e.map((t)=>t.collapsibleJson):e.collapsibleJson,st={};O.nodesByRegisteredId=st;var pc=(e)=>(Dh[e]??=0,`${e}${++Dh[e]}`),hc=(e)=>{let t=Kr[e.kind],n=t.applyConfig?.(e.def,e.$.resolvedConfig)??e.def,r={},{meta:s,...o}=n,a=s===void 0?{}:typeof s==="string"?{description:s}:s,l=Fl(o).sort(([u],[d])=>Lr(u)?Lr(d)?jr(u)-jr(d):1:Lr(d)?-1:u<d?-1:1).filter(([u,d])=>{if(u.startsWith("meta.")){let f=u.slice(5);return a[f]=d,!1}return!0});for(let u of l){let d=u[0],f=t.keys[d];if(!f)return E(`Key ${d} is not valid on ${e.kind} schema`);let p=f.parse?f.parse(u[1],e):u[1];if(p!==pt&&(p!==void 0||f.preserveUndefined))r[d]=p}if(t.reduce&&!e.prereduced){let u=t.reduce(r,e.$);if(u){if(u instanceof j)return u.throw();return PR(u,a)}}return mc({id:e.id,kind:e.kind,inner:r,meta:a,$:e.$})},mc=({id:e,kind:t,inner:n,meta:r,$:s,ignoreCache:o})=>{let a=Kr[t],l=Fl(n),c=[],u={};for(let[v,y]of l){let P=a.keys[v],D=P.serialize??(P.child?OR:Mt);if(u[v]=D(y),P.child===!0){let g=y;if(ve(g))c.push(...g);else c.push(g)}else if(typeof P.child==="function")c.push(...P.child(y))}if(a.finalizeInnerJson)u=a.finalizeInnerJson(u);let d={...u},f={};if(!sn(r))f=ne(r,(v,y)=>[v,v==="examples"?y:Mt(y)]),d.meta=To(f,"description",!0);u=To(u,a.collapsibleKey,!1);let p=JSON.stringify({kind:t,...u});d=To(d,a.collapsibleKey,!1);let h=To(d,a.collapsibleKey,!0),x=JSON.stringify({kind:t,...d});if(s.nodesByHash[x]&&!o)return s.nodesByHash[x];let R={id:e,kind:t,impl:a,inner:n,innerEntries:l,innerJson:u,innerHash:p,meta:r,metaJson:f,json:d,hash:x,collapsibleJson:h,children:c};if(t!=="intersection"){for(let v in n)if(v!=="in"&&v!=="out")R[v]=n[v]}let w=new Lh[t](R,s);return s.nodesByHash[x]=w},Fh=(e,t)=>{if(e.id===t)return e;if($e(st[t]))he(`Unexpected attempt to overwrite node id ${t}`);return mc({id:t,kind:e.kind,inner:e.inner,meta:e.meta,$:e.$,ignoreCache:!0})},PR=(e,t,n)=>{if(n&&$e(st[n]))he(`Unexpected attempt to overwrite node id ${n}`);return mc({id:n??pc(t.alias??e.kind),kind:e.kind,inner:e.inner,meta:t,$:e.$})},To=(e,t,n)=>{let r=Object.keys(e);if(r.length===1&&r[0]===t){let s=e[t];if(n)return s;if(dt(s,"object")&&(Object.keys(s).length===1||Array.isArray(s)))return s}return e};var Ji=(e,t,n)=>{if(e.key!==t.key)return null;let r=e.key,s=Se(e.value,t.value,n),o=e.required||t.required?"required":"optional";if(s instanceof j)if(o==="optional")s=O.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(gc(e.default,t.default)):e.default:t.hasDefault()?t.default:pt;return n.$.node("optional",{key:r,value:s,default:a})};class Xi extends Tt{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=O.intrinsic.object.internal;serializedKey=Ht(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=de(this.value.flatRefs.map((e)=>Wt([this.key,...e.path],e.node)),Wt([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 gt(this.key,()=>this.value.traverseAllows(e[this.key],t),t);return this.optional};traverseApply=(e,t)=>{if(this.key in e)gt(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 gc=(e,t)=>`Invalid intersection of default values ${re(e)} & ${re(t)}`;var MR=se({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(Q.undefined)},{prereduced:!0})}},defaults:{description:(e)=>`${e.compiledKey}?: ${e.value.description}`},intersections:{optional:Ji}});class jh extends Xi{constructor(...e){super(...e);if("default"in this.inner)Zi(this.value,this.inner.default,this.key)}get rawIn(){let e=super.rawIn;if(!this.hasDefault())return e;return this.$.node("optional",bo(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=NR(this);defaultValueMorphRef=this.defaultValueMorph&&Me(this.defaultValueMorph)}var Yi={implementation:MR,Node:jh},TR={},NR=(e)=>{if(!e.hasDefault())return;let t=`{${e.compiledKey}: ${e.value.id} = ${Mt(e.default)}}`;return TR[t]??=_c(e.key,e.value,e.default)},_c=(e,t,n)=>{if(typeof n==="function")return t.includesTransform?(s,o)=>(gt(e,()=>t(s[e]=n(),o),o),s):(s)=>(s[e]=n(),s);let r=t.includesTransform?t.assert(n):n;return dt(r,"object")?(s,o)=>(gt(e,()=>t(s[e]=n,o),o),s):(s)=>(s[e]=r,s)},Zi=(e,t,n)=>{let r=Mn(t);if(dt(t,"object")&&!r)E(DR(n));let s=e.in(r?t():t);if(s instanceof mt){if(n===null)E(`Default ${s.summary}`);let o=s.transform((a)=>a.transform((l)=>({...l,prefixPath:[n]})));E(`Default for ${o.summary}`)}return t},DR=(e)=>`Non-primitive default ${e===null?"":typeof e==="number"?`for value at [${e}] `:`for ${Ht(e)} `}must be specified as a function like () => ({my: 'object'})`;class Nt extends Vi{constructor(e,t){super(e,t);Object.defineProperty(this,it,{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 mt)return t;return{value:t}},jsonSchema:{input:(e)=>this.rawIn.toJsonSchema({target:Uh(e.target),...e.libraryOptions}),output:(e)=>this.rawOut.toJsonSchema({target:Uh(e.target),...e.libraryOptions})}}}as(){return this}brand(e){if(e==="")return E(FR);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=Yl(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 j)return n;return this.$.finalize(n)}rawIntersect(e){return _t(this,e,this.$)}toNeverIfDisjoint(){return this}and(e){let t=this.intersect(e);return t instanceof j?t.throw():t}rawAnd(e){let t=this.rawIntersect(e);return t instanceof j?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(),O.intrinsic.unknown.internal);if(e.branches.length===0)E(tc(`keyof ${this.expression}`));return this._keyof=this.$.finalize(e)}get props(){if(this.branches.length!==1)return E(jR(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(e){let t=this.$.parseDefinition(e);return this.$.schema(t.distribute((n)=>this.applyStructuralOperation("merge",[Bh(n)??E(qh("merge",n.expression))])))}applyStructuralOperation(e,t){return this.distribute((n)=>{if(n.equals(O.intrinsic.object)&&e!=="merge")return n;let r=Bh(n);if(!r)E(qh(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 j)}extends(e){if(this.isNever())return!0;let t=this.intersect(e);return!(t instanceof j)&&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 Zi(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:
|
|
478
|
+
${a}
|
|
479
|
+
`})}}),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=Gi(this,e,this.$);if(t instanceof j)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:he(`Unexpected constraint node ${r}`);let s=e==="root"?this:e==="in"?this.rawIn:this.rawOut;if(s.hasKind("morph")||r.impliedBasis&&!s.extends(r.impliedBasis))return wh(t,r.impliedBasis,this);let o=this.$.node("intersection",{[r.kind]:r}),a=e==="out"?Gi(this,o,this.$):_t(this,o,this.$);if(a instanceof j)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"?bo(s,{undeclared:1}):{...s,undeclared:t}:s,n?void 0:{shouldTransform:(r)=>!Pt(Dr,r.kind)}))}hasEqualMorphs(e){if(!this.includesTransform&&!e.includesTransform)return!0;if(!_n(this.shallowMorphs,e.shallowMorphs))return!1;if(!_n(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",Wr(e))}lessThan(e){return this.constrain("max",Wr(e))}atLeastLength(e){return this.constrain("minLength",e)}atMostLength(e){return this.constrain("maxLength",e)}moreThanLength(e){return this.constrain("minLength",Wr(e))}lessThanLength(e){return this.constrain("maxLength",Wr(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",Wr(e))}earlierThan(e){return this.constrain("before",Wr(e))}}var FR="Expected a non-empty brand name after #",Hh=["draft-2020-12","draft-07"],LR=(e)=>`JSONSchema target '${e}' is not supported (must be ${Hh.map((t)=>`"${t}"`).join(" or ")})`,Uh=(e)=>{if(!Pt(Hh,e))E(LR(e));return e},Wr=(e)=>typeof e==="object"&&!(e instanceof Date)?{...e,exclusive:!0}:{rule:e,exclusive:!0},Qi=(e,t)=>z(t,"root")?z(e,"root")?e.extends(t):t.allows(e):z(e,"root")?e.hasUnit(t):t===e,Bh=(e)=>{if(e.hasKind("morph"))return null;if(e.hasKind("intersection"))return e.inner.structure??(e.basis?.domain==="object"?e.$.bindReference(O.intrinsic.emptyStructure):null);if(e.isBasis()&&e.domain==="object")return e.$.bindReference(O.intrinsic.emptyStructure);return null},jR=(e)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
|
|
480
|
+
${e}`,qh=(e,t)=>`${e} operand must be an object (was ${t})`;var on=(e,t)=>ne(Ao(e),(n,r)=>[r,t]);var UR=(e)=>typeof e==="string"?{reference:e}:e,Kh=(e)=>e instanceof j?O.intrinsic.never.internal:e,BR=se({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(e)=>e.startsWith("$")?e:`$ark.${e}`},resolve:{}},normalize:UR,defaults:{description:(e)=>e.reference},intersections:{alias:(e,t,n)=>n.$.lazilyResolve(()=>Kh(Se(e.resolution,t.resolution,n)),`${e.reference}${n.pipe?"=>":"&"}${t.reference}`),...on("alias",(e,t,n)=>{if(t.isUnknown())return e;if(t.isNever())return t;if(t.isBasis()&&!t.overlaps(O.intrinsic.object))return j.init("assignability",O.intrinsic.object,t);return n.$.lazilyResolve(()=>Kh(Se(e.resolution,t,n)),`${e.reference}${n.pipe?"=>":"&"}${t.id}`)})}});class Wh extends Nt{expression=this.reference;structure=void 0;get resolution(){let e=this._resolve();return st[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=st[e],n=[];while(z(t,"context")){if(n.includes(t.id))return E(qR(t.id,n));n.push(t.id),t=st[t.id]}if(!z(t,"root"))return he(`Unexpected resolution for reference ${this.reference}
|
|
481
|
+
Seen: [${n.join("->")}]
|
|
482
|
+
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 he(`Unexpected resolution for reference ${this.reference}: ${re(t)}`)}get defaultShortDescription(){return ft.object}innerToJsonSchema(e){return this.resolution.toJsonSchemaRecurse(e)}traverseAllows=(e,t)=>{let n=t.seen[this.reference];if(n?.includes(e))return!0;return t.seen[this.reference]=de(n,e),this.resolution.traverseAllows(e,t)};traverseApply=(e,t)=>{let n=t.seen[this.reference];if(n?.includes(e))return;t.seen[this.reference]=de(n,e),this.resolution.traverseApply(e,t)};compile(e){let t=this.resolutionId;e.if(`ctx.seen.${t} && ctx.seen.${t}.includes(data)`,()=>e.return(!0)),e.if(`!ctx.seen.${t}`,()=>e.line(`ctx.seen.${t} = []`)),e.line(`ctx.seen.${t}.push(data)`),e.return(e.invoke(t))}}var qR=(e,t)=>`Alias '${e}' has a shallow resolution cycle: ${[...t,e].join("->")}`,es={implementation:BR,Node:Wh};class lr extends Nt{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 Dn(this.errorContext)}compile(e){if(e.traversalKind==="Allows")e.return(this.compiledCondition);else e.if(this.compiledNegation,()=>e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}}var HR=se({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(e)=>typeof e==="string"?{domain:e}:Tr(e,"numberAllowsNaN")&&e.domain!=="number"?E(No.writeBadAllowNanMessage(e.domain)):e,applyConfig:(e,t)=>e.numberAllowsNaN===void 0&&e.domain==="number"&&t.numberAllowsNaN?{...e,numberAllowsNaN:!0}:e,defaults:{description:(e)=>ft[e.domain],actual:(e)=>Number.isNaN(e)?"NaN":ft[Be(e)]},intersections:{domain:(e,t)=>e.domain==="number"&&t.domain==="number"?e.numberAllowsNaN?t:e:j.init("domain",e,t)}});class Vh extends lr{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?(e)=>typeof e==="number"&&!Number.isNaN(e):(e)=>Be(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 ft[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 No={implementation:HR,Node:Vh,writeBadAllowNanMessage:(e)=>`numberAllowsNaN may only be specified with domain "number" (was ${e})`};var KR=se({kind:"intersection",hasAssociatedError:!0,normalize:(e)=>{if($e(e))return e;let{structure:t,...n}=e,r=!!t,s=t??{},o=ne(n,(a,l)=>{if(qe(a,uh)){if(r)E(`Flattened structure key ${a} cannot be specified alongside a root 'structure' key.`);return s[a]=l,[]}return[a,l]});if(z(s,"constraint")||!sn(s))o.structure=s;return o},finalizeInnerJson:({structure:e,...t})=>dt(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:et("divisor")},max:{child:!0,parse:et("max")},min:{child:!0,parse:et("min")},maxLength:{child:!0,parse:et("maxLength")},minLength:{child:!0,parse:et("minLength")},exactLength:{child:!0,parse:et("exactLength")},before:{child:!0,parse:et("before")},after:{child:!0,parse:et("after")},pattern:{child:!0,parse:et("pattern")},predicate:{child:!0,parse:et("predicate")}},reduce:(e,t)=>Gh({},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(`
|
|
483
|
+
\u25E6 `)}`,problem:(e)=>`(${e.actual}) must be...
|
|
484
|
+
${e.expected}`},intersections:{intersection:(e,t,n)=>Gh(e.inner,t.inner,n),...on("intersection",(e,t,n)=>{if(e.children.length===0)return t;let{domain:r,proto:s,...o}=e.inner,a=s??r,l=a?Se(a,t,n):t;return l instanceof j?l:e?.basis?.equals(l)?e:e.$.node("intersection",{...o,[l.kind]:l},{prereduced:!0})})}});class zh extends Nt{basis=this.inner.domain??this.inner.proto??null;prestructurals=[];refinements=this.children.filter((e)=>{if(!e.isRefinement())return!1;if(Pt(Jl,e.kind))this.prestructurals.push(e);return!0});structure=this.inner.structure;expression=WR(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 yc={implementation:KR,Node:zh},WR=(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"},Gh=(e,t,n)=>{let r={},s=e.proto??e.domain,o=t.proto??t.domain,a=s?o?Se(s,o,n):s:o;if(a instanceof j)return a;if(a)r[a.kind]=a;return Br({kind:"intersection",baseInner:r,l:qr(e),r:qr(t),roots:[],ctx:n})};var VR=se({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(e,t)=>t.$.parseSchema(e)},morphs:{parse:Pn,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(GR(e.expression,t.expression));let r=Se(e.rawIn,t.rawIn,n);if(r instanceof j)return r;let s={morphs:e.morphs};if(e.declaredIn||t.declaredIn){let o=Se(e.rawIn,t.rawIn,n);if(o instanceof j)return o.throw();else s.declaredIn=o}if(e.declaredOut||t.declaredOut){let o=Se(e.rawOut,t.rawOut,n);if(o instanceof j)return o.throw();else s.declaredOut=o}return r.distribute((o)=>n.$.node("morph",{...s,in:o}),n.$.parseSchema)},...on("morph",(e,t,n)=>{let r=e.inner.in?Se(e.inner.in,t,n):t;return r instanceof j?r:r.equals(e.inner.in)?e:n.$.node("morph",{...e.inner,in:r})})}});class Jh extends Nt{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??O.intrinsic.unknown.internal}get rawOut(){return this.declaredOut??this.introspectableOut??O.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 _n(this.morphs,e.morphs,{isEqual:(t,n)=>t===n||z(t,"root")&&z(n,"root")&&t.equals(n)})}}var wc={implementation:VR,Node:Jh},GR=(e,t)=>`The intersection of distinct morphs at a single path is indeterminate:
|
|
485
|
+
Left: ${e}
|
|
486
|
+
Right: ${t}`;var zR=se({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(e)=>Di(e)??Mt(e)},dateAllowsInvalid:{}},normalize:(e)=>{let t=typeof e==="string"?{proto:ir[e]}:typeof e==="function"?$e(e)?e:{proto:e}:typeof e.proto==="string"?{...e,proto:ir[e.proto]}:e;if(typeof t.proto!=="function")E(ts.writeInvalidSchemaMessage(t.proto));if(Tr(t,"dateAllowsInvalid")&&t.proto!==Date)E(ts.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?jp[e.builtinName]:`an instance of ${e.proto.name}`,actual:(e)=>e instanceof Date&&e.toString()==="Invalid Date"?"an invalid Date":Ni(e)},intersections:{proto:(e,t)=>e.proto===Date&&t.proto===Date?e.dateAllowsInvalid?t:e:ql(e.proto,t.proto)?e:ql(t.proto,e.proto)?t:j.init("proto",e,t),domain:(e,t)=>t.domain==="object"?e:j.init("domain",O.intrinsic.object.internal,t)}});class Xh extends lr{builtinName=Di(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 ts={implementation:zR,Node:Xh,writeBadInvalidDateMessage:(e)=>`dateAllowsInvalid may only be specified with constructor Date (was ${e.name})`,writeInvalidSchemaMessage:(e)=>`instanceOf operand must be a function (was ${Be(e)})`};var JR=se({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((l)=>l.hasKind("morph")&&l.hasEqualMorphs(o));if(a===-1)n.push(o);else{let l=n[a];n[a]=t.$.node("morph",{...l.inner,in:l.rawIn.rawOr(o.rawIn)})}}else n.push(o)}if(!t.def.ordered)n.sort((r,s)=>r.hash<s.hash?-1:1);return n}}},normalize:(e)=>ve(e)?{branches:e}:e,reduce:(e,t)=>{let n=s$(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,Vr),expected:(e)=>{let t=Op(e.errors,"propString"),n=Object.entries(t).map(([r,s])=>{let o=[];for(let c of s)rn(o,c.expected);let a=Vr(o),l=s.every((c)=>c.actual===s[0].actual)?s[0].actual:re(s[0].data);return`${r&&`${r} `}must be ${a}${l&&` (was ${l})`}`});return Vr(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 j.init("presence",e,t);let r;if(e.ordered){if(t.ordered)E(a$(e.expression,t.expression));if(r=bc(t.branches,e.branches,n),r instanceof j)r.invert()}else r=bc(e.branches,t.branches,n);if(r instanceof j)return r;return n.$.parseSchema(e.ordered||t.ordered?{branches:r,ordered:!0}:{branches:r})},...on("union",(e,t,n)=>{let r=bc(e.branches,[t],n);if(r instanceof j)return r;if(r.length===1)return r[0];return n.$.parseSchema(e.ordered?{branches:r,ordered:!0}:{branches:r})})}});class Qh extends Nt{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]=O.intrinsic.boolean;continue}e.push(n)}return e}unitBranches=this.branches.filter((e)=>e.rawIn.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?n$(this.discriminant):null;expression=this.distribute((e)=>e.nestableExpression,i$);createBranchedOptimisticRootApply(){return(e,t)=>{let n=this.traverseOptimistic(e);if(n!==pt)return n;let r=new Kt(e,this.$.resolvedConfig);return this.traverseApply(e,r),r.finalize(t)}}get shallowMorphs(){return this.branches.reduce((e,t)=>rn(e,t.shallowMorphs),[])}get defaultShortDescription(){return this.distribute((e)=>e.defaultShortDescription,Vr)}innerToJsonSchema(e){if(this.branchGroups.length===1&&this.branchGroups[0].equals(O.intrinsic.boolean))return{type:"boolean"};let t=this.branchGroups.map((n)=>n.toJsonSchemaRecurse(e));if(t.every((n)=>Object.keys(n).length===1&&Tr(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 pt};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) : "${pt}"`;else p=`${e.invoke(d)} ? data : "${pt}"`;else p=e.invoke(d);e.line(`${f}: return ${p}`)}return e}),e.traversalKind==="Allows"){e.return(s?`"${pt}"`:!1);return}let o=Vr(this.discriminant.kind==="domain"?r.map((u)=>{let d=u.slice(1,-1);return d==="function"?ft.object:ft[d]}):r),a=this.discriminant.path.map((u)=>typeof u==="symbol"?Me(u):JSON.stringify(u)),l=JSON.stringify(o),c=this.discriminant.kind==="domain"?`${e$}[${t}]`:`${t$}(${t})`;e.line(`ctx.errorFromNodeContext({
|
|
118
487
|
code: "predicate",
|
|
119
|
-
expected: ${
|
|
120
|
-
actual: ${
|
|
121
|
-
relativePath: [${
|
|
488
|
+
expected: ${l},
|
|
489
|
+
actual: ${c},
|
|
490
|
+
relativePath: [${a}],
|
|
122
491
|
meta: ${this.compiledMeta}
|
|
123
|
-
})`)}compileIndiscriminable(
|
|
124
|
-
Left: ${
|
|
125
|
-
Right: ${
|
|
126
|
-
Left: ${
|
|
127
|
-
Right: ${Y}`;var xM=v({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(Z)=>Z instanceof Date?Z.toISOString():Q0(Z)}},normalize:(Z)=>Z,defaults:{description:(Z)=>x(Z.unit),problem:({expected:Z,actual:Y})=>`${Z===Y?`must be reference equal to ${Z} (serialized to the same value)`:`must be ${Z} (was ${Y})`}`},intersections:{unit:(Z,Y)=>w.init("unit",Z,Y),...w0("unit",(Z,Y)=>{if(Y.allows(Z.unit))return Z;let X=Y.hasKind("intersection")?Y.basis:Y;if(X){let Q=X.hasKind("domain")?X:F.intrinsic.object;if(Z.domain!==Q.domain){let $=Z.domain==="undefined"||Z.domain==="null"||Z.domain==="boolean"?Z.domain:F.intrinsic[Z.domain];return w.init("domain",$,Q)}}return w.init("assignability",Z,Y.hasKind("intersection")?Y.children.find((Q)=>!Q.allows(Z.unit)):Y)})}});class lJ extends T9{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=cJ(this.unit,this.serializedValue);compiledNegation=cJ(this.unit,this.serializedValue,"negated");expression=x(this.unit);domain=F1(this.unit);get defaultShortDescription(){return this.domain==="object"?f1.object:this.description}innerToJsonSchema(Z){return this.unit===null?{type:"null"}:F.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:Z.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?(Z)=>Z instanceof Date&&Z.toISOString()===this.compiledValue:Number.isNaN(this.unit)?(Z)=>Number.isNaN(Z):(Z)=>Z===this.unit}var G7={implementation:xM,Node:lJ},cJ=(Z,Y,X)=>{if(Z instanceof Date){let Q=`data instanceof Date && data.toISOString() === ${Y}`;return X?`!(${Q})`:Q}if(Number.isNaN(Z))return`${X?"!":""}Number.isNaN(data)`;return`data ${X?"!":"="}== ${Y}`};var kM=v({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(Z,Y)=>{let X=Y.$.parseSchema(Z);if(!X.extends(F.intrinsic.key))return L(fM(X.expression));let Q=X.branches.filter(($)=>$.hasKind("unit"));if(Q.length)return L(vM(Q.map(($)=>x($.unit))));return X}},value:{child:!0,parse:(Z,Y)=>Y.$.parseSchema(Z)}},normalize:(Z)=>Z,defaults:{description:(Z)=>`[${Z.signature.expression}]: ${Z.value.description}`},intersections:{index:(Z,Y,X)=>{if(Z.signature.equals(Y.signature)){let Q=s(Z.value,Y.value,X),$=Q instanceof w?F.intrinsic.never.internal:Q;return X.$.node("index",{signature:Z.signature,value:$})}if(Z.signature.extends(Y.signature)&&Z.value.subsumes(Y.value))return Y;if(Y.signature.extends(Z.signature)&&Y.value.subsumes(Z.value))return Z;return null}}});class iJ extends $0{impliedBasis=F.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=h(this.value.flatRefs.map((Z)=>K0([this.signature,...Z.path],Z.node)),K0([this.signature],this.value));traverseAllows=(Z,Y)=>D9(Z).every((X)=>{if(this.signature.traverseAllows(X[0],Y))return m1(X[0],()=>this.value.traverseAllows(X[1],Y),Y);return!0});traverseApply=(Z,Y)=>{for(let X of D9(Z))if(this.signature.traverseAllows(X[0],Y))m1(X[0],()=>this.value.traverseApply(X[1],Y),Y)};_transform(Z,Y){Y.path.push(this.signature);let X=super._transform(Z,Y);return Y.path.pop(),X}compile(){}}var K7={implementation:kM,Node:iJ},vM=(Z)=>`Index keys ${Z.join(", ")} should be specified as named props.`,fM=(Z)=>`Indexed key definition '${Z}' must be a string or symbol`;var hM=v({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(Z,Y)=>Y.$.parseSchema(Z)}},normalize:(Z)=>Z,defaults:{description:(Z)=>`${Z.compiledKey}: ${Z.value.description}`,expected:(Z)=>Z.missingValueDescription,actual:()=>"missing"},intersections:{required:y6,optional:y6}});class oJ extends b6{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=t0(this.errorContext)}var B7={implementation:hM,Node:oJ};var gM=v({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(Z,Y)=>{if(Z.length===0)return;return Z.map((X)=>Y.$.parseSchema(X))}},optionals:{child:!0,parse:(Z,Y)=>{if(Z.length===0)return;return Z.map((X)=>Y.$.parseSchema(X))}},defaultables:{child:(Z)=>Z.map((Y)=>Y[0]),parse:(Z,Y)=>{if(Z.length===0)return;return Z.map((X)=>{let Q=Y.$.parseSchema(X[0]);return k6(Q,X[1],null),[Q,X[1]]})},serialize:(Z)=>Z.map((Y)=>[Y[0].collapsibleJson,Q0(Y[1])]),reduceIo:(Z,Y,X)=>{if(Z==="in"){Y.optionals=X.map((Q)=>Q[0].rawIn);return}Y.prefix=X.map((Q)=>Q[0].rawOut);return}},variadic:{child:!0,parse:(Z,Y)=>Y.$.parseSchema(Z,Y)},minVariadicLength:{parse:(Z)=>Z===0?void 0:Z},postfix:{child:!0,parse:(Z,Y)=>{if(Z.length===0)return;return Z.map((X)=>Y.$.parseSchema(X))}}},normalize:(Z)=>{if(typeof Z==="string")return{variadic:Z};if("variadic"in Z||"prefix"in Z||"defaultables"in Z||"optionals"in Z||"postfix"in Z||"minVariadicLength"in Z){if(Z.postfix?.length){if(!Z.variadic)return L(dM);if(Z.optionals?.length||Z.defaultables?.length)return L(M7)}if(Z.minVariadicLength&&!Z.variadic)return L("minVariadicLength may not be specified without a variadic element");return Z}return{variadic:Z}},reduce:(Z,Y)=>{let X=Z.minVariadicLength??0,Q=Z.prefix?.slice()??[],$=Z.defaultables?.slice()??[],W=Z.optionals?.slice()??[],J=Z.postfix?.slice()??[];if(Z.variadic){while(W[W.length-1]?.equals(Z.variadic))W.pop();if(W.length===0&&$.length===0)while(Q[Q.length-1]?.equals(Z.variadic))Q.pop(),X++;while(J[0]?.equals(Z.variadic))J.shift(),X++}else if(W.length===0&&$.length===0)Q.push(...J.splice(0));if(X!==Z.minVariadicLength||Z.prefix&&Z.prefix.length!==Q.length)return Y.node("sequence",{...Z,prefix:Q,defaultables:$,optionals:W,postfix:J,minVariadicLength:X},{prereduced:!0})},defaults:{description:(Z)=>{if(Z.isVariadicOnly)return`${Z.variadic.nestableExpression}[]`;return`[${Z.tuple.map((X)=>X.kind==="defaultables"?`${X.node.nestableExpression} = ${x(X.default)}`:X.kind==="optionals"?`${X.node.nestableExpression}?`:X.kind==="variadic"?`...${X.node.nestableExpression}[]`:X.node.expression).join(", ")}]`}},intersections:{sequence:(Z,Y,X)=>{let Q=g6({l:Z.tuple,r:Y.tuple,disjoint:new w,result:[],fixedVariants:[],ctx:X}),$=Q.disjoint.length===0?[Q,...Q.fixedVariants]:Q.fixedVariants;return $.length===0?Q.disjoint:$.length===1?X.$.node("sequence",nJ($[0].result)):X.$.node("union",$.map((W)=>({proto:Array,sequence:nJ(W.result)})))}}});class rJ extends $0{impliedBasis=F.intrinsic.Array.internal;tuple=pM(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((Z)=>{if(Z.kind==="defaultables"||Z.kind==="optionals")return this.defaultablesAndOptionals.push(Z.node),!0;return Z.kind==="prefix"});variadicOrPostfix=x0(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return dY(this.flatRefs,this.prevariadic.flatMap((Z,Y)=>h(Z.node.flatRefs.map((X)=>K0([`${Y}`,...X.path],X.node)),K0([`${Y}`],Z.node)))),dY(this.flatRefs,this.variadicOrPostfix.flatMap((Z)=>h(Z.flatRefs.map((Y)=>K0([F.intrinsic.nonNegativeIntegerString.internal,...Y.path],Y.node)),K0([F.intrinsic.nonNegativeIntegerString.internal],Z)))),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=mM(this);defaultValueMorphsReference=this.defaultValueMorphs.length?Q1(this.defaultValueMorphs):void 0;elementAtIndex(Z,Y){if(Y<this.prevariadic.length)return this.tuple[Y];let X=Z.length-this.postfixLength;if(Y>=X)return{kind:"postfix",node:this.postfix[Y-X]};return{kind:"variadic",node:this.variadic??u(`Unexpected attempt to access index ${Y} on ${this}`)}}traverseAllows=(Z,Y)=>{for(let X=0;X<Z.length;X++)if(!this.elementAtIndex(Z,X).node.traverseAllows(Z[X],Y))return!1;return!0};traverseApply=(Z,Y)=>{let X=0;for(;X<Z.length;X++)m1(X,()=>this.elementAtIndex(Z,X).node.traverseApply(Z[X],Y),Y)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(Z){if(this.prefix)for(let[Y,X]of this.prefix.entries())Z.traverseKey(`${Y}`,`data[${Y}]`,X);for(let[Y,X]of this.defaultablesAndOptionals.entries()){let Q=`${Y+this.prefixLength}`;Z.if(`${Q} >= data.length`,()=>Z.traversalKind==="Allows"?Z.return(!0):Z.return()),Z.traverseKey(Q,`data[${Q}]`,X)}if(this.variadic){if(this.postfix)Z.const("firstPostfixIndex",`data.length${this.postfix?`- ${this.postfix.length}`:""}`);if(Z.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>Z.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[Y,X]of this.postfix.entries()){let Q=`firstPostfixIndex + ${Y}`;Z.traverseKey(Q,`data[${Q}]`,X)}}if(Z.traversalKind==="Allows")Z.return(!0)}_transform(Z,Y){Y.path.push(F.intrinsic.nonNegativeIntegerString.internal);let X=super._transform(Z,Y);return Y.path.pop(),X}expression=this.description;reduceJsonSchema(Z,Y){let X=Y.target==="draft-07";if(this.prevariadic.length){let Q=this.prevariadic.map(($)=>{let W=$.node.toJsonSchemaRecurse(Y);if($.kind==="defaultables"){let J=typeof $.default==="function"?$.default():$.default;W.default=F.intrinsic.jsonData.allows(J)?J:Y.fallback.defaultValue({code:"defaultValue",base:W,value:J})}return W});if(X)Z.items=Q;else Z.prefixItems=Q}if(this.minLength)Z.minItems=this.minLength;if(this.variadic){let Q=this.variadic.toJsonSchemaRecurse(Y);if(X&&this.prevariadic.length)Z.additionalItems=Q;else Z.items=Q;if(this.maxLength)Z.maxItems=this.maxLength;if(this.postfix){let $=this.postfix.map((W)=>W.toJsonSchemaRecurse(Y));Z=Y.fallback.arrayPostfix({code:"arrayPostfix",base:Z,elements:$})}}else{if(X)Z.additionalItems=!1;else Z.items=!1;delete Z.maxItems}return Z}}var uM={},mM=(Z)=>{if(!Z.defaultables)return[];let Y=[],X="[",Q=Z.prefixLength+Z.defaultablesLength-1;for(let $=Z.prefixLength;$<=Q;$++){let[W,J]=Z.defaultables[$-Z.prefixLength];Y.push(z7($,W,J)),X+=`${$}: ${W.id} = ${Q0(J)}, `}return X+="]",uM[X]??=Y},L7={implementation:gM,Node:rJ},pM=(Z)=>{let Y=[];if(Z.prefix)for(let X of Z.prefix)Y.push({kind:"prefix",node:X});if(Z.defaultables)for(let[X,Q]of Z.defaultables)Y.push({kind:"defaultables",node:X,default:Q});if(Z.optionals)for(let X of Z.optionals)Y.push({kind:"optionals",node:X});if(Z.variadic)Y.push({kind:"variadic",node:Z.variadic});if(Z.postfix)for(let X of Z.postfix)Y.push({kind:"postfix",node:X});return Y},nJ=(Z)=>Z.reduce((Y,X)=>{if(X.kind==="variadic")Y.variadic=X.node;else if(X.kind==="defaultables")Y.defaultables=h(Y.defaultables,[[X.node,X.default]]);else Y[X.kind]=h(Y[X.kind],X.node);return Y},{}),M7="A postfix required element cannot follow an optional or defaultable element",dM="A postfix element requires a variadic element",g6=(Z)=>{let[Y,...X]=Z.l,[Q,...$]=Z.r;if(!Y||!Q)return Z;let W=X[X.length-1]?.kind==="postfix",J=$[$.length-1]?.kind==="postfix",z=Y.kind==="prefix"||Q.kind==="prefix"?"prefix":Y.kind==="postfix"||Q.kind==="postfix"?"postfix":Y.kind==="variadic"&&Q.kind==="variadic"?"variadic":W||J?"prefix":Y.kind==="defaultables"||Q.kind==="defaultables"?"defaultables":"optionals";if(Y.kind==="prefix"&&Q.kind==="variadic"&&J){let H=g6({...Z,fixedVariants:[],r:$.map((G)=>({...G,kind:"prefix"}))});if(H.disjoint.length===0)Z.fixedVariants.push(H)}else if(Q.kind==="prefix"&&Y.kind==="variadic"&&W){let H=g6({...Z,fixedVariants:[],l:X.map((G)=>({...G,kind:"prefix"}))});if(H.disjoint.length===0)Z.fixedVariants.push(H)}let V=s(Y.node,Q.node,Z.ctx);if(V instanceof w)if(z==="prefix"||z==="postfix")Z.disjoint.push(...V.withPrefixKey(z==="prefix"?Z.result.length:`-${X.length+1}`,aJ(Y)&&aJ(Q)?"required":"optional")),Z.result=[...Z.result,{kind:z,node:F.intrinsic.never.internal}];else if(z==="optionals"||z==="defaultables")return Z;else return g6({...Z,fixedVariants:[],l:X.map((H)=>({...H,kind:"prefix"})),r:X.map((H)=>({...H,kind:"prefix"}))});else if(z==="defaultables"){if(Y.kind==="defaultables"&&Q.kind==="defaultables"&&Y.default!==Q.default)L(J7(Y.default,Q.default));Z.result=[...Z.result,{kind:z,node:V,default:Y.kind==="defaultables"?Y.default:Q.kind==="defaultables"?Q.default:u(`Unexpected defaultable intersection from ${Y.kind} and ${Q.kind} elements.`)}]}else Z.result=[...Z.result,{kind:z,node:V}];let q=Z.l.length,U=Z.r.length;if(Y.kind!=="variadic"||q>=U&&(Q.kind==="variadic"||U===1))Z.l=X;if(Q.kind!=="variadic"||U>=q&&(Y.kind==="variadic"||q===1))Z.r=$;return g6(Z)},aJ=(Z)=>Z.kind==="prefix"||Z.kind==="postfix";var Zz=(Z)=>(Y)=>{if(Y.props.length||Y.index){let X=Y.index?.map(($)=>$[Z])??[];for(let $ of Y.props)X.push($[Z]);if(Y.undeclared)X.push(`+ (undeclared): ${Y.undeclared}`);let Q=`{ ${X.join(", ")} }`;return Y.sequence?`${Q} & ${Y.sequence.description}`:Q}return Y.sequence?.description??"{}"},cM=Zz("description"),lM=Zz("expression"),sJ=(Z,Y,X)=>{let Q=Z.required?"required":"optional";if(!Y.signature.allows(Z.key))return null;let $=p1(Z.value,Y.value,X);if($ instanceof w)return Q==="optional"?X.node("optional",{key:Z.key,value:F.intrinsic.never.internal}):$.withPrefixKey(Z.key,Z.kind);return null},iM=v({kind:"structure",hasAssociatedError:!1,normalize:(Z)=>Z,applyConfig:(Z,Y)=>{if(!Z.undeclared&&Y.onUndeclaredKey!=="ignore")return{...Z,undeclared:Y.onUndeclaredKey};return Z},keys:{required:{child:!0,parse:I1("required"),reduceIo:(Z,Y,X)=>{Y.required=h(Y.required,X.map((Q)=>Z==="in"?Q.rawIn:Q.rawOut));return}},optional:{child:!0,parse:I1("optional"),reduceIo:(Z,Y,X)=>{if(Z==="in"){Y.optional=X.map((Q)=>Q.rawIn);return}for(let Q of X)Y[Q.outProp.kind]=h(Y[Q.outProp.kind],Q.outProp.rawOut)}},index:{child:!0,parse:I1("index")},sequence:{child:!0,parse:I1("sequence")},undeclared:{parse:(Z)=>Z==="ignore"?void 0:Z,reduceIo:(Z,Y,X)=>{if(X==="reject"){Y.undeclared="reject";return}if(Z==="in")delete Y.undeclared;else Y.undeclared="reject"}}},defaults:{description:cM},intersections:{structure:(Z,Y,X)=>{let Q={...Z.inner},$={...Y.inner},W=new w;if(Z.undeclared){let V=Z.keyof();for(let q of Y.requiredKeys)if(!V.allows(q))W.add("presence",F.intrinsic.never.internal,Y.propsByKey[q].value,{path:[q]});if($.optional)$.optional=$.optional.filter((q)=>V.allows(q.key));if($.index)$.index=$.index.flatMap((q)=>{if(q.signature.extends(V))return q;let U=p1(V,q.signature,X.$);if(U instanceof w)return[];let H=F8(U,q.value,X.$);if(H.required)$.required=x0($.required,H.required);if(H.optional)$.optional=x0($.optional,H.optional);return H.index??[]})}if(Y.undeclared){let V=Y.keyof();for(let q of Z.requiredKeys)if(!V.allows(q))W.add("presence",Z.propsByKey[q].value,F.intrinsic.never.internal,{path:[q]});if(Q.optional)Q.optional=Q.optional.filter((q)=>V.allows(q.key));if(Q.index)Q.index=Q.index.flatMap((q)=>{if(q.signature.extends(V))return q;let U=p1(V,q.signature,X.$);if(U instanceof w)return[];let H=F8(U,q.value,X.$);if(H.required)Q.required=x0(Q.required,H.required);if(H.optional)Q.optional=x0(Q.optional,H.optional);return H.index??[]})}let J={};if(Z.undeclared||Y.undeclared)J.undeclared=Z.undeclared==="reject"||Y.undeclared==="reject"?"reject":"delete";let z=e9({kind:"structure",baseInner:J,l:Z2(Q),r:Z2($),roots:[],ctx:X});if(z instanceof w)W.push(...z);if(W.length)return W;return z}},reduce:(Z,Y)=>{if(!Z.required&&!Z.optional)return;let X={},Q=!1,$=Z.optional?[...Z.optional]:[];if(Z.required)for(let W=0;W<Z.required.length;W++){let J=Z.required[W];if(J.key in X)L(eJ(J.key));if(X[J.key]=!0,Z.index)for(let z of Z.index){let V=sJ(J,z,Y);if(V instanceof w)return V}}if(Z.optional)for(let W=0;W<Z.optional.length;W++){let J=Z.optional[W];if(J.key in X)L(eJ(J.key));if(X[J.key]=!0,Z.index)for(let z of Z.index){let V=sJ(J,z,Y);if(V instanceof w)return V;if(V!==null)$[W]=V,Q=!0}}if(Q)return Y.node("structure",{...Z,optional:$},{prereduced:!0})}});class Yz extends $0{impliedBasis=F.intrinsic.object.internal;impliedSiblings=this.children.flatMap((Z)=>Z.impliedSiblings??[]);props=x0(this.required,this.optional);propsByKey=b(this.props,(Z,Y)=>[Y.key,Y]);propsByKeyReference=Q1(this.propsByKey);expression=lM(this);requiredKeys=this.required?.map((Z)=>Z.key)??[];optionalKeys=this.optional?.map((Z)=>Z.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let Z=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:Y}of this.index)Z=Z.concat(Y.branches);return this._keyof=this.$.node("union",Z)}map(Z){return this.$.node("structure",this.props.flatMap(Z).reduce((Y,X)=>{let Q=this.propsByKey[X.key];if(r(X)){if(X.kind!=="required"&&X.kind!=="optional")return L(`Map result must have kind "required" or "optional" (was ${X.kind})`);return Y[X.kind]=h(Y[X.kind],X),Y}let $=X.kind??Q?.kind??"required",W=b(X,(J,z)=>(J in x6.implementation.keys)?[J,z]:[]);return Y[$]=h(Y[$],this.$.node($,W)),Y},{}))}assertHasKeys(Z){let Y=Z.filter((X)=>!v6(X,this.keyof()));if(Y.length)return L(tJ(this.expression,Y))}get(Z,...Y){let X,Q=!1,$=rM(Z);if((typeof $==="string"||typeof $==="symbol")&&this.propsByKey[$])X=this.propsByKey[$].value,Q=this.propsByKey[$].required;if(this.index){for(let J of this.index)if(v6($,J.signature))X=X?.and(J.value)??J.value}if(this.sequence&&v6($,F.intrinsic.nonNegativeIntegerString))if(P($,"root")){if(this.sequence.variadic)X=X?.and(this.sequence.element)??this.sequence.element}else{let J=Number.parseInt($);if(J<this.sequence.prevariadic.length){let z=this.sequence.prevariadic[J].node;X=X?.and(z)??z,Q||=J<this.sequence.prefixLength}else if(this.sequence.variadic){let z=this.$.node("union",this.sequence.variadicOrPostfix);X=X?.and(z)??z}}if(!X){if(this.sequence?.variadic&&P($,"root")&&$.extends(F.intrinsic.number))return L(sM($.expression,this.sequence.expression));return L(tJ(this.expression,[$]))}let W=X.get(...Y);return Q?W:W.or(F.intrinsic.undefined)}pick(...Z){return this.assertHasKeys(Z),this.$.node("structure",this.filterKeys("pick",Z))}omit(...Z){return this.assertHasKeys(Z),this.$.node("structure",this.filterKeys("omit",Z))}optionalize(){let{required:Z,...Y}=this.inner;return this.$.node("structure",{...Y,optional:this.props.map((X)=>X.hasKind("required")?this.$.node("optional",X.inner):X)})}require(){let{optional:Z,...Y}=this.inner;return this.$.node("structure",{...Y,required:this.props.map((X)=>X.hasKind("optional")?{key:X.key,value:X.value}:X)})}merge(Z){let Y=this.filterKeys("omit",[Z.keyof()]);if(Z.required)Y.required=h(Y.required,Z.required);if(Z.optional)Y.optional=h(Y.optional,Z.optional);if(Z.index)Y.index=h(Y.index,Z.index);if(Z.sequence)Y.sequence=Z.sequence;if(Z.undeclared)Y.undeclared=Z.undeclared;else delete Y.undeclared;return this.$.node("structure",Y)}filterKeys(Z,Y){let X=J8(this.inner),Q=($)=>{let W=Y.some((J)=>v6($,J));return Z==="pick"?W:!W};if(X.required)X.required=X.required.filter(($)=>Q($.key));if(X.optional)X.optional=X.optional.filter(($)=>Q($.key));if(X.index)X.index=X.index.filter(($)=>Q($.signature));return X}traverseAllows=(Z,Y)=>this._traverse("Allows",Z,Y);traverseApply=(Z,Y)=>this._traverse("Apply",Z,Y);_traverse=(Z,Y,X)=>{let Q=X?.currentErrorCount??0;for(let $=0;$<this.props.length;$++)if(Z==="Allows"){if(!this.props[$].traverseAllows(Y,X))return!1}else if(this.props[$].traverseApply(Y,X),X.failFast&&X.currentErrorCount>Q)return!1;if(this.sequence){if(Z==="Allows"){if(!this.sequence.traverseAllows(Y,X))return!1}else if(this.sequence.traverseApply(Y,X),X.failFast&&X.currentErrorCount>Q)return!1}if(this.index||this.undeclared==="reject"){let $=Object.keys(Y);$.push(...Object.getOwnPropertySymbols(Y));for(let W=0;W<$.length;W++){let J=$[W];if(this.index){for(let z of this.index)if(z.signature.traverseAllows(J,X)){if(Z==="Allows"){if(!m1(J,()=>z.value.traverseAllows(Y[J],X),X))return!1}else if(m1(J,()=>z.value.traverseApply(Y[J],X),X),X.failFast&&X.currentErrorCount>Q)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(J)){if(Z==="Allows")return!1;if(X.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[J],meta:this.meta}),X.failFast)return!1}}}if(this.structuralMorph&&X&&!X.hasError())X.queueMorphs([this.structuralMorph]);return!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter((Z)=>Z.hasDefault())??[])}declaresKey=(Z)=>(Z in this.propsByKey)||this.index?.some((Y)=>Y.signature.allows(Z))||this.sequence!==void 0&&F.intrinsic.nonNegativeIntegerString.allows(Z);_compileDeclaresKey(Z){let Y=[];if(this.props.length)Y.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let X of this.index)Y.push(Z.invoke(X.signature,{kind:"Allows",arg:"k"}));if(this.sequence)Y.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return Y.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",nM(this))}structuralMorphRef=this.structuralMorph&&Q1(this.structuralMorph);compile(Z){if(Z.traversalKind==="Apply")Z.initializeErrorCount();for(let Y of this.props)if(Z.check(Y),Z.traversalKind==="Apply")Z.returnIfFailFast();if(this.sequence){if(Z.check(this.sequence),Z.traversalKind==="Apply")Z.returnIfFailFast()}if(this.index||this.undeclared==="reject")Z.const("keys","Object.keys(data)"),Z.line("keys.push(...Object.getOwnPropertySymbols(data))"),Z.for("i < keys.length",()=>this.compileExhaustiveEntry(Z));if(Z.traversalKind==="Allows")return Z.return(!0);if(this.structuralMorphRef)Z.if("ctx && !ctx.hasError()",()=>{return Z.line("ctx.queueMorphs(["),aM(Z,this),Z.line("])")})}compileExhaustiveEntry(Z){if(Z.const("k","keys[i]"),this.index)for(let Y of this.index)Z.if(`${Z.invoke(Y.signature,{arg:"k",kind:"Allows"})}`,()=>Z.traverseKey("k","data[k]",Y.value));if(this.undeclared==="reject")Z.if(`!(${this._compileDeclaresKey(Z)})`,()=>{if(Z.traversalKind==="Allows")return Z.return(!1);return Z.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>Z.return())});return Z}reduceJsonSchema(Z,Y){switch(Z.type){case"object":return this.reduceObjectJsonSchema(Z,Y);case"array":let X=this.sequence?.reduceJsonSchema(Z,Y)??Z;if(this.props.length||this.index)return Y.fallback.arrayObject({code:"arrayObject",base:X,object:this.reduceObjectJsonSchema({type:"object"},Y)});return X;default:return t.throwInternalOperandError("structure",Z)}}reduceObjectJsonSchema(Z,Y){if(this.props.length){Z.properties={};for(let X of this.props){let Q=X.value.toJsonSchemaRecurse(Y);if(typeof X.key==="symbol"){Y.fallback.symbolKey({code:"symbolKey",base:Z,key:X.key,value:Q,optional:X.optional});continue}if(X.hasDefault()){let $=typeof X.default==="function"?X.default():X.default;Q.default=F.intrinsic.jsonData.allows($)?$:Y.fallback.defaultValue({code:"defaultValue",base:Q,value:$})}Z.properties[X.key]=Q}if(this.requiredKeys.length&&Z.properties)Z.required=this.requiredKeys.filter((X)=>typeof X==="string"&&(X in Z.properties))}if(this.index)for(let X of this.index){let Q=X.value.toJsonSchemaRecurse(Y);if(X.signature.equals(F.intrinsic.string)){Z.additionalProperties=Q;continue}for(let $ of X.signature.branches){if(!$.extends(F.intrinsic.string)){Z=Y.fallback.symbolKey({code:"symbolKey",base:Z,key:null,value:Q,optional:!1});continue}let W={type:"string"};if($.hasKind("morph"))W=Y.fallback.morph({code:"morph",base:$.rawIn.toJsonSchemaRecurse(Y),out:$.rawOut.toJsonSchemaRecurse(Y)});if(!$.hasKind("intersection"))return u(`Unexpected index branch kind ${$.kind}.`);let{pattern:J}=$.inner;if(J){let z=Object.assign(W,{pattern:J[0].rule});for(let V=1;V<J.length;V++)W=Y.fallback.patternIntersection({code:"patternIntersection",base:z,pattern:J[V].rule});Z.patternProperties??={},Z.patternProperties[z.pattern]=Q}}}if(this.undeclared&&!Z.additionalProperties)Z.additionalProperties=!1;return Z}}var F7={},oM=(Z)=>{let Y="";for(let X=0;X<Z.defaultable.length;X++)Y+=Z.defaultable[X].defaultValueMorphRef;if(Z.sequence?.defaultValueMorphsReference)Y+=Z.sequence?.defaultValueMorphsReference;if(Z.undeclared==="delete"){if(Y+="delete !(",Z.required)for(let X of Z.required)Y+=X.compiledKey+" | ";if(Z.optional)for(let X of Z.optional)Y+=X.compiledKey+" | ";if(Z.index)for(let X of Z.index)Y+=X.signature.id+" | ";if(Z.sequence)if(Z.sequence.maxLength===null)Y+=C.nonNegativeIntegerString.id;else for(let X=0;X<Z.sequence.tuple.length;X++)Y+=X+" | ";Y+=")"}return Y},nM=(Z)=>{let Y=oM(Z);if(!Y)return;if(F7[Y])return F7[Y];let X=(Q,$)=>{for(let W=0;W<Z.defaultable.length;W++)if(!(Z.defaultable[W].key in Q))Z.defaultable[W].defaultValueMorph(Q,$);if(Z.sequence?.defaultables)for(let W=Q.length-Z.sequence.prefixLength;W<Z.sequence.defaultables.length;W++)Z.sequence.defaultValueMorphs[W](Q,$);if(Z.undeclared==="delete"){for(let W in Q)if(!Z.declaresKey(W))delete Q[W]}return Q};return F7[Y]=X},aM=(Z,Y)=>{let Q=`(data${Y.defaultable.some(($)=>$.defaultValueMorph.length===2)||Y.sequence?.defaultValueMorphs.some(($)=>$.length===2)?", ctx":""})`;return Z.block(`${Q} => `,($)=>{for(let W=0;W<Y.defaultable.length;W++){let{serializedKey:J,defaultValueMorphRef:z}=Y.defaultable[W];$.if(`!(${J} in data)`,(V)=>V.line(`${z}${Q}`))}if(Y.sequence?.defaultables)$.for(`i < ${Y.sequence.defaultables.length}`,(W)=>W.set("data[i]",5),`data.length - ${Y.sequence.prefixLength}`);if(Y.undeclared==="delete")$.forIn("data",(W)=>W.if(`!(${Y._compileDeclaresKey(W)})`,(J)=>J.line("delete data[k]")));return $.return("data")})},N7={implementation:iM,Node:Yz},rM=(Z)=>{if(P(Z,"root")&&Z.hasKind("unit"))Z=Z.unit;if(typeof Z==="number")Z=`${Z}`;return Z},sM=(Z,Y)=>`${Z} is not allowed as an array index on ${Y}. Use the 'nonNegativeIntegerString' keyword instead.`,F8=(Z,Y,X)=>{let[Q,$]=FW(Z.branches,(J)=>J.hasKind("unit"));if(!Q.length)return{index:X.node("index",{signature:Z,value:Y})};let W={};for(let J of Q){let z=X.node("required",{key:J.unit,value:Y});W[z.kind]=h(W[z.kind],z)}if($.length)W.index=X.node("index",{signature:$,value:Y});return W},tM=(Z)=>P(Z,"root")?Z.expression:x(Z),tJ=(Z,Y)=>`Key${Y.length===1?"":"s"} ${Y.map(tM).join(", ")} ${Y.length===1?"does":"do"} not exist on ${Z}`,eJ=(Z)=>`Duplicate key ${H0(Z)}`;var X2={...AJ,alias:f6.implementation,domain:M8.implementation,unit:G7.implementation,proto:h6.implementation,union:H7.implementation,morph:q7.implementation,intersection:V7.implementation,divisor:nY.implementation,pattern:X7.implementation,predicate:oY.implementation,required:B7.implementation,optional:x6.implementation,index:K7.implementation,sequence:L7.implementation,structure:N7.implementation};F.defaultConfig=IW(Object.assign(b(X2,(Z,Y)=>[Z,Y.defaults]),{jitless:yW(),clone:CW,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:t.defaultConfig}));F.resolvedConfig=R6(F.defaultConfig,F.config);var RJ={...EJ,alias:f6.Node,domain:M8.Node,unit:G7.Node,proto:h6.Node,union:H7.Node,morph:q7.Node,intersection:V7.Node,divisor:nY.Node,pattern:X7.Node,predicate:oY.Node,required:B7.Node,optional:x6.Node,index:K7.Node,sequence:L7.Node,structure:N7.Node};class W2 extends jY{get[S1](){return"module"}}var w7=(Z,Y)=>new W2(b(Z,(X,Q)=>[X,P(Q,"module")?w7(Q,Y):Y.bindReference(Q)]));var eM=(Z)=>n(Z)?Z:("branches"in Z)&&n(Z.branches)?Z.branches:void 0,ZF=(Z,Y)=>L(`Node of kind ${Y} is not valid as a ${Z} definition`),Xz=(Z)=>`#${Z} duplicates public alias ${Z}`,D7={};F.ambient??={};var Qz,Wz="function $",YF=(Z)=>Jz(Z,zz(Z)),Jz=(Z,Y)=>{let X=Y.write(Wz,4),Q=Y.compile()();for(let $ of Z){if($.precompilation)continue;if($.traverseAllows=Q[`${$.id}Allows`].bind(Q),$.isRoot()&&!$.allowsRequiresContext)$.allows=$.traverseAllows;if($.traverseApply=Q[`${$.id}Apply`].bind(Q),Q[`${$.id}Optimistic`])$.traverseOptimistic=Q[`${$.id}Optimistic`].bind(Q);$.precompilation=X}},zz=(Z)=>new W8().return(Z.reduce((Y,X)=>{let Q=new I6({kind:"Allows"}).indent();X.compile(Q);let $=Q.write(`${X.id}Allows`),W=new I6({kind:"Apply"}).indent();X.compile(W);let J=W.write(`${X.id}Apply`),z=`${Y}${$},
|
|
128
|
-
${
|
|
129
|
-
`;if(!
|
|
492
|
+
})`)}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?`"${pt}"`:!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 l=this.branches[a],c=_t(o.rawIn,l.rawIn,o.$);if(!(c instanceof j))continue;for(let u of c){if(!u.kind||u.optional)continue;let d,f;if(u.kind==="domain"){let{l:h,r:x}=u;d=`"${typeof h==="string"?h:h.domain}"`,f=`"${typeof x==="string"?x:x.domain}"`}else if(u.kind==="unit")d=u.l.serializedValue,f=u.r.serializedValue;else continue;let p=e.find((h)=>_n(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=rn(p.cases[d].branchIndices,s);else p.cases[d]??={branchIndices:[s],condition:u.l};if(p.cases[f])p.cases[f].branchIndices=rn(p.cases[f].branchIndices,a);else p.cases[f]??={branchIndices:[a],condition:u.r}}}}}let t=this.ordered?ZR(e,this.branches):e;if(!t.length)return null;let n=XR(t,this),r={};for(let s in n.best.cases){let o=YR(n,s);if(o===null){r[s]=!0;continue}if(o.length===this.branches.length)return null;if(this.ordered)o.sort((c,u)=>c.originalIndex-u.originalIndex);let a=o.map((c)=>c.branch),l=a.length===1?a[0]:this.$.node("union",this.ordered?{branches:a,ordered:!0}:a);Object.assign(this.referencesById,l.referencesById),r[s]=l}if(n.defaultEntries.length){let s=n.defaultEntries.map((o)=>o.branch);r.default=this.$.node("union",this.ordered?{branches:s,ordered:!0}:s,{prereduced:!0}),Object.assign(this.referencesById,r.default.referencesById)}return Object.assign(n.location,{cases:r})}}var XR=(e,t)=>{let r=e.sort((a,l)=>a.path.length===l.path.length?Object.keys(l.cases).length-Object.keys(a.cases).length:a.path.length-l.path.length)[0],s={kind:r.kind,path:r.path,optionallyChainedPropString:em(r.path)},o=t.branches.map((a,l)=>({originalIndex:l,branch:a}));return{best:r,location:s,defaultEntries:o,node:t}},YR=(e,t)=>{let n=e.best.cases[t],r=QR(n.condition,e.location.path,e.node.$),s=[],o=[];for(let a=0;a<e.defaultEntries.length;a++){let l=e.defaultEntries[a];if(n.branchIndices.includes(l.originalIndex)){let c=Yh(e.node.branches[l.originalIndex],e.location);if(c===null)s=null;else s?.push({originalIndex:l.originalIndex,branch:c})}else if(l.branch.hasKind("alias")&&r.hasKind("domain")&&r.domain==="object")s?.push(l);else{if(l.branch.rawIn.overlaps(r)){let c=Yh(l.branch,e.location);s?.push({originalIndex:l.originalIndex,branch:c})}o.push(l)}}return e.defaultEntries=o,s},ZR=(e,t)=>e.filter((r)=>{let s=Object.values(r.cases).map((o)=>o.branchIndices);for(let o=0;o<s.length-1;o++){let a=s[o];for(let l=o+1;l<s.length;l++){let c=s[l];for(let u of a)for(let d of c)if(u>d){if(t[u].overlaps(t[d]))return!1}}}return!0}),QR=(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:[...Cp(o).map((a)=>({})),r]}:{domain:"object",required:[{key:o,value:r}]})}return r},em=(e)=>e.reduce((t,n)=>t+zl(n,!0),"data"),e$=Me(Pp),t$=Me(re),vc={implementation:JR,Node:Qh},n$=(e)=>({kind:e.kind,path:e.path.map((t)=>typeof t==="string"?t:Ht(t)),cases:ne(e.cases,(t,n)=>[t,n===!0?n:n.hasKind("union")&&n.discriminantJson?n.discriminantJson:n.json])}),r$={delimiter:" | ",finalDelimiter:" | "},i$=(e)=>Vr(e,r$),Vr=(e,t)=>{let n=t?.delimiter??", ",r=t?.finalDelimiter??" or ";if(e.length===0)return"never";if(e.length===1)return e[0];if(e.length===2&&e[0]==="false"&&e[1]==="true"||e[0]==="true"&&e[1]==="false")return"boolean";let s={},o=e.filter((l)=>s[l]?!1:s[l]=!0),a=o.pop();return`${o.join(n)}${o.length?r:""}${a}`},bc=(e,t,n)=>{let r=t.map(()=>[]);for(let o=0;o<e.length;o++){let a={};for(let l=0;l<t.length;l++){if(r[l]===null)continue;if(e[o].equals(t[l])){r[l]=null,a={};break}let c=Se(e[o],t[l],n);if(c instanceof j)continue;if(c.equals(e[o])){r[l].push(e[o]),a={};break}if(c.equals(t[l]))r[l]=null;else a[l]=c}for(let l in a)r[l][o]=a[l]}let s=r.flatMap((o,a)=>o?.flatMap((l)=>l.branches)??t[a]);return s.length===0?j.init("union",e,t):s},s$=({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=_t(e[r].rawIn,e[s].rawIn,e[0].$);if(o instanceof j)continue;if(!t)o$(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])},o$=(e,t)=>{if(!e.includesTransform&&!t.includesTransform)return;if(!_n(e.shallowMorphs,t.shallowMorphs))E(Zh(e.expression,t.expression));if(!_n(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(Zh(e.expression,t.expression))},Yh=(e,t)=>e.transform((n,r)=>{if(n==="domain"||n==="unit")return null;return r},{shouldTransform:(n,r)=>{let s=em(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"}}),Zh=(e,t)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
|
|
493
|
+
Left: ${e}
|
|
494
|
+
Right: ${t}`,a$=(e,t)=>`The intersection of two ordered unions is indeterminate:
|
|
495
|
+
Left: ${e}
|
|
496
|
+
Right: ${t}`;var l$=se({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(e)=>e instanceof Date?e.toISOString():Mt(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)=>j.init("unit",e,t),...on("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:O.intrinsic.object;if(e.domain!==r.domain){let s=e.domain==="undefined"||e.domain==="null"||e.domain==="boolean"?e.domain:O.intrinsic[e.domain];return j.init("domain",s,r)}}return j.init("assignability",e,t.hasKind("intersection")?t.children.find((r)=>!r.allows(e.unit)):t)})}});class nm extends lr{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=tm(this.unit,this.serializedValue);compiledNegation=tm(this.unit,this.serializedValue,"negated");expression=re(this.unit);domain=Be(this.unit);get defaultShortDescription(){return this.domain==="object"?ft.object:this.description}innerToJsonSchema(e){return this.unit===null?{type:"null"}:O.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 xc={implementation:l$,Node:nm},tm=(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 c$=se({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(e,t)=>{let n=t.$.parseSchema(e);if(!n.extends(O.intrinsic.key))return E(d$(n.expression));let r=n.branches.filter((s)=>s.hasKind("unit"));if(r.length)return E(u$(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=Se(e.value,t.value,n),s=r instanceof j?O.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 rm extends Tt{impliedBasis=O.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=de(this.value.flatRefs.map((e)=>Wt([this.signature,...e.path],e.node)),Wt([this.signature],this.value));traverseAllows=(e,t)=>rr(e).every((n)=>{if(this.signature.traverseAllows(n[0],t))return gt(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))gt(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 kc={implementation:c$,Node:rm},u$=(e)=>`Index keys ${e.join(", ")} should be specified as named props.`,d$=(e)=>`Indexed key definition '${e}' must be a string or symbol`;var f$=se({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:Ji,optional:Ji}});class im extends Xi{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=Dn(this.errorContext)}var Rc={implementation:f$,Node:im};var p$=se({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 Zi(r,n[1],null),[r,n[1]]})},serialize:(e)=>e.map((t)=>[t[0].collapsibleJson,Mt(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(_$);if(e.optionals?.length||e.defaultables?.length)return E(Sc)}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=ns({l:e.tuple,r:t.tuple,disjoint:new j,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",sm(s[0].result)):n.$.node("union",s.map((o)=>({proto:Array,sequence:sm(o.result)})))}}});class am extends Tt{impliedBasis=O.intrinsic.Array.internal;tuple=g$(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=gn(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return Ql(this.flatRefs,this.prevariadic.flatMap((e,t)=>de(e.node.flatRefs.map((n)=>Wt([`${t}`,...n.path],n.node)),Wt([`${t}`],e.node)))),Ql(this.flatRefs,this.variadicOrPostfix.flatMap((e)=>de(e.flatRefs.map((t)=>Wt([O.intrinsic.nonNegativeIntegerString.internal,...t.path],t.node)),Wt([O.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=m$(this);defaultValueMorphsReference=this.defaultValueMorphs.length?Me(this.defaultValueMorphs):void 0;elementAtIndex(e,t){if(t<this.prevariadic.length)return this.tuple[t];let n=e.length-this.postfixLength;if(t>=n)return{kind:"postfix",node:this.postfix[t-n]};return{kind:"variadic",node:this.variadic??he(`Unexpected attempt to access index ${t} on ${this}`)}}traverseAllows=(e,t)=>{for(let n=0;n<e.length;n++)if(!this.elementAtIndex(e,n).node.traverseAllows(e[n],t))return!1;return!0};traverseApply=(e,t)=>{let n=0;for(;n<e.length;n++)gt(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(O.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=O.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 h$={},m$=(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(_c(s,o,a)),n+=`${s}: ${o.id} = ${Mt(a)}, `}return n+="]",h$[n]??=t},$c={implementation:p$,Node:am},g$=(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},sm=(e)=>e.reduce((t,n)=>{if(n.kind==="variadic")t.variadic=n.node;else if(n.kind==="defaultables")t.defaultables=de(t.defaultables,[[n.node,n.default]]);else t[n.kind]=de(t[n.kind],n.node);return t},{}),Sc="A postfix required element cannot follow an optional or defaultable element",_$="A postfix element requires a variadic element",ns=(e)=>{let[t,...n]=e.l,[r,...s]=e.r;if(!t||!r)return e;let o=n[n.length-1]?.kind==="postfix",a=s[s.length-1]?.kind==="postfix",l=t.kind==="prefix"||r.kind==="prefix"?"prefix":t.kind==="postfix"||r.kind==="postfix"?"postfix":t.kind==="variadic"&&r.kind==="variadic"?"variadic":o||a?"prefix":t.kind==="defaultables"||r.kind==="defaultables"?"defaultables":"optionals";if(t.kind==="prefix"&&r.kind==="variadic"&&a){let f=ns({...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=ns({...e,fixedVariants:[],l:n.map((p)=>({...p,kind:"prefix"}))});if(f.disjoint.length===0)e.fixedVariants.push(f)}let c=Se(t.node,r.node,e.ctx);if(c instanceof j)if(l==="prefix"||l==="postfix")e.disjoint.push(...c.withPrefixKey(l==="prefix"?e.result.length:`-${n.length+1}`,om(t)&&om(r)?"required":"optional")),e.result=[...e.result,{kind:l,node:O.intrinsic.never.internal}];else if(l==="optionals"||l==="defaultables")return e;else return ns({...e,fixedVariants:[],l:n.map((f)=>({...f,kind:"prefix"})),r:n.map((f)=>({...f,kind:"prefix"}))});else if(l==="defaultables"){if(t.kind==="defaultables"&&r.kind==="defaultables"&&t.default!==r.default)E(gc(t.default,r.default));e.result=[...e.result,{kind:l,node:c,default:t.kind==="defaultables"?t.default:r.kind==="defaultables"?r.default:he(`Unexpected defaultable intersection from ${t.kind} and ${r.kind} elements.`)}]}else e.result=[...e.result,{kind:l,node:c}];let u=e.l.length,d=e.r.length;if(t.kind!=="variadic"||u>=d&&(r.kind==="variadic"||d===1))e.l=n;if(r.kind!=="variadic"||d>=u&&(t.kind==="variadic"||u===1))e.r=s;return ns(e)},om=(e)=>e.kind==="prefix"||e.kind==="postfix";var dm=(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??"{}"},y$=dm("description"),w$=dm("expression"),lm=(e,t,n)=>{let r=e.required?"required":"optional";if(!t.signature.allows(e.key))return null;let s=_t(e.value,t.value,n);if(s instanceof j)return r==="optional"?n.node("optional",{key:e.key,value:O.intrinsic.never.internal}):s.withPrefixKey(e.key,e.kind);return null},b$=se({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:et("required"),reduceIo:(e,t,n)=>{t.required=de(t.required,n.map((r)=>e==="in"?r.rawIn:r.rawOut));return}},optional:{child:!0,parse:et("optional"),reduceIo:(e,t,n)=>{if(e==="in"){t.optional=n.map((r)=>r.rawIn);return}for(let r of n)t[r.outProp.kind]=de(t[r.outProp.kind],r.outProp.rawOut)}},index:{child:!0,parse:et("index")},sequence:{child:!0,parse:et("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:y$},intersections:{structure:(e,t,n)=>{let r={...e.inner},s={...t.inner},o=new j;if(e.undeclared){let c=e.keyof();for(let u of t.requiredKeys)if(!c.allows(u))o.add("presence",O.intrinsic.never.internal,t.propsByKey[u].value,{path:[u]});if(s.optional)s.optional=s.optional.filter((u)=>c.allows(u.key));if(s.index)s.index=s.index.flatMap((u)=>{if(u.signature.extends(c))return u;let d=_t(c,u.signature,n.$);if(d instanceof j)return[];let f=Do(d,u.value,n.$);if(f.required)s.required=gn(s.required,f.required);if(f.optional)s.optional=gn(s.optional,f.optional);return f.index??[]})}if(t.undeclared){let c=t.keyof();for(let u of e.requiredKeys)if(!c.allows(u))o.add("presence",e.propsByKey[u].value,O.intrinsic.never.internal,{path:[u]});if(r.optional)r.optional=r.optional.filter((u)=>c.allows(u.key));if(r.index)r.index=r.index.flatMap((u)=>{if(u.signature.extends(c))return u;let d=_t(c,u.signature,n.$);if(d instanceof j)return[];let f=Do(d,u.value,n.$);if(f.required)r.required=gn(r.required,f.required);if(f.optional)r.optional=gn(r.optional,f.optional);return f.index??[]})}let a={};if(e.undeclared||t.undeclared)a.undeclared=e.undeclared==="reject"||t.undeclared==="reject"?"reject":"delete";let l=Br({kind:"structure",baseInner:a,l:qr(r),r:qr(s),roots:[],ctx:n});if(l instanceof j)o.push(...l);if(o.length)return o;return l}},reduce:(e,t)=>{if(!e.required&&!e.optional)return;let n={},r=!1,s=e.optional?[...e.optional]:[];if(e.required)for(let o=0;o<e.required.length;o++){let a=e.required[o];if(a.key in n)E(um(a.key));if(n[a.key]=!0,e.index)for(let l of e.index){let c=lm(a,l,t);if(c instanceof j)return c}}if(e.optional)for(let o=0;o<e.optional.length;o++){let a=e.optional[o];if(a.key in n)E(um(a.key));if(n[a.key]=!0,e.index)for(let l of e.index){let c=lm(a,l,t);if(c instanceof j)return c;if(c!==null)s[o]=c,r=!0}}if(r)return t.node("structure",{...e,optional:s},{prereduced:!0})}});class fm extends Tt{impliedBasis=O.intrinsic.object.internal;impliedSiblings=this.children.flatMap((e)=>e.impliedSiblings??[]);props=gn(this.required,this.optional);propsByKey=ne(this.props,(e,t)=>[t.key,t]);propsByKeyReference=Me(this.propsByKey);expression=w$(this);requiredKeys=this.required?.map((e)=>e.key)??[];optionalKeys=this.optional?.map((e)=>e.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let e=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:t}of this.index)e=e.concat(t.branches);return this._keyof=this.$.node("union",e)}map(e){return this.$.node("structure",this.props.flatMap(e).reduce((t,n)=>{let r=this.propsByKey[n.key];if($e(n)){if(n.kind!=="required"&&n.kind!=="optional")return E(`Map result must have kind "required" or "optional" (was ${n.kind})`);return t[n.kind]=de(t[n.kind],n),t}let s=n.kind??r?.kind??"required",o=ne(n,(a,l)=>(a in Yi.implementation.keys)?[a,l]:[]);return t[s]=de(t[s],this.$.node(s,o)),t},{}))}assertHasKeys(e){let t=e.filter((n)=>!Qi(n,this.keyof()));if(t.length)return E(cm(this.expression,t))}get(e,...t){let n,r=!1,s=R$(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(Qi(s,a.signature))n=n?.and(a.value)??a.value}if(this.sequence&&Qi(s,O.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 l=this.sequence.prevariadic[a].node;n=n?.and(l)??l,r||=a<this.sequence.prefixLength}else if(this.sequence.variadic){let l=this.$.node("union",this.sequence.variadicOrPostfix);n=n?.and(l)??l}}if(!n){if(this.sequence?.variadic&&z(s,"root")&&s.extends(O.intrinsic.number))return E($$(s.expression,this.sequence.expression));return E(cm(this.expression,[s]))}let o=n.get(...t);return r?o:o.or(O.intrinsic.undefined)}pick(...e){return this.assertHasKeys(e),this.$.node("structure",this.filterKeys("pick",e))}omit(...e){return this.assertHasKeys(e),this.$.node("structure",this.filterKeys("omit",e))}optionalize(){let{required:e,...t}=this.inner;return this.$.node("structure",{...t,optional:this.props.map((n)=>n.hasKind("required")?this.$.node("optional",n.inner):n)})}require(){let{optional:e,...t}=this.inner;return this.$.node("structure",{...t,required:this.props.map((n)=>n.hasKind("optional")?{key:n.key,value:n.value}:n)})}merge(e){let t=this.filterKeys("omit",[e.keyof()]);if(e.required)t.required=de(t.required,e.required);if(e.optional)t.optional=de(t.optional,e.optional);if(e.index)t.index=de(t.index,e.index);if(e.sequence)t.sequence=e.sequence;if(e.undeclared)t.undeclared=e.undeclared;else delete t.undeclared;return this.$.node("structure",t)}filterKeys(e,t){let n=$o(this.inner),r=(s)=>{let o=t.some((a)=>Qi(s,a));return e==="pick"?o:!o};if(n.required)n.required=n.required.filter((s)=>r(s.key));if(n.optional)n.optional=n.optional.filter((s)=>r(s.key));if(n.index)n.index=n.index.filter((s)=>r(s.signature));return n}traverseAllows=(e,t)=>this._traverse("Allows",e,t);traverseApply=(e,t)=>this._traverse("Apply",e,t);_traverse=(e,t,n)=>{let r=n?.currentErrorCount??0;for(let s=0;s<this.props.length;s++)if(e==="Allows"){if(!this.props[s].traverseAllows(t,n))return!1}else if(this.props[s].traverseApply(t,n),n.failFast&&n.currentErrorCount>r)return!1;if(this.sequence){if(e==="Allows"){if(!this.sequence.traverseAllows(t,n))return!1}else if(this.sequence.traverseApply(t,n),n.failFast&&n.currentErrorCount>r)return!1}if(this.index||this.undeclared==="reject"){let s=Object.keys(t);s.push(...Object.getOwnPropertySymbols(t));for(let o=0;o<s.length;o++){let a=s[o];if(this.index){for(let l of this.index)if(l.signature.traverseAllows(a,n)){if(e==="Allows"){if(!gt(a,()=>l.value.traverseAllows(t[a],n),n))return!1}else if(gt(a,()=>l.value.traverseApply(t[a],n),n),n.failFast&&n.currentErrorCount>r)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(a)){if(e==="Allows")return!1;if(n.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[a],meta:this.meta}),n.failFast)return!1}}}if(this.structuralMorph&&n&&!n.hasError())n.queueMorphs([this.structuralMorph]);return!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter((e)=>e.hasDefault())??[])}declaresKey=(e)=>(e in this.propsByKey)||this.index?.some((t)=>t.signature.allows(e))||this.sequence!==void 0&&O.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",x$(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(["),k$(e,this),e.line("])")))}compileExhaustiveEntry(e){if(e.const("k","keys[i]"),this.index)for(let t of this.index)e.if(`${e.invoke(t.signature,{arg:"k",kind:"Allows"})}`,()=>e.traverseKey("k","data[k]",t.value));if(this.undeclared==="reject")e.if(`!(${this._compileDeclaresKey(e)})`,()=>{if(e.traversalKind==="Allows")return e.return(!1);return e.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>e.return())});return e}reduceJsonSchema(e,t){switch(e.type){case"object":return this.reduceObjectJsonSchema(e,t);case"array":let n=this.sequence?.reduceJsonSchema(e,t)??e;if(this.props.length||this.index)return t.fallback.arrayObject({code:"arrayObject",base:n,object:this.reduceObjectJsonSchema({type:"object"},t)});return n;default:return Ee.throwInternalOperandError("structure",e)}}reduceObjectJsonSchema(e,t){if(this.props.length){e.properties={};for(let n of this.props){let r=n.value.toJsonSchemaRecurse(t);if(typeof n.key==="symbol"){t.fallback.symbolKey({code:"symbolKey",base:e,key:n.key,value:r,optional:n.optional});continue}if(n.hasDefault()){let s=typeof n.default==="function"?n.default():n.default;r.default=O.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(O.intrinsic.string)){e.additionalProperties=r;continue}for(let s of n.signature.branches){if(!s.extends(O.intrinsic.string)){e=t.fallback.symbolKey({code:"symbolKey",base:e,key:null,value:r,optional:!1});continue}let o={type:"string"};if(s.hasKind("morph"))o=t.fallback.morph({code:"morph",base:s.rawIn.toJsonSchemaRecurse(t),out:s.rawOut.toJsonSchemaRecurse(t)});if(!s.hasKind("intersection"))return he(`Unexpected index branch kind ${s.kind}.`);let{pattern:a}=s.inner;if(a){let l=Object.assign(o,{pattern:a[0].rule});for(let c=1;c<a.length;c++)o=t.fallback.patternIntersection({code:"patternIntersection",base:l,pattern:a[c].rule});e.patternProperties??={},e.patternProperties[l.pattern]=r}}}if(this.undeclared&&!e.additionalProperties)e.additionalProperties=!1;return e}}var Ec={},v$=(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+=Q.nonNegativeIntegerString.id;else for(let n=0;n<e.sequence.tuple.length;n++)t+=n+" | ";t+=")"}return t},x$=(e)=>{let t=v$(e);if(!t)return;if(Ec[t])return Ec[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 Ec[t]=n},k$=(e,t)=>{let r=`(data${t.defaultable.some((s)=>s.defaultValueMorph.length===2)||t.sequence?.defaultValueMorphs.some((s)=>s.length===2)?", ctx":""})`;return e.block(`${r} => `,(s)=>{for(let o=0;o<t.defaultable.length;o++){let{serializedKey:a,defaultValueMorphRef:l}=t.defaultable[o];s.if(`!(${a} in data)`,(c)=>c.line(`${l}${r}`))}if(t.sequence?.defaultables)s.for(`i < ${t.sequence.defaultables.length}`,(o)=>o.set("data[i]",5),`data.length - ${t.sequence.prefixLength}`);if(t.undeclared==="delete")s.forIn("data",(o)=>o.if(`!(${t._compileDeclaresKey(o)})`,(a)=>a.line("delete data[k]")));return s.return("data")})},Ac={implementation:b$,Node:fm},R$=(e)=>{if(z(e,"root")&&e.hasKind("unit"))e=e.unit;if(typeof e==="number")e=`${e}`;return e},$$=(e,t)=>`${e} is not allowed as an array index on ${t}. Use the 'nonNegativeIntegerString' keyword instead.`,Do=(e,t,n)=>{let[r,s]=Ap(e.branches,(a)=>a.hasKind("unit"));if(!r.length)return{index:n.node("index",{signature:e,value:t})};let o={};for(let a of r){let l=n.node("required",{key:a.unit,value:t});o[l.kind]=de(o[l.kind],l)}if(s.length)o.index=n.node("index",{signature:s,value:t});return o},S$=(e)=>z(e,"root")?e.expression:re(e),cm=(e,t)=>`Key${t.length===1?"":"s"} ${t.map(S$).join(", ")} ${t.length===1?"does":"do"} not exist on ${e}`,um=(e)=>`Duplicate key ${Ht(e)}`;var Kr={...Ph,alias:es.implementation,domain:No.implementation,unit:xc.implementation,proto:ts.implementation,union:vc.implementation,morph:wc.implementation,intersection:yc.implementation,divisor:ic.implementation,pattern:fc.implementation,predicate:rc.implementation,required:Rc.implementation,optional:Yi.implementation,index:kc.implementation,sequence:$c.implementation,structure:Ac.implementation};O.defaultConfig=Fp(Object.assign(ne(Kr,(e,t)=>[e,t.defaults]),{jitless:Hp(),clone:Up,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:Ee.defaultConfig}));O.resolvedConfig=Ki(O.defaultConfig,O.config);var Lh={...Mh,alias:es.Node,domain:No.Node,unit:xc.Node,proto:ts.Node,union:vc.Node,morph:wc.Node,intersection:yc.Node,divisor:ic.Node,pattern:fc.Node,predicate:rc.Node,required:Rc.Node,optional:Yi.Node,index:kc.Node,sequence:$c.Node,structure:Ac.Node};class Gr extends Ll{get[it](){return"module"}}var Cc=(e,t)=>new Gr(ne(e,(n,r)=>[n,z(r,"module")?Cc(r,t):t.bindReference(r)]));var E$=(e)=>ve(e)?e:("branches"in e)&&ve(e.branches)?e.branches:void 0,A$=(e,t)=>E(`Node of kind ${t} is not valid as a ${e} definition`),pm=(e)=>`#${e} duplicates public alias ${e}`,Ic={};O.ambient??={};var hm,gm="function $",C$=(e)=>_m(e,ym(e)),_m=(e,t)=>{let n=t.write(gm,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}},ym=(e)=>new Ro().return(e.reduce((t,n)=>{let r=new Hi({kind:"Allows"}).indent();n.compile(r);let s=r.write(`${n.id}Allows`),o=new Hi({kind:"Apply"}).indent();n.compile(o);let a=o.write(`${n.id}Apply`),l=`${t}${s},
|
|
497
|
+
${a},
|
|
498
|
+
`;if(!n.hasKind("union"))return l;let c=new Hi({kind:"Allows",optimistic:!0}).indent();n.compile(c);let u=c.write(`${n.id}Optimistic`);return`${l}${u},
|
|
130
499
|
`},`{
|
|
131
|
-
`)+"}");class N8{config;resolvedConfig;name;get[S1](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(Z,Y){if(this.config=R6(F.config,Y),this.resolvedConfig=R6(F.resolvedConfig,Y),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(D7).length}`,this.name in D7)L(`A Scope already named ${this.name} already exists`);D7[this.name]=this;let X=Object.entries(Z).map((Q)=>this.preparseOwnAliasEntry(...Q));for(let[Q,$]of X){let W=Q;if(Q[0]==="#"){if(W=Q.slice(1),W in this.aliases)L(Xz(W));this.aliases[W]=$}else{if(W in this.aliases)L(Xz(Q));this.aliases[W]=$,this.exportedNames.push(W)}if(!P($,"module")&&!P($,"generic")&&!a0($)){let J=this.preparseOwnDefinitionFormat($,{alias:W});this.resolutions[W]=P(J,"root")?this.bindReference(J):this.createParseContext(J).id}}Qz??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[Qz.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=F.intrinsic?b(F.intrinsic,(Q,$)=>Q.startsWith("json")?[]:[Q,this.bindReference($)]):{}}cacheGetter(Z,Y){return Object.defineProperty(this,Z,{value:Y}),Y}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(Z){return Z}generic=(...Z)=>{let Y=this;return(X,Q)=>new Z9(Z,Q?new U8(X):X,Y,Y,Q??null)};units=(Z,Y)=>{let X=[];for(let $ of Z)if(!X.includes($))X.push($);let Q=X.map(($)=>this.node("unit",{unit:$},Y));return this.node("union",Q,{...Y,prereduced:!0})};lazyResolutions=[];lazilyResolve(Z,Y){let X=this.node("alias",{reference:Y??"synthetic",resolve:Z},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(X);return X}schema=(Z,Y)=>this.finalize(this.parseSchema(Z,Y));parseSchema=(Z,Y)=>this.node(_6(Z),Z,Y);preparseNode(Z,Y,X){let Q=typeof Z==="string"?Z:_6(Y,Z);if(r(Y)&&Y.kind===Q)return Y;if(Q==="alias"&&!X?.prereduced){let{reference:J}=f6.implementation.normalize(Y,this);if(J.startsWith("$")){let z=this.resolveRoot(J.slice(1));Y=z,Q=z.kind}}else if(Q==="union"&&v1(Y,"object")){let J=eM(Y);if(J?.length===1)Y=J[0],Q=_6(Y)}if(r(Y)&&Y.kind===Q)return Y;let W=X2[Q].normalize?.(Y,this)??Y;if(r(W))return W.kind===Q?W:ZF(Q,W.kind);return{...X,$:this,kind:Q,def:W,prefix:X.alias??Q}}bindReference(Z){let Y;if(r(Z))Y=Z.$===this?Z:new Z.constructor(Z.attachments,this);else Y=Z.$===this?Z:new Z9(Z.params,Z.bodyDef,Z.$,this,Z.hkt);if(!this.resolved)Object.assign(this.referencesById,Y.referencesById);return Y}resolveRoot(Z){return this.maybeResolveRoot(Z)??L(O7(Z))}maybeResolveRoot(Z){let Y=this.maybeResolve(Z);if(P(Y,"generic"))return;return Y}maybeResolveSubalias(Z){return A7(this.aliases,Z)??A7(this.ambient,Z)}get ambient(){return F.ambient}maybeResolve(Z){let Y=this.resolutions[Z];if(Y){if(typeof Y!=="string")return this.bindReference(Y);let Q=_1[Y];if(P(Q,"root"))return this.resolutions[Z]=Q;if(P(Q,"context")){if(Q.phase==="resolving")return this.node("alias",{reference:`$${Z}`},{prereduced:!0});if(Q.phase==="resolved")return u(`Unexpected resolved context for was uncached by its scope: ${x(Q)}`);Q.phase="resolving";let $=this.bindReference(this.parseOwnDefinitionFormat(Q.def,Q));return Q.phase="resolved",_1[$.id]=$,_1[Q.id]=$,this.resolutions[Z]=$}return u(`Unexpected nodesById entry for ${Y}: ${x(Q)}`)}let X=this.aliases[Z]??this.ambient?.[Z];if(!X)return this.maybeResolveSubalias(Z);if(X=this.normalizeRootScopeValue(X),P(X,"generic"))return this.resolutions[Z]=this.bindReference(X);if(P(X,"module")){if(!X.root)L(Uz(Z));return this.resolutions[Z]=this.bindReference(X.root)}return this.resolutions[Z]=this.parse(X,{alias:Z})}createParseContext(Z){let Y=Z.id??Q7(Z.prefix);return _1[Y]=Object.assign(Z,{[S1]:"context",$:this,id:Y,phase:"unresolved"})}traversal(Z){return new G0(Z,this.resolvedConfig)}import(...Z){return new W2(b(this.export(...Z),(Y,X)=>[`#${Y}`,X]))}precompilation;_exportedResolutions;_exports;export(...Z){if(!this._exports){this._exports={};for(let X of this.exportedNames){let Q=this.aliases[X];this._exports[X]=P(Q,"module")?w7(Q,this):$z(this.maybeResolve(X))}for(let X of this.lazyResolutions)X.resolution;if(this._exportedResolutions=qz(this,this._exports),this._json=Vz(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let X=zz(this.references);this.precompilation=X.write(Wz,4),Jz(this.references,X)}this.resolved=!0}let Y=Z.length?Z:this.exportedNames;return new W2(b(Y,(X,Q)=>[Q,this._exports[Q]]))}resolve(Z){return this.export()[Z]}node=(Z,Y,X={})=>{let Q=this.preparseNode(Z,Y,X);if(r(Q))return this.bindReference(Q);let $=this.createParseContext(Q),W=$7($),J=this.bindReference(W);return _1[$.id]=J};parse=(Z,Y={})=>this.finalize(this.parseDefinition(Z,Y));parseDefinition(Z,Y={}){if(P(Z,"root"))return this.bindReference(Z);let X=this.preparseOwnDefinitionFormat(Z,Y);if(P(X,"root"))return this.bindReference(X);let Q=this.createParseContext(X);_1[Q.id]=Q;let $=this.bindReference(this.parseOwnDefinitionFormat(Z,Q));if($.isCyclic)$=IJ($,Q.id);return _1[Q.id]=$,$}finalize(Z){if($z(Z),!Z.precompilation&&!this.resolvedConfig.jitless)YF(Z.references);return Z}}class E7 extends N8{parseOwnDefinitionFormat(Z,Y){return $7(Y)}preparseOwnDefinitionFormat(Z,Y){return this.preparseNode(_6(Z),Z,Y)}preparseOwnAliasEntry(Z,Y){return[Z,Y]}normalizeRootScopeValue(Z){return Z}}var $z=(Z)=>{let Y=Z.references.filter((X)=>X.hasKind("alias"));for(let X of Y){Object.assign(X.referencesById,X.resolution.referencesById);for(let Q of Z.references)if(X.id in Q.referencesById)Object.assign(Q.referencesById,X.referencesById)}return Z},Vz=(Z)=>b(Z,(Y,X)=>[Y,P(X,"root")||P(X,"generic")?X.json:P(X,"module")?Vz(X):u(`Unexpected resolution ${x(X)}`)]),A7=(Z,Y)=>{let X=Y.indexOf(".");if(X===-1)return;let Q=Y.slice(0,X),$=Z[Q];if($===void 0)return;if(!P($,"module"))return L(XF(Q));let W=Y.slice(X+1),J=$[W];if(J===void 0)return A7($,W);if(P(J,"root")||P(J,"generic"))return J;if(P(J,"module"))return J.root??L(Uz(Y));u(`Unexpected resolution for alias '${Y}': ${x(J)}`)},w8=(Z,Y)=>new E7(Z,Y),u6=new E7({});var qz=(Z,Y)=>{let X={};for(let Q in Y){let $=Y[Q];if(P($,"module")){let W=qz(Z,$),J=b(W,(z,V)=>[`${Q}.${z}`,V]);Object.assign(X,J)}else if(P($,"root")||P($,"generic"))X[Q]=$;else u(`Unexpected scope resolution ${x($)}`)}return X},O7=(Z)=>`'${Z}' is unresolvable`,XF=(Z)=>`'${Z}' must reference a module to be accessed using dot syntax`,Uz=(Z)=>`Reference to submodule '${Z}' must specify an alias`;u6.export();var{schema:c,node:J2,defineSchema:py,generic:J0}=u6;var P7="^(?:0|[1-9]\\d*)$",QF=new RegExp(P7),ly=Q1(QF);var Hz=w8({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={...Hz};var Gz=w8({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:P7}},{prereducedAliases:!0}).export();Object.assign(F.intrinsic,Gz);var $F=w8({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),C={...Hz,...Gz,...$F,emptyStructure:J2("structure",{},{prereduced:!0})};F.intrinsic={...C};var D8=(Z,Y)=>new RegExp(Z,Y);Object.assign(D8,{as:D8});var Bz=(Z)=>typeof Z==="string"&&Z[0]==="d"&&(Z[1]==="'"||Z[1]==='"')&&Z[Z.length-1]===Z[1],Kz=(Z)=>Z.toString()!=="Invalid Date",Lz=(Z)=>Z.slice(2,-1),T7=(Z)=>`'${Z}' could not be parsed by the Date constructor`,Mz=(Z,Y)=>WF(Z,Y),WF=(Z,Y)=>{let X=new Date(Z);if(Kz(X))return X;let Q=pW(Z);if(Q!==void 0){let $=new Date(Q);if(Kz($))return $}return Y?L(Y===!0?T7(Z):Y):void 0};var JF=c({proto:"Array",sequence:"string",required:{key:"groups",value:["object",{unit:void 0}]}}),A8=(Z,Y)=>{let X=Z.scanner.shiftUntilEscapable(VF[wz[Y]]);if(Z.scanner.lookahead==="")return Z.error(UF(X,Y));if(Z.scanner.shift(),Y in Nz){let Q;try{Q=new RegExp(X)}catch($){L(String($))}if(Z.root=Z.ctx.$.node("intersection",{domain:"string",pattern:X},{prereduced:!0}),Y==="x/")Z.root=Z.ctx.$.node("morph",{in:Z.root,morphs:($)=>Q.exec($),declaredOut:JF})}else if(N1(Y,I7))Z.root=Z.ctx.$.node("unit",{unit:X});else{let Q=Mz(X,T7(X));Z.root=Z.ctx.$.node("unit",{meta:X,unit:Q})}},I7={"'":1,'"':1},Fz={"/":1,"'":1,'"':1},zF={"d'":"'",'d"':'"',"'":"'",'"':'"'},Nz={"/":"/","x/":"/"},wz={...zF,...Nz},VF={"'":(Z)=>Z.lookahead==="'",'"':(Z)=>Z.lookahead==='"',"/":(Z)=>Z.lookahead==="/"},qF={'"':"double-quote","'":"single-quote","/":"forward slash"},UF=(Z,Y)=>`${Y}${Z} requires a closing ${qF[wz[Y]]}`;var Dz=(Z)=>`Private type references should not include '#'. Use '${Z}' instead.`,E8="Optional definitions like 'string?' are only valid as properties in an object or tuple",O8="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var D0={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...r0};var Az=(Z,Y)=>Z===">"?Y[0]==="="?Y[1]==="=":Y.trimStart()===""||N1(Y.trimStart()[0],D0):Z==="="?Y[0]!=="=":Z===","||Z==="?";var Ez=(Z,Y,X)=>Oz(Z,Y,X,[]),Oz=(Z,Y,X,Q)=>{let $=X.parseUntilFinalizer();if(Q.push($.root),$.finalizer===">"){if(Q.length!==Y.params.length)return X.error(R7(Z,Y.names,Q.map((W)=>W.expression)));return Q}if($.finalizer===",")return Oz(Z,Y,X,Q);return $.error($8(">"))},R7=(Z,Y,X)=>`${Z}<${Y.join(", ")}> requires exactly ${Y.length} args (got ${X.length}${X.length===0?"":`: ${X.join(", ")}`})`;var P8=(Z)=>{let Y=Z.scanner.shiftUntilLookahead(D0);if(Y==="keyof")Z.addPrefix("keyof");else Z.root=GF(Z,Y)},HF=(Z,Y,X)=>{if(X.scanner.shiftUntilNonWhitespace(),X.scanner.shift()!=="<")return X.error(R7(Z,Y.names,[]));let $=Ez(Z,Y,X);return Y(...$)},GF=(Z,Y)=>KF(Z,Y)??BF(Z,Y)??Z.error(Y===""?Z.scanner.lookahead==="#"?Dz(Z.shiftedBy(1).scanner.shiftUntilLookahead(D0)):j7(Z):O7(Y)),KF=(Z,Y)=>{if(Z.ctx.args?.[Y]){let Q=Z.ctx.args[Y];if(typeof Q!=="string")return Q;return Z.ctx.$.node("alias",{reference:Q},{prereduced:!0})}let X=Z.ctx.$.maybeResolve(Y);if(P(X,"root"))return X;if(X===void 0)return;if(P(X,"generic"))return HF(Y,X,Z);return L(`Unexpected resolution ${x(X)}`)},BF=(Z,Y)=>{let X=dW(Y);if(X!==void 0)return Z.ctx.$.node("unit",{unit:X});let Q=lW(Y);if(Q!==void 0)return Z.ctx.$.node("unit",{unit:Q})},j7=(Z)=>{let Y=Z.previousOperator();return Y?C7(Y,Z.scanner.unscanned):LF(Z.scanner.unscanned)},C7=(Z,Y="")=>`Token '${Z}' requires a right operand${Y?` before '${Y}'`:""}`,LF=(Z)=>`Expected an expression${Z?` before '${Z}'`:""}`;var S7=(Z)=>Z.scanner.lookahead===""?Z.error(j7(Z)):Z.scanner.lookahead==="("?Z.shiftedBy(1).reduceGroupOpen():Z.scanner.lookaheadIsIn(Fz)?A8(Z,Z.scanner.shift()):Z.scanner.lookaheadIsIn(r0)?S7(Z.shiftedBy(1)):Z.scanner.lookahead==="d"?Z.scanner.nextLookahead in I7?A8(Z,`${Z.scanner.shift()}${Z.scanner.shift()}`):P8(Z):Z.scanner.lookahead==="x"?Z.scanner.nextLookahead==="/"?Z.shiftedBy(2)&&A8(Z,"x/"):P8(Z):P8(Z);var Pz={">":!0,">=":!0},Tz={"<":!0,"<=":!0};var z2={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},Iz=(Z,Y)=>`Left bounds are only valid when paired with right bounds (try ...${Y}${Z})`,T8=(Z)=>`Left-bounded expressions must specify their limits using < or <= (was ${Z})`,Rz=(Z,Y,X,Q)=>`An expression may have at most one left bound (parsed ${Z}${z2[Y]}, ${X}${z2[Q]})`;var Cz=(Z,Y)=>{let X=MF(Z,Y);if(Z.root.hasKind("unit")){if(typeof Z.root.unit==="number"){Z.reduceLeftBound(Z.root.unit,X),Z.unsetRoot();return}if(Z.root.unit instanceof Date){let Q=`d'${Z.root.description??Z.root.unit.toISOString()}'`;Z.unsetRoot(),Z.reduceLeftBound(Q,X);return}}return NF(Z,X)},Sz={"<":1,">":1,"=":1},MF=(Z,Y)=>Z.scanner.lookaheadIs("=")?`${Y}${Z.scanner.shift()}`:Y;var jz=(Z,Y,X,Q)=>{if(X.extends(F.intrinsic.number)){if(typeof Y!=="number")return L(_7(Z,Y,Q));return Z==="=="?["min","max"]:Z[0]===">"?["min"]:["max"]}if(X.extends(F.intrinsic.lengthBoundable)){if(typeof Y!=="number")return L(_7(Z,Y,Q));return Z==="=="?["exactLength"]:Z[0]===">"?["minLength"]:["maxLength"]}if(X.extends(F.intrinsic.Date))return Z==="=="?["after","before"]:Z[0]===">"?["after"]:["before"];return L(KJ(X.expression))},FF=(Z)=>({rule:Bz(Z.limit)?Lz(Z.limit):Z.limit,exclusive:Z.comparator.length===1}),NF=(Z,Y)=>{let X=Z.unsetRoot(),Q=Z.scanner.location;Z.parseOperand();let $=Z.unsetRoot(),W=Z.scanner.sliceChars(Q,Z.scanner.location);if(Z.root=X,!$.hasKind("unit")||typeof $.unit!=="number"&&!($.unit instanceof Date))return Z.error(_7(Y,W,"right"));let J=$.unit,z=Y.length===1,V=jz(Y,typeof J==="number"?J:W,X,"right");for(let U of V)Z.constrainRoot(U,Y==="=="?{rule:J}:{rule:J,exclusive:z});if(!Z.branches.leftBound)return;if(!N1(Y,Tz))return Z.error(T8(Y));let q=jz(Z.branches.leftBound.comparator,Z.branches.leftBound.limit,X,"left");Z.constrainRoot(q[0],FF(Z.branches.leftBound)),Z.branches.leftBound=null},_7=(Z,Y,X)=>`Comparator ${X==="left"?z2[Z]:Z} must be ${X==="left"?"preceded":"followed"} by a corresponding literal (was ${Y})`;var _z=(Z)=>{Z.scanner.shiftUntilNonWhitespace();let Y=Z.scanner.shiftUntilLookahead(D0);Z.root=Z.root.brand(Y)};var bz=(Z)=>{Z.scanner.shiftUntilNonWhitespace();let Y=Z.scanner.shiftUntilLookahead(D0),X=cW(Y,{errorOnFail:yz(Y)});if(X===0)Z.error(yz(0));Z.root=Z.root.constrain("divisor",X)},yz=(Z)=>`% operator must be followed by a non-zero integer literal (was ${Z})`;var y7=(Z)=>{let Y=Z.scanner.shift();return Y===""?Z.finalize(""):Y==="["?Z.scanner.shift()==="]"?Z.setRoot(Z.root.array()):Z.error(wF):Y==="|"?Z.scanner.lookahead===">"?Z.shiftedBy(1).pushRootToBranch("|>"):Z.pushRootToBranch(Y):Y==="&"?Z.pushRootToBranch(Y):Y===")"?Z.finalizeGroup():Az(Y,Z.scanner.unscanned)?Z.finalize(Y):N1(Y,Sz)?Cz(Z,Y):Y==="%"?bz(Z):Y==="#"?_z(Z):(Y in r0)?y7(Z):Z.error(I8(Y))},I8=(Z,Y="")=>`'${Z}' is not allowed here${Y&&` (should be ${Y})`}`,wF="Missing expected ']'";var xz=(Z)=>{let Y=Z.unsetRoot();Z.parseOperand();let X=Z.unsetRoot();if(!X.hasKind("unit"))return Z.error(DF(X.expression));let Q=X.unit instanceof Date?()=>new Date(X.unit):X.unit;return[Y,"=",Q]},DF=(Z)=>`Default value '${Z}' must be a literal value`;var b7=(Z,Y)=>{let X=Y.$.maybeResolveRoot(Z);if(X)return X;if(Z.endsWith("[]")){let W=Y.$.maybeResolveRoot(Z.slice(0,-2));if(W)return W.array()}let Q=new V2(new T6(Z),Y),$=AF(Q);if(Q.finalizer===">")L(I8(">"));return $},AF=(Z)=>{Z.parseOperand();let Y=m6(Z).root;if(!Y)return u(`Root was unexpectedly unset after parsing string '${Z.scanner.scanned}'`);if(Z.finalizer==="=")Y=xz(Z);else if(Z.finalizer==="?")Y=[Y,"?"];if(Z.scanner.shiftUntilNonWhitespace(),Z.scanner.lookahead)L(I8(Z.scanner.lookahead));return Y},m6=(Z)=>{while(Z.finalizer===void 0)EF(Z);return Z},EF=(Z)=>Z.hasRoot()?Z.parseOperator():Z.parseOperand();class V2{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(Z,Y){this.scanner=Z,this.ctx=Y}error(Z){return L(Z)}hasRoot(){return this.root!==void 0}setRoot(Z){this.root=Z}unsetRoot(){let Z=this.root;return this.root=void 0,Z}constrainRoot(...Z){this.root=this.root.constrain(Z[0],Z[1])}finalize(Z){if(this.groups.length)return this.error($8(")"));this.finalizeBranches(),this.finalizer=Z}reduceLeftBound(Z,Y){let X=z2[Y];if(!N1(X,Pz))return this.error(T8(Y));if(this.branches.leftBound)return this.error(Rz(this.branches.leftBound.limit,this.branches.leftBound.comparator,Z,X));this.branches.leftBound={comparator:X,limit:Z}}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 Z=this.groups.pop();if(!Z)return this.error(aW(")",this.scanner.unscanned));this.branches=Z}addPrefix(Z){this.branches.prefixes.push(Z)}applyPrefixes(){while(this.branches.prefixes.length){let Z=this.branches.prefixes.pop();this.root=Z==="keyof"?this.root.keyof():u(`Unexpected prefix '${Z}'`)}}pushRootToBranch(Z){this.assertRangeUnset(),this.applyPrefixes();let Y=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(Y)??Y,Z==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,Z==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return m6(new V2(this.scanner,this.ctx))}parseOperator(){return y7(this)}parseOperand(){return S7(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(Iz(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(Z){return this.scanner.jumpForward(Z),this}}var OF="An empty string is not a valid generic parameter name",R8=(Z,Y,X)=>{Z.shiftUntilNonWhitespace();let Q=Z.shiftUntilLookahead(D0);if(Q===""){if(Z.lookahead===""&&Y.length)return Y;return L(OF)}return Z.shiftUntilNonWhitespace(),PF(Z,Q,Y,X)},kz="extends ",PF=(Z,Y,X,Q)=>{if(Z.shiftUntilNonWhitespace(),Z.unscanned.startsWith(kz))Z.jumpForward(kz.length);else{if(Z.lookahead===",")Z.shift();return X.push(Y),R8(Z,X,Q)}let $=m6(new V2(Z,Q));return X.push([Y,$.root]),R8(Z,X,Q)};class x7 extends g1{constructor(Z){let Y={$:Z,raw:Z.fn};super((...X)=>{let Q=X.indexOf(":"),$=Q===-1?X.length-1:Q-1,W=X.slice(0,$+1),J=Z.parse(W).assertHasKind("intersection"),z=Z.intrinsic.unknown;if(Q!==-1){if(Q!==X.length-2)return L(TF);z=Z.parse(X[Q+1])}return(V)=>new vz(V,J,z)},{attach:Y})}}class vz extends g1{raw;params;returns;expression;constructor(Z,Y,X){let Q=`typed ${Z.name}`,$={[Q]:(...J)=>{let z=Y.assert(J),V=Z(...z);return X.assert(V)}}[Q];super($);this.raw=Z,this.params=Y,this.returns=X;let W=Y.expression;if(W[0]==="["&&W[W.length-1]==="]")W=W.slice(1,-1);else if(W.endsWith("[]"))W=`...${W}`;this.expression=`(${W}) => ${X?.expression??"unknown"}`}}var TF=`":" must be followed by exactly one return type e.g:
|
|
132
|
-
fn("string", ":", "number")(s => s.length)`;class k7 extends g1{$;constructor(Z){super((...Y)=>new p6(Z)(...Y),{bind:Z});this.$=Z}in(Z){return new p6(this.$,Z===void 0?void 0:this.$.parse(Z))}at(Z,Y){return new p6(this.$).at(Z,Y)}case(Z,Y){return new p6(this.$).case(Z,Y)}}class p6 extends g1{$;in;key;branches=[];constructor(Z,Y){super((X)=>this.caseEntries(Object.entries(X).map(([Q,$])=>Q==="default"?[Q,$]:[this.$.parse(Q),$])));this.$=Z,this.in=Y}at(Z,Y){if(this.key)L(RF);if(this.branches.length)L(IF);return this.key=Z,Y?this.match(Y):this}case(Z,Y){return this.caseEntry(this.$.parse(Z),Y)}caseEntry(Z,Y){let Q=(this.key?this.$.parse({[this.key]:Z}):Z).pipe(Y);return this.branches.push(Q),this}match(Z){return this(Z)}strings(Z){return this.caseEntries(Object.entries(Z).map(([Y,X])=>Y==="default"?[Y,X]:[this.$.node("unit",{unit:Y}),X]))}caseEntries(Z){for(let Y=0;Y<Z.length;Y++){let[X,Q]=Z[Y];if(X==="default"){if(Y!==Z.length-1)L("default may only be specified as the last key of a switch definition");return this.default(Q)}if(typeof Q!=="function")return L(`Value for case "${X}" must be a function (was ${F1(Q)})`);this.caseEntry(X,Q)}return this}default(Z){if(typeof Z==="function")this.case(C.unknown,Z);let Y={branches:this.branches,ordered:!0};if(Z==="never"||Z==="assert")Y.meta={onFail:fz};let X=this.$.node("union",Y);if(!this.in)return this.$.finalize(X);let Q=this.in.pipe(X);if(Z==="never"||Z==="assert")Q=Q.configureReferences({onFail:fz},"self");return this.$.finalize(Q)}}var fz=(Z)=>Z.throw(),IF="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",RF="At most one key matcher may be specified per expression";var j8=(Z,Y)=>{if(n(Z)){if(Z[1]==="=")return[Y.$.parseOwnDefinitionFormat(Z[0],Y),"=",Z[2]];if(Z[1]==="?")return[Y.$.parseOwnDefinitionFormat(Z[0],Y),"?"]}return C8(Z,Y)},hz="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",gz="Only required keys may specify default values, e.g. { value: 'number = 0' }";var uz=(Z,Y)=>{let X,Q={},$=D9(Z);for(let[J,z]of $){let V=SF(J);if(V.kind==="spread"){if(!N0(Q))return L(CF);let K=Y.$.parseOwnDefinitionFormat(z,Y);if(K.equals(C.object))continue;if(!K.hasKind("intersection")||!K.basis?.equals(C.object))return L(_F(K.expression));X=K.structure;continue}if(V.kind==="undeclared"){if(z!=="reject"&&z!=="delete"&&z!=="ignore")L(jF(z));Q.undeclared=z;continue}let q=j8(z,Y),U=V;if(V.kind==="required"){if(!n(q))v7(Q,"required",{key:V.normalized,value:q},Y);else v7(Q,"optional",q[1]==="="?{key:V.normalized,value:q[0],default:q[2]}:{key:V.normalized,value:q[0]},Y);continue}if(n(q)){if(q[1]==="?")L(hz);if(q[1]==="=")L(gz)}if(V.kind==="optional"){v7(Q,"optional",{key:V.normalized,value:q},Y);continue}let H=Y.$.parseOwnDefinitionFormat(U.normalized,Y),G=F8(H,q,Y.$);if(G.index)Q.index=h(Q.index,G.index);if(G.required)Q.required=h(Q.required,G.required)}let W=Y.$.node("structure",Q);return Y.$.parseSchema({domain:"object",structure:X?.merge(W)??W})},v7=(Z,Y,X,Q)=>{Z[Y]=h(Z[Y],Q.$.node(Y,X))},jF=(Z)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${x(Z)})`,CF="Spread operator may only be used as the first key in an object",SF=(Z)=>typeof Z==="symbol"?{kind:"required",normalized:Z}:Z[Z.length-1]==="?"?Z[Z.length-2]===E9?{kind:"required",normalized:`${Z.slice(0,-2)}?`}:{kind:"optional",normalized:Z.slice(0,-1)}:Z[0]==="["&&Z[Z.length-1]==="]"?{kind:"index",normalized:Z.slice(1,-1)}:Z[0]===E9&&Z[1]==="["&&Z[Z.length-1]==="]"?{kind:"required",normalized:Z.slice(1)}:Z==="..."?{kind:"spread"}:Z==="+"?{kind:"undeclared"}:{kind:"required",normalized:Z==="\\..."?"...":Z==="\\+"?"+":Z},_F=(Z)=>`Spread operand must resolve to an object literal type (was ${Z})`;var pz=(Z,Y)=>mF(Z)?iz[Z[0]](Z,Y):gF(Z)?lz[Z[1]](Z,Y):null,yF=(Z,Y)=>Y.$.parseOwnDefinitionFormat(Z[1],Y).keyof(),f7=(Z,Y)=>{if(Z[2]===void 0)return L(C7(Z[1],""));let X=Y.$.parseOwnDefinitionFormat(Z[0],Y),Q=Y.$.parseOwnDefinitionFormat(Z[2],Y);if(Z[1]==="|")return Y.$.node("union",{branches:[X,Q]});let $=Z[1]==="&"?p1(X,Q,Y.$):S6(X,Q,Y.$);if($ instanceof w)return $.throw();return $},bF=(Z,Y)=>Y.$.parseOwnDefinitionFormat(Z[0],Y).array(),xF=(Z,Y)=>{if(typeof Z[2]!=="function")return L(dz("=>",Z[2]));return Y.$.parseOwnDefinitionFormat(Z[0],Y).pipe(Z[2])},dz=(Z,Y)=>`${Z===":"?"Narrow":"Morph"} expression requires a function following '${Z}' (was ${typeof Y})`,kF=(Z,Y)=>{if(typeof Z[2]!=="function")return L(dz(":",Z[2]));return Y.$.parseOwnDefinitionFormat(Z[0],Y).constrain("predicate",Z[2])},vF=(Z,Y)=>Y.$.parseOwnDefinitionFormat(Z[0],Y).configure(Z[2],Z[3]),cz=(Z)=>Z,fF=cz({"[]":bF,"?":()=>L(E8)}),hF=cz({"|":f7,"&":f7,":":kF,"=>":xF,"|>":f7,"@":vF,"=":()=>L(O8)}),lz={...fF,...hF},gF=(Z)=>lz[Z[1]]!==void 0,uF=(Z)=>Z,iz=uF({keyof:yF,instanceof:(Z,Y)=>{if(typeof Z[1]!=="function")return L(mz(N6(Z[1])));let X=Z.slice(1).map((Q)=>typeof Q==="function"?Y.$.node("proto",{proto:Q}):L(mz(N6(Q))));return X.length===1?X[0]:Y.$.node("union",{branches:X})},"===":(Z,Y)=>Y.$.units(Z.slice(1))}),mF=(Z)=>iz[Z[0]]!==void 0,mz=(Z)=>`Expected a constructor following 'instanceof' operator (was ${Z})`;var az=(Z,Y)=>{let X=[{}],Q=0;while(Q<Z.length){let $=!1;if(Z[Q]==="..."&&Q<Z.length-1)$=!0,Q++;let W=j8(Z[Q],Y),[J,z,V]=!n(W)?[W]:W;if(Q++,$){if(!J.extends(F.intrinsic.Array))return L(cF(J.expression));X=X.flatMap((q)=>J.distribute((U)=>dF(J8(q),U)))}else X=X.map((q)=>{if(z==="?")return rz(q,J);if(z==="=")return pF(q,J,V);return h7(q,J)})}return Y.$.parseSchema(X.map(($)=>N0($)?{proto:Array,exactLength:0}:{proto:Array,sequence:$}))},h7=(Z,Y)=>{if(Z.defaultables||Z.optionals)return L(Z.variadic?M7:lF);if(Z.variadic)Z.postfix=h(Z.postfix,Y);else Z.prefix=h(Z.prefix,Y);return Z},rz=(Z,Y)=>{if(Z.variadic)return L(sz);return Z.optionals=h(Z.optionals,Y),Z},pF=(Z,Y,X)=>{if(Z.variadic)return L(sz);if(Z.optionals)return L(iF);return Z.defaultables=h(Z.defaultables,[[Y,X]]),Z},oz=(Z,Y)=>{if(Z.postfix)L(nz);if(Z.variadic){if(!Z.variadic.equals(Y))L(nz)}else Z.variadic=Y.internal;return Z},dF=(Z,Y)=>{let X=Y.select({method:"find",kind:"sequence"});if(!X)return oz(Z,F.intrinsic.unknown);if(X.prefix)for(let Q of X.prefix)h7(Z,Q);if(X.optionals)for(let Q of X.optionals)rz(Z,Q);if(X.variadic)oz(Z,X.variadic);if(X.postfix)for(let Q of X.postfix)h7(Z,Q);return Z},cF=(Z)=>`Spread element must be an array (was ${Z})`,nz="A tuple may have at most one variadic element",lF="A required element may not follow an optional element",sz="An optional element may not follow a variadic element";var iF="A defaultable element may not follow an optional element without a default";var oF={},C8=(Z,Y)=>{if(typeof Z==="string"){if(Y.args&&Object.keys(Y.args).some((Q)=>Z.includes(Q)))return b7(Z,Y);let X=oF[Y.$.name]??={};return X[Z]??=b7(Z,Y)}return v1(Z,"object")?nF(Z,Y):L(g7(F1(Z)))},nF=(Z,Y)=>{let X=F6(Z);switch(X){case void 0:if(P(Z,"root"))return Z;if("~standard"in Z)return aF(Z,Y);return uz(Z,Y);case"Array":return rF(Z,Y);case"RegExp":return Y.$.node("intersection",{domain:"string",pattern:Z},{prereduced:!0});case"Function":{let Q=a0(Z)?Z():Z;if(P(Q,"root"))return Q;return L(g7("Function"))}default:return L(g7(X??x(Z)))}},aF=(Z,Y)=>Y.$.intrinsic.unknown.pipe((X,Q)=>{let $=Z["~standard"].validate(X);if(!$.issues)return $.value;for(let{message:W,path:J}of $.issues)if(J)if(J.length)Q.error({problem:vW(W),relativePath:J.map((z)=>typeof z==="object"?z.key:z)});else Q.error({message:W});else Q.error({message:W})}),rF=(Z,Y)=>pz(Z,Y)??az(Z,Y),g7=(Z)=>`Type definitions must be strings or objects (was ${Z})`;class u7 extends g1{constructor(Z){let Y=Object.assign({errors:u1,hkt:T1,$:Z,raw:Z.parse,module:Z.constructor.module,scope:Z.constructor.scope,declare:Z.declare,define:Z.define,match:Z.match,generic:Z.generic,schema:Z.schema,keywords:Z.ambient,unit:Z.unit,enumerated:Z.enumerated,instanceOf:Z.instanceOf,valueOf:Z.valueOf,or:Z.or,and:Z.and,merge:Z.merge,pipe:Z.pipe,fn:Z.fn},Z.ambientAttachments);super((...X)=>{if(X.length===1)return Z.parse(X[0]);if(X.length===2&&typeof X[0]==="string"&&X[0][0]==="<"&&X[0][X[0].length-1]===">"){let Q=X[0].slice(1,-1),$=Z.parseGenericParams(Q,{});return new Z9($,X[1],Z,Z,null)}return Z.parse(X)},{attach:Y})}}var q2=F;class S8 extends N8{get ambientAttachments(){if(!q2.typeAttachments)return;return this.cacheGetter("ambientAttachments",b(q2.typeAttachments,(Z,Y)=>[Z,this.bindReference(Y)]))}preparseOwnAliasEntry(Z,Y){let X=Z.indexOf("<");if(X===-1){if(P(Y,"module")||P(Y,"generic"))return[Z,Y];let W=this.name==="ark"?Z:Z==="root"?this.name:`${this.name}.${Z}`,J=this.resolvedConfig.keywords?.[W];if(J)Y=[Y,"@",J];return[Z,Y]}if(Z[Z.length-1]!==">")L("'>' must be the last character of a generic declaration in a scope");let Q=Z.slice(0,X),$=Z.slice(X+1,-1);return[Q,()=>{let W=this.parseGenericParams($,{alias:Q});return UJ(W,Y,this)}]}parseGenericParams(Z,Y){return R8(new T6(Z),[],this.createParseContext({...Y,def:Z,prefix:"generic"}))}normalizeRootScopeValue(Z){if(a0(Z)&&!P(Z,"generic"))return Z();return Z}preparseOwnDefinitionFormat(Z,Y){return{...Y,def:Z,prefix:Y.alias??"type"}}parseOwnDefinitionFormat(Z,Y){if(!(Y.alias&&(Y.alias in this.aliases))&&!Y.args)Y.args={this:Y.id};let Q=C8(Z,Y);if(n(Q)){if(Q[1]==="=")return L(O8);if(Q[1]==="?")return L(E8)}return Q}unit=(Z)=>this.units([Z]);valueOf=(Z)=>this.units(RW(Z));enumerated=(...Z)=>this.units(Z);instanceOf=(Z)=>this.node("proto",{proto:Z},{prereduced:!0});or=(...Z)=>this.schema(Z.map((Y)=>this.parse(Y)));and=(...Z)=>Z.reduce((Y,X)=>Y.and(this.parse(X)),this.intrinsic.unknown);merge=(...Z)=>Z.reduce((Y,X)=>Y.merge(this.parse(X)),this.intrinsic.object);pipe=(...Z)=>this.intrinsic.unknown.pipe(...Z);fn=new x7(this);match=new k7(this);declare=()=>({type:this.type});define(Z){return Z}type=new u7(this);static scope=(Z,Y={})=>new S8(Z,Y);static module=(Z,Y={})=>this.scope(Z,Y).export()}var m7=Object.assign(S8.scope,{define:(Z)=>Z}),f=S8;class tz extends T1{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var sF=J0(["base",C.object],["props",C.object])((Z)=>Z.base.merge(Z.props),tz),ez=f.module({Key:C.key,Merge:sF});class ZV extends T1{}var tF=J0("element")((Z)=>{let Y=Z.element.exclude(C.Array),X=Y.array();return Y.rawOr(X).pipe(n0).distribute((Q)=>Q.assertHasKind("morph").declareOut(X),c)},ZV),YV=f.module({root:C.Array,readonly:"root",index:C.nonNegativeIntegerString,liftFrom:tF},{name:"Array"});var p7=c(["string",O9.FileConstructor]),eF=p7.rawOr(p7.array()),XV=c({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:eF}}),QV=f.module({root:["instanceof",FormData],value:p7,parsed:XV,parse:c({in:FormData,morphs:(Z)=>{let Y={};for(let[X,Q]of Z)if(X in Y){let $=Y[X];if(typeof $==="string"||$ instanceof O9.FileConstructor)Y[X]=[$,Q];else $.push(Q)}else Y[X]=Q;return Y},declaredOut:XV})},{name:"FormData"});var $V=f.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 ZN={Boolean:1,Number:1,String:1},WV=f.module({...b({...CY,..._Y},(Z,Y)=>(Z in ZN)?[]:[Z,["instanceof",Y]]),Array:YV,TypedArray:$V,FormData:QV});var YN=c({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"}),XN=c({domain:"number",divisor:1}),_8=f.module({root:C.number,integer:XN,epoch:YN,safe:c({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 e=(Z,Y,X)=>{let Q={domain:"string",pattern:{rule:Z.source,flags:Z.flags,meta:Y}};if(X)Q.meta={format:X};return J2("intersection",Q)},JV=e(D6,"a well-formed integer string"),NV=f.module({root:JV,parse:c({in:JV,morphs:(Z,Y)=>{let X=Number.parseInt(Z);return Number.isSafeInteger(X)?X:Y.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:C.integer})},{name:"string.integer"}),QN=e(/^[\dA-Fa-f]+$/,"hex characters only"),$N=f.module({root:e(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:e(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),zV=e(/^[A-Z].*$/,"capitalized"),WN=f.module({root:c({in:"string",morphs:(Z)=>Z.charAt(0).toUpperCase()+Z.slice(1),declaredOut:zV}),preformatted:zV},{name:"string.capitalize"}),JN=(Z)=>{let Y=Z.replace(/[ -]+/g,""),X=0,Q,$,W=!1;for(let J=Y.length-1;J>=0;J--){if(Q=Y.substring(J,J+1),$=Number.parseInt(Q,10),W)$*=2,X+=$>=10?$%10+1:$;else X+=$;W=!W}return!!(X%10===0?Y:!1)},zN=/^(?: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}))$/,VN=c({domain:"string",pattern:{meta:"a credit card number",rule:zN.source},predicate:{meta:"a credit card number",predicate:JN}});var qN=/^([+-]?\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 UN=(Z)=>!Number.isNaN(new Date(Z).valueOf()),VV=c({domain:"string",predicate:{meta:"a parsable date",predicate:UN}}).assertHasKind("intersection"),qV=NV.root.internal.narrow((Z,Y)=>{let X=Number.parseInt(Z),Q=_8.epoch(X);if(Q instanceof u1)return Y.errors.merge(Q),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),HN=f.module({root:qV,parse:c({in:qV,morphs:(Z)=>new Date(Z),declaredOut:C.Date})},{name:"string.date.epoch"}),UV=e(qN,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),GN=f.module({root:UV,parse:c({in:UV,morphs:(Z)=>new Date(Z),declaredOut:C.Date})},{name:"string.date.iso"}),KN=f.module({root:VV,parse:c({declaredIn:VV,in:"string",morphs:(Z,Y)=>{let X=new Date(Z);if(Number.isNaN(X.valueOf()))return Y.error("a parsable date");return X},declaredOut:C.Date}),iso:GN,epoch:HN},{name:"string.date"}),BN=e(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),HV="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",Y9=`(${HV}[.]){3}${HV}`,LN=new RegExp(`^${Y9}$`),G1="(?:[0-9a-fA-F]{1,4})",MN=new RegExp(`^((?:${G1}:){7}(?:${G1}|:)|(?:${G1}:){6}(?:${Y9}|:${G1}|:)|(?:${G1}:){5}(?::${Y9}|(:${G1}){1,2}|:)|(?:${G1}:){4}(?:(:${G1}){0,1}:${Y9}|(:${G1}){1,3}|:)|(?:${G1}:){3}(?:(:${G1}){0,2}:${Y9}|(:${G1}){1,4}|:)|(?:${G1}:){2}(?:(:${G1}){0,3}:${Y9}|(:${G1}){1,5}|:)|(?:${G1}:){1}(?:(:${G1}){0,4}:${Y9}|(:${G1}){1,6}|:)|(?::((?::${G1}){0,5}:${Y9}|(?::${G1}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),FN=f.module({root:["v4 | v6","@","an IP address"],v4:e(LN,"an IPv4 address","ipv4"),v6:e(MN,"an IPv6 address","ipv6")},{name:"string.ip"}),U2="a JSON string",wV=(Z)=>{if(!(Z instanceof SyntaxError))throw Z;return`must be ${U2} (${Z})`},NN=c({meta:U2,domain:"string",predicate:{meta:U2,predicate:(Z,Y)=>{try{return JSON.parse(Z),!0}catch(X){return Y.reject({code:"predicate",expected:U2,problem:wV(X)})}}}}),wN=(Z,Y)=>{if(Z.length===0)return Y.error({code:"predicate",expected:U2,actual:"empty"});try{return JSON.parse(Z)}catch(X){return Y.error({code:"predicate",expected:U2,problem:wV(X)})}},DN=f.module({root:NN,parse:c({meta:"safe JSON string parser",in:"string",morphs:wN,declaredOut:C.jsonObject})},{name:"string.json"}),GV=e(/^[a-z]*$/,"only lowercase letters"),AN=f.module({root:c({in:"string",morphs:(Z)=>Z.toLowerCase(),declaredOut:GV}),preformatted:GV},{name:"string.lower"}),DV=["NFC","NFD","NFKC","NFKD"],d6=b(DV,(Z,Y)=>[Y,c({domain:"string",predicate:(X)=>X.normalize(Y)===X,meta:`${Y}-normalized unicode`})]),y8=b(DV,(Z,Y)=>[Y,c({in:"string",morphs:(X)=>X.normalize(Y),declaredOut:d6[Y]})]),EN=f.module({root:y8.NFC,preformatted:d6.NFC},{name:"string.normalize.NFC"}),ON=f.module({root:y8.NFD,preformatted:d6.NFD},{name:"string.normalize.NFD"}),PN=f.module({root:y8.NFKC,preformatted:d6.NFKC},{name:"string.normalize.NFKC"}),TN=f.module({root:y8.NFKD,preformatted:d6.NFKD},{name:"string.normalize.NFKD"}),IN=f.module({root:"NFC",NFC:EN,NFD:ON,NFKC:PN,NFKD:TN},{name:"string.normalize"}),KV=e(X8,"a well-formed numeric string"),RN=f.module({root:KV,parse:c({in:KV,morphs:(Z)=>Number.parseFloat(Z),declaredOut:C.number})},{name:"string.numeric"}),BV="a regex pattern",jN=c({domain:"string",predicate:{meta:BV,predicate:(Z,Y)=>{try{return new RegExp(Z),!0}catch(X){return Y.reject({code:"predicate",expected:BV,problem:String(X)})}}},meta:{format:"regex"}}),CN=/^(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-]+)*))?$/,SN=e(CN,"a semantic version (see https://semver.org/)"),LV=e(/^\S.*\S$|^\S?$/,"trimmed"),_N=f.module({root:c({in:"string",morphs:(Z)=>Z.trim(),declaredOut:LV}),preformatted:LV},{name:"string.trim"}),MV=e(/^[A-Z]*$/,"only uppercase letters"),yN=f.module({root:c({in:"string",morphs:(Z)=>Z.toUpperCase(),declaredOut:MV}),preformatted:MV},{name:"string.upper"}),bN=(Z)=>URL.canParse(Z),FV=c({domain:"string",predicate:{meta:"a URL string",predicate:bN},meta:{format:"uri"}}),xN=f.module({root:FV,parse:c({declaredIn:FV,in:"string",morphs:(Z,Y)=>{try{return new URL(Z)}catch{return Y.error("a URL string")}},declaredOut:c(URL)})},{name:"string.url"}),kN=f.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:e(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:e(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:e(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:e(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:e(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:e(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:e(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:e(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),AV=f.module({root:C.string,alpha:e(/^[A-Za-z]*$/,"only letters"),alphanumeric:e(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:QN,base64:$N,capitalize:WN,creditCard:VN,date:KN,digits:e(/^\d*$/,"only digits 0-9"),email:BN,integer:NV,ip:FN,json:DN,lower:AN,normalize:IN,numeric:RN,regex:jN,semver:SN,trim:_N,upper:yN,url:xN,uuid:kN},{name:"string"});var EV=f.module({bigint:C.bigint,boolean:C.boolean,false:C.false,never:C.never,null:C.null,number:C.number,object:C.object,string:C.string,symbol:C.symbol,true:C.true,unknown:C.unknown,undefined:C.undefined}),OV=f.module({root:C.unknown,any:C.unknown},{name:"unknown"}),vN=f.module({root:C.jsonObject,stringify:J2("morph",{in:C.jsonObject,morphs:(Z)=>JSON.stringify(Z),declaredOut:C.string})},{name:"object.json"}),PV=f.module({root:C.object,json:vN},{name:"object"});class TV extends T1{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var fN=J0(["K",C.key],"V")((Z)=>({domain:"object",index:{signature:Z.K,value:Z.V}}),TV);class IV extends T1{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var hN=J0(["T",C.object],["K",C.key])((Z)=>Z.T.pick(Z.K),IV);class RV extends T1{description='omit a set of properties from an object like `Omit(User, "age")`'}var gN=J0(["T",C.object],["K",C.key])((Z)=>Z.T.omit(Z.K),RV);class jV extends T1{description="make all named properties of an object optional like `Partial(User)`"}var uN=J0(["T",C.object])((Z)=>Z.T.partial(),jV);class CV extends T1{description="make all named properties of an object required like `Required(User)`"}var mN=J0(["T",C.object])((Z)=>Z.T.required(),CV);class SV extends T1{description='exclude branches of a union like `Exclude("boolean", "true")`'}var pN=J0("T","U")((Z)=>Z.T.exclude(Z.U),SV);class _V extends T1{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var dN=J0("T","U")((Z)=>Z.T.extract(Z.U),_V),yV=f.module({Exclude:pN,Extract:dN,Omit:gN,Partial:uN,Pick:hN,Record:fN,Required:mN});var g0=m7({...EV,...yV,...WV,...ez,string:AV,number:_8,object:PV,unknown:OV},{prereducedAliases:!0,name:"ark"}),w1=g0.export();Object.assign(q2.ambient,w1);q2.typeAttachments={string:w1.string.root,number:w1.number.root,bigint:w1.bigint,boolean:w1.boolean,symbol:w1.symbol,undefined:w1.undefined,null:w1.null,object:w1.object.root,unknown:w1.unknown.root,false:w1.false,true:w1.true,never:w1.never,arrayIndex:w1.Array.index,Key:w1.Key,Record:w1.Record,Array:w1.Array.root,Date:w1.Date};var K1=Object.assign(g0.type,q2.typeAttachments),cN=g0.match,lN=g0.fn,iN=g0.generic,Ov=g0.schema,oN=g0.define,nN=g0.declare;var mv=K1("'feature' | 'bugfix' | 'refactor' | 'config' | 'docs' | 'test' | 'mixed'"),bV=K1({summary:"string",purpose:"string",scope:"'feature' | 'bugfix' | 'refactor' | 'config' | 'docs' | 'test' | 'mixed'",affectedAreas:"string[]","suggestedReviewOrder?":"string[]"}),pv=K1("'low' | 'medium' | 'high' | 'critical'"),dv=K1("'high' | 'medium' | 'low'"),aN=K1({severity:"'low' | 'medium' | 'high' | 'critical'",category:"string",description:"string",evidence:"string","file?":"string","mitigation?":"string"}),b8=K1({overallRisk:"'low' | 'medium' | 'high' | 'critical'",summary:"string",risks:aN.array(),confidence:"'high' | 'medium' | 'low'"}),xV=K1({alignment:"'aligned' | 'partial' | 'misaligned'",confidence:"'high' | 'medium' | 'low'",summary:"string",matches:"string[]",mismatches:"string[]",missing:"string[]",unstated:"string[]"}),rN=K1({name:"string",description:"string",files:"string[]",priority:"number"}),cv=K1({flows:rN.array(),uncategorized:"string[]"});function s1(Z){let Y=Z["~standard"];if(!Y)throw new Error("Schema does not have ~standard property. Is this an ArkType schema?");return{"~standard":Y}}function I9(Z){if(Z.status!=="deleted")return!1;return Z.hunks.reduce((X,Q)=>X+Q.lines.filter(($)=>$.type==="delete").length,0)>100}function sN(Z,Y){let X=[];if([".ts",".tsx",".js",".jsx",".mjs",".cjs"].includes(Y)){let Q=Z.matchAll(/^(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+(\w+)/gm);for(let q of Q)X.push(`class ${q[1]}`);let $=Z.matchAll(/^(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s+(\w+)/gm);for(let q of $)X.push(`function ${q[1]}()`);let W=Z.matchAll(/^export\s+const\s+(\w+)\s*=/gm);for(let q of W)X.push(`const ${q[1]}`);let J=Z.matchAll(/^(?:export\s+)?interface\s+(\w+)/gm);for(let q of J)X.push(`interface ${q[1]}`);let z=Z.matchAll(/^(?:export\s+)?type\s+(\w+)\s*=/gm);for(let q of z)X.push(`type ${q[1]}`);let V=Z.matchAll(/^export\s+\{([^}]+)\}/gm);for(let q of V){let U=q[1];if(U){let H=U.split(",").map((G)=>G.trim().split(/\s+as\s+/)[0]?.trim()).filter(Boolean);if(H.length>0)X.push(`export { ${H.join(", ")} }`)}}}if(Y===".py"){let Q=Z.matchAll(/^class\s+(\w+)/gm);for(let W of Q)X.push(`class ${W[1]}`);let $=Z.matchAll(/^(?:async\s+)?def\s+(\w+)/gm);for(let W of $)X.push(`def ${W[1]}()`)}return X}function x8(Z){let Y=Z.hunks.flatMap((Q)=>Q.lines.filter(($)=>$.type==="delete").map(($)=>$.content)),X=kV(Z.path);return{headerLines:Y.slice(0,15),signatures:sN(Y.join(`
|
|
133
|
-
`),
|
|
134
|
-
`)}function kV(Z){let Y=Z.lastIndexOf(".");if(Y===-1)return"";return Z.slice(Y).toLowerCase()}function tN(Z){return{".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".rs":"rust",".go":"go",".java":"java",".rb":"ruby",".css":"css",".scss":"scss",".json":"json",".yaml":"yaml",".yml":"yaml",".md":"markdown"}[Z]||""}function eN(Z){let Y=[Z.header];for(let X of Z.lines){let Q=X.type==="add"?"+":X.type==="delete"?"-":" ";Y.push(`${Q}${X.content}`)}return Y.join(`
|
|
135
|
-
`)}function
|
|
136
|
-
`)
|
|
137
|
-
`)}
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
1.
|
|
141
|
-
2.
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
- But derive intent from the CODE, not just the stated intent
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
-
|
|
163
|
-
|
|
164
|
-
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
-
|
|
234
|
-
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
- Imports may reference files that exist but aren't shown in the diff
|
|
241
|
-
- Functions may be defined in files you can't see
|
|
242
|
-
- Types may be declared elsewhere
|
|
243
|
-
- New files created in this change may appear as imports but not as full file contents
|
|
244
|
-
|
|
245
|
-
When you see something that MIGHT be an issue but could be fine with full context:
|
|
246
|
-
- Don't flag it as critical/high severity
|
|
247
|
-
- Either skip it entirely, or note it as low severity with "may be resolved by unseen context"
|
|
248
|
-
- Focus on issues that are clearly evident FROM the diff itself
|
|
249
|
-
|
|
250
|
-
## Output Quality
|
|
251
|
-
|
|
252
|
-
- Order risks by severity (critical first)
|
|
253
|
-
- Keep descriptions concise but specific
|
|
254
|
-
- If a risk has a clear mitigation, include it
|
|
255
|
-
- If you're uncertain, reflect that in confidence level`;function Qw(Z,Y,X,Q){let $=Y.filter((z)=>z.tier<=2),W=[];W.push("## Diff Overview"),W.push(`Total files changed: ${Z.files.length}`),W.push(`Files included for analysis: ${$.length}`);let J=Y.filter((z)=>z.tier===3);if(J.length>0){W.push(`(${J.length} files excluded from analysis: lock files, generated code, binaries)`);let z=J.filter((V)=>V.file.path.includes(".test.")||V.file.path.includes(".spec."));if(z.length>0)W.push(`Note: ${z.length} test file(s) were in excluded category`)}if(W.push(""),Q)W.push(Q),W.push("");W.push("## Files Changed");for(let z of $){let V=z.file.status;W.push(`- ${z.file.path} (${V})`)}W.push(""),W.push("## Diff Content"),W.push("");for(let z of $)W.push(X9(z.file)),W.push("");if(X)W.push("## Author's Stated Intent"),W.push(""),W.push(X),W.push(""),W.push("Consider whether any risks relate to gaps between this stated intent and the actual implementation."),W.push("");return W.push("---"),W.push(`Analyze this diff for potential risks.
|
|
256
|
-
|
|
257
|
-
Requirements:
|
|
258
|
-
1. For each risk, cite SPECIFIC evidence from the diff (file, line, code snippet)
|
|
259
|
-
2. Only flag issues that have concrete evidence - no generic warnings
|
|
260
|
-
3. If the change looks safe, it's okay to return an empty risks array
|
|
261
|
-
4. Order risks by severity (critical/high first)
|
|
262
|
-
5. Set confidence based on how much context you have
|
|
263
|
-
|
|
264
|
-
REQUIRED OUTPUT FIELDS (all are mandatory):
|
|
265
|
-
- overallRisk: "low" | "medium" | "high" | "critical" - the highest severity among all risks (use "low" if no risks)
|
|
266
|
-
- summary: string - 1-2 sentence actionable summary
|
|
267
|
-
- risks: array of risk objects (can be empty array [] if no risks found)
|
|
268
|
-
- confidence: "high" | "medium" | "low" - how confident you are in this assessment
|
|
269
|
-
|
|
270
|
-
Each risk object MUST have:
|
|
271
|
-
- severity: "low" | "medium" | "high" | "critical"
|
|
272
|
-
- category: string (e.g., "security", "breaking-change", "performance")
|
|
273
|
-
- description: string - what the risk is
|
|
274
|
-
- evidence: string - specific code/line from the diff`),W.join(`
|
|
275
|
-
`)}async function G2(Z,Y,X,Q){let $=Qw(Z,Y,X,Q);try{return await k1({adapter:C1("claude-sonnet-4-5"),systemPrompts:[Xw],messages:[{role:"user",content:$}],outputSchema:s1(b8),temperature:0.4,stream:!1,maxTokens:8192})}catch(W){if(W instanceof Error&&W.message.includes("Validation failed")){let J=new Error(`${W.message}
|
|
276
|
-
|
|
277
|
-
This usually means the LLM response was missing required fields. Check that the diff wasn't too large (${Z.files.length} files, ${Y.filter((z)=>z.tier<=2).length} analyzed).`);throw J.cause=W,J}throw W}}var $w=`You are comparing what an author claims their code change does (stated intent) against what it actually does (derived intent).
|
|
278
|
-
|
|
279
|
-
Your goal is to identify:
|
|
280
|
-
1. Do the stated and derived intents align?
|
|
281
|
-
2. What matches between claimed and actual behavior?
|
|
282
|
-
3. What mismatches - where the code does something different than stated?
|
|
283
|
-
4. What's missing - stated but not implemented?
|
|
284
|
-
5. What's unstated - implemented but not mentioned (scope creep)?
|
|
285
|
-
|
|
286
|
-
## Alignment Levels
|
|
287
|
-
|
|
288
|
-
- **aligned**: The code does what the author says, with no significant extra or missing pieces.
|
|
289
|
-
Use this when the stated intent accurately describes the changes.
|
|
290
|
-
|
|
291
|
-
- **partial**: Some aspects match, but there are notable gaps or additions.
|
|
292
|
-
Use when: core intent is correct but scope differs, or some stated items are missing.
|
|
293
|
-
|
|
294
|
-
- **misaligned**: The code does something substantially different than claimed.
|
|
295
|
-
Use when: stated intent is misleading, or changes don't match the stated goal.
|
|
296
|
-
|
|
297
|
-
## Calibration Guidelines
|
|
298
|
-
|
|
299
|
-
- Be generous with "aligned" - minor wording differences don't matter
|
|
300
|
-
- "partial" is common - real changes often include cleanup/related fixes not mentioned
|
|
301
|
-
- "misaligned" should be rare - only when there's genuine mismatch of stated vs actual
|
|
302
|
-
- Vague stated intent ("misc fixes", "updates") should get medium/low confidence
|
|
303
|
-
- If stated intent is just a feature name with no details, focus on whether the feature exists
|
|
304
|
-
|
|
305
|
-
## Evidence Requirements
|
|
306
|
-
|
|
307
|
-
For each item in matches/mismatches/missing/unstated, cite specific evidence:
|
|
308
|
-
- Good: "Added null check in UserService.ts:45 as stated"
|
|
309
|
-
- Good: "Error refactoring not mentioned but present in 3 files"
|
|
310
|
-
- Bad: "Some things match"
|
|
311
|
-
- Bad: "There might be missing features"
|
|
312
|
-
|
|
313
|
-
## Context Limitations
|
|
314
|
-
|
|
315
|
-
You are comparing stated intent against a diff, not the complete codebase. This means:
|
|
316
|
-
- New files created in this change may not appear in the diff hunks
|
|
317
|
-
- Imports may reference files that exist but aren't shown
|
|
318
|
-
- If an import references a file that isn't visible, assume it likely exists
|
|
319
|
-
|
|
320
|
-
Don't flag "missing implementation" if the code imports from a file you can't see - it's probably implemented there. Focus on alignment issues evident from what IS visible.
|
|
321
|
-
|
|
322
|
-
## Output Quality
|
|
323
|
-
|
|
324
|
-
- Keep summary to 1-2 sentences - the key finding
|
|
325
|
-
- Order matches/mismatches/missing/unstated by importance
|
|
326
|
-
- Empty arrays are fine - not every analysis will have all categories
|
|
327
|
-
- Set confidence based on how clear the comparison is`;function Ww(Z){let Y=[],X=Z.status.toUpperCase();if(Z.status==="renamed"&&Z.oldPath)Y.push(`=== ${Z.oldPath} → ${Z.path} (${X}) ===`);else Y.push(`=== ${Z.path} (${X}) ===`);if(Z.isBinary)return Y.push("[binary file]"),Y.join(`
|
|
328
|
-
`);for(let Q of Z.hunks)Y.push(Jw(Q));return Y.join(`
|
|
329
|
-
`)}function Jw(Z){let Y=[Z.header];for(let X of Z.lines){let Q=X.type==="add"?"+":X.type==="delete"?"-":" ";Y.push(`${Q}${X.content}`)}return Y.join(`
|
|
330
|
-
`)}function zw(Z,Y,X,Q,$){let W=[];if(W.push("## Author's Stated Intent"),W.push(""),W.push(Z),W.push(""),W.push("## Derived Intent (from diff analysis)"),W.push(""),W.push(`**Summary:** ${Y.summary}`),W.push(`**Purpose:** ${Y.purpose}`),W.push(`**Scope:** ${Y.scope}`),W.push(`**Affected Areas:** ${Y.affectedAreas.join(", ")}`),W.push(""),$)W.push($),W.push("");W.push("## Diff Content (for evidence)"),W.push("");let J=Q.filter((z)=>z.tier<=2);for(let z of J)W.push(Ww(z.file)),W.push("");return W.push("---"),W.push(""),W.push(`Compare the stated intent against the derived intent and the actual diff.
|
|
331
|
-
|
|
332
|
-
For each finding, cite specific evidence from the diff.
|
|
333
|
-
|
|
334
|
-
If the stated intent is vague, note that in the summary and set confidence accordingly.`),W.join(`
|
|
335
|
-
`)}async function v8(Z,Y,X,Q,$){let W=zw(Z,Y,X,Q,$);return await k1({adapter:C1("claude-sonnet-4-5"),systemPrompts:[$w],messages:[{role:"user",content:W}],outputSchema:s1(xV),temperature:0.3,stream:!1,maxTokens:4096})}class K2 extends Error{constructor(){super("ANTHROPIC_API_KEY environment variable is not set. Please set it to your Anthropic API key.");this.name="LLMAPIKeyError"}}class B2 extends Error{cause;constructor(Z,Y){super(Z);this.cause=Y;this.name="LLMGenerationError"}}function f8(){return!!process.env.ANTHROPIC_API_KEY}var m=E0(M2(),1);class t1 extends Error{code;constructor(Z,Y){super(Z);this.code=Y;this.name="GitHubError"}}import{dirname as rw}from"path";import{createRequire as Vw}from"module";import{spawn as qw}from"node:child_process";import{delimiter as vV,dirname as Uw,normalize as Hw,resolve as Gw}from"node:path";import{cwd as Kw}from"node:process";import{PassThrough as Bw}from"node:stream";import Lw from"node:readline";var{create:Mw,defineProperty:uV,getOwnPropertyDescriptor:Fw,getOwnPropertyNames:Nw,getPrototypeOf:ww}=Object,Dw=Object.prototype.hasOwnProperty,e1=(Z,Y)=>()=>(Y||Z((Y={exports:{}}).exports,Y),Y.exports),Aw=(Z,Y,X,Q)=>{if(Y&&typeof Y==="object"||typeof Y==="function"){for(var $=Nw(Y),W=0,J=$.length,z;W<J;W++)if(z=$[W],!Dw.call(Z,z)&&z!==X)uV(Z,z,{get:((V)=>Y[V]).bind(null,z),enumerable:!(Q=Fw(Y,z))||Q.enumerable})}return Z},Ew=(Z,Y,X)=>(X=Z!=null?Mw(ww(Z)):{},Aw(Y||!Z||!Z.__esModule?uV(X,"default",{value:Z,enumerable:!0}):X,Z)),Q9=Vw(import.meta.url),Ow=/^path$/i,fV={key:"PATH",value:""};function Pw(Z){for(let Y in Z){if(!Object.prototype.hasOwnProperty.call(Z,Y)||!Ow.test(Y))continue;let X=Z[Y];if(!X)return fV;return{key:Y,value:X}}return fV}function Tw(Z,Y){let X=Y.value.split(vV),Q=Z,$;do X.push(Gw(Q,"node_modules",".bin")),$=Q,Q=Uw(Q);while(Q!==$);return{key:Y.key,value:X.join(vV)}}function Iw(Z,Y){let X={...process.env,...Y},Q=Tw(Z,Pw(X));return X[Q.key]=Q.value,X}var Rw=(Z)=>{let Y=Z.length,X=new Bw,Q=()=>{if(--Y===0)X.emit("end")};for(let $ of Z)$.pipe(X,{end:!1}),$.on("end",Q);return X},jw=e1((Z,Y)=>{Y.exports=W,W.sync=J;var X=Q9("fs");function Q(z,V){var q=V.pathExt!==void 0?V.pathExt:process.env.PATHEXT;if(!q)return!0;if(q=q.split(";"),q.indexOf("")!==-1)return!0;for(var U=0;U<q.length;U++){var H=q[U].toLowerCase();if(H&&z.substr(-H.length).toLowerCase()===H)return!0}return!1}function $(z,V,q){if(!z.isSymbolicLink()&&!z.isFile())return!1;return Q(V,q)}function W(z,V,q){X.stat(z,function(U,H){q(U,U?!1:$(H,z,V))})}function J(z,V){return $(X.statSync(z),z,V)}}),Cw=e1((Z,Y)=>{Y.exports=Q,Q.sync=$;var X=Q9("fs");function Q(z,V,q){X.stat(z,function(U,H){q(U,U?!1:W(H,V))})}function $(z,V){return W(X.statSync(z),V)}function W(z,V){return z.isFile()&&J(z,V)}function J(z,V){var{mode:q,uid:U,gid:H}=z,G=V.uid!==void 0?V.uid:process.getuid&&process.getuid(),K=V.gid!==void 0?V.gid:process.getgid&&process.getgid(),M=parseInt("100",8),E=parseInt("010",8),O=parseInt("001",8),T=M|E,i=q&O||q&E&&H===K||q&M&&U===G||q&T&&G===0;return i}}),Sw=e1((Z,Y)=>{var X=Q9("fs"),Q;if(process.platform==="win32"||global.TESTING_WINDOWS)Q=jw();else Q=Cw();Y.exports=$,$.sync=W;function $(J,z,V){if(typeof z==="function")V=z,z={};if(!V){if(typeof Promise!=="function")throw new TypeError("callback not provided");return new Promise(function(q,U){$(J,z||{},function(H,G){if(H)U(H);else q(G)})})}Q(J,z||{},function(q,U){if(q){if(q.code==="EACCES"||z&&z.ignoreErrors)q=null,U=!1}V(q,U)})}function W(J,z){try{return Q.sync(J,z||{})}catch(V){if(z&&z.ignoreErrors||V.code==="EACCES")return!1;else throw V}}}),_w=e1((Z,Y)=>{let X=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",Q=Q9("path"),$=X?";":":",W=Sw(),J=(U)=>Object.assign(new Error(`not found: ${U}`),{code:"ENOENT"}),z=(U,H)=>{let G=H.colon||$,K=U.match(/\//)||X&&U.match(/\\/)?[""]:[...X?[process.cwd()]:[],...(H.path||process.env.PATH||"").split(G)],M=X?H.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",E=X?M.split(G):[""];if(X){if(U.indexOf(".")!==-1&&E[0]!=="")E.unshift("")}return{pathEnv:K,pathExt:E,pathExtExe:M}},V=(U,H,G)=>{if(typeof H==="function")G=H,H={};if(!H)H={};let{pathEnv:K,pathExt:M,pathExtExe:E}=z(U,H),O=[],T=(g)=>new Promise((Z1,$1)=>{if(g===K.length)return H.all&&O.length?Z1(O):$1(J(U));let W1=K[g],A0=/^".*"$/.test(W1)?W1.slice(1,-1):W1,z0=Q.join(A0,U),W9=!A0&&/^\.[\\\/]/.test(U)?U.slice(0,2)+z0:z0;Z1(i(W9,g,0))}),i=(g,Z1,$1)=>new Promise((W1,A0)=>{if($1===M.length)return W1(T(Z1+1));let z0=M[$1];W(g+z0,{pathExt:E},(W9,u8)=>{if(!W9&&u8)if(H.all)O.push(g+z0);else return W1(g+z0);return W1(i(g,Z1,$1+1))})});return G?T(0).then((g)=>G(null,g),G):T(0)},q=(U,H)=>{H=H||{};let{pathEnv:G,pathExt:K,pathExtExe:M}=z(U,H),E=[];for(let O=0;O<G.length;O++){let T=G[O],i=/^".*"$/.test(T)?T.slice(1,-1):T,g=Q.join(i,U),Z1=!i&&/^\.[\\\/]/.test(U)?U.slice(0,2)+g:g;for(let $1=0;$1<K.length;$1++){let W1=Z1+K[$1];try{if(W.sync(W1,{pathExt:M}))if(H.all)E.push(W1);else return W1}catch(A0){}}}if(H.all&&E.length)return E;if(H.nothrow)return null;throw J(U)};Y.exports=V,V.sync=q}),yw=e1((Z,Y)=>{let X=(Q={})=>{let $=Q.env||process.env;if((Q.platform||process.platform)!=="win32")return"PATH";return Object.keys($).reverse().find((J)=>J.toUpperCase()==="PATH")||"Path"};Y.exports=X,Y.exports.default=X}),bw=e1((Z,Y)=>{let X=Q9("path"),Q=_w(),$=yw();function W(z,V){let q=z.options.env||process.env,U=process.cwd(),H=z.options.cwd!=null,G=H&&process.chdir!==void 0&&!process.chdir.disabled;if(G)try{process.chdir(z.options.cwd)}catch(M){}let K;try{K=Q.sync(z.command,{path:q[$({env:q})],pathExt:V?X.delimiter:void 0})}catch(M){}finally{if(G)process.chdir(U)}if(K)K=X.resolve(H?z.options.cwd:"",K);return K}function J(z){return W(z)||W(z,!0)}Y.exports=J}),xw=e1((Z,Y)=>{let X=/([()\][%!^"`<>&|;, *?])/g;function Q(W){return W=W.replace(X,"^$1"),W}function $(W,J){if(W=`${W}`,W=W.replace(/(\\*)"/g,"$1$1\\\""),W=W.replace(/(\\*)$/,"$1$1"),W=`"${W}"`,W=W.replace(X,"^$1"),J)W=W.replace(X,"^$1");return W}Y.exports.command=Q,Y.exports.argument=$}),kw=e1((Z,Y)=>{Y.exports=/^#!(.*)/}),vw=e1((Z,Y)=>{let X=kw();Y.exports=(Q="")=>{let $=Q.match(X);if(!$)return null;let[W,J]=$[0].replace(/#! ?/,"").split(" "),z=W.split("/").pop();if(z==="env")return J;return J?`${z} ${J}`:z}}),fw=e1((Z,Y)=>{let X=Q9("fs"),Q=vw();function $(W){let z=Buffer.alloc(150),V;try{V=X.openSync(W,"r"),X.readSync(V,z,0,150,0),X.closeSync(V)}catch(q){}return Q(z.toString())}Y.exports=$}),hw=e1((Z,Y)=>{let X=Q9("path"),Q=bw(),$=xw(),W=fw(),J=process.platform==="win32",z=/\.(?:com|exe)$/i,V=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function q(G){G.file=Q(G);let K=G.file&&W(G.file);if(K)return G.args.unshift(G.file),G.command=K,Q(G);return G.file}function U(G){if(!J)return G;let K=q(G),M=!z.test(K);if(G.options.forceShell||M){let E=V.test(K);G.command=X.normalize(G.command),G.command=$.command(G.command),G.args=G.args.map((T)=>$.argument(T,E));let O=[G.command].concat(G.args).join(" ");G.args=["/d","/s","/c",`"${O}"`],G.command=process.env.comspec||"cmd.exe",G.options.windowsVerbatimArguments=!0}return G}function H(G,K,M){if(K&&!Array.isArray(K))M=K,K=null;K=K?K.slice(0):[],M=Object.assign({},M);let E={command:G,args:K,options:M,file:void 0,original:{command:G,args:K}};return M.shell?E:U(E)}Y.exports=H}),gw=e1((Z,Y)=>{let X=process.platform==="win32";function Q(z,V){return Object.assign(new Error(`${V} ${z.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${V} ${z.command}`,path:z.command,spawnargs:z.args})}function $(z,V){if(!X)return;let q=z.emit;z.emit=function(U,H){if(U==="exit"){let G=W(H,V,"spawn");if(G)return q.call(z,"error",G)}return q.apply(z,arguments)}}function W(z,V){if(X&&z===1&&!V.file)return Q(V.original,"spawn");return null}function J(z,V){if(X&&z===1&&!V.file)return Q(V.original,"spawnSync");return null}Y.exports={hookChildProcess:$,verifyENOENT:W,verifyENOENTSync:J,notFoundError:Q}}),uw=e1((Z,Y)=>{let X=Q9("child_process"),Q=hw(),$=gw();function W(z,V,q){let U=Q(z,V,q),H=X.spawn(U.command,U.args,U.options);return $.hookChildProcess(H,U),H}function J(z,V,q){let U=Q(z,V,q),H=X.spawnSync(U.command,U.args,U.options);return H.error=H.error||$.verifyENOENTSync(H.status,U),H}Y.exports=W,Y.exports.spawn=W,Y.exports.sync=J,Y.exports._parse=Q,Y.exports._enoent=$}),mw=Ew(uw(),1),hV=class extends Error{result;output;get exitCode(){if(this.result.exitCode!==null)return this.result.exitCode;return}constructor(Z,Y){super(`Process exited with non-zero status (${Z.exitCode})`);this.result=Z,this.output=Y}},pw={timeout:void 0,persist:!1},dw={windowsHide:!0};function cw(Z,Y){return{command:Hw(Z),args:Y??[]}}function lw(Z){let Y=new AbortController;for(let X of Z){if(X.aborted)return Y.abort(),X;let Q=()=>{Y.abort(X.reason)};X.addEventListener("abort",Q,{signal:Y.signal})}return Y.signal}async function gV(Z){let Y="";for await(let X of Z)Y+=X.toString();return Y}var iw=class{_process;_aborted=!1;_options;_command;_args;_resolveClose;_processClosed;_thrownError;get process(){return this._process}get pid(){return this._process?.pid}get exitCode(){if(this._process&&this._process.exitCode!==null)return this._process.exitCode;return}constructor(Z,Y,X){this._options={...pw,...X},this._command=Z,this._args=Y??[],this._processClosed=new Promise((Q)=>{this._resolveClose=Q})}kill(Z){return this._process?.kill(Z)===!0}get aborted(){return this._aborted}get killed(){return this._process?.killed===!0}pipe(Z,Y,X){return ow(Z,Y,{...X,stdin:this})}async*[Symbol.asyncIterator](){let Z=this._process;if(!Z)return;let Y=[];if(this._streamErr)Y.push(this._streamErr);if(this._streamOut)Y.push(this._streamOut);let X=Rw(Y),Q=Lw.createInterface({input:X});for await(let $ of Q)yield $.toString();if(await this._processClosed,Z.removeAllListeners(),this._thrownError)throw this._thrownError;if(this._options?.throwOnError&&this.exitCode!==0&&this.exitCode!==void 0)throw new hV(this)}async _waitForOutput(){let Z=this._process;if(!Z)throw new Error("No process was started");let[Y,X]=await Promise.all([this._streamOut?gV(this._streamOut):"",this._streamErr?gV(this._streamErr):""]);if(await this._processClosed,this._options?.stdin)await this._options.stdin;if(Z.removeAllListeners(),this._thrownError)throw this._thrownError;let Q={stderr:X,stdout:Y,exitCode:this.exitCode};if(this._options.throwOnError&&this.exitCode!==0&&this.exitCode!==void 0)throw new hV(this,Q);return Q}then(Z,Y){return this._waitForOutput().then(Z,Y)}_streamOut;_streamErr;spawn(){let Z=Kw(),Y=this._options,X={...dw,...Y.nodeOptions},Q=[];if(this._resetState(),Y.timeout!==void 0)Q.push(AbortSignal.timeout(Y.timeout));if(Y.signal!==void 0)Q.push(Y.signal);if(Y.persist===!0)X.detached=!0;if(Q.length>0)X.signal=lw(Q);X.env=Iw(Z,X.env);let{command:$,args:W}=cw(this._command,this._args),J=(0,mw._parse)($,W,X),z=qw(J.command,J.args,J.options);if(z.stderr)this._streamErr=z.stderr;if(z.stdout)this._streamOut=z.stdout;if(this._process=z,z.once("error",this._onError),z.once("close",this._onClose),Y.stdin!==void 0&&z.stdin&&Y.stdin.process){let{stdout:V}=Y.stdin.process;if(V)V.pipe(z.stdin)}}_resetState(){this._aborted=!1,this._processClosed=new Promise((Z)=>{this._resolveClose=Z}),this._thrownError=void 0}_onError=(Z)=>{if(Z.name==="AbortError"&&(!(Z.cause instanceof Error)||Z.cause.name!=="TimeoutError")){this._aborted=!0;return}this._thrownError=Z};_onClose=()=>{if(this._resolveClose)this._resolveClose()}},d7=(Z,Y,X)=>{let Q=new iw(Z,Y,X);return Q.spawn(),Q},ow=d7;import{readFile as nw,access as aw}from"node:fs/promises";var h8=typeof Bun!=="undefined";async function mV(Z){if(h8)return Bun.file(Z).text();return nw(Z,"utf-8")}async function pV(Z){if(h8)return Bun.file(Z).exists();try{return await aw(Z),!0}catch{return!1}}async function dV(){if(h8)return Bun.stdin.text();let Z=[];for await(let Y of process.stdin)Z.push(Y);return Buffer.concat(Z).toString("utf-8")}async function $9(Z,Y,X){if(h8){let $={stdout:"pipe",stderr:"pipe"};if(X?.cwd)$.cwd=X.cwd;let W=Bun.spawn([Z,...Y],$),[J,z,V]=await Promise.all([new Response(W.stdout).text(),new Response(W.stderr).text(),W.exited]);return{stdout:J,stderr:z,exitCode:V}}let Q=await d7(Z,Y,{nodeOptions:{cwd:X?.cwd},throwOnError:!1});return{stdout:Q.stdout,stderr:Q.stderr,exitCode:Q.exitCode??0}}async function cV(){if((await $9("gh",["--version"])).exitCode!==0)throw new t1("gh CLI is not installed. Install it from https://cli.github.com/","GH_NOT_INSTALLED");if((await $9("gh",["auth","status"])).exitCode!==0)throw new t1("Not authenticated with GitHub. Run `gh auth login` to authenticate.","NOT_AUTHENTICATED")}async function lV(Z,Y){let X=["pr","diff",String(Z)];if(Y)X.push("-R",Y);let{stdout:Q,stderr:$,exitCode:W}=await $9("gh",X);if(W!==0)oV($,Z,Y);return Q}async function iV(Z,Y){let X=["title","body","author","commits","baseRefName","headRefName","state","number","url"].join(","),Q=["pr","view",String(Z),"--json",X];if(Y)Q.push("-R",Y);let{stdout:$,stderr:W,exitCode:J}=await $9("gh",Q);if(J!==0)oV(W,Z,Y);try{return JSON.parse($)}catch{throw new t1(`Failed to parse PR metadata: ${$.slice(0,200)}`,"GH_ERROR")}}function oV(Z,Y,X){let Q=Z.toLowerCase(),$=X?` in ${X}`:"";if(Q.includes("could not resolve to a pullrequest")||Q.includes("no pull requests found")||Q.includes("http 404"))throw new t1(`PR #${Y} not found${$}`,"PR_NOT_FOUND");if(Q.includes("could not resolve to a repository")||Q.includes("repository not found"))throw new t1(`Repository not found: ${X||"(current)"}`,"REPO_NOT_FOUND");if(Q.includes("not logged in")||Q.includes("authentication"))throw new t1("Not authenticated with GitHub. Run `gh auth login` to authenticate.","NOT_AUTHENTICATED");if(Q.includes("not a git repository")||Q.includes("could not determine current repository"))throw new t1("Not in a git repository. Use -R owner/repo to specify the repository.","NOT_IN_REPO");throw new t1(`gh error: ${Z.trim()}`,"GH_ERROR")}function nV(Z){let Y=[];if(Y.push(`PR Title: ${Z.title}`),Y.push(`Author: ${Z.author.name||Z.author.login}`),Y.push(`Branch: ${Z.headRefName} → ${Z.baseRefName}`),Z.body?.trim())Y.push(""),Y.push("PR Description:"),Y.push(Z.body.trim());if(Z.commits.length>1){Y.push(""),Y.push(`Commits (${Z.commits.length}):`);for(let X of Z.commits)if(Y.push(` - ${X.messageHeadline}`),X.messageBody?.trim()){let Q=X.messageBody.trim().split(`
|
|
336
|
-
`).map(($)=>` ${$}`).join(`
|
|
337
|
-
`);Y.push(Q)}}return Y.join(`
|
|
338
|
-
`)}async function aV(Z,Y,X){if(Z.length===0)return[];let Q=["api",`repos/${X}/git/trees/${Y}?recursive=1`,"--jq",".tree[].path"],{stdout:$,stderr:W,exitCode:J}=await $9("gh",Q);if(J!==0){let U=[];return U.warning=`Could not fetch repository context from GitHub: ${W.trim()}`,U}let z=$.split(`
|
|
339
|
-
`).filter(Boolean),V=new Set(Z),q=[];for(let U of z){let H=rw(U);if(V.has(H))q.push({path:U,status:"existing"})}return q.sort((U,H)=>U.path.localeCompare(H.path))}function sw(Z){let Y=[],X=m.default.dim("─".repeat(60));return Y.push(X),Y.push(m.default.bold(m.default.cyan(`PR #${Z.number}: ${Z.title}`))),Y.push(X),Y.push(""),Y.push(`${m.default.bold("Author:")} ${Z.author.name||Z.author.login}`),Y.push(`${m.default.bold("URL:")} ${m.default.blue(Z.url)}`),Y.push(`${m.default.bold("Branch:")} ${Z.headRefName} → ${Z.baseRefName}`),Y.push(`${m.default.bold("State:")} ${tw(Z.state)}`),Y.push(""),Y.join(`
|
|
340
|
-
`)}function tw(Z){switch(Z){case"OPEN":return m.default.green(Z);case"MERGED":return m.default.magenta(Z);case"CLOSED":return m.default.red(Z)}}function ew(Z,Y,X,Q,$,W){if(W.json)console.log(JSON.stringify({pr:{number:Z.number,title:Z.title,author:Z.author,url:Z.url,state:Z.state,branch:{head:Z.headRefName,base:Z.baseRefName}},statedIntent:Q,intent:Y,risks:X,alignment:$},null,2));else if(console.log(sw(Z)),W.verbose)console.log(s6(Y,X,Q,$));else console.log(r6(Y,X,Q,$))}async function ZD(){let{stdout:Z,exitCode:Y}=await $9("gh",["repo","view","--json","nameWithOwner","--jq",".nameWithOwner"]);if(Y!==0)throw new t1("Could not determine current repository. Use -R owner/repo to specify.","NOT_IN_REPO");return Z.trim()}function YD(Z){let Y=Z;if(!Y.startsWith("http://")&&!Y.startsWith("https://"))Y=`https://${Y}`;let X;try{X=new URL(Y)}catch{return null}if(X.hostname!=="github.com")return null;let Q=X.pathname.slice(1).split("/");if(Q.length<4||Q[2]!=="pull")return null;let $=Q[0],W=Q[1],J=Q[3];if(!$||!W||!J)return null;let z=parseInt(J,10);if(isNaN(z))return null;return{owner:$,repo:W,prNumber:z}}function XD(Z,Y){let X=YD(Z);if(X)return{repo:`${X.owner}/${X.repo}`,prNumber:X.prNumber};let Q=Z.match(/^([^#]+)#(\d+)$/);if(Q&&Q[1]&&Q[2])return{repo:Q[1],prNumber:parseInt(Q[2],10)};let $=parseInt(Z,10);if(isNaN($))throw new Error(`Invalid PR identifier: ${Z}. Use a number, owner/repo#number, or GitHub URL.`);return{prNumber:$,repo:Y}}function rV(){return new R9("pr").description("Analyze a GitHub PR").argument("<identifier>","PR number, owner/repo#number, or GitHub URL").option("-R, --repo <repo>","Repository in owner/repo format").option("-v, --verbose","Show detailed output",!1).option("--json","Output results as JSON",!1).action(async(Z,Y)=>{try{let{prNumber:X,repo:Q}=XD(Z,Y.repo),$={...Y,prNumber:X,repo:Q};if(console.log(m.default.dim("Checking gh CLI...")),await cV(),!f8())console.error(m.default.red(`Error: ANTHROPIC_API_KEY environment variable is not set.
|
|
341
|
-
`)+m.default.dim(`Set it in your .env file or export it in your shell:
|
|
342
|
-
`)+m.default.dim(" export ANTHROPIC_API_KEY=sk-ant-...")),process.exit(1);console.log(m.default.dim(`Fetching PR #${X}...`));let[W,J]=await Promise.all([iV(X,Q),lV(X,Q)]);if(!J.trim()){console.log(m.default.yellow(`
|
|
343
|
-
PR has no file changes.`)),console.log(m.default.dim(`URL: ${W.url}`));return}console.log(m.default.dim("Parsing diff..."));let z=v9(J),V=f9(z);console.log(m.default.dim(`Found ${z.files.length} file(s), analyzing with AI...`));let q=nV(W),U=iZ(z),H=Q||await ZD(),G=await aV(U,W.baseRefName,H),K=G.warning;if(K)console.log(m.default.yellow(`⚠ ${K}`)),console.log(m.default.dim(" Analysis will continue but may flag false positives about missing files."));let M=oZ(G),[E,O]=await Promise.all([H2(z,V,q,M),G2(z,V,q,M)]);console.log(m.default.dim("Analyzing intent alignment..."));let T=await v8(q,E,z,V,M);console.log(""),ew(W,E,O,q,T,$)}catch(X){if(X instanceof t1){if(console.error(m.default.red(`GitHub error: ${X.message}`)),X.code==="GH_NOT_INSTALLED")console.error(m.default.dim("Install gh from https://cli.github.com/"));else if(X.code==="NOT_AUTHENTICATED")console.error(m.default.dim("Run `gh auth login` to authenticate."));else if(X.code==="NOT_IN_REPO")console.error(m.default.dim("Specify the repository with -R owner/repo"));process.exit(1)}if(X instanceof K2)console.error(m.default.red(`Error: Invalid or missing API key.
|
|
344
|
-
`)+m.default.dim("Check that your ANTHROPIC_API_KEY is correct.")),process.exit(1);if(X instanceof B2)console.error(m.default.red(`Error: AI analysis failed.
|
|
345
|
-
`)+m.default.dim(X.message)),process.exit(1);let Q=X instanceof Error?X.message:String(X);console.error(m.default.red(`Error: ${Q}`)),process.exit(1)}})}var q1=E0(M2(),1);function sV(Z){return Math.ceil(Z.length/4)}function QD(Z){let Y=Z.hunks.flatMap((Q)=>Q.lines.map(($)=>$.content)).join(`
|
|
346
|
-
`),X=sV(Y);if(I9(Z)){let Q=x8(Z),$=k8(Z,Q);return{original:X,withSummarization:sV($),summarized:!0}}return{original:X,withSummarization:X,summarized:!1}}function tV(Z){let Y=Z.map((W)=>({path:W.path,estimate:QD(W)})),X=Y.reduce((W,J)=>W+J.estimate.original,0),Q=Y.reduce((W,J)=>W+J.estimate.withSummarization,0),$=X-Q;return{files:Y,totals:{original:X,withSummarization:Q,savings:$,savingsPercent:X>0?Math.round($/X*100):0}}}function eV(Z){if(Z.status==="deleted")return Z.hunks.reduce((Y,X)=>Y+X.lines.filter((Q)=>Q.type==="delete").length,0);return Z.hunks.reduce((Y,X)=>Y+X.lines.filter((Q)=>Q.type==="add"||Q.type==="delete").length,0)}function $D(Z,Y){let X=[],Q=Z.filter((z)=>z.tier===1).length,$=Z.filter((z)=>z.tier===2).length,W=Z.filter((z)=>z.tier===3).length;X.push(q1.default.bold(`Files (${Z.length} total: ${Q} Tier 1, ${$} Tier 2, ${W} excluded):`));let J=[...Z].sort((z,V)=>{if(z.tier!==V.tier)return z.tier-V.tier;return z.file.path.localeCompare(V.file.path)});for(let z of J){let V=z.file,q=eV(V),U=V.status.toUpperCase().padEnd(8),H=I9(V),G;switch(V.status){case"added":G=q1.default.green(U);break;case"deleted":G=q1.default.red(U);break;case"renamed":G=q1.default.yellow(U);break;default:G=q1.default.blue(U)}let K=z.tier===3?q1.default.dim(" [excluded]"):"",M=H?q1.default.cyan(" [summarized]"):"";X.push(` ${G} ${V.path} (${q} lines)${M}${K}`)}return X.join(`
|
|
347
|
-
`)}function WD(Z){let Y=[],{totals:X}=Z;if(Y.push(q1.default.bold("Token Estimate:")),Y.push(` Original: ${X.original.toLocaleString()} tokens`),Y.push(` Summarized: ${X.withSummarization.toLocaleString()} tokens`),X.savings>0)Y.push(q1.default.green(` Savings: ${X.savings.toLocaleString()} tokens (${X.savingsPercent}%)`));return Y.join(`
|
|
348
|
-
`)}function Zq(Z){let Y=[],X=Z.filter((Q)=>Q.tier<=2);for(let Q of X)Y.push(X9(Q.file)),Y.push("");return Y.join(`
|
|
349
|
-
`)}function JD(Z,Y,X){let $={files:Z.map((W)=>{let J=W.file,z=Y.files.find((V)=>V.path===J.path);return{path:J.path,status:J.status,tier:W.tier,lines:eV(J),summarized:I9(J),tokens:z?{original:z.estimate.original,withSummarization:z.estimate.withSummarization}:{original:0,withSummarization:0}}}),totals:{files:Z.length,tier1:Z.filter((W)=>W.tier===1).length,tier2:Z.filter((W)=>W.tier===2).length,excluded:Z.filter((W)=>W.tier===3).length,tokens:Y.totals}};if(!X.stats&&!X.filesOnly)$.content=Zq(Z);return $}async function zD(Z,Y){let X={target:Z,...Y};try{console.error(q1.default.dim(`Fetching ${X.target} diff...`));let Q=await P4(X.target,X.cwd);if(!Q.hasChanges){if(X.json)console.log(JSON.stringify({files:[],totals:{files:0,tier1:0,tier2:0,excluded:0,tokens:{original:0,withSummarization:0,savings:0,savingsPercent:0}}},null,2));else if(console.log(q1.default.yellow(`
|
|
350
|
-
No changes found.`)),X.target==="unstaged")console.log(q1.default.dim(`Make some changes first, or try:
|
|
351
|
-
`)+q1.default.dim(` diffloupe summarize --staged
|
|
352
|
-
`)+q1.default.dim(" diffloupe summarize HEAD~1"));return}let $=v9(Q.diff),W=f9($),J=W.filter((q)=>q.tier<=2).map((q)=>q.file),z=tV(J);if(X.json){let q=JD(W,z,X);console.log(JSON.stringify(q,null,2));return}let V=[];if(V.push(q1.default.bold(q1.default.cyan("=== DIFF SUMMARY ==="))),V.push(""),V.push($D(W,z)),V.push(""),!X.noTokens)V.push(WD(z)),V.push("");if(!X.stats&&!X.filesOnly)V.push(q1.default.bold(q1.default.cyan("=== DIFF CONTENT ==="))),V.push(""),V.push(Zq(W));console.log(V.join(`
|
|
353
|
-
`))}catch(Q){if(Q instanceof O1){if(console.error(q1.default.red(`Git error: ${Q.message}`)),Q.code==="NOT_A_REPO")console.error(q1.default.dim("Run this command from within a git repository."));process.exit(1)}let $=Q instanceof Error?Q.message:String(Q);console.error(q1.default.red(`Error: ${$}`)),process.exit(1)}}function Yq(){return new R9("summarize").description("Preview diff formatting without running LLM analysis").argument("[target]","What to diff: unstaged, staged, HEAD, branch:name, commit:hash, or range:a..b","unstaged").option("--stats","Show only file list and token estimates",!1).option("--full","Include system prompt framing (not yet implemented)",!1).option("--json","Output as JSON",!1).option("--no-tokens","Skip token estimates").option("--files-only","Show only file list",!1).option("-C, --cwd <path>","Run as if started in <path>").action(zD)}function VD(Z){let Y=0;for(let X of Z.files)for(let Q of X.hunks)for(let $ of Q.lines)if($.type==="add"||$.type==="delete")Y++;return Y}function c7(Z,Y){let X=Y.length,Q=VD(Z),$=Y.reduce((J,z)=>J+z.estimatedTokens,0),W=Y.filter((J)=>J.tier===1).length;return{fileCount:X,totalLines:Q,estimatedTokens:$,tier1FileCount:W}}function l7(Z){let{fileCount:Y,estimatedTokens:X}=Z;if(Y<=15||X<=8000)return{strategy:"direct",reason:Y<=15?`Small diff (${Y} files ≤ ${"15"})`:`Low token count (${X} ≤ ${"8000"})`,metrics:Z};if(Y<=40)return{strategy:"two-pass",reason:`Medium diff (${Y} files, 16-40 range)`,metrics:Z};if(Y<=80)return{strategy:"flow-based",reason:`Large diff (${Y} files, 41-80 range)`,metrics:Z};return{strategy:"hierarchical",reason:`Huge diff (${Y} files > 80)`,metrics:Z}}var qD=K1({summary:"string",purpose:"string",scope:"'feature' | 'bugfix' | 'refactor' | 'config' | 'docs' | 'test' | 'mixed'",affectedAreas:"string[]",flaggedFiles:K1({path:"string",reason:"string"}).array(),initialRisks:K1({severity:"'low' | 'medium' | 'high' | 'critical'",category:"string",description:"string",evidence:"string","file?":"string"}).array()}),Xq=20,UD=`You are an experienced code reviewer doing a quick scan of a diff to identify areas needing detailed review.
|
|
354
|
-
|
|
355
|
-
Your goal in this OVERVIEW pass is to:
|
|
356
|
-
1. Understand the overall intent of the change
|
|
357
|
-
2. Identify which files need careful, detailed review
|
|
358
|
-
3. Flag any immediately obvious risks
|
|
359
|
-
|
|
360
|
-
## Key Principles
|
|
361
|
-
|
|
362
|
-
- This is a QUICK SCAN, not a detailed review
|
|
363
|
-
- Flag files that have:
|
|
364
|
-
- Security-sensitive changes (auth, validation, secrets)
|
|
365
|
-
- Complex logic changes
|
|
366
|
-
- API/interface changes that could break things
|
|
367
|
-
- Error handling modifications
|
|
368
|
-
- Database/data layer changes
|
|
369
|
-
- Don't flag routine files:
|
|
370
|
-
- Pure test files (unless testing critical paths)
|
|
371
|
-
- Config files with minor changes
|
|
372
|
-
- Formatting/style changes
|
|
373
|
-
- Simple type additions
|
|
374
|
-
|
|
375
|
-
## Scope Definitions
|
|
376
|
-
|
|
377
|
-
- **feature**: New functionality
|
|
378
|
-
- **bugfix**: Fixing incorrect behavior
|
|
379
|
-
- **refactor**: Code restructuring without behavior change
|
|
380
|
-
- **config**: Build, tooling, CI/CD changes
|
|
381
|
-
- **docs**: Documentation only
|
|
382
|
-
- **test**: Test additions/modifications only
|
|
383
|
-
- **mixed**: Multiple categories
|
|
384
|
-
|
|
385
|
-
## Output Quality
|
|
386
|
-
|
|
387
|
-
- Be selective: flag 20-50% of files, not everything
|
|
388
|
-
- Order flagged files by importance
|
|
389
|
-
- Keep reasons concise but specific`;function HD(Z){let Y=[],X=Z.hunks.reduce((J,z)=>J+z.lines.filter((V)=>V.type==="add").length,0),Q=Z.hunks.reduce((J,z)=>J+z.lines.filter((V)=>V.type==="delete").length,0),$=Z.status.toUpperCase();if(Z.status==="renamed"&&Z.oldPath)Y.push(`=== ${Z.oldPath} → ${Z.path} (${$}) [+${X}/-${Q}] ===`);else Y.push(`=== ${Z.path} (${$}) [+${X}/-${Q}] ===`);if(Z.isBinary)return Y.push("[binary file]"),Y.join(`
|
|
390
|
-
`);let W=0;for(let J of Z.hunks){if(W>=Xq)break;Y.push(J.header);for(let z of J.lines){if(W>=Xq){Y.push(`... (${X+Q-W} more changed lines)`);break}if(z.type==="add"||z.type==="delete"){let V=z.type==="add"?"+":"-";Y.push(`${V}${z.content}`),W++}}}return Y.join(`
|
|
391
|
-
`)}function Qq(Z,Y,X,Q){let $=Y.filter((z)=>z.tier<=2),W=[];W.push("## Diff Overview"),W.push(`Total files changed: ${Z.files.length}`),W.push(`Files for overview: ${$.length}`);let J=Y.filter((z)=>z.tier===3).length;if(J>0)W.push(`(${J} files excluded: lock files, generated code, binaries)`);if(W.push(""),Q)W.push(Q),W.push("");W.push("## Files Changed (with stats)");for(let z of $){let V=z.file,q=V.hunks.reduce((H,G)=>H+G.lines.filter((K)=>K.type==="add").length,0),U=V.hunks.reduce((H,G)=>H+G.lines.filter((K)=>K.type==="delete").length,0);W.push(`- ${V.path} (${V.status}) [+${q}/-${U}]`)}W.push(""),W.push("## Diff Preview (first ~20 changed lines per file)"),W.push("");for(let z of $)W.push(HD(z.file)),W.push("");if(X)W.push("## Author's Stated Intent"),W.push(""),W.push(X),W.push("");return W.push("---"),W.push(`Analyze this diff OVERVIEW and identify which files need detailed review.
|
|
392
|
-
|
|
393
|
-
REQUIRED OUTPUT:
|
|
394
|
-
- summary: string - 1-2 sentence summary of what this diff does
|
|
395
|
-
- purpose: string - why this change is being made
|
|
396
|
-
- scope: "feature" | "bugfix" | "refactor" | "config" | "docs" | "test" | "mixed"
|
|
397
|
-
- affectedAreas: string[] - high-level areas touched
|
|
398
|
-
- flaggedFiles: array of { path: string, reason: string } - files needing detailed review
|
|
399
|
-
- initialRisks: array of any immediately obvious risks (can be empty)
|
|
400
|
-
|
|
401
|
-
Be SELECTIVE with flaggedFiles - flag 20-50% of files, not everything.`),W.join(`
|
|
402
|
-
`)}async function $q(Z,Y,X,Q){let $=Qq(Z,Y,X,Q),W=await k1({adapter:C1("claude-sonnet-4-5"),systemPrompts:[UD],messages:[{role:"user",content:$}],outputSchema:s1(qD),temperature:0.3,stream:!1,maxTokens:4096});return{summary:W.summary,flaggedFiles:W.flaggedFiles.map((J)=>J.path),initialRisks:W.initialRisks.map((J)=>({severity:J.severity,category:J.category,description:J.description,evidence:J.evidence,file:J.file})),overviewIntent:{summary:W.summary,purpose:W.purpose,scope:W.scope,affectedAreas:W.affectedAreas}}}var GD=`You are an experienced code reviewer doing a DETAILED analysis of specific files that were flagged for careful review.
|
|
403
|
-
|
|
404
|
-
This is a DEEP-DIVE pass. You've already done a quick overview and now need to:
|
|
405
|
-
1. Thoroughly analyze the flagged files
|
|
406
|
-
2. Identify all risks in these files
|
|
407
|
-
3. Provide detailed, specific findings
|
|
408
|
-
|
|
409
|
-
## Key Principles
|
|
410
|
-
|
|
411
|
-
- Every risk MUST cite specific evidence from the diff
|
|
412
|
-
- Don't repeat findings already noted in the overview - focus on NEW details
|
|
413
|
-
- Be thorough - these files were flagged for a reason
|
|
414
|
-
|
|
415
|
-
## Risk Categories
|
|
416
|
-
|
|
417
|
-
- security: Auth, secrets, injection, validation
|
|
418
|
-
- breaking-change: API changes, removed exports
|
|
419
|
-
- performance: N+1, unbounded operations
|
|
420
|
-
- error-handling: Missing catches, unhandled cases
|
|
421
|
-
- backwards-compatibility: Migrations, protocol changes
|
|
422
|
-
- data-integrity: Race conditions, partial updates
|
|
423
|
-
- test-coverage: Removed tests, untested risky paths
|
|
424
|
-
|
|
425
|
-
## Severity Calibration
|
|
426
|
-
|
|
427
|
-
- **critical**: Must fix before merge (security vulns, data loss)
|
|
428
|
-
- **high**: Likely production issues if not addressed
|
|
429
|
-
- **medium**: Should review carefully
|
|
430
|
-
- **low**: Worth noting but unlikely to cause problems`;function Wq(Z,Y,X,Q,$,W){let J=Y.filter((H)=>H.tier<=2),z=new Set(X),V=J.filter((H)=>z.has(H.file.path)),q=J.filter((H)=>!z.has(H.file.path)),U=[];if(U.push("## Context from Overview Pass"),U.push(""),U.push(`Overall change: ${Q}`),U.push(`Files flagged for detailed review: ${V.length}`),U.push(`Files not flagged (already reviewed): ${q.length}`),U.push(""),W)U.push(W),U.push("");if(q.length>0){U.push("## Files NOT Flagged (for reference only)");for(let H of q)U.push(`- ${H.file.path} (${H.file.status})`);U.push("")}U.push("## Flagged Files (FULL DIFF - analyze in detail)"),U.push("");for(let H of V)U.push(X9(H.file)),U.push("");if($)U.push("## Author's Stated Intent"),U.push(""),U.push($),U.push("");return U.push("---"),U.push(`Analyze these FLAGGED files in detail for risks.
|
|
431
|
-
|
|
432
|
-
REQUIRED OUTPUT:
|
|
433
|
-
- overallRisk: "low" | "medium" | "high" | "critical" - highest severity found
|
|
434
|
-
- summary: string - actionable summary of findings
|
|
435
|
-
- risks: array of detailed risk objects (can be empty)
|
|
436
|
-
- confidence: "high" | "medium" | "low"
|
|
437
|
-
|
|
438
|
-
Each risk MUST have:
|
|
439
|
-
- severity, category, description, evidence
|
|
440
|
-
- Be SPECIFIC - cite actual code and line numbers`),U.join(`
|
|
441
|
-
`)}async function Jq(Z,Y,X,Q,$,W){if(X.length===0)return{overallRisk:"low",summary:"No files required detailed review - change appears safe.",risks:[],confidence:"high"};let J=Wq(Z,Y,X,Q,$,W);return await k1({adapter:C1("claude-sonnet-4-5"),systemPrompts:[GD],messages:[{role:"user",content:J}],outputSchema:s1(b8),temperature:0.4,stream:!1,maxTokens:8192})}function zq(Z,Y){let X={summary:Z.overviewIntent.summary||Z.summary,purpose:Z.overviewIntent.purpose||Z.summary,scope:Z.overviewIntent.scope||"mixed",affectedAreas:Z.overviewIntent.affectedAreas||[]};if(Z.flaggedFiles.length>0)X.suggestedReviewOrder=Z.flaggedFiles;let Q=[...Z.initialRisks,...Y.risks],$=new Set,W=Q.filter((H)=>{let G=`${H.category}:${H.description.slice(0,50)}`;if($.has(G))return!1;return $.add(G),!0}),J={critical:0,high:1,medium:2,low:3};W.sort((H,G)=>J[H.severity]-J[G.severity]);let z=W[0],V=z?z.severity:"low",q;if(W.length===0)q="No significant risks identified in detailed review.";else{let H=W.filter((K)=>K.severity==="critical").length,G=W.filter((K)=>K.severity==="high").length;if(H>0)q=`${H} critical risk(s) found. ${Y.summary}`;else if(G>0)q=`${G} high-severity risk(s) found. ${Y.summary}`;else q=Y.summary}let U={overallRisk:V,summary:q,risks:W,confidence:Y.confidence};return{intent:X,risks:U}}async function i7(Z,Y,X,Q){let $=Y.filter((q)=>q.tier<=2),W=await $q(Z,Y,X,Q),J=await Jq(Z,Y,W.flaggedFiles,W.summary,X,Q),{intent:z,risks:V}=zq(W,J);return{intent:z,risks:V,metadata:{strategy:"two-pass",overviewFileCount:$.length,flaggedFileCount:W.flaggedFiles.length,deepDiveFileCount:W.flaggedFiles.length}}}var KD=K1({flows:K1({name:"string",description:"string",files:"string[]",priority:"number"}).array()}),BD=8,LD=`You are an expert code reviewer analyzing a large diff to identify logical "flows" or concerns.
|
|
442
|
-
|
|
443
|
-
Your task is to GROUP the changed files into logical flows. A flow is a cohesive unit of related changes that serve a common purpose.
|
|
444
|
-
|
|
445
|
-
## Guidelines
|
|
446
|
-
|
|
447
|
-
1. **Identify 3-8 flows** - Too few loses granularity, too many fragments the review
|
|
448
|
-
2. **Each file belongs to ONE flow** - No overlap. Assign to the PRIMARY concern.
|
|
449
|
-
3. **Name flows clearly** - Use names like "Authentication", "Data Layer", "API Routes", "UI Components", "Configuration", "Testing"
|
|
450
|
-
4. **Set priority based on risk/importance**:
|
|
451
|
-
- Priority 1: Security, auth, data mutations
|
|
452
|
-
- Priority 2: Core business logic, API changes
|
|
453
|
-
- Priority 3: Supporting code, utilities
|
|
454
|
-
- Priority 4: Tests, config, docs
|
|
455
|
-
|
|
456
|
-
## Common Flow Patterns
|
|
457
|
-
|
|
458
|
-
- **Authentication/Security**: Login, auth middleware, tokens, permissions
|
|
459
|
-
- **Data Layer**: Database, models, migrations, queries
|
|
460
|
-
- **API Layer**: Routes, controllers, handlers, middleware
|
|
461
|
-
- **UI Components**: React components, Vue components, templates
|
|
462
|
-
- **State Management**: Redux, MobX, stores, actions
|
|
463
|
-
- **Configuration**: Build config, env, CI/CD
|
|
464
|
-
- **Testing**: Test files, fixtures, mocks
|
|
465
|
-
- **Utilities**: Helpers, shared functions, types
|
|
466
|
-
|
|
467
|
-
## Edge Cases
|
|
468
|
-
|
|
469
|
-
- **Cross-cutting files** (e.g., types used everywhere): Assign to the flow they MOST support
|
|
470
|
-
- **Mixed-purpose files**: Assign to the HIGHER priority flow
|
|
471
|
-
- **Very small groups** (1-2 files): Consider merging with related flow or marking as uncategorized
|
|
472
|
-
|
|
473
|
-
## Output Quality
|
|
474
|
-
|
|
475
|
-
- Order flows by priority (1 first)
|
|
476
|
-
- Descriptions should be 1-2 sentences
|
|
477
|
-
- Don't create a flow for just 1 file unless it's critical`;function MD(Z,Y){let X=[],Q=0;for(let $ of Z.hunks){if(Q>=Y)break;for(let W of $.lines){if(Q>=Y)break;if(W.type==="add"||W.type==="delete"){let J=W.type==="add"?"+":"-";X.push(`${J}${W.content}`),Q++}}}return X}function Vq(Z,Y){let X=Y.filter((J)=>J.tier<=2),Q=[];Q.push("## Diff Overview"),Q.push(`Total files to group: ${X.length}`);let $=X.filter((J)=>J.tier===1).length,W=X.filter((J)=>J.tier===2).length;Q.push(`- Tier 1 (high priority): ${$} files (source code, tests, critical config)`),Q.push(`- Tier 2 (lower priority): ${W} files (docs, other config, types)`),Q.push(""),Q.push("## Files to Group"),Q.push("");for(let J of X){let z=J.file,V=z.hunks.reduce((G,K)=>G+K.lines.filter((M)=>M.type==="add").length,0),q=z.hunks.reduce((G,K)=>G+K.lines.filter((M)=>M.type==="delete").length,0),U=z.status.toUpperCase();if(Q.push(`### ${z.path} (${U}) [+${V}/-${q}] [Tier ${J.tier}]`),z.isBinary){Q.push("[binary file]"),Q.push("");continue}let H=MD(z,BD);if(H.length>0){if(Q.push("```"),Q.push(...H),V+q>H.length)Q.push(`... (${V+q-H.length} more lines)`);Q.push("```")}Q.push("")}return Q.push("---"),Q.push(`Group these ${X.length} files into logical flows.
|
|
478
|
-
|
|
479
|
-
REQUIREMENTS:
|
|
480
|
-
1. Create 3-8 flows (no more, no fewer unless diff is very small)
|
|
481
|
-
2. Every file must be assigned to exactly ONE flow
|
|
482
|
-
3. Set priority: 1 = most important to review, higher = less critical
|
|
483
|
-
4. If a file doesn't fit any flow well, you can leave it out (it will be uncategorized)
|
|
484
|
-
|
|
485
|
-
OUTPUT FORMAT:
|
|
486
|
-
{
|
|
487
|
-
"flows": [
|
|
488
|
-
{
|
|
489
|
-
"name": "Flow Name",
|
|
490
|
-
"description": "What this flow accomplishes",
|
|
491
|
-
"files": ["path/to/file1.ts", "path/to/file2.ts"],
|
|
492
|
-
"priority": 1
|
|
493
|
-
}
|
|
494
|
-
]
|
|
495
|
-
}`),Q.join(`
|
|
496
|
-
`)}async function o7(Z,Y){let X=Y.filter((q)=>q.tier<=2),Q=new Set(X.map((q)=>q.file.path)),$=Vq(Z,Y),W=await k1({adapter:C1("claude-sonnet-4-5"),systemPrompts:[LD],messages:[{role:"user",content:$}],outputSchema:s1(KD),temperature:0.3,stream:!1,maxTokens:4096}),J=new Set,z=[];for(let q of W.flows){let U=q.files.filter((H)=>{if(!Q.has(H))return!1;if(J.has(H))return!1;return!0});for(let H of U)J.add(H);if(U.length>0)z.push({name:q.name,description:q.description,files:U,priority:Math.max(1,Math.min(10,Math.round(q.priority)))})}z.sort((q,U)=>q.priority-U.priority);let V=X.filter((q)=>!J.has(q.file.path)).map((q)=>q.file.path);return{flows:z,uncategorized:V}}function n7(Z,Y){let X=new Set(Z.files);return Y.filter((Q)=>X.has(Q.file.path))}var FD=K1({summary:"string",purpose:"string",scope:"'feature' | 'bugfix' | 'refactor' | 'config' | 'docs' | 'test' | 'mixed'",affectedAreas:"string[]","suggestedReviewOrder?":"string[]",overallRisk:"'low' | 'medium' | 'high' | 'critical'",riskSummary:"string",crossFlowConcerns:"string[]",confidence:"'high' | 'medium' | 'low'"}),qq=3;function Uq(Z,Y){let X=new Set(Y.files);return{files:Z.files.filter((Q)=>X.has(Q.path))}}function Hq(Z,Y){return n7(Y,Z)}function ND(Z,Y){return`## Flow Context
|
|
497
|
-
|
|
498
|
-
This analysis is for the "${Z.name}" flow (${Z.files.length} files, priority ${Z.priority}/${Y}).
|
|
499
|
-
|
|
500
|
-
**Flow description:** ${Z.description}
|
|
501
|
-
|
|
502
|
-
Focus your analysis on this specific concern. Other flows in this diff will be analyzed separately.
|
|
503
|
-
|
|
504
|
-
`}async function Gq(Z,Y,X,Q,$,W){let J=Uq(Y,Z),z=Hq(X,Z),V=ND(Z,Q),q=W?`${V}${W}`:V,[U,H]=await Promise.all([H2(J,z,$,q),G2(J,z,$,q)]);return{flow:Z,intent:U,risks:H}}async function Kq(Z,Y,X,Q,$,W){let J=[],z=Z.length;for(let V=0;V<Z.length;V+=qq){let q=Z.slice(V,V+qq),U=await Promise.all(q.map(async(H,G)=>{let K=V+G;if(W)W(K,H.name,z);return Gq(H,Y,X,z,Q,$)}));J.push(...U)}return J}var wD=`You are an expert code reviewer synthesizing analysis from multiple code flows.
|
|
505
|
-
|
|
506
|
-
You've received individual analyses for different logical flows (groups of related files) in a large diff. Your task is to:
|
|
507
|
-
|
|
508
|
-
1. **Synthesize intent** - Combine the individual flow intents into a coherent overall understanding
|
|
509
|
-
2. **Merge risks** - Identify the most important risks across all flows, note cross-flow concerns
|
|
510
|
-
3. **Identify patterns** - Look for patterns that span multiple flows (e.g., consistent error handling, shared security concerns)
|
|
511
|
-
|
|
512
|
-
## Key Principles
|
|
513
|
-
|
|
514
|
-
- Be CONCISE - this is a summary, not a repetition of all findings
|
|
515
|
-
- Focus on the BIG PICTURE - what is this change as a whole trying to accomplish?
|
|
516
|
-
- Highlight CROSS-FLOW concerns - risks that span multiple flows are often the most important
|
|
517
|
-
- Don't just concatenate - SYNTHESIZE into a coherent narrative
|
|
518
|
-
|
|
519
|
-
## Severity Calibration
|
|
520
|
-
|
|
521
|
-
When determining overall risk:
|
|
522
|
-
- Use the HIGHEST severity from any flow as the baseline
|
|
523
|
-
- Elevate if multiple flows have high-severity risks (compounding concern)
|
|
524
|
-
- Cross-flow risks (issues that span boundaries) may warrant higher severity`;function Bq(Z,Y){let X=[];X.push("## Flow Analysis Summary"),X.push(""),X.push(`Total flows analyzed: ${Z.length}`),X.push(`Total files: ${Z.reduce((Q,$)=>Q+$.flow.files.length,0)}`),X.push("");for(let Q of Z){if(X.push(`### Flow: ${Q.flow.name} (Priority ${Q.flow.priority})`),X.push(`**Files:** ${Q.flow.files.length}`),X.push(`**Description:** ${Q.flow.description}`),X.push(""),X.push("**Intent:**"),X.push(`- Summary: ${Q.intent.summary}`),X.push(`- Purpose: ${Q.intent.purpose}`),X.push(`- Scope: ${Q.intent.scope}`),X.push(`- Affected Areas: ${Q.intent.affectedAreas.join(", ")}`),X.push(""),X.push("**Risks:**"),X.push(`- Overall: ${Q.risks.overallRisk}`),X.push(`- Summary: ${Q.risks.summary}`),Q.risks.risks.length>0){X.push(`- Individual risks (${Q.risks.risks.length}):`);for(let $ of Q.risks.risks.slice(0,5))X.push(` - [${$.severity}] ${$.category}: ${$.description}`);if(Q.risks.risks.length>5)X.push(` - ... and ${Q.risks.risks.length-5} more`)}else X.push("- No significant risks identified");X.push("")}if(Y)X.push("## Author's Stated Intent"),X.push(""),X.push(Y),X.push(""),X.push("Consider how well the combined flows achieve this intent."),X.push("");return X.push("---"),X.push(`Synthesize these flow analyses into a unified assessment.
|
|
525
|
-
|
|
526
|
-
REQUIRED OUTPUT:
|
|
527
|
-
- summary: string - 1-2 sentence summary of what the ENTIRE diff accomplishes
|
|
528
|
-
- purpose: string - the overall WHY behind all these changes
|
|
529
|
-
- scope: "feature" | "bugfix" | "refactor" | "config" | "docs" | "test" | "mixed"
|
|
530
|
-
- affectedAreas: string[] - all areas affected (deduplicated and consolidated)
|
|
531
|
-
- suggestedReviewOrder: string[] - suggested order to review files (optional)
|
|
532
|
-
- overallRisk: "low" | "medium" | "high" | "critical" - highest severity across all flows
|
|
533
|
-
- riskSummary: string - actionable summary of risks across all flows
|
|
534
|
-
- crossFlowConcerns: string[] - risks or issues that span multiple flows
|
|
535
|
-
- confidence: "high" | "medium" | "low"
|
|
536
|
-
|
|
537
|
-
Focus on synthesis - what does this change mean AS A WHOLE?`),X.join(`
|
|
538
|
-
`)}async function Lq(Z,Y){let X=Bq(Z,Y),Q=await k1({adapter:C1("claude-sonnet-4-5"),systemPrompts:[wD],messages:[{role:"user",content:X}],outputSchema:s1(FD),temperature:0.3,stream:!1,maxTokens:4096}),$=Z.flatMap((U)=>U.risks.risks),W=new Set,J=$.filter((U)=>{let H=`${U.category}:${U.description.slice(0,50)}`;if(W.has(H))return!1;return W.add(H),!0}),z={critical:0,high:1,medium:2,low:3};J.sort((U,H)=>z[U.severity]-z[H.severity]);let V={summary:Q.summary,purpose:Q.purpose,scope:Q.scope,affectedAreas:Q.affectedAreas,suggestedReviewOrder:Q.suggestedReviewOrder},q={overallRisk:Q.overallRisk,summary:Q.riskSummary,risks:J,confidence:Q.confidence};return{overallIntent:V,overallRisks:q}}async function g8(Z,Y,X,Q,$){if($)$("detecting","Identifying logical flows in diff...");let W=await o7(Z,Y);if(W.flows.length===0){let U={name:"All Changes",description:"All changes in this diff",files:Y.filter((H)=>H.tier<=2).map((H)=>H.file.path),priority:1};W.flows=[U],W.uncategorized=[]}let J=$?(U,H,G)=>{$("analyzing",`Flow ${U+1}/${G}: ${H}`)}:void 0,z=await Kq(W.flows,Z,Y,X,Q,J);if($)$("synthesizing","Combining flow analyses...");let V=await Lq(z,X),q={strategy:"flow-based",totalFileCount:Y.filter((U)=>U.tier<=2).length,flowCount:W.flows.length,uncategorizedCount:W.uncategorized.length,flowFileCounts:W.flows.map((U)=>({name:U.name,fileCount:U.files.length}))};return{flows:z,synthesis:V,metadata:q}}async function DD(Z){if(Z.intent)return Z.intent.trim();if(Z.intentFile){if(!await pV(Z.intentFile))throw new Error(`Intent file not found: ${Z.intentFile}`);return(await mV(Z.intentFile)).trim()||void 0}if(Z.target.startsWith("commit:")){let Y=Z.target.slice(7);if(Y){let X=await q$(Y,Z.cwd);return`Commit ${Y.length>7?Y.slice(0,7):Y}: ${X}`}}if(!process.stdin.isTTY)return(await dV()).trim()||void 0;return}function Mq(Z,Y,X,Q,$){if(X.json)console.log(JSON.stringify({intent:Z,risks:Y,statedIntent:Q,alignment:$},null,2));else if(X.verbose)console.log(s6(Z,Y,Q,$));else console.log(r6(Z,Y,Q,$))}var c6=new R9;c6.name("diffloupe").description("AI-powered diff analysis tool").version("0.1.0");var AD={summary:"Adds rate limiting middleware to protect API endpoints from abuse",purpose:"Prevents API abuse and ensures fair usage across tenants by limiting requests per IP",scope:"feature",affectedAreas:["API middleware","authentication","rate limiting"],suggestedReviewOrder:["src/middleware/rateLimit.ts","src/config/limits.ts","src/routes/api.ts","src/tests/rateLimit.test.ts"]},ED={overallRisk:"medium",summary:"One medium-severity issue with error handling; otherwise looks good",confidence:"high",risks:[{severity:"medium",category:"error-handling",description:"Rate limit errors return 500 instead of 429 status code",evidence:"Line 45: catch block uses generic error response without setting status",file:"src/middleware/rateLimit.ts",mitigation:"Return 429 Too Many Requests with Retry-After header"},{severity:"low",category:"performance",description:"Redis lookup on every request may add latency",evidence:"No caching of rate limit state between checks",file:"src/middleware/rateLimit.ts"},{severity:"low",category:"test-coverage",description:"Missing test for concurrent request handling",evidence:"Tests only cover sequential requests, not race conditions",file:"src/tests/rateLimit.test.ts"}]};c6.command("analyze").description("Analyze code changes with AI assistance").argument("[target]","What to diff: staged, unstaged, HEAD, branch:name, commit:hash, or range:a..b","staged").option("-v, --verbose","Show detailed output",!1).option("--json","Output results as JSON",!1).option("-f, --force","Skip cache and force fresh analysis",!1).option("-i, --intent <intent>","Describe the intent of the changes").option("--intent-file <path>","Read intent from a file").option("-C, --cwd <path>","Run as if git was started in <path>").option("--demo","Show demo output with mock data",!1).option("--strategy <strategy>","Force decomposition strategy (direct, two-pass, flow-based, hierarchical)").action(async(Z,Y)=>{let X={target:Z,...Y},Q;try{Q=await DD(X)}catch($){let W=$ instanceof Error?$.message:String($);console.error(p.default.red(`Error: ${W}`)),process.exit(1)}if(X.demo){Mq(AD,ED,X,Q);return}if(!f8())console.error(p.default.red(`Error: ANTHROPIC_API_KEY environment variable is not set.
|
|
539
|
-
`)+p.default.dim(`Set it in your .env file or export it in your shell:
|
|
540
|
-
`)+p.default.dim(` export ANTHROPIC_API_KEY=sk-ant-...
|
|
541
|
-
|
|
542
|
-
`)+p.default.dim("Or use --demo to see example output without an API key.")),process.exit(1);try{console.log(p.default.dim(`Fetching ${X.target} diff...`));let $=await P4(X.target,X.cwd);if(!$.hasChanges){if(console.log(p.default.yellow(`
|
|
543
|
-
No changes found.`)),X.target==="staged")console.log(p.default.dim(`Stage some changes with 'git add' first, or try:
|
|
544
|
-
`)+p.default.dim(` diffloupe analyze HEAD # all uncommitted changes
|
|
545
|
-
`)+p.default.dim(" diffloupe analyze branch:main # compare to main"));return}console.log(p.default.dim("Parsing diff..."));let W=v9($.diff),J=f9(W),z=c7(W,J),V=X.strategy?{strategy:X.strategy,reason:"Forced via --strategy flag",metrics:z}:l7(z);console.log(p.default.dim(`Found ${W.files.length} file(s), ~${z.estimatedTokens} tokens`)),console.log(p.default.dim(`Strategy: ${V.strategy} (${V.reason})`));let q=await K$(W,X.cwd),U,H;if(V.strategy==="two-pass"){console.log(p.default.dim("Pass 1: Quick overview..."));let K=await i7(W,J,Q,q);console.log(p.default.dim(`Pass 2: Deep-dive on ${K.metadata.flaggedFileCount} flagged file(s)...`)),U=K.intent,H=K.risks}else if(V.strategy==="flow-based"){let K=await g8(W,J,Q,q,(M,E)=>{if(M==="detecting")console.log(p.default.dim("Detecting logical flows..."));else if(M==="analyzing"&&E)console.log(p.default.dim(E));else if(M==="synthesizing")console.log(p.default.dim("Synthesizing results..."))});console.log(p.default.dim(`Analyzed ${K.metadata.flowCount} flows across ${K.metadata.totalFileCount} files`)),U=K.synthesis.overallIntent,H=K.synthesis.overallRisks}else if(V.strategy==="hierarchical"){console.log(p.default.yellow("Note: hierarchical strategy not yet implemented, using flow-based analysis"));let K=await g8(W,J,Q,q,(M,E)=>{if(M==="detecting")console.log(p.default.dim("Detecting logical flows..."));else if(M==="analyzing"&&E)console.log(p.default.dim(E));else if(M==="synthesizing")console.log(p.default.dim("Synthesizing results..."))});U=K.synthesis.overallIntent,H=K.synthesis.overallRisks}else console.log(p.default.dim("Analyzing with AI...")),[U,H]=await Promise.all([H2(W,J,Q,q),G2(W,J,Q,q)]);let G;if(Q)console.log(p.default.dim("Analyzing intent alignment...")),G=await v8(Q,U,W,J,q);console.log(""),Mq(U,H,X,Q,G)}catch($){if($ instanceof O1){if(console.error(p.default.red(`Git error: ${$.message}`)),$.code==="NOT_A_REPO")console.error(p.default.dim("Run this command from within a git repository."));process.exit(1)}if($ instanceof K2)console.error(p.default.red(`Error: Invalid or missing API key.
|
|
546
|
-
`)+p.default.dim("Check that your ANTHROPIC_API_KEY is correct.")),process.exit(1);if($ instanceof B2)console.error(p.default.red(`Error: AI analysis failed.
|
|
547
|
-
`)+p.default.dim($.message)),process.exit(1);let W=$ instanceof Error?$.message:String($);console.error(p.default.red(`Error: ${W}`)),process.exit(1)}});c6.addCommand(rV());c6.addCommand(Yq());function Fq(){c6.parse()}Fq();
|
|
500
|
+
`)+"}");class Fo{config;resolvedConfig;name;get[it](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(e,t){if(this.config=Ki(O.config,t),this.resolvedConfig=Ki(O.resolvedConfig,t),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(Ic).length}`,this.name in Ic)E(`A Scope already named ${this.name} already exists`);Ic[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(pm(o));this.aliases[o]=s}else{if(o in this.aliases)E(pm(r));this.aliases[o]=s,this.exportedNames.push(o)}if(!z(s,"module")&&!z(s,"generic")&&!Mn(s)){let a=this.preparseOwnDefinitionFormat(s,{alias:o});this.resolutions[o]=z(a,"root")?this.bindReference(a):this.createParseContext(a).id}}hm??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[hm.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=O.intrinsic?ne(O.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 Ln(e,r?new Co(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(zi(e),e,t);preparseNode(e,t,n){let r=typeof e==="string"?e:zi(t,e);if($e(t)&&t.kind===r)return t;if(r==="alias"&&!n?.prereduced){let{reference:a}=es.implementation.normalize(t,this);if(a.startsWith("$")){let l=this.resolveRoot(a.slice(1));t=l,r=l.kind}}else if(r==="union"&&dt(t,"object")){let a=E$(t);if(a?.length===1)t=a[0],r=zi(t)}if($e(t)&&t.kind===r)return t;let o=Kr[r].normalize?.(t,this)??t;if($e(o))return o.kind===r?o:A$(r,o.kind);return{...n,$:this,kind:r,def:o,prefix:n.alias??r}}bindReference(e){let t;if($e(e))t=e.$===this?e:new e.constructor(e.attachments,this);else t=e.$===this?e:new Ln(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(Mc(e))}maybeResolveRoot(e){let t=this.maybeResolve(e);if(z(t,"generic"))return;return t}maybeResolveSubalias(e){return Oc(this.aliases,e)??Oc(this.ambient,e)}get ambient(){return O.ambient}maybeResolve(e){let t=this.resolutions[e];if(t){if(typeof t!=="string")return this.bindReference(t);let r=st[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 he(`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",st[s.id]=s,st[r.id]=s,this.resolutions[e]=s}return he(`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(vm(e));return this.resolutions[e]=this.bindReference(n.root)}return this.resolutions[e]=this.parse(n,{alias:e})}createParseContext(e){let t=e.id??pc(e.prefix);return st[t]=Object.assign(e,{[it]:"context",$:this,id:t,phase:"unresolved"})}traversal(e){return new Kt(e,this.resolvedConfig)}import(...e){return new Gr(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")?Cc(r,this):mm(this.maybeResolve(n))}for(let n of this.lazyResolutions)n.resolution;if(this._exportedResolutions=bm(this,this._exports),this._json=wm(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let n=ym(this.references);this.precompilation=n.write(gm,4),_m(this.references,n)}this.resolved=!0}let t=e.length?e:this.exportedNames;return new Gr(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($e(r))return this.bindReference(r);let s=this.createParseContext(r),o=hc(s),a=this.bindReference(o);return st[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);st[r.id]=r;let s=this.bindReference(this.parseOwnDefinitionFormat(e,r));if(s.isCyclic)s=Fh(s,r.id);return st[r.id]=s,s}finalize(e){if(mm(e),!e.precompilation&&!this.resolvedConfig.jitless)C$(e.references);return e}}class Pc extends Fo{parseOwnDefinitionFormat(e,t){return hc(t)}preparseOwnDefinitionFormat(e,t){return this.preparseNode(zi(e),e,t)}preparseOwnAliasEntry(e,t){return[e,t]}normalizeRootScopeValue(e){return e}}var mm=(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},wm=(e)=>ne(e,(t,n)=>[t,z(n,"root")||z(n,"generic")?n.json:z(n,"module")?wm(n):he(`Unexpected resolution ${re(n)}`)]),Oc=(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(I$(r));let o=t.slice(n+1),a=s[o];if(a===void 0)return Oc(s,o);if(z(a,"root")||z(a,"generic"))return a;if(z(a,"module"))return a.root??E(vm(t));he(`Unexpected resolution for alias '${t}': ${re(a)}`)},Lo=(e,t)=>new Pc(e,t),rs=new Pc({});var bm=(e,t)=>{let n={};for(let r in t){let s=t[r];if(z(s,"module")){let o=bm(e,s),a=ne(o,(l,c)=>[`${r}.${l}`,c]);Object.assign(n,a)}else if(z(s,"root")||z(s,"generic"))n[r]=s;else he(`Unexpected scope resolution ${re(s)}`)}return n},Mc=(e)=>`'${e}' is unresolvable`,I$=(e)=>`'${e}' must reference a module to be accessed using dot syntax`,vm=(e)=>`Reference to submodule '${e}' must specify an alias`;rs.export();var{schema:me,node:zr,defineSchema:mL,generic:Dt}=rs;var Tc="^(?:0|[1-9]\\d*)$",O$=new RegExp(Tc),yL=Me(O$);var xm=Lo({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();O.intrinsic={...xm};var km=Lo({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:Tc}},{prereducedAliases:!0}).export();Object.assign(O.intrinsic,km);var P$=Lo({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),Q={...xm,...km,...P$,emptyStructure:zr("structure",{},{prereduced:!0})};O.intrinsic={...Q};var jo=(e,t)=>new RegExp(e,t);Object.assign(jo,{as:jo});var $m=(e)=>typeof e==="string"&&e[0]==="d"&&(e[1]==="'"||e[1]==='"')&&e[e.length-1]===e[1],Rm=(e)=>e.toString()!=="Invalid Date",Sm=(e)=>e.slice(2,-1),Nc=(e)=>`'${e}' could not be parsed by the Date constructor`,Em=(e,t)=>M$(e,t),M$=(e,t)=>{let n=new Date(e);if(Rm(n))return n;let r=Qp(e);if(r!==void 0){let s=new Date(r);if(Rm(s))return s}return t?E(t===!0?Nc(e):t):void 0};var T$=me({proto:"Array",sequence:"string",required:{key:"groups",value:["object",{unit:void 0}]}}),Uo=(e,t)=>{let n=e.scanner.shiftUntilEscapable(D$[Im[t]]);if(e.scanner.lookahead==="")return e.error(L$(n,t));if(e.scanner.shift(),t in Cm){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:T$})}else if(qe(t,Dc))e.root=e.ctx.$.node("unit",{unit:n});else{let r=Em(n,Nc(n));e.root=e.ctx.$.node("unit",{meta:n,unit:r})}},Dc={"'":1,'"':1},Am={"/":1,"'":1,'"':1},N$={"d'":"'",'d"':'"',"'":"'",'"':'"'},Cm={"/":"/","x/":"/"},Im={...N$,...Cm},D$={"'":(e)=>e.lookahead==="'",'"':(e)=>e.lookahead==='"',"/":(e)=>e.lookahead==="/"},F$={'"':"double-quote","'":"single-quote","/":"forward slash"},L$=(e,t)=>`${t}${e} requires a closing ${F$[Im[t]]}`;var Om=(e)=>`Private type references should not include '#'. Use '${e}' instead.`,Bo="Optional definitions like 'string?' are only valid as properties in an object or tuple",qo="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var an={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...Tn};var Pm=(e,t)=>e===">"?t[0]==="="?t[1]==="=":t.trimStart()===""||qe(t.trimStart()[0],an):e==="="?t[0]!=="=":e===","||e==="?";var Mm=(e,t,n)=>Tm(e,t,n,[]),Tm=(e,t,n,r)=>{let s=n.parseUntilFinalizer();if(r.push(s.root),s.finalizer===">"){if(r.length!==t.params.length)return n.error(Fc(e,t.names,r.map((o)=>o.expression)));return r}if(s.finalizer===",")return Tm(e,t,n,r);return s.error(ko(">"))},Fc=(e,t,n)=>`${e}<${t.join(", ")}> requires exactly ${t.length} args (got ${n.length}${n.length===0?"":`: ${n.join(", ")}`})`;var Ho=(e)=>{let t=e.scanner.shiftUntilLookahead(an);if(t==="keyof")e.addPrefix("keyof");else e.root=U$(e,t)},j$=(e,t,n)=>{if(n.scanner.shiftUntilNonWhitespace(),n.scanner.shift()!=="<")return n.error(Fc(e,t.names,[]));let s=Mm(e,t,n);return t(...s)},U$=(e,t)=>B$(e,t)??q$(e,t)??e.error(t===""?e.scanner.lookahead==="#"?Om(e.shiftedBy(1).scanner.shiftUntilLookahead(an)):Lc(e):Mc(t)),B$=(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 j$(t,n,e);return E(`Unexpected resolution ${re(n)}`)},q$=(e,t)=>{let n=eh(t);if(n!==void 0)return e.ctx.$.node("unit",{unit:n});let r=nh(t);if(r!==void 0)return e.ctx.$.node("unit",{unit:r})},Lc=(e)=>{let t=e.previousOperator();return t?jc(t,e.scanner.unscanned):H$(e.scanner.unscanned)},jc=(e,t="")=>`Token '${e}' requires a right operand${t?` before '${t}'`:""}`,H$=(e)=>`Expected an expression${e?` before '${e}'`:""}`;var Uc=(e)=>e.scanner.lookahead===""?e.error(Lc(e)):e.scanner.lookahead==="("?e.shiftedBy(1).reduceGroupOpen():e.scanner.lookaheadIsIn(Am)?Uo(e,e.scanner.shift()):e.scanner.lookaheadIsIn(Tn)?Uc(e.shiftedBy(1)):e.scanner.lookahead==="d"?e.scanner.nextLookahead in Dc?Uo(e,`${e.scanner.shift()}${e.scanner.shift()}`):Ho(e):e.scanner.lookahead==="x"?e.scanner.nextLookahead==="/"?e.shiftedBy(2)&&Uo(e,"x/"):Ho(e):Ho(e);var Nm={">":!0,">=":!0},Dm={"<":!0,"<=":!0};var Jr={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},Fm=(e,t)=>`Left bounds are only valid when paired with right bounds (try ...${t}${e})`,Ko=(e)=>`Left-bounded expressions must specify their limits using < or <= (was ${e})`,Lm=(e,t,n,r)=>`An expression may have at most one left bound (parsed ${e}${Jr[t]}, ${n}${Jr[r]})`;var Um=(e,t)=>{let n=K$(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 V$(e,n)},Bm={"<":1,">":1,"=":1},K$=(e,t)=>e.scanner.lookaheadIs("=")?`${t}${e.scanner.shift()}`:t;var jm=(e,t,n,r)=>{if(n.extends(O.intrinsic.number)){if(typeof t!=="number")return E(Bc(e,t,r));return e==="=="?["min","max"]:e[0]===">"?["min"]:["max"]}if(n.extends(O.intrinsic.lengthBoundable)){if(typeof t!=="number")return E(Bc(e,t,r));return e==="=="?["exactLength"]:e[0]===">"?["minLength"]:["maxLength"]}if(n.extends(O.intrinsic.Date))return e==="=="?["after","before"]:e[0]===">"?["after"]:["before"];return E(Rh(n.expression))},W$=(e)=>({rule:$m(e.limit)?Sm(e.limit):e.limit,exclusive:e.comparator.length===1}),V$=(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(Bc(t,o,"right"));let a=s.unit,l=t.length===1,c=jm(t,typeof a==="number"?a:o,n,"right");for(let d of c)e.constrainRoot(d,t==="=="?{rule:a}:{rule:a,exclusive:l});if(!e.branches.leftBound)return;if(!qe(t,Dm))return e.error(Ko(t));let u=jm(e.branches.leftBound.comparator,e.branches.leftBound.limit,n,"left");e.constrainRoot(u[0],W$(e.branches.leftBound)),e.branches.leftBound=null},Bc=(e,t,n)=>`Comparator ${n==="left"?Jr[e]:e} must be ${n==="left"?"preceded":"followed"} by a corresponding literal (was ${t})`;var qm=(e)=>{e.scanner.shiftUntilNonWhitespace();let t=e.scanner.shiftUntilLookahead(an);e.root=e.root.brand(t)};var Km=(e)=>{e.scanner.shiftUntilNonWhitespace();let t=e.scanner.shiftUntilLookahead(an),n=th(t,{errorOnFail:Hm(t)});if(n===0)e.error(Hm(0));e.root=e.root.constrain("divisor",n)},Hm=(e)=>`% operator must be followed by a non-zero integer literal (was ${e})`;var qc=(e)=>{let t=e.scanner.shift();return t===""?e.finalize(""):t==="["?e.scanner.shift()==="]"?e.setRoot(e.root.array()):e.error(G$):t==="|"?e.scanner.lookahead===">"?e.shiftedBy(1).pushRootToBranch("|>"):e.pushRootToBranch(t):t==="&"?e.pushRootToBranch(t):t===")"?e.finalizeGroup():Pm(t,e.scanner.unscanned)?e.finalize(t):qe(t,Bm)?Um(e,t):t==="%"?Km(e):t==="#"?qm(e):(t in Tn)?qc(e):e.error(Wo(t))},Wo=(e,t="")=>`'${e}' is not allowed here${t&&` (should be ${t})`}`,G$="Missing expected ']'";var Wm=(e)=>{let t=e.unsetRoot();e.parseOperand();let n=e.unsetRoot();if(!n.hasKind("unit"))return e.error(z$(n.expression));let r=n.unit instanceof Date?()=>new Date(n.unit):n.unit;return[t,"=",r]},z$=(e)=>`Default value '${e}' must be a literal value`;var Hc=(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 Xr(new qi(e),t),s=J$(r);if(r.finalizer===">")E(Wo(">"));return s},J$=(e)=>{e.parseOperand();let t=is(e).root;if(!t)return he(`Root was unexpectedly unset after parsing string '${e.scanner.scanned}'`);if(e.finalizer==="=")t=Wm(e);else if(e.finalizer==="?")t=[t,"?"];if(e.scanner.shiftUntilNonWhitespace(),e.scanner.lookahead)E(Wo(e.scanner.lookahead));return t},is=(e)=>{while(e.finalizer===void 0)X$(e);return e},X$=(e)=>e.hasRoot()?e.parseOperator():e.parseOperand();class Xr{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(ko(")"));this.finalizeBranches(),this.finalizer=e}reduceLeftBound(e,t){let n=Jr[t];if(!qe(n,Nm))return this.error(Ko(t));if(this.branches.leftBound)return this.error(Lm(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(oh(")",this.scanner.unscanned));this.branches=e}addPrefix(e){this.branches.prefixes.push(e)}applyPrefixes(){while(this.branches.prefixes.length){let e=this.branches.prefixes.pop();this.root=e==="keyof"?this.root.keyof():he(`Unexpected prefix '${e}'`)}}pushRootToBranch(e){this.assertRangeUnset(),this.applyPrefixes();let t=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(t)??t,e==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,e==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return is(new Xr(this.scanner,this.ctx))}parseOperator(){return qc(this)}parseOperand(){return Uc(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(Fm(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 Y$="An empty string is not a valid generic parameter name",Vo=(e,t,n)=>{e.shiftUntilNonWhitespace();let r=e.shiftUntilLookahead(an);if(r===""){if(e.lookahead===""&&t.length)return t;return E(Y$)}return e.shiftUntilNonWhitespace(),Z$(e,r,t,n)},Vm="extends ",Z$=(e,t,n,r)=>{if(e.shiftUntilNonWhitespace(),e.unscanned.startsWith(Vm))e.jumpForward(Vm.length);else{if(e.lookahead===",")e.shift();return n.push(t),Vo(e,n,r)}let s=is(new Xr(e,r));return n.push([t,s.root]),Vo(e,n,r)};class Kc extends ht{constructor(e){let t={$:e,raw:e.fn};super((...n)=>{let r=n.indexOf(":"),s=r===-1?n.length-1:r-1,o=n.slice(0,s+1),a=e.parse(o).assertHasKind("intersection"),l=e.intrinsic.unknown;if(r!==-1){if(r!==n.length-2)return E(Q$);l=e.parse(n[r+1])}return(c)=>new Gm(c,a,l)},{attach:t})}}class Gm extends ht{raw;params;returns;expression;constructor(e,t,n){let r=`typed ${e.name}`,s={[r]:(...a)=>{let l=t.assert(a),c=e(...l);return n.assert(c)}}[r];super(s);this.raw=e,this.params=t,this.returns=n;let o=t.expression;if(o[0]==="["&&o[o.length-1]==="]")o=o.slice(1,-1);else if(o.endsWith("[]"))o=`...${o}`;this.expression=`(${o}) => ${n?.expression??"unknown"}`}}var Q$=`":" must be followed by exactly one return type e.g:
|
|
501
|
+
fn("string", ":", "number")(s => s.length)`;class Wc extends ht{$;constructor(e){super((...t)=>new ss(e)(...t),{bind:e});this.$=e}in(e){return new ss(this.$,e===void 0?void 0:this.$.parse(e))}at(e,t){return new ss(this.$).at(e,t)}case(e,t){return new ss(this.$).case(e,t)}}class ss extends ht{$;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(tS);if(this.branches.length)E(eS);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 ${Be(r)})`);this.caseEntry(n,r)}return this}default(e){if(typeof e==="function")this.case(Q.unknown,e);let t={branches:this.branches,ordered:!0};if(e==="never"||e==="assert")t.meta={onFail:zm};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:zm},"self");return this.$.finalize(r)}}var zm=(e)=>e.throw(),eS="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",tS="At most one key matcher may be specified per expression";var Go=(e,t)=>{if(ve(e)){if(e[1]==="=")return[t.$.parseOwnDefinitionFormat(e[0],t),"=",e[2]];if(e[1]==="?")return[t.$.parseOwnDefinitionFormat(e[0],t),"?"]}return zo(e,t)},Jm="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",Xm="Only required keys may specify default values, e.g. { value: 'number = 0' }";var Ym=(e,t)=>{let n,r={},s=rr(e);for(let[a,l]of s){let c=iS(a);if(c.kind==="spread"){if(!sn(r))return E(rS);let h=t.$.parseOwnDefinitionFormat(l,t);if(h.equals(Q.object))continue;if(!h.hasKind("intersection")||!h.basis?.equals(Q.object))return E(sS(h.expression));n=h.structure;continue}if(c.kind==="undeclared"){if(l!=="reject"&&l!=="delete"&&l!=="ignore")E(nS(l));r.undeclared=l;continue}let u=Go(l,t),d=c;if(c.kind==="required"){if(!ve(u))Vc(r,"required",{key:c.normalized,value:u},t);else Vc(r,"optional",u[1]==="="?{key:c.normalized,value:u[0],default:u[2]}:{key:c.normalized,value:u[0]},t);continue}if(ve(u)){if(u[1]==="?")E(Jm);if(u[1]==="=")E(Xm)}if(c.kind==="optional"){Vc(r,"optional",{key:c.normalized,value:u},t);continue}let f=t.$.parseOwnDefinitionFormat(d.normalized,t),p=Do(f,u,t.$);if(p.index)r.index=de(r.index,p.index);if(p.required)r.required=de(r.required,p.required)}let o=t.$.node("structure",r);return t.$.parseSchema({domain:"object",structure:n?.merge(o)??o})},Vc=(e,t,n,r)=>{e[t]=de(e[t],r.$.node(t,n))},nS=(e)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${re(e)})`,rS="Spread operator may only be used as the first key in an object",iS=(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},sS=(e)=>`Spread operand must resolve to an object literal type (was ${e})`;var Qm=(e,t)=>mS(e)?rg[e[0]](e,t):pS(e)?ng[e[1]](e,t):null,oS=(e,t)=>t.$.parseOwnDefinitionFormat(e[1],t).keyof(),Gc=(e,t)=>{if(e[2]===void 0)return E(jc(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]==="&"?_t(n,r,t.$):Gi(n,r,t.$);if(s instanceof j)return s.throw();return s},aS=(e,t)=>t.$.parseOwnDefinitionFormat(e[0],t).array(),lS=(e,t)=>{if(typeof e[2]!=="function")return E(eg("=>",e[2]));return t.$.parseOwnDefinitionFormat(e[0],t).pipe(e[2])},eg=(e,t)=>`${e===":"?"Narrow":"Morph"} expression requires a function following '${e}' (was ${typeof t})`,cS=(e,t)=>{if(typeof e[2]!=="function")return E(eg(":",e[2]));return t.$.parseOwnDefinitionFormat(e[0],t).constrain("predicate",e[2])},uS=(e,t)=>t.$.parseOwnDefinitionFormat(e[0],t).configure(e[2],e[3]),tg=(e)=>e,dS=tg({"[]":aS,"?":()=>E(Bo)}),fS=tg({"|":Gc,"&":Gc,":":cS,"=>":lS,"|>":Gc,"@":uS,"=":()=>E(qo)}),ng={...dS,...fS},pS=(e)=>ng[e[1]]!==void 0,hS=(e)=>e,rg=hS({keyof:oS,instanceof:(e,t)=>{if(typeof e[1]!=="function")return E(Zm(Ni(e[1])));let n=e.slice(1).map((r)=>typeof r==="function"?t.$.node("proto",{proto:r}):E(Zm(Ni(r))));return n.length===1?n[0]:t.$.node("union",{branches:n})},"===":(e,t)=>t.$.units(e.slice(1))}),mS=(e)=>rg[e[0]]!==void 0,Zm=(e)=>`Expected a constructor following 'instanceof' operator (was ${e})`;var og=(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=Go(e[r],t),[a,l,c]=!ve(o)?[o]:o;if(r++,s){if(!a.extends(O.intrinsic.Array))return E(yS(a.expression));n=n.flatMap((u)=>a.distribute((d)=>_S($o(u),d)))}else n=n.map((u)=>{if(l==="?")return ag(u,a);if(l==="=")return gS(u,a,c);return zc(u,a)})}return t.$.parseSchema(n.map((s)=>sn(s)?{proto:Array,exactLength:0}:{proto:Array,sequence:s}))},zc=(e,t)=>{if(e.defaultables||e.optionals)return E(e.variadic?Sc:wS);if(e.variadic)e.postfix=de(e.postfix,t);else e.prefix=de(e.prefix,t);return e},ag=(e,t)=>{if(e.variadic)return E(lg);return e.optionals=de(e.optionals,t),e},gS=(e,t,n)=>{if(e.variadic)return E(lg);if(e.optionals)return E(bS);return e.defaultables=de(e.defaultables,[[t,n]]),e},ig=(e,t)=>{if(e.postfix)E(sg);if(e.variadic){if(!e.variadic.equals(t))E(sg)}else e.variadic=t.internal;return e},_S=(e,t)=>{let n=t.select({method:"find",kind:"sequence"});if(!n)return ig(e,O.intrinsic.unknown);if(n.prefix)for(let r of n.prefix)zc(e,r);if(n.optionals)for(let r of n.optionals)ag(e,r);if(n.variadic)ig(e,n.variadic);if(n.postfix)for(let r of n.postfix)zc(e,r);return e},yS=(e)=>`Spread element must be an array (was ${e})`,sg="A tuple may have at most one variadic element",wS="A required element may not follow an optional element",lg="An optional element may not follow a variadic element";var bS="A defaultable element may not follow an optional element without a default";var vS={},zo=(e,t)=>{if(typeof e==="string"){if(t.args&&Object.keys(t.args).some((r)=>e.includes(r)))return Hc(e,t);let n=vS[t.$.name]??={};return n[e]??=Hc(e,t)}return dt(e,"object")?xS(e,t):E(Jc(Be(e)))},xS=(e,t)=>{let n=Ti(e);switch(n){case void 0:if(z(e,"root"))return e;if("~standard"in e)return kS(e,t);return Ym(e,t);case"Array":return RS(e,t);case"RegExp":return t.$.node("intersection",{domain:"string",pattern:e},{prereduced:!0});case"Function":{let r=Mn(e)?e():e;if(z(r,"root"))return r;return E(Jc("Function"))}default:return E(Jc(n??re(e)))}},kS=(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:Gp(o),relativePath:a.map((l)=>typeof l==="object"?l.key:l)});else r.error({message:o});else r.error({message:o})}),RS=(e,t)=>Qm(e,t)??og(e,t),Jc=(e)=>`Type definitions must be strings or objects (was ${e})`;class Xc extends ht{constructor(e){let t=Object.assign({errors:mt,hkt:Qe,$: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 Ln(s,n[1],e,e,null)}return e.parse(n)},{attach:t})}}var Yr=O;class Jo extends Fo{get ambientAttachments(){if(!Yr.typeAttachments)return;return this.cacheGetter("ambientAttachments",ne(Yr.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 vh(o,t,this)}]}parseGenericParams(e,t){return Vo(new qi(e),[],this.createParseContext({...t,def:e,prefix:"generic"}))}normalizeRootScopeValue(e){if(Mn(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=zo(e,t);if(ve(r)){if(r[1]==="=")return E(qo);if(r[1]==="?")return E(Bo)}return r}unit=(e)=>this.units([e]);valueOf=(e)=>this.units(Lp(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 Kc(this);match=new Wc(this);declare=()=>({type:this.type});define(e){return e}type=new Xc(this);static scope=(e,t={})=>new Jo(e,t);static module=(e,t={})=>this.scope(e,t).export()}var Yc=Object.assign(Jo.scope,{define:(e)=>e}),ce=Jo;class cg extends Qe{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var $S=Dt(["base",Q.object],["props",Q.object])((e)=>e.base.merge(e.props),cg),ug=ce.module({Key:Q.key,Merge:$S});class dg extends Qe{}var SS=Dt("element")((e)=>{let t=e.element.exclude(Q.Array),n=t.array();return t.rawOr(n).pipe(Pn).distribute((r)=>r.assertHasKind("morph").declareOut(n),me)},dg),fg=ce.module({root:Q.Array,readonly:"root",index:Q.nonNegativeIntegerString,liftFrom:SS},{name:"Array"});var Zc=me(["string",or.FileConstructor]),ES=Zc.rawOr(Zc.array()),pg=me({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:ES}}),hg=ce.module({root:["instanceof",FormData],value:Zc,parsed:pg,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 or.FileConstructor)t[n]=[s,r];else s.push(r)}else t[n]=r;return t},declaredOut:pg})},{name:"FormData"});var mg=ce.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 AS={Boolean:1,Number:1,String:1},gg=ce.module({...ne({...jl,...Bl},(e,t)=>(e in AS)?[]:[e,["instanceof",t]]),Array:fg,TypedArray:mg,FormData:hg});var CS=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"}),IS=me({domain:"number",divisor:1}),Xo=ce.module({root:Q.number,integer:IS,epoch:CS,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 Ae=(e,t,n)=>{let r={domain:"string",pattern:{rule:e.source,flags:e.flags,meta:t}};if(n)r.meta={format:n};return zr("intersection",r)},_g=Ae(Fi,"a well-formed integer string"),Cg=ce.module({root:_g,parse:me({in:_g,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:Q.integer})},{name:"string.integer"}),OS=Ae(/^[\dA-Fa-f]+$/,"hex characters only"),PS=ce.module({root:Ae(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:Ae(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),yg=Ae(/^[A-Z].*$/,"capitalized"),MS=ce.module({root:me({in:"string",morphs:(e)=>e.charAt(0).toUpperCase()+e.slice(1),declaredOut:yg}),preformatted:yg},{name:"string.capitalize"}),TS=(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)},NS=/^(?: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}))$/,DS=me({domain:"string",pattern:{meta:"a credit card number",rule:NS.source},predicate:{meta:"a credit card number",predicate:TS}});var FS=/^([+-]?\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 LS=(e)=>!Number.isNaN(new Date(e).valueOf()),wg=me({domain:"string",predicate:{meta:"a parsable date",predicate:LS}}).assertHasKind("intersection"),bg=Cg.root.internal.narrow((e,t)=>{let n=Number.parseInt(e),r=Xo.epoch(n);if(r instanceof mt)return t.errors.merge(r),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),jS=ce.module({root:bg,parse:me({in:bg,morphs:(e)=>new Date(e),declaredOut:Q.Date})},{name:"string.date.epoch"}),vg=Ae(FS,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),US=ce.module({root:vg,parse:me({in:vg,morphs:(e)=>new Date(e),declaredOut:Q.Date})},{name:"string.date.iso"}),BS=ce.module({root:wg,parse:me({declaredIn:wg,in:"string",morphs:(e,t)=>{let n=new Date(e);if(Number.isNaN(n.valueOf()))return t.error("a parsable date");return n},declaredOut:Q.Date}),iso:US,epoch:jS},{name:"string.date"}),qS=Ae(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),xg="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",jn=`(${xg}[.]){3}${xg}`,HS=new RegExp(`^${jn}$`),Le="(?:[0-9a-fA-F]{1,4})",KS=new RegExp(`^((?:${Le}:){7}(?:${Le}|:)|(?:${Le}:){6}(?:${jn}|:${Le}|:)|(?:${Le}:){5}(?::${jn}|(:${Le}){1,2}|:)|(?:${Le}:){4}(?:(:${Le}){0,1}:${jn}|(:${Le}){1,3}|:)|(?:${Le}:){3}(?:(:${Le}){0,2}:${jn}|(:${Le}){1,4}|:)|(?:${Le}:){2}(?:(:${Le}){0,3}:${jn}|(:${Le}){1,5}|:)|(?:${Le}:){1}(?:(:${Le}){0,4}:${jn}|(:${Le}){1,6}|:)|(?::((?::${Le}){0,5}:${jn}|(?::${Le}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),WS=ce.module({root:["v4 | v6","@","an IP address"],v4:Ae(HS,"an IPv4 address","ipv4"),v6:Ae(KS,"an IPv6 address","ipv6")},{name:"string.ip"}),Zr="a JSON string",Ig=(e)=>{if(!(e instanceof SyntaxError))throw e;return`must be ${Zr} (${e})`},VS=me({meta:Zr,domain:"string",predicate:{meta:Zr,predicate:(e,t)=>{try{return JSON.parse(e),!0}catch(n){return t.reject({code:"predicate",expected:Zr,problem:Ig(n)})}}}}),GS=(e,t)=>{if(e.length===0)return t.error({code:"predicate",expected:Zr,actual:"empty"});try{return JSON.parse(e)}catch(n){return t.error({code:"predicate",expected:Zr,problem:Ig(n)})}},zS=ce.module({root:VS,parse:me({meta:"safe JSON string parser",in:"string",morphs:GS,declaredOut:Q.jsonObject})},{name:"string.json"}),kg=Ae(/^[a-z]*$/,"only lowercase letters"),JS=ce.module({root:me({in:"string",morphs:(e)=>e.toLowerCase(),declaredOut:kg}),preformatted:kg},{name:"string.lower"}),Og=["NFC","NFD","NFKC","NFKD"],os=ne(Og,(e,t)=>[t,me({domain:"string",predicate:(n)=>n.normalize(t)===n,meta:`${t}-normalized unicode`})]),Yo=ne(Og,(e,t)=>[t,me({in:"string",morphs:(n)=>n.normalize(t),declaredOut:os[t]})]),XS=ce.module({root:Yo.NFC,preformatted:os.NFC},{name:"string.normalize.NFC"}),YS=ce.module({root:Yo.NFD,preformatted:os.NFD},{name:"string.normalize.NFD"}),ZS=ce.module({root:Yo.NFKC,preformatted:os.NFKC},{name:"string.normalize.NFKC"}),QS=ce.module({root:Yo.NFKD,preformatted:os.NFKD},{name:"string.normalize.NFKD"}),eE=ce.module({root:"NFC",NFC:XS,NFD:YS,NFKC:ZS,NFKD:QS},{name:"string.normalize"}),Rg=Ae(vo,"a well-formed numeric string"),tE=ce.module({root:Rg,parse:me({in:Rg,morphs:(e)=>Number.parseFloat(e),declaredOut:Q.number})},{name:"string.numeric"}),$g="a regex pattern",nE=me({domain:"string",predicate:{meta:$g,predicate:(e,t)=>{try{return new RegExp(e),!0}catch(n){return t.reject({code:"predicate",expected:$g,problem:String(n)})}}},meta:{format:"regex"}}),rE=/^(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-]+)*))?$/,iE=Ae(rE,"a semantic version (see https://semver.org/)"),Sg=Ae(/^\S.*\S$|^\S?$/,"trimmed"),sE=ce.module({root:me({in:"string",morphs:(e)=>e.trim(),declaredOut:Sg}),preformatted:Sg},{name:"string.trim"}),Eg=Ae(/^[A-Z]*$/,"only uppercase letters"),oE=ce.module({root:me({in:"string",morphs:(e)=>e.toUpperCase(),declaredOut:Eg}),preformatted:Eg},{name:"string.upper"}),aE=(e)=>URL.canParse(e),Ag=me({domain:"string",predicate:{meta:"a URL string",predicate:aE},meta:{format:"uri"}}),lE=ce.module({root:Ag,parse:me({declaredIn:Ag,in:"string",morphs:(e,t)=>{try{return new URL(e)}catch{return t.error("a URL string")}},declaredOut:me(URL)})},{name:"string.url"}),cE=ce.module({root:["versioned | nil | max","@",{description:"a UUID",format:"uuid"}],"#nil":"'00000000-0000-0000-0000-000000000000'","#max":"'ffffffff-ffff-ffff-ffff-ffffffffffff'","#versioned":/[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}/i,v1:Ae(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:Ae(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:Ae(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:Ae(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:Ae(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:Ae(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:Ae(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:Ae(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),Pg=ce.module({root:Q.string,alpha:Ae(/^[A-Za-z]*$/,"only letters"),alphanumeric:Ae(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:OS,base64:PS,capitalize:MS,creditCard:DS,date:BS,digits:Ae(/^\d*$/,"only digits 0-9"),email:qS,integer:Cg,ip:WS,json:zS,lower:JS,normalize:eE,numeric:tE,regex:nE,semver:iE,trim:sE,upper:oE,url:lE,uuid:cE},{name:"string"});var Mg=ce.module({bigint:Q.bigint,boolean:Q.boolean,false:Q.false,never:Q.never,null:Q.null,number:Q.number,object:Q.object,string:Q.string,symbol:Q.symbol,true:Q.true,unknown:Q.unknown,undefined:Q.undefined}),Tg=ce.module({root:Q.unknown,any:Q.unknown},{name:"unknown"}),uE=ce.module({root:Q.jsonObject,stringify:zr("morph",{in:Q.jsonObject,morphs:(e)=>JSON.stringify(e),declaredOut:Q.string})},{name:"object.json"}),Ng=ce.module({root:Q.object,json:uE},{name:"object"});class Dg extends Qe{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var dE=Dt(["K",Q.key],"V")((e)=>({domain:"object",index:{signature:e.K,value:e.V}}),Dg);class Fg extends Qe{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var fE=Dt(["T",Q.object],["K",Q.key])((e)=>e.T.pick(e.K),Fg);class Lg extends Qe{description='omit a set of properties from an object like `Omit(User, "age")`'}var pE=Dt(["T",Q.object],["K",Q.key])((e)=>e.T.omit(e.K),Lg);class jg extends Qe{description="make all named properties of an object optional like `Partial(User)`"}var hE=Dt(["T",Q.object])((e)=>e.T.partial(),jg);class Ug extends Qe{description="make all named properties of an object required like `Required(User)`"}var mE=Dt(["T",Q.object])((e)=>e.T.required(),Ug);class Bg extends Qe{description='exclude branches of a union like `Exclude("boolean", "true")`'}var gE=Dt("T","U")((e)=>e.T.exclude(e.U),Bg);class qg extends Qe{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var _E=Dt("T","U")((e)=>e.T.extract(e.U),qg),Hg=ce.module({Exclude:gE,Extract:_E,Omit:pE,Partial:hE,Pick:fE,Record:dE,Required:mE});var vn=Yc({...Mg,...Hg,...gg,...ug,string:Pg,number:Xo,object:Ng,unknown:Tg},{prereducedAliases:!0,name:"ark"}),He=vn.export();Object.assign(Yr.ambient,He);Yr.typeAttachments={string:He.string.root,number:He.number.root,bigint:He.bigint,boolean:He.boolean,symbol:He.symbol,undefined:He.undefined,null:He.null,object:He.object.root,unknown:He.unknown.root,false:He.false,true:He.true,never:He.never,arrayIndex:He.Array.index,Key:He.Key,Record:He.Record,Array:He.Array.root,Date:He.Date};var ae=Object.assign(vn.type,Yr.typeAttachments),{match:yE,fn:wE,generic:bE,schema:XB,define:vE,declare:xE}=vn;var Zo=ae("'running' | 'complete' | 'failed' | 'cancelled'"),Qo=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"}),Wg=ae("'additions' | 'deletions'"),kE=ae("'not-in-diff' | 'far-from-diff' | 'no-line' | 'deleted-file' | 'no-hunks'"),Vg=ae({file:"string",side:Wg,kind:"'line' | 'nearby' | 'file'",line:"number","endLine?":"number",cited:{line:"number","endLine?":"number"},"text?":"string","reason?":kE}),RE=ae("'added' | 'removed' | 'modified' | 'renamed' | 'copied'"),Gg=ae("'product' | 'deploy' | 'tooling'"),$E=ae({path:"string","previousPath?":"string",status:RE,additions:"number",deletions:"number",isBinary:"boolean","blob?":"string",groupId:"string",classification:"'code' | 'docs' | 'skip'","surface?":Gg}),SE=ae("'bug' | 'wrench' | 'path' | 'flask' | 'doc' | 'gear'"),Qc=ae({id:"string","parentId?":"string",title:"string","summary?":"string","icon?":SE,files:"string[]",findingIds:"string[]",stopIds:"string[]",critical:"boolean"}),EE=ae({id:"string",chapterId:"string",index:"number",title:"string","prose?":"string",importance:"'critical' | 'normal' | 'context'",locations:Vg.and({"label?":"string"}).array()}),AE=ae("'blocker' | 'should-fix' | 'nice-to-have' | 'question'"),Kg=ae({id:"string",file:"string",anchor:Vg,severity:AE,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?":Gg}),CE=ae({unit:"string",part:"number",parts:"number",status:"'ok' | 'failed'",costUsd:"number",wallMs:"number"}),ea=ae({root:"string","slug?":"string","remote?":"boolean"}),as=ae("'review' | 'diff'");function zg(e){return e.meta.kind??"review"}var Jg=ae({schemaVersion:"1",id:"string",status:Zo,createdAt:"string",repo:ea,target:Qo,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:$E.array(),groups:Qc.array(),stops:EE.array(),findings:Kg.array(),overCapFindings:Kg.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"}},"kind?":as,wallMs:"number",costUsd:"number",slices:CE.array(),rejectedCount:"number",coreSource:"string","mergeMode?":"'coordinator' | 'nothing-to-merge' | 'deterministic-fallback'","budgetStopped?":"boolean"},untrackedSkipped:"string[]","priorRunId?":"string","error?":"string"}),hq=ae({reviewedFiles:"string[]",findingStatus:ae.Record("string","'open' | 'accepted' | 'dismissed'"),comments:ae({id:"string",file:"string",side:Wg,line:"number","endLine?":"number",body:"string"}).array(),"submitted?":{at:"string","url?":"string"}}),mq=ae({id:"string",status:Zo,createdAt:"string",target:Qo,repo:ea,"kind?":as,findingCounts:{blocker:"number","should-fix":"number","nice-to-have":"number",question:"number"},costUsd:"number","invalid?":"string"});function Vt(){return Ge.join(process.env.XDG_DATA_HOME||Ge.join(IE.homedir(),".local","share"),"diffloupe")}function cs(){return Ge.join(Vt(),"runs")}function Qr(){return Ge.join(Vt(),"artifacts")}function tu(e){let[t="",n=""]=e.toLowerCase().split("/");return Ge.join(Vt(),"repos",t,`${n}.git`)}function yt(e){if(!e||e.includes("/")||e.includes("\\")||e.startsWith("."))throw Error(`invalid run id: ${e}`);return Ge.join(cs(),e)}var e_={reviewedFiles:[],findingStatus:{},comments:[]};async function t_(e){let t=yt(e);return await OE(Ge.join(t,"raw"),{recursive:!0}),await Qg(Ge.join(t,"state.json"),`${JSON.stringify(e_,null,2)}
|
|
502
|
+
`),t}async function ei(e){await Qg(Ge.join(yt(e.id),"run.json"),`${JSON.stringify(e,null,2)}
|
|
503
|
+
`)}class Un extends Error{id;summary;raw;constructor(e,t,n){super(`run ${e} has an invalid run.json: ${t}`);this.id=e;this.summary=t;this.raw=n;this.name="InvalidRunError"}}async function xn(e){let t=JSON.parse(await Zg(Ge.join(yt(e),"run.json"),"utf8")),n=Jg(t);if(n instanceof ae.errors)throw new Un(e,n.summary,t);return n}async function n_(e){try{return JSON.parse(await Zg(Ge.join(yt(e),"state.json"),"utf8"))}catch{return e_}}function PE(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 eu(e,t,n){let r=e(t);return r instanceof ae.errors?n:r}function r_(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:eu(Zo,t.status,"failed"),createdAt:typeof t.createdAt==="string"?t.createdAt:"",target:eu(Qo,t.target,{kind:"worktree"}),repo:eu(ea,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 Gt(){let e;try{e=await ls(cs())}catch{return[]}let t=[];for(let n of e)try{let r=await xn(n);t.push({id:r.id,status:r.status,createdAt:r.createdAt,target:r.target,repo:r.repo,findingCounts:PE(r),costUsd:r.meta?.costUsd??0,...r.meta?.kind?{kind:r.meta.kind}:{}})}catch(r){if(r instanceof Un)t.push(r_(r))}return t.sort((n,r)=>r.createdAt.localeCompare(n.createdAt))}function Yg(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 i_(e,t,n){let r=Yg(e,t);return(await Gt()).find((o)=>o.status==="complete"&&o.kind!=="diff"&&o.createdAt<n&&Yg(o.repo,o.target)===r)?.id}function us(){return Ge.join(Vt(),"scratch")}function ta(){let e=Ge.join(us(),"oc","shared");return[Ge.join(e,"data"),Ge.join(e,"state")]}function ME(){let e=Qr();return[...["logs","prompts","raw","reviews","runs"].map((t)=>Ge.join(e,t)),us(),...ta()]}async function TE(e,t){try{if((await te("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 ds(e){let t=[],n=yt(e),r;try{r=(await xn(e)).repo.root}catch(s){if(s instanceof Un)r=r_(s).repo.root||void 0}for(let s of ME()){let o;try{o=await ls(s)}catch{continue}for(let a of o)if(a.startsWith(`${e}-`)||a.startsWith(`${e}.`)){let l=Ge.join(s,a);await Xg(l,{recursive:!0,force:!0}),t.push(l)}}if(r){for(let s of[`refs/diffloupe/${e}`,`refs/diffloupe/${e}-base`])if(await TE(r,s))t.push(s)}try{await ls(n),await Xg(n,{recursive:!0,force:!0}),t.push(n)}catch{}return t}function s_(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 o_(){let e=[];try{e=await ls(cs())}catch{}let t=(await Gt()).filter((o)=>o.status==="running").map((o)=>o.id),n=(o,a)=>a.some((l)=>o.startsWith(`${l}-`)||o.startsWith(`${l}.`)),r=[],s=async(o,a)=>{let l;try{l=await ls(o)}catch{return}for(let c of l)if(!a(c))r.push(Ge.join(o,c))};await s(us(),(o)=>!o.endsWith(".json")||n(o,e));for(let o of ta())await s(o,(a)=>n(a,t));return r}import{readFile as GE}from"fs/promises";xt();import{copyFile as NE,mkdir as DE,rm as FE,stat as c_}from"fs/promises";import LE from"os";import ti from"path";import{randomBytes as jE}from"crypto";function nu(e,t){if(!t)return e;let n=e;for(let r=2;t(n);r++)n=`${e}-${r}`;return n}var UE=1048576;class xe extends Error{name="TargetError"}function ps(e){let t=(e??"worktree").trim();if(t===""||t==="worktree")return{kind:"worktree"};if(t==="staged")return{kind:"staged"};if(t==="HEAD")return{kind:"commit",rev:"HEAD"};let n=t.match(/^(?:#|pr:)(\d+)$/);if(n?.[1])return{kind:"pr",pr:Number(n[1])};let r=t.match(/^([\w.-]+\/[\w.-]+)#(\d+)$/);if(r?.[1]&&r[2])return{kind:"pr",pr:Number(r[2]),repo:r[1]};if(/github\.com\//.test(t)){let l=t.match(/^(?:https?:\/\/)?(?:www\.)?github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)(?:[/?#].*)?$/);if(!l?.[1]||!l[2]||!l[3])throw new xe(`not a GitHub pull request URL: ${t}`);return{kind:"pr",pr:Number(l[3]),repo:`${l[1]}/${l[2]}`}}let s=t.indexOf(":"),o=s>0?t.slice(0,s):"",a=s>0?t.slice(s+1):"";if(o==="branch"&&a)return{kind:"branch",branch:a};if(o==="commit"&&a)return{kind:"commit",rev:a};if(o==="range"){let l=a_(a);if(l)return l}if(!o&&!t.startsWith("-")&&!/\s/.test(t))if(t.includes("..")){let l=a_(t);if(l)return l}else return{kind:"commit",rev:t};throw new xe(`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 a_(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 ru(e,t,n,r=new Date){let s=(c)=>String(c).padStart(2,"0"),o=`${r.getFullYear()}${s(r.getMonth()+1)}${s(r.getDate())}${s(r.getHours())}${s(r.getMinutes())}${s(r.getSeconds())}`,a=t.kind==="pr"?`pr${t.pr}`:t.kind;return`${e.replace(/[^\w.-]+/g,"_")}-${a}-${n.slice(0,7)}-${o}`}async function u_(e,t,n={}){let r=ps(t),s=(y,P={})=>le("git",["-C",e,...y],P),o=async(y)=>{let P=await te("git",["-C",e,"rev-parse","--verify","--quiet",`${y}^{commit}`],{allowFail:!0});if(P.code!==0){let D=/^\d+$/.test(y)?` (for pull request ${y}, use #${y})`:"";throw new xe(`unknown revision "${y}": not a commit in ${e}${D}`)}return P.stdout.trim()},a=async(y,P)=>(await s(["merge-base",y,P])).trim();if((await te("git",["-C",e,"rev-parse","--show-toplevel"],{allowFail:!0})).code!==0)throw new xe(`${e} is not inside a git repository`+(r.kind==="pr"&&r.repo?". diffloupe diff can show this pull request without a clone.":""));let c=await fo(e),u,d,f,p=[],h=!1;switch(r.kind){case"pr":{if(r.repo&&!c.startsWith("local/")&&r.repo.toLowerCase()!==c.toLowerCase())throw new xe(`pull request is in ${r.repo} but ${e} is a clone of ${c}. Run from a clone of ${r.repo} or pass -C. diffloupe diff can show it without a clone.`);f=await m_(e,r.pr,r.repo??(c.startsWith("local/")?void 0:c)),d=f.headRefOid,await l_(e,d,[`refs/pull/${r.pr}/head`]),await l_(e,f.baseRefOid,[f.baseRefName]),u=await a(f.baseRefOid,d);break}case"branch":{d=await o(r.branch),u=await a(await KE(e),d);break}case"range":{let y=await o(r.from);d=await o(r.to),u=r.mergeBase?await a(y,d):y;break}case"commit":{d=await o(r.rev);let y=await te("git",["-C",e,"rev-parse","--verify","--quiet",`${d}^`],{allowFail:!0});if(y.code!==0)throw new xe(`${r.rev} is a root commit; use range: instead`);u=y.stdout.trim();break}case"staged":case"worktree":{let y=await o("HEAD"),P=r.kind==="staged"?await WE(e,y):await VE(e,y);d=P.commit,p=P.skipped,u=n.base?await a(await o(n.base),y):y,h=!0;break}}let x=c.split("/").pop()??ti.basename(e),R=nu(ru(x,r,d,n.now),n.isTaken);if(h)await s(["update-ref",`refs/diffloupe/${R}`,d]);let w=await iu(e,u,d),v={base:u,head:d,slug:c,...r.kind==="pr"?{pr:String(r.pr)}:{}};return{spec:r,target:v,tag:R,changes:w,skippedUntracked:p,...f?{pullRequest:f}:{}}}async function d_(e,t,n,r,s={}){let o=await Promise.all([n,r].map((f)=>na(e,f))),a=[n,r].filter((f,p)=>!o[p]);if(a.length)throw new xe(`commit ${a[0]} is no longer in ${e}`);let l=await fo(e),c=l.split("/").pop()??ti.basename(e),u=nu(ru(c,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:l,...t.kind==="pr"?{pr:String(t.pr)}:{}};return{spec:t,target:d,tag:u,changes:await iu(e,n,r),skippedUntracked:[]}}var BE=/^(?!\.{1,2}$)[\w.-]+$/;function qE(e){let t=e.split("/");return t.length===2&&t.every((n)=>BE.test(n))}async function f_(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 fo(e);return!r.startsWith("local/")&&r.toLowerCase()!==t.repo.toLowerCase()}async function p_(e,t,n=`https://github.com/${t}.git`){if(!qE(t))throw new xe(`not a GitHub repository: ${t}`);let r=(...o)=>le("git",["-C",e,...o]);if(await c_(ti.join(e,"HEAD")).catch(()=>null))return;await DE(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 h_(e,t,n={}){let r=await m_(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 HE(e,[a,s],[`refs/pull/${t.pr}/head`]);let l=t.repo.split("/").pop()??t.repo,c=nu(ru(l,t,s,n.now),n.isTaken);return await le("git",["-C",e,"update-ref",`refs/diffloupe/${c}`,s]),await le("git",["-C",e,"update-ref",`refs/diffloupe/${c}-base`,a]),{spec:t,target:{base:a,head:s,slug:t.repo,pr:String(t.pr)},tag:c,changes:await iu(e,a,s),skippedUntracked:[],pullRequest:r}}async function HE(e,t,n){let r=async()=>{let l=await Promise.all(t.map((c)=>na(e,c)));return t.filter((c,u)=>!l[u])},s=(l)=>te("git",["-C",e,"fetch","-q","--depth=1","--filter=blob:none","--no-tags","origin",...l],{allowFail:!0}),o=await r();if(o.length===0)return;let a=await s(o);o=await r();for(let l of n){if(o.length===0)return;await s([l]),o=await r()}if(o.length)throw new xe(`could not fetch ${o.map((l)=>l.slice(0,10)).join(", ")} from GitHub: ${a.stderr.trim()||"not found"}`)}async function m_(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 xe(`gh pr view ${t} failed: ${o.stderr.trim()||`exit ${o.code}`}`);return JSON.parse(o.stdout)}async function na(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 l_(e,t,n){if(await na(e,t))return;for(let r of n)if(await te("git",["-C",e,"fetch","-q","origin",r],{allowFail:!0}),await na(e,t))return;throw new xe(`commit ${t} is not in this clone and could not be fetched from origin`)}async function KE(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 xe("could not determine the default branch; use range:<base>..<branch> instead")}async function g_(e,t,n,r,s){let o=(await le("git",["-C",e,"rev-parse",`${n}^{tree}`])).trim();if(t===o)throw new xe("no changes to review");return(await le("git",["-C",e,"commit-tree",t,"-p",n,"-m",r],s?{env:s}:{})).trim()}async function WE(e,t){let n=(await le("git",["-C",e,"write-tree"])).trim();return{commit:await g_(e,n,t,"diffloupe: staged changes"),skipped:[]}}async function VE(e,t){let n=(await le("git",["-C",e,"rev-parse","--show-toplevel"])).trim(),r=ti.resolve(n,(await le("git",["-C",n,"rev-parse","--git-path","index"])).trim()),s=ti.join(LE.tmpdir(),`diffloupe-index-${process.pid}-${jE(4).toString("hex")}`);try{await NE(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),l=[];for(let d of a){let f=await c_(ti.join(n,d)).catch(()=>null);if(f&&f.isFile()&&f.size>UE)l.push(d)}let c=l.map((d)=>`:(exclude,literal)${d}`);await le("git",["-C",n,"add","-A","--",".",...c],{env:o});let u=(await le("git",["-C",n,"write-tree"],{env:o})).trim();return{commit:await g_(n,u,t,"diffloupe: working tree",o),skipped:l}}finally{await FE(s,{force:!0})}}async function iu(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(`
|
|
504
|
+
`)){if(!o.trim())continue;let[a,l]=o.split("\t");s.files++,s.insertions+=Number(a)||0,s.deletions+=Number(l)||0}return s}var zE=ae({"+":"reject","$schema?":"string","provider?":"string","models?":{"+":"reject","review?":"string","coordinator?":"string","walkthrough?":"string"},"effort?":"string","surfaces?":{"+":"reject","deploy?":"string[]","tooling?":"string[]"},"extraExcludes?":"string[]"});function JE(e,t){let n=zE(e);if(n instanceof ae.errors)throw new xe(`invalid settings in ${t}: ${n.summary}`);for(let r of[...n.surfaces?.deploy??[],...n.surfaces?.tooling??[]])try{new RegExp(r)}catch(s){throw new xe(`invalid surface pattern in ${t}: ${s instanceof Error?s.message:String(s)}`)}return n}async function ra(e){let t;try{t=await GE(e,"utf8")}catch(r){throw new xe(`cannot read settings file ${e}: ${r instanceof Error?r.message:String(r)}`)}let n;try{n=JSON.parse(t)}catch(r){throw new xe(`settings file ${e} is not valid JSON: ${r instanceof Error?r.message:String(r)}`)}return JE(n,e)}function __(e){let t={};if(e.surfaces)t.surfaces={deploy:e.surfaces.deploy??Yn.deploy,tooling:e.surfaces.tooling??Yn.tooling};if(e.extraExcludes)t.extraExcludes=e.extraExcludes;return t}var y_={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"]},w_=new Set(["amazon-bedrock","google-vertex","google-vertex-anthropic","ollama","lmstudio","vllm"]);function hs(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function b_(e,t){let n=t?.[e],r=hs(n)&&Array.isArray(n.env)?n.env.filter((s)=>typeof s==="string"):[];return[...new Set([...r,...y_[e]??[]])]}function XE(e,t){let n=t?.[e];if(!hs(n))return!1;for(let r of[n.settings,n.options])if(hs(r)&&typeof r.apiKey==="string"&&r.apiKey)return!0;return!1}function v_(e){for(let t of e.providers.keys()){if(w_.has(t))continue;if(b_(t,e.userProviders).some((n)=>e.env[n]))continue;if(e.apiKeys?.[t])continue;return!0}return!1}function YE(e,t,n){let r=t.map((o)=>qs[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 x_(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=b_(n,e.userProviders),a=o.find((f)=>e.env[f]);if(a){s("env",a);continue}let l=e.apiKeys?.[n];if(l){let f=o[0];if(f)t.childEnv[f]=l;else t.imports.push({id:`cred_diffloupe_${n.replace(/[^\w-]/g,"_")}`,integrationID:n,label:"API key",active:!0,value:{type:"key",key:l}});s("config",`apiKeys.${n}`);continue}let c=(e.saved??[]).filter((f)=>f.integrationID===n),u=c.filter((f)=>f.value?.type==="key"&&typeof f.value.key==="string");if(u.length){let f=u.find((p)=>p.active)??u[0];if(f)t.imports.push({...f,active:!0});s("opencode","opencode auth login");continue}let d=c.length>0;if(d)t.warnings.push(`OpenCode has a ${n} login that is not an API key; DiffLoupe does not copy those. Set ${o[0]??"an API key"} or add apiKeys.${n} to ~/.config/diffloupe/config.json.`);if(XE(n,e.userProviders)){s("providers",`providers.${n} in the OpenCode config`);continue}if(w_.has(n)){s("ambient","credentials from the machine");continue}if(s("none",""),y_[n]||d)t.errors.push(YE(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 k_(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)=>hs(r)&&typeof r.id==="string"&&typeof r.integrationID==="string"&&hs(r.value))}catch{return}}function R_(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}async function $_(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=R_(n)&&Array.isArray(n.data)?n.data:void 0;if(!r)return;return r.filter((s)=>R_(s)&&typeof s.id==="string"&&typeof s.providerID==="string")}catch{return}}function S_(e,t,n=Xt){let r={errors:[],zeroCost:[]};for(let s of n){let o=e[s],a=t.filter((f)=>f.providerID===o.provider);if(!a.length)continue;let l=a.find((f)=>f.id===o.id||f.modelID===o.id),c=(f)=>r.errors.push(`Model \`${o.model}\` is not available in OpenCode: ${f}. Set \`${qs[s]}\` in ~/.config/diffloupe/config.json or pass --model ${s}=<provider/model>.`);if(!l){c(`provider \`${o.provider}\` has no model \`${o.id}\``);continue}let u=l.variants?.map((f)=>f.id)??[];if(o.variant&&!u.includes(o.variant)){c(u.length?`it has no variant \`${o.variant}\` (variants: ${u.join(", ")})`:`it has no variants, so \`#${o.variant}\` and effort cannot apply`);continue}let d=l.cost??[];if(d.length&&d.every((f)=>!f.input&&!f.output))r.zeroCost.push(s)}return r}import{readFileSync as ZE}from"fs";import A_ from"os";import su from"path";function QE(e=process.env,t=A_.homedir()){let n=e.XDG_CONFIG_HOME?e.XDG_CONFIG_HOME:su.join(t,".config"),r=su.join(n,"opencode");return["opencode.jsonc","opencode.json"].map((s)=>su.join(r,s))}function e0(e){let t=Bun.JSONC;if(t)try{return t.parse(e)}catch{return}return ul(e)}function E_(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function t0(e,t){if(!E_(e))return{};let n=t?{path:t}:{};if(typeof e.model==="string"&&e.model.trim())n.model=e.model.trim();if(E_(e.providers))n.providers=e.providers;return n}function C_(e=process.env,t=A_.homedir()){for(let n of QE(e,t)){let r;try{r=ZE(n,"utf8")}catch{continue}return t0(e0(r),n)}return{}}async function ia(e){let t=e.env??process.env,n=e.openCodeUser??C_(t),r=e.settings??{},s={env:t,...e.cli?{cli:e.cli}:{},settings:r,config:e.userConfig,...n.model?{openCodeModel:n.model}:{}},o=$d(s),a={providers:Sd(o,e.stages),env:t,...e.userConfig.apiKeys?{apiKeys:e.userConfig.apiKeys}:{},...n.providers?{userProviders:n.providers}:{}},l=v_(a)?await(e.exportCredentials??(()=>k_(t)))():void 0,c=x_({...a,...l?{saved:l}:{}}),u=await(e.readCatalog??(()=>$_()))();return{provider:Ya(s),models:o,openCodeUser:n,credentials:c,...u?{catalog:S_(o,u,e.stages)}:{}}}function I_(e){return{provider:e.provider,model:e.models.review.model,modelMerge:e.models.coordinator.model,modelWalk:e.models.walkthrough.model,effort:"",effortAux:"",providers:e.openCodeUser.providers??{},childEnv:e.credentials.childEnv,authImport:e.credentials.imports.length?JSON.stringify(e.credentials.imports):""}}function O_(e,t=Xt){let n={};for(let r of t)n[r]={model:e.models[r].model,source:e.models[r].source};return n}var yu={git:"https://git-scm.com/downloads",opencode:"https://opencode.ai/docs/ (npm i -g opencode-ai)",tilth:"https://github.com/jahala/tilth (cargo install tilth)",gh:"https://cli.github.com/ (then `gh auth login`)"},ay={review:"model",coordinator:"modelMerge",walkthrough:"modelWalk"};function N0(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 ay))throw new xe(`--model expects stage=model-id with stage one of ${Object.keys(ay).join(", ")}; got "${n}"`);t[s]=o}return t}async function ws(e){let t=e.intent?.trim();if(!t&&e.intentFile)t=(await cy(e.intentFile,"utf8")).trim();let n=N0(e.model??[]);return{...e.kind==="diff"?{kind:"diff"}:{},...e.kind==="diff"&&e.walkthrough?{walkthrough:!0}:{},repo:ot.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:ot.resolve(e.config)}:{}}}function D0(e,t={}){let n=ps(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 xe(["Missing required tools on PATH:",...o.map((a)=>` ${a}: ${yu[a]??""}`)].join(`
|
|
505
|
+
`))}async function uy(e,t,n,r={}){let s=e.kind??"review",o=s==="diff",a=o&&e.walkthrough===!0,l=e.fromRun,c=l?await xn(l).catch((ue)=>{throw new xe(`cannot start from run ${l}: ${ue instanceof Error?ue.message:String(ue)}`)}):void 0,u=c?j0(c.target):void 0;if(c?.repo.remote&&!o)throw new xe(`reviewing ${c.repo.slug??"this repository"} needs a local clone; run diffloupe review from a clone of it`);D0(u?u.kind==="pr"?`#${u.pr}`:"":e.target,{kind:s,walkthrough:a});let d=ot.resolve(e.repo??t),f=c?void 0:ps(e.target),p=o&&f?.kind==="pr"&&f.repo&&await f_(d,f)?{...f,repo:f.repo}:void 0;if(p)await p_(tu(p.repo),p.repo);let h=c?c.repo.root:p?tu(p.repo):d,x=p!==void 0||c?.repo.remote===!0,R=e.intent?.trim()||c?.intent.stated||void 0,w=await gr(),v=e.settingsFile?await ra(ot.resolve(e.settingsFile)):{},y=o?a?["walkthrough"]:[]:Xt,P=y.length?await(r.resolveSetup??ia)({cli:{...e.models?{models:e.models}:{},...e.effort?{effort:e.effort}:{}},settings:v,userConfig:w,stages:y}):void 0,D=P?[...P.credentials.errors,...P.catalog?.errors??[]]:[];if(D.length)throw new xe(D.join(`
|
|
506
|
+
`));let g={artifacts:Qr(),out:ot.join(Vt(),"scratch"),...__(v),...P?I_(P):{}},k=o?void 0:e.maxCostUsd??w.maxCostUsd,C=c&&u?await d_(h,u,c.base,c.head,{isTaken:_u}):p?await h_(h,p,{isTaken:_u}):await u_(h,e.target,{...e.base?{base:e.base}:{},isTaken:_u}),{target:M,changes:I,tag:F}=C,B=C.pullRequest,L=o?"Diff of":"Reviewing";if(n(B?`${L} ${M.slug}#${B.number}: ${B.title}`:`${L} ${M.slug} (${C.spec.kind})`),n(` ${M.base.slice(0,10)}..${M.head.slice(0,10)}`),n(` ${I.files} file(s) changed, +${I.insertions} -${I.deletions}`),n(` run ${F}`),P){for(let ue of y){let Fe=P.models[ue];n(` ${ue}: ${Fe.model} (${Hs(Fe.source)})`)}for(let ue of P.credentials.warnings)n(` warning: ${ue}`)}if(k!==void 0)n(P?.catalog?.zeroCost.includes("review")?" cost limit not enforced: models report no cost":` cost limit $${k.toFixed(2)}`);if(C.skippedUntracked.length){n(` skipped ${C.skippedUntracked.length} untracked file(s) over 1 MB:`);for(let ue of C.skippedUntracked)n(` ${ue}`)}let H=new Date().toISOString(),ge={root:h,...M.slug?{slug:M.slug}:{},...x?{remote:x}:{}},ke=c?c.target:await U0(h,C),ie=c?c.untrackedSkipped:C.skippedUntracked,De=await t_(F),Pe=await le("git",["-C",h,"diff","--no-color","--no-ext-diff","--full-index","-M",M.base,M.head]);await oa(ot.join(De,"diff.patch"),Pe);let we=o?void 0:await i_(ge,ke,H),q=we?await F0(h,we,M.head):void 0;if(q?.run.findings.length)n(` ${q.run.findings.length} finding(s) from prior run ${q.run.id}`);let T=await L0(),U=P?O_(P,y):void 0;await Promise.resolve().then(() => mu());let fe=oy({id:F,createdAt:H,repo:ge,target:ke,base:M.base,head:M.head,...R?{statedIntent:R}:{},patch:Pe,untrackedSkipped:ie,coreSource:T,...we?{priorRunId:we}:{},...U?{models:U}:{},...o?{kind:s}:{}});return await ei(fe),{id:F,kind:s,walkthrough:a,dir:De,createdAt:H,repo:h,target:M,reviewTarget:ke,config:g,...k!==void 0?{maxCostUsd:k}:{},...R?{intent:R}:{},patch:Pe,...we?{priorRunId:we}:{},...q?{previous:q}:{},untrackedSkipped:ie,coreSource:T,...U?{models:U}:{},pending:fe}}async function dy(e,t){let{id:n,dir:r}=e;await Promise.resolve().then(() => mu());let a=e.pending,l=Promise.resolve(),c=(f)=>{if(f.type!=="units"){t.onProgress(f);return}a=sy(ly(e),f.units,f.byClass),t.onProgress(Ep(a));let p=a;l=l.then(()=>ei(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 bp({repo:e.repo,target:e.target,tag:n,config:e.config,walkthrough:e.walkthrough,signal:t.signal,...e.intent?{intent:e.intent}:{},onProgress:c}):await pp({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.previous?{prior:kp(e.previous.run)}:{},onProgress:c})}catch(f){let p=t.signal.aborted;throw await l,await ei({...a,status:p?"cancelled":"failed",...p?{}:{error:f instanceof Error?f.message:String(f)}}),f}if(u.markdownPath){let f=e.config.artifacts??Qr();await gu(ot.join(f,"runs",`${n}.json`),ot.join(r,"raw","record.json")),await gu(u.markdownPath,ot.join(r,"raw","review.md")),await gu(ot.join(f,"reviews",`${n}.payloads.json`),ot.join(r,"raw","payloads.json"))}else if(u.record)await oa(ot.join(r,"raw","record.json"),`${JSON.stringify(u.record,null,2)}
|
|
507
|
+
`);await oa(ot.join(r,"raw","units.json"),`${JSON.stringify(u.units,null,2)}
|
|
508
|
+
`),await oa(ot.join(r,"raw","byClass.json"),`${JSON.stringify(u.byClass,null,2)}
|
|
509
|
+
`);let d;await l;try{d=hu({...ly(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 ei({...a,status:"failed",error:p}),Error(p,{cause:f})}if(await ei(d),e.kind==="review")t.log(` anchors: ${_o(d)}`);return{run:d,reviewed:e.kind==="diff"||u.record!==null}}function ly(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.models?{models:e.models}:{},...e.kind==="diff"?{kind:e.kind}:{}}}async function F0(e,t,n){try{let r=await xn(t),s=await n_(t),o=Object.entries(s.findingStatus).filter(([,c])=>c==="dismissed").map(([c])=>c),a=new Map,l=[...new Set(r.findings.map((c)=>c.file))];if(r.head!==n&&l.length)try{let c=await le("git",["-C",e,"diff","-U0","--no-color","--no-ext-diff",r.head,n,"--",...l]);a=Rp(c)}catch{}return{run:r,dismissed:o,lineMap:a}}catch{return}}async function gu(e,t){try{await T0(e,t)}catch{}}var ys;async function L0(){if(ys)return ys;try{ys=`diffloupe@${(await le("git",["-C",import.meta.dir,"rev-parse","--short","HEAD"])).trim()}`}catch{ys="diffloupe"}return ys}var _u=(e)=>M0(yt(e));function j0(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 ps(`range:${e.spec}`);default:return{kind:e.kind}}}async function U0(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 fy(e){try{return await cy(ot.join(e,"raw","review.md"),"utf8")}catch{return}}var wu=Fs.engines.bun.replace(/^>=\s*/,"");function py(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 H0(e){return/\d+\.\d+(?:\.\d+)?/.exec(e)?.[0]??null}function hy(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 aa(e,t,n,r){if(!e.which(t))return{name:t,status:n,detail:`not found on PATH. Install: ${yu[t]??t}`};let s=await e.exec(t,["--version"]),o=s&&s.code===0?H0(s.output):null,a=r?.(o)??{status:"ok"},l=[o??"version unknown",a.note].filter(Boolean).join(", ");return{name:t,status:a.status,detail:l}}async function K0(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:py(e.bunVersion,wu)?"ok":"fail",detail:py(e.bunVersion,wu)?e.bunVersion:`${e.bunVersion}, needs ${wu} or newer`}),t.push(await aa(e,"git","fail")),t.push(await aa(e,"opencode","fail",(a)=>a&&a.startsWith("2.")?{status:"ok"}:{status:"fail",note:"needs OpenCode 2.x (https://opencode.ai/v2/docs/)"})),t.push(await aa(e,"tilth","fail"));let n=await aa(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 Xt){let l=r.models[a];t.push({name:`model: ${a}`,status:"ok",detail:`${l.model} (${Hs(l.source)})`})}if(!r.catalog)t.push({name:"model catalog",status:"warn",detail:"could not ask OpenCode for its models; not checked"});else{for(let a of r.catalog.errors)t.push({name:"model catalog",status:"fail",detail:a});if(r.catalog.zeroCost.length>0)t.push({name:"model catalog",status:"warn",detail:`no cost reported for ${r.catalog.zeroCost.join(", ")}: --max-cost cannot be enforced`})}for(let a of r.credentials.coverage){if(a.source==="none")continue;t.push({name:`credential: ${a.provider}`,status:"ok",detail:`${a.source}: ${a.detail}`})}for(let a of r.credentials.warnings)t.push({name:"credentials",status:"warn",detail:a});for(let a of r.credentials.errors)t.push({name:"credentials",status:"fail",detail:a})}let s=await e.dataSizes(),o=Object.values(s).reduce((a,l)=>a+l,0);return t.push({name:"data dir",status:"ok",detail:`${Vt()}: ${hy(o)} (${Object.entries(s).map(([a,l])=>`${a} ${hy(l)}`).join(", ")}). \`diffloupe runs prune\` removes old runs`}),t}async function la(e){let t=0,n;try{n=await B0(e,{withFileTypes:!0})}catch{return 0}for(let r of n){let s=my.join(e,r.name);if(r.isDirectory())t+=await la(s);else if(r.isFile())t+=await q0(s).then((o)=>o.size,()=>0)}return t}async function W0(e,t){try{let n=await te(e,t,{allowFail:!0,timeoutMs:20000});return{code:n.code,output:`${n.stdout}
|
|
510
|
+
${n.stderr}`}}catch{return null}}var V0={ok:bs.default.green("ok "),warn:bs.default.yellow("warn"),fail:bs.default.red("FAIL")};function gy(){return new Ft("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 K0({platform:process.platform,bunVersion:Bun.version,which:(n)=>Bun.which(n),exec:W0,setup:async()=>{let n=e.config?await ra(my.resolve(e.config)):{};return ia({settings:n,userConfig:await gr()})},dataSizes:async()=>({runs:await la(cs()),artifacts:await la(Qr()),scratch:await la(us())})});for(let n of t)console.log(`${V0[n.status]} ${bs.default.bold(n.name)}: ${n.detail}`);if(t.some((n)=>n.status==="fail"))process.exit(1)})}import KA from"path";var ln=Ba(Bs(),1);function vs(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 G0 from"path";import{appendFileSync as z0}from"fs";import{readFile as J0}from"fs/promises";function X0(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 ca(e){return X0({prepare:(t,n)=>uy(t,e,n),execute:dy})}class ua extends Error{activeRunId;constructor(e){super(e?`run ${e} is still running`:"a run is starting");this.activeRunId=e;this.name="RunBusyError"}}function _y(e){return G0.join(yt(e),"events.jsonl")}async function yy(e){let t;try{t=await J0(_y(e),"utf8")}catch{return[]}let n=[];return t.split(`
|
|
511
|
+
`).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 xs{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 ua(this.activeRunId);this.starting=!0;let t=[],n;try{n=await this.prepare(e,(a)=>t.push(a))}finally{this.starting=!1}let r=new AbortController,s={id:n.id,controller:r,seq:0,subscribers:new Set,pending:n.pending,done:Promise.resolve({status:"cancelled"})};this.active=s;let o=(a)=>this.emit(s,a);for(let a of t)o({type:"log",message:a});return s.done=n.execute({signal:r.signal,onProgress:o,log:(a)=>o({type:"log",message:a})}).then(({run:a,reviewed:l})=>(o({type:"done",status:"complete",findings:a.findings.length,carriedOver:a.findings.filter((c)=>c.carriedFrom).length,costUsd:a.meta.costUsd,wallMs:a.meta.wallMs,...l?{}:{noChanges:!0},...a.meta.kind==="diff"?{kind:"diff",files:a.files.length}:{}}),{status:"complete",run:a,reviewed:l}),(a)=>{if(r.signal.aborted||a instanceof It)return o({type:"cancelled"}),{status:"cancelled"};let l=a instanceof Error?a.message:String(a);return o({type:"error",message:l}),{status:"failed",error:l}}).finally(()=>{if(this.active===s)this.active=null}),{id:n.id,done:s.done}}cancel(e){let t=this.active;if(!t||t.id!==e)return;return t.controller.abort(),t.done}subscribe(e,t){let n=this.active;if(!n||n.id!==e)return;return n.subscribers.add(t),{lastSeq:n.seq,unsubscribe:()=>n.subscribers.delete(t)}}emit(e,t){if(t.type==="groups")e.pending=Sp(e.pending,t);let n={...t,seq:++e.seq,at:new Date().toISOString()};try{z0(_y(e.id),`${JSON.stringify(n)}
|
|
512
|
+
`)}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 ri(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 xu(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 Y0(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 by(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} ${ri(t.target)}`,t.kind==="diff"?` ${t.repo.slug??t.repo.root}${t.costUsd?` $${t.costUsd.toFixed(2)}`:""}`:` ${t.repo.slug??t.repo.root} ${Y0(t.findingCounts)} $${t.costUsd.toFixed(2)}`].join(`
|
|
513
|
+
`)).join(`
|
|
514
|
+
|
|
515
|
+
`)}function vy(e){return e.carriedFrom?` (open since ${e.carriedFrom})`:""}function bu(e){return` [${e.severity}] ${e.title}${vy(e)}
|
|
516
|
+
${xu(e.anchor)}`}function xy(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?`
|
|
517
|
+
${t} ${n.note}`:""}`)]}function ky(e){let t=[];if(t.push(`${e.id} ${e.status}`),t.push(`${ri(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}`);if(e.overview.focus)t.push(`focus: ${e.overview.focus}`);if(e.intent.alignment)t.push(`intent: ${e.intent.alignment}`);let n=new Map(e.files.map((s)=>[s.path,s]));t.push(...$y(e));let r=e.findings.filter((s)=>!n.has(s.file));if(r.length){t.push("",`Findings on files outside the diff (${r.length})`);for(let s of r)t.push(bu(s))}if(e.overCapFindings.length){t.push("",`Over the posting cap (${e.overCapFindings.length})`);for(let s of e.overCapFindings)t.push(bu(s))}if(t.push(...xy(e," ")),e.stops.length){t.push("",`Walkthrough stops (${e.stops.length})`);for(let s of e.stops){t.push(` ${s.id} ${s.title}${s.importance==="normal"?"":` [${s.importance}]`}`);for(let o of s.locations)t.push(` ${xu(o)}`)}}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(zg(e)==="diff")return t.push("",`${e.files.length} files${Ry(e)}, ${(e.meta.wallMs/1000).toFixed(1)}s`),t.join(`
|
|
518
|
+
`);return t.push("",`${e.findings.length} findings, ${e.files.length} files, $${e.meta.costUsd.toFixed(2)}, ${Math.round(e.meta.wallMs/1000)}s`,`anchors: ${_o(e)}`),t.join(`
|
|
519
|
+
`)}function Ry(e){return e.meta.costUsd?`, $${e.meta.costUsd.toFixed(2)}`:""}function $y(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((l)=>l.parentId===s.id);if(!o||!s.parentId&&s.files.length===0){let l=o&&s.stopIds.length?` (stops ${s.stopIds.join(", ")}; files sit in other groups)`:"";t.push("",`${s.critical?"! ":""}${s.title}${l}`);continue}let a=s.parentId?" ":"";t.push(`${s.parentId?"":`
|
|
520
|
+
`}${a}${s.critical?"! ":""}${s.title}`);for(let l of s.files){let c=r.get(l),u=c?` ${c.status} +${c.additions} -${c.deletions}${c.isBinary?" binary":""}`:"";t.push(`${a} ${l}${u}`);for(let d of s.findingIds){let f=n.get(d);if(f?.file===l)t.push(bu(f))}}}return t}function Sy(e){let t=[];if(t.push(`${ri(e.target)} ${e.base.slice(0,10)}..${e.head.slice(0,10)}`),e.intent.inferred)t.push("",`What it does: ${vu(e.intent.inferred,400)}`);if(t.push(...$y(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}${Ry(e)}`),t.join(`
|
|
521
|
+
`)}var wy=["blocker","should-fix","question","nice-to-have"];function vu(e,t=200){let n=e.trim().split(/(?<=[.!?])\s+/)[0]??"";return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function Ey(e){let t=[];if(t.push(`${ri(e.target)} ${e.base.slice(0,10)}..${e.head.slice(0,10)}`),e.unreviewed.failed.length)t.push(`Incomplete: ${e.unreviewed.failed.length} slice(s) failed.`);let n=e.unreviewed.budget??[];if(n.length)t.push(`Incomplete: cost limit reached, ${n.length} file(s) not reviewed.`);let{intent:r}=e;if(r.alignment){t.push("",`Intent: ${r.alignment}`);for(let o of r.mismatches??[])t.push(` - ${o}`)}else if(r.inferred)t.push("",`What it does: ${vu(r.inferred,400)}`);if(e.overview.focus)t.push("",`Focus: ${e.overview.focus}`);let s=[...e.findings].sort((o,a)=>wy.indexOf(o.severity)-wy.indexOf(a.severity));t.push("",s.length?`Findings (${s.length})`:"No findings.");for(let o of s){t.push(` [${o.severity}] ${o.title}${vy(o)}`,` ${xu(o.anchor)}`);let a=vu(o.impact??o.explanation);if(a&&a!==o.title)t.push(` ${a}`)}if(e.overCapFindings.length)t.push(` \u2026and ${e.overCapFindings.length} more over the cap (runs show)`);if(t.push(...xy(e," ")),e.overview.startHere.length)t.push("","Start here"),e.overview.startHere.forEach((o,a)=>t.push(` ${a+1}. ${o.file} \u2014 ${o.why}`));return t.join(`
|
|
522
|
+
`)}async function Ay(e){let t=(c)=>console.error(c),n=new xs(ca(process.cwd()));n.watch((c,u)=>{let d=vs(u);if(d)t(d)});let r;try{r=await n.start(await ws(e))}catch(c){return t(`Error: ${c instanceof Error?c.message:String(c)}`),1}let s=ks(()=>{t(`
|
|
523
|
+
Cancelling: stopping agents and removing the worktree (Ctrl+C again to exit now)...`),n.cancel(r.id)}),o=await r.done;s();let a=yt(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})
|
|
524
|
+
`),e.kind==="diff")return process.stdout.write(`${Sy(o.run)}
|
|
525
|
+
`),0;if(!o.reviewed)return 0;let l=e.markdown?await fy(a):void 0;return process.stdout.write(l??`${Ey(o.run)}
|
|
526
|
+
`),0}function ks(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 Z0 from"os";import{existsSync as Q0,readFileSync as eA}from"fs";var tA=new Set(["true","false","none",":","0","1"]);function nA(){if(process.platform!=="linux")return!1;if(Z0.release().toLowerCase().includes("microsoft"))return!0;try{let e=eA("/proc/version","utf8").toLowerCase();return e.includes("microsoft")||e.includes("wsl")}catch{return!1}}function rA(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("/mnt/")||e.toLowerCase().endsWith(".exe")}function iA(e,t){let n=t.browser?.trim()&&!tA.has(t.browser.trim().toLowerCase())?t.browser.trim():void 0;if(t.wsl){if(!n)return["cmd.exe","/c","start","",e];if(rA(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 Cy(e){let t=nA(),n=iA(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"&&Q0("/mnt/c")?{cwd:"/mnt/c"}:{}}).exited===0}catch{return!1}}var ku=(e,t,n)=>(r,s)=>{let o=-1;return a(0);async function a(l){if(l<=o)throw Error("next() called multiple times");o=l;let c,u=!1,d;if(e[l])d=e[l][0][0],r.req.routeIndex=l;else d=l===e.length&&s||void 0;if(d)try{c=await d(r,()=>a(l+1))}catch(f){if(f instanceof Error&&t)r.error=f,c=await t(f,r),u=!0;else throw f}else if(r.finalized===!1&&n)c=await n(r);if(c&&(r.finalized===!1||u))r.res=c;return r}};var Iy=Symbol();var Oy=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,o=(e instanceof da?e.raw.headers:e.headers).get("Content-Type");if(o?.startsWith("multipart/form-data")||o?.startsWith("application/x-www-form-urlencoded"))return sA(e,{all:n,dot:r});return{}};async function sA(e,t){let n=await e.formData();if(n)return oA(n,t);return{}}function oA(e,t){let n=Object.create(null);if(e.forEach((r,s)=>{if(!(t.all||s.endsWith("[]")))n[s]=r;else aA(n,s,r)}),t.dot)Object.entries(n).forEach(([r,s])=>{if(r.includes("."))lA(n,r,s),delete n[r]});return n}var aA=(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]},lA=(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 $u=(e)=>{let t=e.split("/");if(t[0]==="")t.shift();return t},Py=(e)=>{let{groups:t,path:n}=cA(e),r=$u(n);return uA(r,t)},cA=(e)=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(n,r)=>{let s=`@${r}`;return t.push([s,n]),s}),{groups:t,path:e}},uA=(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},fa={},My=(e,t)=>{if(e==="*")return"*";let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;if(!fa[r])if(n[2])fa[r]=t&&t[0]!==":"&&t[0]!=="*"?[r,n[1],new RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],new RegExp(`^${n[2]}$`)];else fa[r]=[e,n[1],!0];return fa[r]}return null},pa=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,(n)=>{try{return t(n)}catch{return n}})}},dA=(e)=>pa(e,decodeURI),Su=(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 dA(a.includes("%25")?a.replace(/%25/g,"%2525"):a)}else if(s===63)break}return t.slice(n,r)};var Ty=(e)=>{let t=Su(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},cr=(e,t,...n)=>{if(n.length)t=cr(t,...n);return`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`},ha=(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)},Ru=(e)=>{if(!/[%+]/.test(e))return e;if(e.indexOf("+")!==-1)e=e.replace(/\+/g," ");return e.indexOf("%")!==-1?pa(e,Eu):e},Ny=(e,t,n)=>{let r;if(!n&&t&&!/[%+]/.test(t)){let a=e.indexOf("?",8);if(a===-1)return;if(!e.startsWith(t,a+1))a=e.indexOf(`&${t}`,a+1);while(a!==-1){let l=e.charCodeAt(a+t.length+1);if(l===61){let c=a+t.length+2,u=e.indexOf("&",c);return Ru(e.slice(c,u===-1?void 0:u))}else if(l==38||isNaN(l))return"";a=e.indexOf(`&${t}`,a+1)}if(r=/[%+]/.test(e),!r)return}let s={};r??=/[%+]/.test(e);let o=e.indexOf("?",8);while(o!==-1){let a=e.indexOf("&",o+1),l=e.indexOf("=",o);if(l>a&&a!==-1)l=-1;let c=e.slice(o+1,l===-1?a===-1?void 0:a:l);if(r)c=Ru(c);if(o=a,c==="")continue;let u;if(l===-1)u="";else if(u=e.slice(l+1,a===-1?void 0:a),r)u=Ru(u);if(n){if(!(s[c]&&Array.isArray(s[c])))s[c]=[];s[c].push(u)}else s[c]??=u}return t?s[t]:s},Dy=Ny,Fy=(e,t)=>Ny(e,t,!0),Eu=decodeURIComponent;var Ly=(e)=>pa(e,Eu),da=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)?Ly(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)?Ly(r):r}return e}#i(e){return this.#e[1]?this.#e[1][e]:e}query(e){return Dy(this.url,e)}queries(e){return Fy(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 Oy(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[Iy](){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 ma={Stringify:1,BeforeStream:2,Stream:3},fA=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n};var Rs=async(e,t,n,r,s)=>{if(typeof e==="object"&&!(e instanceof String)){if(!(e instanceof Promise))e=e.toString();if(e instanceof Promise)e=await e}let o=e.callbacks;if(!o?.length)return Promise.resolve(e);if(s)s[0]+=e;else s=[e];let a=Promise.all(o.map((l)=>l({phase:t,buffer:s,context:r}))).then((l)=>Promise.all(l.filter(Boolean).map((c)=>Rs(c,t,!1,r,s))).then(()=>s[0]));if(n)return fA(await a,o);else return a};var jy="text/plain; charset=UTF-8",Au=(e,t)=>({"Content-Type":e,...t}),Uy=class{#t;#e;env={};#n;finalized=!1;error;#s;#i;#r;#u;#l;#c;#a;#d;#f;constructor(e,t){if(this.#t=e,t)this.#i=t.executionCtx,this.env=t.env,this.#c=t.notFoundHandler,this.#f=t.path,this.#d=t.matchResult}get req(){return this.#e??=new da(this.#t,this.#f,this.#d),this.#e}get event(){if(this.#i&&"respondWith"in this.#i)return this.#i;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#i)return this.#i;else throw Error("This context has no ExecutionContext")}get res(){return this.#r||=new Response(null,{headers:this.#a??=new Headers})}set res(e){if(this.#r&&e){e=new Response(e.body,e);for(let[t,n]of this.#r.headers.entries()){if(t==="content-type")continue;if(t==="set-cookie"){let r=this.#r.headers.getSetCookie();e.headers.delete("set-cookie");for(let s of r)e.headers.append("set-cookie",s)}else e.headers.set(t,n)}}this.#r=e,this.finalized=!0}render=(...e)=>(this.#l??=(t)=>this.html(t),this.#l(...e));setLayout=(e)=>this.#u=e;getLayout=()=>this.#u;setRenderer=(e)=>{this.#l=e};header=(e,t,n)=>{if(this.finalized)this.#r=new Response(this.#r.body,this.#r);let r=this.#r?this.#r.headers:this.#a??=new Headers;if(t===void 0)r.delete(e);else if(n?.append)r.append(e,t);else r.set(e,t)};status=(e)=>{this.#s=e};set=(e,t)=>{this.#n??=new Map,this.#n.set(e,t)};get=(e)=>this.#n?this.#n.get(e):void 0;get var(){if(!this.#n)return{};return Object.fromEntries(this.#n)}#o(e,t,n){let r=this.#r?new Headers(this.#r.headers):this.#a??new Headers;if(typeof t==="object"&&"headers"in t){let o=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[a,l]of o)if(a.toLowerCase()==="set-cookie")r.append(a,l);else r.set(a,l)}if(n)for(let[o,a]of Object.entries(n))if(typeof a==="string")r.set(o,a);else{r.delete(o);for(let l of a)r.append(o,l)}let s=typeof t==="number"?t:t?.status??this.#s;return new Response(e,{status:s,headers:r})}newResponse=(...e)=>this.#o(...e);body=(e,t,n)=>this.#o(e,t,n);text=(e,t,n)=>!this.#a&&!this.#s&&!t&&!n&&!this.finalized?new Response(e):this.#o(e,t,Au(jy,n));json=(e,t,n)=>this.#o(JSON.stringify(e),t,Au("application/json",n));html=(e,t,n)=>{let r=(s)=>this.#o(s,t,Au("text/html; charset=UTF-8",n));return typeof e==="object"?Rs(e,ma.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header("Location",!/[^\x00-\xFF]/.test(n)?n:encodeURI(n)),this.newResponse(null,t??302)};notFound=()=>(this.#c??=()=>new Response,this.#c(this))};var Oe="ALL",By="all",qy=["get","post","put","delete","options","patch"],ga="Can not add a route since the matcher is already built.",_a=class extends Error{};var Hy="__COMPOSED_HANDLER";var pA=(e)=>e.text("404 Not Found",404),Ky=(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)},Wy=class e{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...qy,By].forEach((o)=>{this[o]=(a,...l)=>{if(typeof a==="string")this.#t=a;else this.#s(o,this.#t,a);return l.forEach((c)=>{this.#s(o,this.#t,c)}),this}}),this.on=(o,a,...l)=>{for(let c of[a].flat()){this.#t=c;for(let u of[o].flat())l.map((d)=>{this.#s(u.toUpperCase(),this.#t,d)})}return this},this.use=(o,...a)=>{if(typeof o==="string")this.#t=o;else this.#t="*",a.unshift(o);return a.forEach((l)=>{this.#s(Oe,this.#t,l)}),this};let{strict:r,...s}=t;Object.assign(this,s),this.getPath=r??!0?t.getPath??Su:Ty}#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=pA;errorHandler=Ky;route(t,n){let r=this.basePath(t);return n.routes.map((s)=>{let o;if(n.errorHandler===Ky)o=s.handler;else o=async(a,l)=>(await ku([],n.errorHandler)(a,()=>s.handler(a,l))).res,o[Hy]=s.handler;r.#s(s.method,s.path,o)}),this}basePath(t){let n=this.#e();return n._basePath=cr(this._basePath,t),n}onError=(t)=>(this.errorHandler=t,this);notFound=(t)=>(this.#n=t,this);mount(t,n,r){let s,o;if(r)if(typeof r==="function")o=r;else if(o=r.optionHandler,r.replaceRequest===!1)s=(c)=>c;else s=r.replaceRequest;let a=o?(c)=>{let u=o(c);return Array.isArray(u)?u:[u]}:(c)=>{let u=void 0;try{u=c.executionCtx}catch{}return[c.env,u]};s||=(()=>{let c=cr(this._basePath,t),u=c==="/"?0:c.length;return(d)=>{let f=new URL(d.url);return f.pathname=f.pathname.slice(u)||"/",new Request(f,d)}})();let l=async(c,u)=>{let d=await n(s(c.req.raw),...a(c));if(d)return d;await u()};return this.#s(Oe,cr(t,"*"),l),this}#s(t,n,r){t=t.toUpperCase(),n=cr(this._basePath,n);let s={basePath:this._basePath,path:n,method:t,handler:r};this.router.add(t,n,[r,s]),this.routes.push(s)}#i(t,n){if(t instanceof Error)return this.errorHandler(t,n);throw t}#r(t,n,r,s){if(s==="HEAD")return(async()=>new Response(null,await this.#r(t,n,r,"GET")))();let o=this.getPath(t,{env:r}),a=this.router.match(s,o),l=new Uy(t,{path:o,matchResult:a,env:r,executionCtx:n,notFoundHandler:this.#n});if(a[0].length===1){let u;try{u=a[0][0][0][0](l,async()=>{l.res=await this.#n(l)})}catch(d){return this.#i(d,l)}return u instanceof Promise?u.then((d)=>d||(l.finalized?l.res:this.#n(l))).catch((d)=>this.#i(d,l)):u??this.#n(l)}let c=ku(a[0],this.errorHandler,this.#n);return(async()=>{try{let u=await c(l);if(!u.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return u.res}catch(u){return this.#i(u,l)}})()}fetch=(t,...n)=>this.#r(t,n[1],n[0],t.method);request=(t,n,r,s)=>{if(t instanceof Request)return this.fetch(n?new Request(t,n):t,r,s);return t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${cr("/",t)}`,n),r,s)};fire=()=>{addEventListener("fetch",(t)=>{t.respondWith(this.#r(t.request,t,void 0,t.request.method))})}};var ya=[];function Cu(e,t){let n=this.buildAllMatchers(),r=(s,o)=>{let a=n[s]||n[Oe],l=a[2][o];if(l)return l;let c=o.match(a[0]);if(!c)return[[],ya];let u=c.indexOf("",1);return[a[1][u],c]};return this.match=r,r(e,t)}var wa="[^/]+",$s=".*",Ss="(?:|/.*)",ur=Symbol(),hA=new Set(".\\+*[^]$()");function mA(e,t){if(e.length===1)return t.length===1?e<t?-1:1:-1;if(t.length===1)return 1;if(e===$s||e===Ss)return 1;else if(t===$s||t===Ss)return-1;if(e===wa)return 1;else if(t===wa)return-1;return e.length===t.length?e<t?-1:1:t.length-e.length}var Vy=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,...l]=t,c=a==="*"?l.length===0?["","",$s]:["","",wa]:a==="/*"?["","",Ss]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),u;if(c){let d=c[1],f=c[2]||wa;if(d&&c[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!==$s&&p!==Ss))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!==$s&&d!==Ss))throw ur;if(o)return;u=this.#n[a]=new e}u.insert(l,n,r,s,o)}buildRegExpStr(){let n=Object.keys(this.#n).sort(mA).map((r)=>{let s=this.#n[r];return(typeof s.#e==="number"?`(${r})@${s.#e}`:hA.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 Gy=class{#t={varIndex:0};#e=new Vy;insert(e,t,n){let r=[],s=[];for(let a=0;;){let l=!1;if(e=e.replace(/\{[^}]+\}/g,(c)=>{let u=`@\\${a}`;return s[a]=[u,c],a++,l=!0,u}),!l)break}let o=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let a=s.length-1;a>=0;a--){let[l]=s[a];for(let c=o.length-1;c>=0;c--)if(o[c].indexOf(l)!==-1){o[c]=o[c].replace(l,s[a][1]);break}}return this.#e.insert(o,t,r,this.#t,n),r}buildRegExp(){let e=this.#e.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(s,o,a)=>{if(o!==void 0)return n[++t]=Number(o),"$()";if(a!==void 0)return r[Number(a)]=++t,"";return""}),[new RegExp(`^${e}`),n,r]}};var gA=[/^$/,[],Object.create(null)],zy=Object.create(null);function Jy(e){return zy[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(t,n)=>n?`\\${n}`:"(?:|/.*)")}$`)}function _A(){zy=Object.create(null)}function yA(e){let t=new Gy,n=[];if(e.length===0)return gA;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,x]=r[u];if(p)s[h]=[x.map(([w])=>[w,Object.create(null)]),ya];else d++;let R;try{R=t.insert(h,d,p)}catch(w){throw w===ur?new _a(h):w}if(p)continue;n[d]=x.map(([w,v])=>{let y=Object.create(null);v-=1;for(;v>=0;v--){let[P,D]=R[v];y[P]=D}return[w,y]})}let[o,a,l]=t.buildRegExp();for(let u=0,d=n.length;u<d;u++)for(let f=0,p=n[u].length;f<p;f++){let h=n[u][f]?.[1];if(!h)continue;let x=Object.keys(h);for(let R=0,w=x.length;R<w;R++)h[x[R]]=l[h[x[R]]]}let c=[];for(let u in a)c[u]=n[a[u]];return[o,c,s]}function ii(e,t){if(!e)return;for(let n of Object.keys(e).sort((r,s)=>s.length-r.length))if(Jy(n).test(t))return[...e[n]];return}var ba=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(ga);if(!r[e])[r,s].forEach((l)=>{l[e]=Object.create(null),Object.keys(l[Oe]).forEach((c)=>{l[e][c]=[...l[Oe][c]]})});if(t==="/*")t="*";let o=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let l=Jy(t);if(e===Oe)Object.keys(r).forEach((c)=>{r[c][t]||=ii(r[c],t)||ii(r[Oe],t)||[]});else r[e][t]||=ii(r[e],t)||ii(r[Oe],t)||[];Object.keys(r).forEach((c)=>{if(e===Oe||e===c)Object.keys(r[c]).forEach((u)=>{l.test(u)&&r[c][u].push([n,o])})}),Object.keys(s).forEach((c)=>{if(e===Oe||e===c)Object.keys(s[c]).forEach((u)=>l.test(u)&&s[c][u].push([n,o]))});return}let a=ha(t)||[t];for(let l=0,c=a.length;l<c;l++){let u=a[l];Object.keys(s).forEach((d)=>{if(e===Oe||e===d)s[d][u]||=[...ii(r[d],u)||ii(r[Oe],u)||[]],s[d][u].push([n,o-c+l+1])})}}match=Cu;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,_A(),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 yA(t)}};var Iu=class{name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,n){if(!this.#e)throw Error(ga);this.#e.push([e,t,n])}match(e,t){if(!this.#e)throw Error("Fatal error");let n=this.#t,r=this.#e,s=n.length,o=0,a;for(;o<s;o++){let l=n[o];try{for(let c=0,u=r.length;c<u;c++)l.add(...r[c]);a=l.match(e,t)}catch(c){if(c instanceof _a)continue;throw c}this.match=l.match.bind(l),this.#t=[l],this.#e=void 0;break}if(o===s)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,a}get activeRouter(){if(this.#e||this.#t.length!==1)throw Error("No active router has been determined yet.");return this.#t[0]}};var Es=Object.create(null),Xy=class e{#t;#e;#n;#s=0;#i=Es;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=Py(n),a=[];for(let l=0,c=o.length;l<c;l++){let u=o[l],d=o[l+1],f=My(u,d),p=Array.isArray(f)?f[0]:u;if(p in s.#e){if(s=s.#e[p],f)a.push(f[1]);continue}if(s.#e[p]=new e,f)s.#n.push(f),a.push(f[1]);s=s.#e[p]}return s.#t.push({[t]:{handler:r,possibleKeys:a.filter((l,c,u)=>u.indexOf(l)===c),score:this.#s}}),s}#r(t,n,r,s){let o=[];for(let a=0,l=t.#t.length;a<l;a++){let c=t.#t[a],u=c[n]||c[Oe],d={};if(u!==void 0){if(u.params=Object.create(null),o.push(u),r!==Es||s&&s!==Es)for(let f=0,p=u.possibleKeys.length;f<p;f++){let h=u.possibleKeys[f],x=d[u.score];u.params[h]=s?.[h]&&!x?s[h]:r[h]??s?.[h],d[u.score]=!0}}}return o}search(t,n){let r=[];this.#i=Es;let o=[this],a=$u(n),l=[];for(let c=0,u=a.length;c<u;c++){let d=a[c],f=c===u-1,p=[];for(let h=0,x=o.length;h<x;h++){let R=o[h],w=R.#e[d];if(w)if(w.#i=R.#i,f){if(w.#e["*"])r.push(...this.#r(w.#e["*"],t,R.#i));r.push(...this.#r(w,t,R.#i))}else p.push(w);for(let v=0,y=R.#n.length;v<y;v++){let P=R.#n[v],D=R.#i===Es?{}:{...R.#i};if(P==="*"){let F=R.#e["*"];if(F)r.push(...this.#r(F,t,R.#i)),F.#i=D,p.push(F);continue}let[g,k,C]=P;if(!d&&!(C instanceof RegExp))continue;let M=R.#e[g],I=a.slice(c).join("/");if(C instanceof RegExp){let F=C.exec(I);if(F){if(D[k]=F[0],r.push(...this.#r(M,t,R.#i,D)),Object.keys(M.#e).length){M.#i=D;let B=F[0].match(/\//)?.length??0;(l[B]||=[]).push(M)}continue}}if(C===!0||C.test(d))if(D[k]=d,f){if(r.push(...this.#r(M,t,D,R.#i)),M.#e["*"])r.push(...this.#r(M.#e["*"],t,D,R.#i))}else M.#i=D,p.push(M)}}o=p.concat(l.shift()??[])}if(r.length>1)r.sort((c,u)=>c.score-u.score);return[r.map(({handler:c,params:u})=>[c,u])]}};var Ou=class{name="TrieRouter";#t;constructor(){this.#t=new Xy}add(e,t,n){let r=ha(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 Wy{constructor(e={}){super(e);this.router=e.router??new Iu({routers:[new ba,new Ou]})}};import{readdir as Yy,rm as Zy,stat as wA}from"fs/promises";import bA from"os";import Qy from"path";async function tw(){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 nw(){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 vA=86400000,ew="code-review-subject-";function xA(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}async function rw(e,t){let n=bA.tmpdir(),r=[];try{r=await Yy(n)}catch{}for(let o of r){if(!o.startsWith(ew))continue;let a=Number(o.slice(ew.length).split("-")[1]);if(!Number.isInteger(a)||a<=0||xA(a))continue;let l=Qy.join(n,o);await Zy(l,{recursive:!0,force:!0}).catch(()=>{}),t(`removed stale review worktree ${l}`)}if(e)await te("git",["-C",e,"worktree","prune"],{allowFail:!0}).catch(()=>{});let s=(await Gt()).filter((o)=>o.status==="running").map((o)=>o.id);for(let o of ta()){let a;try{a=await Yy(o)}catch{continue}for(let l of a){let c=Qy.join(o,l);try{if(!(s.some((d)=>l.startsWith(`${d}-`))&&Date.now()-(await wA(c)).mtimeMs<vA))await Zy(c,{recursive:!0,force:!0})}catch{}}}}import sw from"os";function iw(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 kA="DIFFLOUPE_ALLOWED_HOSTS",ow=["localhost","127.0.0.1","::1"];function Pu(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 As(e){let t=e.replace(/^\[|\]$/g,"").toLowerCase();return ow.includes(t)||t.startsWith("127.")||t.endsWith(".localhost")}function Mu(e,t=process.env[kA]){let n=new Set(ow);for(let r of(t??"").split(",")){let s=Pu(r);if(s)n.add(s)}if(!As(e)){let r=Pu(e.includes(":")&&!e.startsWith("[")?`[${e}]`:e);if(r)n.add(r);n.add(sw.hostname().toLowerCase());for(let s of Object.values(sw.networkInterfaces()))for(let o of s??[])n.add(o.address.toLowerCase())}return n}function aw(e){return async(t,n)=>{let r=Pu(t.req.header("host"));if(r===null||r!==void 0&&!e.has(r)&&!As(r))return t.json({error:"host not allowed"},403);await n()}}function lw(){return async(e,t)=>{let n=e.req.method;if(n!=="GET"&&n!=="HEAD"&&n!=="OPTIONS"){if(!iw(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 cw(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 TA}from"fs/promises";import NA from"path";var Tu=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+`
|
|
527
|
+
`),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 va=()=>{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 va=()=>t,t};var uw=class extends Tu{constructor(e,t){super(e,t)}async writeSSE(e){let n=(await Rs(e.data,ma.Stringify,!1,{})).split(/\r\n|\r|\n/).map((s)=>`data: ${s}`).join(`
|
|
528
|
+
`),r=[e.event&&`event: ${e.event}`,n,e.id&&`id: ${e.id}`,e.retry&&`retry: ${e.retry}`].filter(Boolean).join(`
|
|
529
|
+
`)+`
|
|
530
|
+
|
|
531
|
+
`;await this.write(r)}},RA=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()}},$A=new WeakMap,Nu=(e,t,n)=>{let{readable:r,writable:s}=new TransformStream,o=new uw(s,r);if(va())e.req.raw.signal.addEventListener("abort",()=>{if(!o.closed)o.abort()});return $A.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"),RA(o,t,n),e.newResponse(o.responseReadable)};var EA=15000,AA=new Set(["done","cancelled","error"]);function CA(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 fw(e,t,n){e.header("Cache-Control","no-cache"),e.header("X-Accel-Buffering","no");let r=CA(e);return Nu(e,async(s)=>{let o=r,a=null,l=[],c=!1,u=null,d=async(h)=>{if(h.seq<=o)return;if(o=h.seq,await s.writeSSE({id:String(h.seq),event:h.type,data:JSON.stringify(h)}),AA.has(h.type))c=!0},f=t.subscribe(n,(h)=>{if(a)a(h);else l.push(h)});s.onAbort(()=>{f?.unsubscribe(),c=!0,u?.()});for(let h of await yy(n))await d(h);for(let h of l.splice(0))await d(h);if(!f||c){await dw(s),f?.unsubscribe();return}let p=[];a=(h)=>{p.push(h),u?.()};while(!c&&!s.aborted){if(p.length===0){if(await new Promise((h)=>{let x=setTimeout(h,EA);u=()=>{clearTimeout(x),h()}}),u=null,p.length===0&&!c&&!s.aborted)await s.write(`: keepalive
|
|
532
|
+
|
|
533
|
+
`);continue}for(let h of p.splice(0))await d(h)}if(f.unsubscribe(),!s.aborted)await dw(s)})}async function dw(e){await e.writeSSE({event:"end",data:"{}"})}var pw=ae({"+":"reject","target?":"string","repo?":"string","base?":"string","intent?":"string","models?":{"+":"reject","review?":"string","coordinator?":"string","walkthrough?":"string"},"effort?":"string","maxCostUsd?":"number > 0","settingsFile?":"string","kind?":as,"walkthrough?":"boolean","fromRun?":"string"}),R2=ae({id:"string",url:"string"}),IA=ae("'resolving_target' | 'checking_registry' | 'building_map' | 'grouping' | 'reviewing' | 'coordinating' | 'walkthrough' | 'verifying' | 'writing'"),OA=ae({type:"'stage'",stage:IA}).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"}),PA=ae({type:"'groups'",groups:Qc.array(),files:ae({path:"string",groupId:"string",classification:"'code' | 'docs' | 'skip'"}).array()}),MA=OA.or(PA).or({type:"'done'",status:"'complete'",findings:"number","carriedOver?":"number",costUsd:"number",wallMs:"number","noChanges?":"boolean","kind?":as,"files?":"number"}).or({type:"'cancelled'"}).or({type:"'error'",message:"string"}),$2=MA.and({seq:"number",at:"string"}),S2=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"}}),E2=ae({error:"string","activeRunId?":"string"});var DA=2097152;function hw(e){try{return yt(e),!0}catch{return!1}}function mw(e){let t=new dr;async function n(s){let o=e.runs.pendingRun(s);if(o)return o;if(!hw(s))return;try{return await xn(s)}catch(a){if(a instanceof Un)return a;return}}let r=(s)=>({error:`no run ${s}`});return t.get("/",async(s)=>s.json(await Gt())),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=pw(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:l}=await e.runs.start(a),c=new URL(`/runs/${l}`,s.req.url).href;return s.json({id:l,url:c},202)}catch(l){if(l instanceof ua)return s.json({error:l.message,...l.activeRunId?{activeRunId:l.activeRunId}:{}},409);let c=l instanceof Error?l.message:String(l);return s.json({error:c},l instanceof xe?400:500)}}),t.get("/:id",async(s)=>{let o=s.req.param("id"),a=await n(o);if(a instanceof Un)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(!hw(o))return s.json(r(o),404);try{let a=await TA(NA.join(yt(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"),l=s.req.query("path");if(a!=="base"&&a!=="head"||!l)return s.json({error:"side=base|head and path are required"},400);let c=await n(o);if(!c)return s.json(r(o),404);if(c instanceof Un)return s.json({error:c.message},422);let u=c.files.find((R)=>R.path===l);if(!u)return s.json({error:`${l} is not part of run ${o}`},404);if(a==="base"&&u.status==="added"||a==="head"&&u.status==="removed")return s.json({error:`${l} does not exist on the ${a} side`},404);if(u.isBinary)return s.json({error:`${l} is a binary file`},415);let d=a==="base"?c.base:c.head,f=a==="base"?u.previousPath??u.path:u.path,p=`${d}:${f}`,h=await te("git",["-C",c.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())>DA)return s.json({error:`${f} is larger than 2 MB`},413);let x=await te("git",["-C",c.repo.root,"show",p],{allowFail:!0});if(x.code!==0)return s.json({error:`cannot read ${p}`},404);return s.text(x.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 fw(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 ds(o)})}),t}import kn from"path";import{existsSync as FA}from"fs";var gw=`<!doctype html>
|
|
534
|
+
<html lang="en">
|
|
535
|
+
<head>
|
|
536
|
+
<meta charset="utf-8">
|
|
537
|
+
<title>DiffLoupe</title>
|
|
538
|
+
<style>
|
|
539
|
+
body { font: 14px/1.4 system-ui, sans-serif; margin: 0; display: flex; height: 100vh; color: #ddd; background: #1b1d21; }
|
|
540
|
+
nav { width: 22rem; overflow: auto; border-right: 1px solid #333; padding: .5rem; }
|
|
541
|
+
main { flex: 1; overflow: auto; padding: .5rem 1rem; }
|
|
542
|
+
a { color: #8cb4ff; text-decoration: none; display: block; padding: .25rem; border-radius: 4px; }
|
|
543
|
+
a.sel { background: #2c3340; }
|
|
544
|
+
.st { font-size: 12px; color: #999; }
|
|
545
|
+
.running { color: #e5c07b; } .complete { color: #98c379; } .failed { color: #e06c75; } .cancelled { color: #999; }
|
|
546
|
+
pre { margin: 0; white-space: pre-wrap; font: 12px/1.5 ui-monospace, monospace; }
|
|
547
|
+
button { margin: .5rem 0; }
|
|
548
|
+
</style>
|
|
549
|
+
</head>
|
|
550
|
+
<body>
|
|
551
|
+
<nav><h3>Runs</h3><div id="runs"></div></nav>
|
|
552
|
+
<main><h3 id="title">No run selected</h3><button id="cancel" hidden>Cancel run</button><pre id="log"></pre></main>
|
|
553
|
+
<script>
|
|
554
|
+
let selected = location.pathname.match(/^\\/runs\\/([^/]+)/)?.[1] ?? null;
|
|
555
|
+
let source = null;
|
|
556
|
+
const $ = (id) => document.getElementById(id);
|
|
557
|
+
const esc = (s) => String(s).replace(/[&<>"]/g, (ch) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[ch]);
|
|
558
|
+
function line(e) {
|
|
559
|
+
if (e.type === "stage") return "\xBB " + e.stage.replaceAll("_", " ");
|
|
560
|
+
if (e.type === "log") return e.message;
|
|
561
|
+
if (e.type === "slice") return " [" + (e.index + 1) + "/" + e.total + "] " + e.status + " " + e.title + (e.costUsd != null ? " $" + e.costUsd.toFixed(2) : "");
|
|
562
|
+
if (e.type === "budget") return " cost limit reached at $" + e.totalUsd.toFixed(2) + "; " + e.skippedSlices + " slice(s) not started";
|
|
563
|
+
if (e.type === "done" && e.noChanges) return "No code changes to review.";
|
|
564
|
+
if (e.type === "done") return (e.carriedOver ? (e.findings - e.carriedOver) + " new finding(s), " + e.carriedOver + " carried over" : e.findings + " finding(s)") + " \xB7 $" + e.costUsd.toFixed(2) + " \xB7 " + Math.round(e.wallMs / 1000) + "s";
|
|
565
|
+
if (e.type === "cancelled") return "Cancelled.";
|
|
566
|
+
if (e.type === "error") return "Failed: " + e.message;
|
|
567
|
+
return null;
|
|
568
|
+
}
|
|
569
|
+
async function loadRuns() {
|
|
570
|
+
const [runs, health] = await Promise.all([fetch("/api/runs").then((r) => r.json()), fetch("/api/health").then((r) => r.json())]);
|
|
571
|
+
if (!selected) selected = health.activeRunId ?? runs[0]?.id ?? null;
|
|
572
|
+
$("runs").innerHTML = runs.map((r) => '<a href="/runs/' + esc(r.id) + '" class="' + (r.id === selected ? "sel" : "") + '">' + esc(r.id) +
|
|
573
|
+
'<div class="st"><span class="' + esc(r.status) + '">' + esc(r.status) + "</span> \xB7 " + esc(Object.values(r.findingCounts ?? {}).reduce((a, b) => a + b, 0)) + " finding(s) \xB7 $" + (r.costUsd ?? 0).toFixed(2) + "</div></a>").join("");
|
|
574
|
+
$("cancel").hidden = !selected || health.activeRunId !== selected;
|
|
575
|
+
return health;
|
|
576
|
+
}
|
|
577
|
+
function follow(id) {
|
|
578
|
+
if (source) source.close();
|
|
579
|
+
$("log").textContent = "";
|
|
580
|
+
$("title").textContent = id;
|
|
581
|
+
source = new EventSource("/api/runs/" + encodeURIComponent(id) + "/events");
|
|
582
|
+
source.onmessage = () => {};
|
|
583
|
+
for (const type of ["stage", "log", "slice", "budget", "done", "cancelled", "error"]) {
|
|
584
|
+
source.addEventListener(type, (m) => {
|
|
585
|
+
const text = line(JSON.parse(m.data));
|
|
586
|
+
if (text != null) $("log").textContent += text + "\\n";
|
|
587
|
+
if (type === "done" || type === "cancelled" || type === "error") loadRuns();
|
|
588
|
+
});
|
|
589
|
+
}
|
|
590
|
+
source.addEventListener("end", () => source.close());
|
|
591
|
+
}
|
|
592
|
+
$("cancel").onclick = () => fetch("/api/runs/" + encodeURIComponent(selected) + "/cancel", { method: "POST" });
|
|
593
|
+
loadRuns().then(() => { if (selected) follow(selected); });
|
|
594
|
+
setInterval(loadRuns, 5000);
|
|
595
|
+
</script>
|
|
596
|
+
</body>
|
|
597
|
+
</html>
|
|
598
|
+
`;function _w(e=import.meta.dir){let t=process.env.DIFFLOUPE_WEB_DIR;if(t)return kn.resolve(t);for(let n of[kn.join(e,"web"),kn.resolve(e,"../../dist/web")])if(FA(kn.join(n,"index.html")))return n;return null}async function yw(e,t){if(!t)return e.html(gw,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=kn.resolve(t),s=kn.resolve(r,`.${n}`);if(s!==r&&!s.startsWith(r+kn.sep))return e.text("not found",404);if(s!==r&&!n.endsWith("/")){let a=Bun.file(s);if(await a.exists()){let l=n.startsWith("/assets/");return new Response(a,{headers:{"Cache-Control":l?"public, max-age=31536000, immutable":"no-cache"}})}if(kn.extname(n))return e.text("not found",404)}let o=Bun.file(kn.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,Bn="127.0.0.1",LA=10;function jA(e,t=Mu(Bn)){let n=new dr;return n.use("*",aw(t)),n.use("*",lw()),n.route("/api/health",cw(e)),n.route("/api/runs",mw(e)),n.all("/api/*",(r)=>r.json({error:"not found"},404)),n.get("*",(r)=>yw(r,e.webDir)),n}function UA(e){let t=e;return t?.code==="EADDRINUSE"||/address already in use|EADDRINUSE|port .* in use/i.test(t?.message??"")}function BA(e,t){if(As(e)||e==="0.0.0.0"||e==="::")return`http://localhost:${t}`;return`http://${e.includes(":")?`[${e}]`:e}:${t}`}async function Du(e){let t=e.host??Bn,n=e.port??fr,r=e.log??((f)=>console.error(f)),[s,o]=await Promise.all([tw(),nw()]);await rw(e.defaultRepo,r);let a={version:Ls,defaultRepo:e.defaultRepo,dataDir:Vt(),webDir:_w(),gh:s,opencode:o,runs:new xs(ca(e.defaultRepo??process.cwd()))},l=Mu(t),c=jA(a,l),u=e.strictPort?n:Math.min(n+LA,65535),d;for(let f=n;f<=u;f++)try{let p=Bun.serve({hostname:t,port:f,fetch:c.fetch,idleTimeout:0});if(!As(t))r(`Warning: listening on ${t}; anyone who can reach this machine on port ${f} can start reviews.`);return{ctx:a,url:BA(t,f),port:f,stop:()=>p.stop(!0)}}catch(p){if(!UA(p))throw p;d=p}throw Error(`no free port in ${n}-${u}: ${d instanceof Error?d.message:String(d)}`)}async function qA(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 Fu(e){let t=Array.from({length:11},(r,s)=>e+s).filter((r)=>r<=65535),n=await Promise.all(t.map(qA));return t.flatMap((r,s)=>{let o=n[s];return o?[{base:`http://localhost:${r}`,port:r,health:o}]:[]})}class xa extends Error{status;constructor(e,t){super(e);this.status=t;this.name="ServerRequestError"}}async function ww(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 xa("error"in r?r.error:`HTTP ${n.status}`,n.status);return r}async function bw(e,t){try{return(await fetch(`${e}/api/runs/${encodeURIComponent(t)}/cancel`,{method:"POST"})).ok}catch{return!1}}async function vw(e,t,n){let r=null,s=0;for(let o=0;o<5&&!r;o++){let a;try{a=await fetch(`${e}/api/runs/${encodeURIComponent(t)}/events?after=${s}`)}catch{await Bun.sleep(500);continue}if(!a.ok||!a.body)return null;let l=!1;for await(let c of HA(a.body)){if(c.event==="end"){l=!0;break}if(!c.data)continue;let u=JSON.parse(c.data);if(s=u.seq,n(u),u.type==="done"||u.type==="cancelled"||u.type==="error")r=u}if(l)break}return r}async function*HA(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(`
|
|
599
|
+
`))>=0){let l=n.slice(0,a).replace(/\r$/,"");if(n=n.slice(a+1),l===""){if(s.length)yield{event:r,data:s.join(`
|
|
600
|
+
`)};else if(r!=="message")yield{event:r,data:""};r="message",s=[]}else if(l.startsWith(":"))continue;else{let c=l.indexOf(":"),u=c<0?l:l.slice(0,c),d=c<0?"":l.slice(c+1).replace(/^ /,"");if(u==="event")r=d;else if(u==="data")s.push(d)}}}}var xw=1e4;function kw(e,t){return[...t,e]}function ka(e){let t=Number(e);if(!Number.isInteger(t)||t<1||t>65535)throw new pi("must be a port number 1-65535");return t}function WA(e){let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new pi("must be a positive number of US dollars");return t}function Ne(e){console.error(e)}function Rw(e){let t=vs(e);if(t)Ne(t)}async function $w(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 Ra(e){let t=await gr();return{host:e.host??t.host??Bn,port:e.port??t.port??fr}}async function $a(e,t){if(t&&!await Cy(e))Ne(`Could not open a browser; visit ${e}`)}function Sa(e,t){return`${e}/runs/${t}`}async function VA(e,t){let n;try{({id:n}=await ww(e,await ws(t)))}catch(a){if(a instanceof xa&&a.status===409)return-1;return Ne(ln.default.red(`Error: ${a instanceof Error?a.message:String(a)}`)),1}let r=Sa(e,n);Ne(`DiffLoupe ready at ${r} (running on the server already at ${e})`),await $a(r,t.open);let s=ks(()=>{Ne(`
|
|
601
|
+
Cancelling the run (Ctrl+C again to stop following it)...`),bw(e,n)}),o=await vw(e,n,Rw);if(s(),o?.type==="done")return Ne(`Results: ${r}`),0;return o?.type==="cancelled"?130:1}async function GA(e){let t=await ws(e),{host:n,port:r}=await Ra(e),s;try{s=await Du({host:n,port:r,defaultRepo:await $w(t.repo??process.cwd())??null,log:Ne})}catch(f){return Ne(ln.default.red(`Error starting server: ${f instanceof Error?f.message:String(f)}`)),1}let o=s.ctx.runs;o.watch((f,p)=>Rw(p));let a;try{a=await o.start(t)}catch(f){return Ne(ln.default.red(`Error: ${f instanceof Error?f.message:String(f)}`)),await s.stop(),1}let l=Sa(s.url,a.id);Ne(ln.default.green(`DiffLoupe ready at ${l}`)),await $a(l,e.open);let c=!0,u=!1;ks(()=>{if(!c)process.exit(0);u=!0,Ne(`
|
|
602
|
+
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(xw)]).then(()=>process.exit(130))});let d=await a.done;if(c=!1,u)return new Promise(()=>{});if(d.status==="complete")Ne(`Results: ${l}`);else if(d.status==="failed")Ne(`Results (failed run): ${l}`);return Ne(ln.default.dim("Server still running. Press Ctrl+C to stop.")),new Promise(()=>{})}async function Sw(e,t){let n={...t,...e?{target:e}:{}};if(n.headless)process.exit(await Ay(n));let{port:r}=await Ra(n);for(let s of await Fu(r)){if(s.health.activeRunId)continue;let o=await VA(s.base,n);if(o>=0)process.exit(o)}process.exit(await GA(n))}var Ew="worktree (default), staged, a commit (<sha>, HEAD~2, commit:<rev>), a range (<a>..<b>, <a>...<b>), branch:<name>, #<pr>, pr:<n>, or a PR URL";function Aw(){return new Ft("review").description("Review changes with the multi-agent reviewer (requires opencode, tilth, git; gh for PRs)").argument("[target]",Ew).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 (repeatable)",kw,[]).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)").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)",WA).option("--host <host>",`Address for the server to listen on (default: ${Bn})`).option("--port <port>",`Port for the server (default: ${fr}, or the next free one)`,ka).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(Sw)}function Cw(){return new Ft("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]",Ew).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",kw,[]).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: ${Bn})`).option("--port <port>",`Port for the server (default: ${fr}, or the next free one)`,ka).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)=>Sw(e,{...t,kind:"diff"}))}function Iw(){return new Ft("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: ${Bn})`).option("--port <port>",`Port to look for a server on (default: ${fr})`,ka).option("--open","Open the URL in a browser",!1).action(async(e,t)=>{let n=e;if(!n&&t.last){if(n=(await Gt())[0]?.id,!n)Ne("No saved runs."),process.exit(1)}let{host:r,port:s}=await Ra(t),o=(await Fu(s))[0];if(o){let a=n?Sa(o.base,n):o.base;console.log(a),await $a(a,t.open),process.exit(0)}await Ow({...t,host:r,port:s},n)})}async function Ow(e,t){let n=KA.resolve(e.repo??process.cwd()),r;try{r=await Du({host:e.host,port:e.port,defaultRepo:await $w(n),log:Ne})}catch(o){Ne(ln.default.red(`Error starting server: ${o instanceof Error?o.message:String(o)}`)),process.exit(1)}let s=t?Sa(r.url,t):r.url;return Ne(ln.default.green(`DiffLoupe ready at ${s}`)),Ne(ln.default.dim("Press Ctrl+C to stop.")),r.ctx.runs.watch((o,a)=>{let l=vs(a);if(l)Ne(`${ln.default.dim(o)} ${l}`)}),ks(()=>{let o=r.ctx.runs.activeRunId;if(!o)process.exit(0);Ne(`
|
|
603
|
+
Cancelling the active run (Ctrl+C again to exit now)...`);let a=r.ctx.runs.cancel(o)??Promise.resolve();Promise.race([a,Bun.sleep(xw)]).then(()=>process.exit(130))}),await $a(s,e.open),r}function Pw(){return new Ft("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: ${Bn})`).option("--port <port>",`Port (default: ${fr}, or the next free one)`,ka).option("--open","Open the server in a browser",!1).action(async(e)=>{await Ow({...e,...await Ra(e)})})}import{rm as YA}from"fs/promises";var Cs=Ba(Bs(),1);var Mw=["blocker","should-fix","nice-to-have","question"],zA={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 JA(e){let t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return n>0?zA[t.slice(n+1).toLowerCase()]??"":""}function Lu(e,t){return t&&t!==e?`${e}-${t}`:`${e}`}function XA(e){let t=e.side==="deletions"?" (old)":"";if(e.kind==="file")return e.cited.line>0?`${e.file}:${Lu(e.cited.line,e.cited.endLine)}`:e.file;if(e.kind==="nearby")return`${e.file}:${Lu(e.cited.line,e.cited.endLine)}${t}`;return`${e.file}:${Lu(e.line,e.endLine)}${t}`}function Tw(e){let t=[`### [${e.severity}] ${e.title}`,Or(XA(e.anchor))],n=[e.carriedFrom&&`Open since run ${e.carriedFrom}.`,e.repeatOf!==void 0&&`Repeats PR comment #${e.repeatOf}.`].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(Ai(e.suggestedCode,JA(e.file)))}else if(e.suggestion?.trim())t.push(`**Suggestion:** ${e.suggestion.trim()}`);return t.join(`
|
|
604
|
+
|
|
605
|
+
`)}function Nw(e){return[...e].sort((t,n)=>Mw.indexOf(t.severity)-Mw.indexOf(n.severity)||t.file.localeCompare(n.file)||t.anchor.line-n.anchor.line)}function Dw(e,t={}){let n=[`# Review findings: ${ri(e.target)}`,`Base ${Or(e.base.slice(0,12))}, head ${Or(e.head.slice(0,12))}`];if(e.findings.length===0)n.push("No findings.");for(let r of Nw(e.findings))n.push(Tw(r));if(t.includeOverCap&&e.overCapFindings.length){n.push(`## Over the posting cap (${e.overCapFindings.length})`);for(let r of Nw(e.overCapFindings))n.push(Tw(r))}return`${n.join(`
|
|
606
|
+
|
|
607
|
+
`)}
|
|
608
|
+
`}async function ZA(e){try{return await xn(e)}catch(t){console.error(Cs.default.red(`No run.json for ${e}: ${t instanceof Error?t.message:String(t)}`)),process.exit(1)}}function jw(){let e=new Ft("runs").description("List saved runs").option("--json","Print run headers as JSON",!1).option("--kind <kind>","Only review or diff runs",Fw).action(async(t)=>{let n=Lw(await Gt(),t.kind);console.log(t.json?JSON.stringify(n,null,2):by(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 ZA(t);if(n.markdown){process.stdout.write(Dw(r,{includeOverCap:n.overCap}));return}console.log(n.json?JSON.stringify(r,null,2):ky(r))}),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 ds(t);if(n.length===0)console.error(Cs.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)",Fw).option("--yes","Delete instead of listing",!1).action(async(t)=>{let n=eC(t.olderThan),r=Number(t.keep);if(n===null||!Number.isInteger(r)||r<0)console.error(Cs.default.red("--older-than takes a number with d, h, or w; --keep takes a whole number")),process.exit(1);let s=s_(Lw(await Gt(),t.kind),{olderThanMs:n,keep:r}),o=await o_();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(Cs.default.dim("Run again with --yes to delete."));return}for(let a of s)await ds(a.id),console.log(`deleted run ${a.id}`);for(let a of o)await YA(a,{recursive:!0,force:!0});if(o.length>0)console.log(`deleted ${o.length} orphaned scratch entries`)}),e}function Fw(e){if(e!=="review"&&e!=="diff")throw new pi("must be review or diff");return e}function Lw(e,t){return t?e.filter((n)=>(n.kind??"review")===t):e}var QA={h:3600000,d:86400000,w:604800000};function eC(e){let t=/^(\d+)([hdw])$/.exec(e.trim());return t?Number(t[1])*QA[t[2]]:null}var qn=new Ft;qn.name("diffloupe").description("Grouped diffs and multi-agent code review for local changes and pull requests").version(Ls);qn.addCommand(Aw());qn.addCommand(Cw());qn.addCommand(Iw());qn.addCommand(Pw());qn.addCommand(jw());qn.addCommand(gy());function Uw(){qn.parseAsync()}Uw();
|