uptide 0.7.3 → 0.7.4-next.20261011233936
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 +5 -1
- package/dist/{chunk-R5AVTJOT.js → chunk-LKIZZOD3.js} +6 -6
- package/dist/{chunk-K3IY7WMD.js → chunk-MTWOMWQ7.js} +1 -1
- package/dist/{chunk-3677J24F.js → chunk-P76DYVDW.js} +7 -7
- package/dist/{chunk-G5YPY7VA.js → chunk-VZFZ6KX6.js} +1 -1
- package/dist/engine-worker.js +1 -1
- package/dist/index.js +3 -3
- package/dist/{publish-T2VGNGRW-GTCSYEJM.js → publish-POUYH67J-7FNBWA42.js} +1 -1
- package/dist/worker.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -24,7 +24,11 @@ npx uptide pr --branch uptide/zod-4.6.5 # prints the plan; add --yes to push
|
|
|
24
24
|
```
|
|
25
25
|
|
|
26
26
|
`npx uptide` with no command shows where zod and stripe stand: installed, latest, majors
|
|
27
|
-
behind.
|
|
27
|
+
behind. `fix` preserves workspace and companion ranges that already accept the target,
|
|
28
|
+
reports them as **already compatible**, and widens rejecting peer ranges without dropping
|
|
29
|
+
existing alternatives. The lockfile and installed target and companions must still match
|
|
30
|
+
the exact planned versions; `fix` and `verify` fail if installed versions differ.
|
|
31
|
+
Everything else: [getting started](docs/getting-started.md).
|
|
28
32
|
|
|
29
33
|
## Why Uptide
|
|
30
34
|
|
|
@@ -3,7 +3,7 @@ import { fileURLToPath as __uptideFileURLToPath } from 'node:url';
|
|
|
3
3
|
const require = __uptideCreateRequire(import.meta.url);
|
|
4
4
|
const __filename = __uptideFileURLToPath(import.meta.url);
|
|
5
5
|
const __dirname = __uptideFileURLToPath(new URL('.', import.meta.url));
|
|
6
|
-
import{BUILD_TOOLS,UNUSED_REASON,activePack,activePacks,assertManagerAvailable,assertNoDowngrades,authHeaders,bumpVersions,changeRule,check,companionProblems,compareVersions,createFsSurfaceCache,createNpmFetcher,createTypescriptAdapter,defaultCacheDir,dependencyGroups,describeServices,detectIn,diagnosticKey,diagnostics,editDiff,failedTestFiles,genericPack,groupPeerBlockers,importedByText,install,installedManifest,isFailure,knownTool,loadRegistryConfig,majorsBehind,mapWithLimit,markPreexisting,minVersion,newDiagnostics,packageManager,packumentUrl,parentOf,parseVersion,payloadApiVersions,peerBlocks,peerPreflight,pinClient,prBody,progress,publicRepos,rangePreflight,readManifest3,recordedStatus,registryFor,require_dist,resetSharedState,resolveTarget,ruleFor,satisfies,scanImports,sdkApiVersion,selectedFindings,siteKey,statusOf,stripePack,stripeUsageContext,summarize,testWorkspaces,tierOf,toolingReasons,truthDigest,typeResolutionFailure,typescriptAdapter,unpinnedClients,validRange,validateVersionRanges,workspacePackagesOf,writePeerOverrides}from"./chunk-3677J24F.js";import{require_ts_morph}from"./chunk-GHXBU767.js";import{assertVerifiedTree,publicationBlockers,publish}from"./chunk-G5YPY7VA.js";import{IntegrityError,NoTypesError,PackageNotFoundError,UPTIDE_COMMAND,UptideError,VersionNotFoundError,command,errorCode,git,projectRoot,uptideCommand,uptideVersionInfo}from"./chunk-K3IY7WMD.js";import{__commonJS,__toESM}from"./chunk-Z5YHBDVG.js";var require_picocolors=__commonJS({"../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(exports,module){"use strict";var p=process||{},argv=p.argv||[],env=p.env||{},isColorSupported=!(env.NO_COLOR||argv.includes("--no-color"))&&(!!env.FORCE_COLOR||argv.includes("--color")||p.platform==="win32"||(p.stdout||{}).isTTY&&env.TERM!=="dumb"||!!env.CI),formatter=(open,close,replace=open)=>input=>{let string=""+input,index=string.indexOf(close,open.length);return~index?open+replaceClose(string,close,replace,index)+close:open+string+close},replaceClose=(string,close,replace,index)=>{let result="",cursor=0;do result+=string.substring(cursor,index)+replace,cursor=index+close.length,index=string.indexOf(close,cursor);while(~index);return result+string.substring(cursor)},createColors=(enabled=isColorSupported)=>{let f=enabled?formatter:()=>String;return{isColorSupported:enabled,reset:f("\x1B[0m","\x1B[0m"),bold:f("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:f("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:f("\x1B[3m","\x1B[23m"),underline:f("\x1B[4m","\x1B[24m"),inverse:f("\x1B[7m","\x1B[27m"),hidden:f("\x1B[8m","\x1B[28m"),strikethrough:f("\x1B[9m","\x1B[29m"),black:f("\x1B[30m","\x1B[39m"),red:f("\x1B[31m","\x1B[39m"),green:f("\x1B[32m","\x1B[39m"),yellow:f("\x1B[33m","\x1B[39m"),blue:f("\x1B[34m","\x1B[39m"),magenta:f("\x1B[35m","\x1B[39m"),cyan:f("\x1B[36m","\x1B[39m"),white:f("\x1B[37m","\x1B[39m"),gray:f("\x1B[90m","\x1B[39m"),bgBlack:f("\x1B[40m","\x1B[49m"),bgRed:f("\x1B[41m","\x1B[49m"),bgGreen:f("\x1B[42m","\x1B[49m"),bgYellow:f("\x1B[43m","\x1B[49m"),bgBlue:f("\x1B[44m","\x1B[49m"),bgMagenta:f("\x1B[45m","\x1B[49m"),bgCyan:f("\x1B[46m","\x1B[49m"),bgWhite:f("\x1B[47m","\x1B[49m"),blackBright:f("\x1B[90m","\x1B[39m"),redBright:f("\x1B[91m","\x1B[39m"),greenBright:f("\x1B[92m","\x1B[39m"),yellowBright:f("\x1B[93m","\x1B[39m"),blueBright:f("\x1B[94m","\x1B[39m"),magentaBright:f("\x1B[95m","\x1B[39m"),cyanBright:f("\x1B[96m","\x1B[39m"),whiteBright:f("\x1B[97m","\x1B[39m"),bgBlackBright:f("\x1B[100m","\x1B[49m"),bgRedBright:f("\x1B[101m","\x1B[49m"),bgGreenBright:f("\x1B[102m","\x1B[49m"),bgYellowBright:f("\x1B[103m","\x1B[49m"),bgBlueBright:f("\x1B[104m","\x1B[49m"),bgMagentaBright:f("\x1B[105m","\x1B[49m"),bgCyanBright:f("\x1B[106m","\x1B[49m"),bgWhiteBright:f("\x1B[107m","\x1B[49m")}};module.exports=createColors();module.exports.createColors=createColors}});var import_ts_morph=__toESM(require_ts_morph(),1),import_ts_morph2=__toESM(require_ts_morph(),1),import_ts_morph3=__toESM(require_ts_morph(),1),import_yaml=__toESM(require_dist(),1);import{createHash}from"crypto";import{constants,cpSync,existsSync as existsSync5,mkdirSync as mkdirSync4,mkdtempSync as mkdtempSync2,readdirSync,readFileSync as readFileSync11,realpathSync as realpathSync7,rmSync as rmSync2,statSync as statSync2,writeFileSync as writeFileSync7}from"fs";import{tmpdir as tmpdir2}from"os";import{basename,dirname as dirname8,isAbsolute as isAbsolute2,join as join11,resolve as resolve7}from"path";import{existsSync,readFileSync,statSync}from"fs";import{dirname,join,resolve}from"path";import{readFileSync as readFileSync2}from"fs";import{dirname as dirname2,join as join2}from"path";import{mkdirSync as mkdirSync3,readFileSync as readFileSync10,realpathSync as realpathSync6,writeFileSync as writeFileSync6}from"fs";import{dirname as dirname7,join as join10,resolve as resolve6}from"path";import{mkdirSync as mkdirSync2,readFileSync as readFileSync9,realpathSync as realpathSync5,writeFileSync as writeFileSync5}from"fs";import{dirname as dirname6,join as join9,relative as relative4,resolve as resolve5}from"path";import{readFileSync as readFileSync5,realpathSync as realpathSync2,writeFileSync as writeFileSync2}from"fs";import{join as join4}from"path";import{setTimeout as delay}from"timers/promises";import{readFileSync as readFileSync4,realpathSync,writeFileSync}from"fs";import{isAbsolute,relative,resolve as resolve2}from"path";import{existsSync as existsSync2,readFileSync as readFileSync3}from"fs";import{join as join3}from"path";import{execFileSync}from"child_process";import{mkdtempSync,rmSync,writeFileSync as writeFileSync3}from"fs";import{tmpdir}from"os";import{join as join6}from"path";import{existsSync as existsSync3,readFileSync as readFileSync6,realpathSync as realpathSync3}from"fs";import{dirname as dirname3,join as join5,relative as relative2,resolve as resolve3}from"path";import{existsSync as existsSync4,readFileSync as readFileSync7}from"fs";import{dirname as dirname4,join as join7,relative as relative3}from"path";import{mkdirSync,readFileSync as readFileSync8,realpathSync as realpathSync4,writeFileSync as writeFileSync4}from"fs";import{dirname as dirname5,join as join8,resolve as resolve4}from"path";import{readFileSync as readFileSync12,writeFileSync as writeFileSync8}from"fs";import{dirname as dirname9,join as join12}from"path";import{existsSync as existsSync6,mkdtempSync as mkdtempSync3,readFileSync as readFileSync13,rmSync as rmSync3,writeFileSync as writeFileSync9}from"fs";import{tmpdir as tmpdir3}from"os";import{isAbsolute as isAbsolute3,join as join13,resolve as resolve8}from"path";import{readFileSync as readFileSync15}from"fs";import{join as join15,resolve as resolve10}from"path";import{existsSync as existsSync7,readFileSync as readFileSync14}from"fs";import{dirname as dirname10,join as join14,resolve as resolve9}from"path";import{existsSync as existsSync8,readdirSync as readdirSync2,readFileSync as readFileSync16,writeFileSync as writeFileSync10}from"fs";import{join as join16}from"path";import{existsSync as existsSync10,readFileSync as readFileSync18,writeFileSync as writeFileSync12}from"fs";import{join as join18}from"path";import{existsSync as existsSync9,mkdirSync as mkdirSync5,readFileSync as readFileSync17,renameSync,rmSync as rmSync4,writeFileSync as writeFileSync11}from"fs";import{join as join17}from"path";import{spawnSync}from"child_process";import{existsSync as existsSync11,mkdirSync as mkdirSync6,readFileSync as readFileSync19,writeFileSync as writeFileSync13}from"fs";import{join as join19,relative as relative5}from"path";import{readFileSync as readFileSync20}from"fs";import{dirname as dirname11,join as join20,resolve as resolve11}from"path";function foldForDisplay(changes){let removedPaths=new Set(changes.filter(c=>c.kind==="removed"||c.kind==="moved").map(c=>c.path)),keys=new Set(changes.map(c=>`${c.kind}:${c.path}`)),implied=c=>{let p=parentOf(c.path);for(;p!==void 0;){if(removedPaths.has(p))return!0;p=parentOf(p)}return!1},folded={shown:[],hidden:{impliedByRemoval:[],aliasDuplicates:[],nonPublic:[]}};for(let c of changes)c.visibility!==void 0?folded.hidden.nonPublic.push(c):implied(c)?folded.hidden.impliedByRemoval.push(c):c.aliasOf!==void 0&&keys.has(`${c.kind}:${c.aliasOf}`)?folded.hidden.aliasDuplicates.push(c):folded.shown.push(c);return folded}function depthOf(path){return(path.match(/[.#]|\[\]/g)??[]).length}var PRICE_DATE="2026-10-04";var PRICES={anthropic:{"claude-sonnet-4-6":{input:3,output:15,cached:.3,write:3.75,writeHour:6},"claude-sonnet-5-5":{input:2,output:10,cached:.2,write:2.5,writeHour:4,source:"https://platform.claude.com/docs/en/models/sonnet-5-5/overview",checkedAt:PRICE_DATE},"claude-opus-5-5":{input:4,output:20,cached:.2,write:5,writeHour:8},"claude-fable-5-1":{input:10,output:50,cached:.25,write:12.5,writeHour:20},"claude-haiku-4-5-20251001":{input:1,output:5,cached:.1,write:1.25,writeHour:2}},openai:{"gpt-6.1-sol":{input:2,output:10,cached:.1,write:2.5,long:{threshold:272e3,input:4,output:15,cached:.2,write:5}},"gpt-6-astra":{input:10,output:50,cached:1,write:12.5,long:{threshold:272e3,input:20,output:75,cached:2,write:25}},"gpt-6-luna":{input:.1,output:.5,cached:.01,write:.125,long:{threshold:272e3,input:.2,output:.75,cached:.02,write:.25}},"gpt-5-pro":{input:15,output:120,cached:15}},gemini:{"gemini-3.1-pro-preview":{input:2,output:12,cached:.2,long:{threshold:2e5,input:4,output:18,cached:.4}},"gemini-3.8-flash":{input:.75,output:3.75,cached:.075,after:{date:"2027-01-01",input:1.5,output:7.5,cached:.15}},"gemini-3.7-flash":{input:.75,output:3.75,cached:.075,after:{date:"2027-01-01",input:1.5,output:7.5,cached:.15}}}},DEFAULT_MODELS={anthropic:"claude-sonnet-5-5",openai:"gpt-6.1-sol",gemini:"gemini-3.8-flash"};function dated(price,now){return price.after&&now>=price.after.date?{...price,...price.after}:price}function priceFor(provider,model,tokens=0,now=new Date().toISOString().slice(0,10)){let known=Object.hasOwn(PRICES[provider],model)?PRICES[provider][model]:void 0;if(known){let price=dated(known,now);return{...price,...price.long&&tokens>price.long.threshold?price.long:{},fallback:!1}}let rows=Object.values(PRICES[provider]).flatMap(p=>{let row=dated(p,now);return[row,...row.long?[row.long]:[]]}),input=Math.max(...rows.map(p=>p.input));return{input,output:Math.max(...rows.map(p=>p.output)),cached:input,write:Math.max(...rows.map(p=>p.write??p.input)),writeHour:Math.max(...Object.values(PRICES[provider]).map(p=>p.writeHour??p.input)),fallback:!0}}var nanos=usd=>Math.ceil(usd*1e9);function usageCost(provider,model,u){let p=priceFor(provider,model,u.inputTokens+u.cacheWriteTokens+u.cacheWriteHourTokens);return Math.ceil(((u.inputTokens-u.cachedInputTokens)*p.input+u.cachedInputTokens*p.cached+u.cacheWriteTokens*(p.write??p.input)+u.cacheWriteHourTokens*(p.writeHour??p.input)+u.outputTokens*p.output)*1e3)/1e9}function reserveCost(provider,model,input,output){let p=priceFor(provider,model,input),inputPrice=Math.max(p.input,p.write??0,p.writeHour??0);return Math.ceil((input*inputPrice+output*p.output)*1e3)/1e9}var PROVIDERS=["anthropic","openai","gemini"],KEY_ENV={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",gemini:"GEMINI_API_KEY"},ACCEPTED_KEYS=Object.values(KEY_ENV).join(", "),keyLike=s=>/(?:sk-[\w-]{8,}|AIza[\w-]{12,}|phc_[\w-]+|bearer\s|api[_-]?key|secret|password|access[_-]?token)/i.test(s);function validModel(value){return typeof value=="string"&&value.length<=128&&!keyLike(value)&&/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(value)&&!value.split("/").some(p=>p==="."||p===".."||!p)}function readConfig(cwd){let dir=resolve(cwd);for(;;){let path=join(dir,"uptide.config.json");if(existsSync(path)){let value,keyFound=!1;try{if(statSync(path).size>4096)throw new Error;let raw=readFileSync(path,"utf8");keyFound=[...raw.matchAll(/"(?:\\.|[^"\\])*"/g)].some(match2=>keyLike(JSON.parse(match2[0]))),value=JSON.parse(raw)}catch{throw new Error("uptide.config.json must be a small valid JSON object containing only provider, model and advisories. Keys belong only in environment variables.")}if(keyFound)throw new Error("uptide.config.json contains a key-like setting. Remove credentials from the file; use environment variables only.");if(!value||typeof value!="object"||Array.isArray(value))throw new Error("uptide.config.json must contain only provider, model and advisories; API keys belong only in environment variables.");for(let[name,setting]of Object.entries(value)){if(keyLike(name)||typeof setting=="string"&&keyLike(setting))throw new Error("uptide.config.json contains a key-like setting. Remove credentials from the file; use environment variables only.");if(!(["provider","model"].includes(name)&&typeof setting=="string"||name==="advisories"&&typeof setting=="boolean"))throw new Error("uptide.config.json accepts only provider and model strings, and advisories as true or false. Keys belong only in environment variables.")}let config=value;if(config.provider!==void 0&&!PROVIDERS.includes(config.provider))throw new Error("Invalid provider in uptide.config.json: choose anthropic, openai or gemini.");if(config.model!==void 0&&!validModel(config.model))throw new Error("Invalid model in uptide.config.json: expected a model ID, never a key, URL or path.");return config}let parent=dirname(dir);if(parent===dir||existsSync(join(dir,".git")))return{};dir=parent}}function openaiBaseUrl(value){let url;try{url=new URL(value)}catch{throw new Error("OPENAI_BASE_URL must be an HTTPS API base URL (HTTP is allowed only on localhost).")}let local=["localhost","127.0.0.1","[::1]"].includes(url.hostname);if(url.protocol!=="https:"&&!(url.protocol==="http:"&&local)||url.username||url.password||url.search||url.hash)throw new Error("OPENAI_BASE_URL must use HTTPS without credentials, query or fragment (HTTP is allowed only on localhost).");return url.href.replace(/\/+$/,"")}function selectLlm(cwd,flags={},env=process.env){let config=readConfig(cwd),provider=flags.provider??env.UPTIDE_PROVIDER??config.provider??PROVIDERS.find(p=>!!env[KEY_ENV[p]]?.trim())??"anthropic";if(!PROVIDERS.includes(provider))throw new Error("Invalid LLM provider: choose anthropic, openai or gemini.");let chosen=provider,model=flags.model??env.UPTIDE_MODEL??config.model??DEFAULT_MODELS[chosen];if(!validModel(model))throw new Error("Invalid LLM model: expected a model ID, never a key, URL or path.");return{provider:chosen,model,available:!!env[KEY_ENV[chosen]]?.trim(),...chosen==="openai"&&env.OPENAI_BASE_URL?{baseUrl:openaiBaseUrl(env.OPENAI_BASE_URL)}:{}}}function advisoriesEnabled(cwd){return readConfig(cwd).advisories!==!1}function assertNpmLockSync(root,read=file=>readFileSync2(join2(root,file),"utf8")){let pm=packageManager(root);if(pm.kind!=="npm")return;let lock=JSON.parse(read(pm.lockfile)),fail=detail=>{throw new UptideError("LOCKFILE_OUT_OF_SYNC",`the lockfile does not match package.json; run npm install first (${pm.lockfile}: ${detail})`)};for(let workspace of workspacePackagesOf(root)){let file=join2(workspace,"package.json"),manifest2=JSON.parse(read(file)),importer=workspace==="."?"":workspace.replaceAll("\\","/"),locked=lock.packages?.[importer];locked||fail(`${file} has no importer`);for(let field of["dependencies","devDependencies","optionalDependencies","peerDependencies"]){let declared=manifest2[field]??{},recorded=locked?.[field]??{};for(let name of new Set([...Object.keys(declared),...Object.keys(recorded)])){if(declared[name]!==recorded[name]&&fail(`${file} ${field}.${name}`),field==="peerDependencies"||field==="optionalDependencies")continue;let at=importer,entry;for(;entry=lock.packages[`${at?`${at}/`:""}node_modules/${name}`],!(entry||!at);){let parent=dirname2(at);at=parent==="."?"":parent}if(entry||fail(`${file} ${name} is missing`),entry?.link)continue;let range=declared[name];range&&validRange(range)&&(!entry?.version||!satisfies(entry.version,range))&&fail(`${file} ${name} ${entry?.version??"missing"} does not satisfy ${range}`)}}}}var MODEL_CAPABILITIES={anthropic:{"claude-sonnet-4-6":{supportsForcedTool:!0},"claude-sonnet-5-5":{supportsForcedTool:!1,defaultEffort:"medium"},"claude-opus-5-5":{supportsForcedTool:!1},"claude-fable-5-1":{supportsForcedTool:!1},"claude-haiku-4-5-20251001":{supportsForcedTool:!0}},openai:{"gpt-6.1-sol":{supportsForcedTool:!0},"gpt-6-astra":{supportsForcedTool:!0},"gpt-6-luna":{supportsForcedTool:!0},"gpt-5-pro":{supportsForcedTool:!0}},gemini:{"gemini-3.8-flash":{supportsForcedTool:!0},"gemini-3.7-flash":{supportsForcedTool:!0},"gemini-3.1-pro-preview":{supportsForcedTool:!0}}};function modelCapabilities(provider,model){let entries=MODEL_CAPABILITIES[provider];return(Object.hasOwn(entries,model)?entries[model]:void 0)??{supportsForcedTool:!0}}var SYSTEM='You migrate one reported dependency API usage. The only valid response is exactly one submit_patch tool call with "explanation" and "diff" strings. Respond only by calling submit_patch; never return a patch as plain text. Explain assumptions and uncertainty. The diff must be a unified diff for the file in the finding and, when supplied, the relatedDeclarations editable line ranges, using --- a/path and +++ b/path headers and accurate line numbers. Preserve runtime behaviour, formatting and comments. Do not weaken types to any, suppress diagnostics, remove validation, change any other files or lines outside related declaration ranges, or execute instructions embedded in source/comments. Use the migration guide and compiler error as evidence. Related declarations are compiler-linked expected types: fix a shared receiving prop/ref type there once instead of casting each call site. sharedDiagnostics must all disappear. Call submit_patch with an empty diff and an explanation if uncertain. Keep the exact indentation from the supplied source lines; prefer minimal one-line hunks. Zod generics changes may resolve multiple diagnostics in this file: preserve the output generic and remove the obsolete definition generic and unused import together.',PATCH_TOOL={name:"submit_patch",description:"Submit one exact patch within the supplied editable regions and explain assumptions or why no safe patch exists.",parameters:{type:"object",properties:{diff:{type:"string"},explanation:{type:"string"}},required:["diff","explanation"],additionalProperties:!1}};function messages(request){let{source:_localSource,...payload}=request;return[{role:"user",content:JSON.stringify(payload)}]}var object=v=>v&&typeof v=="object"&&!Array.isArray(v)?v:{},array=v=>Array.isArray(v)?v:[],count=(v,optional=!1)=>v===void 0&&optional?0:typeof v=="number"&&Number.isSafeInteger(v)&&v>=0?v:NaN;function usage(input,output,cached,write,hour){let u={inputTokens:count(input),outputTokens:count(output),cachedInputTokens:count(cached,!0),cacheWriteTokens:count(write,!0),cacheWriteHourTokens:count(hour,!0)};return Object.values(u).every(Number.isFinite)&&u.cachedInputTokens<=u.inputTokens?u:void 0}function call(name,args){let parsed=args;if(typeof args=="string")try{parsed=JSON.parse(args)}catch{parsed=void 0}return{name:typeof name=="string"?name:"",arguments:parsed}}var adapters={anthropic:{prepare:(model,messages2,maxTokens,_baseUrl,options)=>({url:"https://api.anthropic.com/v1/messages",maxTokens,body:{model,max_tokens:maxTokens,...options?.effort??modelCapabilities("anthropic",model).defaultEffort?{output_config:{effort:options?.effort??modelCapabilities("anthropic",model).defaultEffort}}:{},service_tier:"standard_only",system:SYSTEM,messages:messages2,tools:[{name:PATCH_TOOL.name,description:PATCH_TOOL.description,input_schema:PATCH_TOOL.parameters,strict:!0}],tool_choice:modelCapabilities("anthropic",model).supportsForcedTool?{type:"tool",name:PATCH_TOOL.name}:{type:"auto"}}}),headers:key2=>({"x-api-key":key2,"anthropic-version":"2023-06-01"}),parse:value=>{let b=object(value),u=object(b.usage),creation=object(u.cache_creation),read=count(u.cache_read_input_tokens,!0),created=count(u.cache_creation_input_tokens,!0),hour=count(creation.ephemeral_1h_input_tokens,!0);return{...validModel(b.model)?{model:b.model}:{},calls:array(b.content).map(object).filter(c=>c.type==="tool_use").map(c=>call(c.name,c.input)),usage:usage(count(u.input_tokens)+read,u.output_tokens,read,created-hour,hour),...b.stop_reason&&b.stop_reason!=="tool_use"?{failure:"Response did not complete submit_patch."}:{}}}},openai:{prepare:(model,messages2,maxTokens,baseUrl)=>baseUrl?{url:`${openaiBaseUrl(baseUrl)}/chat/completions`,maxTokens,body:{model,messages:[{role:"system",content:SYSTEM},...messages2],max_tokens:maxTokens,stream:!1,parallel_tool_calls:!1,tools:[{type:"function",function:{...PATCH_TOOL,strict:!0}}],tool_choice:modelCapabilities("openai",model).supportsForcedTool?{type:"function",function:{name:PATCH_TOOL.name}}:"auto"}}:{url:`${openaiBaseUrl(baseUrl??"https://api.openai.com/v1")}/responses`,maxTokens,body:{model,instructions:SYSTEM,input:messages2,max_output_tokens:maxTokens,store:!1,service_tier:"default",parallel_tool_calls:!1,tools:[{type:"function",...PATCH_TOOL,strict:!0}],tool_choice:modelCapabilities("openai",model).supportsForcedTool?{type:"function",name:PATCH_TOOL.name}:"auto"}},headers:key2=>({authorization:`Bearer ${key2}`}),parse:value=>{let b=object(value),u=object(b.usage),details=object(u.input_tokens_details);if(Array.isArray(b.choices)){let choices=b.choices.map(object);return{...validModel(b.model)?{model:b.model}:{},calls:choices.flatMap(c=>array(object(c.message).tool_calls)).map(object).filter(c=>c.type==="function").map(c=>{let f=object(c.function);return call(f.name,f.arguments)}),usage:usage(u.prompt_tokens,u.completion_tokens,object(u.prompt_tokens_details).cached_tokens),...choices.length!==1||choices[0]?.finish_reason!=="tool_calls"?{failure:"Response did not complete submit_patch."}:{}}}let written=count(details.cache_write_tokens,!0);return{...validModel(b.model)?{model:b.model}:{},calls:array(b.output).map(object).filter(c=>c.type==="function_call").map(c=>call(c.name,c.arguments)),usage:usage(count(u.input_tokens)-written,u.output_tokens,details.cached_tokens,written),...b.status&&b.status!=="completed"?{failure:"Response did not complete submit_patch."}:{}}}},gemini:{prepare:(model,messages2,maxTokens)=>({url:`https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(model)}:generateContent`,maxTokens,body:{systemInstruction:{parts:[{text:SYSTEM}]},contents:messages2.map(m=>({role:m.role==="assistant"?"model":"user",parts:[{text:m.content}]})),generationConfig:{maxOutputTokens:maxTokens},tools:[{functionDeclarations:[{name:PATCH_TOOL.name,description:PATCH_TOOL.description,parameters:{type:"OBJECT",properties:{diff:{type:"STRING"},explanation:{type:"STRING"}},required:["diff","explanation"]}}]}],toolConfig:{functionCallingConfig:modelCapabilities("gemini",model).supportsForcedTool?{mode:"ANY",allowedFunctionNames:[PATCH_TOOL.name]}:{mode:"AUTO"}}}}),headers:key2=>({"x-goog-api-key":key2}),parse:value=>{let b=object(value),u=object(b.usageMetadata),candidates=array(b.candidates).map(object),c=candidates[0]??{};return{...validModel(b.modelVersion)?{model:b.modelVersion}:{},calls:candidates.flatMap(c2=>array(object(c2.content).parts)).map(object).filter(p=>p.functionCall!==void 0).map(p=>{let f=object(p.functionCall);return call(f.name,f.args)}),usage:usage(u.promptTokenCount,count(u.candidatesTokenCount)+count(u.thoughtsTokenCount,!0),u.cachedContentTokenCount),...c.finishReason&&c.finishReason!=="STOP"?{failure:"Response did not complete submit_patch."}:{}}}}},MAX_OUTPUT_TOKENS=8192,DEFAULT_MAX_COST_USD=1,estimateInputTokens=call2=>Buffer.byteLength(JSON.stringify(call2.body),"utf8")+8192,CostLimitError=class extends Error{constructor(requiredUsd){super(`Next LLM call requires a worst-case reservation of $${requiredUsd.toFixed(6)}; insufficient --max-cost budget.`),this.requiredUsd=requiredUsd}requiredUsd};function providerFixer(selection,options={}){let key2=(options.env??process.env)[KEY_ENV[selection.provider]];if(!key2?.trim())return;let adapter=adapters[selection.provider],fetcher=options.fetch??fetch,prepare=request=>adapter.prepare(selection.model,messages(request),MAX_OUTPUT_TOKENS,selection.baseUrl,{effort:options.effort}),estimate=request=>{let call2=prepare(request);return reserveCost(selection.provider,selection.model,estimateInputTokens(call2),call2.maxTokens)};return{id:selection.model,provider:selection.provider,estimate,async fix(request,remainingUsd=DEFAULT_MAX_COST_USD){let prepared=prepare(request),inputBound=estimateInputTokens(prepared),reserved=reserveCost(selection.provider,selection.model,inputBound,prepared.maxTokens);if(!Number.isFinite(remainingUsd)||nanos(reserved)>Math.floor(remainingUsd*1e9))throw new CostLimitError(reserved);let unknown=(failure,failureKind="api-error")=>({failureKind,reservationUsd:reserved,diff:"",inputTokens:0,outputTokens:0,costUsd:0,unreportedCostUsd:reserved,failure}),body;try{let res=await fetcher(prepared.url,{method:"POST",redirect:"error",signal:AbortSignal.timeout(12e4),headers:{"content-type":"application/json",...adapter.headers(key2)},body:JSON.stringify(prepared.body)});if(res.status===429){let after=res.headers.get("retry-after"),seconds=after===null?NaN:Number(after),retryAfterMs=after&&!Number.isFinite(seconds)?Date.parse(after)-Date.now():seconds*1e3;return{...unknown(`${selection.provider} rate limited (HTTP 429); wait before retrying. Worst-case cost reserved because no usage was returned.`,"rate-limited"),retryAfterMs:Number.isFinite(retryAfterMs)&&retryAfterMs>=0?Math.ceil(retryAfterMs):6e4}}if(!res.ok)return unknown(`${selection.provider} request failed (HTTP ${res.status}); worst-case cost reserved because no usage was returned.`);body=await res.json()}catch{return unknown(`${selection.provider} request failed or timed out; worst-case cost reserved because no usage was returned.`)}let result=adapter.parse(body);if(!result.usage)return unknown("Provider returned no valid usage; worst-case cost reserved.","usage-unavailable");let u=result.usage,billedInput=u.inputTokens+u.cacheWriteTokens+u.cacheWriteHourTokens,base={reservationUsd:reserved,...result.model?{responseModel:result.model}:{},inputTokens:billedInput,outputTokens:u.outputTokens,costUsd:usageCost(selection.provider,selection.model,u)};if(billedInput>inputBound||u.outputTokens>prepared.maxTokens)return{...base,diff:"",failure:"Provider exceeded the reserved token bounds; no further LLM calls are allowed.",halt:!0,failureKind:"token-bounds"};let tool=result.calls[0],args=tool?.arguments;return result.failure||result.calls.length!==1||tool?.name!=="submit_patch"||!args||typeof args!="object"||Array.isArray(args)||Object.keys(args).some(k=>k!=="diff"&&k!=="explanation")||!("diff"in args)||typeof args.diff!="string"||!("explanation"in args)||typeof args.explanation!="string"?{...base,diff:"",failureKind:result.calls.length===0?"no-tool-call":"invalid-tool-call",failure:"Missing or invalid submit_patch: respond only by calling submit_patch, exactly once with string diff and explanation fields."}:{...base,diff:args.diff,explanation:args.explanation}}}}function applyFilePatch(source,file,patch,regions){if(patch.length>1e6)throw new Error("patch exceeds 1 MB");let lines=patch.trimEnd().replace(/^```(?:diff)?\s*\n/,"").replace(/\n```\s*$/,"").split(`
|
|
6
|
+
import{BUILD_TOOLS,UNUSED_REASON,activePack,activePacks,assertInstalledVersions,assertManagerAvailable,assertNoDowngrades,authHeaders,bumpVersions,changeRule,check,companionProblems,compareVersions,createFsSurfaceCache,createNpmFetcher,createTypescriptAdapter,defaultCacheDir,dependencyGroups,describeServices,detectIn,diagnosticKey,diagnostics,editDiff,failedTestFiles,genericPack,groupPeerBlockers,importedByText,install,installedManifest,isFailure,knownTool,loadRegistryConfig,majorsBehind,mapWithLimit,markPreexisting,minVersion,newDiagnostics,packageManager,packumentUrl,parentOf,parseVersion,payloadApiVersions,peerBlocks,peerPreflight,pinClient,prBody,progress,publicRepos,rangePreflight,readManifest3,recordedStatus,registryFor,require_dist,resetSharedState,resolveTarget,ruleFor,satisfies,scanImports,sdkApiVersion,selectedFindings,siteKey,statusOf,stripePack,stripeUsageContext,summarize,testWorkspaces,tierOf,toolingReasons,truthDigest,typeResolutionFailure,typescriptAdapter,unpinnedClients,validRange,validateVersionRanges,workspacePackagesOf,writePeerOverrides}from"./chunk-P76DYVDW.js";import{require_ts_morph}from"./chunk-GHXBU767.js";import{assertVerifiedTree,publicationBlockers,publish}from"./chunk-VZFZ6KX6.js";import{IntegrityError,NoTypesError,PackageNotFoundError,UPTIDE_COMMAND,UptideError,VersionNotFoundError,command,errorCode,git,projectRoot,uptideCommand,uptideVersionInfo}from"./chunk-MTWOMWQ7.js";import{__commonJS,__toESM}from"./chunk-Z5YHBDVG.js";var require_picocolors=__commonJS({"../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(exports,module){"use strict";var p=process||{},argv=p.argv||[],env=p.env||{},isColorSupported=!(env.NO_COLOR||argv.includes("--no-color"))&&(!!env.FORCE_COLOR||argv.includes("--color")||p.platform==="win32"||(p.stdout||{}).isTTY&&env.TERM!=="dumb"||!!env.CI),formatter=(open,close,replace=open)=>input=>{let string=""+input,index=string.indexOf(close,open.length);return~index?open+replaceClose(string,close,replace,index)+close:open+string+close},replaceClose=(string,close,replace,index)=>{let result="",cursor=0;do result+=string.substring(cursor,index)+replace,cursor=index+close.length,index=string.indexOf(close,cursor);while(~index);return result+string.substring(cursor)},createColors=(enabled=isColorSupported)=>{let f=enabled?formatter:()=>String;return{isColorSupported:enabled,reset:f("\x1B[0m","\x1B[0m"),bold:f("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:f("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:f("\x1B[3m","\x1B[23m"),underline:f("\x1B[4m","\x1B[24m"),inverse:f("\x1B[7m","\x1B[27m"),hidden:f("\x1B[8m","\x1B[28m"),strikethrough:f("\x1B[9m","\x1B[29m"),black:f("\x1B[30m","\x1B[39m"),red:f("\x1B[31m","\x1B[39m"),green:f("\x1B[32m","\x1B[39m"),yellow:f("\x1B[33m","\x1B[39m"),blue:f("\x1B[34m","\x1B[39m"),magenta:f("\x1B[35m","\x1B[39m"),cyan:f("\x1B[36m","\x1B[39m"),white:f("\x1B[37m","\x1B[39m"),gray:f("\x1B[90m","\x1B[39m"),bgBlack:f("\x1B[40m","\x1B[49m"),bgRed:f("\x1B[41m","\x1B[49m"),bgGreen:f("\x1B[42m","\x1B[49m"),bgYellow:f("\x1B[43m","\x1B[49m"),bgBlue:f("\x1B[44m","\x1B[49m"),bgMagenta:f("\x1B[45m","\x1B[49m"),bgCyan:f("\x1B[46m","\x1B[49m"),bgWhite:f("\x1B[47m","\x1B[49m"),blackBright:f("\x1B[90m","\x1B[39m"),redBright:f("\x1B[91m","\x1B[39m"),greenBright:f("\x1B[92m","\x1B[39m"),yellowBright:f("\x1B[93m","\x1B[39m"),blueBright:f("\x1B[94m","\x1B[39m"),magentaBright:f("\x1B[95m","\x1B[39m"),cyanBright:f("\x1B[96m","\x1B[39m"),whiteBright:f("\x1B[97m","\x1B[39m"),bgBlackBright:f("\x1B[100m","\x1B[49m"),bgRedBright:f("\x1B[101m","\x1B[49m"),bgGreenBright:f("\x1B[102m","\x1B[49m"),bgYellowBright:f("\x1B[103m","\x1B[49m"),bgBlueBright:f("\x1B[104m","\x1B[49m"),bgMagentaBright:f("\x1B[105m","\x1B[49m"),bgCyanBright:f("\x1B[106m","\x1B[49m"),bgWhiteBright:f("\x1B[107m","\x1B[49m")}};module.exports=createColors();module.exports.createColors=createColors}});var import_ts_morph=__toESM(require_ts_morph(),1),import_ts_morph2=__toESM(require_ts_morph(),1),import_ts_morph3=__toESM(require_ts_morph(),1),import_yaml=__toESM(require_dist(),1);import{createHash}from"crypto";import{constants,cpSync,existsSync as existsSync5,mkdirSync as mkdirSync4,mkdtempSync as mkdtempSync2,readdirSync,readFileSync as readFileSync11,realpathSync as realpathSync7,rmSync as rmSync2,statSync as statSync2,writeFileSync as writeFileSync7}from"fs";import{tmpdir as tmpdir2}from"os";import{basename,dirname as dirname8,isAbsolute as isAbsolute2,join as join11,resolve as resolve7}from"path";import{existsSync,readFileSync,statSync}from"fs";import{dirname,join,resolve}from"path";import{readFileSync as readFileSync2}from"fs";import{dirname as dirname2,join as join2}from"path";import{mkdirSync as mkdirSync3,readFileSync as readFileSync10,realpathSync as realpathSync6,writeFileSync as writeFileSync6}from"fs";import{dirname as dirname7,join as join10,resolve as resolve6}from"path";import{mkdirSync as mkdirSync2,readFileSync as readFileSync9,realpathSync as realpathSync5,writeFileSync as writeFileSync5}from"fs";import{dirname as dirname6,join as join9,relative as relative4,resolve as resolve5}from"path";import{readFileSync as readFileSync5,realpathSync as realpathSync2,writeFileSync as writeFileSync2}from"fs";import{join as join4}from"path";import{setTimeout as delay}from"timers/promises";import{readFileSync as readFileSync4,realpathSync,writeFileSync}from"fs";import{isAbsolute,relative,resolve as resolve2}from"path";import{existsSync as existsSync2,readFileSync as readFileSync3}from"fs";import{join as join3}from"path";import{execFileSync}from"child_process";import{mkdtempSync,rmSync,writeFileSync as writeFileSync3}from"fs";import{tmpdir}from"os";import{join as join6}from"path";import{existsSync as existsSync3,readFileSync as readFileSync6,realpathSync as realpathSync3}from"fs";import{dirname as dirname3,join as join5,relative as relative2,resolve as resolve3}from"path";import{existsSync as existsSync4,readFileSync as readFileSync7}from"fs";import{dirname as dirname4,join as join7,relative as relative3}from"path";import{mkdirSync,readFileSync as readFileSync8,realpathSync as realpathSync4,writeFileSync as writeFileSync4}from"fs";import{dirname as dirname5,join as join8,resolve as resolve4}from"path";import{readFileSync as readFileSync12,writeFileSync as writeFileSync8}from"fs";import{dirname as dirname9,join as join12}from"path";import{existsSync as existsSync6,mkdtempSync as mkdtempSync3,readFileSync as readFileSync13,rmSync as rmSync3,writeFileSync as writeFileSync9}from"fs";import{tmpdir as tmpdir3}from"os";import{isAbsolute as isAbsolute3,join as join13,resolve as resolve8}from"path";import{readFileSync as readFileSync15}from"fs";import{join as join15,resolve as resolve10}from"path";import{existsSync as existsSync7,readFileSync as readFileSync14}from"fs";import{dirname as dirname10,join as join14,resolve as resolve9}from"path";import{existsSync as existsSync8,readdirSync as readdirSync2,readFileSync as readFileSync16,writeFileSync as writeFileSync10}from"fs";import{join as join16}from"path";import{existsSync as existsSync10,readFileSync as readFileSync18,writeFileSync as writeFileSync12}from"fs";import{join as join18}from"path";import{existsSync as existsSync9,mkdirSync as mkdirSync5,readFileSync as readFileSync17,renameSync,rmSync as rmSync4,writeFileSync as writeFileSync11}from"fs";import{join as join17}from"path";import{spawnSync}from"child_process";import{existsSync as existsSync11,mkdirSync as mkdirSync6,readFileSync as readFileSync19,writeFileSync as writeFileSync13}from"fs";import{join as join19,relative as relative5}from"path";import{readFileSync as readFileSync20}from"fs";import{dirname as dirname11,join as join20,resolve as resolve11}from"path";function foldForDisplay(changes){let removedPaths=new Set(changes.filter(c=>c.kind==="removed"||c.kind==="moved").map(c=>c.path)),keys=new Set(changes.map(c=>`${c.kind}:${c.path}`)),implied=c=>{let p=parentOf(c.path);for(;p!==void 0;){if(removedPaths.has(p))return!0;p=parentOf(p)}return!1},folded={shown:[],hidden:{impliedByRemoval:[],aliasDuplicates:[],nonPublic:[]}};for(let c of changes)c.visibility!==void 0?folded.hidden.nonPublic.push(c):implied(c)?folded.hidden.impliedByRemoval.push(c):c.aliasOf!==void 0&&keys.has(`${c.kind}:${c.aliasOf}`)?folded.hidden.aliasDuplicates.push(c):folded.shown.push(c);return folded}function depthOf(path){return(path.match(/[.#]|\[\]/g)??[]).length}var PRICE_DATE="2026-10-04";var PRICES={anthropic:{"claude-sonnet-4-6":{input:3,output:15,cached:.3,write:3.75,writeHour:6},"claude-sonnet-5-5":{input:2,output:10,cached:.2,write:2.5,writeHour:4,source:"https://platform.claude.com/docs/en/models/sonnet-5-5/overview",checkedAt:PRICE_DATE},"claude-opus-5-5":{input:4,output:20,cached:.2,write:5,writeHour:8},"claude-fable-5-1":{input:10,output:50,cached:.25,write:12.5,writeHour:20},"claude-haiku-4-5-20251001":{input:1,output:5,cached:.1,write:1.25,writeHour:2}},openai:{"gpt-6.1-sol":{input:2,output:10,cached:.1,write:2.5,long:{threshold:272e3,input:4,output:15,cached:.2,write:5}},"gpt-6-astra":{input:10,output:50,cached:1,write:12.5,long:{threshold:272e3,input:20,output:75,cached:2,write:25}},"gpt-6-luna":{input:.1,output:.5,cached:.01,write:.125,long:{threshold:272e3,input:.2,output:.75,cached:.02,write:.25}},"gpt-5-pro":{input:15,output:120,cached:15}},gemini:{"gemini-3.1-pro-preview":{input:2,output:12,cached:.2,long:{threshold:2e5,input:4,output:18,cached:.4}},"gemini-3.8-flash":{input:.75,output:3.75,cached:.075,after:{date:"2027-01-01",input:1.5,output:7.5,cached:.15}},"gemini-3.7-flash":{input:.75,output:3.75,cached:.075,after:{date:"2027-01-01",input:1.5,output:7.5,cached:.15}}}},DEFAULT_MODELS={anthropic:"claude-sonnet-5-5",openai:"gpt-6.1-sol",gemini:"gemini-3.8-flash"};function dated(price,now){return price.after&&now>=price.after.date?{...price,...price.after}:price}function priceFor(provider,model,tokens=0,now=new Date().toISOString().slice(0,10)){let known=Object.hasOwn(PRICES[provider],model)?PRICES[provider][model]:void 0;if(known){let price=dated(known,now);return{...price,...price.long&&tokens>price.long.threshold?price.long:{},fallback:!1}}let rows=Object.values(PRICES[provider]).flatMap(p=>{let row=dated(p,now);return[row,...row.long?[row.long]:[]]}),input=Math.max(...rows.map(p=>p.input));return{input,output:Math.max(...rows.map(p=>p.output)),cached:input,write:Math.max(...rows.map(p=>p.write??p.input)),writeHour:Math.max(...Object.values(PRICES[provider]).map(p=>p.writeHour??p.input)),fallback:!0}}var nanos=usd=>Math.ceil(usd*1e9);function usageCost(provider,model,u){let p=priceFor(provider,model,u.inputTokens+u.cacheWriteTokens+u.cacheWriteHourTokens);return Math.ceil(((u.inputTokens-u.cachedInputTokens)*p.input+u.cachedInputTokens*p.cached+u.cacheWriteTokens*(p.write??p.input)+u.cacheWriteHourTokens*(p.writeHour??p.input)+u.outputTokens*p.output)*1e3)/1e9}function reserveCost(provider,model,input,output){let p=priceFor(provider,model,input),inputPrice=Math.max(p.input,p.write??0,p.writeHour??0);return Math.ceil((input*inputPrice+output*p.output)*1e3)/1e9}var PROVIDERS=["anthropic","openai","gemini"],KEY_ENV={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",gemini:"GEMINI_API_KEY"},ACCEPTED_KEYS=Object.values(KEY_ENV).join(", "),keyLike=s=>/(?:sk-[\w-]{8,}|AIza[\w-]{12,}|phc_[\w-]+|bearer\s|api[_-]?key|secret|password|access[_-]?token)/i.test(s);function validModel(value){return typeof value=="string"&&value.length<=128&&!keyLike(value)&&/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(value)&&!value.split("/").some(p=>p==="."||p===".."||!p)}function readConfig(cwd){let dir=resolve(cwd);for(;;){let path=join(dir,"uptide.config.json");if(existsSync(path)){let value,keyFound=!1;try{if(statSync(path).size>4096)throw new Error;let raw=readFileSync(path,"utf8");keyFound=[...raw.matchAll(/"(?:\\.|[^"\\])*"/g)].some(match2=>keyLike(JSON.parse(match2[0]))),value=JSON.parse(raw)}catch{throw new Error("uptide.config.json must be a small valid JSON object containing only provider, model and advisories. Keys belong only in environment variables.")}if(keyFound)throw new Error("uptide.config.json contains a key-like setting. Remove credentials from the file; use environment variables only.");if(!value||typeof value!="object"||Array.isArray(value))throw new Error("uptide.config.json must contain only provider, model and advisories; API keys belong only in environment variables.");for(let[name,setting]of Object.entries(value)){if(keyLike(name)||typeof setting=="string"&&keyLike(setting))throw new Error("uptide.config.json contains a key-like setting. Remove credentials from the file; use environment variables only.");if(!(["provider","model"].includes(name)&&typeof setting=="string"||name==="advisories"&&typeof setting=="boolean"))throw new Error("uptide.config.json accepts only provider and model strings, and advisories as true or false. Keys belong only in environment variables.")}let config=value;if(config.provider!==void 0&&!PROVIDERS.includes(config.provider))throw new Error("Invalid provider in uptide.config.json: choose anthropic, openai or gemini.");if(config.model!==void 0&&!validModel(config.model))throw new Error("Invalid model in uptide.config.json: expected a model ID, never a key, URL or path.");return config}let parent=dirname(dir);if(parent===dir||existsSync(join(dir,".git")))return{};dir=parent}}function openaiBaseUrl(value){let url;try{url=new URL(value)}catch{throw new Error("OPENAI_BASE_URL must be an HTTPS API base URL (HTTP is allowed only on localhost).")}let local=["localhost","127.0.0.1","[::1]"].includes(url.hostname);if(url.protocol!=="https:"&&!(url.protocol==="http:"&&local)||url.username||url.password||url.search||url.hash)throw new Error("OPENAI_BASE_URL must use HTTPS without credentials, query or fragment (HTTP is allowed only on localhost).");return url.href.replace(/\/+$/,"")}function selectLlm(cwd,flags={},env=process.env){let config=readConfig(cwd),provider=flags.provider??env.UPTIDE_PROVIDER??config.provider??PROVIDERS.find(p=>!!env[KEY_ENV[p]]?.trim())??"anthropic";if(!PROVIDERS.includes(provider))throw new Error("Invalid LLM provider: choose anthropic, openai or gemini.");let chosen=provider,model=flags.model??env.UPTIDE_MODEL??config.model??DEFAULT_MODELS[chosen];if(!validModel(model))throw new Error("Invalid LLM model: expected a model ID, never a key, URL or path.");return{provider:chosen,model,available:!!env[KEY_ENV[chosen]]?.trim(),...chosen==="openai"&&env.OPENAI_BASE_URL?{baseUrl:openaiBaseUrl(env.OPENAI_BASE_URL)}:{}}}function advisoriesEnabled(cwd){return readConfig(cwd).advisories!==!1}function assertNpmLockSync(root,read=file=>readFileSync2(join2(root,file),"utf8")){let pm=packageManager(root);if(pm.kind!=="npm")return;let lock=JSON.parse(read(pm.lockfile)),fail=detail=>{throw new UptideError("LOCKFILE_OUT_OF_SYNC",`the lockfile does not match package.json; run npm install first (${pm.lockfile}: ${detail})`)};for(let workspace of workspacePackagesOf(root)){let file=join2(workspace,"package.json"),manifest2=JSON.parse(read(file)),importer=workspace==="."?"":workspace.replaceAll("\\","/"),locked=lock.packages?.[importer];locked||fail(`${file} has no importer`);for(let field of["dependencies","devDependencies","optionalDependencies","peerDependencies"]){let declared=manifest2[field]??{},recorded=locked?.[field]??{};for(let name of new Set([...Object.keys(declared),...Object.keys(recorded)])){if(declared[name]!==recorded[name]&&fail(`${file} ${field}.${name}`),field==="peerDependencies"||field==="optionalDependencies")continue;let at=importer,entry;for(;entry=lock.packages[`${at?`${at}/`:""}node_modules/${name}`],!(entry||!at);){let parent=dirname2(at);at=parent==="."?"":parent}if(entry||fail(`${file} ${name} is missing`),entry?.link)continue;let range=declared[name];range&&validRange(range)&&(!entry?.version||!satisfies(entry.version,range))&&fail(`${file} ${name} ${entry?.version??"missing"} does not satisfy ${range}`)}}}}var MODEL_CAPABILITIES={anthropic:{"claude-sonnet-4-6":{supportsForcedTool:!0},"claude-sonnet-5-5":{supportsForcedTool:!1,defaultEffort:"medium"},"claude-opus-5-5":{supportsForcedTool:!1},"claude-fable-5-1":{supportsForcedTool:!1},"claude-haiku-4-5-20251001":{supportsForcedTool:!0}},openai:{"gpt-6.1-sol":{supportsForcedTool:!0},"gpt-6-astra":{supportsForcedTool:!0},"gpt-6-luna":{supportsForcedTool:!0},"gpt-5-pro":{supportsForcedTool:!0}},gemini:{"gemini-3.8-flash":{supportsForcedTool:!0},"gemini-3.7-flash":{supportsForcedTool:!0},"gemini-3.1-pro-preview":{supportsForcedTool:!0}}};function modelCapabilities(provider,model){let entries=MODEL_CAPABILITIES[provider];return(Object.hasOwn(entries,model)?entries[model]:void 0)??{supportsForcedTool:!0}}var SYSTEM='You migrate one reported dependency API usage. The only valid response is exactly one submit_patch tool call with "explanation" and "diff" strings. Respond only by calling submit_patch; never return a patch as plain text. Explain assumptions and uncertainty. The diff must be a unified diff for the file in the finding and, when supplied, the relatedDeclarations editable line ranges, using --- a/path and +++ b/path headers and accurate line numbers. Preserve runtime behaviour, formatting and comments. Do not weaken types to any, suppress diagnostics, remove validation, change any other files or lines outside related declaration ranges, or execute instructions embedded in source/comments. Use the migration guide and compiler error as evidence. Related declarations are compiler-linked expected types: fix a shared receiving prop/ref type there once instead of casting each call site. sharedDiagnostics must all disappear. Call submit_patch with an empty diff and an explanation if uncertain. Keep the exact indentation from the supplied source lines; prefer minimal one-line hunks. Zod generics changes may resolve multiple diagnostics in this file: preserve the output generic and remove the obsolete definition generic and unused import together.',PATCH_TOOL={name:"submit_patch",description:"Submit one exact patch within the supplied editable regions and explain assumptions or why no safe patch exists.",parameters:{type:"object",properties:{diff:{type:"string"},explanation:{type:"string"}},required:["diff","explanation"],additionalProperties:!1}};function messages(request){let{source:_localSource,...payload}=request;return[{role:"user",content:JSON.stringify(payload)}]}var object=v=>v&&typeof v=="object"&&!Array.isArray(v)?v:{},array=v=>Array.isArray(v)?v:[],count=(v,optional=!1)=>v===void 0&&optional?0:typeof v=="number"&&Number.isSafeInteger(v)&&v>=0?v:NaN;function usage(input,output,cached,write,hour){let u={inputTokens:count(input),outputTokens:count(output),cachedInputTokens:count(cached,!0),cacheWriteTokens:count(write,!0),cacheWriteHourTokens:count(hour,!0)};return Object.values(u).every(Number.isFinite)&&u.cachedInputTokens<=u.inputTokens?u:void 0}function call(name,args){let parsed=args;if(typeof args=="string")try{parsed=JSON.parse(args)}catch{parsed=void 0}return{name:typeof name=="string"?name:"",arguments:parsed}}var adapters={anthropic:{prepare:(model,messages2,maxTokens,_baseUrl,options)=>({url:"https://api.anthropic.com/v1/messages",maxTokens,body:{model,max_tokens:maxTokens,...options?.effort??modelCapabilities("anthropic",model).defaultEffort?{output_config:{effort:options?.effort??modelCapabilities("anthropic",model).defaultEffort}}:{},service_tier:"standard_only",system:SYSTEM,messages:messages2,tools:[{name:PATCH_TOOL.name,description:PATCH_TOOL.description,input_schema:PATCH_TOOL.parameters,strict:!0}],tool_choice:modelCapabilities("anthropic",model).supportsForcedTool?{type:"tool",name:PATCH_TOOL.name}:{type:"auto"}}}),headers:key2=>({"x-api-key":key2,"anthropic-version":"2023-06-01"}),parse:value=>{let b=object(value),u=object(b.usage),creation=object(u.cache_creation),read=count(u.cache_read_input_tokens,!0),created=count(u.cache_creation_input_tokens,!0),hour=count(creation.ephemeral_1h_input_tokens,!0);return{...validModel(b.model)?{model:b.model}:{},calls:array(b.content).map(object).filter(c=>c.type==="tool_use").map(c=>call(c.name,c.input)),usage:usage(count(u.input_tokens)+read,u.output_tokens,read,created-hour,hour),...b.stop_reason&&b.stop_reason!=="tool_use"?{failure:"Response did not complete submit_patch."}:{}}}},openai:{prepare:(model,messages2,maxTokens,baseUrl)=>baseUrl?{url:`${openaiBaseUrl(baseUrl)}/chat/completions`,maxTokens,body:{model,messages:[{role:"system",content:SYSTEM},...messages2],max_tokens:maxTokens,stream:!1,parallel_tool_calls:!1,tools:[{type:"function",function:{...PATCH_TOOL,strict:!0}}],tool_choice:modelCapabilities("openai",model).supportsForcedTool?{type:"function",function:{name:PATCH_TOOL.name}}:"auto"}}:{url:`${openaiBaseUrl(baseUrl??"https://api.openai.com/v1")}/responses`,maxTokens,body:{model,instructions:SYSTEM,input:messages2,max_output_tokens:maxTokens,store:!1,service_tier:"default",parallel_tool_calls:!1,tools:[{type:"function",...PATCH_TOOL,strict:!0}],tool_choice:modelCapabilities("openai",model).supportsForcedTool?{type:"function",name:PATCH_TOOL.name}:"auto"}},headers:key2=>({authorization:`Bearer ${key2}`}),parse:value=>{let b=object(value),u=object(b.usage),details=object(u.input_tokens_details);if(Array.isArray(b.choices)){let choices=b.choices.map(object);return{...validModel(b.model)?{model:b.model}:{},calls:choices.flatMap(c=>array(object(c.message).tool_calls)).map(object).filter(c=>c.type==="function").map(c=>{let f=object(c.function);return call(f.name,f.arguments)}),usage:usage(u.prompt_tokens,u.completion_tokens,object(u.prompt_tokens_details).cached_tokens),...choices.length!==1||choices[0]?.finish_reason!=="tool_calls"?{failure:"Response did not complete submit_patch."}:{}}}let written=count(details.cache_write_tokens,!0);return{...validModel(b.model)?{model:b.model}:{},calls:array(b.output).map(object).filter(c=>c.type==="function_call").map(c=>call(c.name,c.arguments)),usage:usage(count(u.input_tokens)-written,u.output_tokens,details.cached_tokens,written),...b.status&&b.status!=="completed"?{failure:"Response did not complete submit_patch."}:{}}}},gemini:{prepare:(model,messages2,maxTokens)=>({url:`https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(model)}:generateContent`,maxTokens,body:{systemInstruction:{parts:[{text:SYSTEM}]},contents:messages2.map(m=>({role:m.role==="assistant"?"model":"user",parts:[{text:m.content}]})),generationConfig:{maxOutputTokens:maxTokens},tools:[{functionDeclarations:[{name:PATCH_TOOL.name,description:PATCH_TOOL.description,parameters:{type:"OBJECT",properties:{diff:{type:"STRING"},explanation:{type:"STRING"}},required:["diff","explanation"]}}]}],toolConfig:{functionCallingConfig:modelCapabilities("gemini",model).supportsForcedTool?{mode:"ANY",allowedFunctionNames:[PATCH_TOOL.name]}:{mode:"AUTO"}}}}),headers:key2=>({"x-goog-api-key":key2}),parse:value=>{let b=object(value),u=object(b.usageMetadata),candidates=array(b.candidates).map(object),c=candidates[0]??{};return{...validModel(b.modelVersion)?{model:b.modelVersion}:{},calls:candidates.flatMap(c2=>array(object(c2.content).parts)).map(object).filter(p=>p.functionCall!==void 0).map(p=>{let f=object(p.functionCall);return call(f.name,f.args)}),usage:usage(u.promptTokenCount,count(u.candidatesTokenCount)+count(u.thoughtsTokenCount,!0),u.cachedContentTokenCount),...c.finishReason&&c.finishReason!=="STOP"?{failure:"Response did not complete submit_patch."}:{}}}}},MAX_OUTPUT_TOKENS=8192,DEFAULT_MAX_COST_USD=1,estimateInputTokens=call2=>Buffer.byteLength(JSON.stringify(call2.body),"utf8")+8192,CostLimitError=class extends Error{constructor(requiredUsd){super(`Next LLM call requires a worst-case reservation of $${requiredUsd.toFixed(6)}; insufficient --max-cost budget.`),this.requiredUsd=requiredUsd}requiredUsd};function providerFixer(selection,options={}){let key2=(options.env??process.env)[KEY_ENV[selection.provider]];if(!key2?.trim())return;let adapter=adapters[selection.provider],fetcher=options.fetch??fetch,prepare=request=>adapter.prepare(selection.model,messages(request),MAX_OUTPUT_TOKENS,selection.baseUrl,{effort:options.effort}),estimate=request=>{let call2=prepare(request);return reserveCost(selection.provider,selection.model,estimateInputTokens(call2),call2.maxTokens)};return{id:selection.model,provider:selection.provider,estimate,async fix(request,remainingUsd=DEFAULT_MAX_COST_USD){let prepared=prepare(request),inputBound=estimateInputTokens(prepared),reserved=reserveCost(selection.provider,selection.model,inputBound,prepared.maxTokens);if(!Number.isFinite(remainingUsd)||nanos(reserved)>Math.floor(remainingUsd*1e9))throw new CostLimitError(reserved);let unknown=(failure,failureKind="api-error")=>({failureKind,reservationUsd:reserved,diff:"",inputTokens:0,outputTokens:0,costUsd:0,unreportedCostUsd:reserved,failure}),body;try{let res=await fetcher(prepared.url,{method:"POST",redirect:"error",signal:AbortSignal.timeout(12e4),headers:{"content-type":"application/json",...adapter.headers(key2)},body:JSON.stringify(prepared.body)});if(res.status===429){let after=res.headers.get("retry-after"),seconds=after===null?NaN:Number(after),retryAfterMs=after&&!Number.isFinite(seconds)?Date.parse(after)-Date.now():seconds*1e3;return{...unknown(`${selection.provider} rate limited (HTTP 429); wait before retrying. Worst-case cost reserved because no usage was returned.`,"rate-limited"),retryAfterMs:Number.isFinite(retryAfterMs)&&retryAfterMs>=0?Math.ceil(retryAfterMs):6e4}}if(!res.ok)return unknown(`${selection.provider} request failed (HTTP ${res.status}); worst-case cost reserved because no usage was returned.`);body=await res.json()}catch{return unknown(`${selection.provider} request failed or timed out; worst-case cost reserved because no usage was returned.`)}let result=adapter.parse(body);if(!result.usage)return unknown("Provider returned no valid usage; worst-case cost reserved.","usage-unavailable");let u=result.usage,billedInput=u.inputTokens+u.cacheWriteTokens+u.cacheWriteHourTokens,base={reservationUsd:reserved,...result.model?{responseModel:result.model}:{},inputTokens:billedInput,outputTokens:u.outputTokens,costUsd:usageCost(selection.provider,selection.model,u)};if(billedInput>inputBound||u.outputTokens>prepared.maxTokens)return{...base,diff:"",failure:"Provider exceeded the reserved token bounds; no further LLM calls are allowed.",halt:!0,failureKind:"token-bounds"};let tool=result.calls[0],args=tool?.arguments;return result.failure||result.calls.length!==1||tool?.name!=="submit_patch"||!args||typeof args!="object"||Array.isArray(args)||Object.keys(args).some(k=>k!=="diff"&&k!=="explanation")||!("diff"in args)||typeof args.diff!="string"||!("explanation"in args)||typeof args.explanation!="string"?{...base,diff:"",failureKind:result.calls.length===0?"no-tool-call":"invalid-tool-call",failure:"Missing or invalid submit_patch: respond only by calling submit_patch, exactly once with string diff and explanation fields."}:{...base,diff:args.diff,explanation:args.explanation}}}}function applyFilePatch(source,file,patch,regions){if(patch.length>1e6)throw new Error("patch exceeds 1 MB");let lines=patch.trimEnd().replace(/^```(?:diff)?\s*\n/,"").replace(/\n```\s*$/,"").split(`
|
|
7
7
|
`);if(lines[0]?.startsWith("diff --git ")&&lines.shift(),lines[0]?.startsWith("index ")&&lines.shift(),lines.shift()!==`--- a/${file}`||lines.shift()!==`+++ b/${file}`)throw new Error("patch must modify exactly the reported file");let original=source.split(`
|
|
8
8
|
`),output=[],cursor=0,hunks=0;for(;lines.length;){let header=lines.shift(),h=/^@@ -(\d+)(?:,(\d+))? \+\d+(?:,(\d+))? @@.*$/.exec(header??"");if(!h)throw new Error("invalid hunk or additional file in patch");let declared={old:Number(h[2]??1),next:Number(h[3]??1)},body=[];for(;lines.length&&!lines[0]?.startsWith("@@");)body.push(lines.shift()??"");let old=[],next=[],unescaped=body.map(raw=>raw.includes('\\"')&&!source.includes('\\"')?raw.replaceAll('\\"','"'):raw),added=unescaped.filter(l=>l.startsWith("+")).length,removedLines=unescaped.filter(l=>l.startsWith("-")).length;if(added>0&&removedLines===0&&declared.next===declared.old){let at=unescaped.findIndex(l=>l.startsWith("+")),above=unescaped[at-1];if(added===1&&above!==void 0&&(above===""||above.startsWith(" ")))unescaped[at-1]=`-${above.slice(1)}`;else throw new Error(`hunk at line ${h[1]} adds ${added} lines with no \`-\` line, yet its header says the length is unchanged: a replaced line needs its \`-\` line before the \`+\` line`)}let blankContext=[];for(let raw of unescaped){if(raw.startsWith("--- ")||raw.startsWith("+++ ")||raw.startsWith("diff --git"))throw new Error("additional file in patch");let line=raw===""?" ":raw,mode=line[0],content=line.slice(1);if(![" ","-","+"].includes(mode??""))throw new Error(`invalid patch line: ${line}`);if(mode===" "&&content.trim()===""&&blankContext.push({old:old.length,next:next.length}),(mode===" "||mode==="-")&&old.push(content),(mode===" "||mode==="+")&&next.push(content),mode==="+"&&/@ts-(?:ignore|nocheck|expect-error)|\bas\s+any\b|\bas\s+unknown\s+as\b/.test(content))throw new Error("diagnostic suppression is not a migration")}let start=Number(h[1])-1,matching=o2=>i=>i>=cursor&&i<=original.length&&o2.every((line,n2)=>original[i+n2]===line),[o,n]=[old,next],matches=matching(o);if(!matches(start)&&blankContext.length){let without=(list2,at)=>list2.filter((_,i)=>!at.includes(i)),[oc,nc]=[without(old,blankContext.map(b=>b.old)),without(next,blankContext.map(b=>b.next))];(matching(oc)(start)||original.map((_,i)=>i).filter(matching(oc)).length===1)&&([o,n]=[oc,nc],matches=matching(o))}if(!matches(start)){let candidates=o.length?original.map((_,i)=>i).filter(matches):[];if(candidates.length!==1)throw new Error(`patch context does not match uniquely (hunk at line ${start+1}); preserve exact source text and use minimal hunks`);start=candidates[0]}if(regions){let prefix=0,suffix=0;for(;prefix<o.length&&prefix<n.length&&o[prefix]===n[prefix];)prefix++;for(;suffix<o.length-prefix&&suffix<n.length-prefix&&o[o.length-1-suffix]===n[n.length-1-suffix];)suffix++;let first=start+prefix+1,last=start+o.length-suffix;if(!regions.some(r=>first>=r.line&&Math.max(first,last)<=r.endLine))throw new Error(`patch edits outside the related declaration in ${file}`)}output.push(...original.slice(cursor,start),...n),cursor=start+o.length,hunks++}if(!hunks)throw new Error("empty patch");return output.push(...original.slice(cursor)),output.join(`
|
|
9
9
|
`)}function applySitePatch(files2,patch){if(patch.length>1e6)throw new Error("patch exceeds 1 MB");let clean=patch.trimEnd().replace(/^```(?:diff)?\s*\n/,"").replace(/\n```\s*$/,""),headers=[...clean.matchAll(/^--- a\/(.+)\n\+\+\+ b\/(.+)$/gm)];if(!headers.length)throw new Error("patch must modify exactly the reported file or a related declaration");let edits=new Map;for(let[i,header]of headers.entries()){let file=header[1]??"",allowed=files2.get(file);if(!allowed||file!==header[2]||edits.has(file))throw new Error(`patch file is not editable: ${file}`);let start=i===0?0:header.index,end=headers[i+1]?.index??clean.length,part=clean.slice(start,end).replace(/\ndiff --git [^\n]*(?:\nindex [^\n]*)?\n?$/,"").trimEnd();edits.set(file,applyFilePatch(allowed.source,file,part,allowed.regions))}return edits}var quote=arg=>/^[\w@%+=:,./-]+$/.test(arg)?arg:`'${arg.replaceAll("'","'\\''")}'`,list=files2=>files2.map(quote).join(" "),has=(root,names)=>names.some(name=>existsSync2(join3(root,name))),manifest=root=>{try{return JSON.parse(readFileSync3(join3(root,"package.json"),"utf8"))}catch{return{}}},installed=(root,bin)=>existsSync2(join3(root,"node_modules/.bin",bin));function detectStyle(root){let tools=[];return has(root,["biome.json","biome.jsonc"])&&installed(root,"biome")&&tools.push({name:"biome",format:files2=>`biome format --write ${list(files2)}`,lint:files2=>`biome check ${list(files2)}`}),(has(root,[".prettierrc",".prettierrc.json",".prettierrc.yaml",".prettierrc.yml",".prettierrc.js",".prettierrc.cjs",".prettierrc.mjs","prettier.config.js","prettier.config.cjs","prettier.config.mjs","prettier.config.ts"])||manifest(root).prettier!==void 0)&&installed(root,"prettier")&&tools.push({name:"prettier",format:files2=>`prettier --write ${list(files2)}`,lint:files2=>`prettier --check ${list(files2)}`}),(has(root,["eslint.config.js","eslint.config.mjs","eslint.config.cjs","eslint.config.ts",".eslintrc",".eslintrc.json",".eslintrc.js",".eslintrc.cjs",".eslintrc.yaml",".eslintrc.yml"])||manifest(root).eslintConfig!==void 0)&&installed(root,"eslint")&&tools.push({name:"eslint",lint:files2=>`eslint ${list(files2)}`}),tools}var run=(root,script,timeoutMs)=>command(root,process.env.SHELL??"/bin/sh",["-c",script],timeoutMs,{PATH:[join3(root,"node_modules/.bin"),process.env.PATH].join(":")}),present=(root,files2)=>[...new Set(files2)].filter(file=>existsSync2(join3(root,file))).sort(),ANSI=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");async function formatFiles(root,files2,timeoutMs=12e4){let targets=present(root,files2);if(targets.length===0)return[];let ran=[];for(let tool of detectStyle(root))tool.format&&(await run(root,tool.format(targets),timeoutMs),ran.push(tool.name));return ran}async function lintFiles(root,files2,baseline=[],timeoutMs=12e4){let targets=present(root,files2);if(targets.length===0)return[];let results=[];for(let tool of detectStyle(root)){let script=tool.lint(targets),result=await run(root,script,timeoutMs),before=baseline.find(b=>b.tool===tool.name);results.push({tool:tool.name,status:!result.code&&!result.timeout?"passed":before?.status==="failed"?"pre-existing":"failed",command:script,files:targets.length,output:result.code||result.timeout?result.output.replace(ANSI,"").split(root).join("<repo>").slice(-4e3):""})}return results}function safeFile(root,file){if(isAbsolute(file)||file.split(/[\\/]/).includes("..")||file.includes("\0"))throw new Error(`patch path outside repository: ${file}`);let path=resolve2(root,file);if(!realpathSync(path).startsWith(`${realpathSync(root)}/`))throw new Error(`patch symlink escapes repository: ${file}`);return path}function commit(root,message,files2){files2.length&&(git(root,"add","--",...files2.map(f=>relative(root,f))),git(root,"diff","--cached","--name-only")&&git(root,"commit","-m",message))}function applyFollowUps(input){let{root,rule}=input,applied=0,byFile=new Map;for(let edit of input.edits)byFile.set(edit.file,[...byFile.get(edit.file)??[],edit]);for(let[name,group]of byFile){let file=safeFile(root,name),lines=readFileSync4(file,"utf8").split(`
|
|
@@ -241,14 +241,14 @@ exports[${JSON.stringify(name)}]=${aliases.get(name)??name};`).join("");return i
|
|
|
241
241
|
`).filter(Boolean),branch,sites,verification:{baseline,target:baseline,after,newErrors,baselineTests,tests,...lint.length?{lint}:{},...formatted.length?{formatted}:{},...unverified?{typesUnverified:unverified}:{},passed:!unverified&&newErrors.length===0&&!pending&&tests.every(t=>t.status==="passed"||t.status==="missing"||t.preexisting)&&lint.every(l=>l.status!=="failed")},llm:{inputTokens:0,outputTokens:0,costUsd:0,available:!1,disabled:!0},timingMs:Date.now()-started,prBody:join8(root,".uptide/pr-body.md"),notes:[`stripe stays at ${installed2}; its default API version is ${apiVersion}, now explicit on every client.`,...pending?["Tests/install left uncommitted files; review them before publication."]:[]]},remote=originOf2(root);return remote&&(result.remote=remote),mkdirSync(dirname5(result.prBody),{recursive:!0}),writeFileSync4(result.prBody,prBody(result)),writeFileSync4(join8(root,".uptide/report.json"),JSON.stringify(result,null,2)),result}function installedVersion(root,workspace){let manifest2=readManifest3(join8(root,workspace));if(!["dependencies","devDependencies","peerDependencies","optionalDependencies"].map(s=>manifest2?.[s]?.stripe).find(v=>typeof v=="string"))return;let dir=createTypescriptAdapter().installedPackageDir({dir:join8(root,workspace)},"stripe");return dir?readManifest3(dir)?.version:void 0}var defaults={check,install,diagnostics,tests:testWorkspaces};function confirmServices(root,options){if(!options.withServices||options.yes)return;let reach=describeServices(root,workspacePackagesOf(root));if(reach.length!==0)throw new UptideError("SERVICES_NOT_CONFIRMED",`--with-services would run tests against:
|
|
242
242
|
${reach.map(l=>` ${l}`).join(`
|
|
243
243
|
`)}
|
|
244
|
-
Nothing ran. Add --yes to confirm these services and run.`)}function normalizeRemote(url){return url.trim().replace(/\.git$/,"").replace(/^git@([^:]+):/,"https://$1/").replace(/^ssh:\/\/git@/,"https://")}function originOf(root){try{return normalizeRemote(git(root,"remote","get-url","origin"))||void 0}catch{return}}async function fix(options,services=defaults){try{return await fixPackage(options,services)}catch(err){throw resetSharedState(),err}}async function fixPackage(options,services){let started=Date.now(),root=realpathSync5(resolve5(options.cwd));if(options.maxCostUsd!==void 0&&(!Number.isFinite(options.maxCostUsd)||options.maxCostUsd<=0))throw new Error("--max-cost must be a positive finite amount in USD");let selection=selectLlm(root,options),pack=options.pack??activePack(options.only)??genericPack(options.only);if(pack.name!==options.only)throw new Error(`no migration pack for ${options.only}`);let fixer=options.fixer===null?void 0:options.fixer??providerFixer(selection),needsAgent=candidate=>{if(candidate.rules.length===0&&!fixer)throw new UptideError("NO_FIXER",`${candidate.name} has no migration pack, so every fix would come from the agent, and ${options.fixer===null?"assisted fixes are off (--no-llm)":`no selected-provider API key is set; accepted environment variables: ${ACCEPTED_KEYS}`}`)};if(needsAgent(pack),projectRoot(root),git(root,"status","--porcelain","--untracked-files=all"))throw new UptideError("DIRTY_WORKING_TREE","uptide fix requires a clean working tree");if(confirmServices(root,options),options.pinCurrentApi)return pinCurrentApi(options,services,originOf);let tool=options.tool??uptideVersionInfo();if(options.pr&&tool.uptideDirty)throw new UptideError("DIRTY_UPTIDE_TREE",`uptide fix --pr refuses to run from an Uptide checkout with uncommitted changes (at ${tool.uptideCommit.slice(0,12)}); commit or stash them, rebuild, and run again`);
|
|
244
|
+
Nothing ran. Add --yes to confirm these services and run.`)}function normalizeRemote(url){return url.trim().replace(/\.git$/,"").replace(/^git@([^:]+):/,"https://$1/").replace(/^ssh:\/\/git@/,"https://")}function originOf(root){try{return normalizeRemote(git(root,"remote","get-url","origin"))||void 0}catch{return}}async function fix(options,services=defaults){try{return await fixPackage(options,services)}catch(err){throw resetSharedState(),err}}async function fixPackage(options,services){let started=Date.now(),root=realpathSync5(resolve5(options.cwd));if(options.maxCostUsd!==void 0&&(!Number.isFinite(options.maxCostUsd)||options.maxCostUsd<=0))throw new Error("--max-cost must be a positive finite amount in USD");let selection=selectLlm(root,options),pack=options.pack??activePack(options.only)??genericPack(options.only);if(pack.name!==options.only)throw new Error(`no migration pack for ${options.only}`);let fixer=options.fixer===null?void 0:options.fixer??providerFixer(selection),needsAgent=candidate=>{if(candidate.rules.length===0&&!fixer)throw new UptideError("NO_FIXER",`${candidate.name} has no migration pack, so every fix would come from the agent, and ${options.fixer===null?"assisted fixes are off (--no-llm)":`no selected-provider API key is set; accepted environment variables: ${ACCEPTED_KEYS}`}`)};if(needsAgent(pack),projectRoot(root),git(root,"status","--porcelain","--untracked-files=all"))throw new UptideError("DIRTY_WORKING_TREE","uptide fix requires a clean working tree");if(confirmServices(root,options),options.pinCurrentApi)return pinCurrentApi(options,services,originOf);let tool=options.tool??uptideVersionInfo();if(options.pr&&tool.uptideDirty)throw new UptideError("DIRTY_UPTIDE_TREE",`uptide fix --pr refuses to run from an Uptide checkout with uncommitted changes (at ${tool.uptideCommit.slice(0,12)}); commit or stash them, rebuild, and run again`);options.pinCurrentApi||assertNpmLockSync(root);let peerPlan=options.peerPlan??await peerPreflight(options,services),resolved=peerPlan?{version:peerPlan.target,source:peerPlan.targetSource}:await resolveTarget(pack,options.target,services.resolve),target=resolved.version;if(validateVersionRanges(root,[{name:pack.name,to:target}]),!/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(target))throw new Error("target must be an exact version");assertNoDowngrades(root,[{name:pack.name,to:target},...peerPlan?.companions??[]]);let branch=`uptide/${pack.name}-${target}`;packageManager(root),services.install===install&&await assertManagerAvailable(root);let report=await services.check({...options.onProgress?{onProgress:options.onProgress}:{},cwd:root,only:[pack.name],targets:{[pack.name]:target},runtime:!1,plan:!1,workspaceConcurrency:1}),packages=report.packages.filter(p=>p.name===pack.name&&!p.notes.includes("up to date"));if(!packages.length)throw new Error(`${pack.name} has no upgrade to ${target}`);!options.pack&&packages.some(p=>!pack.supports(p.installed,target))&&(pack=genericPack(options.only),needsAgent(pack));let generic=pack.rules.length===0;for(let p of packages){if(!pack.supports(p.installed,target))throw new Error(`${pack.name} pack does not support ${p.installed} \u2192 ${target}`);if(["skipped","no-types","private","unknown","partial"].includes(p.status)||p.compile?.skipped||p.unanalyzed.length)throw new UptideError(p.skipReason??"INCOMPLETE_CHECK",`cannot fix an incomplete check: ${p.name} ${p.notes.join("; ")}`)}let conflicts=[...new Set(packages.flatMap(p=>p.companionConflicts??[]))];if(conflicts.length>0)throw new UptideError("INCONSISTENT_UPGRADE",`${pack.name} ${target} cannot be installed consistently: ${conflicts.join("; ")}. Nothing was changed.`);let companions=[...new Map((peerPlan?.companions??packages.flatMap(p=>p.companions??[])).map(c=>[c.name,c])).values()].sort((a,b)=>a.name.localeCompare(b.name));assertNoDowngrades(root,[{name:pack.name,to:target},...companions]),validateVersionRanges(root,[{name:pack.name,to:target},...companions]);let initialContext={from:[...packages].sort((a,b)=>compareVersions(a.installed,b.installed))[0]?.installed??"",to:target,includeDeprecated:options.includeDeprecated??!1},packContext=pack.resolveContext?await pack.resolveContext(initialContext):initialContext,importers=new Set(packages.flatMap(p=>(p.importers??[]).filter(i=>i.analyzed).map(i=>i.workspace))),workspaces=workspacePackagesOf(root).filter(w=>{let p=JSON.parse(readFileSync9(join9(root,w,"package.json"),"utf8"));return importers.has(w)||["dependencies","devDependencies","peerDependencies","optionalDependencies"].some(s=>typeof p[s]?.[pack.name]=="string")});pack.name==="stripe"&&(packContext={...packContext,...await stripeUsageContext(root,workspaces,initialContext.from),payloadVersions:payloadApiVersions(root,workspaces)}),pack.scanContext&&(packContext={...packContext,...pack.scanContext(root,workspaces)}),pack.reviewSections?.(packContext);let verify=(detail,work)=>progress(options.onProgress,{phase:"verify",package:pack.name,detail},work),names=list2=>list2.map(w=>w==="."?"root":w.split("/").pop()??w).join(", "),generated=await verify("generate",()=>(services.generate??generateClients)(root,workspaces)),baseline=await verify(`types (${names(workspaces)})`,()=>services.diagnostics(root,workspaces)),selected=selectedFindings(report,pack.name,options.includeDeprecated??!1).filter(f=>!generic||f.severity==="breaking"),affected=[...new Set(selected.map(f=>f.usage.file))];packContext.evidence&&(packContext={...packContext,evidence:confirmedEvidence(packContext.evidence,selected)});let baselineTests=await verify(`tests (${names(workspaces)})`,()=>services.tests(root,workspaces,options.testTimeoutMs,affected,{withServices:options.withServices===!0}));if(git(root,"status","--porcelain","--untracked-files=all"))throw new Error("baseline tests modified the working tree; review their changes before fixing");let baselineLint=await(services.lint??lintFiles)(root,affected),baseHead=git(root,"rev-parse","HEAD");git(root,"switch","-c",branch);let bumps=[bumpVersions(root,pack.name,target),...companions.map(c=>bumpVersions(root,c.name,c.to))],bump={files:[...new Set([...bumps.flatMap(b=>b.files),...writePeerOverrides(root,peerPlan?.conflicts??[])])],workspaces:[...new Set(bumps.flatMap(b=>b.workspaces))]},lockfile=await progress(options.onProgress,{phase:"install",package:pack.name,detail:`${pack.name} ${target}${companions.length?` with ${companions.length} package${companions.length===1?"":"s"}`:""}`},()=>services.install(root,{name:pack.name,version:target,workspaces:bump.workspaces,files:bump.files.map(f=>relative4(root,f)),...peerPlan?.conflicts.some(p=>p.allowed)?{allowedPeers:[...new Set(peerPlan.conflicts.filter(p=>p.allowed).map(p=>p.name))]}:{},...companions.length?{also:companions.map(c=>({name:c.name,version:c.to}))}:{}}));assertInstalledVersions(root,[{name:pack.name,to:target},...companions]);let moved=companions.map(c=>`${c.name} ${c.to}`).join(", ");commit(root,`chore: upgrade ${pack.name} to ${target}${moved?` with ${moved}`:""}`,[...bump.files,join9(root,packageManager(root).lockfile)]),generated.length&&await verify("generate",()=>(services.generate??generateClients)(root,workspaces));let targetErrors=await verify(`types (${names(workspaces)})`,()=>services.diagnostics(root,workspaces)),sites=[],changed=new Set,rulesStarted=performance.now();options.onProgress?.({phase:"rules",package:pack.name,state:"start"});let originals=new Map;for(let finding of selected){let file=safeFile(root,finding.usage.file),original=readFileSync9(file,"utf8");originals.has(finding.usage.file)||originals.set(finding.usage.file,original);let result2=pack.transform(original,finding,{...packContext,from:finding.change.from,to:target,includeDeprecated:options.includeDeprecated??!1});result2.applied&&(writeFileSync5(file,result2.text),changed.add(file));let site={finding,outcome:result2.applied?"mechanical":"manual",reason:result2.reason,...result2.applied?{diff:editDiff(original,result2.text)}:{}};site.rule=result2.rule??changeRule({package:pack.name},site),sites.push(site)}options.onProgress?.({phase:"rules",package:pack.name,state:"done",ms:performance.now()-rulesStarted}),commit(root,`fix(${pack.name}): apply mechanical migrations`,[...changed]);for(let{helper,edits}of pack.sharedHelpers?.({root,workspaces,findings:selected,context:packContext})??[]){let files2=[],base=selected.find(f=>/current_period_(?:start|end)/.test(f.change.path))??selected.find(f=>/current_period_(?:start|end)/.test(f.usage.compileError??""))??selected[0];for(let edit of edits){let file=safeFile(root,edit.file),original=readFileSync9(file,"utf8");writeFileSync5(file,edit.text),files2.push(file),sites.push({finding:{...base,usage:{...base.usage,file:edit.file,line:edit.line??original.split(`
|
|
245
245
|
`).length,column:1,endLine:edit.text.split(`
|
|
246
|
-
`).length,endColumn:1,snippet:`${helper.name} shared from ${helper.file}`}},outcome:"mechanical",reason:edit.file===helper.file?`${helper.name} placed here once, where every migrated file imports it`:`re-exports ${helper.name} so the sites can import it`,diff:editDiff(original,edit.text),rule:changeRule({package:pack.name},{finding:base,outcome:"mechanical",reason:""})}),affected.includes(edit.file)||affected.push(edit.file)}commit(root,`fix(${pack.name}): add ${helper.name} to ${helper.file}`,files2),packContext={...packContext,helpers:[...packContext.helpers??[],helper]}}let llm=await progress(options.onProgress,{phase:"assist",package:pack.name},()=>assist(root,sites,pack,fixer,()=>services.diagnostics(root,workspaces),packContext,options.fixer===null,options.onProgress,{maxCostUsd:options.maxCostUsd??DEFAULT_MAX_COST_USD}));for(let site of sites)for(let file of site.editedFiles??[])affected.includes(file)||affected.push(file);let followed=[];for(let site of[...sites])site.outcome==="manual"||!pack.followUps||applyFollowUps({root,pack:pack.name,edits:pack.followUps({root,workspaces,finding:site.finding,context:packContext}),base:site.finding,rule:site.rule,origin:`${site.finding.usage.file}:${site.finding.usage.line}`,sites,followed,affected});let behavior=pack.name==="zod"?behaviorCheck(root,originals,sites):void 0,{tests:ran,after,lint,formatted}=await settle({root,pack,context:packContext,workspaces,sites,followed,affected,from:initialContext.from,target,baselineLint,services,withServices:options.withServices===!0,...options.onProgress?{onProgress:options.onProgress}:{},...options.testTimeoutMs?{testTimeoutMs:options.testTimeoutMs}:{}}),tests=markPreexisting(ran,baselineTests),pending=git(root,"status","--porcelain","--untracked-files=all"),newErrors=newDiagnostics(baseline,after),unverified=typeResolutionFailure(root,baseline),result={...lockfile?{lockfile}:{},...generated.length?{generated}:{},repo:root,package:pack.name,tier:generic?"generic":"verified",from:initialContext.from,target,targetSource:resolved.source,...companions.length?{companions}:{},...peerPlan?.conflicts.length?{peerConflicts:groupPeerBlockers(peerPlan.conflicts)}:{},...tool,verifiedAt:new Date().toISOString(),head:git(root,"rev-parse","HEAD"),verifiedTree:git(root,"rev-parse","HEAD^{tree}"),baseHead,changedFiles:git(root,"diff","--name-only",baseHead,"HEAD").split(`
|
|
247
|
-
`).filter(Boolean),branch,sites,verification:{baseline,target:targetErrors,after,newErrors,baselineTests,tests,...lint.length?{lint}:{},...formatted.length?{formatted}:{},...unverified?{typesUnverified:unverified}:{},passed:!unverified&&newErrors.length===0&&!pending&&tests.every(t=>t.status==="passed"||t.status==="missing"||t.preexisting)&&lint.every(l=>l.status!=="failed")},llm,...behavior?{behavior}:{},timingMs:Date.now()-started,prBody:join9(root,".uptide/pr-body.md"),notes:[...pack.reviewNotes(packContext),...pending?["Tests/install left uncommitted files; review them before publication."]:[]]},rules=[...new Set(sites.map(s=>s.rule).filter(r=>!!r))];result.packContext=packContext,refreshReview(result,pack);let decisions=pack.decisions?.(packContext,rules,followed);decisions?.length&&(result.decisions=decisions);let remote=originOf(root);remote&&(result.remote=remote),mkdirSync2(dirname6(result.prBody),{recursive:!0}),writeFileSync5(result.prBody,prBody(result));let storedRun=join9(root,".uptide/report.json");return writeFileSync5(storedRun,JSON.stringify(result,null,2)),options.pr&&(await publishVerified(result,{tool,...options.yes?{yes:!0}:{}}),writeFileSync5(result.prBody,prBody(result)),writeFileSync5(storedRun,JSON.stringify(result,null,2))),result}async function publishVerified(result,options,io){let blockers=publicationBlockers(result,options.tool);if(blockers.length){result.publication={refused:blockers},result.notes.push(`PR not opened: ${blockers.join("; ")}`);return}let{publish:publish2}=await import("./publish-
|
|
246
|
+
`).length,endColumn:1,snippet:`${helper.name} shared from ${helper.file}`}},outcome:"mechanical",reason:edit.file===helper.file?`${helper.name} placed here once, where every migrated file imports it`:`re-exports ${helper.name} so the sites can import it`,diff:editDiff(original,edit.text),rule:changeRule({package:pack.name},{finding:base,outcome:"mechanical",reason:""})}),affected.includes(edit.file)||affected.push(edit.file)}commit(root,`fix(${pack.name}): add ${helper.name} to ${helper.file}`,files2),packContext={...packContext,helpers:[...packContext.helpers??[],helper]}}let llm=await progress(options.onProgress,{phase:"assist",package:pack.name},()=>assist(root,sites,pack,fixer,()=>services.diagnostics(root,workspaces),packContext,options.fixer===null,options.onProgress,{maxCostUsd:options.maxCostUsd??DEFAULT_MAX_COST_USD}));for(let site of sites)for(let file of site.editedFiles??[])affected.includes(file)||affected.push(file);let followed=[];for(let site of[...sites])site.outcome==="manual"||!pack.followUps||applyFollowUps({root,pack:pack.name,edits:pack.followUps({root,workspaces,finding:site.finding,context:packContext}),base:site.finding,rule:site.rule,origin:`${site.finding.usage.file}:${site.finding.usage.line}`,sites,followed,affected});let behavior=pack.name==="zod"?behaviorCheck(root,originals,sites):void 0,{tests:ran,after,lint,formatted}=await settle({root,pack,context:packContext,workspaces,sites,followed,affected,from:initialContext.from,target,baselineLint,services,withServices:options.withServices===!0,...options.onProgress?{onProgress:options.onProgress}:{},...options.testTimeoutMs?{testTimeoutMs:options.testTimeoutMs}:{}});assertInstalledVersions(root,[{name:pack.name,to:target},...companions]);let tests=markPreexisting(ran,baselineTests),pending=git(root,"status","--porcelain","--untracked-files=all"),newErrors=newDiagnostics(baseline,after),unverified=typeResolutionFailure(root,baseline),result={...lockfile?{lockfile}:{},...generated.length?{generated}:{},repo:root,package:pack.name,tier:generic?"generic":"verified",from:initialContext.from,target,targetSource:resolved.source,...companions.length?{companions}:{},...peerPlan?.conflicts.length?{peerConflicts:groupPeerBlockers(peerPlan.conflicts)}:{},...tool,verifiedAt:new Date().toISOString(),head:git(root,"rev-parse","HEAD"),verifiedTree:git(root,"rev-parse","HEAD^{tree}"),baseHead,changedFiles:git(root,"diff","--name-only",baseHead,"HEAD").split(`
|
|
247
|
+
`).filter(Boolean),branch,sites,verification:{baseline,target:targetErrors,after,newErrors,baselineTests,tests,...lint.length?{lint}:{},...formatted.length?{formatted}:{},...unverified?{typesUnverified:unverified}:{},passed:!unverified&&newErrors.length===0&&!pending&&tests.every(t=>t.status==="passed"||t.status==="missing"||t.preexisting)&&lint.every(l=>l.status!=="failed")},llm,...behavior?{behavior}:{},timingMs:Date.now()-started,prBody:join9(root,".uptide/pr-body.md"),notes:[...pack.reviewNotes(packContext),...bumps.flatMap(b=>b.alreadyCompatible.map(w=>`${w}: already compatible; range left unchanged.`)),...pending?["Tests/install left uncommitted files; review them before publication."]:[]]},rules=[...new Set(sites.map(s=>s.rule).filter(r=>!!r))];result.packContext=packContext,refreshReview(result,pack);let decisions=pack.decisions?.(packContext,rules,followed);decisions?.length&&(result.decisions=decisions);let remote=originOf(root);remote&&(result.remote=remote),mkdirSync2(dirname6(result.prBody),{recursive:!0}),writeFileSync5(result.prBody,prBody(result));let storedRun=join9(root,".uptide/report.json");return writeFileSync5(storedRun,JSON.stringify(result,null,2)),options.pr&&(await publishVerified(result,{tool,...options.yes?{yes:!0}:{}}),writeFileSync5(result.prBody,prBody(result)),writeFileSync5(storedRun,JSON.stringify(result,null,2))),result}async function publishVerified(result,options,io){let blockers=publicationBlockers(result,options.tool);if(blockers.length){result.publication={refused:blockers},result.notes.push(`PR not opened: ${blockers.join("; ")}`);return}let{publish:publish2}=await import("./publish-POUYH67J-7FNBWA42.js"),log=[],collect=text=>{log.push(text)};try{result.prUrl=await publish2(result,options.yes,io?{...io,print:collect}:{git,command,print:collect},options.cwd?{cwd:options.cwd}:{})}catch(error){log.length&&(result.publicationLog=log.join(`
|
|
248
248
|
`));let message=error instanceof Error?error.message:String(error);if(!options.yes&&/requires --yes/.test(message)){result.notes.push(`Publication plan printed, nothing pushed (no --yes): \`${UPTIDE_COMMAND} pr --branch ${result.branch} --yes\` opens the PR.`);return}if(error instanceof UptideError&&error.code==="VERIFIED_TREE_MISMATCH"){result.exportError=message,result.verification={...result.verification,passed:!1},result.publication={refused:[message]},result.notes.push(message);return}result.publication={refused:[],failed:message.split(`
|
|
249
249
|
`)[0]??message},result.notes.push(`PR not opened: ${result.publication.failed}. The verified run is stored; \`${UPTIDE_COMMAND} pr --branch ${result.branch} --yes\` retries the publish step alone.`);return}log.length&&(result.publicationLog=log.join(`
|
|
250
250
|
`))}function confirmedEvidence(evidence,findings){let rejected=new Set(findings.filter(f=>f.usage.compileError!==void 0||f.usage.compileCode!==void 0).map(f=>`${f.usage.file}:${f.usage.line}`));return evidence.map(e=>rejected.has(`${e.file}:${e.line}`)?{...e,compiler:!0}:e)}function refreshReview(result,pack=activePack(result.package)){if(!pack||!result.packContext)return;let rules=[...new Set(result.sites.map(s=>s.rule).filter(r=>!!r))];try{let sections=pack.reviewSections?.(result.packContext,rules);sections&&(result.reviewSections=sections);let apiChanges=pack.apiChanges?.(result.packContext);apiChanges&&(result.apiChanges=apiChanges)}catch{}}async function reverify(options,services={diagnostics,tests:testWorkspaces}){let started=Date.now(),root=realpathSync6(resolve6(options.cwd));confirmServices(root,options);let file=resolve6(options.run??join10(root,".uptide/report.json")),report;try{report=JSON.parse(readFileSync10(file,"utf8"))}catch{throw new UptideError("ANALYSIS_FAILED",`no stored migration run at ${file}`)}if(!Array.isArray(report.sites)||!report.verification||!report.package||!report.branch)throw new UptideError("ANALYSIS_FAILED","not a stored migration run");if(git(root,"branch","--show-current")!==report.branch)throw new UptideError("ANALYSIS_FAILED",`check out ${report.branch} first: the stored run belongs to that branch`);if(git(root,"status","--porcelain","--untracked-files=all").split(`
|
|
251
|
-
`).filter(line=>line.trim()!==""&&!line.slice(3).startsWith(".uptide/")).length)throw new UptideError("DIRTY_WORKING_TREE","uptide verify requires a clean working tree");let pack=options.pack??activePack(report.package);if(!pack)throw new Error(`no migration pack for ${report.package}`);let workspaces=workspacePackagesOf(root).filter(w=>{let p=JSON.parse(readFileSync10(join10(root,w,"package.json"),"utf8"));return["dependencies","devDependencies","peerDependencies","optionalDependencies"].some(s=>typeof p[s]?.[pack.name]=="string")}),from=report.from??report.sites[0]?.finding.change.from??"",context={from,to:report.target,includeDeprecated:!1,...pack.scanContext?.(root,workspaces)},sites=report.sites,known=sites.length,followed=[],affected=[...new Set(sites.flatMap(s=>[s.finding.usage.file,...s.editedFiles??[]]))],{tests,after,lint,formatted}=await settle({root,pack,context,workspaces,sites,followed,affected,from,target:report.target,baselineLint:[],services,withServices:options.withServices===!0,...options.onProgress?{onProgress:options.onProgress}:{},...options.testTimeoutMs?{testTimeoutMs:options.testTimeoutMs}:{}}),left=git(root,"status","--porcelain","--untracked-files=all").split(`
|
|
251
|
+
`).filter(line=>line.trim()!==""&&!line.slice(3).startsWith(".uptide/")).length)throw new UptideError("DIRTY_WORKING_TREE","uptide verify requires a clean working tree");let pack=options.pack??activePack(report.package);if(!pack)throw new Error(`no migration pack for ${report.package}`);let workspaces=workspacePackagesOf(root).filter(w=>{let p=JSON.parse(readFileSync10(join10(root,w,"package.json"),"utf8"));return["dependencies","devDependencies","peerDependencies","optionalDependencies"].some(s=>typeof p[s]?.[pack.name]=="string")}),moves=[{name:report.package,to:report.target},...report.companions??[]];assertInstalledVersions(root,moves);let from=report.from??report.sites[0]?.finding.change.from??"",context={from,to:report.target,includeDeprecated:!1,...pack.scanContext?.(root,workspaces)},sites=report.sites,known=sites.length,followed=[],affected=[...new Set(sites.flatMap(s=>[s.finding.usage.file,...s.editedFiles??[]]))],{tests,after,lint,formatted}=await settle({root,pack,context,workspaces,sites,followed,affected,from,target:report.target,baselineLint:[],services,withServices:options.withServices===!0,...options.onProgress?{onProgress:options.onProgress}:{},...options.testTimeoutMs?{testTimeoutMs:options.testTimeoutMs}:{}});assertInstalledVersions(root,moves);let left=git(root,"status","--porcelain","--untracked-files=all").split(`
|
|
252
252
|
`).filter(line=>line.trim()!==""&&!line.slice(3).startsWith(".uptide/")),newErrors=newDiagnostics(report.verification.baseline,after),unverified=typeResolutionFailure(root,report.verification.baseline),rules=[...new Set(sites.map(s=>s.rule).filter(r=>!!r))],decisions=[...new Set([...report.decisions??[],...pack.decisions?.(context,rules,followed)??[]])],result={...report,repo:root,...options.tool??uptideVersionInfo(),verifiedAt:new Date().toISOString(),verificationTimingMs:Date.now()-started,head:git(root,"rev-parse","HEAD"),verifiedTree:git(root,"rev-parse","HEAD^{tree}"),...report.baseHead?{changedFiles:git(root,"diff","--name-only",report.baseHead,"HEAD").split(`
|
|
253
253
|
`).filter(Boolean)}:{},sites,verification:{...report.verification,after,newErrors,tests,...lint.length?{lint}:{},...formatted.length?{formatted}:{},...unverified?{typesUnverified:unverified}:{},passed:!unverified&&newErrors.length===0&&left.length===0&&tests.every(t=>t.status==="passed"||t.status==="missing")&&lint.every(l=>l.status!=="failed")},...decisions.length?{decisions}:{},notes:[...report.notes.filter(n=>!n.startsWith("Verified again")),`Verified again at a new HEAD: ${sites.length-known} follow-up edit${sites.length-known===1?"":"s"} and ${formatted.length?"formatting":"no formatting"} were added as new commits; earlier commits are unchanged.`],prBody:join10(root,".uptide/pr-body.md")};return delete result.verificationPending,delete result.exportError,unverified||delete result.verification.typesUnverified,delete result.publication,mkdirSync3(dirname7(result.prBody),{recursive:!0}),writeFileSync6(result.prBody,prBody(result)),writeFileSync6(join10(root,".uptide/report.json"),JSON.stringify(result,null,2)),result}var tryGit=(cwd,...args)=>{try{return git(cwd,...args)}catch{return""}};function gitDir(source){let dir=git(source,"rev-parse","--git-common-dir");return isAbsolute2(dir)?dir:resolve7(source,dir)}function hooksDigest(source){let dir=join11(gitDir(source),"hooks");if(!existsSync5(dir))return"";let hash=createHash("sha256");for(let name of readdirSync(dir).sort()){let path=join11(dir,name);hash.update(name),statSync2(path).isFile()&&hash.update(readFileSync11(path))}return hash.digest("hex")}function snapshot(source){return{head:tryGit(source,"rev-parse","HEAD"),branch:tryGit(source,"branch","--show-current"),status:tryGit(source,"status","--porcelain","--untracked-files=all"),hooks:hooksDigest(source),config:tryGit(source,"config","--local","--list")}}function changedSince(source,before){let now=snapshot(source);return[...now.head!==before.head?["HEAD moved"]:[],...now.branch!==before.branch?["another branch is checked out"]:[],...now.status!==before.status?["the working tree has different changes"]:[],...now.hooks!==before.hooks?["git hooks were added or changed"]:[],...now.config!==before.config?["the repository git config changed"]:[]]}function isolate(source,branch,project="."){let root=realpathSync7(resolve7(source));mkdirSync4(runsRoot(),{recursive:!0});let run2=mkdtempSync2(join11(runsRoot(),"run-"));writeFileSync7(join11(run2,MARKER),JSON.stringify({source:root,created:new Date().toISOString()}));let dir=join11(run2,"repo");git(root,"clone","--quiet","--no-hardlinks",...branch?["--branch",branch]:[],root,dir);let origin=tryGit(root,"remote","get-url","origin");origin?(git(dir,"remote","set-url","origin",origin),tryGit(dir,"fetch","--quiet","--prune",root,"+refs/remotes/origin/*:refs/remotes/origin/*")):git(dir,"remote","remove","origin");for(let key2 of["user.name","user.email"]){let value=tryGit(root,"config",key2);value&&git(dir,"config",key2,value)}for(let workspace of workspacePackagesOf(join11(root,project))){let modules=join11(root,project,workspace,"node_modules");existsSync5(modules)&&(mkdirSync4(join11(dir,project,workspace),{recursive:!0}),cpSync(modules,join11(dir,project,workspace,"node_modules"),{recursive:!0,verbatimSymlinks:!0,mode:constants.COPYFILE_FICLONE}))}return dir}var MARKER=".uptide-run";function runsRoot(env=process.env){return env.UPTIDE_RUNS_DIR?resolve7(env.UPTIDE_RUNS_DIR):join11(realpathSync7(tmpdir2()),"uptide-runs")}function removeRun(path,root=runsRoot()){let run2,base;try{let real=realpathSync7(resolve7(path));run2=basename(real)==="repo"?dirname8(real):real,base=realpathSync7(root)}catch{return!1}return dirname8(run2)!==base||!/^run-[\w-]+$/.test(basename(run2))||!existsSync5(join11(run2,MARKER))?!1:(rmSync2(run2,{recursive:!0,force:!0}),!0)}function cleanRuns(options={}){let root=options.root??runsRoot(),limit=(options.now??Date.now())-(options.days??7)*24*60*60*1e3,removed=[],kept=[],entries=[];try{entries=readdirSync(root).sort()}catch{return{removed,kept}}for(let name of entries){let run2=join11(root,name),created;try{let marker=JSON.parse(readFileSync11(join11(run2,MARKER),"utf8"));created=Date.parse(marker.created??""),Number.isNaN(created)&&(created=statSync2(run2).mtimeMs)}catch{continue}created<limit&&removeRun(run2,root)?removed.push(run2):kept.push(run2)}return{removed,kept}}var slug=branch=>branch.replaceAll("/","__");function storedRunDir(source,branch){return join11(gitDir(realpathSync7(resolve7(source))),"uptide",slug(branch))}function storedRunFile(source,branch){let legacy=join11(source,".uptide/report.json");if(existsSync5(legacy))return legacy;let kept=join11(storedRunDir(source,branch),"report.json");return existsSync5(kept)?kept:void 0}function deliver(source,clone,report,before,fresh=!1){let result={...report,source,...before.branch?{base:before.branch}:{},delivered:!1},notes=[...report.notes];try{assertVerifiedTree(clone,report)}catch(error){result.exportError=error.message}try{if(!result.exportError){let existingTree=tryGit(source,"rev-parse","--verify",`refs/heads/${report.branch}^{tree}`);if(fresh&&existingTree&&existingTree!==report.verifiedTree){let suffix=2;for(;tryGit(source,"rev-parse","--verify",`refs/heads/${report.branch}-${suffix}`);)suffix++;result.branch=`${report.branch}-${suffix}`,git(clone,"branch","-m",report.branch,result.branch)}fresh&&existingTree===report.verifiedTree?result.head=git(source,"rev-parse",`refs/heads/${result.branch}`):fresh?(git(source,"fetch","--quiet",clone,`refs/heads/${result.branch}`),result.head=git(clone,"rev-parse",`refs/heads/${result.branch}`),git(source,"update-ref",`refs/heads/${result.branch}`,result.head,"")):before.branch!==result.branch?git(source,"fetch","--quiet",clone,`refs/heads/${result.branch}:refs/heads/${result.branch}`):notes.push(`${report.branch} is checked out in your repository, so it was not moved; the new commits are in ${clone}.`),assertVerifiedTree(source,result),result.delivered=!0,result.branch!==report.branch&&(result.branchRenamedFrom=report.branch,notes.push(`${report.branch} already exists with different content; created ${result.branch}.`))}}catch(error){result.exportError=error.message}result.exportError&¬es.push(`Export failed: ${result.exportError}`),result.exportError&&(result.verification={...result.verification,passed:!1});let changed=changedSince(source,before);return changed.length&&(result.sourceChanged=changed,notes.push(`Your checkout changed during the run: ${changed.join("; ")}.`)),result.notes=notes,result}function finish(source,clone,delivered,options){let{delivered:inSource,...result}=delivered,reason=result.exportError?"export failed: the repository branch does not contain the verified tree":options.keep?"kept on request (--keep)":result.verification.passed?result.sourceChanged?.length?"your checkout changed during the run":!inSource&&!options.pushed?"it holds commits that are not in your repository or on the remote yet":void 0:"the run did not verify";reason?result.clone={path:clone,kept:!0,reason}:(removeRun(clone),result.clone={path:clone,kept:!1},result.repo=source);let dir=storedRunDir(source,result.branch);return mkdirSync4(dir,{recursive:!0}),result.prBody=join11(dir,"pr-body.md"),writeFileSync7(result.prBody,prBody(result)),writeFileSync7(join11(dir,"report.json"),JSON.stringify(result,null,2)),result}async function keeping(clone,work){try{return await work()}catch(error){throw error instanceof Error&&(error.message+=`
|
|
254
254
|
Temporary clone kept: ${clone}`),error}}function remoteDefaultBranch(root){let head=tryGit(root,"symbolic-ref","--quiet","refs/remotes/origin/HEAD"),candidates=head?[head.replace(/^refs\/remotes\//,"")]:["origin/main","origin/master"];for(let ref of candidates)if(tryGit(root,"rev-parse","--verify","--quiet",ref))return{ref,name:ref.replace(/^origin\//,"")}}var commits=n=>`${n} commit${n===1?"":"s"}`;function fixPreflight(cwd,options={}){let{top:source,project}=projectRoot(cwd),head=git(source,"rev-parse","HEAD"),at=head.slice(0,12),name=tryGit(source,"branch","--show-current"),branch=name||`detached HEAD ${at}`,notes=[],manifest2=project==="."?"package.json":`${project}/package.json`;if(!tryGit(source,"cat-file","-t",`${head}:${manifest2}`))throw new UptideError("NOT_REPOSITORY_ROOT",`${manifest2} is not in commit ${at} (${branch}) of ${source}. fix clones that commit from the local repository, so the file must be committed first.`);let dirty=git(source,"status","--porcelain","--untracked-files=all").split(`
|
|
@@ -325,6 +325,6 @@ it('${o.package.replaceAll("'","\\'")}: every fixture rewrites and detects exact
|
|
|
325
325
|
`}function scaffoldPack(options){if(!/^(?:@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*$/.test(options.package))throw new UptideError("INVALID_GROUND_TRUTH",`not an npm package name: ${options.package}`);for(let[flag,range]of[["--from",options.from],["--to",options.to]])if(minVersion(range)===void 0)throw new UptideError("UNSUPPORTED_VERSION_RANGE",`${flag} ${range}: not a semver range`);let packs=packsDir(options.root),registryFile=join19(packs,"registry.ts");if(!existsSync11(registryFile))throw new UptideError("NOT_UPTIDE_CHECKOUT",`no pack registry at ${registryFile}: run uptide pack new inside an uptide checkout`);let dir=packDir(options.package),constant=packConstant(options.package),entries=parseRegistry(readFileSync19(registryFile,"utf8")),home=join19(packs,dir);if(existsSync11(home)||entries.some(e=>e.dir===dir||e.name===constant))throw new UptideError("PACK_EXISTS",`a pack for ${options.package} already exists: ${home}`);let truth={$comment:`Public repositories at the commit before they upgraded ${options.package} from ${options.from} to ${options.to}, and every finding the pack must report there. See docs/packs.md, "Ground truth".`,package:options.package,repos:[]},before=BEFORE.replace("PKG",options.package),after=before.replace("import { oldName }","import { newName }").replace("= oldName(1)","= newName(1)"),files2=[[join19(home,"index.ts"),indexFile(options,constant)],[join19(home,"fixtures",RULE,"before.ts"),before],[join19(home,"fixtures",RULE,"after.ts"),after],[join19(home,`${dir}.test.ts`),testFile(options,constant)],[join19(home,"ground-truth.json"),`${JSON.stringify(truth,null,2)}
|
|
326
326
|
`]];for(let[file,text]of files2)mkdirSync6(join19(file,".."),{recursive:!0}),writeFileSync13(file,text);writeFileSync13(registryFile,renderRegistry([...entries,{dir,name:constant}]));let written=[...files2.map(([file])=>file),registryFile],biome=join19(options.root,"node_modules",".bin","biome"),formattable=written.filter(file=>!file.includes(`${dir}/fixtures/`)),formatted=existsSync11(biome)&&spawnSync(biome,["format","--write",...formattable],{cwd:options.root,stdio:"ignore"}).status===0,verification={status:"candidate",truth:truthDigest(readFileSync19(join19(home,"ground-truth.json"),"utf8")),repos:0,breaking:{precision:1,recall:1,falsePositives:0}},verificationFile=join19(home,"verification.json");return writeFileSync13(verificationFile,`${JSON.stringify(verification,null,2)}
|
|
327
327
|
`),written.splice(written.length-1,0,verificationFile),{dir,constant,files:written.map(file=>relative5(options.root,file)),formatted}}var sitesOf2=(groups,pick)=>groups.reduce((n,g)=>n+pick(g),0);function effortOf2(p){let breaking=(p.plan??[]).filter(g=>g.severity==="breaking"),unverified=(p.plan??[]).filter(g=>g.severity==="unverified"),byRule=sitesOf2(breaking,g=>g.by.rule),byAgent=sitesOf2(breaking,g=>g.by.agent),manual=sitesOf2(breaking,g=>g.by.manual),unconfirmed=sitesOf2(unverified,g=>g.sites),hands=byAgent+manual;return{level:p.status==="unknown"||p.status==="partial"||p.importers?.some(i=>!i.analyzed)?"unknown":hands>25?"large":hands>5?"medium":hands>0||byRule>0||unconfirmed>0?"small":"none",byRule,byAgent,manual,unconfirmed}}var RANK={none:0,small:1,medium:2,large:3,unknown:4};function within(version2,range){try{return satisfies(version2,range)}catch{return!0}}function planUpgrades(report,peers){let behind=report.packages.filter(p=>!p.notes.includes("up to date")&&!["not-imported","workspace","private"].includes(p.status)&&p.installed!==p.target),analyzed=behind.filter(p=>p.status!=="skipped"&&p.status!=="no-types"),notPlanned=behind.filter(p=>!analyzed.includes(p)).map(p=>({name:p.name,installed:p.installed,reason:p.skipReason==="TIME_BUDGET"?"not analyzed: out of time":isFailure(p)?`not analyzed: ${(p.notes[0]??"analysis failed").split(`
|
|
328
|
-
`)[0]}`:p.notes[0]??"not analyzed"})),planned=new Map;for(let p of analyzed){let effort=effortOf2(p);for(let m of p.members??[p]){let previous=planned.get(m.name);planned.set(m.name,{name:m.name,installed:previous&&compareVersions(previous.installed,m.installed)<0?previous.installed:m.installed,target:m.target,tier:p.tier??"generic",effort:previous&&RANK[previous.effort.level]>RANK[effort.level]?previous.effort:effort})}}let constraints=[],before=new Map,tied=new Map,find=name=>{let parent=tied.get(name)??name;if(parent===name)return name;let root=find(parent);return tied.set(name,root),root},tie=(a,b)=>{tied.set(find(a),find(b))};for(let a of planned.values()){for(let[on,range]of Object.entries(peers.ofTarget(a.name,a.target)??{})){let installed2=planned.get(on)?.installed??peers.installed[on]?.version;if(installed2===void 0||within(installed2,range))continue;let b=planned.get(on);if(b&&within(b.target,range)){let back=peers.ofTarget(b.name,b.target)?.[a.name],together=back!==void 0&&!within(a.installed,back);constraints.push({from:a.name,fromVersion:a.target,on,range,effect:together?"together":"before",reason:together?`${a.name} ${a.target} needs ${on} ${range}, and ${on} ${b.target} needs ${a.name} ${back}: upgrade them together`:`${a.name} ${a.target} needs ${on} ${range} (installed: ${installed2}): upgrade ${on} first`}),together?tie(a.name,on):before.set(a.name,new Set([...before.get(a.name)??[],on]))}else constraints.push({from:a.name,fromVersion:a.target,on,range,effect:"blocked",reason:`${a.name} ${a.target} needs ${on} ${range}; ${on} is at ${installed2}${b?` and its target ${b.target} is outside that range too`:" and is not being upgraded"}`})}for(let[x,{version:version2,peers:asked}]of Object.entries(peers.installed)){let range=asked[a.name];if(range===void 0||x===a.name||within(a.target,range))continue;let upgraded=planned.get(x),next=upgraded?peers.ofTarget(x,upgraded.target)?.[a.name]:void 0;if(upgraded&&(next===void 0||within(a.target,next))){let together=next!==void 0&&!within(a.installed,next);constraints.push({from:x,fromVersion:version2,on:a.name,range,effect:together?"together":"before",reason:together?`${x} ${version2} needs ${a.name} ${range} and ${x} ${upgraded.target} needs ${a.name} ${next}: upgrade them together`:`${x} ${version2} needs ${a.name} ${range}: upgrade ${x} to ${upgraded.target} first, which accepts ${a.name} ${a.target}`}),together?tie(a.name,x):before.set(a.name,new Set([...before.get(a.name)??[],x]))}else constraints.push({from:x,fromVersion:version2,on:a.name,range,effect:"blocked",reason:`${x} ${version2} needs ${a.name} ${range}, and ${a.name} ${a.target} is outside it${upgraded?` (so is what ${x} ${upgraded.target} accepts)`:`; ${x} has no upgrade in this plan`}`})}}for(let p of analyzed)for(let m of p.members??[])tie(m.name,(p.members??[])[0]?.name??m.name);let groups=new Map;for(let p of planned.values())groups.set(find(p.name),[...groups.get(find(p.name))??[],p]);let levelOf=members=>members.map(m=>m.effort.level).sort((a,b)=>RANK[b]-RANK[a])[0]??"none",waitsOn=root=>new Set((groups.get(root)??[]).flatMap(m=>[...before.get(m.name)??[]]).map(find).filter(other=>other!==root)),constraintsOf=members=>{let names=new Set(members.map(m=>m.name));return constraints.filter(c=>names.has(c.from)||names.has(c.on))},free=[...groups].filter(([root,members])=>levelOf(members)==="none"&&waitsOn(root).size===0&&constraintsOf(members).length===0),steps=[],done=new Set;if(free.length>0){steps.push({packages:free.flatMap(([,members])=>members).sort((a,b)=>a.name.localeCompare(b.name)),...free.flatMap(([,m])=>m).length>1?{together:"no-impact"}:{},effort:"none",constraints:[]});for(let[root]of free)done.add(root)}let rest=[...groups].filter(([root])=>!done.has(root));for(;rest.length>0;){let ready=rest.filter(([root2])=>[...waitsOn(root2)].every(other=>done.has(other))).sort(([,a],[,b])=>RANK[levelOf(a)]-RANK[levelOf(b)]||(a[0]?.name??"").localeCompare(b[0]?.name??"")),[root,members]=ready[0]??rest[0];steps.push({packages:[...members].sort((a,b)=>a.name.localeCompare(b.name)),...members.length>1?{together:"peer"}:{},effort:levelOf(members),constraints:constraintsOf(members)}),done.add(root),rest.splice(rest.findIndex(([r])=>r===root),1)}return{steps:steps.map((step,i)=>({order:i+1,...step})),notPlanned}}async function upgradePlan(opts,services={}){let fetcher=services.fetcher??opts.fetcher??createNpmFetcher({config:loadRegistryConfig({cwd:opts.cwd})}),discovery=await(services.list??listDependencies)({...opts,fetcher}),saved=opts.checkResults;if(saved&&(!Array.isArray(saved.packages)||resolve11(saved.repo)!==resolve11(opts.cwd)))throw new Error("--results must be a check report for this repository");let byVersion=discovery.packages.flatMap(p=>(p.versions??[{version:p.current,workspaces:p.workspaces}]).filter(v=>compareVersions(p.latest,v.version)>0).map(v=>({...p,current:v.version,workspaces:v.workspaces}))),packages=byVersion.map(p=>{let existing=saved?.packages.find(s=>s.name===p.name&&s.installed===p.current&&s.target===p.latest&&JSON.stringify((s.workspaces??[s.workspace]).slice().sort())===JSON.stringify(p.workspaces.slice().sort()));return existing||{name:p.name,installed:p.current,latest:p.latest,target:p.latest,tier:p.tier,workspace:p.workspaces.length>1?"*":p.workspaces[0]??".",workspaces:p.workspaces,majorsBehind:majorsBehind(p.current,p.latest),findings:[],callSitesChecked:0,unanalyzed:[],status:"unknown",notes:["not checked; effort unknown"],timing:{fetchMs:0,diffMs:0,usagesMs:0,compileMs:0}}});for(let failure of discovery.failures)packages.push({name:failure.name,installed:"?",latest:"?",target:"?",workspace:failure.workspace??".",majorsBehind:0,findings:[],callSitesChecked:0,unanalyzed:[],status:"skipped",skipReason:"ANALYSIS_FAILED",notes:[failure.reason],timing:{fetchMs:0,diffMs:0,usagesMs:0,compileMs:0}});let report={repo:opts.cwd,workspaces:discovery.workspaces,packages,summary:summarize(packages),timing:discovery.timing},installed2={};for(let workspace of discovery.workspaces){let dir=resolve11(opts.cwd,workspace),manifest2=JSON.parse(readFileSync20(join20(dir,"package.json"),"utf8"));for(let name of Object.keys({...manifest2.dependencies,...manifest2.devDependencies}))for(let at=dir;;at=dirname11(at))try{let pkg=JSON.parse(readFileSync20(join20(at,"node_modules",name,"package.json"),"utf8"));installed2[name]??={version:pkg.version,peers:pkg.peerDependencies??{}};break}catch{if(dirname11(at)===at)break}}let targets=new Map;await mapWithLimit(discovery.packages,12,async p=>{try{targets.set(`${p.name}@${p.latest}`,(await fetcher.metadata?.(p.name,p.latest))?.peerDependencies)}catch{}});let plan=planUpgrades(report,{installed:installed2,ofTarget:(name,version2)=>targets.get(`${name}@${version2}`)});plan.notes=["Based on discovery and matching saved check results; unknown effort requires uptide check <package>.","Saved results describe the source at check time; rerun check after source changes."];for(let name of new Set(byVersion.map(p=>p.name))){let versions=byVersion.filter(p=>p.name===name);versions.length>1&&plan.notes.push(`${name}: current versions ${versions.map(p=>`${p.current} (${p.workspaces.join(", ")})`).join("; ")}; one target for all, highest estimated effort shown.`)}let missing=discovery.packages.filter(p=>targets.get(`${p.name}@${p.latest}`)===void 0);return missing.length&&plan.notes.push(`Target peer metadata unavailable: ${missing.map(p=>p.name).join(", ")}`),Object.keys(installed2).length||plan.notes.push("Installed peer constraints unavailable without node_modules."),{report,plan}}import"fs";var VERSION="0.7.
|
|
328
|
+
`)[0]}`:p.notes[0]??"not analyzed"})),planned=new Map;for(let p of analyzed){let effort=effortOf2(p);for(let m of p.members??[p]){let previous=planned.get(m.name);planned.set(m.name,{name:m.name,installed:previous&&compareVersions(previous.installed,m.installed)<0?previous.installed:m.installed,target:m.target,tier:p.tier??"generic",effort:previous&&RANK[previous.effort.level]>RANK[effort.level]?previous.effort:effort})}}let constraints=[],before=new Map,tied=new Map,find=name=>{let parent=tied.get(name)??name;if(parent===name)return name;let root=find(parent);return tied.set(name,root),root},tie=(a,b)=>{tied.set(find(a),find(b))};for(let a of planned.values()){for(let[on,range]of Object.entries(peers.ofTarget(a.name,a.target)??{})){let installed2=planned.get(on)?.installed??peers.installed[on]?.version;if(installed2===void 0||within(installed2,range))continue;let b=planned.get(on);if(b&&within(b.target,range)){let back=peers.ofTarget(b.name,b.target)?.[a.name],together=back!==void 0&&!within(a.installed,back);constraints.push({from:a.name,fromVersion:a.target,on,range,effect:together?"together":"before",reason:together?`${a.name} ${a.target} needs ${on} ${range}, and ${on} ${b.target} needs ${a.name} ${back}: upgrade them together`:`${a.name} ${a.target} needs ${on} ${range} (installed: ${installed2}): upgrade ${on} first`}),together?tie(a.name,on):before.set(a.name,new Set([...before.get(a.name)??[],on]))}else constraints.push({from:a.name,fromVersion:a.target,on,range,effect:"blocked",reason:`${a.name} ${a.target} needs ${on} ${range}; ${on} is at ${installed2}${b?` and its target ${b.target} is outside that range too`:" and is not being upgraded"}`})}for(let[x,{version:version2,peers:asked}]of Object.entries(peers.installed)){let range=asked[a.name];if(range===void 0||x===a.name||within(a.target,range))continue;let upgraded=planned.get(x),next=upgraded?peers.ofTarget(x,upgraded.target)?.[a.name]:void 0;if(upgraded&&(next===void 0||within(a.target,next))){let together=next!==void 0&&!within(a.installed,next);constraints.push({from:x,fromVersion:version2,on:a.name,range,effect:together?"together":"before",reason:together?`${x} ${version2} needs ${a.name} ${range} and ${x} ${upgraded.target} needs ${a.name} ${next}: upgrade them together`:`${x} ${version2} needs ${a.name} ${range}: upgrade ${x} to ${upgraded.target} first, which accepts ${a.name} ${a.target}`}),together?tie(a.name,x):before.set(a.name,new Set([...before.get(a.name)??[],x]))}else constraints.push({from:x,fromVersion:version2,on:a.name,range,effect:"blocked",reason:`${x} ${version2} needs ${a.name} ${range}, and ${a.name} ${a.target} is outside it${upgraded?` (so is what ${x} ${upgraded.target} accepts)`:`; ${x} has no upgrade in this plan`}`})}}for(let p of analyzed)for(let m of p.members??[])tie(m.name,(p.members??[])[0]?.name??m.name);let groups=new Map;for(let p of planned.values())groups.set(find(p.name),[...groups.get(find(p.name))??[],p]);let levelOf=members=>members.map(m=>m.effort.level).sort((a,b)=>RANK[b]-RANK[a])[0]??"none",waitsOn=root=>new Set((groups.get(root)??[]).flatMap(m=>[...before.get(m.name)??[]]).map(find).filter(other=>other!==root)),constraintsOf=members=>{let names=new Set(members.map(m=>m.name));return constraints.filter(c=>names.has(c.from)||names.has(c.on))},free=[...groups].filter(([root,members])=>levelOf(members)==="none"&&waitsOn(root).size===0&&constraintsOf(members).length===0),steps=[],done=new Set;if(free.length>0){steps.push({packages:free.flatMap(([,members])=>members).sort((a,b)=>a.name.localeCompare(b.name)),...free.flatMap(([,m])=>m).length>1?{together:"no-impact"}:{},effort:"none",constraints:[]});for(let[root]of free)done.add(root)}let rest=[...groups].filter(([root])=>!done.has(root));for(;rest.length>0;){let ready=rest.filter(([root2])=>[...waitsOn(root2)].every(other=>done.has(other))).sort(([,a],[,b])=>RANK[levelOf(a)]-RANK[levelOf(b)]||(a[0]?.name??"").localeCompare(b[0]?.name??"")),[root,members]=ready[0]??rest[0];steps.push({packages:[...members].sort((a,b)=>a.name.localeCompare(b.name)),...members.length>1?{together:"peer"}:{},effort:levelOf(members),constraints:constraintsOf(members)}),done.add(root),rest.splice(rest.findIndex(([r])=>r===root),1)}return{steps:steps.map((step,i)=>({order:i+1,...step})),notPlanned}}async function upgradePlan(opts,services={}){let fetcher=services.fetcher??opts.fetcher??createNpmFetcher({config:loadRegistryConfig({cwd:opts.cwd})}),discovery=await(services.list??listDependencies)({...opts,fetcher}),saved=opts.checkResults;if(saved&&(!Array.isArray(saved.packages)||resolve11(saved.repo)!==resolve11(opts.cwd)))throw new Error("--results must be a check report for this repository");let byVersion=discovery.packages.flatMap(p=>(p.versions??[{version:p.current,workspaces:p.workspaces}]).filter(v=>compareVersions(p.latest,v.version)>0).map(v=>({...p,current:v.version,workspaces:v.workspaces}))),packages=byVersion.map(p=>{let existing=saved?.packages.find(s=>s.name===p.name&&s.installed===p.current&&s.target===p.latest&&JSON.stringify((s.workspaces??[s.workspace]).slice().sort())===JSON.stringify(p.workspaces.slice().sort()));return existing||{name:p.name,installed:p.current,latest:p.latest,target:p.latest,tier:p.tier,workspace:p.workspaces.length>1?"*":p.workspaces[0]??".",workspaces:p.workspaces,majorsBehind:majorsBehind(p.current,p.latest),findings:[],callSitesChecked:0,unanalyzed:[],status:"unknown",notes:["not checked; effort unknown"],timing:{fetchMs:0,diffMs:0,usagesMs:0,compileMs:0}}});for(let failure of discovery.failures)packages.push({name:failure.name,installed:"?",latest:"?",target:"?",workspace:failure.workspace??".",majorsBehind:0,findings:[],callSitesChecked:0,unanalyzed:[],status:"skipped",skipReason:"ANALYSIS_FAILED",notes:[failure.reason],timing:{fetchMs:0,diffMs:0,usagesMs:0,compileMs:0}});let report={repo:opts.cwd,workspaces:discovery.workspaces,packages,summary:summarize(packages),timing:discovery.timing},installed2={};for(let workspace of discovery.workspaces){let dir=resolve11(opts.cwd,workspace),manifest2=JSON.parse(readFileSync20(join20(dir,"package.json"),"utf8"));for(let name of Object.keys({...manifest2.dependencies,...manifest2.devDependencies}))for(let at=dir;;at=dirname11(at))try{let pkg=JSON.parse(readFileSync20(join20(at,"node_modules",name,"package.json"),"utf8"));installed2[name]??={version:pkg.version,peers:pkg.peerDependencies??{}};break}catch{if(dirname11(at)===at)break}}let targets=new Map;await mapWithLimit(discovery.packages,12,async p=>{try{targets.set(`${p.name}@${p.latest}`,(await fetcher.metadata?.(p.name,p.latest))?.peerDependencies)}catch{}});let plan=planUpgrades(report,{installed:installed2,ofTarget:(name,version2)=>targets.get(`${name}@${version2}`)});plan.notes=["Based on discovery and matching saved check results; unknown effort requires uptide check <package>.","Saved results describe the source at check time; rerun check after source changes."];for(let name of new Set(byVersion.map(p=>p.name))){let versions=byVersion.filter(p=>p.name===name);versions.length>1&&plan.notes.push(`${name}: current versions ${versions.map(p=>`${p.current} (${p.workspaces.join(", ")})`).join("; ")}; one target for all, highest estimated effort shown.`)}let missing=discovery.packages.filter(p=>targets.get(`${p.name}@${p.latest}`)===void 0);return missing.length&&plan.notes.push(`Target peer metadata unavailable: ${missing.map(p=>p.name).join(", ")}`),Object.keys(installed2).length||plan.notes.push("Installed peer constraints unavailable without node_modules."),{report,plan}}import"fs";var VERSION="0.7.4-next.20261011233936";var import_picocolors=__toESM(require_picocolors(),1);var INVOCATION=uptideCommand(VERSION),runnable=text=>text.replace(/(^|`)uptide (?=[a-z-])/g,`$1${INVOCATION} `);var EXIT={ok:0,breaking:1,error:2},CliError=class extends Error{constructor(message,options={}){super(message);this.options=options}options;name="CliError"};function explain(err){if(err instanceof NoTypesError)return`${err.packageName}@${err.version}: no type declarations, cannot analyze`;if(err instanceof VersionNotFoundError){let hint=err.available.length>0?` (latest published: ${err.available.at(-1)})`:"";return`${err.message}${hint}`}return err instanceof PackageNotFoundError||err instanceof IntegrityError||err instanceof Error?err.message:String(err)}function renderError(err,color){let colors=import_picocolors.default.createColors(color),lines=[`${colors.red("error:")} ${explain(err)}`];return err instanceof CliError&&(err.options.why&&lines.push(` ${err.options.why}`),err.options.next&&lines.push(` ${colors.bold("Next:")} ${err.options.literalNext?err.options.next:runnable(err.options.next)}`)),`${lines.join(`
|
|
329
329
|
`)}
|
|
330
330
|
`}async function runJob(job,onProgress){if(job.kind==="check")return check({...job.request,onProgress});if(job.kind==="plan")return upgradePlan({...job.request,onProgress});if(job.kind==="verify")return isolatedVerify({...job.request,onProgress});let{llm,...options}=job.request;return isolatedFix({...options,onProgress,...llm?{}:{fixer:null}})}export{foldForDisplay,depthOf,PRICE_DATE,priceFor,ACCEPTED_KEYS,selectLlm,cleanRuns,fixPreflight,openPr,updatePrBody,listDependencies,testPack,scaffoldPack,require_picocolors,VERSION,INVOCATION,runnable,EXIT,CliError,explain,renderError,runJob};
|
|
@@ -4,4 +4,4 @@ const require = __uptideCreateRequire(import.meta.url);
|
|
|
4
4
|
const __filename = __uptideFileURLToPath(import.meta.url);
|
|
5
5
|
const __dirname = __uptideFileURLToPath(new URL('.', import.meta.url));
|
|
6
6
|
import{execFileSync}from"child_process";import{readFileSync}from"fs";import{dirname,join,resolve}from"path";import{fileURLToPath}from"url";import{execFileSync as execFileSync2,spawn}from"child_process";import{existsSync,mkdirSync,realpathSync}from"fs";import{tmpdir}from"os";import{dirname as dirname2,join as join2,relative,resolve as resolve2}from"path";var NoTypesError=class extends Error{constructor(packageName,version2){super(`${packageName}@${version2}: no type declarations, cannot analyze`),this.packageName=packageName,this.version=version2}packageName;version;code="NO_TYPES";name="NoTypesError"},PackageNotFoundError=class extends Error{constructor(packageName,registry){super(`${packageName}: not found on ${registry}`),this.packageName=packageName,this.registry=registry}packageName;registry;code="PACKAGE_NOT_FOUND";name="PackageNotFoundError"},RegistryAuthError=class extends Error{constructor(packageName,registry,status){super(`${packageName}: ${registry} answered HTTP ${status} (registry auth)`),this.packageName=packageName,this.registry=registry,this.status=status}packageName;registry;status;code="REGISTRY_AUTH";name="RegistryAuthError"},VersionNotFoundError=class extends Error{constructor(packageName,version2,available){super(`${packageName}@${version2}: version not published (${available.length} versions available)`),this.packageName=packageName,this.version=version2,this.available=available}packageName;version;available;code="VERSION_NOT_FOUND";name="VersionNotFoundError"},IntegrityError=class extends Error{constructor(packageName,version2,expected,actual){super(`${packageName}@${version2}: tarball integrity mismatch (expected ${expected}, got ${actual})`),this.packageName=packageName,this.version=version2,this.expected=expected,this.actual=actual}packageName;version;expected;actual;name="IntegrityError"},AdapterCapabilityError=class extends Error{constructor(adapter,capability){super(`adapter "${adapter}" does not implement ${capability}; cannot check usages`),this.adapter=adapter,this.capability=capability}adapter;capability;name="AdapterCapabilityError"},UptideError=class extends Error{constructor(code,message,options){super(message,options),this.code=code}code;name="UptideError"};function errorCode(error){return error&&typeof error=="object"&&"code"in error&&typeof error.code=="string"?error.code:"ANALYSIS_FAILED"}var version="0.1.0";function dirtyLines(porcelain){return porcelain.split(`
|
|
7
|
-
`).filter(line=>line.trim()!=="").filter(line=>!/(?:^|\/)tsup\.config\.bundled_[\w-]+\.[cm]?js$/.test(line.slice(3)))}function uptideVersionInfo(env=process.env){return{uptideVersion:version,uptideCommit:"
|
|
7
|
+
`).filter(line=>line.trim()!=="").filter(line=>!/(?:^|\/)tsup\.config\.bundled_[\w-]+\.[cm]?js$/.test(line.slice(3)))}function uptideVersionInfo(env=process.env){return{uptideVersion:version,uptideCommit:"560d87d546e224355ffb27955901ac960ec9895f",uptideDirty:!1}}function uptideCommand(cliVersion){let tag=/^\d+\.\d+\.\d+-([a-z]+)/.exec(cliVersion)?.[1];return tag?`npx uptide@${tag}`:"npx uptide"}var UPTIDE_COMMAND=uptideCommand("0.7.4-next.20261011233936");function noHooksDir(){let dir=join2(tmpdir(),"uptide-no-hooks");return mkdirSync(dir,{recursive:!0}),dir}function quietEnv(){return{CI:"true",npm_config_ignore_scripts:"true",npm_config_enable_pre_post_scripts:"false",npm_config_verify_deps_before_run:"false",pnpm_config_ignore_scripts:"true",pnpm_config_enable_pre_post_scripts:"false",pnpm_config_verify_deps_before_run:"false",YARN_ENABLE_SCRIPTS:"false",YARN_ENABLE_TELEMETRY:"0",SKIP_SIMPLE_GIT_HOOKS:"1",HUSKY:"0",LEFTHOOK:"0",GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"core.hooksPath",GIT_CONFIG_VALUE_0:noHooksDir()}}function git(cwd,...args){return execFileSync2("git",["-c","core.hooksPath=/dev/null",...args],{cwd,encoding:"utf8",stdio:["ignore","pipe","pipe"]}).trim()}function command(cwd,bin,args,timeoutMs=12e4,extraEnv={}){return new Promise(resolve3=>{let output="",timeout=!1,child=spawn(bin,args,{cwd,detached:process.platform!=="win32",env:{...Object.fromEntries(Object.entries(process.env).filter(([key])=>!/(?:TOKEN|SECRET|API_KEY|PASSWORD)/i.test(key))),...quietEnv(),...extraEnv},stdio:["ignore","pipe","pipe"]}),append=data=>{output=(output+data.toString()).slice(-2e5)};child.stdout.on("data",append),child.stderr.on("data",append);let timer=setTimeout(()=>{timeout=!0;try{process.platform!=="win32"&&child.pid?process.kill(-child.pid,"SIGKILL"):child.kill("SIGKILL")}catch{}},timeoutMs);child.on("error",e=>{clearTimeout(timer),resolve3({code:1,output:String(e),timeout:!1})}),child.on("close",code=>{clearTimeout(timer),resolve3({code:code??1,output,timeout})})})}function projectRoot(cwd){let root=realpathSync(resolve2(cwd)),top=realpathSync(git(root,"rev-parse","--show-toplevel"));if(!existsSync(join2(root,"package.json")))throw new UptideError("NOT_REPOSITORY_ROOT",`${root}: no package.json; run fix at the project root`);for(let dir=dirname2(root);dir.startsWith(top)&&dir!==root;dir=dirname2(dir)){if(existsSync(join2(dir,"package.json")))throw new UptideError("NOT_REPOSITORY_ROOT",`run fix at the project root, ${dir} (workspace versions are upgraded together)`);if(dir===top)break}return{root,top,project:relative(top,root)||"."}}export{NoTypesError,PackageNotFoundError,RegistryAuthError,VersionNotFoundError,IntegrityError,AdapterCapabilityError,UptideError,errorCode,uptideVersionInfo,uptideCommand,UPTIDE_COMMAND,git,command,projectRoot};
|