@sous-io/sous 1.1.4 → 1.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/sous.js CHANGED
@@ -356,14 +356,14 @@ ${value}`,this.dataLineCount++;return}if(isFieldName(line,fieldLength,RETRY)){is
356
356
  `).slice(1).join(`
357
357
  `);err.stack=stack?`${stack}
358
358
  ${captureLines}`:capture.stack}module2.exports.fetch=function(init,options2=void 0){return fetchImpl(init,options2).catch(err=>{throw currentFilename?appendFetchStackTrace(err,currentFilename):err&&typeof err=="object"&&Error.captureStackTrace(err,module2.exports.fetch),err})};module2.exports.Headers=require_headers().Headers;module2.exports.Response=require_response().Response;module2.exports.Request=require_request2().Request;module2.exports.FormData=require_formdata().FormData;var{setGlobalOrigin,getGlobalOrigin}=require_global();module2.exports.setGlobalOrigin=setGlobalOrigin;module2.exports.getGlobalOrigin=getGlobalOrigin;var{CacheStorage}=require_cachestorage(),{kConstruct}=require_symbols();module2.exports.caches=new CacheStorage(kConstruct);var{deleteCookie,getCookies,getSetCookies,setCookie,parseCookie}=require_cookies();module2.exports.deleteCookie=deleteCookie;module2.exports.getCookies=getCookies;module2.exports.getSetCookies=getSetCookies;module2.exports.setCookie=setCookie;module2.exports.parseCookie=parseCookie;var{parseMIMEType,serializeAMimeType}=require_data_url();module2.exports.parseMIMEType=parseMIMEType;module2.exports.serializeAMimeType=serializeAMimeType;var{CloseEvent,ErrorEvent,MessageEvent}=require_events(),{WebSocket,ping}=require_websocket();module2.exports.WebSocket=WebSocket;module2.exports.CloseEvent=CloseEvent;module2.exports.ErrorEvent=ErrorEvent;module2.exports.MessageEvent=MessageEvent;module2.exports.ping=ping;module2.exports.WebSocketStream=require_websocketstream().WebSocketStream;module2.exports.WebSocketError=require_websocketerror().WebSocketError;module2.exports.request=makeDispatcher(api.request);module2.exports.stream=makeDispatcher(api.stream);module2.exports.pipeline=makeDispatcher(api.pipeline);module2.exports.connect=makeDispatcher(api.connect);module2.exports.upgrade=makeDispatcher(api.upgrade);module2.exports.MockClient=MockClient;module2.exports.MockCallHistory=MockCallHistory;module2.exports.MockCallHistoryLog=MockCallHistoryLog;module2.exports.MockPool=MockPool;module2.exports.MockAgent=MockAgent;module2.exports.SnapshotAgent=SnapshotAgent;module2.exports.mockErrors=mockErrors;var{EventSource}=require_eventsource();module2.exports.EventSource=EventSource;function install(){globalThis.fetch=module2.exports.fetch,globalThis.Headers=module2.exports.Headers,globalThis.Response=module2.exports.Response,globalThis.Request=module2.exports.Request,globalThis.FormData=module2.exports.FormData,globalThis.WebSocket=module2.exports.WebSocket,globalThis.CloseEvent=module2.exports.CloseEvent,globalThis.ErrorEvent=module2.exports.ErrorEvent,globalThis.MessageEvent=module2.exports.MessageEvent,globalThis.EventSource=module2.exports.EventSource}module2.exports.install=install}});import{SousError as SousError10}from"@sous-io/sous-plugin-api";function proxySettings(env){let read=name=>(env[name.toLowerCase()]??env[name.toUpperCase()]??"").trim(),settings={httpProxy:read("HTTP_PROXY"),httpsProxy:read("HTTPS_PROXY"),noProxy:read("NO_PROXY")};return settings.httpProxy===""&&settings.httpsProxy===""?void 0:settings}async function proxiedFetch(settings,made){let key=JSON.stringify(settings),existing=made.get(key);if(existing!==void 0)return existing;let undici=await Promise.resolve().then(()=>__toESM(require_undici(),1)),dispatcher=new undici.EnvHttpProxyAgent(settings),proxied=(url2,init)=>undici.fetch(url2,{...init,dispatcher});return made.set(key,proxied),proxied}function connectionReason(error51){if(!(error51 instanceof Error))return String(error51);let cause=error51.cause;if(cause instanceof Error){let nested=cause.errors;if(cause.message.trim()!=="")return cause.message.trim();if(Array.isArray(nested)&&nested[0]instanceof Error&&nested[0].message.trim()!=="")return nested[0].message.trim();let code=cause.code;if(typeof code=="string")return code}return error51.message}function headersOf(headers){let plain3={};return headers.forEach((value,name)=>{plain3[name.toLowerCase()]=value}),plain3}function wrap(response,durationMs,requested){let body2,read=()=>body2??=response.arrayBuffer().then(buffer=>new Uint8Array(buffer));return{status:response.status,statusText:response.statusText,url:response.url||requested,redirected:response.redirected,headers:headersOf(response.headers),durationMs,async text(){return new TextDecoder().decode(await read())},async json(){return JSON.parse(new TextDecoder().decode(await read()))},bytes:read}}function createHttp(deps={}){let proxied=new Map,request=async req=>{let proxy=deps.fetch===void 0&&deps.env!==void 0?proxySettings(deps.env()):void 0,fetchImpl=deps.fetch??(proxy===void 0?globalThis.fetch:await proxiedFetch(proxy,proxied));if(typeof fetchImpl!="function")throw new HttpError(req.url,`Sous cannot fetch ${req.url}: this Node runtime provides no global fetch. Sous requires Node 22 or newer.`);let timeoutMs=req.timeoutMs??DEFAULT_HTTP_TIMEOUT_MS,timeout=AbortSignal.timeout(timeoutMs),startedAt=performance.now(),init={method:req.method??"GET",headers:req.headers===void 0?void 0:{...req.headers},body:req.body,redirect:req.redirect??"follow",signal:req.signal===void 0?timeout:AbortSignal.any([timeout,req.signal])};try{let response=await fetchImpl(req.url,init);return wrap(response,performance.now()-startedAt,req.url)}catch(error51){throw timeout.aborted?new HttpError(req.url,`The request to ${req.url} did not finish within ${Math.round(timeoutMs/1e3)} seconds.`,{cause:error51,timedOut:!0}):req.signal?.aborted===!0?error51:new HttpError(req.url,`Sous could not reach ${req.url}: ${connectionReason(error51)}.`,{cause:error51})}};return{request,get:(url2,options2={})=>request({...options2,url:url2})}}var DEFAULT_HTTP_TIMEOUT_MS,HttpError,init_http=__esm({"../sous-plugin-host/src/http.ts"(){"use strict";DEFAULT_HTTP_TIMEOUT_MS=15e3,HttpError=class extends SousError10{url;timedOut;constructor(url2,message2,options2={}){super(message2,{cause:options2.cause,details:options2.details}),this.url=url2,this.timedOut=options2.timedOut??!1}}}});import{existsSync as existsSync2,readFileSync as readFileSync2,realpathSync as realpathSync2}from"node:fs";import path14 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";import{PluginError as PluginError5}from"@sous-io/sous-plugin-api";function readPackage(file2){try{return JSON.parse(readFileSync2(file2,"utf8"))}catch{return}}function findRoot(from,names2){let current=path14.resolve(from);for(;;){for(let root of[current,path14.join(current,"packages","sous")]){let manifest=readPackage(path14.join(root,"package.json"));if(manifest?.name!==void 0&&names2.includes(manifest.name))return{root,version:manifest.version??"0.0.0"}}let parent=path14.dirname(current);if(parent===current)return;current=parent}}function createPackage(options2={}){let identity2;return{identity(){if(identity2!==void 0)return identity2;let names2=options2.names??SOUS_PACKAGE_NAMES,bin="bin"in options2?options2.bin:process.argv[1],startDir=options2.startDir??path14.dirname(fileURLToPath2(import.meta.url)),starts=[startDir];bin!==void 0&&existsSync2(bin)&&starts.push(path14.dirname(realpathSync2(bin)));for(let start2 of starts){let found=findRoot(start2,names2);if(found!==void 0)return identity2={name:readPackage(path14.join(found.root,"package.json"))?.name??names2[0],version:found.version,root:found.root,realRoot:realpathSync2(found.root),bin},identity2}throw new PluginError5("@sous-io/sous-plugin-host",`Could not find the installed sous: no package.json named ${names2.join(" or ")} above ${startDir}.`)}}}var SOUS_PACKAGE_NAMES,init_package_identity=__esm({"../sous-plugin-host/src/package-identity.ts"(){"use strict";SOUS_PACKAGE_NAMES=["@sous-io/sous"]}});import{spawn,spawnSync}from"node:child_process";import{constants,existsSync as existsSync3,promises as fs11}from"node:fs";import path15 from"node:path";import{SousError as SousError11}from"@sous-io/sous-plugin-api";function cleanEnvironment(env){let clean2={};for(let[name,value]of Object.entries(env))value!==void 0&&(clean2[name]=value);return clean2}function failedToStart(command,args,error51,startedAt,cwd){let missing=error51.code==="ENOENT",reason=missing&&cwd!==void 0&&!existsSync3(cwd)?`The directory ${cwd} does not exist`:missing?`${command} is not installed, or is not on your PATH`:error51.message;return{command,args,exitCode:NOT_FOUND_EXIT_CODE,signal:null,stdout:"",stderr:reason,durationMs:performance.now()-startedAt,timedOut:!1}}function checked(result,options2){if(options2.reject===!0&&(result.exitCode!==0||result.timedOut))throw new ProcessError(result);return result}function fromSync(command,args,raw2,startedAt,cwd){let error51=raw2.error;return error51!==void 0&&error51.code!=="ETIMEDOUT"?failedToStart(command,args,error51,startedAt,cwd):{command,args,exitCode:raw2.status,signal:raw2.signal,stdout:raw2.stdout??"",stderr:raw2.stderr??"",durationMs:performance.now()-startedAt,timedOut:error51?.code==="ETIMEDOUT"}}function searchPlaces(env){let windows=process.platform==="win32",key=Object.keys(env).find(name=>name.toUpperCase()==="PATH")??"PATH",directories=(env[key]??"").split(path15.delimiter).filter(entry=>entry.length>0),extensions=windows?["",...(env.PATHEXT??".EXE;.CMD;.BAT").split(";").filter(entry=>entry.length>0)]:[""];return{directories,extensions}}async function isExecutable(file2){try{return(await fs11.stat(file2)).isFile()?(await fs11.access(file2,constants.X_OK),!0):!1}catch{return!1}}function createProcesses(deps){let environmentOf=options2=>cleanEnvironment(options2.env??deps.env),platform=deps.platform??process.platform,shellFor=(command,options2)=>options2.windowsShell===!0&&platform==="win32"&&!path15.isAbsolute(command);return{run(command,args,options2={}){let startedAt=performance.now();return new Promise((resolve4,reject2)=>{let finish4=result=>{try{resolve4(checked(result,options2))}catch(error51){reject2(error51)}},child2=spawn(command,[...args],{cwd:options2.cwd,env:environmentOf(options2),stdio:["pipe","pipe","pipe"],signal:options2.signal,shell:shellFor(command,options2)}),stdout="",stderr="",timedOut=!1,done2=!1,timer=options2.timeoutMs===void 0?void 0:setTimeout(()=>{timedOut=!0,child2.kill("SIGKILL")},options2.timeoutMs),end=result=>{done2||(done2=!0,clearTimeout(timer),finish4(result))};child2.stdout.setEncoding("utf8").on("data",chunk=>stdout+=chunk),child2.stderr.setEncoding("utf8").on("data",chunk=>stderr+=chunk),child2.stdin.on("error",()=>{}),child2.on("error",error51=>{error51.code!=="ABORT_ERR"&&end({...failedToStart(command,args,error51,startedAt,options2.cwd),stdout})}),child2.on("close",(exitCode,signal)=>{end({command,args,exitCode,signal,stdout,stderr,durationMs:performance.now()-startedAt,timedOut})}),child2.stdin.end(options2.input)})},runSync(command,args,options2={}){let startedAt=performance.now(),raw2=spawnSync(command,[...args],{cwd:options2.cwd,env:environmentOf(options2),input:options2.input,encoding:"utf8",timeout:options2.timeoutMs,killSignal:"SIGKILL",shell:shellFor(command,options2)});return checked(fromSync(command,args,raw2,startedAt,options2.cwd),options2)},runInteractive(command,args,options2={}){let startedAt=performance.now();return new Promise(resolve4=>{let child2=spawn(command,[...args],{cwd:options2.cwd,env:environmentOf(options2),stdio:"inherit",signal:options2.signal,shell:shellFor(command,options2)});child2.on("error",()=>resolve4({exitCode:NOT_FOUND_EXIT_CODE,signal:null,durationMs:performance.now()-startedAt})),child2.on("close",(exitCode,signal)=>resolve4({exitCode,signal,durationMs:performance.now()-startedAt}))})},async which(command,env=deps.env){let{directories,extensions}=searchPlaces(env),candidates=path15.isAbsolute(command)||command.includes("/")?[command]:directories.map(directory=>path15.join(directory,command));for(let candidate of candidates)for(let extension of extensions)if(await isExecutable(candidate+extension))return candidate+extension}}}var NOT_FOUND_EXIT_CODE,ProcessError,init_processes=__esm({"../sous-plugin-host/src/processes.ts"(){"use strict";NOT_FOUND_EXIT_CODE=127,ProcessError=class extends SousError11{result;constructor(result){let label=[result.command,...result.args].join(" "),how=result.timedOut?"did not finish in time and was stopped":result.exitCode===null?`was ended by the signal ${result.signal}`:`failed with exit code ${result.exitCode}`,said=(result.stderr.trim()||result.stdout.trim()).split(`
359
- `).filter(line=>line.length>0);super(`The command '${label}' ${how}.`,{details:said}),this.result=result}}}});import os3 from"node:os";import path16 from"node:path";function expandHome(value){return value==="~"?os3.homedir():value.startsWith("~/")||value.startsWith("~\\")?path16.join(os3.homedir(),value.slice(2)):value}function resolveSousHomePaths(env){let raw2=env[SOUS_HOME_ENV_VAR],root=typeof raw2=="string"&&raw2.trim().length>0?path16.normalize(path16.resolve(expandHome(raw2.trim()))):path16.join(os3.homedir(),SOUS_HOME_DIR_NAME),store2=path16.join(root,STORE_DIR_NAME);return{root,store:store2,indexCache:path16.join(store2,INDEX_CACHE_DIR_NAME),repos:path16.join(root,GLOBAL_REPOS_DIR_NAME),links:path16.join(root,GLOBAL_LINKS_FILENAME),readStrategies:path16.join(store2,READ_STRATEGIES_FILENAME)}}function createSousHome(getEnv){return{paths:env=>resolveSousHomePaths(env??getEnv()),resolve:(...segments)=>path16.join(resolveSousHomePaths(getEnv()).root,...segments)}}var SOUS_HOME_DIR_NAME,SOUS_HOME_ENV_VAR,STORE_DIR_NAME,INDEX_CACHE_DIR_NAME,GLOBAL_REPOS_DIR_NAME,GLOBAL_LINKS_FILENAME,READ_STRATEGIES_FILENAME,init_sous_home=__esm({"../sous-plugin-host/src/sous-home.ts"(){"use strict";SOUS_HOME_DIR_NAME=".sous",SOUS_HOME_ENV_VAR="SOUS_HOME",STORE_DIR_NAME="cache",INDEX_CACHE_DIR_NAME="_indexes",GLOBAL_REPOS_DIR_NAME="repos",GLOBAL_LINKS_FILENAME="sous.links.json",READ_STRATEGIES_FILENAME="read-strategies.json"}});var package_default3,init_package=__esm({"../sous-plugin-host/package.json"(){package_default3={name:"@sous-io/sous-plugin-host",version:"1.1.4",description:"The machine sous runs on: processes, HTTP, globs and paths, sous home, self-describing directories, the .gitignore block, package identity.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*",glob:"^13.0.6",minimatch:"^10.2.4",undici:"^7.30.2"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}}}});import{ConfigError as ConfigError9}from"@sous-io/sous-plugin-api";function isRegexSpelling(entry){return entry.length>=3&&entry.startsWith("/")&&entry.endsWith("/")}function compileEntry(entry,where3,isMatch){if(!isRegexSpelling(entry))return text=>isMatch(text,entry);let expression;try{expression=new RegExp(entry.slice(1,-1))}catch(error51){let reason=error51 instanceof Error?error51.message:String(error51);throw new ConfigError9(`The value ${JSON.stringify(entry)} in '${where3}' is written as a regular expression, but it is not a valid one: ${reason}`)}return text=>expression.test(text)}function compilePatternList(entries,where3,isMatch){let matchers=(entries??[]).map(entry=>compileEntry(entry,where3,isMatch));return text=>matchers.some(matches=>matches(text))}function compilePatternFinder(entries,where3,isMatch){let matchers=(entries??[]).map(entry=>compileEntry(entry,where3,isMatch));return text=>{let index=matchers.findIndex(matches=>matches(text));return index===-1?void 0:`${where3}[${index}]`}}var init_pattern_list=__esm({"../sous-plugin-host/src/pattern-list.ts"(){"use strict"}});import{definePlugin as definePlugin3,jsonSchema as jsonSchema6}from"@sous-io/sous-plugin-api";var PLUGIN_NAME2,pointerFileSchema,hostPlugin,init_src2=__esm({"../sous-plugin-host/src/index.ts"(){"use strict";init_directories();init_gitignore();init_globs();init_http();init_package_identity();init_processes();init_sous_home();init_package();init_directories();init_gitignore();init_globs();init_http();init_package_identity();init_pattern_list();init_processes();init_readmes();init_sous_home();PLUGIN_NAME2="@sous-io/sous-plugin-host",pointerFileSchema=jsonSchema6({type:"object",properties:{id:{type:"string"},fileName:{type:"string",minLength:1},content:{type:"string"}},required:["id","fileName"]}),hostPlugin=definePlugin3({name:PLUGIN_NAME2,version:package_default3.version,description:"The machine sous runs on: processes, HTTP, globs and paths, sous home, self-describing directories, the .gitignore block, package identity.",dependsOn:{},register(sous){sous.entities.define("pointer-file",pointerFileSchema,{description:"A one-line file written once into every self-describing directory, telling an agent to read its README."}),sous.services.add("host.processes",(_config,ctx)=>createProcesses({env:ctx.env}),{lifetime:"singleton"}),sous.services.add("host.http",(_config,ctx)=>createHttp({env:()=>ctx.env}),{lifetime:"singleton"}),sous.services.add("host.globs",()=>hostGlobs,{lifetime:"singleton"}),sous.services.add("host.sous-home",(_config,ctx)=>createSousHome(()=>ctx.env),{lifetime:"singleton"}),sous.services.add("host.gitignore",()=>createGitignore(),{lifetime:"singleton"}),sous.services.add("host.package",()=>createPackage(),{lifetime:"singleton"}),sous.services.add("host.directories",(_config,ctx)=>createDirectories({entities:ctx.entities,sousHome:ctx.services.get("host.sous-home")}),{lifetime:"config"})}})}});import{SousError as SousError12}from"@sous-io/sous-plugin-api";var GIT_TIMEOUT_EXIT_CODE,GitError,init_errors=__esm({"../sous-plugin-git/src/errors.ts"(){"use strict";GIT_TIMEOUT_EXIT_CODE=124,GitError=class extends SousError12{result;cwd;timedOut;constructor(result,options2={}){let timedOut=options2.timedOut??!1,said=(result.stderr.trim()||result.stdout.trim()).split(`
359
+ `).filter(line=>line.length>0);super(`The command '${label}' ${how}.`,{details:said}),this.result=result}}}});import os3 from"node:os";import path16 from"node:path";function expandHome(value){return value==="~"?os3.homedir():value.startsWith("~/")||value.startsWith("~\\")?path16.join(os3.homedir(),value.slice(2)):value}function resolveSousHomePaths(env){let raw2=env[SOUS_HOME_ENV_VAR],root=typeof raw2=="string"&&raw2.trim().length>0?path16.normalize(path16.resolve(expandHome(raw2.trim()))):path16.join(os3.homedir(),SOUS_HOME_DIR_NAME),store2=path16.join(root,STORE_DIR_NAME);return{root,store:store2,indexCache:path16.join(store2,INDEX_CACHE_DIR_NAME),repos:path16.join(root,GLOBAL_REPOS_DIR_NAME),links:path16.join(root,GLOBAL_LINKS_FILENAME),readStrategies:path16.join(store2,READ_STRATEGIES_FILENAME)}}function createSousHome(getEnv){return{paths:env=>resolveSousHomePaths(env??getEnv()),resolve:(...segments)=>path16.join(resolveSousHomePaths(getEnv()).root,...segments)}}var SOUS_HOME_DIR_NAME,SOUS_HOME_ENV_VAR,STORE_DIR_NAME,INDEX_CACHE_DIR_NAME,GLOBAL_REPOS_DIR_NAME,GLOBAL_LINKS_FILENAME,READ_STRATEGIES_FILENAME,init_sous_home=__esm({"../sous-plugin-host/src/sous-home.ts"(){"use strict";SOUS_HOME_DIR_NAME=".sous",SOUS_HOME_ENV_VAR="SOUS_HOME",STORE_DIR_NAME="cache",INDEX_CACHE_DIR_NAME="_indexes",GLOBAL_REPOS_DIR_NAME="repos",GLOBAL_LINKS_FILENAME="sous.links.json",READ_STRATEGIES_FILENAME="read-strategies.json"}});var package_default3,init_package=__esm({"../sous-plugin-host/package.json"(){package_default3={name:"@sous-io/sous-plugin-host",version:"1.1.6",description:"The machine sous runs on: processes, HTTP, globs and paths, sous home, self-describing directories, the .gitignore block, package identity.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*",glob:"^13.0.6",minimatch:"^10.2.4",undici:"^7.30.2"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}}}});import{ConfigError as ConfigError9}from"@sous-io/sous-plugin-api";function isRegexSpelling(entry){return entry.length>=3&&entry.startsWith("/")&&entry.endsWith("/")}function compileEntry(entry,where3,isMatch){if(!isRegexSpelling(entry))return text=>isMatch(text,entry);let expression;try{expression=new RegExp(entry.slice(1,-1))}catch(error51){let reason=error51 instanceof Error?error51.message:String(error51);throw new ConfigError9(`The value ${JSON.stringify(entry)} in '${where3}' is written as a regular expression, but it is not a valid one: ${reason}`)}return text=>expression.test(text)}function compilePatternList(entries,where3,isMatch){let matchers=(entries??[]).map(entry=>compileEntry(entry,where3,isMatch));return text=>matchers.some(matches=>matches(text))}function compilePatternFinder(entries,where3,isMatch){let matchers=(entries??[]).map(entry=>compileEntry(entry,where3,isMatch));return text=>{let index=matchers.findIndex(matches=>matches(text));return index===-1?void 0:`${where3}[${index}]`}}var init_pattern_list=__esm({"../sous-plugin-host/src/pattern-list.ts"(){"use strict"}});import{definePlugin as definePlugin3,jsonSchema as jsonSchema6}from"@sous-io/sous-plugin-api";var PLUGIN_NAME2,pointerFileSchema,hostPlugin,init_src2=__esm({"../sous-plugin-host/src/index.ts"(){"use strict";init_directories();init_gitignore();init_globs();init_http();init_package_identity();init_processes();init_sous_home();init_package();init_directories();init_gitignore();init_globs();init_http();init_package_identity();init_pattern_list();init_processes();init_readmes();init_sous_home();PLUGIN_NAME2="@sous-io/sous-plugin-host",pointerFileSchema=jsonSchema6({type:"object",properties:{id:{type:"string"},fileName:{type:"string",minLength:1},content:{type:"string"}},required:["id","fileName"]}),hostPlugin=definePlugin3({name:PLUGIN_NAME2,version:package_default3.version,description:"The machine sous runs on: processes, HTTP, globs and paths, sous home, self-describing directories, the .gitignore block, package identity.",dependsOn:{},register(sous){sous.entities.define("pointer-file",pointerFileSchema,{description:"A one-line file written once into every self-describing directory, telling an agent to read its README."}),sous.services.add("host.processes",(_config,ctx)=>createProcesses({env:ctx.env}),{lifetime:"singleton"}),sous.services.add("host.http",(_config,ctx)=>createHttp({env:()=>ctx.env}),{lifetime:"singleton"}),sous.services.add("host.globs",()=>hostGlobs,{lifetime:"singleton"}),sous.services.add("host.sous-home",(_config,ctx)=>createSousHome(()=>ctx.env),{lifetime:"singleton"}),sous.services.add("host.gitignore",()=>createGitignore(),{lifetime:"singleton"}),sous.services.add("host.package",()=>createPackage(),{lifetime:"singleton"}),sous.services.add("host.directories",(_config,ctx)=>createDirectories({entities:ctx.entities,sousHome:ctx.services.get("host.sous-home")}),{lifetime:"config"})}})}});import{SousError as SousError12}from"@sous-io/sous-plugin-api";var GIT_TIMEOUT_EXIT_CODE,GitError,init_errors=__esm({"../sous-plugin-git/src/errors.ts"(){"use strict";GIT_TIMEOUT_EXIT_CODE=124,GitError=class extends SousError12{result;cwd;timedOut;constructor(result,options2={}){let timedOut=options2.timedOut??!1,said=(result.stderr.trim()||result.stdout.trim()).split(`
360
360
  `).filter(line=>line.length>0),details=[];options2.cwd!==void 0&&details.push(`It was run in ${options2.cwd}.`),details.push(...said),timedOut&&options2.timeoutMs!==void 0&&details.push(`Sous stops this command after ${Math.round(options2.timeoutMs/1e3)} seconds.`),result.exitCode===127&&details.push("Sous fetches recipes with git, so git must be installed and on your PATH."),super(timedOut?`The command 'git ${result.args.join(" ")}' did not finish in time and was stopped.`:`The command 'git ${result.args.join(" ")}' failed with exit code ${result.exitCode}.`,{details}),this.result=result,this.cwd=options2.cwd,this.timedOut=timedOut}}}});import{promises as fs12}from"node:fs";import os4 from"node:os";import path17 from"node:path";function batchSshCommand(command){let trimmed=command?.trim()??"";if(trimmed.length===0)return"ssh -o BatchMode=yes";if(/batchmode/i.test(trimmed))return trimmed;let name=(/^"([^"]*)"|^'([^']*)'|^(\S+)/.exec(trimmed)?.slice(1).find(part=>part!==void 0)??"").split(/[\\/]/).pop()??"";return/^ssh(\.exe)?$/i.test(name)?`${trimmed} -o BatchMode=yes`:void 0}function chomp(text){return text.replace(/\r?\n$/,"")}function looksLikeOption(text){return text.startsWith("-")}function createGitRunner(deps){let environmentFor=options2=>({...deps.env,...options2.env,GIT_TERMINAL_PROMPT:"0"}),toResult=(args,raw2)=>({args,exitCode:raw2.timedOut?GIT_TIMEOUT_EXIT_CODE:raw2.exitCode??1,stdout:chomp(raw2.stdout),stderr:raw2.stderr.trim(),durationMs:raw2.durationMs}),check3=(result,raw2,options2)=>{if((options2.reject??!0)&&result.exitCode!==0)throw new GitError(result,{cwd:options2.cwd,timedOut:raw2.timedOut,timeoutMs:options2.timeoutMs});return result},processOptions=(args,options2)=>({cwd:options2.cwd,env:environmentFor(options2),input:options2.input,timeoutMs:options2.timeoutMs,signal:options2.signal,label:`git ${args[0]??""}`.trim()}),run=async(args,options2)=>{let raw2=await deps.processes.run("git",args,processOptions(args,options2));return check3(toResult(args,raw2),raw2,options2)},ask3=async(args,cwd)=>{let result=await run(args,{cwd,reject:!1});return result.exitCode===0&&result.stdout.length>0?result.stdout:void 0},configuredSsh,configuredSshCommand=()=>(configuredSsh??=ask3(["config","--get","core.sshCommand"],deps.env.TMPDIR??os4.tmpdir()),configuredSsh),downloadEnvironment=async extra=>{let env={...deps.env,...extra};if((env.GIT_SSH??"")!=="")return{...extra};let own=(env.GIT_SSH_COMMAND??"")!==""?env.GIT_SSH_COMMAND:await configuredSshCommand(),command=batchSshCommand(own);return command===void 0?{...extra}:{...extra,GIT_SSH_COMMAND:command}},lines3=text=>(text??"").split(`
361
- `).map(line=>line.trim()).filter(line=>line.length>0);return{run,runSync(args,options2){let raw2=deps.processes.runSync("git",args,processOptions(args,options2));return check3(toResult(args,raw2),raw2,options2)},async available(){return await deps.processes.which("git",deps.env)!==void 0},async version(){let raw2=await deps.processes.run("git",["--version"],{env:environmentFor({}),label:"git --version"});return raw2.exitCode===0?/(\d+\.\d+(?:\.\d+)?)/.exec(raw2.stdout)?.[1]:void 0},root:cwd=>ask3(["rev-parse","--show-toplevel"],cwd),currentBranch:cwd=>ask3(["symbolic-ref","--quiet","--short","HEAD"],cwd),async revParse(ref,cwd){if(!looksLikeOption(ref))return ask3(["rev-parse","--verify","--quiet",`${ref}^{commit}`],cwd)},async status(cwd){let parts=(await run(["status","--porcelain=v1","-z"],{cwd})).stdout.split("\0"),entries=[];for(let index=0;index<parts.length;index+=1){let part=parts[index];if(part.length<4)continue;let code=part.slice(0,2),entryPath=part.slice(3);code.includes("R")||code.includes("C")?(entries.push({path:entryPath,code,from:parts[index+1]??""}),index+=1):entries.push({path:entryPath,code})}return entries},async tags(cwd,pattern){return lines3((await run(pattern===void 0?["tag","--list"]:["tag","--list",pattern],{cwd})).stdout)},async remoteUrl(cwd,remote="origin"){return looksLikeOption(remote)?void 0:ask3(["remote","get-url",remote],cwd)},async clone(url2,directory,options2={}){let parent=path17.dirname(directory),sparse=options2.sparsePaths!==void 0&&options2.sparsePaths.length>0,args=["clone",...LF_CHECKOUT_OPTIONS];options2.depth!==void 0&&options2.depth>0&&args.push("--depth",String(options2.depth)),sparse&&args.push("--filter=blob:none","--sparse"),options2.branch!==void 0&&args.push("--branch",options2.branch),options2.noCheckout===!0&&args.push("--no-checkout"),args.push("--",url2,directory),await fs12.mkdir(parent,{recursive:!0}),await run(args,{cwd:parent,env:await downloadEnvironment(options2.env),timeoutMs:options2.timeoutMs??GIT_DOWNLOAD_TIMEOUT_MS,signal:options2.signal}),sparse&&await run(["sparse-checkout","set","--",...options2.sparsePaths],{cwd:directory,env:options2.env,signal:options2.signal})},async readRemoteFile(url2,filePath,options2={}){if(looksLikeOption(url2))throw new GitError({args:["fetch",url2],exitCode:1,stdout:"",stderr:`${url2} is not a repository address.`,durationMs:0});let ref=options2.ref??"HEAD",tmp=await fs12.mkdtemp(path17.join(deps.env.TMPDIR??os4.tmpdir(),"sous-git-read-")),common={cwd:tmp,env:await downloadEnvironment(options2.env),timeoutMs:options2.timeoutMs??GIT_DOWNLOAD_TIMEOUT_MS,signal:options2.signal};try{await run(["init","--quiet"],common),await run(["remote","add","origin","--",url2],common),await run(["fetch","--quiet","--depth","1","--filter=blob:none","origin",ref],common);let shown=await run(["show",`FETCH_HEAD:${filePath}`],{...common,reject:!1});if(shown.exitCode!==0)throw new GitError(shown,{cwd:tmp});return shown.stdout}finally{await fs12.rm(tmp,{recursive:!0,force:!0})}}}}var LF_CHECKOUT_OPTIONS,GIT_DOWNLOAD_TIMEOUT_MS,init_runner=__esm({"../sous-plugin-git/src/runner.ts"(){"use strict";init_errors();LF_CHECKOUT_OPTIONS=["--config","core.autocrlf=false","--config","core.eol=lf"],GIT_DOWNLOAD_TIMEOUT_MS=12e4}});var package_default4,init_package2=__esm({"../sous-plugin-git/package.json"(){package_default4={name:"@sous-io/sous-plugin-git",version:"1.1.4",description:"The one git runner.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-host":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}}}});import{definePlugin as definePlugin4}from"@sous-io/sous-plugin-api";var PLUGIN_NAME3,gitPlugin,init_src3=__esm({"../sous-plugin-git/src/index.ts"(){"use strict";init_runner();init_package2();init_errors();init_runner();PLUGIN_NAME3="@sous-io/sous-plugin-git",gitPlugin=definePlugin4({name:PLUGIN_NAME3,version:package_default4.version,description:"The one git runner.",dependsOn:{"@sous-io/sous-plugin-host":`^${package_default4.version}`},register(sous){sous.services.add("git.runner",(_config,ctx)=>createGitRunner({processes:ctx.services.get("host.processes"),env:ctx.env}),{lifetime:"singleton"})}})}});function repoOf(ref){switch(ref.kind){case"repo":return ref;case"namespace":return ref.repo;case"recipe":return ref.namespace?.repo??ref.repo;case"recipeFile":return repoOf(ref.recipe);case"variable":return ref.recipe===void 0?ref.repo:repoOf(ref.recipe)??ref.repo;case"envVar":return}}function locationOf(ref){return repoOf(ref)?.location}function namespaceOf(ref){switch(ref.kind){case"namespace":return ref;case"recipe":return ref.namespace;case"recipeFile":return ref.recipe.namespace;case"variable":return ref.recipe?.namespace;default:return}}function recipeOf(ref){switch(ref.kind){case"recipe":return ref;case"recipeFile":case"variable":return ref.recipe;default:return}}function rangeOf(ref){return ref.kind==="recipe"||ref.kind==="recipeFile"||ref.kind==="repo"?ref.range:void 0}function qualificationOf(candidate){return candidate.kind==="envVar"?3:candidate.kind==="repo"||repoOf(candidate)!==void 0?0:candidate.kind==="recipe"&&candidate.namespace!==void 0||candidate.kind==="recipeFile"||candidate.kind==="variable"&&candidate.recipe!==void 0?1:2}function isStoredKind(ref){return ref.kind==="namespace"||ref.kind==="recipe"&&ref.namespace!==void 0}function shortKey(ref){let namespace=namespaceOf(ref)?.name,recipe=ref.kind==="namespace"?void 0:recipeOf(ref)?.name;return namespace===void 0?recipe??"":recipe===void 0?namespace:`${namespace}/${recipe}`}var REF_KINDS,KIND_LABELS,init_parts=__esm({"../sous-plugin-refs/src/parts.ts"(){"use strict";REF_KINDS=["repo","namespace","recipe","recipeFile","variable","envVar"],KIND_LABELS={repo:"repository",namespace:"namespace",recipe:"recipe",recipeFile:"recipe file",variable:"variable",envVar:"environment variable"}}});import{ConfigError as ConfigError10}from"@sous-io/sous-plugin-api";function repoPart(repo){return repo===void 0?void 0:repo.name??repo.location?.identity}function pathPart(ref){switch(ref.kind){case"repo":return ref.browsed===void 0?"":`tree/${ref.browsed}`;case"namespace":return ref.name;case"recipe":return ref.namespace===void 0?ref.name:`${ref.namespace.name}/${ref.name}`;case"recipeFile":return`${pathPart(ref.recipe)}/${ref.path}`;case"variable":return`${ref.recipe===void 0?"":`${pathPart(ref.recipe)}.`}${ref.name}`;case"envVar":return ref.name}}function refKey(ref){let repo=ref.kind==="envVar"?void 0:repoPart(repoOf(ref)),rest=pathPart(ref);return repo===void 0?rest:ref.kind==="repo"&&rest===""?repo:`${repo}:${rest}`}function storedKey(ref){return ref.kind==="repo"?refKey(ref):pathPart(ref)}function refIdentity(ref){return`${ref.kind} ${refKey(ref)}`}function repoLabel(repo){return repo?.name??repo?.location?.url??"unknown"}function isNamedRef(ref){return ref.kind==="namespace"||ref.kind==="recipe"&&ref.namespace!==void 0}function namespaceRef(name,repo){return{kind:"namespace",name,...repo===void 0?{}:{repo:{kind:"repo",name:repo}}}}function recipeRef(namespace,name,options2={}){return{kind:"recipe",name,namespace:namespaceRef(namespace,options2.repo),...options2.range===void 0?{}:{range:options2.range}}}function formatter(locations){let qualified=(repo,rest)=>{if(repo===void 0)return rest;if(repo.name!==void 0)return rest===""?repo.name:`${repo.name}:${rest}`;if(repo.location!==void 0){let{host,repoPath,url:url2,provider}=repo.location,reader=provider==="local"?void 0:locations().host(provider);return reader!==void 0?reader.formatLocator(host,repoPath,rest):rest===""?url2:`${url2}/${rest}`}return rest},format3=ref=>{let body2=qualified(ref.kind==="envVar"?void 0:repoOf(ref),pathPart(ref)),range3=rangeOf(ref),pairs=Object.entries(ref.vars??{}).map(([name,value])=>`${encodeURIComponent(name)}=${encodeURIComponent(value)}`);return`${body2}${range3===void 0?"":`@${range3}`}${pairs.length===0?"":`?${pairs.join("&")}`}`},spelling=ref=>{let repo=ref.kind==="envVar"?void 0:repoOf(ref);return repo!==void 0&&repo.name===void 0&&repo.location!==void 0?format3(ref):refKey(ref)};return{format:format3,spelling,describe:ref=>{let summary2=ref.description===void 0?"":`: ${ref.description}`,key=spelling(ref);switch(ref.kind){case"repo":{let where3=ref.location?.url;return`${key} (the repository '${ref.name??key}'${where3===void 0?"":`, at ${where3}`})`}case"namespace":return`${key} (the whole namespace '${ref.name}' in the repository '${repoLabel(ref.repo)}')`;case"recipe":return`${key} (the recipe '${ref.name}' in the namespace '${ref.namespace?.name??"unknown"}' of the repository '${repoLabel(repoOf(ref))}'${summary2})`;case"recipeFile":return`${key} (the file '${ref.path}' of the recipe '${pathPart(ref.recipe)}'${summary2})`;case"variable":return`${key} (the variable '${ref.name}' of the recipe '${ref.recipe===void 0?"unknown":pathPart(ref.recipe)}'${summary2})`;case"envVar":{let first2=ref.variables?.[0],answers=first2===void 0?"":` answering '${first2.name}' of the recipe '${first2.recipe===void 0?"unknown":pathPart(first2.recipe)}'`;return`${ref.name} (the environment variable${answers}${summary2})`}}}}}function createRefsFormat(ctx){let written=formatter(()=>ctx.services.get("refs.locations")),storedKeys=new Map,parseNamedRef=(input,from="commandLine")=>{let{refs}=ctx.services.get("refs.resolver").parse(input,from),named=refs.filter(ref=>isNamedRef(ref)&&locationOf(ref)===void 0);if(named.length===1&&!refs.some(ref=>locationOf(ref)!==void 0))return named[0];throw new ConfigError10(`Invalid ref '${input}': this needs a namespace or a recipe named by its short form, such as 'workflow/alpha', and this ref names a location.`)},readStoredKey=key=>{let known=storedKeys.get(key);if(known!==void 0)return known;let parsed=parseNamedRef(key,"lockfile"),read=parsed.kind==="namespace"?{namespace:parsed.name}:{namespace:parsed.namespace.name,name:parsed.name};return storedKeys.set(key,read),read};return{key:storedKey,identity(ref){let location=locationOf(ref);if(location===void 0)return refKey(ref);let rest=pathPart(ref);return rest===""?location.identity:`${location.identity}:${rest}`},...written,kindLabel:ref=>KIND_LABELS[ref.kind],splitRecipeKey(key){let{namespace,name}=readStoredKey(key);if(name===void 0)throw new ConfigError10(`Invalid ref '${key}': a recipe key names a namespace and a recipe.`,{details:["A stored key is written as 'namespace' or 'namespace/recipe'."]});return{namespace,name}},namespaceOfKey:key=>readStoredKey(key).namespace,namespaceRef,recipeRef,parseNamedRef,partsOf(ref){let repo=repoOf(ref),namespace=namespaceOf(ref),recipe=recipeOf(ref),range3=rangeOf(ref);return{...repo===void 0?{}:{repo},...namespace===void 0?{}:{namespace},...recipe===void 0?{}:{recipe},...range3===void 0?{}:{range:range3}}}}}var init_format2=__esm({"../sous-plugin-refs/src/format.ts"(){"use strict";init_parts()}});var VALID_NAME,hashNameSchema,projectHashName,init_hash_names=__esm({"../sous-plugin-refs/src/hash-names.ts"(){"use strict";VALID_NAME=/^[a-z][a-z0-9-]*$/,hashNameSchema={"~standard":{version:1,vendor:"sous",validate(value){let entry=value,issues=[];return typeof entry!="object"||entry===null?{issues:[{message:"Expected an object."}]}:((typeof entry.id!="string"||!VALID_NAME.test(entry.id))&&issues.push({message:`The name '#${String(entry.id)}' is invalid: a name is lowercase kebab-case, a letter then letters, digits or hyphens.`,path:["id"]}),typeof entry.description!="string"&&issues.push({message:"Required, but missing.",path:["description"]}),entry.bases!==void 0&&typeof entry.bases!="function"&&issues.push({message:"Expected a function.",path:["bases"]}),entry.view!==void 0&&typeof entry.view!="function"&&issues.push({message:"Expected a function.",path:["view"]}),entry.bases!==void 0&&entry.view!==void 0&&issues.push({message:"A name either stands for directories ('bases') or lists files ('view'), not both."}),issues.length>0?{issues}:{value:entry})}}},projectHashName={id:"project",description:"the root directory of the project being built.",bases:ctx=>ctx.project===void 0?[]:[ctx.project.root]}}});function repositoryIdentity(canonical){let name=canonical.name.replace(/\.git$/i,"");return identitySegments(`${canonical.host}/${canonical.owner}/${name}`).join("/")}function identitySegments(identity2){return identity2.split("/").map(segment=>segment.trim().toLowerCase()).filter(segment=>segment.length>0)}function shortNameFromIdentity(identity2){let segments=identitySegments(identity2),cleaned=(segments[segments.length-1]??"").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");return SHORT_NAME.test(cleaned)?cleaned:cleaned.length===0?"repository":`repo-${cleaned}`}var SHORT_NAME,init_identity=__esm({"../sous-plugin-refs/src/locations/identity.ts"(){"use strict";SHORT_NAME=/^[a-z][a-z0-9-]*$/}});import{ConfigError as ConfigError11}from"@sous-io/sous-plugin-api";function repositoryHosts(entities){return entities.list(REPOSITORY_HOST_KIND)}function schemesOf(host){return host.schemes??[host.id]}function hostedIds(hosts){return hosts.filter(host=>host.defaultHost!==void 0).map(host=>host.id).sort()}function createRefsLocations(entities){let hosts=()=>repositoryHosts(entities),hostById=id=>hosts().find(host=>host.id===id),hostFor2=url2=>hosts().find(host=>host.matches(url2)),asUrl=url2=>{let scheme=SCHEME.exec(url2.trim());if(scheme===null||URL_SCHEMES.has(scheme[1].toLowerCase()))return{url:url2};let name=scheme[1].toLowerCase(),host=hosts().find(entry=>schemesOf(entry).includes(name));if(host?.defaultHost===void 0)return{url:url2};let path122=scheme[2].replace(/^\/+/,"");return{url:`https://${(path122.split("/")[0]??"").includes(".")?path122:`${host.defaultHost}/${path122}`}`,host}},requireHost=(url2,provider)=>{let known=hosts().map(host=>host.id).join(", ")||"none";if(provider!==void 0){let named=hostById(provider);if(named===void 0)throw new ConfigError11(`The repository at ${url2} names the provider '${provider}', which sous does not have.`,{details:[`Sous has these providers: ${known}.`]});if(!named.matches(url2)){let owner=hostFor2(url2);if(owner!==void 0&&owner.id!==named.id)throw new ConfigError11(`The ${named.id} provider does not handle ${url2}; that is ${owner.id==="local"?"a local path":`a ${owner.id} URL`}, which the ${owner.id} provider handles.`,{details:[`Drop '--provider' and let sous work it out, or name '${owner.id}'.`]})}return named}let detected=hostFor2(url2);if(detected!==void 0)return detected;throw new ConfigError11(`Sous does not recognize the host in the repository URL ${url2}.`,{details:[`Sous has these providers: ${known}. For a self-hosted instance, name the provider that host runs on the repository entry, as in 'sous repo add ${url2} --provider <provider>'.`]})},canonicalize=(url2,provider)=>{let target=asUrl(url2);return(provider===void 0&&target.host!==void 0?target.host:requireHost(target.url,provider)).canonicalize(target.url)};return{fromUrl(url2,provider){try{let target=asUrl(url2),host=provider===void 0&&target.host!==void 0?target.host:requireHost(target.url,provider),canonical=host.canonicalize(target.url);return{provider:host.id,host:canonical.host,repoPath:`${canonical.owner}/${canonical.name}`,identity:repositoryIdentity(canonical),url:url2}}catch{return}},locationFor(provider,host,repoPath){let reader=hostById(provider);if(reader===void 0)throw new ConfigError11(`No provider '${provider}' reads the repository ${host}/${repoPath}.`);let url2=`https://${host}/${repoPath}`;return{provider,host,repoPath,identity:repositoryIdentity(reader.canonicalize(url2)),url:url2}},canonicalize,identity:(url2,provider)=>repositoryIdentity(canonicalize(url2,provider)),identityOf:repository=>repositoryIdentity(repository),hostFor:hostFor2,host:hostById,hosts,shortName:shortNameFromIdentity}}function tryLocationFor(locations,provider,host,repoPath){try{return locations.locationFor(provider,host,repoPath)}catch{return}}var REPOSITORY_HOST_KIND,URL_SCHEMES,SCHEME,init_locations=__esm({"../sous-plugin-refs/src/locations/locations.ts"(){"use strict";init_identity();REPOSITORY_HOST_KIND="repository-host",URL_SCHEMES=new Set(["http","https","ssh","git","git+ssh","ssh+git"]),SCHEME=/^([a-z][a-z0-9+.-]*):\/\/(.*)$/is}});function splitter(id,order,read){return{id,order,split:(state,ctx)=>state.ref!==void 0?[state]:read(state,ctx)}}function finishRef(state,ref){let withVars=state.vars===void 0?ref:{...ref,vars:state.vars};return{...state,rest:"",ref:withVars}}var SCHEME2,SCP,init_partial_ref=__esm({"../sous-plugin-refs/src/parser/partial-ref.ts"(){"use strict";SCHEME2=/^[a-z][a-z0-9+.-]*:\/\//i,SCP=/^[^@\s/:]+@([^@\s/:]+):(.+)$/s}});function looksLikeLocation(ref){let trimmed=ref.trim();if(SCHEME_PATTERN.test(trimmed)||SCP_PATTERN.test(trimmed))return!0;let first2=trimmed.split("/")[0]??"";return trimmed.includes("/")&&first2.includes(".")&&!first2.includes(":")}function pathSegments(pathname){return pathname.split(/[?#]/)[0].split("/").map(segment=>{try{return decodeURIComponent(segment)}catch{return segment}}).filter(segment=>segment.length>0)}function local(state,path122){return finishRef(state,{kind:"repo",location:{provider:"local",host:"localhost",repoPath:path122,identity:`localhost/${path122.replace(/^\/+/,"")}`,url:state.rest}})}function forHost(state,hosts,hostName,segments){let probe=`https://${hostName}/${segments.slice(0,2).join("/")}`,host=hosts.find(entry=>entry.matches(probe));if(host!==void 0&&host.defaultHost!==void 0)return{host,hostName,segments};let ids=hostedIds(hosts);state.problems.push(`sous does not recognize the host '${hostName}'. For a self-hosted instance, write the location with the provider's scheme and the host, as in '${ids[0]??"gitlab"}://${hostName}/owner/repository/namespace/recipe' (sous has these providers: ${ids.join(", ")||"none"}).`)}function take(state,hosts,scheme){let body2=state.rest;if(scheme!==null){let name=scheme[1].toLowerCase();if(URL_SCHEMES2.has(name)){let url2;try{url2=new URL(body2)}catch{state.problems.push("the URL could not be read.");return}return forHost(state,hosts,url2.host.toLowerCase(),pathSegments(url2.pathname))}let host=hosts.find(entry=>schemesOf(entry).includes(name));if(host?.defaultHost===void 0){state.problems.push(`'${name}' is not a provider sous can read a location from. The scheme of a locator is the provider's own identifier; sous has these: ${hostedIds(hosts).join(", ")||"none"}. An ordinary 'https://' URL works too.`);return}let segments=pathSegments(scheme[2]),hostName=host.defaultHost;return segments[0]?.includes(".")===!0&&(hostName=segments[0].toLowerCase(),segments=segments.slice(1)),{host,hostName,segments}}let scp=SCP_PATTERN.exec(body2);if(scp!==null)return forHost(state,hosts,scp[1].toLowerCase(),pathSegments(scp[2]));let all=pathSegments(body2);return forHost(state,hosts,all[0].toLowerCase(),all.slice(1))}function readLocation(state,locations){if(state.repo!==void 0||!looksLikeLocation(state.rest))return[state];let scheme=SCHEME_PATTERN.exec(state.rest);if(scheme!==null&&LOCAL_SCHEMES.has(scheme[1].toLowerCase()))return[local(state,scheme[2])];let taken=take(state,locations.hosts(),scheme);if(taken===void 0)return[];let{host,hostName,segments}=taken,specific=[],repositories=[];for(let reading of host.readLocation({host:hostName,segments})){let location=tryLocationFor(locations,host.id,hostName,reading.repoPath);if(location===void 0)continue;if(reading.browsed!==void 0){let browsed=reading.browsed.replace(/^\/+|\/+$/g,"");browsed.length>0&&specific.push(finishRef(state,{kind:"repo",location,browsed,...state.range===void 0?{}:{range:state.range}}));continue}let named=reading.named??[];named.length===0?repositories.push({kind:"repo",location}):specific.push({...state,rest:named.join("/"),repo:{kind:"repo",location}})}return specific.length>0?specific:repositories.length===0?(state.problems.push(`the ${host.id} provider cannot read a namespace or a recipe from this location. After the repository, a location names a namespace and optionally a recipe, as in '${host.formatLocator(hostName,"owner/repository","workflow/alpha")}'.`),[]):state.range!==void 0?(state.problems.push("a version range applies to a recipe, not to a repository."),[]):repositories.map(repo=>finishRef(state,repo))}var SCHEME_PATTERN,SCP_PATTERN,URL_SCHEMES2,LOCAL_SCHEMES,locationSplitter,init_location_splitter=__esm({"../sous-plugin-refs/src/parser/location-splitter.ts"(){"use strict";init_locations();init_partial_ref();SCHEME_PATTERN=/^([a-z][a-z0-9+.-]*):\/\/(.*)$/is,SCP_PATTERN=/^[^@\s/:]+@([^@\s/:]+):(.+)$/s,URL_SCHEMES2=new Set(["http","https","ssh","git","git+ssh","ssh+git"]),LOCAL_SCHEMES=new Set(["local","file"]);locationSplitter=splitter("location",30,(state,ctx)=>readLocation(state,ctx.services.get("refs.locations")))}});function isGlobName(text,globs){return globs.hasGlob(text)&&GLOB_NAME.test(text)}function splitSegments(text){let segments=[],depth=0,current="";for(let character of text){if(character==="{"&&(depth+=1),character==="}"&&depth>0&&(depth-=1),character==="/"&&depth===0){segments.push(current),current="";continue}current+=character}return segments.push(current),segments}var NAME_ANY_CASE,VARIABLE_NAME,ENV_VAR_NAME,GLOB_NAME,init_names=__esm({"../sous-plugin-refs/src/names.ts"(){"use strict";NAME_ANY_CASE=/^[a-z][a-z0-9-]*$/i,VARIABLE_NAME=/^[a-z][a-zA-Z0-9]*$/,ENV_VAR_NAME=/^[A-Za-z_][A-Za-z0-9_]*$/,GLOB_NAME=/^[A-Za-z0-9_\-.*?[\]{},!^]+$/}});function isName(reader,segment){return NAME_ANY_CASE.test(segment)||isGlobName(segment,reader.globs)}function isVariableName(reader,segment){return VARIABLE_NAME.test(segment)||isGlobName(segment,reader.globs)}function badName(what,name){return`the ${what} '${name}' must be kebab-case: a letter, then letters, digits or hyphens.`}function withGlob(reader,names2){return names2.some(name=>reader.globs.hasGlob(name))?{glob:!0}:{}}function readOne(reader,text){let{state,make:make2,ns:ns2}=reader,{repo,range:range3}=state,dot=text.indexOf("."),located=repo?.location!==void 0,inRepo=repo===void 0?{}:{repo};if(!located&&dot>0&&dot<text.length-1&&range3===void 0){let left=text.slice(0,dot),right=text.slice(dot+1);isName(reader,left)&&isVariableName(reader,right)&&make2({kind:"variable",name:right,recipe:{kind:"recipe",name:left,...inRepo},...withGlob(reader,[left,right])})}isName(reader,text)&&(range3===void 0?(make2({...ns2(text),...withGlob(reader,[text])}),repo===void 0&&make2({kind:"repo",name:text,...withGlob(reader,[text])})):state.problems.push(NAMESPACE_NOT_VERSIONED),located||make2({kind:"recipe",name:text,...inRepo,...range3===void 0?{}:{range:range3},...withGlob(reader,[text])})),!located&&range3===void 0&&isVariableName(reader,text)&&make2({kind:"variable",name:text,...inRepo,...withGlob(reader,[text])});let readsAsOther=repo===void 0&&(VARIABLE_NAME.test(text)||ENV_VAR_NAME.test(text));!isName(reader,text)&&!readsAsOther&&dot<=0&&state.problems.push(badName("namespace",text))}function readTwo(reader,namespace,second){let{state,make:make2,ns:ns2}=reader,{range:range3}=state,dot=second.indexOf(".");if(second==="*"&&(range3===void 0?make2({...ns2(namespace),wildcard:!0,...withGlob(reader,[namespace])}):state.problems.push(NAMESPACE_NOT_VERSIONED)),dot>0&&dot<second.length-1&&range3===void 0){let left=second.slice(0,dot),right=second.slice(dot+1);isName(reader,left)&&isVariableName(reader,right)&&make2({kind:"variable",name:right,recipe:{kind:"recipe",name:left,namespace:ns2(namespace)},...withGlob(reader,[namespace,left,right])})}isName(reader,second)?make2({kind:"recipe",name:second,namespace:ns2(namespace),...range3===void 0?{}:{range:range3},...withGlob(reader,[namespace,second])}):dot<=0&&state.problems.push(badName("recipe name",second))}var FILE_PATH,NAMESPACE_NOT_VERSIONED,namePathSplitter,init_name_path_splitter=__esm({"../sous-plugin-refs/src/parser/name-path-splitter.ts"(){"use strict";init_names();init_partial_ref();FILE_PATH=/^[^\s\\]+$/,NAMESPACE_NOT_VERSIONED="a version range applies to a recipe, and namespaces are not versioned. Name a recipe, as in 'workflow/task-files@^1.2.0'.";namePathSplitter=splitter("name-path",60,(state,ctx)=>{let segments=splitSegments(state.rest),out=[state],make2=ref=>{out.push(finishRef(state,ref))},repo=state.repo,ns2=name=>({kind:"namespace",name,...repo===void 0?{}:{repo}}),reader={state,globs:ctx.services.get("host.globs"),make:make2,ns:ns2};if(segments[0]==="")return state.problems.push("the namespace is empty."),out;if(segments.length>1&&segments.includes(""))return state.problems.push(segments[segments.length-1]===""?"the recipe name after '/' is empty.":"a ref has an empty segment between two '/'."),out;if(segments.length===1)return readOne(reader,segments[0]),out;let[namespace,second]=segments;if(!isName(reader,namespace))return state.problems.push(badName("namespace",namespace)),out;if(segments.length===2)return readTwo(reader,namespace,second),out;let path122=segments.slice(2).join("/");if(!isName(reader,second))return state.problems.push(badName("recipe name",second)),out;if(!FILE_PATH.test(path122))return state.problems.push(`the path '${path122}' inside a recipe holds a space or a backslash.`),out;let recipe={kind:"recipe",name:second,namespace:ns2(namespace)};return make2({kind:"recipeFile",path:path122,recipe,...state.range===void 0?{}:{range:state.range},...withGlob(reader,[namespace,second,path122])}),out})}});import{ConfigError as ConfigError12}from"@sous-io/sous-plugin-api";function earlyProblem(input){if(typeof input!="string")return"a ref must be a string.";let trimmed=input.trim();if(trimmed.length===0)return"a ref must not be empty.";if(trimmed.startsWith("@"))return"refs take no '@' prefix. The '@' character introduces a version range only, as in 'workflow/task-files@^1.2.0'.";if(trimmed.startsWith("~"))return"refs take no '~' prefix. The '~' sigil belongs to template include lines ('@~workflow/file.md'); a ref itself is written without it."}function finished(states){let seen=new Set,refs=[];for(let state of states){if(state.ref===void 0||state.rest!=="")continue;let key=JSON.stringify(state.ref);seen.has(key)||(seen.add(key),refs.push(state.ref))}return refs.map((ref,position)=>({ref,position})).sort((left,right)=>REF_KINDS.indexOf(left.ref.kind)-REF_KINDS.indexOf(right.ref.kind)||left.position-right.position).map(entry=>entry.ref)}function parseWith(splitters,input,ctx){let early=earlyProblem(input);if(early!==void 0)return{input:String(input),readings:[],problems:[early]};let trimmed=input.trim(),problems=[],ordered2=[...splitters].sort((left,right)=>left.order-right.order),states=[{input:trimmed,rest:trimmed,problems}];for(let entry of ordered2)if(states=states.flatMap(state=>entry.split(state,ctx)),states.length===0)break;return{input,readings:finished(states),problems:[...new Set(problems)]}}function parseError(result){let reasons=result.problems,problem;return reasons.length===0?problem="it does not fit any form of a ref.":reasons.length===1?problem=reasons[0]:problem=`it fits no form of a ref:
361
+ `).map(line=>line.trim()).filter(line=>line.length>0);return{run,runSync(args,options2){let raw2=deps.processes.runSync("git",args,processOptions(args,options2));return check3(toResult(args,raw2),raw2,options2)},async available(){return await deps.processes.which("git",deps.env)!==void 0},async version(){let raw2=await deps.processes.run("git",["--version"],{env:environmentFor({}),label:"git --version"});return raw2.exitCode===0?/(\d+\.\d+(?:\.\d+)?)/.exec(raw2.stdout)?.[1]:void 0},root:cwd=>ask3(["rev-parse","--show-toplevel"],cwd),currentBranch:cwd=>ask3(["symbolic-ref","--quiet","--short","HEAD"],cwd),async revParse(ref,cwd){if(!looksLikeOption(ref))return ask3(["rev-parse","--verify","--quiet",`${ref}^{commit}`],cwd)},async status(cwd){let parts=(await run(["status","--porcelain=v1","-z"],{cwd})).stdout.split("\0"),entries=[];for(let index=0;index<parts.length;index+=1){let part=parts[index];if(part.length<4)continue;let code=part.slice(0,2),entryPath=part.slice(3);code.includes("R")||code.includes("C")?(entries.push({path:entryPath,code,from:parts[index+1]??""}),index+=1):entries.push({path:entryPath,code})}return entries},async tags(cwd,pattern){return lines3((await run(pattern===void 0?["tag","--list"]:["tag","--list",pattern],{cwd})).stdout)},async remoteUrl(cwd,remote="origin"){return looksLikeOption(remote)?void 0:ask3(["remote","get-url",remote],cwd)},async clone(url2,directory,options2={}){let parent=path17.dirname(directory),sparse=options2.sparsePaths!==void 0&&options2.sparsePaths.length>0,args=["clone",...LF_CHECKOUT_OPTIONS];options2.depth!==void 0&&options2.depth>0&&args.push("--depth",String(options2.depth)),sparse&&args.push("--filter=blob:none","--sparse"),options2.branch!==void 0&&args.push("--branch",options2.branch),options2.noCheckout===!0&&args.push("--no-checkout"),args.push("--",url2,directory),await fs12.mkdir(parent,{recursive:!0}),await run(args,{cwd:parent,env:await downloadEnvironment(options2.env),timeoutMs:options2.timeoutMs??GIT_DOWNLOAD_TIMEOUT_MS,signal:options2.signal}),sparse&&await run(["sparse-checkout","set","--",...options2.sparsePaths],{cwd:directory,env:options2.env,signal:options2.signal})},async readRemoteFile(url2,filePath,options2={}){if(looksLikeOption(url2))throw new GitError({args:["fetch",url2],exitCode:1,stdout:"",stderr:`${url2} is not a repository address.`,durationMs:0});let ref=options2.ref??"HEAD",tmp=await fs12.mkdtemp(path17.join(deps.env.TMPDIR??os4.tmpdir(),"sous-git-read-")),common={cwd:tmp,env:await downloadEnvironment(options2.env),timeoutMs:options2.timeoutMs??GIT_DOWNLOAD_TIMEOUT_MS,signal:options2.signal};try{await run(["init","--quiet"],common),await run(["remote","add","origin","--",url2],common),await run(["fetch","--quiet","--depth","1","--filter=blob:none","origin",ref],common);let shown=await run(["show",`FETCH_HEAD:${filePath}`],{...common,reject:!1});if(shown.exitCode!==0)throw new GitError(shown,{cwd:tmp});return shown.stdout}finally{await fs12.rm(tmp,{recursive:!0,force:!0})}}}}var LF_CHECKOUT_OPTIONS,GIT_DOWNLOAD_TIMEOUT_MS,init_runner=__esm({"../sous-plugin-git/src/runner.ts"(){"use strict";init_errors();LF_CHECKOUT_OPTIONS=["--config","core.autocrlf=false","--config","core.eol=lf"],GIT_DOWNLOAD_TIMEOUT_MS=12e4}});var package_default4,init_package2=__esm({"../sous-plugin-git/package.json"(){package_default4={name:"@sous-io/sous-plugin-git",version:"1.1.6",description:"The one git runner.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-host":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}}}});import{definePlugin as definePlugin4}from"@sous-io/sous-plugin-api";var PLUGIN_NAME3,gitPlugin,init_src3=__esm({"../sous-plugin-git/src/index.ts"(){"use strict";init_runner();init_package2();init_errors();init_runner();PLUGIN_NAME3="@sous-io/sous-plugin-git",gitPlugin=definePlugin4({name:PLUGIN_NAME3,version:package_default4.version,description:"The one git runner.",dependsOn:{"@sous-io/sous-plugin-host":`^${package_default4.version}`},register(sous){sous.services.add("git.runner",(_config,ctx)=>createGitRunner({processes:ctx.services.get("host.processes"),env:ctx.env}),{lifetime:"singleton"})}})}});function repoOf(ref){switch(ref.kind){case"repo":return ref;case"namespace":return ref.repo;case"recipe":return ref.namespace?.repo??ref.repo;case"recipeFile":return repoOf(ref.recipe);case"variable":return ref.recipe===void 0?ref.repo:repoOf(ref.recipe)??ref.repo;case"envVar":return}}function locationOf(ref){return repoOf(ref)?.location}function namespaceOf(ref){switch(ref.kind){case"namespace":return ref;case"recipe":return ref.namespace;case"recipeFile":return ref.recipe.namespace;case"variable":return ref.recipe?.namespace;default:return}}function recipeOf(ref){switch(ref.kind){case"recipe":return ref;case"recipeFile":case"variable":return ref.recipe;default:return}}function rangeOf(ref){return ref.kind==="recipe"||ref.kind==="recipeFile"||ref.kind==="repo"?ref.range:void 0}function qualificationOf(candidate){return candidate.kind==="envVar"?3:candidate.kind==="repo"||repoOf(candidate)!==void 0?0:candidate.kind==="recipe"&&candidate.namespace!==void 0||candidate.kind==="recipeFile"||candidate.kind==="variable"&&candidate.recipe!==void 0?1:2}function isStoredKind(ref){return ref.kind==="namespace"||ref.kind==="recipe"&&ref.namespace!==void 0}function shortKey(ref){let namespace=namespaceOf(ref)?.name,recipe=ref.kind==="namespace"?void 0:recipeOf(ref)?.name;return namespace===void 0?recipe??"":recipe===void 0?namespace:`${namespace}/${recipe}`}var REF_KINDS,KIND_LABELS,init_parts=__esm({"../sous-plugin-refs/src/parts.ts"(){"use strict";REF_KINDS=["repo","namespace","recipe","recipeFile","variable","envVar"],KIND_LABELS={repo:"repository",namespace:"namespace",recipe:"recipe",recipeFile:"recipe file",variable:"variable",envVar:"environment variable"}}});import{ConfigError as ConfigError10}from"@sous-io/sous-plugin-api";function repoPart(repo){return repo===void 0?void 0:repo.name??repo.location?.identity}function pathPart(ref){switch(ref.kind){case"repo":return ref.browsed===void 0?"":`tree/${ref.browsed}`;case"namespace":return ref.name;case"recipe":return ref.namespace===void 0?ref.name:`${ref.namespace.name}/${ref.name}`;case"recipeFile":return`${pathPart(ref.recipe)}/${ref.path}`;case"variable":return`${ref.recipe===void 0?"":`${pathPart(ref.recipe)}.`}${ref.name}`;case"envVar":return ref.name}}function refKey(ref){let repo=ref.kind==="envVar"?void 0:repoPart(repoOf(ref)),rest=pathPart(ref);return repo===void 0?rest:ref.kind==="repo"&&rest===""?repo:`${repo}:${rest}`}function storedKey(ref){return ref.kind==="repo"?refKey(ref):pathPart(ref)}function refIdentity(ref){return`${ref.kind} ${refKey(ref)}`}function repoLabel(repo){return repo?.name??repo?.location?.url??"unknown"}function isNamedRef(ref){return ref.kind==="namespace"||ref.kind==="recipe"&&ref.namespace!==void 0}function namespaceRef(name,repo){return{kind:"namespace",name,...repo===void 0?{}:{repo:{kind:"repo",name:repo}}}}function recipeRef(namespace,name,options2={}){return{kind:"recipe",name,namespace:namespaceRef(namespace,options2.repo),...options2.range===void 0?{}:{range:options2.range}}}function formatter(locations){let qualified=(repo,rest)=>{if(repo===void 0)return rest;if(repo.name!==void 0)return rest===""?repo.name:`${repo.name}:${rest}`;if(repo.location!==void 0){let{host,repoPath,url:url2,provider}=repo.location,reader=provider==="local"?void 0:locations().host(provider);return reader!==void 0?reader.formatLocator(host,repoPath,rest):rest===""?url2:`${url2}/${rest}`}return rest},format3=ref=>{let body2=qualified(ref.kind==="envVar"?void 0:repoOf(ref),pathPart(ref)),range3=rangeOf(ref),pairs=Object.entries(ref.vars??{}).map(([name,value])=>`${encodeURIComponent(name)}=${encodeURIComponent(value)}`);return`${body2}${range3===void 0?"":`@${range3}`}${pairs.length===0?"":`?${pairs.join("&")}`}`},spelling=ref=>{let repo=ref.kind==="envVar"?void 0:repoOf(ref);return repo!==void 0&&repo.name===void 0&&repo.location!==void 0?format3(ref):refKey(ref)};return{format:format3,spelling,describe:ref=>{let summary2=ref.description===void 0?"":`: ${ref.description}`,key=spelling(ref);switch(ref.kind){case"repo":{let where3=ref.location?.url;return`${key} (the repository '${ref.name??key}'${where3===void 0?"":`, at ${where3}`})`}case"namespace":return`${key} (the whole namespace '${ref.name}' in the repository '${repoLabel(ref.repo)}')`;case"recipe":return`${key} (the recipe '${ref.name}' in the namespace '${ref.namespace?.name??"unknown"}' of the repository '${repoLabel(repoOf(ref))}'${summary2})`;case"recipeFile":return`${key} (the file '${ref.path}' of the recipe '${pathPart(ref.recipe)}'${summary2})`;case"variable":return`${key} (the variable '${ref.name}' of the recipe '${ref.recipe===void 0?"unknown":pathPart(ref.recipe)}'${summary2})`;case"envVar":{let first2=ref.variables?.[0],answers=first2===void 0?"":` answering '${first2.name}' of the recipe '${first2.recipe===void 0?"unknown":pathPart(first2.recipe)}'`;return`${ref.name} (the environment variable${answers}${summary2})`}}}}}function createRefsFormat(ctx){let written=formatter(()=>ctx.services.get("refs.locations")),storedKeys=new Map,parseNamedRef=(input,from="commandLine")=>{let{refs}=ctx.services.get("refs.resolver").parse(input,from),named=refs.filter(ref=>isNamedRef(ref)&&locationOf(ref)===void 0);if(named.length===1&&!refs.some(ref=>locationOf(ref)!==void 0))return named[0];throw new ConfigError10(`Invalid ref '${input}': this needs a namespace or a recipe named by its short form, such as 'workflow/alpha', and this ref names a location.`)},readStoredKey=key=>{let known=storedKeys.get(key);if(known!==void 0)return known;let parsed=parseNamedRef(key,"lockfile"),read=parsed.kind==="namespace"?{namespace:parsed.name}:{namespace:parsed.namespace.name,name:parsed.name};return storedKeys.set(key,read),read};return{key:storedKey,identity(ref){let location=locationOf(ref);if(location===void 0)return refKey(ref);let rest=pathPart(ref);return rest===""?location.identity:`${location.identity}:${rest}`},...written,kindLabel:ref=>KIND_LABELS[ref.kind],splitRecipeKey(key){let{namespace,name}=readStoredKey(key);if(name===void 0)throw new ConfigError10(`Invalid ref '${key}': a recipe key names a namespace and a recipe.`,{details:["A stored key is written as 'namespace' or 'namespace/recipe'."]});return{namespace,name}},namespaceOfKey:key=>readStoredKey(key).namespace,namespaceRef,recipeRef,parseNamedRef,partsOf(ref){let repo=repoOf(ref),namespace=namespaceOf(ref),recipe=recipeOf(ref),range3=rangeOf(ref);return{...repo===void 0?{}:{repo},...namespace===void 0?{}:{namespace},...recipe===void 0?{}:{recipe},...range3===void 0?{}:{range:range3}}}}}var init_format2=__esm({"../sous-plugin-refs/src/format.ts"(){"use strict";init_parts()}});var VALID_NAME,hashNameSchema,projectHashName,init_hash_names=__esm({"../sous-plugin-refs/src/hash-names.ts"(){"use strict";VALID_NAME=/^[a-z][a-z0-9-]*$/,hashNameSchema={"~standard":{version:1,vendor:"sous",validate(value){let entry=value,issues=[];return typeof entry!="object"||entry===null?{issues:[{message:"Expected an object."}]}:((typeof entry.id!="string"||!VALID_NAME.test(entry.id))&&issues.push({message:`The name '#${String(entry.id)}' is invalid: a name is lowercase kebab-case, a letter then letters, digits or hyphens.`,path:["id"]}),typeof entry.description!="string"&&issues.push({message:"Required, but missing.",path:["description"]}),entry.bases!==void 0&&typeof entry.bases!="function"&&issues.push({message:"Expected a function.",path:["bases"]}),entry.view!==void 0&&typeof entry.view!="function"&&issues.push({message:"Expected a function.",path:["view"]}),entry.bases!==void 0&&entry.view!==void 0&&issues.push({message:"A name either stands for directories ('bases') or lists files ('view'), not both."}),issues.length>0?{issues}:{value:entry})}}},projectHashName={id:"project",description:"the root directory of the project being built.",bases:ctx=>ctx.project===void 0?[]:[ctx.project.root]}}});function repositoryIdentity(canonical){let name=canonical.name.replace(/\.git$/i,"");return identitySegments(`${canonical.host}/${canonical.owner}/${name}`).join("/")}function identitySegments(identity2){return identity2.split("/").map(segment=>segment.trim().toLowerCase()).filter(segment=>segment.length>0)}function shortNameFromIdentity(identity2){let segments=identitySegments(identity2),cleaned=(segments[segments.length-1]??"").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");return SHORT_NAME.test(cleaned)?cleaned:cleaned.length===0?"repository":`repo-${cleaned}`}var SHORT_NAME,init_identity=__esm({"../sous-plugin-refs/src/locations/identity.ts"(){"use strict";SHORT_NAME=/^[a-z][a-z0-9-]*$/}});import{ConfigError as ConfigError11}from"@sous-io/sous-plugin-api";function repositoryHosts(entities){return entities.list(REPOSITORY_HOST_KIND)}function schemesOf(host){return host.schemes??[host.id]}function hostedIds(hosts){return hosts.filter(host=>host.defaultHost!==void 0).map(host=>host.id).sort()}function createRefsLocations(entities){let hosts=()=>repositoryHosts(entities),hostById=id=>hosts().find(host=>host.id===id),hostFor2=url2=>hosts().find(host=>host.matches(url2)),asUrl=url2=>{let scheme=SCHEME.exec(url2.trim());if(scheme===null||URL_SCHEMES.has(scheme[1].toLowerCase()))return{url:url2};let name=scheme[1].toLowerCase(),host=hosts().find(entry=>schemesOf(entry).includes(name));if(host?.defaultHost===void 0)return{url:url2};let path122=scheme[2].replace(/^\/+/,"");return{url:`https://${(path122.split("/")[0]??"").includes(".")?path122:`${host.defaultHost}/${path122}`}`,host}},requireHost=(url2,provider)=>{let known=hosts().map(host=>host.id).join(", ")||"none";if(provider!==void 0){let named=hostById(provider);if(named===void 0)throw new ConfigError11(`The repository at ${url2} names the provider '${provider}', which sous does not have.`,{details:[`Sous has these providers: ${known}.`]});if(!named.matches(url2)){let owner=hostFor2(url2);if(owner!==void 0&&owner.id!==named.id)throw new ConfigError11(`The ${named.id} provider does not handle ${url2}; that is ${owner.id==="local"?"a local path":`a ${owner.id} URL`}, which the ${owner.id} provider handles.`,{details:[`Drop '--provider' and let sous work it out, or name '${owner.id}'.`]})}return named}let detected=hostFor2(url2);if(detected!==void 0)return detected;throw new ConfigError11(`Sous does not recognize the host in the repository URL ${url2}.`,{details:[`Sous has these providers: ${known}. For a self-hosted instance, name the provider that host runs on the repository entry, as in 'sous repo add ${url2} --provider <provider>'.`]})},canonicalize=(url2,provider)=>{let target=asUrl(url2);return(provider===void 0&&target.host!==void 0?target.host:requireHost(target.url,provider)).canonicalize(target.url)};return{fromUrl(url2,provider){try{let target=asUrl(url2),host=provider===void 0&&target.host!==void 0?target.host:requireHost(target.url,provider),canonical=host.canonicalize(target.url);return{provider:host.id,host:canonical.host,repoPath:`${canonical.owner}/${canonical.name}`,identity:repositoryIdentity(canonical),url:url2}}catch{return}},locationFor(provider,host,repoPath){let reader=hostById(provider);if(reader===void 0)throw new ConfigError11(`No provider '${provider}' reads the repository ${host}/${repoPath}.`);let url2=`https://${host}/${repoPath}`;return{provider,host,repoPath,identity:repositoryIdentity(reader.canonicalize(url2)),url:url2}},canonicalize,identity:(url2,provider)=>repositoryIdentity(canonicalize(url2,provider)),identityOf:repository=>repositoryIdentity(repository),hostFor:hostFor2,host:hostById,hosts,shortName:shortNameFromIdentity}}function tryLocationFor(locations,provider,host,repoPath){try{return locations.locationFor(provider,host,repoPath)}catch{return}}var REPOSITORY_HOST_KIND,URL_SCHEMES,SCHEME,init_locations=__esm({"../sous-plugin-refs/src/locations/locations.ts"(){"use strict";init_identity();REPOSITORY_HOST_KIND="repository-host",URL_SCHEMES=new Set(["http","https","ssh","git","git+ssh","ssh+git"]),SCHEME=/^([a-z][a-z0-9+.-]*):\/\/(.*)$/is}});function splitter(id,order,read){return{id,order,split:(state,ctx)=>state.ref!==void 0?[state]:read(state,ctx)}}function finishRef(state,ref){let withVars=state.vars===void 0?ref:{...ref,vars:state.vars};return{...state,rest:"",ref:withVars}}var SCHEME2,SCP,init_partial_ref=__esm({"../sous-plugin-refs/src/parser/partial-ref.ts"(){"use strict";SCHEME2=/^[a-z][a-z0-9+.-]*:\/\//i,SCP=/^[^@\s/:]+@([^@\s/:]+):(.+)$/s}});function looksLikeLocation(ref){let trimmed=ref.trim();if(SCHEME_PATTERN.test(trimmed)||SCP_PATTERN.test(trimmed))return!0;let first2=trimmed.split("/")[0]??"";return trimmed.includes("/")&&first2.includes(".")&&!first2.includes(":")}function pathSegments(pathname){return pathname.split(/[?#]/)[0].split("/").map(segment=>{try{return decodeURIComponent(segment)}catch{return segment}}).filter(segment=>segment.length>0)}function local(state,path122){return finishRef(state,{kind:"repo",location:{provider:"local",host:"localhost",repoPath:path122,identity:`localhost/${path122.replace(/^\/+/,"")}`,url:state.rest}})}function forHost(state,hosts,hostName,segments){let probe=`https://${hostName}/${segments.slice(0,2).join("/")}`,host=hosts.find(entry=>entry.matches(probe));if(host!==void 0&&host.defaultHost!==void 0)return{host,hostName,segments};let ids=hostedIds(hosts);state.problems.push(`sous does not recognize the host '${hostName}'. For a self-hosted instance, write the location with the provider's scheme and the host, as in '${ids[0]??"gitlab"}://${hostName}/owner/repository/namespace/recipe' (sous has these providers: ${ids.join(", ")||"none"}).`)}function take(state,hosts,scheme){let body2=state.rest;if(scheme!==null){let name=scheme[1].toLowerCase();if(URL_SCHEMES2.has(name)){let url2;try{url2=new URL(body2)}catch{state.problems.push("the URL could not be read.");return}return forHost(state,hosts,url2.host.toLowerCase(),pathSegments(url2.pathname))}let host=hosts.find(entry=>schemesOf(entry).includes(name));if(host?.defaultHost===void 0){state.problems.push(`'${name}' is not a provider sous can read a location from. The scheme of a locator is the provider's own identifier; sous has these: ${hostedIds(hosts).join(", ")||"none"}. An ordinary 'https://' URL works too.`);return}let segments=pathSegments(scheme[2]),hostName=host.defaultHost;return segments[0]?.includes(".")===!0&&(hostName=segments[0].toLowerCase(),segments=segments.slice(1)),{host,hostName,segments}}let scp=SCP_PATTERN.exec(body2);if(scp!==null)return forHost(state,hosts,scp[1].toLowerCase(),pathSegments(scp[2]));let all=pathSegments(body2);return forHost(state,hosts,all[0].toLowerCase(),all.slice(1))}function readLocation(state,locations){if(state.repo!==void 0||!looksLikeLocation(state.rest))return[state];let scheme=SCHEME_PATTERN.exec(state.rest);if(scheme!==null&&LOCAL_SCHEMES.has(scheme[1].toLowerCase()))return[local(state,scheme[2])];let taken=take(state,locations.hosts(),scheme);if(taken===void 0)return[];let{host,hostName,segments}=taken,specific=[],repositories=[];for(let reading of host.readLocation({host:hostName,segments})){let location=tryLocationFor(locations,host.id,hostName,reading.repoPath);if(location===void 0)continue;if(reading.browsed!==void 0){let browsed=reading.browsed.replace(/^\/+|\/+$/g,"");browsed.length>0&&specific.push(finishRef(state,{kind:"repo",location,browsed,...state.range===void 0?{}:{range:state.range}}));continue}let named=reading.named??[];named.length===0?repositories.push({kind:"repo",location}):specific.push({...state,rest:named.join("/"),repo:{kind:"repo",location}})}return specific.length>0?specific:repositories.length===0?(state.problems.push(`the ${host.id} provider cannot read a namespace or a recipe from this location. After the repository, a location names a namespace and optionally a recipe, as in '${host.formatLocator(hostName,"owner/repository","workflow/alpha")}'.`),[]):state.range!==void 0?(state.problems.push("a version range applies to a recipe, not to a repository."),[]):repositories.map(repo=>finishRef(state,repo))}var SCHEME_PATTERN,SCP_PATTERN,URL_SCHEMES2,LOCAL_SCHEMES,locationSplitter,init_location_splitter=__esm({"../sous-plugin-refs/src/parser/location-splitter.ts"(){"use strict";init_locations();init_partial_ref();SCHEME_PATTERN=/^([a-z][a-z0-9+.-]*):\/\/(.*)$/is,SCP_PATTERN=/^[^@\s/:]+@([^@\s/:]+):(.+)$/s,URL_SCHEMES2=new Set(["http","https","ssh","git","git+ssh","ssh+git"]),LOCAL_SCHEMES=new Set(["local","file"]);locationSplitter=splitter("location",30,(state,ctx)=>readLocation(state,ctx.services.get("refs.locations")))}});function isGlobName(text,globs){return globs.hasGlob(text)&&GLOB_NAME.test(text)}function splitSegments(text){let segments=[],depth=0,current="";for(let character of text){if(character==="{"&&(depth+=1),character==="}"&&depth>0&&(depth-=1),character==="/"&&depth===0){segments.push(current),current="";continue}current+=character}return segments.push(current),segments}var NAME_ANY_CASE,VARIABLE_NAME,ENV_VAR_NAME,GLOB_NAME,init_names=__esm({"../sous-plugin-refs/src/names.ts"(){"use strict";NAME_ANY_CASE=/^[a-z][a-z0-9-]*$/i,VARIABLE_NAME=/^[a-z][a-zA-Z0-9]*$/,ENV_VAR_NAME=/^[A-Za-z_][A-Za-z0-9_]*$/,GLOB_NAME=/^[A-Za-z0-9_\-.*?[\]{},!^]+$/}});function isName(reader,segment){return NAME_ANY_CASE.test(segment)||isGlobName(segment,reader.globs)}function isVariableName(reader,segment){return VARIABLE_NAME.test(segment)||isGlobName(segment,reader.globs)}function badName(what,name){return`the ${what} '${name}' must be kebab-case: a letter, then letters, digits or hyphens.`}function withGlob(reader,names2){return names2.some(name=>reader.globs.hasGlob(name))?{glob:!0}:{}}function readOne(reader,text){let{state,make:make2,ns:ns2}=reader,{repo,range:range3}=state,dot=text.indexOf("."),located=repo?.location!==void 0,inRepo=repo===void 0?{}:{repo};if(!located&&dot>0&&dot<text.length-1&&range3===void 0){let left=text.slice(0,dot),right=text.slice(dot+1);isName(reader,left)&&isVariableName(reader,right)&&make2({kind:"variable",name:right,recipe:{kind:"recipe",name:left,...inRepo},...withGlob(reader,[left,right])})}isName(reader,text)&&(range3===void 0?(make2({...ns2(text),...withGlob(reader,[text])}),repo===void 0&&make2({kind:"repo",name:text,...withGlob(reader,[text])})):state.problems.push(NAMESPACE_NOT_VERSIONED),located||make2({kind:"recipe",name:text,...inRepo,...range3===void 0?{}:{range:range3},...withGlob(reader,[text])})),!located&&range3===void 0&&isVariableName(reader,text)&&make2({kind:"variable",name:text,...inRepo,...withGlob(reader,[text])});let readsAsOther=repo===void 0&&(VARIABLE_NAME.test(text)||ENV_VAR_NAME.test(text));!isName(reader,text)&&!readsAsOther&&dot<=0&&state.problems.push(badName("namespace",text))}function readTwo(reader,namespace,second){let{state,make:make2,ns:ns2}=reader,{range:range3}=state,dot=second.indexOf(".");if(second==="*"&&(range3===void 0?make2({...ns2(namespace),wildcard:!0,...withGlob(reader,[namespace])}):state.problems.push(NAMESPACE_NOT_VERSIONED)),dot>0&&dot<second.length-1&&range3===void 0){let left=second.slice(0,dot),right=second.slice(dot+1);isName(reader,left)&&isVariableName(reader,right)&&make2({kind:"variable",name:right,recipe:{kind:"recipe",name:left,namespace:ns2(namespace)},...withGlob(reader,[namespace,left,right])})}isName(reader,second)?make2({kind:"recipe",name:second,namespace:ns2(namespace),...range3===void 0?{}:{range:range3},...withGlob(reader,[namespace,second])}):dot<=0&&state.problems.push(badName("recipe name",second))}var FILE_PATH,NAMESPACE_NOT_VERSIONED,namePathSplitter,init_name_path_splitter=__esm({"../sous-plugin-refs/src/parser/name-path-splitter.ts"(){"use strict";init_names();init_partial_ref();FILE_PATH=/^[^\s\\]+$/,NAMESPACE_NOT_VERSIONED="a version range applies to a recipe, and namespaces are not versioned. Name a recipe, as in 'workflow/task-files@^1.2.0'.";namePathSplitter=splitter("name-path",60,(state,ctx)=>{let segments=splitSegments(state.rest),out=[state],make2=ref=>{out.push(finishRef(state,ref))},repo=state.repo,ns2=name=>({kind:"namespace",name,...repo===void 0?{}:{repo}}),reader={state,globs:ctx.services.get("host.globs"),make:make2,ns:ns2};if(segments[0]==="")return state.problems.push("the namespace is empty."),out;if(segments.length>1&&segments.includes(""))return state.problems.push(segments[segments.length-1]===""?"the recipe name after '/' is empty.":"a ref has an empty segment between two '/'."),out;if(segments.length===1)return readOne(reader,segments[0]),out;let[namespace,second]=segments;if(!isName(reader,namespace))return state.problems.push(badName("namespace",namespace)),out;if(segments.length===2)return readTwo(reader,namespace,second),out;let path122=segments.slice(2).join("/");if(!isName(reader,second))return state.problems.push(badName("recipe name",second)),out;if(!FILE_PATH.test(path122))return state.problems.push(`the path '${path122}' inside a recipe holds a space or a backslash.`),out;let recipe={kind:"recipe",name:second,namespace:ns2(namespace)};return make2({kind:"recipeFile",path:path122,recipe,...state.range===void 0?{}:{range:state.range},...withGlob(reader,[namespace,second,path122])}),out})}});import{ConfigError as ConfigError12}from"@sous-io/sous-plugin-api";function earlyProblem(input){if(typeof input!="string")return"a ref must be a string.";let trimmed=input.trim();if(trimmed.length===0)return"a ref must not be empty.";if(trimmed.startsWith("@"))return"refs take no '@' prefix. The '@' character introduces a version range only, as in 'workflow/task-files@^1.2.0'.";if(trimmed.startsWith("~"))return"refs take no '~' prefix. The '~' sigil belongs to template include lines ('@~workflow/file.md'); a ref itself is written without it."}function finished(states){let seen=new Set,refs=[];for(let state of states){if(state.ref===void 0||state.rest!=="")continue;let key=JSON.stringify(state.ref);seen.has(key)||(seen.add(key),refs.push(state.ref))}return refs.map((ref,position)=>({ref,position})).sort((left,right)=>REF_KINDS.indexOf(left.ref.kind)-REF_KINDS.indexOf(right.ref.kind)||left.position-right.position).map(entry=>entry.ref)}function parseWith(splitters,input,ctx){let early=earlyProblem(input);if(early!==void 0)return{input:String(input),readings:[],problems:[early]};let trimmed=input.trim(),problems=[],ordered2=[...splitters].sort((left,right)=>left.order-right.order),states=[{input:trimmed,rest:trimmed,problems}];for(let entry of ordered2)if(states=states.flatMap(state=>entry.split(state,ctx)),states.length===0)break;return{input,readings:finished(states),problems:[...new Set(problems)]}}function parseError(result){let reasons=result.problems,problem;return reasons.length===0?problem="it does not fit any form of a ref.":reasons.length===1?problem=reasons[0]:problem=`it fits no form of a ref:
362
362
  ${reasons.map(reason=>` ${reason}`).join(`
363
363
  `)}`,new ConfigError12(`Invalid ref '${result.input}': ${problem}`,{details:[SYNTAX_HELP]})}function createRefsParser(ctx){return{parse:input=>parseWith(ctx.entities.list("ref-splitter"),input,ctx)}}var SYNTAX_HELP,init_parser2=__esm({"../sous-plugin-refs/src/parser/parser.ts"(){"use strict";init_parts();SYNTAX_HELP="A ref is written as 'namespace', 'namespace/recipe', 'repo:namespace/recipe', 'namespace/recipe/path/to/file.md', 'namespace/recipe.variable', an environment variable name, any of those with '@<range>' or '?name=value', or a location such as 'github://owner/repository/namespace/recipe' or a URL copied from the browser."}});function decodeQuery(query){if(query.length===0)return;let vars={};for(let pair of query.split("&")){let match2=PAIR.exec(pair);if(match2===null)return;try{vars[decodeURIComponent(match2[1].replace(/\+/g," "))]=decodeURIComponent(match2[2].replace(/\+/g," "))}catch{return}}return vars}var import_semver,PAIR,querySplitter,rangeSplitter,repoQualifierSplitter,envVarSplitter,init_splitters=__esm({"../sous-plugin-refs/src/parser/splitters.ts"(){"use strict";import_semver=__toESM(require_semver2(),1);init_names();init_partial_ref();PAIR=/^([A-Za-z0-9\-._~%+!*'(),:@/$]+)=([A-Za-z0-9\-._~%+!*'(),:@/$]*)$/;querySplitter=splitter("query",10,state=>{if(SCHEME2.test(state.rest))return[state];let mark=state.rest.lastIndexOf("?");if(mark<=0)return[state];let vars=decodeQuery(state.rest.slice(mark+1));return vars===void 0?[state]:[{...state,rest:state.rest.slice(0,mark),vars:{...state.vars,...vars}},state]}),rangeSplitter=splitter("range",20,state=>{let text=state.rest,at2=text.lastIndexOf("@");if(at2===-1||at2<text.lastIndexOf("/"))return[state];let before=text.slice(0,at2).trim(),range3=text.slice(at2+1).trim();return range3.length===0?(state.problems.push("the '@' is not followed by a version range."),[]):before.includes("@")&&!SCHEME2.test(before)&&!SCP.test(before)?(state.problems.push("a ref may carry at most one '@' version range."),[]):import_semver.default.validRange(range3)===null?(state.problems.push(`'${range3}' is not a version range. Ranges follow npm's rules, such as '^1.2.0', '~2.1', '>=1.0.0 <2.0.0' or '*'.`),[state]):[{...state,rest:before,range:range3}]}),repoQualifierSplitter=splitter("repo-qualifier",40,(state,ctx)=>{let text=state.rest;if(state.repo!==void 0||SCHEME2.test(text)||SCP.test(text))return[state];let match2=/^([^:/\s]*):(.*)$/s.exec(text);if(match2===null)return[state];let name=match2[1],rest=match2[2];return name.length===0?(state.problems.push("the repo qualifier before ':' is empty."),[]):rest.includes(":")?(state.problems.push("a ref may carry at most one 'repo:' qualifier."),[]):!NAME_ANY_CASE.test(name)&&!isGlobName(name,ctx.services.get("host.globs"))?(state.problems.push(`the repo qualifier '${name}' must be kebab-case: a letter, then letters, digits or hyphens.`),[]):[{...state,rest,repo:{kind:"repo",name}}]}),envVarSplitter=splitter("env-var",50,state=>state.repo!==void 0||state.range!==void 0||!ENV_VAR_NAME.test(state.rest)?[state]:[state,finishRef(state,{kind:"envVar",name:state.rest})])}});import{ConfigError as ConfigError13,NonInteractiveError as NonInteractiveError2}from"@sous-io/sous-plugin-api";function resolvedRefFacts(ref,search2,reason){let subject2=ref.kind==="envVar"?ref.variables?.[0]??ref:ref,resolvedTo=refKey(subject2),repoName=repoOf(subject2)?.name,recipe=recipeOf(subject2),namespace=namespaceOf(subject2);return{search:search2,resolvedTo,kind:KIND_LABELS[ref.kind],...subject2.kind==="variable"?{variable:subject2.name}:{},...recipe===void 0||subject2.kind==="namespace"?{}:{recipe:recipe.name},...namespace===void 0?{}:{namespace:namespace.name},...repoName===void 0||repoName===resolvedTo?{}:{repository:repoName},...ref.kind==="repo"&&ref.location!==void 0?{location:ref.location.url}:{},...ref.kind!=="repo"&&subject2.description!==void 0?{description:subject2.description}:{},...reason===void 0?{}:{reason}}}function reasonOf(facts){return facts.reason??`'${facts.search}' named one ${facts.kind}, and nothing else, so that is what is being used.`}function createRefsPicker(locations){let{spelling,describe:describe6}=formatter(locations),announce=(io,ref,search2,reason)=>{let facts=resolvedRefFacts(ref,search2,reason);io.reporter.resolvedReference(reasonOf(facts),facts)};return{facts:resolvedRefFacts,async pick(matches,options2,io){let{search:search2}=options2,shouldAnnounce=options2.announce??!0;if(matches.length===0)throw new ConfigError13(`Nothing called '${search2}' was found.`,{details:options2.details??[]});let first2=matches[0];if(matches.length===1)return shouldAnnounce&&announce(io,first2,search2),first2;if(options2.acceptFirst===!0){let reason=`'${search2}' named ${matches.length} things, and '${ACCEPT_FIRST_FLAG}' was passed, so the first one listed is being used.`;return shouldAnnounce?announce(io,first2,search2,reason):io.reporter.notice(reason),first2}let message2=options2.prompt??`Which '${search2}' did you mean?`;if(!io.prompter.interactive){let example=spelling(matches.find(match2=>spelling(match2)!==search2)??first2);throw new NonInteractiveError2(message2,ACCEPT_FIRST_FLAG,{details:[`'${search2}' matched ${matches.length} things:`,...matches.map(match2=>` ${describe6(match2)}`),`Write the full reference (for example '${example}'), or pass '${ACCEPT_FIRST_FLAG}' to take the first one listed.`]})}return io.prompter.askChoice({message:message2,answeredBy:ACCEPT_FIRST_FLAG,choices:matches.map(match2=>({label:describe6(match2),value:match2}))})}}}var ACCEPT_FIRST_FLAG,init_picker=__esm({"../sous-plugin-refs/src/picker.ts"(){"use strict";init_format2();init_parts();ACCEPT_FIRST_FLAG="--accept-first"}});import{ConfigError as ConfigError14}from"@sous-io/sous-plugin-api";function textOf(text,ref,input,ctx){return typeof text=="function"?text(ref,input,ctx):text}function rulePruner(options2){let normalize4=options2.normalize??(ref=>ref);return{id:options2.id,source:options2.source,place:options2.place??SOURCE_LABELS[options2.source]??`as '${options2.source}'`,prune(candidates,input,ctx){let kept=[],dropped=[],warnings=[];for(let ref of candidates){let rule=options2.rules.find(entry=>entry.matches(ref,input));if(rule===void 0){kept.push(normalize4(ref));continue}let message2=textOf(rule.message,ref,input,ctx);if(rule.action==="throw")throw new ConfigError14(message2);if(rule.action==="warn"){kept.push(normalize4(ref)),warnings.push(message2);continue}dropped.push(rule.instead===void 0?{ref,reason:message2}:{ref,reason:message2,instead:textOf(rule.instead,ref,input,ctx)})}return{kept,dropped,warnings}}}}function describeDropped(dropped){return dropped.instead===void 0?dropped.reason:`${dropped.reason}
364
364
  Write ${dropped.instead} instead.`}function isLocal(ref){return locationOf(ref)?.provider==="local"}function hasLocation(ref){return locationOf(ref)!==void 0}function hasRepoName(ref){return ref.kind!=="repo"&&repoOf(ref)?.name!==void 0}var SOURCE_LABELS,KEBAB_REASON,init_rules=__esm({"../sous-plugin-refs/src/pruners/rules.ts"(){"use strict";init_parts();SOURCE_LABELS={commandLine:"on the command line",config:"as a subscription key in a config file",manifest:"in a recipe manifest's 'depends' or 'subscribes' list",lockfile:"as a key sous stores",include:"in an include line"};KEBAB_REASON="only a namespace or a recipe can be named here, and their names must be kebab-case: a letter, then letters, digits or hyphens."}});function lowercaseNames(ref){return ref.kind==="namespace"?{...ref,name:ref.name.toLowerCase()}:ref.kind==="recipe"?{...ref,name:ref.name.toLowerCase(),...ref.namespace===void 0?{}:{namespace:{...ref.namespace,name:ref.namespace.name.toLowerCase()}}}:ref}function includeInstead(ref){return ref.kind!=="recipeFile"?"'namespace/recipe/path/to/file.md'":`'${ref.recipe.namespace?.name??"namespace"}/${ref.recipe.name}/${ref.path}'`}var NO_PATHS,lowerKey,commandLinePruner,sharedStoredRules,configPruner,lockfilePruner,manifestPruner,includePruner,BUILT_IN_PRUNERS,init_pruners=__esm({"../sous-plugin-refs/src/pruners/pruners.ts"(){"use strict";init_parts();init_names();init_rules();NO_PATHS="a short ref has at most two path segments, a namespace and a recipe. A folder path inside a repository is written as a URL copied from the browser instead.",lowerKey=ref=>`'${shortKey(ref).toLowerCase()}'`,commandLinePruner=rulePruner({id:"commandLine",source:"commandLine",rules:[{matches:isLocal,action:"drop",message:"a repository on this machine is added by its path, and its recipes are then named by their short form.",instead:"'sous repo add <path>', then 'namespace/recipe'"},{matches:ref=>ref.kind==="recipeFile",action:"drop",message:NO_PATHS,instead:"'namespace/recipe', or the URL copied from the browser"},{matches:ref=>ref.glob===!0,action:"drop",message:"a name here must be kebab-case (a letter, then letters, digits or hyphens), so a glob pattern is not accepted.",instead:"the name itself"}]}),sharedStoredRules=[{matches:ref=>ref.kind==="namespace"&&ref.wildcard===!0,action:"drop",message:"a whole namespace is stored as its name alone.",instead:lowerKey},{matches:ref=>ref.vars!==void 0,action:"drop",message:"a stored key carries no query values.",instead:lowerKey},{matches:ref=>shortKey(ref)!==shortKey(ref).toLowerCase(),action:"drop",message:"stored names are lowercase.",instead:lowerKey}],configPruner=rulePruner({id:"config",source:"config",rules:[{matches:hasLocation,action:"drop",message:"a config file names a subscription by its short form; the repository it lives in is a separate entry under 'repos'.",instead:(_ref,input)=>`'namespace/recipe', or run 'sous subscribe ${input.trim()}', which adds the repository and writes the subscription in its short form`},{matches:ref=>!isStoredKind(ref),action:"drop",message:KEBAB_REASON,instead:"'namespace/recipe'"},{matches:hasRepoName,action:"drop",message:ref=>`the repository a subscription resolves into is recorded in the lockfile, not in the key. To choose between repositories, run 'sous subscribe ${repoOf(ref)?.name}:${shortKey(ref).toLowerCase()}', which records the choice.`,instead:lowerKey},{matches:ref=>ref.glob===!0,action:"drop",message:"a glob pattern is not a stored key; names here must be kebab-case.",instead:lowerKey},{matches:ref=>rangeOf(ref)!==void 0,action:"drop",message:"a subscription's version range belongs in the entry's own 'range' field.",instead:ref=>`${lowerKey(ref)}: { range: '${rangeOf(ref)}' }`},...sharedStoredRules]}),lockfilePruner=rulePruner({id:"lockfile",source:"lockfile",rules:[{matches:hasLocation,action:"drop",message:"a stored key never names a location.",instead:"'namespace/recipe'"},{matches:ref=>!isStoredKind(ref),action:"drop",message:KEBAB_REASON,instead:"'namespace/recipe'"},{matches:hasRepoName,action:"drop",message:"a stored key never names a repository.",instead:lowerKey},{matches:ref=>ref.glob===!0,action:"drop",message:"a glob pattern is not a stored key; names here must be kebab-case.",instead:lowerKey},{matches:ref=>rangeOf(ref)!==void 0,action:"drop",message:"a stored key carries no version range.",instead:lowerKey},...sharedStoredRules]});manifestPruner=rulePruner({id:"manifest",source:"manifest",normalize:lowercaseNames,rules:[{matches:hasRepoName,action:"drop",message:"a 'repo:' qualifier names a short name that only the consuming project knows, so it cannot appear in a published manifest.",instead:ref=>`${lowerKey(ref)} for a recipe in this same repository, or name the other repository by its location, as in 'github://owner/repository/${shortKey(ref).toLowerCase()}'`},{matches:isLocal,action:"drop",message:"a local repository is a consumer's convenience, not a published location, so a manifest cannot depend on one.",instead:"the recipe's published location, such as 'github://owner/repository/namespace/recipe'"},{matches:ref=>ref.kind==="recipeFile",action:"drop",message:NO_PATHS,instead:"'namespace/recipe', or the URL copied from the browser"},{matches:ref=>ref.glob===!0,action:"drop",message:KEBAB_REASON,instead:"'namespace/recipe'"},{matches:ref=>ref.kind==="repo"&&ref.browsed===void 0&&ref.location!==void 0,action:"drop",message:ref=>`it names the repository at ${ref.kind==="repo"?ref.location?.url:"that location"} and nothing inside it, and a dependency is a namespace or a recipe.`,instead:(ref,_input,ctx)=>{if(ref.kind!=="repo"||ref.location===void 0)return"'github://owner/repository'";let{host,repoPath,url:url2,provider}=ref.location,reader=ctx.services.get("refs.locations").host(provider);return`'${reader===void 0?`${url2}/namespace/recipe`:reader.formatLocator(host,repoPath,"namespace/recipe")}'`}},{matches:ref=>ref.kind==="recipe"&&ref.namespace===void 0,action:"drop",message:ref=>rangeOf(ref)===void 0?"a recipe is named with its namespace here, and a bare name is read as a namespace.":"a version range applies to a recipe, and namespaces are not versioned. Name the recipe with its namespace.",instead:"'namespace/recipe', optionally with a range such as '@^1.1'"},{matches:ref=>!isStoredKind(ref)&&!(ref.kind==="repo"&&ref.browsed!==void 0),action:"drop",message:KEBAB_REASON,instead:"'namespace/recipe'"},{matches:ref=>ref.vars!==void 0,action:"drop",message:"a manifest's dependency carries no query values.",instead:lowerKey}]});includePruner=rulePruner({id:"include",source:"include",rules:[{matches:ref=>ref.kind!=="recipeFile",action:"drop",message:"an include line names a file inside a recipe: its namespace, its recipe and the path inside it.",instead:includeInstead},{matches:hasLocation,action:"drop",message:"an include line never names a location; it reads the recipes this project pins.",instead:includeInstead},{matches:ref=>rangeOf(ref)!==void 0,action:"drop",message:"an include line takes no version range; the version of a recipe is the one this project pins.",instead:includeInstead},{matches:ref=>ref.kind==="recipeFile"&&splitSegments(ref.path).some(part=>part==="."||part===".."),action:"drop",message:"the path inside a recipe may not contain '.' or '..' segments.",instead:includeInstead}]}),BUILT_IN_PRUNERS=[commandLinePruner,configPruner,manifestPruner,lockfilePruner,includePruner]}});import{ConfigError as ConfigError15}from"@sous-io/sous-plugin-api";function browsedFits(ref,kinds){return ref.kind==="repo"&&ref.browsed!==void 0&&(kinds.includes("namespace")||kinds.includes("recipe"))}function answersFor(lookup,candidate){return lookup.kinds===void 0||lookup.kinds.includes(candidate.kind)||browsedFits(candidate,lookup.kinds)}function orderRefs(entries){let seen=new Set;return entries.map((entry,position)=>({...entry,position})).sort((left,right)=>qualificationOf(left.rank)-qualificationOf(right.rank)||REF_KINDS.indexOf(left.ref.kind)-REF_KINDS.indexOf(right.ref.kind)||left.position-right.position).map(entry=>entry.ref).filter(ref=>{let identity2=`${refIdentity(ref)} ${JSON.stringify(ref.vars??{})}`;return seen.has(identity2)?!1:(seen.add(identity2),!0)})}function selectLookups(all,selection){if(selection===void 0||selection===!0)return all.filter(lookup=>lookup.optIn!==!0);if(selection===!1)return[];let chosen=[];for(let selector of selection)for(let lookup of all)(lookup.id===selector||lookup.tags?.includes(selector)===!0)&&!chosen.includes(lookup)&&chosen.push(lookup);return chosen}function createRefsResolver(ctx){let prune3=(input,from)=>{let pruners=ctx.entities.list("ref-pruner").filter(pruner=>pruner.source===from);if(pruners.length===0)throw new ConfigError15(`No pruner is registered for a ref written as '${from}'.`,{details:["A plugin that adds a place to write refs adds a 'ref-pruner' entity for it."]});let parsed=ctx.services.get("refs.parser").parse(input);if(parsed.readings.length===0)throw parseError(parsed);let kept=parsed.readings,dropped=[],warnings=[];for(let pruner of pruners){let result=pruner.prune(kept,input.trim(),ctx);kept=result.kept,dropped.push(...result.dropped),warnings.push(...result.warnings)}return{kept,dropped,warnings,place:pruners[0].place}},refusal=(input,place,dropped)=>{let reasons=[...new Set(dropped.map(describeDropped))];return reasons.length===1?new ConfigError15(`The ref '${input.trim()}' cannot be written ${place}: ${reasons[0]}`):new ConfigError15(`The ref '${input.trim()}' cannot be written ${place}. Every way it reads is refused:
365
365
  `+reasons.map(reason=>` - ${reason}`).join(`
366
- `))},resolution=(input,refs,pruned,usedLookup)=>({input,refs,dropped:pruned.dropped,warnings:pruned.warnings,usedLookup}),parse6=(input,from="commandLine")=>{let pruned=prune3(input,from);if(pruned.kept.length===0)throw refusal(input,pruned.place,pruned.dropped);return resolution(input,orderRefs(pruned.kept.map(ref=>({ref,rank:ref}))),pruned,!1)},begin=request=>{let pruned;try{pruned=prune3(request.input,request.from??"commandLine")}catch(error51){if(request.refusedIsEmpty===!0)return{result:resolution(request.input,[],{dropped:[],warnings:[]},!0)};throw error51}if(pruned.kept.length===0){if(request.refusedIsEmpty===!0)return{result:resolution(request.input,[],pruned,!0)};throw refusal(request.input,pruned.place,pruned.dropped)}let kinds=request.kinds,kept=kinds===void 0?pruned.kept:pruned.kept.filter(ref=>kinds.includes(ref.kind)||browsedFits(ref,kinds)),selected2=selectLookups(ctx.entities.list("ref-lookup"),request.lookups),lookups=[...request.extraLookups??[],...selected2];if(Array.isArray(request.lookups)&&request.lookups.length>0&&selected2.length===0&&request.extraLookups===void 0)throw new ConfigError15(`No ref lookup answers to ${request.lookups.map(name=>`'${name}'`).join(", ")}.`,{details:["The plugin that adds it may be disabled or missing."]});return lookups.length===0?{result:resolution(request.input,orderRefs(kept.map(ref=>({ref,rank:ref}))),pruned,!1)}:{kept,pruned,lookups}},finish4=(request,pruned,found)=>{let kinds=request.kinds,matching2=found.filter(entry=>kinds===void 0||kinds.includes(entry.match.ref.kind)),exact=matching2.filter(entry=>entry.match.exactSpelling),chosen=exact.length>0?exact:matching2;return resolution(request.input,orderRefs(chosen.map(entry=>({ref:entry.match.ref,rank:entry.rank}))),pruned,!0)};return{parse:parse6,async resolve(request){let early=begin(request);if("result"in early)return early.result;let found=[];for(let candidate of early.kept)for(let lookup of early.lookups)if(answersFor(lookup,candidate))for(let match2 of await lookup.find(candidate,ctx))found.push({match:match2,rank:candidate});return finish4(request,early.pruned,found)},resolveSync(request){let early=begin(request);if("result"in early)return early.result;let found=[];for(let candidate of early.kept)for(let lookup of early.lookups)if(lookup.findSync!==void 0&&answersFor(lookup,candidate))for(let match2 of lookup.findSync(candidate,ctx))found.push({match:match2,rank:candidate});return finish4(request,early.pruned,found)},isValid(input,from="commandLine"){try{return parse6(input,from),!0}catch{return!1}},findInString(text,from="commandLine"){let found=[];for(let word of text.matchAll(/\S+/g)){let bare=word[0].replace(/^[`"'([<{]+/,"").replace(/[`"')\]>},.;:!]+$/,"");if(bare.length!==0)try{found.push({text:bare,index:word.index+word[0].indexOf(bare),result:parse6(bare,from)})}catch{}}return found}}}var init_resolver=__esm({"../sous-plugin-refs/src/resolver.ts"(){"use strict";init_format2();init_parser2();init_parts();init_rules()}});var package_default5,init_package3=__esm({"../sous-plugin-refs/package.json"(){package_default5={name:"@sous-io/sous-plugin-refs",version:"1.1.4",description:"Parsing and resolving refs, picking among matches, # names, repository locations and identity.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-host":"workspace:*",semver:"^7.8.5"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*","@types/semver":"^7.8.0"},engines:{node:">=22"}}}});function withoutGitSuffix(segment){return segment.replace(/\.git$/i,"")}function readingsAfterRepository(repoPath,rest){let after=rest[0]==="-"?rest.slice(1):[...rest],readings=[];return after.length>=2&&BROWSE_WORDS.has(after[0].toLowerCase())&&readings.push({repoPath,browsed:after.slice(1).join("/")}),readings.push({repoPath,named:after}),readings}function normalizeRepoUrl(url2){let value=url2.trim();for(;value.endsWith("/");)value=value.slice(0,-1);return value.endsWith(".git")&&(value=value.slice(0,-4)),value}function splitRepoUrl(url2){let normalized=normalizeRepoUrl(url2);if(normalized.length===0)return;let host,repoPath,sshPort,scp=/^(?:([^@\s/]+)@)?([^@\s/:]+):(.+)$/.exec(normalized);if(/^[a-z][a-z0-9+.-]*:\/\//i.test(normalized)){let parsed;try{parsed=new URL(normalized)}catch{return}/^ssh:$/i.test(parsed.protocol)||/^git\+ssh:$/i.test(parsed.protocol)?(host=parsed.hostname.toLowerCase(),sshPort=parsed.port===""?void 0:Number(parsed.port)):host=parsed.host.toLowerCase(),repoPath=parsed.pathname.replace(/^\/+/,"")}else if(scp!==null)host=scp[2].toLowerCase(),repoPath=scp[3].replace(/^\/+/,"");else return;let segments=repoPath.split("/").filter(segment=>segment.length>0);if(!(segments.length<2||host.length===0))return{host,owner:segments.slice(0,-1).join("/"),name:segments[segments.length-1],...sshPort===void 0?{}:{sshPort}}}function hostWithoutPort(host){return host.replace(/:\d+$/,"")}function buildCanonicalRepository(host,owner,name,options2={}){let basePath=options2.basePath?.replace(/^\/+|\/+$/g,"")||void 0,sshOwner=basePath!==void 0&&owner.startsWith(`${basePath}/`)?owner.slice(basePath.length+1):owner,sshHost=hostWithoutPort(host);return{host,owner,name,httpsUrl:`https://${host}/${owner}/${name}.git`,sshUrl:options2.sshPort===void 0?`git@${sshHost}:${sshOwner}/${name}.git`:`ssh://git@${sshHost}:${options2.sshPort}/${sshOwner}/${name}.git`,...options2.sshPort===void 0?{}:{sshPort:options2.sshPort},...basePath===void 0||sshOwner===owner?{}:{basePath}}}function defaultLocator(id,defaultHost,host,repoPath,rest){let where3=host===defaultHost?repoPath:`${host}/${repoPath}`;return`${id}://${where3}${rest.length===0?"":`/${rest}`}`}var BROWSE_WORDS,init_host_helpers=__esm({"../sous-plugin-refs/src/locations/host-helpers.ts"(){"use strict";BROWSE_WORDS=new Set(["tree","blob"])}});import{definePlugin as definePlugin5,jsonSchema as jsonSchema7}from"@sous-io/sous-plugin-api";var PLUGIN_NAME4,BUILT_IN_SPLITTERS,refsPlugin,init_src4=__esm({"../sous-plugin-refs/src/index.ts"(){"use strict";init_format2();init_hash_names();init_locations();init_location_splitter();init_name_path_splitter();init_parser2();init_splitters();init_picker();init_pruners();init_resolver();init_package3();init_picker();init_partial_ref();init_rules();init_host_helpers();init_identity();init_names();init_parts();PLUGIN_NAME4="@sous-io/sous-plugin-refs",BUILT_IN_SPLITTERS=[querySplitter,rangeSplitter,locationSplitter,repoQualifierSplitter,envVarSplitter,namePathSplitter],refsPlugin=definePlugin5({name:PLUGIN_NAME4,version:package_default5.version,description:"Parsing and resolving refs, picking among matches, # names, repository locations and identity.",dependsOn:{"@sous-io/sous-plugin-host":`^${package_default5.version}`},register(sous){sous.entities.define("ref-splitter",jsonSchema7({type:"object",properties:{id:{type:"string"},order:{type:"number"}},required:["id","order","split"]}),{description:"One step of the ref parser: reads part of a written ref, every way it can be read."}),sous.entities.define("ref-pruner",jsonSchema7({type:"object",properties:{id:{type:"string"},source:{type:"string"},place:{type:"string"}},required:["id","source","place","prune"]}),{description:"Which readings of a ref count in one place it is written."}),sous.entities.define("ref-lookup",jsonSchema7({type:"object",properties:{id:{type:"string"},description:{type:"string"},kinds:{type:"array",items:{type:"string"}},tags:{type:"array",items:{type:"string"}},optIn:{type:"boolean"}},required:["id","find"]}),{description:"What exists, for narrowing the readings of a ref."}),sous.entities.define("hash-name",hashNameSchema,{description:"A '#' name, such as '#project', and what it stands for."});for(let splitter2 of BUILT_IN_SPLITTERS)sous.entities.add("ref-splitter",splitter2);for(let pruner of BUILT_IN_PRUNERS)sous.entities.add("ref-pruner",pruner);sous.entities.add("hash-name",projectHashName),sous.services.add("refs.locations",(_config,ctx)=>createRefsLocations(ctx.entities),{lifetime:"config"}),sous.services.add("refs.parser",(_config,ctx)=>createRefsParser(ctx),{lifetime:"config"}),sous.services.add("refs.resolver",(_config,ctx)=>createRefsResolver(ctx),{lifetime:"config"}),sous.services.add("refs.format",(_config,ctx)=>createRefsFormat(ctx),{lifetime:"config"}),sous.services.add("refs.picker",(_config,ctx)=>createRefsPicker(()=>ctx.services.get("refs.locations")),{lifetime:"config"})}})}});function $constructor(name,initializer3,params){function init(inst,def){if(inst._zod||Object.defineProperty(inst,"_zod",{value:{def,constr:_2,traits:new Set},enumerable:!1}),inst._zod.traits.has(name))return;inst._zod.traits.add(name),initializer3(inst,def);let proto=_2.prototype,keys=Object.keys(proto);for(let i=0;i<keys.length;i++){let k2=keys[i];k2 in inst||(inst[k2]=proto[k2].bind(inst))}}let Parent=params?.Parent??Object;class Definition extends Parent{}Object.defineProperty(Definition,"name",{value:name});function _2(def){var _a4;let inst=params?.Parent?new Definition:this;init(inst,def),(_a4=inst._zod).deferred??(_a4.deferred=[]);for(let fn of inst._zod.deferred)fn();return inst}return Object.defineProperty(_2,"init",{value:init}),Object.defineProperty(_2,Symbol.hasInstance,{value:inst=>params?.Parent&&inst instanceof params.Parent?!0:inst?._zod?.traits?.has(name)}),Object.defineProperty(_2,"name",{value:name}),_2}function config(newConfig){return newConfig&&Object.assign(globalConfig,newConfig),globalConfig}var _a2,NEVER,$brand,$ZodAsyncError,$ZodEncodeError,globalConfig,init_core=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/core.js"(){NEVER=Object.freeze({status:"aborted"});$brand=Symbol("zod_brand"),$ZodAsyncError=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},$ZodEncodeError=class extends Error{constructor(name){super(`Encountered unidirectional transform during encode: ${name}`),this.name="ZodEncodeError"}};(_a2=globalThis).__zod_globalConfig??(_a2.__zod_globalConfig={});globalConfig=globalThis.__zod_globalConfig}});var util_exports={};__export(util_exports,{BIGINT_FORMAT_RANGES:()=>BIGINT_FORMAT_RANGES,Class:()=>Class,NUMBER_FORMAT_RANGES:()=>NUMBER_FORMAT_RANGES,aborted:()=>aborted,allowsEval:()=>allowsEval,assert:()=>assert2,assertEqual:()=>assertEqual,assertIs:()=>assertIs,assertNever:()=>assertNever,assertNotEqual:()=>assertNotEqual,assignProp:()=>assignProp,base64ToUint8Array:()=>base64ToUint8Array,base64urlToUint8Array:()=>base64urlToUint8Array,cached:()=>cached,captureStackTrace:()=>captureStackTrace,cleanEnum:()=>cleanEnum,cleanRegex:()=>cleanRegex,clone:()=>clone,cloneDef:()=>cloneDef,createTransparentProxy:()=>createTransparentProxy,defineLazy:()=>defineLazy,esc:()=>esc,escapeRegex:()=>escapeRegex2,explicitlyAborted:()=>explicitlyAborted,extend:()=>extend,finalizeIssue:()=>finalizeIssue,floatSafeRemainder:()=>floatSafeRemainder,getElementAtPath:()=>getElementAtPath,getEnumValues:()=>getEnumValues,getLengthableOrigin:()=>getLengthableOrigin,getParsedType:()=>getParsedType,getSizableOrigin:()=>getSizableOrigin,hexToUint8Array:()=>hexToUint8Array,isObject:()=>isObject3,isPlainObject:()=>isPlainObject,issue:()=>issue,joinValues:()=>joinValues,jsonStringifyReplacer:()=>jsonStringifyReplacer,merge:()=>merge,mergeDefs:()=>mergeDefs,normalizeParams:()=>normalizeParams,nullish:()=>nullish,numKeys:()=>numKeys,objectClone:()=>objectClone,omit:()=>omit,optionalKeys:()=>optionalKeys,parsedType:()=>parsedType,partial:()=>partial,pick:()=>pick2,prefixIssues:()=>prefixIssues,primitiveTypes:()=>primitiveTypes,promiseAllObject:()=>promiseAllObject,propertyKeyTypes:()=>propertyKeyTypes,randomString:()=>randomString,required:()=>required,safeExtend:()=>safeExtend,shallowClone:()=>shallowClone,slugify:()=>slugify2,stringifyPrimitive:()=>stringifyPrimitive,uint8ArrayToBase64:()=>uint8ArrayToBase64,uint8ArrayToBase64url:()=>uint8ArrayToBase64url,uint8ArrayToHex:()=>uint8ArrayToHex,unwrapMessage:()=>unwrapMessage});function assertEqual(val){return val}function assertNotEqual(val){return val}function assertIs(_arg){}function assertNever(_x){throw new Error("Unexpected value in exhaustive check")}function assert2(_2){}function getEnumValues(entries){let numericValues=Object.values(entries).filter(v2=>typeof v2=="number");return Object.entries(entries).filter(([k2,_2])=>numericValues.indexOf(+k2)===-1).map(([_2,v2])=>v2)}function joinValues(array2,separator="|"){return array2.map(val=>stringifyPrimitive(val)).join(separator)}function jsonStringifyReplacer(_2,value){return typeof value=="bigint"?value.toString():value}function cached(getter){return{get value(){{let value=getter();return Object.defineProperty(this,"value",{value}),value}throw new Error("cached value already set")}}}function nullish(input){return input==null}function cleanRegex(source){let start2=source.startsWith("^")?1:0,end=source.endsWith("$")?source.length-1:source.length;return source.slice(start2,end)}function floatSafeRemainder(val,step){let ratio=val/step,roundedRatio=Math.round(ratio),tolerance=Number.EPSILON*Math.max(Math.abs(ratio),1);return Math.abs(ratio-roundedRatio)<tolerance?0:ratio-roundedRatio}function defineLazy(object3,key,getter){let value;Object.defineProperty(object3,key,{get(){if(value!==EVALUATING)return value===void 0&&(value=EVALUATING,value=getter()),value},set(v2){Object.defineProperty(object3,key,{value:v2})},configurable:!0})}function objectClone(obj){return Object.create(Object.getPrototypeOf(obj),Object.getOwnPropertyDescriptors(obj))}function assignProp(target,prop,value){Object.defineProperty(target,prop,{value,writable:!0,enumerable:!0,configurable:!0})}function mergeDefs(...defs){let mergedDescriptors={};for(let def of defs){let descriptors=Object.getOwnPropertyDescriptors(def);Object.assign(mergedDescriptors,descriptors)}return Object.defineProperties({},mergedDescriptors)}function cloneDef(schema){return mergeDefs(schema._zod.def)}function getElementAtPath(obj,path122){return path122?path122.reduce((acc,key)=>acc?.[key],obj):obj}function promiseAllObject(promisesObj){let keys=Object.keys(promisesObj),promises=keys.map(key=>promisesObj[key]);return Promise.all(promises).then(results=>{let resolvedObj={};for(let i=0;i<keys.length;i++)resolvedObj[keys[i]]=results[i];return resolvedObj})}function randomString(length=10){let chars="abcdefghijklmnopqrstuvwxyz",str="";for(let i=0;i<length;i++)str+=chars[Math.floor(Math.random()*chars.length)];return str}function esc(str){return JSON.stringify(str)}function slugify2(input){return input.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function isObject3(data){return typeof data=="object"&&data!==null&&!Array.isArray(data)}function isPlainObject(o){if(isObject3(o)===!1)return!1;let ctor=o.constructor;if(ctor===void 0||typeof ctor!="function")return!0;let prot=ctor.prototype;return!(isObject3(prot)===!1||Object.prototype.hasOwnProperty.call(prot,"isPrototypeOf")===!1)}function shallowClone(o){return isPlainObject(o)?{...o}:Array.isArray(o)?[...o]:o instanceof Map?new Map(o):o instanceof Set?new Set(o):o}function numKeys(data){let keyCount=0;for(let key in data)Object.prototype.hasOwnProperty.call(data,key)&&keyCount++;return keyCount}function escapeRegex2(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function clone(inst,def,params){let cl=new inst._zod.constr(def??inst._zod.def);return(!def||params?.parent)&&(cl._zod.parent=inst),cl}function normalizeParams(_params){let params=_params;if(!params)return{};if(typeof params=="string")return{error:()=>params};if(params?.message!==void 0){if(params?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");params.error=params.message}return delete params.message,typeof params.error=="string"?{...params,error:()=>params.error}:params}function createTransparentProxy(getter){let target;return new Proxy({},{get(_2,prop,receiver){return target??(target=getter()),Reflect.get(target,prop,receiver)},set(_2,prop,value,receiver){return target??(target=getter()),Reflect.set(target,prop,value,receiver)},has(_2,prop){return target??(target=getter()),Reflect.has(target,prop)},deleteProperty(_2,prop){return target??(target=getter()),Reflect.deleteProperty(target,prop)},ownKeys(_2){return target??(target=getter()),Reflect.ownKeys(target)},getOwnPropertyDescriptor(_2,prop){return target??(target=getter()),Reflect.getOwnPropertyDescriptor(target,prop)},defineProperty(_2,prop,descriptor){return target??(target=getter()),Reflect.defineProperty(target,prop,descriptor)}})}function stringifyPrimitive(value){return typeof value=="bigint"?value.toString()+"n":typeof value=="string"?`"${value}"`:`${value}`}function optionalKeys(shape){return Object.keys(shape).filter(k2=>shape[k2]._zod.optin==="optional"&&shape[k2]._zod.optout==="optional")}function pick2(schema,mask){let currDef=schema._zod.def,checks=currDef.checks;if(checks&&checks.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let def=mergeDefs(schema._zod.def,{get shape(){let newShape={};for(let key in mask){if(!(key in currDef.shape))throw new Error(`Unrecognized key: "${key}"`);mask[key]&&(newShape[key]=currDef.shape[key])}return assignProp(this,"shape",newShape),newShape},checks:[]});return clone(schema,def)}function omit(schema,mask){let currDef=schema._zod.def,checks=currDef.checks;if(checks&&checks.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let def=mergeDefs(schema._zod.def,{get shape(){let newShape={...schema._zod.def.shape};for(let key in mask){if(!(key in currDef.shape))throw new Error(`Unrecognized key: "${key}"`);mask[key]&&delete newShape[key]}return assignProp(this,"shape",newShape),newShape},checks:[]});return clone(schema,def)}function extend(schema,shape){if(!isPlainObject(shape))throw new Error("Invalid input to extend: expected a plain object");let checks=schema._zod.def.checks;if(checks&&checks.length>0){let existingShape=schema._zod.def.shape;for(let key in shape)if(Object.getOwnPropertyDescriptor(existingShape,key)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let def=mergeDefs(schema._zod.def,{get shape(){let _shape={...schema._zod.def.shape,...shape};return assignProp(this,"shape",_shape),_shape}});return clone(schema,def)}function safeExtend(schema,shape){if(!isPlainObject(shape))throw new Error("Invalid input to safeExtend: expected a plain object");let def=mergeDefs(schema._zod.def,{get shape(){let _shape={...schema._zod.def.shape,...shape};return assignProp(this,"shape",_shape),_shape}});return clone(schema,def)}function merge(a,b){if(a._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let def=mergeDefs(a._zod.def,{get shape(){let _shape={...a._zod.def.shape,...b._zod.def.shape};return assignProp(this,"shape",_shape),_shape},get catchall(){return b._zod.def.catchall},checks:b._zod.def.checks??[]});return clone(a,def)}function partial(Class2,schema,mask){let checks=schema._zod.def.checks;if(checks&&checks.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let def=mergeDefs(schema._zod.def,{get shape(){let oldShape=schema._zod.def.shape,shape={...oldShape};if(mask)for(let key in mask){if(!(key in oldShape))throw new Error(`Unrecognized key: "${key}"`);mask[key]&&(shape[key]=Class2?new Class2({type:"optional",innerType:oldShape[key]}):oldShape[key])}else for(let key in oldShape)shape[key]=Class2?new Class2({type:"optional",innerType:oldShape[key]}):oldShape[key];return assignProp(this,"shape",shape),shape},checks:[]});return clone(schema,def)}function required(Class2,schema,mask){let def=mergeDefs(schema._zod.def,{get shape(){let oldShape=schema._zod.def.shape,shape={...oldShape};if(mask)for(let key in mask){if(!(key in shape))throw new Error(`Unrecognized key: "${key}"`);mask[key]&&(shape[key]=new Class2({type:"nonoptional",innerType:oldShape[key]}))}else for(let key in oldShape)shape[key]=new Class2({type:"nonoptional",innerType:oldShape[key]});return assignProp(this,"shape",shape),shape}});return clone(schema,def)}function aborted(x2,startIndex=0){if(x2.aborted===!0)return!0;for(let i=startIndex;i<x2.issues.length;i++)if(x2.issues[i]?.continue!==!0)return!0;return!1}function explicitlyAborted(x2,startIndex=0){if(x2.aborted===!0)return!0;for(let i=startIndex;i<x2.issues.length;i++)if(x2.issues[i]?.continue===!1)return!0;return!1}function prefixIssues(path122,issues){return issues.map(iss=>{var _a4;return(_a4=iss).path??(_a4.path=[]),iss.path.unshift(path122),iss})}function unwrapMessage(message2){return typeof message2=="string"?message2:message2?.message}function finalizeIssue(iss,ctx,config2){let message2=iss.message?iss.message:unwrapMessage(iss.inst?._zod.def?.error?.(iss))??unwrapMessage(ctx?.error?.(iss))??unwrapMessage(config2.customError?.(iss))??unwrapMessage(config2.localeError?.(iss))??"Invalid input",{inst:_inst,continue:_continue,input:_input,...rest}=iss;return rest.path??(rest.path=[]),rest.message=message2,ctx?.reportInput&&(rest.input=_input),rest}function getSizableOrigin(input){return input instanceof Set?"set":input instanceof Map?"map":input instanceof File?"file":"unknown"}function getLengthableOrigin(input){return Array.isArray(input)?"array":typeof input=="string"?"string":"unknown"}function parsedType(data){let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"nan":"number";case"object":{if(data===null)return"null";if(Array.isArray(data))return"array";let obj=data;if(obj&&Object.getPrototypeOf(obj)!==Object.prototype&&"constructor"in obj&&obj.constructor)return obj.constructor.name}}return t}function issue(...args){let[iss,input,inst]=args;return typeof iss=="string"?{message:iss,code:"custom",input,inst}:{...iss}}function cleanEnum(obj){return Object.entries(obj).filter(([k2,_2])=>Number.isNaN(Number.parseInt(k2,10))).map(el=>el[1])}function base64ToUint8Array(base643){let binaryString=atob(base643),bytes=new Uint8Array(binaryString.length);for(let i=0;i<binaryString.length;i++)bytes[i]=binaryString.charCodeAt(i);return bytes}function uint8ArrayToBase64(bytes){let binaryString="";for(let i=0;i<bytes.length;i++)binaryString+=String.fromCharCode(bytes[i]);return btoa(binaryString)}function base64urlToUint8Array(base64url3){let base643=base64url3.replace(/-/g,"+").replace(/_/g,"/"),padding="=".repeat((4-base643.length%4)%4);return base64ToUint8Array(base643+padding)}function uint8ArrayToBase64url(bytes){return uint8ArrayToBase64(bytes).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function hexToUint8Array(hex3){let cleanHex=hex3.replace(/^0x/,"");if(cleanHex.length%2!==0)throw new Error("Invalid hex string length");let bytes=new Uint8Array(cleanHex.length/2);for(let i=0;i<cleanHex.length;i+=2)bytes[i/2]=Number.parseInt(cleanHex.slice(i,i+2),16);return bytes}function uint8ArrayToHex(bytes){return Array.from(bytes).map(b=>b.toString(16).padStart(2,"0")).join("")}var EVALUATING,captureStackTrace,allowsEval,getParsedType,propertyKeyTypes,primitiveTypes,NUMBER_FORMAT_RANGES,BIGINT_FORMAT_RANGES,Class,init_util=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/util.js"(){init_core();EVALUATING=Symbol("evaluating");captureStackTrace="captureStackTrace"in Error?Error.captureStackTrace:(..._args)=>{};allowsEval=cached(()=>{if(globalConfig.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let F2=Function;return new F2(""),!0}catch{return!1}});getParsedType=data=>{let t=typeof data;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(data)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(data)?"array":data===null?"null":data.then&&typeof data.then=="function"&&data.catch&&typeof data.catch=="function"?"promise":typeof Map<"u"&&data instanceof Map?"map":typeof Set<"u"&&data instanceof Set?"set":typeof Date<"u"&&data instanceof Date?"date":typeof File<"u"&&data instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},propertyKeyTypes=new Set(["string","number","symbol"]),primitiveTypes=new Set(["string","number","bigint","boolean","symbol","undefined"]);NUMBER_FORMAT_RANGES={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},BIGINT_FORMAT_RANGES={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Class=class{constructor(..._args){}}}});function flattenError(error51,mapper=issue2=>issue2.message){let fieldErrors={},formErrors=[];for(let sub of error51.issues)sub.path.length>0?(fieldErrors[sub.path[0]]=fieldErrors[sub.path[0]]||[],fieldErrors[sub.path[0]].push(mapper(sub))):formErrors.push(mapper(sub));return{formErrors,fieldErrors}}function formatError(error51,mapper=issue2=>issue2.message){let fieldErrors={_errors:[]},processError=(error52,path122=[])=>{for(let issue2 of error52.issues)if(issue2.code==="invalid_union"&&issue2.errors.length)issue2.errors.map(issues=>processError({issues},[...path122,...issue2.path]));else if(issue2.code==="invalid_key")processError({issues:issue2.issues},[...path122,...issue2.path]);else if(issue2.code==="invalid_element")processError({issues:issue2.issues},[...path122,...issue2.path]);else{let fullpath=[...path122,...issue2.path];if(fullpath.length===0)fieldErrors._errors.push(mapper(issue2));else{let curr=fieldErrors,i=0;for(;i<fullpath.length;){let el=fullpath[i];i===fullpath.length-1?(curr[el]=curr[el]||{_errors:[]},curr[el]._errors.push(mapper(issue2))):curr[el]=curr[el]||{_errors:[]},curr=curr[el],i++}}}};return processError(error51),fieldErrors}function treeifyError(error51,mapper=issue2=>issue2.message){let result={errors:[]},processError=(error52,path122=[])=>{var _a4,_b;for(let issue2 of error52.issues)if(issue2.code==="invalid_union"&&issue2.errors.length)issue2.errors.map(issues=>processError({issues},[...path122,...issue2.path]));else if(issue2.code==="invalid_key")processError({issues:issue2.issues},[...path122,...issue2.path]);else if(issue2.code==="invalid_element")processError({issues:issue2.issues},[...path122,...issue2.path]);else{let fullpath=[...path122,...issue2.path];if(fullpath.length===0){result.errors.push(mapper(issue2));continue}let curr=result,i=0;for(;i<fullpath.length;){let el=fullpath[i],terminal=i===fullpath.length-1;typeof el=="string"?(curr.properties??(curr.properties={}),(_a4=curr.properties)[el]??(_a4[el]={errors:[]}),curr=curr.properties[el]):(curr.items??(curr.items=[]),(_b=curr.items)[el]??(_b[el]={errors:[]}),curr=curr.items[el]),terminal&&curr.errors.push(mapper(issue2)),i++}}};return processError(error51),result}function toDotPath(_path){let segs=[],path122=_path.map(seg=>typeof seg=="object"?seg.key:seg);for(let seg of path122)typeof seg=="number"?segs.push(`[${seg}]`):typeof seg=="symbol"?segs.push(`[${JSON.stringify(String(seg))}]`):/[^\w$]/.test(seg)?segs.push(`[${JSON.stringify(seg)}]`):(segs.length&&segs.push("."),segs.push(seg));return segs.join("")}function prettifyError(error51){let lines3=[],issues=[...error51.issues].sort((a,b)=>(a.path??[]).length-(b.path??[]).length);for(let issue2 of issues)lines3.push(`\u2716 ${issue2.message}`),issue2.path?.length&&lines3.push(` \u2192 at ${toDotPath(issue2.path)}`);return lines3.join(`
366
+ `))},resolution=(input,refs,pruned,usedLookup)=>({input,refs,dropped:pruned.dropped,warnings:pruned.warnings,usedLookup}),parse6=(input,from="commandLine")=>{let pruned=prune3(input,from);if(pruned.kept.length===0)throw refusal(input,pruned.place,pruned.dropped);return resolution(input,orderRefs(pruned.kept.map(ref=>({ref,rank:ref}))),pruned,!1)},begin=request=>{let pruned;try{pruned=prune3(request.input,request.from??"commandLine")}catch(error51){if(request.refusedIsEmpty===!0)return{result:resolution(request.input,[],{dropped:[],warnings:[]},!0)};throw error51}if(pruned.kept.length===0){if(request.refusedIsEmpty===!0)return{result:resolution(request.input,[],pruned,!0)};throw refusal(request.input,pruned.place,pruned.dropped)}let kinds=request.kinds,kept=kinds===void 0?pruned.kept:pruned.kept.filter(ref=>kinds.includes(ref.kind)||browsedFits(ref,kinds)),selected2=selectLookups(ctx.entities.list("ref-lookup"),request.lookups),lookups=[...request.extraLookups??[],...selected2];if(Array.isArray(request.lookups)&&request.lookups.length>0&&selected2.length===0&&request.extraLookups===void 0)throw new ConfigError15(`No ref lookup answers to ${request.lookups.map(name=>`'${name}'`).join(", ")}.`,{details:["The plugin that adds it may be disabled or missing."]});return lookups.length===0?{result:resolution(request.input,orderRefs(kept.map(ref=>({ref,rank:ref}))),pruned,!1)}:{kept,pruned,lookups}},finish4=(request,pruned,found)=>{let kinds=request.kinds,matching2=found.filter(entry=>kinds===void 0||kinds.includes(entry.match.ref.kind)),exact=matching2.filter(entry=>entry.match.exactSpelling),chosen=exact.length>0?exact:matching2;return resolution(request.input,orderRefs(chosen.map(entry=>({ref:entry.match.ref,rank:entry.rank}))),pruned,!0)};return{parse:parse6,async resolve(request){let early=begin(request);if("result"in early)return early.result;let found=[];for(let candidate of early.kept)for(let lookup of early.lookups)if(answersFor(lookup,candidate))for(let match2 of await lookup.find(candidate,ctx))found.push({match:match2,rank:candidate});return finish4(request,early.pruned,found)},resolveSync(request){let early=begin(request);if("result"in early)return early.result;let found=[];for(let candidate of early.kept)for(let lookup of early.lookups)if(lookup.findSync!==void 0&&answersFor(lookup,candidate))for(let match2 of lookup.findSync(candidate,ctx))found.push({match:match2,rank:candidate});return finish4(request,early.pruned,found)},isValid(input,from="commandLine"){try{return parse6(input,from),!0}catch{return!1}},findInString(text,from="commandLine"){let found=[];for(let word of text.matchAll(/\S+/g)){let bare=word[0].replace(/^[`"'([<{]+/,"").replace(/[`"')\]>},.;:!]+$/,"");if(bare.length!==0)try{found.push({text:bare,index:word.index+word[0].indexOf(bare),result:parse6(bare,from)})}catch{}}return found}}}var init_resolver=__esm({"../sous-plugin-refs/src/resolver.ts"(){"use strict";init_format2();init_parser2();init_parts();init_rules()}});var package_default5,init_package3=__esm({"../sous-plugin-refs/package.json"(){package_default5={name:"@sous-io/sous-plugin-refs",version:"1.1.6",description:"Parsing and resolving refs, picking among matches, # names, repository locations and identity.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-host":"workspace:*",semver:"^7.8.5"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*","@types/semver":"^7.8.0"},engines:{node:">=22"}}}});function withoutGitSuffix(segment){return segment.replace(/\.git$/i,"")}function readingsAfterRepository(repoPath,rest){let after=rest[0]==="-"?rest.slice(1):[...rest],readings=[];return after.length>=2&&BROWSE_WORDS.has(after[0].toLowerCase())&&readings.push({repoPath,browsed:after.slice(1).join("/")}),readings.push({repoPath,named:after}),readings}function normalizeRepoUrl(url2){let value=url2.trim();for(;value.endsWith("/");)value=value.slice(0,-1);return value.endsWith(".git")&&(value=value.slice(0,-4)),value}function splitRepoUrl(url2){let normalized=normalizeRepoUrl(url2);if(normalized.length===0)return;let host,repoPath,sshPort,scp=/^(?:([^@\s/]+)@)?([^@\s/:]+):(.+)$/.exec(normalized);if(/^[a-z][a-z0-9+.-]*:\/\//i.test(normalized)){let parsed;try{parsed=new URL(normalized)}catch{return}/^ssh:$/i.test(parsed.protocol)||/^git\+ssh:$/i.test(parsed.protocol)?(host=parsed.hostname.toLowerCase(),sshPort=parsed.port===""?void 0:Number(parsed.port)):host=parsed.host.toLowerCase(),repoPath=parsed.pathname.replace(/^\/+/,"")}else if(scp!==null)host=scp[2].toLowerCase(),repoPath=scp[3].replace(/^\/+/,"");else return;let segments=repoPath.split("/").filter(segment=>segment.length>0);if(!(segments.length<2||host.length===0))return{host,owner:segments.slice(0,-1).join("/"),name:segments[segments.length-1],...sshPort===void 0?{}:{sshPort}}}function hostWithoutPort(host){return host.replace(/:\d+$/,"")}function buildCanonicalRepository(host,owner,name,options2={}){let basePath=options2.basePath?.replace(/^\/+|\/+$/g,"")||void 0,sshOwner=basePath!==void 0&&owner.startsWith(`${basePath}/`)?owner.slice(basePath.length+1):owner,sshHost=hostWithoutPort(host);return{host,owner,name,httpsUrl:`https://${host}/${owner}/${name}.git`,sshUrl:options2.sshPort===void 0?`git@${sshHost}:${sshOwner}/${name}.git`:`ssh://git@${sshHost}:${options2.sshPort}/${sshOwner}/${name}.git`,...options2.sshPort===void 0?{}:{sshPort:options2.sshPort},...basePath===void 0||sshOwner===owner?{}:{basePath}}}function defaultLocator(id,defaultHost,host,repoPath,rest){let where3=host===defaultHost?repoPath:`${host}/${repoPath}`;return`${id}://${where3}${rest.length===0?"":`/${rest}`}`}var BROWSE_WORDS,init_host_helpers=__esm({"../sous-plugin-refs/src/locations/host-helpers.ts"(){"use strict";BROWSE_WORDS=new Set(["tree","blob"])}});import{definePlugin as definePlugin5,jsonSchema as jsonSchema7}from"@sous-io/sous-plugin-api";var PLUGIN_NAME4,BUILT_IN_SPLITTERS,refsPlugin,init_src4=__esm({"../sous-plugin-refs/src/index.ts"(){"use strict";init_format2();init_hash_names();init_locations();init_location_splitter();init_name_path_splitter();init_parser2();init_splitters();init_picker();init_pruners();init_resolver();init_package3();init_picker();init_partial_ref();init_rules();init_host_helpers();init_identity();init_names();init_parts();PLUGIN_NAME4="@sous-io/sous-plugin-refs",BUILT_IN_SPLITTERS=[querySplitter,rangeSplitter,locationSplitter,repoQualifierSplitter,envVarSplitter,namePathSplitter],refsPlugin=definePlugin5({name:PLUGIN_NAME4,version:package_default5.version,description:"Parsing and resolving refs, picking among matches, # names, repository locations and identity.",dependsOn:{"@sous-io/sous-plugin-host":`^${package_default5.version}`},register(sous){sous.entities.define("ref-splitter",jsonSchema7({type:"object",properties:{id:{type:"string"},order:{type:"number"}},required:["id","order","split"]}),{description:"One step of the ref parser: reads part of a written ref, every way it can be read."}),sous.entities.define("ref-pruner",jsonSchema7({type:"object",properties:{id:{type:"string"},source:{type:"string"},place:{type:"string"}},required:["id","source","place","prune"]}),{description:"Which readings of a ref count in one place it is written."}),sous.entities.define("ref-lookup",jsonSchema7({type:"object",properties:{id:{type:"string"},description:{type:"string"},kinds:{type:"array",items:{type:"string"}},tags:{type:"array",items:{type:"string"}},optIn:{type:"boolean"}},required:["id","find"]}),{description:"What exists, for narrowing the readings of a ref."}),sous.entities.define("hash-name",hashNameSchema,{description:"A '#' name, such as '#project', and what it stands for."});for(let splitter2 of BUILT_IN_SPLITTERS)sous.entities.add("ref-splitter",splitter2);for(let pruner of BUILT_IN_PRUNERS)sous.entities.add("ref-pruner",pruner);sous.entities.add("hash-name",projectHashName),sous.services.add("refs.locations",(_config,ctx)=>createRefsLocations(ctx.entities),{lifetime:"config"}),sous.services.add("refs.parser",(_config,ctx)=>createRefsParser(ctx),{lifetime:"config"}),sous.services.add("refs.resolver",(_config,ctx)=>createRefsResolver(ctx),{lifetime:"config"}),sous.services.add("refs.format",(_config,ctx)=>createRefsFormat(ctx),{lifetime:"config"}),sous.services.add("refs.picker",(_config,ctx)=>createRefsPicker(()=>ctx.services.get("refs.locations")),{lifetime:"config"})}})}});function $constructor(name,initializer3,params){function init(inst,def){if(inst._zod||Object.defineProperty(inst,"_zod",{value:{def,constr:_2,traits:new Set},enumerable:!1}),inst._zod.traits.has(name))return;inst._zod.traits.add(name),initializer3(inst,def);let proto=_2.prototype,keys=Object.keys(proto);for(let i=0;i<keys.length;i++){let k2=keys[i];k2 in inst||(inst[k2]=proto[k2].bind(inst))}}let Parent=params?.Parent??Object;class Definition extends Parent{}Object.defineProperty(Definition,"name",{value:name});function _2(def){var _a4;let inst=params?.Parent?new Definition:this;init(inst,def),(_a4=inst._zod).deferred??(_a4.deferred=[]);for(let fn of inst._zod.deferred)fn();return inst}return Object.defineProperty(_2,"init",{value:init}),Object.defineProperty(_2,Symbol.hasInstance,{value:inst=>params?.Parent&&inst instanceof params.Parent?!0:inst?._zod?.traits?.has(name)}),Object.defineProperty(_2,"name",{value:name}),_2}function config(newConfig){return newConfig&&Object.assign(globalConfig,newConfig),globalConfig}var _a2,NEVER,$brand,$ZodAsyncError,$ZodEncodeError,globalConfig,init_core=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/core.js"(){NEVER=Object.freeze({status:"aborted"});$brand=Symbol("zod_brand"),$ZodAsyncError=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},$ZodEncodeError=class extends Error{constructor(name){super(`Encountered unidirectional transform during encode: ${name}`),this.name="ZodEncodeError"}};(_a2=globalThis).__zod_globalConfig??(_a2.__zod_globalConfig={});globalConfig=globalThis.__zod_globalConfig}});var util_exports={};__export(util_exports,{BIGINT_FORMAT_RANGES:()=>BIGINT_FORMAT_RANGES,Class:()=>Class,NUMBER_FORMAT_RANGES:()=>NUMBER_FORMAT_RANGES,aborted:()=>aborted,allowsEval:()=>allowsEval,assert:()=>assert2,assertEqual:()=>assertEqual,assertIs:()=>assertIs,assertNever:()=>assertNever,assertNotEqual:()=>assertNotEqual,assignProp:()=>assignProp,base64ToUint8Array:()=>base64ToUint8Array,base64urlToUint8Array:()=>base64urlToUint8Array,cached:()=>cached,captureStackTrace:()=>captureStackTrace,cleanEnum:()=>cleanEnum,cleanRegex:()=>cleanRegex,clone:()=>clone,cloneDef:()=>cloneDef,createTransparentProxy:()=>createTransparentProxy,defineLazy:()=>defineLazy,esc:()=>esc,escapeRegex:()=>escapeRegex2,explicitlyAborted:()=>explicitlyAborted,extend:()=>extend,finalizeIssue:()=>finalizeIssue,floatSafeRemainder:()=>floatSafeRemainder,getElementAtPath:()=>getElementAtPath,getEnumValues:()=>getEnumValues,getLengthableOrigin:()=>getLengthableOrigin,getParsedType:()=>getParsedType,getSizableOrigin:()=>getSizableOrigin,hexToUint8Array:()=>hexToUint8Array,isObject:()=>isObject3,isPlainObject:()=>isPlainObject,issue:()=>issue,joinValues:()=>joinValues,jsonStringifyReplacer:()=>jsonStringifyReplacer,merge:()=>merge,mergeDefs:()=>mergeDefs,normalizeParams:()=>normalizeParams,nullish:()=>nullish,numKeys:()=>numKeys,objectClone:()=>objectClone,omit:()=>omit,optionalKeys:()=>optionalKeys,parsedType:()=>parsedType,partial:()=>partial,pick:()=>pick2,prefixIssues:()=>prefixIssues,primitiveTypes:()=>primitiveTypes,promiseAllObject:()=>promiseAllObject,propertyKeyTypes:()=>propertyKeyTypes,randomString:()=>randomString,required:()=>required,safeExtend:()=>safeExtend,shallowClone:()=>shallowClone,slugify:()=>slugify2,stringifyPrimitive:()=>stringifyPrimitive,uint8ArrayToBase64:()=>uint8ArrayToBase64,uint8ArrayToBase64url:()=>uint8ArrayToBase64url,uint8ArrayToHex:()=>uint8ArrayToHex,unwrapMessage:()=>unwrapMessage});function assertEqual(val){return val}function assertNotEqual(val){return val}function assertIs(_arg){}function assertNever(_x){throw new Error("Unexpected value in exhaustive check")}function assert2(_2){}function getEnumValues(entries){let numericValues=Object.values(entries).filter(v2=>typeof v2=="number");return Object.entries(entries).filter(([k2,_2])=>numericValues.indexOf(+k2)===-1).map(([_2,v2])=>v2)}function joinValues(array2,separator="|"){return array2.map(val=>stringifyPrimitive(val)).join(separator)}function jsonStringifyReplacer(_2,value){return typeof value=="bigint"?value.toString():value}function cached(getter){return{get value(){{let value=getter();return Object.defineProperty(this,"value",{value}),value}throw new Error("cached value already set")}}}function nullish(input){return input==null}function cleanRegex(source){let start2=source.startsWith("^")?1:0,end=source.endsWith("$")?source.length-1:source.length;return source.slice(start2,end)}function floatSafeRemainder(val,step){let ratio=val/step,roundedRatio=Math.round(ratio),tolerance=Number.EPSILON*Math.max(Math.abs(ratio),1);return Math.abs(ratio-roundedRatio)<tolerance?0:ratio-roundedRatio}function defineLazy(object3,key,getter){let value;Object.defineProperty(object3,key,{get(){if(value!==EVALUATING)return value===void 0&&(value=EVALUATING,value=getter()),value},set(v2){Object.defineProperty(object3,key,{value:v2})},configurable:!0})}function objectClone(obj){return Object.create(Object.getPrototypeOf(obj),Object.getOwnPropertyDescriptors(obj))}function assignProp(target,prop,value){Object.defineProperty(target,prop,{value,writable:!0,enumerable:!0,configurable:!0})}function mergeDefs(...defs){let mergedDescriptors={};for(let def of defs){let descriptors=Object.getOwnPropertyDescriptors(def);Object.assign(mergedDescriptors,descriptors)}return Object.defineProperties({},mergedDescriptors)}function cloneDef(schema){return mergeDefs(schema._zod.def)}function getElementAtPath(obj,path122){return path122?path122.reduce((acc,key)=>acc?.[key],obj):obj}function promiseAllObject(promisesObj){let keys=Object.keys(promisesObj),promises=keys.map(key=>promisesObj[key]);return Promise.all(promises).then(results=>{let resolvedObj={};for(let i=0;i<keys.length;i++)resolvedObj[keys[i]]=results[i];return resolvedObj})}function randomString(length=10){let chars="abcdefghijklmnopqrstuvwxyz",str="";for(let i=0;i<length;i++)str+=chars[Math.floor(Math.random()*chars.length)];return str}function esc(str){return JSON.stringify(str)}function slugify2(input){return input.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function isObject3(data){return typeof data=="object"&&data!==null&&!Array.isArray(data)}function isPlainObject(o){if(isObject3(o)===!1)return!1;let ctor=o.constructor;if(ctor===void 0||typeof ctor!="function")return!0;let prot=ctor.prototype;return!(isObject3(prot)===!1||Object.prototype.hasOwnProperty.call(prot,"isPrototypeOf")===!1)}function shallowClone(o){return isPlainObject(o)?{...o}:Array.isArray(o)?[...o]:o instanceof Map?new Map(o):o instanceof Set?new Set(o):o}function numKeys(data){let keyCount=0;for(let key in data)Object.prototype.hasOwnProperty.call(data,key)&&keyCount++;return keyCount}function escapeRegex2(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function clone(inst,def,params){let cl=new inst._zod.constr(def??inst._zod.def);return(!def||params?.parent)&&(cl._zod.parent=inst),cl}function normalizeParams(_params){let params=_params;if(!params)return{};if(typeof params=="string")return{error:()=>params};if(params?.message!==void 0){if(params?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");params.error=params.message}return delete params.message,typeof params.error=="string"?{...params,error:()=>params.error}:params}function createTransparentProxy(getter){let target;return new Proxy({},{get(_2,prop,receiver){return target??(target=getter()),Reflect.get(target,prop,receiver)},set(_2,prop,value,receiver){return target??(target=getter()),Reflect.set(target,prop,value,receiver)},has(_2,prop){return target??(target=getter()),Reflect.has(target,prop)},deleteProperty(_2,prop){return target??(target=getter()),Reflect.deleteProperty(target,prop)},ownKeys(_2){return target??(target=getter()),Reflect.ownKeys(target)},getOwnPropertyDescriptor(_2,prop){return target??(target=getter()),Reflect.getOwnPropertyDescriptor(target,prop)},defineProperty(_2,prop,descriptor){return target??(target=getter()),Reflect.defineProperty(target,prop,descriptor)}})}function stringifyPrimitive(value){return typeof value=="bigint"?value.toString()+"n":typeof value=="string"?`"${value}"`:`${value}`}function optionalKeys(shape){return Object.keys(shape).filter(k2=>shape[k2]._zod.optin==="optional"&&shape[k2]._zod.optout==="optional")}function pick2(schema,mask){let currDef=schema._zod.def,checks=currDef.checks;if(checks&&checks.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let def=mergeDefs(schema._zod.def,{get shape(){let newShape={};for(let key in mask){if(!(key in currDef.shape))throw new Error(`Unrecognized key: "${key}"`);mask[key]&&(newShape[key]=currDef.shape[key])}return assignProp(this,"shape",newShape),newShape},checks:[]});return clone(schema,def)}function omit(schema,mask){let currDef=schema._zod.def,checks=currDef.checks;if(checks&&checks.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let def=mergeDefs(schema._zod.def,{get shape(){let newShape={...schema._zod.def.shape};for(let key in mask){if(!(key in currDef.shape))throw new Error(`Unrecognized key: "${key}"`);mask[key]&&delete newShape[key]}return assignProp(this,"shape",newShape),newShape},checks:[]});return clone(schema,def)}function extend(schema,shape){if(!isPlainObject(shape))throw new Error("Invalid input to extend: expected a plain object");let checks=schema._zod.def.checks;if(checks&&checks.length>0){let existingShape=schema._zod.def.shape;for(let key in shape)if(Object.getOwnPropertyDescriptor(existingShape,key)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let def=mergeDefs(schema._zod.def,{get shape(){let _shape={...schema._zod.def.shape,...shape};return assignProp(this,"shape",_shape),_shape}});return clone(schema,def)}function safeExtend(schema,shape){if(!isPlainObject(shape))throw new Error("Invalid input to safeExtend: expected a plain object");let def=mergeDefs(schema._zod.def,{get shape(){let _shape={...schema._zod.def.shape,...shape};return assignProp(this,"shape",_shape),_shape}});return clone(schema,def)}function merge(a,b){if(a._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let def=mergeDefs(a._zod.def,{get shape(){let _shape={...a._zod.def.shape,...b._zod.def.shape};return assignProp(this,"shape",_shape),_shape},get catchall(){return b._zod.def.catchall},checks:b._zod.def.checks??[]});return clone(a,def)}function partial(Class2,schema,mask){let checks=schema._zod.def.checks;if(checks&&checks.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let def=mergeDefs(schema._zod.def,{get shape(){let oldShape=schema._zod.def.shape,shape={...oldShape};if(mask)for(let key in mask){if(!(key in oldShape))throw new Error(`Unrecognized key: "${key}"`);mask[key]&&(shape[key]=Class2?new Class2({type:"optional",innerType:oldShape[key]}):oldShape[key])}else for(let key in oldShape)shape[key]=Class2?new Class2({type:"optional",innerType:oldShape[key]}):oldShape[key];return assignProp(this,"shape",shape),shape},checks:[]});return clone(schema,def)}function required(Class2,schema,mask){let def=mergeDefs(schema._zod.def,{get shape(){let oldShape=schema._zod.def.shape,shape={...oldShape};if(mask)for(let key in mask){if(!(key in shape))throw new Error(`Unrecognized key: "${key}"`);mask[key]&&(shape[key]=new Class2({type:"nonoptional",innerType:oldShape[key]}))}else for(let key in oldShape)shape[key]=new Class2({type:"nonoptional",innerType:oldShape[key]});return assignProp(this,"shape",shape),shape}});return clone(schema,def)}function aborted(x2,startIndex=0){if(x2.aborted===!0)return!0;for(let i=startIndex;i<x2.issues.length;i++)if(x2.issues[i]?.continue!==!0)return!0;return!1}function explicitlyAborted(x2,startIndex=0){if(x2.aborted===!0)return!0;for(let i=startIndex;i<x2.issues.length;i++)if(x2.issues[i]?.continue===!1)return!0;return!1}function prefixIssues(path122,issues){return issues.map(iss=>{var _a4;return(_a4=iss).path??(_a4.path=[]),iss.path.unshift(path122),iss})}function unwrapMessage(message2){return typeof message2=="string"?message2:message2?.message}function finalizeIssue(iss,ctx,config2){let message2=iss.message?iss.message:unwrapMessage(iss.inst?._zod.def?.error?.(iss))??unwrapMessage(ctx?.error?.(iss))??unwrapMessage(config2.customError?.(iss))??unwrapMessage(config2.localeError?.(iss))??"Invalid input",{inst:_inst,continue:_continue,input:_input,...rest}=iss;return rest.path??(rest.path=[]),rest.message=message2,ctx?.reportInput&&(rest.input=_input),rest}function getSizableOrigin(input){return input instanceof Set?"set":input instanceof Map?"map":input instanceof File?"file":"unknown"}function getLengthableOrigin(input){return Array.isArray(input)?"array":typeof input=="string"?"string":"unknown"}function parsedType(data){let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"nan":"number";case"object":{if(data===null)return"null";if(Array.isArray(data))return"array";let obj=data;if(obj&&Object.getPrototypeOf(obj)!==Object.prototype&&"constructor"in obj&&obj.constructor)return obj.constructor.name}}return t}function issue(...args){let[iss,input,inst]=args;return typeof iss=="string"?{message:iss,code:"custom",input,inst}:{...iss}}function cleanEnum(obj){return Object.entries(obj).filter(([k2,_2])=>Number.isNaN(Number.parseInt(k2,10))).map(el=>el[1])}function base64ToUint8Array(base643){let binaryString=atob(base643),bytes=new Uint8Array(binaryString.length);for(let i=0;i<binaryString.length;i++)bytes[i]=binaryString.charCodeAt(i);return bytes}function uint8ArrayToBase64(bytes){let binaryString="";for(let i=0;i<bytes.length;i++)binaryString+=String.fromCharCode(bytes[i]);return btoa(binaryString)}function base64urlToUint8Array(base64url3){let base643=base64url3.replace(/-/g,"+").replace(/_/g,"/"),padding="=".repeat((4-base643.length%4)%4);return base64ToUint8Array(base643+padding)}function uint8ArrayToBase64url(bytes){return uint8ArrayToBase64(bytes).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function hexToUint8Array(hex3){let cleanHex=hex3.replace(/^0x/,"");if(cleanHex.length%2!==0)throw new Error("Invalid hex string length");let bytes=new Uint8Array(cleanHex.length/2);for(let i=0;i<cleanHex.length;i+=2)bytes[i/2]=Number.parseInt(cleanHex.slice(i,i+2),16);return bytes}function uint8ArrayToHex(bytes){return Array.from(bytes).map(b=>b.toString(16).padStart(2,"0")).join("")}var EVALUATING,captureStackTrace,allowsEval,getParsedType,propertyKeyTypes,primitiveTypes,NUMBER_FORMAT_RANGES,BIGINT_FORMAT_RANGES,Class,init_util=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/util.js"(){init_core();EVALUATING=Symbol("evaluating");captureStackTrace="captureStackTrace"in Error?Error.captureStackTrace:(..._args)=>{};allowsEval=cached(()=>{if(globalConfig.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let F2=Function;return new F2(""),!0}catch{return!1}});getParsedType=data=>{let t=typeof data;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(data)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(data)?"array":data===null?"null":data.then&&typeof data.then=="function"&&data.catch&&typeof data.catch=="function"?"promise":typeof Map<"u"&&data instanceof Map?"map":typeof Set<"u"&&data instanceof Set?"set":typeof Date<"u"&&data instanceof Date?"date":typeof File<"u"&&data instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},propertyKeyTypes=new Set(["string","number","symbol"]),primitiveTypes=new Set(["string","number","bigint","boolean","symbol","undefined"]);NUMBER_FORMAT_RANGES={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},BIGINT_FORMAT_RANGES={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Class=class{constructor(..._args){}}}});function flattenError(error51,mapper=issue2=>issue2.message){let fieldErrors={},formErrors=[];for(let sub of error51.issues)sub.path.length>0?(fieldErrors[sub.path[0]]=fieldErrors[sub.path[0]]||[],fieldErrors[sub.path[0]].push(mapper(sub))):formErrors.push(mapper(sub));return{formErrors,fieldErrors}}function formatError(error51,mapper=issue2=>issue2.message){let fieldErrors={_errors:[]},processError=(error52,path122=[])=>{for(let issue2 of error52.issues)if(issue2.code==="invalid_union"&&issue2.errors.length)issue2.errors.map(issues=>processError({issues},[...path122,...issue2.path]));else if(issue2.code==="invalid_key")processError({issues:issue2.issues},[...path122,...issue2.path]);else if(issue2.code==="invalid_element")processError({issues:issue2.issues},[...path122,...issue2.path]);else{let fullpath=[...path122,...issue2.path];if(fullpath.length===0)fieldErrors._errors.push(mapper(issue2));else{let curr=fieldErrors,i=0;for(;i<fullpath.length;){let el=fullpath[i];i===fullpath.length-1?(curr[el]=curr[el]||{_errors:[]},curr[el]._errors.push(mapper(issue2))):curr[el]=curr[el]||{_errors:[]},curr=curr[el],i++}}}};return processError(error51),fieldErrors}function treeifyError(error51,mapper=issue2=>issue2.message){let result={errors:[]},processError=(error52,path122=[])=>{var _a4,_b;for(let issue2 of error52.issues)if(issue2.code==="invalid_union"&&issue2.errors.length)issue2.errors.map(issues=>processError({issues},[...path122,...issue2.path]));else if(issue2.code==="invalid_key")processError({issues:issue2.issues},[...path122,...issue2.path]);else if(issue2.code==="invalid_element")processError({issues:issue2.issues},[...path122,...issue2.path]);else{let fullpath=[...path122,...issue2.path];if(fullpath.length===0){result.errors.push(mapper(issue2));continue}let curr=result,i=0;for(;i<fullpath.length;){let el=fullpath[i],terminal=i===fullpath.length-1;typeof el=="string"?(curr.properties??(curr.properties={}),(_a4=curr.properties)[el]??(_a4[el]={errors:[]}),curr=curr.properties[el]):(curr.items??(curr.items=[]),(_b=curr.items)[el]??(_b[el]={errors:[]}),curr=curr.items[el]),terminal&&curr.errors.push(mapper(issue2)),i++}}};return processError(error51),result}function toDotPath(_path){let segs=[],path122=_path.map(seg=>typeof seg=="object"?seg.key:seg);for(let seg of path122)typeof seg=="number"?segs.push(`[${seg}]`):typeof seg=="symbol"?segs.push(`[${JSON.stringify(String(seg))}]`):/[^\w$]/.test(seg)?segs.push(`[${JSON.stringify(seg)}]`):(segs.length&&segs.push("."),segs.push(seg));return segs.join("")}function prettifyError(error51){let lines3=[],issues=[...error51.issues].sort((a,b)=>(a.path??[]).length-(b.path??[]).length);for(let issue2 of issues)lines3.push(`\u2716 ${issue2.message}`),issue2.path?.length&&lines3.push(` \u2192 at ${toDotPath(issue2.path)}`);return lines3.join(`
367
367
  `)}var initializer,$ZodError,$ZodRealError,init_errors2=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/errors.js"(){init_core();init_util();initializer=(inst,def)=>{inst.name="$ZodError",Object.defineProperty(inst,"_zod",{value:inst._zod,enumerable:!1}),Object.defineProperty(inst,"issues",{value:def,enumerable:!1}),inst.message=JSON.stringify(def,jsonStringifyReplacer,2),Object.defineProperty(inst,"toString",{value:()=>inst.message,enumerable:!1})},$ZodError=$constructor("$ZodError",initializer),$ZodRealError=$constructor("$ZodError",initializer,{Parent:Error})}});var _parse,parse3,_parseAsync,parseAsync,_safeParse,safeParse,_safeParseAsync,safeParseAsync,_encode,encode,_decode,decode,_encodeAsync,encodeAsync,_decodeAsync,decodeAsync,_safeEncode,safeEncode,_safeDecode,safeDecode,_safeEncodeAsync,safeEncodeAsync,_safeDecodeAsync,safeDecodeAsync,init_parse=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/parse.js"(){init_core();init_errors2();init_util();_parse=_Err=>(schema,value,_ctx,_params)=>{let ctx=_ctx?{..._ctx,async:!1}:{async:!1},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError;if(result.issues.length){let e=new(_params?.Err??_Err)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())));throw captureStackTrace(e,_params?.callee),e}return result.value},parse3=_parse($ZodRealError),_parseAsync=_Err=>async(schema,value,_ctx,params)=>{let ctx=_ctx?{..._ctx,async:!0}:{async:!0},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise&&(result=await result),result.issues.length){let e=new(params?.Err??_Err)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())));throw captureStackTrace(e,params?.callee),e}return result.value},parseAsync=_parseAsync($ZodRealError),_safeParse=_Err=>(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!1}:{async:!1},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError;return result.issues.length?{success:!1,error:new(_Err??$ZodError)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}:{success:!0,data:result.value}},safeParse=_safeParse($ZodRealError),_safeParseAsync=_Err=>async(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!0}:{async:!0},result=schema._zod.run({value,issues:[]},ctx);return result instanceof Promise&&(result=await result),result.issues.length?{success:!1,error:new _Err(result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}:{success:!0,data:result.value}},safeParseAsync=_safeParseAsync($ZodRealError),_encode=_Err=>(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _parse(_Err)(schema,value,ctx)},encode=_encode($ZodRealError),_decode=_Err=>(schema,value,_ctx)=>_parse(_Err)(schema,value,_ctx),decode=_decode($ZodRealError),_encodeAsync=_Err=>async(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _parseAsync(_Err)(schema,value,ctx)},encodeAsync=_encodeAsync($ZodRealError),_decodeAsync=_Err=>async(schema,value,_ctx)=>_parseAsync(_Err)(schema,value,_ctx),decodeAsync=_decodeAsync($ZodRealError),_safeEncode=_Err=>(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _safeParse(_Err)(schema,value,ctx)},safeEncode=_safeEncode($ZodRealError),_safeDecode=_Err=>(schema,value,_ctx)=>_safeParse(_Err)(schema,value,_ctx),safeDecode=_safeDecode($ZodRealError),_safeEncodeAsync=_Err=>async(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _safeParseAsync(_Err)(schema,value,ctx)},safeEncodeAsync=_safeEncodeAsync($ZodRealError),_safeDecodeAsync=_Err=>async(schema,value,_ctx)=>_safeParseAsync(_Err)(schema,value,_ctx),safeDecodeAsync=_safeDecodeAsync($ZodRealError)}});var regexes_exports={};__export(regexes_exports,{base64:()=>base64,base64url:()=>base64url,bigint:()=>bigint,boolean:()=>boolean,browserEmail:()=>browserEmail,cidrv4:()=>cidrv4,cidrv6:()=>cidrv6,cuid:()=>cuid,cuid2:()=>cuid2,date:()=>date2,datetime:()=>datetime,domain:()=>domain,duration:()=>duration,e164:()=>e164,email:()=>email,emoji:()=>emoji,extendedDuration:()=>extendedDuration,guid:()=>guid,hex:()=>hex,hostname:()=>hostname,html5Email:()=>html5Email,httpProtocol:()=>httpProtocol,idnEmail:()=>idnEmail,integer:()=>integer,ipv4:()=>ipv4,ipv6:()=>ipv6,ksuid:()=>ksuid,lowercase:()=>lowercase,mac:()=>mac,md5_base64:()=>md5_base64,md5_base64url:()=>md5_base64url,md5_hex:()=>md5_hex,nanoid:()=>nanoid,null:()=>_null,number:()=>number,rfc5322Email:()=>rfc5322Email,sha1_base64:()=>sha1_base64,sha1_base64url:()=>sha1_base64url,sha1_hex:()=>sha1_hex,sha256_base64:()=>sha256_base64,sha256_base64url:()=>sha256_base64url,sha256_hex:()=>sha256_hex,sha384_base64:()=>sha384_base64,sha384_base64url:()=>sha384_base64url,sha384_hex:()=>sha384_hex,sha512_base64:()=>sha512_base64,sha512_base64url:()=>sha512_base64url,sha512_hex:()=>sha512_hex,string:()=>string,time:()=>time,ulid:()=>ulid,undefined:()=>_undefined,unicodeEmail:()=>unicodeEmail,uppercase:()=>uppercase,uuid:()=>uuid,uuid4:()=>uuid4,uuid6:()=>uuid6,uuid7:()=>uuid7,xid:()=>xid});function emoji(){return new RegExp(_emoji,"u")}function timeSource(args){let hhmm="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof args.precision=="number"?args.precision===-1?`${hhmm}`:args.precision===0?`${hhmm}:[0-5]\\d`:`${hhmm}:[0-5]\\d\\.\\d{${args.precision}}`:`${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`}function time(args){return new RegExp(`^${timeSource(args)}$`)}function datetime(args){let time3=timeSource({precision:args.precision}),opts=["Z"];args.local&&opts.push(""),args.offset&&opts.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let timeRegex=`${time3}(?:${opts.join("|")})`;return new RegExp(`^${dateSource}T(?:${timeRegex})$`)}function fixedBase64(bodyLength,padding){return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`)}function fixedBase64url(length){return new RegExp(`^[A-Za-z0-9_-]{${length}}$`)}var cuid,cuid2,ulid,xid,ksuid,nanoid,duration,extendedDuration,guid,uuid,uuid4,uuid6,uuid7,email,html5Email,rfc5322Email,unicodeEmail,idnEmail,browserEmail,_emoji,ipv4,ipv6,mac,cidrv4,cidrv6,base64,base64url,hostname,domain,httpProtocol,e164,dateSource,date2,string,bigint,integer,number,boolean,_null,_undefined,lowercase,uppercase,hex,md5_hex,md5_base64,md5_base64url,sha1_hex,sha1_base64,sha1_base64url,sha256_hex,sha256_base64,sha256_base64url,sha384_hex,sha384_base64,sha384_base64url,sha512_hex,sha512_base64,sha512_base64url,init_regexes=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/regexes.js"(){init_util();cuid=/^[cC][0-9a-z]{6,}$/,cuid2=/^[0-9a-z]+$/,ulid=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,xid=/^[0-9a-vA-V]{20}$/,ksuid=/^[A-Za-z0-9]{27}$/,nanoid=/^[a-zA-Z0-9_-]{21}$/,duration=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,extendedDuration=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,guid=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,uuid=version2=>version2?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,uuid4=uuid(4),uuid6=uuid(6),uuid7=uuid(7),email=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,html5Email=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,rfc5322Email=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,unicodeEmail=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,idnEmail=unicodeEmail,browserEmail=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,_emoji="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";ipv4=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,mac=delimiter2=>{let escapedDelim=escapeRegex2(delimiter2??":");return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`)},cidrv4=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,cidrv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,base64url=/^[A-Za-z0-9_-]*$/,hostname=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,domain=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,httpProtocol=/^https?$/,e164=/^\+[1-9]\d{6,14}$/,dateSource="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",date2=new RegExp(`^${dateSource}$`);string=params=>{let regex=params?`[\\s\\S]{${params?.minimum??0},${params?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${regex}$`)},bigint=/^-?\d+n?$/,integer=/^-?\d+$/,number=/^-?\d+(?:\.\d+)?$/,boolean=/^(?:true|false)$/i,_null=/^null$/i,_undefined=/^undefined$/i,lowercase=/^[^A-Z]*$/,uppercase=/^[^a-z]*$/,hex=/^[0-9a-fA-F]*$/;md5_hex=/^[0-9a-fA-F]{32}$/,md5_base64=fixedBase64(22,"=="),md5_base64url=fixedBase64url(22),sha1_hex=/^[0-9a-fA-F]{40}$/,sha1_base64=fixedBase64(27,"="),sha1_base64url=fixedBase64url(27),sha256_hex=/^[0-9a-fA-F]{64}$/,sha256_base64=fixedBase64(43,"="),sha256_base64url=fixedBase64url(43),sha384_hex=/^[0-9a-fA-F]{96}$/,sha384_base64=fixedBase64(64,""),sha384_base64url=fixedBase64url(64),sha512_hex=/^[0-9a-fA-F]{128}$/,sha512_base64=fixedBase64(86,"=="),sha512_base64url=fixedBase64url(86)}});function handleCheckPropertyResult(result,payload,property){result.issues.length&&payload.issues.push(...prefixIssues(property,result.issues))}var $ZodCheck,numericOriginMap,$ZodCheckLessThan,$ZodCheckGreaterThan,$ZodCheckMultipleOf,$ZodCheckNumberFormat,$ZodCheckBigIntFormat,$ZodCheckMaxSize,$ZodCheckMinSize,$ZodCheckSizeEquals,$ZodCheckMaxLength,$ZodCheckMinLength,$ZodCheckLengthEquals,$ZodCheckStringFormat,$ZodCheckRegex,$ZodCheckLowerCase,$ZodCheckUpperCase,$ZodCheckIncludes,$ZodCheckStartsWith,$ZodCheckEndsWith,$ZodCheckProperty,$ZodCheckMimeType,$ZodCheckOverwrite,init_checks=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/checks.js"(){init_core();init_regexes();init_util();$ZodCheck=$constructor("$ZodCheck",(inst,def)=>{var _a4;inst._zod??(inst._zod={}),inst._zod.def=def,(_a4=inst._zod).onattach??(_a4.onattach=[])}),numericOriginMap={number:"number",bigint:"bigint",object:"date"},$ZodCheckLessThan=$constructor("$ZodCheckLessThan",(inst,def)=>{$ZodCheck.init(inst,def);let origin=numericOriginMap[typeof def.value];inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag,curr=(def.inclusive?bag.maximum:bag.exclusiveMaximum)??Number.POSITIVE_INFINITY;def.value<curr&&(def.inclusive?bag.maximum=def.value:bag.exclusiveMaximum=def.value)}),inst._zod.check=payload=>{(def.inclusive?payload.value<=def.value:payload.value<def.value)||payload.issues.push({origin,code:"too_big",maximum:typeof def.value=="object"?def.value.getTime():def.value,input:payload.value,inclusive:def.inclusive,inst,continue:!def.abort})}}),$ZodCheckGreaterThan=$constructor("$ZodCheckGreaterThan",(inst,def)=>{$ZodCheck.init(inst,def);let origin=numericOriginMap[typeof def.value];inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag,curr=(def.inclusive?bag.minimum:bag.exclusiveMinimum)??Number.NEGATIVE_INFINITY;def.value>curr&&(def.inclusive?bag.minimum=def.value:bag.exclusiveMinimum=def.value)}),inst._zod.check=payload=>{(def.inclusive?payload.value>=def.value:payload.value>def.value)||payload.issues.push({origin,code:"too_small",minimum:typeof def.value=="object"?def.value.getTime():def.value,input:payload.value,inclusive:def.inclusive,inst,continue:!def.abort})}}),$ZodCheckMultipleOf=$constructor("$ZodCheckMultipleOf",(inst,def)=>{$ZodCheck.init(inst,def),inst._zod.onattach.push(inst2=>{var _a4;(_a4=inst2._zod.bag).multipleOf??(_a4.multipleOf=def.value)}),inst._zod.check=payload=>{if(typeof payload.value!=typeof def.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof payload.value=="bigint"?payload.value%def.value===BigInt(0):floatSafeRemainder(payload.value,def.value)===0)||payload.issues.push({origin:typeof payload.value,code:"not_multiple_of",divisor:def.value,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckNumberFormat=$constructor("$ZodCheckNumberFormat",(inst,def)=>{$ZodCheck.init(inst,def),def.format=def.format||"float64";let isInt=def.format?.includes("int"),origin=isInt?"int":"number",[minimum,maximum]=NUMBER_FORMAT_RANGES[def.format];inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.format=def.format,bag.minimum=minimum,bag.maximum=maximum,isInt&&(bag.pattern=integer)}),inst._zod.check=payload=>{let input=payload.value;if(isInt){if(!Number.isInteger(input)){payload.issues.push({expected:origin,format:def.format,code:"invalid_type",continue:!1,input,inst});return}if(!Number.isSafeInteger(input)){input>0?payload.issues.push({input,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst,origin,inclusive:!0,continue:!def.abort}):payload.issues.push({input,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst,origin,inclusive:!0,continue:!def.abort});return}}input<minimum&&payload.issues.push({origin:"number",input,code:"too_small",minimum,inclusive:!0,inst,continue:!def.abort}),input>maximum&&payload.issues.push({origin:"number",input,code:"too_big",maximum,inclusive:!0,inst,continue:!def.abort})}}),$ZodCheckBigIntFormat=$constructor("$ZodCheckBigIntFormat",(inst,def)=>{$ZodCheck.init(inst,def);let[minimum,maximum]=BIGINT_FORMAT_RANGES[def.format];inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.format=def.format,bag.minimum=minimum,bag.maximum=maximum}),inst._zod.check=payload=>{let input=payload.value;input<minimum&&payload.issues.push({origin:"bigint",input,code:"too_small",minimum,inclusive:!0,inst,continue:!def.abort}),input>maximum&&payload.issues.push({origin:"bigint",input,code:"too_big",maximum,inclusive:!0,inst,continue:!def.abort})}}),$ZodCheckMaxSize=$constructor("$ZodCheckMaxSize",(inst,def)=>{var _a4;$ZodCheck.init(inst,def),(_a4=inst._zod.def).when??(_a4.when=payload=>{let val=payload.value;return!nullish(val)&&val.size!==void 0}),inst._zod.onattach.push(inst2=>{let curr=inst2._zod.bag.maximum??Number.POSITIVE_INFINITY;def.maximum<curr&&(inst2._zod.bag.maximum=def.maximum)}),inst._zod.check=payload=>{let input=payload.value;input.size<=def.maximum||payload.issues.push({origin:getSizableOrigin(input),code:"too_big",maximum:def.maximum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckMinSize=$constructor("$ZodCheckMinSize",(inst,def)=>{var _a4;$ZodCheck.init(inst,def),(_a4=inst._zod.def).when??(_a4.when=payload=>{let val=payload.value;return!nullish(val)&&val.size!==void 0}),inst._zod.onattach.push(inst2=>{let curr=inst2._zod.bag.minimum??Number.NEGATIVE_INFINITY;def.minimum>curr&&(inst2._zod.bag.minimum=def.minimum)}),inst._zod.check=payload=>{let input=payload.value;input.size>=def.minimum||payload.issues.push({origin:getSizableOrigin(input),code:"too_small",minimum:def.minimum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckSizeEquals=$constructor("$ZodCheckSizeEquals",(inst,def)=>{var _a4;$ZodCheck.init(inst,def),(_a4=inst._zod.def).when??(_a4.when=payload=>{let val=payload.value;return!nullish(val)&&val.size!==void 0}),inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.minimum=def.size,bag.maximum=def.size,bag.size=def.size}),inst._zod.check=payload=>{let input=payload.value,size2=input.size;if(size2===def.size)return;let tooBig=size2>def.size;payload.issues.push({origin:getSizableOrigin(input),...tooBig?{code:"too_big",maximum:def.size}:{code:"too_small",minimum:def.size},inclusive:!0,exact:!0,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckMaxLength=$constructor("$ZodCheckMaxLength",(inst,def)=>{var _a4;$ZodCheck.init(inst,def),(_a4=inst._zod.def).when??(_a4.when=payload=>{let val=payload.value;return!nullish(val)&&val.length!==void 0}),inst._zod.onattach.push(inst2=>{let curr=inst2._zod.bag.maximum??Number.POSITIVE_INFINITY;def.maximum<curr&&(inst2._zod.bag.maximum=def.maximum)}),inst._zod.check=payload=>{let input=payload.value;if(input.length<=def.maximum)return;let origin=getLengthableOrigin(input);payload.issues.push({origin,code:"too_big",maximum:def.maximum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckMinLength=$constructor("$ZodCheckMinLength",(inst,def)=>{var _a4;$ZodCheck.init(inst,def),(_a4=inst._zod.def).when??(_a4.when=payload=>{let val=payload.value;return!nullish(val)&&val.length!==void 0}),inst._zod.onattach.push(inst2=>{let curr=inst2._zod.bag.minimum??Number.NEGATIVE_INFINITY;def.minimum>curr&&(inst2._zod.bag.minimum=def.minimum)}),inst._zod.check=payload=>{let input=payload.value;if(input.length>=def.minimum)return;let origin=getLengthableOrigin(input);payload.issues.push({origin,code:"too_small",minimum:def.minimum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckLengthEquals=$constructor("$ZodCheckLengthEquals",(inst,def)=>{var _a4;$ZodCheck.init(inst,def),(_a4=inst._zod.def).when??(_a4.when=payload=>{let val=payload.value;return!nullish(val)&&val.length!==void 0}),inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.minimum=def.length,bag.maximum=def.length,bag.length=def.length}),inst._zod.check=payload=>{let input=payload.value,length=input.length;if(length===def.length)return;let origin=getLengthableOrigin(input),tooBig=length>def.length;payload.issues.push({origin,...tooBig?{code:"too_big",maximum:def.length}:{code:"too_small",minimum:def.length},inclusive:!0,exact:!0,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckStringFormat=$constructor("$ZodCheckStringFormat",(inst,def)=>{var _a4,_b;$ZodCheck.init(inst,def),inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.format=def.format,def.pattern&&(bag.patterns??(bag.patterns=new Set),bag.patterns.add(def.pattern))}),def.pattern?(_a4=inst._zod).check??(_a4.check=payload=>{def.pattern.lastIndex=0,!def.pattern.test(payload.value)&&payload.issues.push({origin:"string",code:"invalid_format",format:def.format,input:payload.value,...def.pattern?{pattern:def.pattern.toString()}:{},inst,continue:!def.abort})}):(_b=inst._zod).check??(_b.check=()=>{})}),$ZodCheckRegex=$constructor("$ZodCheckRegex",(inst,def)=>{$ZodCheckStringFormat.init(inst,def),inst._zod.check=payload=>{def.pattern.lastIndex=0,!def.pattern.test(payload.value)&&payload.issues.push({origin:"string",code:"invalid_format",format:"regex",input:payload.value,pattern:def.pattern.toString(),inst,continue:!def.abort})}}),$ZodCheckLowerCase=$constructor("$ZodCheckLowerCase",(inst,def)=>{def.pattern??(def.pattern=lowercase),$ZodCheckStringFormat.init(inst,def)}),$ZodCheckUpperCase=$constructor("$ZodCheckUpperCase",(inst,def)=>{def.pattern??(def.pattern=uppercase),$ZodCheckStringFormat.init(inst,def)}),$ZodCheckIncludes=$constructor("$ZodCheckIncludes",(inst,def)=>{$ZodCheck.init(inst,def);let escapedRegex=escapeRegex2(def.includes),pattern=new RegExp(typeof def.position=="number"?`^.{${def.position}}${escapedRegex}`:escapedRegex);def.pattern=pattern,inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set),bag.patterns.add(pattern)}),inst._zod.check=payload=>{payload.value.includes(def.includes,def.position)||payload.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:def.includes,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckStartsWith=$constructor("$ZodCheckStartsWith",(inst,def)=>{$ZodCheck.init(inst,def);let pattern=new RegExp(`^${escapeRegex2(def.prefix)}.*`);def.pattern??(def.pattern=pattern),inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set),bag.patterns.add(pattern)}),inst._zod.check=payload=>{payload.value.startsWith(def.prefix)||payload.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:def.prefix,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckEndsWith=$constructor("$ZodCheckEndsWith",(inst,def)=>{$ZodCheck.init(inst,def);let pattern=new RegExp(`.*${escapeRegex2(def.suffix)}$`);def.pattern??(def.pattern=pattern),inst._zod.onattach.push(inst2=>{let bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set),bag.patterns.add(pattern)}),inst._zod.check=payload=>{payload.value.endsWith(def.suffix)||payload.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:def.suffix,input:payload.value,inst,continue:!def.abort})}});$ZodCheckProperty=$constructor("$ZodCheckProperty",(inst,def)=>{$ZodCheck.init(inst,def),inst._zod.check=payload=>{let result=def.schema._zod.run({value:payload.value[def.property],issues:[]},{});if(result instanceof Promise)return result.then(result2=>handleCheckPropertyResult(result2,payload,def.property));handleCheckPropertyResult(result,payload,def.property)}}),$ZodCheckMimeType=$constructor("$ZodCheckMimeType",(inst,def)=>{$ZodCheck.init(inst,def);let mimeSet=new Set(def.mime);inst._zod.onattach.push(inst2=>{inst2._zod.bag.mime=def.mime}),inst._zod.check=payload=>{mimeSet.has(payload.value.type)||payload.issues.push({code:"invalid_value",values:def.mime,input:payload.value.type,inst,continue:!def.abort})}}),$ZodCheckOverwrite=$constructor("$ZodCheckOverwrite",(inst,def)=>{$ZodCheck.init(inst,def),inst._zod.check=payload=>{payload.value=def.tx(payload.value)}})}});var Doc,init_doc=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/doc.js"(){Doc=class{constructor(args=[]){this.content=[],this.indent=0,this&&(this.args=args)}indented(fn){this.indent+=1,fn(this),this.indent-=1}write(arg){if(typeof arg=="function"){arg(this,{execution:"sync"}),arg(this,{execution:"async"});return}let lines3=arg.split(`
368
368
  `).filter(x2=>x2),minIndent=Math.min(...lines3.map(x2=>x2.length-x2.trimStart().length)),dedented=lines3.map(x2=>x2.slice(minIndent)).map(x2=>" ".repeat(this.indent*2)+x2);for(let line of dedented)this.content.push(line)}compile(){let F2=Function,args=this?.args,lines3=[...(this?.content??[""]).map(x2=>` ${x2}`)];return new F2(...args,lines3.join(`
369
369
  `))}}}});var version,init_versions=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/versions.js"(){version={major:4,minor:4,patch:3}}});function isValidBase64(data){if(data==="")return!0;if(/\s/.test(data)||data.length%4!==0)return!1;try{return atob(data),!0}catch{return!1}}function isValidBase64URL(data){if(!base64url.test(data))return!1;let base643=data.replace(/[-_]/g,c=>c==="-"?"+":"/"),padded=base643.padEnd(Math.ceil(base643.length/4)*4,"=");return isValidBase64(padded)}function isValidJWT(token,algorithm=null){try{let tokensParts=token.split(".");if(tokensParts.length!==3)return!1;let[header]=tokensParts;if(!header)return!1;let parsedHeader=JSON.parse(atob(header));return!("typ"in parsedHeader&&parsedHeader?.typ!=="JWT"||!parsedHeader.alg||algorithm&&(!("alg"in parsedHeader)||parsedHeader.alg!==algorithm))}catch{return!1}}function handleArrayResult(result,final,index){result.issues.length&&final.issues.push(...prefixIssues(index,result.issues)),final.value[index]=result.value}function handlePropertyResult(result,final,key,input,isOptionalIn,isOptionalOut){let isPresent=key in input;if(result.issues.length){if(isOptionalIn&&isOptionalOut&&!isPresent)return;final.issues.push(...prefixIssues(key,result.issues))}if(!isPresent&&!isOptionalIn){result.issues.length||final.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[key]});return}result.value===void 0?isPresent&&(final.value[key]=void 0):final.value[key]=result.value}function normalizeDef(def){let keys=Object.keys(def.shape);for(let k2 of keys)if(!def.shape?.[k2]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${k2}": expected a Zod schema`);let okeys=optionalKeys(def.shape);return{...def,keys,keySet:new Set(keys),numKeys:keys.length,optionalKeys:new Set(okeys)}}function handleCatchall(proms,input,payload,ctx,def,inst){let unrecognized=[],keySet=def.keySet,_catchall=def.catchall._zod,t=_catchall.def.type,isOptionalIn=_catchall.optin==="optional",isOptionalOut=_catchall.optout==="optional";for(let key in input){if(key==="__proto__"||keySet.has(key))continue;if(t==="never"){unrecognized.push(key);continue}let r=_catchall.run({value:input[key],issues:[]},ctx);r instanceof Promise?proms.push(r.then(r2=>handlePropertyResult(r2,payload,key,input,isOptionalIn,isOptionalOut))):handlePropertyResult(r,payload,key,input,isOptionalIn,isOptionalOut)}return unrecognized.length&&payload.issues.push({code:"unrecognized_keys",keys:unrecognized,input,inst}),proms.length?Promise.all(proms).then(()=>payload):payload}function handleUnionResults(results,final,inst,ctx){for(let result of results)if(result.issues.length===0)return final.value=result.value,final;let nonaborted=results.filter(r=>!aborted(r));return nonaborted.length===1?(final.value=nonaborted[0].value,nonaborted[0]):(final.issues.push({code:"invalid_union",input:final.value,inst,errors:results.map(result=>result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}),final)}function handleExclusiveUnionResults(results,final,inst,ctx){let successes=results.filter(r=>r.issues.length===0);return successes.length===1?(final.value=successes[0].value,final):(successes.length===0?final.issues.push({code:"invalid_union",input:final.value,inst,errors:results.map(result=>result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}):final.issues.push({code:"invalid_union",input:final.value,inst,errors:[],inclusive:!1}),final)}function mergeValues(a,b){if(a===b)return{valid:!0,data:a};if(a instanceof Date&&b instanceof Date&&+a==+b)return{valid:!0,data:a};if(isPlainObject(a)&&isPlainObject(b)){let bKeys=Object.keys(b),sharedKeys=Object.keys(a).filter(key=>bKeys.indexOf(key)!==-1),newObj={...a,...b};for(let key of sharedKeys){let sharedValue=mergeValues(a[key],b[key]);if(!sharedValue.valid)return{valid:!1,mergeErrorPath:[key,...sharedValue.mergeErrorPath]};newObj[key]=sharedValue.data}return{valid:!0,data:newObj}}if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)return{valid:!1,mergeErrorPath:[]};let newArray=[];for(let index=0;index<a.length;index++){let itemA=a[index],itemB=b[index],sharedValue=mergeValues(itemA,itemB);if(!sharedValue.valid)return{valid:!1,mergeErrorPath:[index,...sharedValue.mergeErrorPath]};newArray.push(sharedValue.data)}return{valid:!0,data:newArray}}return{valid:!1,mergeErrorPath:[]}}function handleIntersectionResults(result,left,right){let unrecKeys=new Map,unrecIssue;for(let iss of left.issues)if(iss.code==="unrecognized_keys"){unrecIssue??(unrecIssue=iss);for(let k2 of iss.keys)unrecKeys.has(k2)||unrecKeys.set(k2,{}),unrecKeys.get(k2).l=!0}else result.issues.push(iss);for(let iss of right.issues)if(iss.code==="unrecognized_keys")for(let k2 of iss.keys)unrecKeys.has(k2)||unrecKeys.set(k2,{}),unrecKeys.get(k2).r=!0;else result.issues.push(iss);let bothKeys=[...unrecKeys].filter(([,f])=>f.l&&f.r).map(([k2])=>k2);if(bothKeys.length&&unrecIssue&&result.issues.push({...unrecIssue,keys:bothKeys}),aborted(result))return result;let merged=mergeValues(left.value,right.value);if(!merged.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);return result.value=merged.data,result}function getTupleOptStart(items2,key){for(let i=items2.length-1;i>=0;i--)if(items2[i]._zod[key]!=="optional")return i+1;return 0}function handleTupleResult(result,final,index){result.issues.length&&final.issues.push(...prefixIssues(index,result.issues)),final.value[index]=result.value}function handleTupleResults(itemResults,final,items2,input,optoutStart){for(let i=0;i<items2.length;i++){let r=itemResults[i],isPresent=i<input.length;if(r.issues.length){if(!isPresent&&i>=optoutStart){final.value.length=i;break}final.issues.push(...prefixIssues(i,r.issues))}final.value[i]=r.value}for(let i=final.value.length-1;i>=input.length&&(items2[i]._zod.optout==="optional"&&final.value[i]===void 0);i--)final.value.length=i;return final}function handleMapResult(keyResult,valueResult,final,key,input,inst,ctx){keyResult.issues.length&&(propertyKeyTypes.has(typeof key)?final.issues.push(...prefixIssues(key,keyResult.issues)):final.issues.push({code:"invalid_key",origin:"map",input,inst,issues:keyResult.issues.map(iss=>finalizeIssue(iss,ctx,config()))})),valueResult.issues.length&&(propertyKeyTypes.has(typeof key)?final.issues.push(...prefixIssues(key,valueResult.issues)):final.issues.push({origin:"map",code:"invalid_element",input,inst,key,issues:valueResult.issues.map(iss=>finalizeIssue(iss,ctx,config()))})),final.value.set(keyResult.value,valueResult.value)}function handleSetResult(result,final){result.issues.length&&final.issues.push(...result.issues),final.value.add(result.value)}function handleOptionalResult(result,input){return input===void 0&&(result.issues.length||result.fallback)?{issues:[],value:void 0}:result}function handleDefaultResult(payload,def){return payload.value===void 0&&(payload.value=def.defaultValue),payload}function handleNonOptionalResult(payload,inst){return!payload.issues.length&&payload.value===void 0&&payload.issues.push({code:"invalid_type",expected:"nonoptional",input:payload.value,inst}),payload}function handlePipeResult(left,next,ctx){return left.issues.length?(left.aborted=!0,left):next._zod.run({value:left.value,issues:left.issues,fallback:left.fallback},ctx)}function handleCodecAResult(result,def,ctx){if(result.issues.length)return result.aborted=!0,result;if((ctx.direction||"forward")==="forward"){let transformed=def.transform(result.value,result);return transformed instanceof Promise?transformed.then(value=>handleCodecTxResult(result,value,def.out,ctx)):handleCodecTxResult(result,transformed,def.out,ctx)}else{let transformed=def.reverseTransform(result.value,result);return transformed instanceof Promise?transformed.then(value=>handleCodecTxResult(result,value,def.in,ctx)):handleCodecTxResult(result,transformed,def.in,ctx)}}function handleCodecTxResult(left,value,nextSchema,ctx){return left.issues.length?(left.aborted=!0,left):nextSchema._zod.run({value,issues:left.issues},ctx)}function handleReadonlyResult(payload){return payload.value=Object.freeze(payload.value),payload}function handleRefineResult(result,payload,input,inst){if(!result){let _iss={code:"custom",input,inst,path:[...inst._zod.def.path??[]],continue:!inst._zod.def.abort};inst._zod.def.params&&(_iss.params=inst._zod.def.params),payload.issues.push(issue(_iss))}}var $ZodType,$ZodString,$ZodStringFormat,$ZodGUID,$ZodUUID,$ZodEmail,$ZodURL,$ZodEmoji,$ZodNanoID,$ZodCUID,$ZodCUID2,$ZodULID,$ZodXID,$ZodKSUID,$ZodISODateTime,$ZodISODate,$ZodISOTime,$ZodISODuration,$ZodIPv4,$ZodIPv6,$ZodMAC,$ZodCIDRv4,$ZodCIDRv6,$ZodBase64,$ZodBase64URL,$ZodE164,$ZodJWT,$ZodCustomStringFormat,$ZodNumber,$ZodNumberFormat,$ZodBoolean,$ZodBigInt,$ZodBigIntFormat,$ZodSymbol,$ZodUndefined,$ZodNull,$ZodAny,$ZodUnknown,$ZodNever,$ZodVoid,$ZodDate,$ZodArray,$ZodObject,$ZodObjectJIT,$ZodUnion,$ZodXor,$ZodDiscriminatedUnion,$ZodIntersection,$ZodTuple,$ZodRecord,$ZodMap,$ZodSet,$ZodEnum,$ZodLiteral,$ZodFile,$ZodTransform,$ZodOptional,$ZodExactOptional,$ZodNullable,$ZodDefault,$ZodPrefault,$ZodNonOptional,$ZodSuccess,$ZodCatch,$ZodNaN,$ZodPipe,$ZodCodec,$ZodPreprocess,$ZodReadonly,$ZodTemplateLiteral,$ZodFunction,$ZodPromise,$ZodLazy,$ZodCustom,init_schemas=__esm({"../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/schemas.js"(){init_checks();init_core();init_doc();init_parse();init_regexes();init_util();init_versions();init_util();$ZodType=$constructor("$ZodType",(inst,def)=>{var _a4;inst??(inst={}),inst._zod.def=def,inst._zod.bag=inst._zod.bag||{},inst._zod.version=version;let checks=[...inst._zod.def.checks??[]];inst._zod.traits.has("$ZodCheck")&&checks.unshift(inst);for(let ch of checks)for(let fn of ch._zod.onattach)fn(inst);if(checks.length===0)(_a4=inst._zod).deferred??(_a4.deferred=[]),inst._zod.deferred?.push(()=>{inst._zod.run=inst._zod.parse});else{let runChecks=(payload,checks2,ctx)=>{let isAborted=aborted(payload),asyncResult;for(let ch of checks2){if(ch._zod.def.when){if(explicitlyAborted(payload)||!ch._zod.def.when(payload))continue}else if(isAborted)continue;let currLen=payload.issues.length,_2=ch._zod.check(payload);if(_2 instanceof Promise&&ctx?.async===!1)throw new $ZodAsyncError;if(asyncResult||_2 instanceof Promise)asyncResult=(asyncResult??Promise.resolve()).then(async()=>{await _2,payload.issues.length!==currLen&&(isAborted||(isAborted=aborted(payload,currLen)))});else{if(payload.issues.length===currLen)continue;isAborted||(isAborted=aborted(payload,currLen))}}return asyncResult?asyncResult.then(()=>payload):payload},handleCanaryResult=(canary,payload,ctx)=>{if(aborted(canary))return canary.aborted=!0,canary;let checkResult=runChecks(payload,checks,ctx);if(checkResult instanceof Promise){if(ctx.async===!1)throw new $ZodAsyncError;return checkResult.then(checkResult2=>inst._zod.parse(checkResult2,ctx))}return inst._zod.parse(checkResult,ctx)};inst._zod.run=(payload,ctx)=>{if(ctx.skipChecks)return inst._zod.parse(payload,ctx);if(ctx.direction==="backward"){let canary=inst._zod.parse({value:payload.value,issues:[]},{...ctx,skipChecks:!0});return canary instanceof Promise?canary.then(canary2=>handleCanaryResult(canary2,payload,ctx)):handleCanaryResult(canary,payload,ctx)}let result=inst._zod.parse(payload,ctx);if(result instanceof Promise){if(ctx.async===!1)throw new $ZodAsyncError;return result.then(result2=>runChecks(result2,checks,ctx))}return runChecks(result,checks,ctx)}}defineLazy(inst,"~standard",()=>({validate:value=>{try{let r=safeParse(inst,value);return r.success?{value:r.data}:{issues:r.error?.issues}}catch{return safeParseAsync(inst,value).then(r=>r.success?{value:r.data}:{issues:r.error?.issues})}},vendor:"zod",version:1}))}),$ZodString=$constructor("$ZodString",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=[...inst?._zod.bag?.patterns??[]].pop()??string(inst._zod.bag),inst._zod.parse=(payload,_2)=>{if(def.coerce)try{payload.value=String(payload.value)}catch{}return typeof payload.value=="string"||payload.issues.push({expected:"string",code:"invalid_type",input:payload.value,inst}),payload}}),$ZodStringFormat=$constructor("$ZodStringFormat",(inst,def)=>{$ZodCheckStringFormat.init(inst,def),$ZodString.init(inst,def)}),$ZodGUID=$constructor("$ZodGUID",(inst,def)=>{def.pattern??(def.pattern=guid),$ZodStringFormat.init(inst,def)}),$ZodUUID=$constructor("$ZodUUID",(inst,def)=>{if(def.version){let v2={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[def.version];if(v2===void 0)throw new Error(`Invalid UUID version: "${def.version}"`);def.pattern??(def.pattern=uuid(v2))}else def.pattern??(def.pattern=uuid());$ZodStringFormat.init(inst,def)}),$ZodEmail=$constructor("$ZodEmail",(inst,def)=>{def.pattern??(def.pattern=email),$ZodStringFormat.init(inst,def)}),$ZodURL=$constructor("$ZodURL",(inst,def)=>{$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{try{let trimmed=payload.value.trim();if(!def.normalize&&def.protocol?.source===httpProtocol.source&&!/^https?:\/\//i.test(trimmed)){payload.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:payload.value,inst,continue:!def.abort});return}let url2=new URL(trimmed);def.hostname&&(def.hostname.lastIndex=0,def.hostname.test(url2.hostname)||payload.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:def.hostname.source,input:payload.value,inst,continue:!def.abort})),def.protocol&&(def.protocol.lastIndex=0,def.protocol.test(url2.protocol.endsWith(":")?url2.protocol.slice(0,-1):url2.protocol)||payload.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:def.protocol.source,input:payload.value,inst,continue:!def.abort})),def.normalize?payload.value=url2.href:payload.value=trimmed;return}catch{payload.issues.push({code:"invalid_format",format:"url",input:payload.value,inst,continue:!def.abort})}}}),$ZodEmoji=$constructor("$ZodEmoji",(inst,def)=>{def.pattern??(def.pattern=emoji()),$ZodStringFormat.init(inst,def)}),$ZodNanoID=$constructor("$ZodNanoID",(inst,def)=>{def.pattern??(def.pattern=nanoid),$ZodStringFormat.init(inst,def)}),$ZodCUID=$constructor("$ZodCUID",(inst,def)=>{def.pattern??(def.pattern=cuid),$ZodStringFormat.init(inst,def)}),$ZodCUID2=$constructor("$ZodCUID2",(inst,def)=>{def.pattern??(def.pattern=cuid2),$ZodStringFormat.init(inst,def)}),$ZodULID=$constructor("$ZodULID",(inst,def)=>{def.pattern??(def.pattern=ulid),$ZodStringFormat.init(inst,def)}),$ZodXID=$constructor("$ZodXID",(inst,def)=>{def.pattern??(def.pattern=xid),$ZodStringFormat.init(inst,def)}),$ZodKSUID=$constructor("$ZodKSUID",(inst,def)=>{def.pattern??(def.pattern=ksuid),$ZodStringFormat.init(inst,def)}),$ZodISODateTime=$constructor("$ZodISODateTime",(inst,def)=>{def.pattern??(def.pattern=datetime(def)),$ZodStringFormat.init(inst,def)}),$ZodISODate=$constructor("$ZodISODate",(inst,def)=>{def.pattern??(def.pattern=date2),$ZodStringFormat.init(inst,def)}),$ZodISOTime=$constructor("$ZodISOTime",(inst,def)=>{def.pattern??(def.pattern=time(def)),$ZodStringFormat.init(inst,def)}),$ZodISODuration=$constructor("$ZodISODuration",(inst,def)=>{def.pattern??(def.pattern=duration),$ZodStringFormat.init(inst,def)}),$ZodIPv4=$constructor("$ZodIPv4",(inst,def)=>{def.pattern??(def.pattern=ipv4),$ZodStringFormat.init(inst,def),inst._zod.bag.format="ipv4"}),$ZodIPv6=$constructor("$ZodIPv6",(inst,def)=>{def.pattern??(def.pattern=ipv6),$ZodStringFormat.init(inst,def),inst._zod.bag.format="ipv6",inst._zod.check=payload=>{try{new URL(`http://[${payload.value}]`)}catch{payload.issues.push({code:"invalid_format",format:"ipv6",input:payload.value,inst,continue:!def.abort})}}}),$ZodMAC=$constructor("$ZodMAC",(inst,def)=>{def.pattern??(def.pattern=mac(def.delimiter)),$ZodStringFormat.init(inst,def),inst._zod.bag.format="mac"}),$ZodCIDRv4=$constructor("$ZodCIDRv4",(inst,def)=>{def.pattern??(def.pattern=cidrv4),$ZodStringFormat.init(inst,def)}),$ZodCIDRv6=$constructor("$ZodCIDRv6",(inst,def)=>{def.pattern??(def.pattern=cidrv6),$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{let parts=payload.value.split("/");try{if(parts.length!==2)throw new Error;let[address,prefix]=parts;if(!prefix)throw new Error;let prefixNum=Number(prefix);if(`${prefixNum}`!==prefix)throw new Error;if(prefixNum<0||prefixNum>128)throw new Error;new URL(`http://[${address}]`)}catch{payload.issues.push({code:"invalid_format",format:"cidrv6",input:payload.value,inst,continue:!def.abort})}}});$ZodBase64=$constructor("$ZodBase64",(inst,def)=>{def.pattern??(def.pattern=base64),$ZodStringFormat.init(inst,def),inst._zod.bag.contentEncoding="base64",inst._zod.check=payload=>{isValidBase64(payload.value)||payload.issues.push({code:"invalid_format",format:"base64",input:payload.value,inst,continue:!def.abort})}});$ZodBase64URL=$constructor("$ZodBase64URL",(inst,def)=>{def.pattern??(def.pattern=base64url),$ZodStringFormat.init(inst,def),inst._zod.bag.contentEncoding="base64url",inst._zod.check=payload=>{isValidBase64URL(payload.value)||payload.issues.push({code:"invalid_format",format:"base64url",input:payload.value,inst,continue:!def.abort})}}),$ZodE164=$constructor("$ZodE164",(inst,def)=>{def.pattern??(def.pattern=e164),$ZodStringFormat.init(inst,def)});$ZodJWT=$constructor("$ZodJWT",(inst,def)=>{$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{isValidJWT(payload.value,def.alg)||payload.issues.push({code:"invalid_format",format:"jwt",input:payload.value,inst,continue:!def.abort})}}),$ZodCustomStringFormat=$constructor("$ZodCustomStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{def.fn(payload.value)||payload.issues.push({code:"invalid_format",format:def.format,input:payload.value,inst,continue:!def.abort})}}),$ZodNumber=$constructor("$ZodNumber",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=inst._zod.bag.pattern??number,inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=Number(payload.value)}catch{}let input=payload.value;if(typeof input=="number"&&!Number.isNaN(input)&&Number.isFinite(input))return payload;let received=typeof input=="number"?Number.isNaN(input)?"NaN":Number.isFinite(input)?void 0:"Infinity":void 0;return payload.issues.push({expected:"number",code:"invalid_type",input,inst,...received?{received}:{}}),payload}}),$ZodNumberFormat=$constructor("$ZodNumberFormat",(inst,def)=>{$ZodCheckNumberFormat.init(inst,def),$ZodNumber.init(inst,def)}),$ZodBoolean=$constructor("$ZodBoolean",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=boolean,inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=!!payload.value}catch{}let input=payload.value;return typeof input=="boolean"||payload.issues.push({expected:"boolean",code:"invalid_type",input,inst}),payload}}),$ZodBigInt=$constructor("$ZodBigInt",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=bigint,inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=BigInt(payload.value)}catch{}return typeof payload.value=="bigint"||payload.issues.push({expected:"bigint",code:"invalid_type",input:payload.value,inst}),payload}}),$ZodBigIntFormat=$constructor("$ZodBigIntFormat",(inst,def)=>{$ZodCheckBigIntFormat.init(inst,def),$ZodBigInt.init(inst,def)}),$ZodSymbol=$constructor("$ZodSymbol",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;return typeof input=="symbol"||payload.issues.push({expected:"symbol",code:"invalid_type",input,inst}),payload}}),$ZodUndefined=$constructor("$ZodUndefined",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=_undefined,inst._zod.values=new Set([void 0]),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;return typeof input>"u"||payload.issues.push({expected:"undefined",code:"invalid_type",input,inst}),payload}}),$ZodNull=$constructor("$ZodNull",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=_null,inst._zod.values=new Set([null]),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;return input===null||payload.issues.push({expected:"null",code:"invalid_type",input,inst}),payload}}),$ZodAny=$constructor("$ZodAny",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=payload=>payload}),$ZodUnknown=$constructor("$ZodUnknown",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=payload=>payload}),$ZodNever=$constructor("$ZodNever",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,_ctx)=>(payload.issues.push({expected:"never",code:"invalid_type",input:payload.value,inst}),payload)}),$ZodVoid=$constructor("$ZodVoid",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;return typeof input>"u"||payload.issues.push({expected:"void",code:"invalid_type",input,inst}),payload}}),$ZodDate=$constructor("$ZodDate",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=new Date(payload.value)}catch{}let input=payload.value,isDate=input instanceof Date;return isDate&&!Number.isNaN(input.getTime())||payload.issues.push({expected:"date",code:"invalid_type",input,...isDate?{received:"Invalid Date"}:{},inst}),payload}});$ZodArray=$constructor("$ZodArray",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!Array.isArray(input))return payload.issues.push({expected:"array",code:"invalid_type",input,inst}),payload;payload.value=Array(input.length);let proms=[];for(let i=0;i<input.length;i++){let item=input[i],result=def.element._zod.run({value:item,issues:[]},ctx);result instanceof Promise?proms.push(result.then(result2=>handleArrayResult(result2,payload,i))):handleArrayResult(result,payload,i)}return proms.length?Promise.all(proms).then(()=>payload):payload}});$ZodObject=$constructor("$ZodObject",(inst,def)=>{if($ZodType.init(inst,def),!Object.getOwnPropertyDescriptor(def,"shape")?.get){let sh=def.shape;Object.defineProperty(def,"shape",{get:()=>{let newSh={...sh};return Object.defineProperty(def,"shape",{value:newSh}),newSh}})}let _normalized=cached(()=>normalizeDef(def));defineLazy(inst._zod,"propValues",()=>{let shape=def.shape,propValues={};for(let key in shape){let field=shape[key]._zod;if(field.values){propValues[key]??(propValues[key]=new Set);for(let v2 of field.values)propValues[key].add(v2)}}return propValues});let isObject5=isObject3,catchall=def.catchall,value;inst._zod.parse=(payload,ctx)=>{value??(value=_normalized.value);let input=payload.value;if(!isObject5(input))return payload.issues.push({expected:"object",code:"invalid_type",input,inst}),payload;payload.value={};let proms=[],shape=value.shape;for(let key of value.keys){let el=shape[key],isOptionalIn=el._zod.optin==="optional",isOptionalOut=el._zod.optout==="optional",r=el._zod.run({value:input[key],issues:[]},ctx);r instanceof Promise?proms.push(r.then(r2=>handlePropertyResult(r2,payload,key,input,isOptionalIn,isOptionalOut))):handlePropertyResult(r,payload,key,input,isOptionalIn,isOptionalOut)}return catchall?handleCatchall(proms,input,payload,ctx,_normalized.value,inst):proms.length?Promise.all(proms).then(()=>payload):payload}}),$ZodObjectJIT=$constructor("$ZodObjectJIT",(inst,def)=>{$ZodObject.init(inst,def);let superParse=inst._zod.parse,_normalized=cached(()=>normalizeDef(def)),generateFastpass=shape=>{let doc=new Doc(["shape","payload","ctx"]),normalized=_normalized.value,parseStr=key=>{let k2=esc(key);return`shape[${k2}]._zod.run({ value: input[${k2}], issues: [] }, ctx)`};doc.write("const input = payload.value;");let ids=Object.create(null),counter=0;for(let key of normalized.keys)ids[key]=`key_${counter++}`;doc.write("const newResult = {};");for(let key of normalized.keys){let id=ids[key],k2=esc(key),schema=shape[key],isOptionalIn=schema?._zod?.optin==="optional",isOptionalOut=schema?._zod?.optout==="optional";doc.write(`const ${id} = ${parseStr(key)};`),isOptionalIn&&isOptionalOut?doc.write(`
@@ -439,7 +439,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
439
439
  A manifest is written as ${MANIFEST_EXTENSIONS.join(", ")}. Manifests are never JavaScript, because a manifest is data that sous reads, validates and browses without executing anything, including before the repository is trusted.`)}function isFile3(candidate){try{return fs14.statSync(candidate).isFile()}catch{return!1}}function findManifest(directory,baseName2,label){let found=[];for(let extension of MANIFEST_EXTENSIONS){let candidate=path20.join(directory,`${baseName2}${extension}`);isFile3(candidate)&&found.push(candidate)}if(found.length>1){let names2=found.map(entry=>path20.basename(entry)).join(", ");throw new ConfigError20(`Found more than one ${label} in ${directory}: ${names2}.
440
440
  A directory holds exactly one ${label}. Remove the copies you do not want, so it is never ambiguous which one sous reads.`)}return found[0]}function missingRepoManifestMessage(repoRoot){return`No repo manifest in ${repoRoot}.
441
441
  A sous repository declares itself with a '${REPO_MANIFEST_BASENAME}${MANIFEST_EXTENSIONS[0]}' file at its root.`}function missingRecipeManifestMessage(recipeDir){return`No recipe manifest in ${recipeDir}.
442
- Every directory listed under 'recipes' in a repo manifest holds a '${RECIPE_MANIFEST_BASENAME}${MANIFEST_EXTENSIONS[0]}' file.`}function createManifests(deps={}){let baseName2=kind=>kind==="recipe"?RECIPE_MANIFEST_BASENAME:REPO_MANIFEST_BASENAME,label=kind=>kind==="recipe"?"recipe manifest":"repo manifest",find2=(directory,kind)=>findManifest(directory,baseName2(kind),label(kind));async function read(directory,kind,parse6){let file2=find2(directory,kind);if(file2!==void 0)return{path:file2,manifest:parse6(await readManifestFile(file2),file2)}}let readRecipe2=directory=>read(directory,"recipe",(value,source)=>parseRecipeManifest(value,source,deps.checkRef)),readRepo=directory=>read(directory,"repo",(value,source)=>parseRepoManifest(value,source));async function require_(directory,kind,reader){let found=await reader(directory);if(found!==void 0)return found;let message2=kind==="recipe"?missingRecipeManifestMessage(directory):missingRepoManifestMessage(directory);throw new NotFoundError4(label(kind),directory,message2)}return{find:find2,readRecipe:readRecipe2,readRepo,requireRecipe:directory=>require_(directory,"recipe",readRecipe2),requireRepo:directory=>require_(directory,"repo",readRepo),parseText:(text,fileName)=>parseManifestText(text,fileName),readFile:filePath=>readManifestFile(filePath)}}function parseManifestText(text,fileName){let extension=path20.extname(fileName).toLowerCase();if(extension===".yaml"||extension===".yml")return parseYamlText2(text,fileName);if(extension===".json"||extension===".jsonc")return parseJsoncText2(text,fileName);throw notAManifestFormat(fileName,extension)}async function readManifestFile(filePath){let text;try{text=await fsPromises.readFile(filePath,"utf8")}catch(error51){throw unreadable(filePath,"manifest",error51)}return parseManifestText(text,filePath)}var import_yaml5,init_manifests=__esm({"../sous-plugin-formats/src/manifests.ts"(){"use strict";import_yaml5=__toESM(require_dist(),1);init_main();init_common();init_recipe_manifest();init_repo_manifest()}});function namespaceOfKey(key){let slash=key.indexOf("/");return slash===-1?key:key.slice(0,slash)}var indexDependencySchema,indexVersionSchema,indexRecipeSchema,indexReplacementSchema,indexRetiredRecipeSchema,indexNamespaceSchema,indexFileSchema,init_index_file=__esm({"../sous-plugin-formats/src/formats/index-file.ts"(){"use strict";init_zod();init_common();init_variable_definition();indexDependencySchema=forwardCompatibleObject({version:semverVersionSchema.optional(),range:semverRangeSchema.optional(),repo:repoIdentitySchema.optional(),declared:external_exports.string().min(1,"must not be empty").optional(),kind:dependencyKindSchema.optional()}).refine(entry=>entry.version!==void 0||entry.range!==void 0,{message:"must record the range this dependency may take, or the exact version an older release resolved it to"}),indexVersionSchema=forwardCompatibleObject({hash:contentHashSchema,tag:external_exports.string().min(1,"must not be empty"),prerelease:external_exports.boolean(),seeded:external_exports.boolean().optional(),releasedAt:isoTimestampSchema.optional(),dependencies:external_exports.record(recipeKeySchema,indexDependencySchema).optional(),variables:external_exports.array(publishedVariableDefinitionSchema).optional(),depends:external_exports.array(external_exports.string().min(1,"must not be empty")).optional(),subscribes:external_exports.array(external_exports.string().min(1,"must not be empty")).optional()}),indexRecipeSchema=forwardCompatibleObject({path:relativePathSchema("a recipe path"),description:external_exports.string().optional(),versions:external_exports.record(semverVersionSchema,indexVersionSchema).refine(versions=>Object.keys(versions).length>0,{message:"must list at least one published version"})}),indexReplacementSchema=forwardCompatibleObject({key:recipeKeySchema,repo:repoIdentitySchema.optional(),declared:external_exports.string().min(1,"must not be empty")}),indexRetiredRecipeSchema=forwardCompatibleObject({path:relativePathSchema("a recipe path"),description:external_exports.string().optional(),replacements:external_exports.array(indexReplacementSchema).optional(),versions:external_exports.record(semverVersionSchema,indexVersionSchema).refine(versions=>Object.keys(versions).length>0,{message:"must list at least one published version"})}),indexNamespaceSchema=forwardCompatibleObject({description:external_exports.string().optional()}),indexFileSchema=forwardCompatibleObject({$comment:external_exports.string().optional(),formatVersion:formatVersionSchema,name:repoNameSchema,generatedAt:isoTimestampSchema,generator:semverVersionSchema,namespaces:external_exports.record(namespaceNameSchema,indexNamespaceSchema),recipes:external_exports.record(recipeKeySchema,indexRecipeSchema),retired:external_exports.record(recipeKeySchema,indexRetiredRecipeSchema).optional()}).superRefine((index,ctx)=>{for(let key of Object.keys(index.recipes)){let namespace=namespaceOfKey(key);Object.hasOwn(index.namespaces,namespace)||ctx.addIssue({code:"custom",path:["recipes",key],message:`belongs to the namespace '${namespace}', which this index does not declare under 'namespaces'`})}let sections=[["recipes",index.recipes],["retired",index.retired??{}]];for(let[section2,entries]of sections)for(let[key,recipe]of Object.entries(entries))for(let[version2,published]of Object.entries(recipe.versions)){let expected=`${key}@${version2}`;published.tag!==expected&&ctx.addIssue({code:"custom",path:[section2,key,"versions",version2,"tag"],message:`is '${published.tag}', but a published version's tag names the recipe and the version it carries, so this one must be '${expected}'`})}for(let key of Object.keys(index.retired??{}))Object.hasOwn(index.recipes,key)&&ctx.addIssue({code:"custom",path:["retired",key],message:"is also listed under 'recipes'; a recipe is either published or retired"})})}});function createEmptyLinksMap(){return{formatVersion:1,links:{}}}var LINK_ORIGINS,repoLinkSchema,linksMapSchema,init_links_map=__esm({"../sous-plugin-formats/src/formats/links-map.ts"(){"use strict";init_zod();init_common();LINK_ORIGINS=["clone","path"],repoLinkSchema=external_exports.strictObject({path:absolutePathSchema,linkedAt:isoTimestampSchema,origin:external_exports.enum(LINK_ORIGINS)}),linksMapSchema=external_exports.strictObject({formatVersion:formatVersionSchema,links:external_exports.record(repoNameSchema,repoLinkSchema)})}});function createEmptyLockfile(){return{formatVersion:1,repos:{},recipes:{}}}var LOCK_KINDS,lockedRepoSchema,lockedPinSchema,lockedRecipeSchema,lockfileSchema,init_lockfile=__esm({"../sous-plugin-formats/src/formats/lockfile.ts"(){"use strict";init_zod();init_common();LOCK_KINDS=DEPENDENCY_KINDS,lockedRepoSchema=external_exports.strictObject({url:repoUrlSchema,identity:repoIdentitySchema.optional(),indexHash:contentHashSchema.optional()}),lockedPinSchema=external_exports.strictObject({version:semverVersionSchema,hash:contentHashSchema}),lockedRecipeSchema=external_exports.strictObject({repo:repoNameSchema,version:semverVersionSchema,hash:contentHashSchema,requestedBy:external_exports.array(external_exports.string().min(1,"must not be empty")).min(1,"must name at least one holder"),kind:external_exports.enum(LOCK_KINDS),pins:external_exports.record(recipeKeySchema,lockedPinSchema).optional()}),lockfileSchema=external_exports.strictObject({formatVersion:formatVersionSchema,repos:external_exports.record(repoNameSchema,lockedRepoSchema),recipes:external_exports.record(recipeKeySchema,lockedRecipeSchema),migratedVersion:semverVersionSchema.optional()}).superRefine((lock,ctx)=>{for(let[key,entry]of Object.entries(lock.recipes)){Object.hasOwn(lock.repos,entry.repo)||ctx.addIssue({code:"custom",path:["recipes",key,"repo"],message:`names the repo '${entry.repo}', which this lockfile does not describe under 'repos'`});for(let holder of Object.keys(entry.pins??{}))entry.requestedBy.includes(holder)||ctx.addIssue({code:"custom",path:["recipes",key,"pins",holder],message:`pins a version for '${holder}', which is not listed in 'requestedBy'`})}})}});var storeEntrySchema,init_store_entry=__esm({"../sous-plugin-formats/src/formats/store-entry.ts"(){"use strict";init_zod();init_common();storeEntrySchema=external_exports.strictObject({formatVersion:formatVersionSchema,repo:repoIdentitySchema,namespace:namespaceNameSchema,name:recipeNameSchema,version:semverVersionSchema,hash:contentHashSchema,fetchedAt:isoTimestampSchema,lastAccessAt:isoTimestampSchema,sizeBytes:byteCountSchema,statFingerprint:external_exports.string().min(1).optional()})}});function readOnly(label,schema,fileName){return{label,...fileName===void 0?{}:{fileName},parse:(value,sourceLabel2)=>parseFormat(schema,value,sourceLabel2,label),check:(value,sourceLabel2)=>{let result=checkFormat(schema,value);return result.issues===void 0?{value:result.value}:{issues:[`Invalid ${label} at ${sourceLabel2}:`,...result.issues]}}}}function writable(label,schema,fileName,empty){return{...readOnly(label,schema,fileName),stringify:stableJsonStringify,empty}}function createRecipeManifestFormat(checkRef){return readOnly("recipe manifest",createRecipeManifestSchema(checkRef))}var lockfileFormat,linksMapFormat,indexFileFormat,storeEntryFormat,repoManifestFormat,variableDefinitionFormat,init_parsers=__esm({"../sous-plugin-formats/src/parsers.ts"(){"use strict";init_common();init_index_file();init_links_map();init_lockfile();init_recipe_manifest();init_repo_manifest();init_store_entry();init_variable_definition();init_common();lockfileFormat=writable("lockfile",lockfileSchema,LOCKFILE_FILENAME,createEmptyLockfile),linksMapFormat=writable("links map",linksMapSchema,LINKS_FILENAME,createEmptyLinksMap),indexFileFormat=writable("index file",indexFileSchema,INDEX_FILENAME,()=>({formatVersion:1,name:"",generatedAt:new Date(0).toISOString(),generator:"",namespaces:{},recipes:{}})),storeEntryFormat=writable("store entry",storeEntrySchema,STORE_ENTRY_FILENAME,()=>({formatVersion:1,repo:"",namespace:"",name:"",version:"",hash:`sha256-${"0".repeat(64)}`,fetchedAt:new Date(0).toISOString(),lastAccessAt:new Date(0).toISOString(),sizeBytes:0})),repoManifestFormat=readOnly("repo manifest",repoManifestSchema),variableDefinitionFormat=readOnly("variable definition",variableDefinitionSchema)}});import{createHash as createHash3}from"node:crypto";import fsSync from"node:fs";import fs15 from"node:fs/promises";import path21 from"node:path";async function collectFiles(dir,prefix=""){let entries=await fs15.readdir(dir,{withFileTypes:!0}),found=[];for(let entry of entries){if(entry.name===GIT_DIR_NAME||entry.name===STORE_ENTRY_FILENAME||entry.isSymbolicLink())continue;let relative4=prefix.length>0?`${prefix}/${entry.name}`:entry.name,absolute=path21.join(dir,entry.name);entry.isDirectory()?found.push(...await collectFiles(absolute,relative4)):entry.isFile()&&found.push(relative4)}return found}function bytewiseCompare(a,b){return a<b?-1:a>b?1:0}async function hashDirectory(dir){let root=path21.resolve(dir),files=(await collectFiles(root)).sort(bytewiseCompare),hash2=createHash3("sha256");for(let relative4 of files)updateWithFile(hash2,relative4,await fs15.readFile(path21.join(root,...relative4.split("/"))));return`sha256-${hash2.digest("hex")}`}function hashDirectorySync(dir){let root=path21.resolve(dir),files=collectFilesSync(root).sort(bytewiseCompare),hash2=createHash3("sha256");for(let relative4 of files)updateWithFile(hash2,relative4,fsSync.readFileSync(path21.join(root,...relative4.split("/"))));return`sha256-${hash2.digest("hex")}`}function collectFilesSync(dir,prefix=""){let entries=fsSync.readdirSync(dir,{withFileTypes:!0}),found=[];for(let entry of entries){if(entry.name===GIT_DIR_NAME||entry.name===STORE_ENTRY_FILENAME||entry.isSymbolicLink())continue;let relative4=prefix.length>0?`${prefix}/${entry.name}`:entry.name,absolute=path21.join(dir,entry.name);entry.isDirectory()?found.push(...collectFilesSync(absolute,relative4)):entry.isFile()&&found.push(relative4)}return found}function updateWithFile(hash2,relative4,bytes){hash2.update(Buffer.from(relative4,"utf8")),hash2.update(FIELD_SEPARATOR),hash2.update(Buffer.from(String(bytes.byteLength),"utf8")),hash2.update(FIELD_SEPARATOR),hash2.update(bytes),hash2.update(FIELD_SEPARATOR)}function hashesEqual(a,b){return a.toLowerCase()===b.toLowerCase()}function isContentHash(text){return CONTENT_HASH_PATTERN.test(text)}var GIT_DIR_NAME,FIELD_SEPARATOR,recipeHash,init_recipe_hash=__esm({"../sous-plugin-formats/src/recipe-hash.ts"(){"use strict";init_common();GIT_DIR_NAME=".git",FIELD_SEPARATOR=Buffer.from([0]);recipeHash={hashDirectory,hashDirectorySync,equal:hashesEqual,isHash:isContentHash}}});var package_default8,init_package4=__esm({"../sous-plugin-formats/package.json"(){package_default8={name:"@sous-io/sous-plugin-formats",version:"1.1.4",description:"One parser per on-disk format, reading manifests, and the recipe content hash.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-refs":"workspace:*","jsonc-parser":"^3.3.1",semver:"^7.8.5",yaml:"^2.9.0",zod:"^4.4.3"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*","@types/semver":"^7.8.0"},engines:{node:">=22"}}}});import{definePlugin as definePlugin8,SousError as SousError14}from"@sous-io/sous-plugin-api";function manifestRefChecker(ctx){return ref=>{let resolver;try{resolver=ctx.services.get("refs.resolver")}catch(error51){if(error51 instanceof SousError14&&error51.message.includes("cannot be used while the config is being built"))return;throw error51}resolver.parse(ref,"manifest")}}var PLUGIN_NAME7,formatsPlugin,init_src5=__esm({"../sous-plugin-formats/src/index.ts"(){"use strict";init_manifests();init_parsers();init_recipe_hash();init_package4();init_manifests();init_parsers();init_recipe_hash();init_links_map();init_store_entry();init_common();init_recipe_manifest();PLUGIN_NAME7="@sous-io/sous-plugin-formats";formatsPlugin=definePlugin8({name:PLUGIN_NAME7,version:package_default8.version,description:"One parser per on-disk format, reading manifests, and the recipe content hash.",dependsOn:{"@sous-io/sous-plugin-refs":`^${package_default8.version}`},register(sous){let once2={lifetime:"singleton"};sous.services.add("formats.lockfile",()=>lockfileFormat,once2),sous.services.add("formats.repo-manifest",()=>repoManifestFormat,once2),sous.services.add("formats.index-file",()=>indexFileFormat,once2),sous.services.add("formats.links-map",()=>linksMapFormat,once2),sous.services.add("formats.store-entry",()=>storeEntryFormat,once2),sous.services.add("formats.variable-definition",()=>variableDefinitionFormat,once2),sous.services.add("formats.recipe-hash",()=>recipeHash,once2),sous.services.add("formats.recipe-manifest",(_config,ctx)=>createRecipeManifestFormat(manifestRefChecker(ctx)),once2),sous.services.add("formats.manifests",(_config,ctx)=>createManifests({checkRef:manifestRefChecker(ctx)}),once2)}})}});var require_tiktoken_bg=__commonJS({"../../node_modules/.pnpm/tiktoken@1.0.22/node_modules/tiktoken/tiktoken_bg.cjs"(exports,module2){var wasm;module2.exports.__wbg_set_wasm=function(val){wasm=val};var lTextDecoder=typeof TextDecoder>"u"?(0,module2.require)("util").TextDecoder:TextDecoder,cachedTextDecoder=new lTextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});cachedTextDecoder.decode();var cachedUint8ArrayMemory0=null;function getUint8ArrayMemory0(){return(cachedUint8ArrayMemory0===null||cachedUint8ArrayMemory0.byteLength===0)&&(cachedUint8ArrayMemory0=new Uint8Array(wasm.memory.buffer)),cachedUint8ArrayMemory0}function getStringFromWasm0(ptr,len){return ptr=ptr>>>0,cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr,ptr+len))}var heap=new Array(128).fill(void 0);heap.push(void 0,null,!0,!1);var heap_next=heap.length;function addHeapObject(obj){heap_next===heap.length&&heap.push(heap.length+1);let idx=heap_next;return heap_next=heap[idx],heap[idx]=obj,idx}function handleError(f,args){try{return f.apply(this,args)}catch(e){wasm.__wbindgen_export_0(addHeapObject(e))}}function getObject(idx){return heap[idx]}function dropObject(idx){idx<132||(heap[idx]=heap_next,heap_next=idx)}function takeObject(idx){let ret=getObject(idx);return dropObject(idx),ret}var WASM_VECTOR_LEN=0,lTextEncoder=typeof TextEncoder>"u"?(0,module2.require)("util").TextEncoder:TextEncoder,cachedTextEncoder=new lTextEncoder("utf-8"),encodeString=typeof cachedTextEncoder.encodeInto=="function"?function(arg,view){return cachedTextEncoder.encodeInto(arg,view)}:function(arg,view){let buf=cachedTextEncoder.encode(arg);return view.set(buf),{read:arg.length,written:buf.length}};function passStringToWasm0(arg,malloc,realloc){if(realloc===void 0){let buf=cachedTextEncoder.encode(arg),ptr2=malloc(buf.length,1)>>>0;return getUint8ArrayMemory0().subarray(ptr2,ptr2+buf.length).set(buf),WASM_VECTOR_LEN=buf.length,ptr2}let len=arg.length,ptr=malloc(len,1)>>>0,mem=getUint8ArrayMemory0(),offset2=0;for(;offset2<len;offset2++){let code=arg.charCodeAt(offset2);if(code>127)break;mem[ptr+offset2]=code}if(offset2!==len){offset2!==0&&(arg=arg.slice(offset2)),ptr=realloc(ptr,len,len=offset2+arg.length*3,1)>>>0;let view=getUint8ArrayMemory0().subarray(ptr+offset2,ptr+len),ret=encodeString(arg,view);offset2+=ret.written,ptr=realloc(ptr,len,offset2,1)>>>0}return WASM_VECTOR_LEN=offset2,ptr}function isLikeNone(x2){return x2==null}var cachedDataViewMemory0=null;function getDataViewMemory0(){return(cachedDataViewMemory0===null||cachedDataViewMemory0.buffer.detached===!0||cachedDataViewMemory0.buffer.detached===void 0&&cachedDataViewMemory0.buffer!==wasm.memory.buffer)&&(cachedDataViewMemory0=new DataView(wasm.memory.buffer)),cachedDataViewMemory0}var cachedUint32ArrayMemory0=null;function getUint32ArrayMemory0(){return(cachedUint32ArrayMemory0===null||cachedUint32ArrayMemory0.byteLength===0)&&(cachedUint32ArrayMemory0=new Uint32Array(wasm.memory.buffer)),cachedUint32ArrayMemory0}function getArrayU32FromWasm0(ptr,len){return ptr=ptr>>>0,getUint32ArrayMemory0().subarray(ptr/4,ptr/4+len)}function passArray8ToWasm0(arg,malloc){let ptr=malloc(arg.length*1,1)>>>0;return getUint8ArrayMemory0().set(arg,ptr/1),WASM_VECTOR_LEN=arg.length,ptr}function passArray32ToWasm0(arg,malloc){let ptr=malloc(arg.length*4,4)>>>0;return getUint32ArrayMemory0().set(arg,ptr/4),WASM_VECTOR_LEN=arg.length,ptr}function getArrayU8FromWasm0(ptr,len){return ptr=ptr>>>0,getUint8ArrayMemory0().subarray(ptr/1,ptr/1+len)}module2.exports.get_encoding=function(encoding,extend_special_tokens){if(wasm==null)throw new Error("tiktoken: WASM binary has not been propery initialized.");try{let retptr=wasm.__wbindgen_add_to_stack_pointer(-16),ptr0=passStringToWasm0(encoding,wasm.__wbindgen_export_1,wasm.__wbindgen_export_2),len0=WASM_VECTOR_LEN;wasm.get_encoding(retptr,ptr0,len0,addHeapObject(extend_special_tokens));var r0=getDataViewMemory0().getInt32(retptr+0,!0),r1=getDataViewMemory0().getInt32(retptr+4,!0),r2=getDataViewMemory0().getInt32(retptr+8,!0);if(r2)throw takeObject(r1);return Tiktoken.__wrap(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}};module2.exports.encoding_for_model=function(model,extend_special_tokens){if(wasm==null)throw new Error("tiktoken: WASM binary has not been propery initialized.");try{let retptr=wasm.__wbindgen_add_to_stack_pointer(-16),ptr0=passStringToWasm0(model,wasm.__wbindgen_export_1,wasm.__wbindgen_export_2),len0=WASM_VECTOR_LEN;wasm.encoding_for_model(retptr,ptr0,len0,addHeapObject(extend_special_tokens));var r0=getDataViewMemory0().getInt32(retptr+0,!0),r1=getDataViewMemory0().getInt32(retptr+4,!0),r2=getDataViewMemory0().getInt32(retptr+8,!0);if(r2)throw takeObject(r1);return Tiktoken.__wrap(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}};module2.exports.get_encoding_name_for_model=function(model){if(wasm==null)throw new Error("tiktoken: WASM binary has not been propery initialized.");let deferred3_0,deferred3_1;try{let retptr=wasm.__wbindgen_add_to_stack_pointer(-16),ptr0=passStringToWasm0(model,wasm.__wbindgen_export_1,wasm.__wbindgen_export_2),len0=WASM_VECTOR_LEN;wasm.get_encoding_name_for_model(retptr,ptr0,len0);var r0=getDataViewMemory0().getInt32(retptr+0,!0),r1=getDataViewMemory0().getInt32(retptr+4,!0),r2=getDataViewMemory0().getInt32(retptr+8,!0),r3=getDataViewMemory0().getInt32(retptr+12,!0),ptr2=r0,len2=r1;if(r3)throw ptr2=0,len2=0,takeObject(r2);return deferred3_0=ptr2,deferred3_1=len2,getStringFromWasm0(ptr2,len2)}finally{wasm.__wbindgen_add_to_stack_pointer(16),wasm.__wbindgen_export_3(deferred3_0,deferred3_1,1)}};var TiktokenFinalization=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(ptr=>wasm.__wbg_tiktoken_free(ptr>>>0,1)),Tiktoken=class _Tiktoken{constructor(tiktoken_bfe,special_tokens,pat_str){if(wasm==null)throw new Error("tiktoken: WASM binary has not been propery initialized.");let ptr0=passStringToWasm0(tiktoken_bfe,wasm.__wbindgen_export_1,wasm.__wbindgen_export_2),len0=WASM_VECTOR_LEN,ptr1=passStringToWasm0(pat_str,wasm.__wbindgen_export_1,wasm.__wbindgen_export_2),len1=WASM_VECTOR_LEN,ret=wasm.tiktoken_new(ptr0,len0,addHeapObject(special_tokens),ptr1,len1);return this.__wbg_ptr=ret>>>0,TiktokenFinalization.register(this,this.__wbg_ptr,this),this}get name(){try{let retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.tiktoken_name(retptr,this.__wbg_ptr);var r0=getDataViewMemory0().getInt32(retptr+0,!0),r1=getDataViewMemory0().getInt32(retptr+4,!0);let v1;return r0!==0&&(v1=getStringFromWasm0(r0,r1).slice(),wasm.__wbindgen_export_3(r0,r1*1,1)),v1}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}static __wrap(ptr){ptr=ptr>>>0;let obj=Object.create(_Tiktoken.prototype);return obj.__wbg_ptr=ptr,TiktokenFinalization.register(obj,obj.__wbg_ptr,obj),obj}__destroy_into_raw(){let ptr=this.__wbg_ptr;return this.__wbg_ptr=0,TiktokenFinalization.unregister(this),ptr}free(){if(wasm==null)throw new Error("tiktoken: WASM binary has not been propery initialized.");let ptr=this.__destroy_into_raw();wasm.__wbg_tiktoken_free(ptr,0)}encode(text,allowed_special,disallowed_special){if(wasm==null)throw new Error("tiktoken: WASM binary has not been propery initialized.");try{let retptr=wasm.__wbindgen_add_to_stack_pointer(-16),ptr0=passStringToWasm0(text,wasm.__wbindgen_export_1,wasm.__wbindgen_export_2),len0=WASM_VECTOR_LEN;wasm.tiktoken_encode(retptr,this.__wbg_ptr,ptr0,len0,addHeapObject(allowed_special),addHeapObject(disallowed_special));var r0=getDataViewMemory0().getInt32(retptr+0,!0),r1=getDataViewMemory0().getInt32(retptr+4,!0),r2=getDataViewMemory0().getInt32(retptr+8,!0),r3=getDataViewMemory0().getInt32(retptr+12,!0);if(r3)throw takeObject(r2);var v2=getArrayU32FromWasm0(r0,r1).slice();return wasm.__wbindgen_export_3(r0,r1*4,4),v2}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}encode_ordinary(text){if(wasm==null)throw new Error("tiktoken: WASM binary has not been propery initialized.");try{let retptr=wasm.__wbindgen_add_to_stack_pointer(-16),ptr0=passStringToWasm0(text,wasm.__wbindgen_export_1,wasm.__wbindgen_export_2),len0=WASM_VECTOR_LEN;wasm.tiktoken_encode_ordinary(retptr,this.__wbg_ptr,ptr0,len0);var r0=getDataViewMemory0().getInt32(retptr+0,!0),r1=getDataViewMemory0().getInt32(retptr+4,!0),v2=getArrayU32FromWasm0(r0,r1).slice();return wasm.__wbindgen_export_3(r0,r1*4,4),v2}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}encode_with_unstable(text,allowed_special,disallowed_special){if(wasm==null)throw new Error("tiktoken: WASM binary has not been propery initialized.");try{let retptr=wasm.__wbindgen_add_to_stack_pointer(-16),ptr0=passStringToWasm0(text,wasm.__wbindgen_export_1,wasm.__wbindgen_export_2),len0=WASM_VECTOR_LEN;wasm.tiktoken_encode_with_unstable(retptr,this.__wbg_ptr,ptr0,len0,addHeapObject(allowed_special),addHeapObject(disallowed_special));var r0=getDataViewMemory0().getInt32(retptr+0,!0),r1=getDataViewMemory0().getInt32(retptr+4,!0),r2=getDataViewMemory0().getInt32(retptr+8,!0);if(r2)throw takeObject(r1);return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}encode_single_token(bytes){if(wasm==null)throw new Error("tiktoken: WASM binary has not been propery initialized.");let ptr0=passArray8ToWasm0(bytes,wasm.__wbindgen_export_1),len0=WASM_VECTOR_LEN;return wasm.tiktoken_encode_single_token(this.__wbg_ptr,ptr0,len0)>>>0}decode(tokens){if(wasm==null)throw new Error("tiktoken: WASM binary has not been propery initialized.");try{let retptr=wasm.__wbindgen_add_to_stack_pointer(-16),ptr0=passArray32ToWasm0(tokens,wasm.__wbindgen_export_1),len0=WASM_VECTOR_LEN;wasm.tiktoken_decode(retptr,this.__wbg_ptr,ptr0,len0);var r0=getDataViewMemory0().getInt32(retptr+0,!0),r1=getDataViewMemory0().getInt32(retptr+4,!0),v2=getArrayU8FromWasm0(r0,r1).slice();return wasm.__wbindgen_export_3(r0,r1*1,1),v2}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}decode_single_token_bytes(token){if(wasm==null)throw new Error("tiktoken: WASM binary has not been propery initialized.");try{let retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.tiktoken_decode_single_token_bytes(retptr,this.__wbg_ptr,token);var r0=getDataViewMemory0().getInt32(retptr+0,!0),r1=getDataViewMemory0().getInt32(retptr+4,!0),v1=getArrayU8FromWasm0(r0,r1).slice();return wasm.__wbindgen_export_3(r0,r1*1,1),v1}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}token_byte_values(){if(wasm==null)throw new Error("tiktoken: WASM binary has not been propery initialized.");let ret=wasm.tiktoken_token_byte_values(this.__wbg_ptr);return takeObject(ret)}};module2.exports.Tiktoken=Tiktoken;module2.exports.__wbg_parse_def2e24ef1252aff=function(){return handleError(function(arg0,arg1){let ret=JSON.parse(getStringFromWasm0(arg0,arg1));return addHeapObject(ret)},arguments)};module2.exports.__wbg_stringify_f7ed6987935b4a24=function(){return handleError(function(arg0){let ret=JSON.stringify(getObject(arg0));return addHeapObject(ret)},arguments)};module2.exports.__wbindgen_error_new=function(arg0,arg1){let ret=new Error(getStringFromWasm0(arg0,arg1));return addHeapObject(ret)};module2.exports.__wbindgen_is_undefined=function(arg0){return getObject(arg0)===void 0};module2.exports.__wbindgen_object_drop_ref=function(arg0){takeObject(arg0)};module2.exports.__wbindgen_string_get=function(arg0,arg1){if(wasm==null)throw new Error("tiktoken: WASM binary has not been propery initialized.");let obj=getObject(arg1),ret=typeof obj=="string"?obj:void 0;var ptr1=isLikeNone(ret)?0:passStringToWasm0(ret,wasm.__wbindgen_export_1,wasm.__wbindgen_export_2),len1=WASM_VECTOR_LEN;getDataViewMemory0().setInt32(arg0+4,len1,!0),getDataViewMemory0().setInt32(arg0+0,ptr1,!0)};module2.exports.__wbindgen_throw=function(arg0,arg1){throw new Error(getStringFromWasm0(arg0,arg1))}}});var require_tiktoken=__commonJS({"../../node_modules/.pnpm/tiktoken@1.0.22/node_modules/tiktoken/tiktoken.cjs"(exports){var wasm=require_tiktoken_bg(),imports={};imports["./tiktoken_bg.js"]=wasm;var path122=__require("path"),fs88=__require("fs"),candidates=__dirname.split(path122.sep).reduce((memo,_2,index,array2)=>{let prefix=array2.slice(0,index+1).join(path122.sep)+path122.sep;return prefix.includes("node_modules"+path122.sep)||memo.unshift(path122.join(prefix,"node_modules","tiktoken","","./tiktoken_bg.wasm")),memo},[]);candidates.unshift(path122.join(__dirname,"./tiktoken_bg.wasm"));var bytes=null;for(let candidate of candidates)try{bytes=fs88.readFileSync(candidate);break}catch{}if(bytes==null)throw new Error("Missing tiktoken_bg.wasm");var wasmModule=new WebAssembly.Module(bytes),wasmInstance=new WebAssembly.Instance(wasmModule,imports);wasm.__wbg_set_wasm(wasmInstance.exports);exports.get_encoding=wasm.get_encoding;exports.encoding_for_model=wasm.encoding_for_model;exports.get_encoding_name_for_model=wasm.get_encoding_name_for_model;exports.Tiktoken=wasm.Tiktoken}});import fs29 from"node:fs";import path39 from"node:path";function readConfig(config2,key){return"atPath"in config2?config2.atPath(key).get():config2.get(key)}function isInline(item){return typeof item=="object"&&item!==null&&typeof item.$inline=="string"&&typeof item.path=="string"}function inlineText(item){return item.$inline.split("$${").join("${")}function inlineBase(dir,virtualPath){let[first2,...rest]=virtualPath.split("/");return rest.length===0?dir:path39.join(dir,first2)}function isEntry(value){let entry=value;return typeof value=="object"&&value!==null&&typeof entry.recipe=="string"&&typeof entry.dir=="string"&&typeof entry.kind=="string"&&Array.isArray(entry.include)}function isFile8(candidate){try{return fs29.statSync(candidate).isFile()}catch{return!1}}var RECIPES_CONTENTS_KEY,RecipeContents,init_contents=__esm({"../sous-plugin-recipes/src/part-a/contents.ts"(){"use strict";RECIPES_CONTENTS_KEY="recipes.contents";RecipeContents=class{constructor(services){this.services=services}entries(config2,kind){let value=readConfig(config2,RECIPES_CONTENTS_KEY);return Array.isArray(value)?value.filter(entry=>isEntry(entry)&&entry.kind===kind):[]}of(config2,kind){return this.entries(config2,kind).map(entry=>({recipe:entry.recipe,kind:entry.kind,entry,files:this.files(entry)}))}files(entry){let globs=this.services.get("host.globs"),seen=new Set,files=[];for(let include of entry.include){if(isInline(include)){let absolute=path39.join(entry.dir,include.path),excluded=(entry.exclude??[]).some(pattern=>globs.isMatch(include.path,pattern,{dot:!0}));!seen.has(absolute)&&!excluded&&(seen.add(absolute),files.push({path:include.path,file:absolute,base:inlineBase(entry.dir,include.path),content:inlineText(include)}));continue}let staticBase2=globs.hasGlob(include)?globs.staticBase(include):path39.posix.dirname(include),base=path39.join(entry.dir,staticBase2==="/"?".":staticBase2),relative4=globs.matchSync(include,{cwd:entry.dir,dot:!0,ignore:[...entry.exclude??[]]});for(let file2 of globs.sortBytewise(relative4)){let absolute=path39.join(entry.dir,file2);seen.has(absolute)||!isFile8(absolute)||(seen.add(absolute),files.push({path:globs.toPosix(file2),file:absolute,base}))}}return files}}}});function describeError2(error51){return error51 instanceof Error?error51.message:String(error51)}function compareBytewise2(left,right){let a=Buffer.from(left,"utf8"),b=Buffer.from(right,"utf8");return Buffer.compare(a,b)}function sortBytewise(items2){return[...items2].sort(compareBytewise2)}function isPlainObject4(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function entryMap(value){return isPlainObject4(value)?value:{}}function shortNameFromIdentity2(identity2){let segments=identity2.split("/").map(segment=>segment.trim().toLowerCase()).filter(segment=>segment.length>0),cleaned=(segments[segments.length-1]??"").replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"");return REPO_NAME_PATTERN2.test(cleaned)?cleaned:cleaned.length===0?"repository":`repo-${cleaned}`}function proposeRepoName(taken,identity2){let used=new Set(taken),base=shortNameFromIdentity2(identity2);if(!used.has(base))return base;for(let suffix=2;;suffix++)if(!used.has(`${base}-${suffix}`))return`${base}-${suffix}`}function hasIntent(ctx,name){return ctx.engine.intents.get(name)!==void 0}function nowIso(){return new Date().toISOString()}function resolvedAtPin(recipe,pin){let{variables:_variables,pins:_pins,declares:_declares,dependencies:_dependencies,...rest}=recipe;return{...rest,version:pin.version,hash:pin.hash,tag:pin.tag,...pin.variables===void 0?{}:{variables:pin.variables},...pin.declares===void 0?{}:{declares:pin.declares},...pin.dependencies===void 0?{}:{dependencies:pin.dependencies}}}var REPO_NAME_PATTERN2,init_util2=__esm({"../sous-plugin-recipes/src/part-a/util.ts"(){"use strict";REPO_NAME_PATTERN2=/^[a-z][a-z0-9-]*$/}});import{ConfigError as ConfigError25,jsonSchema as jsonSchema11}from"@sous-io/sous-plugin-api";function registerContentKinds(sous){sous.entities.kinds().includes(CONTENT_KIND)||sous.entities.define(CONTENT_KIND,jsonSchema11({type:"object",properties:{id:{type:"string"},description:{type:"string"}},required:["id","description"]}),{description:"A kind of content a recipe's manifest may publish under contents; the plugin that adds it responds to recipes.contents entries of that kind."});for(let kind of BUILT_IN_CONTENT_KINDS)sous.entities.add(CONTENT_KIND,{...kind})}function manifestLabel(recipe){return`${recipe.id}/sous.recipe.yaml`}function manifestsContributor(services,after){return{id:MANIFESTS_CONTRIBUTOR,after:[...after],contribute(config2){let evaluator=services.has("expressions.evaluator")?services.get("expressions.evaluator"):void 0,recipes=[...config2.entities("active-recipe")].sort((left,right)=>compareBytewise2(left.id,right.id));for(let recipe of recipes){let declared=evaluateManifest(recipe,config2,evaluator);recipe.kind==="subscribes"&&declared.contents.forEach((group,index)=>{config2.atPath(RECIPES_CONTENTS_KEY).append(contentsEntry(recipe,group,index))});for(let edit of declared.edits)config2.atPath(EDITOR_EDITS_KEY).append(editEntry(recipe,edit))}}}}function evaluateManifest(recipe,config2,evaluator){let data={contents:recipe.manifest.contents??[],edits:recipe.manifest.edits??[]};if(evaluator===void 0||!evaluator.hasExpressions(data))return data;let value=evaluator.evaluateLayer(data,{file:manifestLabel(recipe),config:config2,fromRecipe:!0,baseDir:recipe.dir,scopeKey:recipe.id}).value;return{contents:value?.contents??[],edits:value?.edits??[]}}function contentsEntry(recipe,group,index){let checked3=parseRecipeContentGroup(group,`${manifestLabel(recipe)} contents[${index}]`);return{recipe:recipe.id,dir:recipe.dir,kind:checked3.kind,include:checked3.include,...checked3.exclude===void 0?{}:{exclude:checked3.exclude}}}function editEntry(recipe,edit){if(typeof edit!="object"||edit===null||Array.isArray(edit))throw new ConfigError25(`${manifestLabel(recipe)} declares an edit that is not an object, after its expressions were evaluated.`);return{...edit,recipe:recipe.id}}function unknownKindsError(entries,kinds){if(!Array.isArray(entries))return;let known=new Set(kinds.map(kind=>kind.id)),unknown2=entries.filter(entry=>typeof entry?.kind=="string"&&!known.has(entry.kind));if(unknown2.length===0)return;let lines3=[...new Set(unknown2.map(entry=>`The recipe ${entry.recipe} publishes content of the kind "${entry.kind}", which no plugin registers.`))];return new ConfigError25(lines3.join(`
442
+ Every directory listed under 'recipes' in a repo manifest holds a '${RECIPE_MANIFEST_BASENAME}${MANIFEST_EXTENSIONS[0]}' file.`}function createManifests(deps={}){let baseName2=kind=>kind==="recipe"?RECIPE_MANIFEST_BASENAME:REPO_MANIFEST_BASENAME,label=kind=>kind==="recipe"?"recipe manifest":"repo manifest",find2=(directory,kind)=>findManifest(directory,baseName2(kind),label(kind));async function read(directory,kind,parse6){let file2=find2(directory,kind);if(file2!==void 0)return{path:file2,manifest:parse6(await readManifestFile(file2),file2)}}let readRecipe2=directory=>read(directory,"recipe",(value,source)=>parseRecipeManifest(value,source,deps.checkRef)),readRepo=directory=>read(directory,"repo",(value,source)=>parseRepoManifest(value,source));async function require_(directory,kind,reader){let found=await reader(directory);if(found!==void 0)return found;let message2=kind==="recipe"?missingRecipeManifestMessage(directory):missingRepoManifestMessage(directory);throw new NotFoundError4(label(kind),directory,message2)}return{find:find2,readRecipe:readRecipe2,readRepo,requireRecipe:directory=>require_(directory,"recipe",readRecipe2),requireRepo:directory=>require_(directory,"repo",readRepo),parseText:(text,fileName)=>parseManifestText(text,fileName),readFile:filePath=>readManifestFile(filePath)}}function parseManifestText(text,fileName){let extension=path20.extname(fileName).toLowerCase();if(extension===".yaml"||extension===".yml")return parseYamlText2(text,fileName);if(extension===".json"||extension===".jsonc")return parseJsoncText2(text,fileName);throw notAManifestFormat(fileName,extension)}async function readManifestFile(filePath){let text;try{text=await fsPromises.readFile(filePath,"utf8")}catch(error51){throw unreadable(filePath,"manifest",error51)}return parseManifestText(text,filePath)}var import_yaml5,init_manifests=__esm({"../sous-plugin-formats/src/manifests.ts"(){"use strict";import_yaml5=__toESM(require_dist(),1);init_main();init_common();init_recipe_manifest();init_repo_manifest()}});function namespaceOfKey(key){let slash=key.indexOf("/");return slash===-1?key:key.slice(0,slash)}var indexDependencySchema,indexVersionSchema,indexRecipeSchema,indexReplacementSchema,indexRetiredRecipeSchema,indexNamespaceSchema,indexFileSchema,init_index_file=__esm({"../sous-plugin-formats/src/formats/index-file.ts"(){"use strict";init_zod();init_common();init_variable_definition();indexDependencySchema=forwardCompatibleObject({version:semverVersionSchema.optional(),range:semverRangeSchema.optional(),repo:repoIdentitySchema.optional(),declared:external_exports.string().min(1,"must not be empty").optional(),kind:dependencyKindSchema.optional()}).refine(entry=>entry.version!==void 0||entry.range!==void 0,{message:"must record the range this dependency may take, or the exact version an older release resolved it to"}),indexVersionSchema=forwardCompatibleObject({hash:contentHashSchema,tag:external_exports.string().min(1,"must not be empty"),prerelease:external_exports.boolean(),seeded:external_exports.boolean().optional(),releasedAt:isoTimestampSchema.optional(),dependencies:external_exports.record(recipeKeySchema,indexDependencySchema).optional(),variables:external_exports.array(publishedVariableDefinitionSchema).optional(),depends:external_exports.array(external_exports.string().min(1,"must not be empty")).optional(),subscribes:external_exports.array(external_exports.string().min(1,"must not be empty")).optional()}),indexRecipeSchema=forwardCompatibleObject({path:relativePathSchema("a recipe path"),description:external_exports.string().optional(),versions:external_exports.record(semverVersionSchema,indexVersionSchema).refine(versions=>Object.keys(versions).length>0,{message:"must list at least one published version"})}),indexReplacementSchema=forwardCompatibleObject({key:recipeKeySchema,repo:repoIdentitySchema.optional(),declared:external_exports.string().min(1,"must not be empty")}),indexRetiredRecipeSchema=forwardCompatibleObject({path:relativePathSchema("a recipe path"),description:external_exports.string().optional(),replacements:external_exports.array(indexReplacementSchema).optional(),versions:external_exports.record(semverVersionSchema,indexVersionSchema).refine(versions=>Object.keys(versions).length>0,{message:"must list at least one published version"})}),indexNamespaceSchema=forwardCompatibleObject({description:external_exports.string().optional()}),indexFileSchema=forwardCompatibleObject({$comment:external_exports.string().optional(),formatVersion:formatVersionSchema,name:repoNameSchema,generatedAt:isoTimestampSchema,generator:semverVersionSchema,namespaces:external_exports.record(namespaceNameSchema,indexNamespaceSchema),recipes:external_exports.record(recipeKeySchema,indexRecipeSchema),retired:external_exports.record(recipeKeySchema,indexRetiredRecipeSchema).optional()}).superRefine((index,ctx)=>{for(let key of Object.keys(index.recipes)){let namespace=namespaceOfKey(key);Object.hasOwn(index.namespaces,namespace)||ctx.addIssue({code:"custom",path:["recipes",key],message:`belongs to the namespace '${namespace}', which this index does not declare under 'namespaces'`})}let sections=[["recipes",index.recipes],["retired",index.retired??{}]];for(let[section2,entries]of sections)for(let[key,recipe]of Object.entries(entries))for(let[version2,published]of Object.entries(recipe.versions)){let expected=`${key}@${version2}`;published.tag!==expected&&ctx.addIssue({code:"custom",path:[section2,key,"versions",version2,"tag"],message:`is '${published.tag}', but a published version's tag names the recipe and the version it carries, so this one must be '${expected}'`})}for(let key of Object.keys(index.retired??{}))Object.hasOwn(index.recipes,key)&&ctx.addIssue({code:"custom",path:["retired",key],message:"is also listed under 'recipes'; a recipe is either published or retired"})})}});function createEmptyLinksMap(){return{formatVersion:1,links:{}}}var LINK_ORIGINS,repoLinkSchema,linksMapSchema,init_links_map=__esm({"../sous-plugin-formats/src/formats/links-map.ts"(){"use strict";init_zod();init_common();LINK_ORIGINS=["clone","path"],repoLinkSchema=external_exports.strictObject({path:absolutePathSchema,linkedAt:isoTimestampSchema,origin:external_exports.enum(LINK_ORIGINS)}),linksMapSchema=external_exports.strictObject({formatVersion:formatVersionSchema,links:external_exports.record(repoNameSchema,repoLinkSchema)})}});function createEmptyLockfile(){return{formatVersion:1,repos:{},recipes:{}}}var LOCK_KINDS,lockedRepoSchema,lockedPinSchema,lockedRecipeSchema,lockfileSchema,init_lockfile=__esm({"../sous-plugin-formats/src/formats/lockfile.ts"(){"use strict";init_zod();init_common();LOCK_KINDS=DEPENDENCY_KINDS,lockedRepoSchema=external_exports.strictObject({url:repoUrlSchema,identity:repoIdentitySchema.optional(),indexHash:contentHashSchema.optional()}),lockedPinSchema=external_exports.strictObject({version:semverVersionSchema,hash:contentHashSchema}),lockedRecipeSchema=external_exports.strictObject({repo:repoNameSchema,version:semverVersionSchema,hash:contentHashSchema,requestedBy:external_exports.array(external_exports.string().min(1,"must not be empty")).min(1,"must name at least one holder"),kind:external_exports.enum(LOCK_KINDS),pins:external_exports.record(recipeKeySchema,lockedPinSchema).optional()}),lockfileSchema=external_exports.strictObject({formatVersion:formatVersionSchema,repos:external_exports.record(repoNameSchema,lockedRepoSchema),recipes:external_exports.record(recipeKeySchema,lockedRecipeSchema),migratedVersion:semverVersionSchema.optional()}).superRefine((lock,ctx)=>{for(let[key,entry]of Object.entries(lock.recipes)){Object.hasOwn(lock.repos,entry.repo)||ctx.addIssue({code:"custom",path:["recipes",key,"repo"],message:`names the repo '${entry.repo}', which this lockfile does not describe under 'repos'`});for(let holder of Object.keys(entry.pins??{}))entry.requestedBy.includes(holder)||ctx.addIssue({code:"custom",path:["recipes",key,"pins",holder],message:`pins a version for '${holder}', which is not listed in 'requestedBy'`})}})}});var storeEntrySchema,init_store_entry=__esm({"../sous-plugin-formats/src/formats/store-entry.ts"(){"use strict";init_zod();init_common();storeEntrySchema=external_exports.strictObject({formatVersion:formatVersionSchema,repo:repoIdentitySchema,namespace:namespaceNameSchema,name:recipeNameSchema,version:semverVersionSchema,hash:contentHashSchema,fetchedAt:isoTimestampSchema,lastAccessAt:isoTimestampSchema,sizeBytes:byteCountSchema,statFingerprint:external_exports.string().min(1).optional()})}});function readOnly(label,schema,fileName){return{label,...fileName===void 0?{}:{fileName},parse:(value,sourceLabel2)=>parseFormat(schema,value,sourceLabel2,label),check:(value,sourceLabel2)=>{let result=checkFormat(schema,value);return result.issues===void 0?{value:result.value}:{issues:[`Invalid ${label} at ${sourceLabel2}:`,...result.issues]}}}}function writable(label,schema,fileName,empty){return{...readOnly(label,schema,fileName),stringify:stableJsonStringify,empty}}function createRecipeManifestFormat(checkRef){return readOnly("recipe manifest",createRecipeManifestSchema(checkRef))}var lockfileFormat,linksMapFormat,indexFileFormat,storeEntryFormat,repoManifestFormat,variableDefinitionFormat,init_parsers=__esm({"../sous-plugin-formats/src/parsers.ts"(){"use strict";init_common();init_index_file();init_links_map();init_lockfile();init_recipe_manifest();init_repo_manifest();init_store_entry();init_variable_definition();init_common();lockfileFormat=writable("lockfile",lockfileSchema,LOCKFILE_FILENAME,createEmptyLockfile),linksMapFormat=writable("links map",linksMapSchema,LINKS_FILENAME,createEmptyLinksMap),indexFileFormat=writable("index file",indexFileSchema,INDEX_FILENAME,()=>({formatVersion:1,name:"",generatedAt:new Date(0).toISOString(),generator:"",namespaces:{},recipes:{}})),storeEntryFormat=writable("store entry",storeEntrySchema,STORE_ENTRY_FILENAME,()=>({formatVersion:1,repo:"",namespace:"",name:"",version:"",hash:`sha256-${"0".repeat(64)}`,fetchedAt:new Date(0).toISOString(),lastAccessAt:new Date(0).toISOString(),sizeBytes:0})),repoManifestFormat=readOnly("repo manifest",repoManifestSchema),variableDefinitionFormat=readOnly("variable definition",variableDefinitionSchema)}});import{createHash as createHash3}from"node:crypto";import fsSync from"node:fs";import fs15 from"node:fs/promises";import path21 from"node:path";async function collectFiles(dir,prefix=""){let entries=await fs15.readdir(dir,{withFileTypes:!0}),found=[];for(let entry of entries){if(entry.name===GIT_DIR_NAME||entry.name===STORE_ENTRY_FILENAME||entry.isSymbolicLink())continue;let relative4=prefix.length>0?`${prefix}/${entry.name}`:entry.name,absolute=path21.join(dir,entry.name);entry.isDirectory()?found.push(...await collectFiles(absolute,relative4)):entry.isFile()&&found.push(relative4)}return found}function bytewiseCompare(a,b){return a<b?-1:a>b?1:0}async function hashDirectory(dir){let root=path21.resolve(dir),files=(await collectFiles(root)).sort(bytewiseCompare),hash2=createHash3("sha256");for(let relative4 of files)updateWithFile(hash2,relative4,await fs15.readFile(path21.join(root,...relative4.split("/"))));return`sha256-${hash2.digest("hex")}`}function hashDirectorySync(dir){let root=path21.resolve(dir),files=collectFilesSync(root).sort(bytewiseCompare),hash2=createHash3("sha256");for(let relative4 of files)updateWithFile(hash2,relative4,fsSync.readFileSync(path21.join(root,...relative4.split("/"))));return`sha256-${hash2.digest("hex")}`}function collectFilesSync(dir,prefix=""){let entries=fsSync.readdirSync(dir,{withFileTypes:!0}),found=[];for(let entry of entries){if(entry.name===GIT_DIR_NAME||entry.name===STORE_ENTRY_FILENAME||entry.isSymbolicLink())continue;let relative4=prefix.length>0?`${prefix}/${entry.name}`:entry.name,absolute=path21.join(dir,entry.name);entry.isDirectory()?found.push(...collectFilesSync(absolute,relative4)):entry.isFile()&&found.push(relative4)}return found}function updateWithFile(hash2,relative4,bytes){hash2.update(Buffer.from(relative4,"utf8")),hash2.update(FIELD_SEPARATOR),hash2.update(Buffer.from(String(bytes.byteLength),"utf8")),hash2.update(FIELD_SEPARATOR),hash2.update(bytes),hash2.update(FIELD_SEPARATOR)}function hashesEqual(a,b){return a.toLowerCase()===b.toLowerCase()}function isContentHash(text){return CONTENT_HASH_PATTERN.test(text)}var GIT_DIR_NAME,FIELD_SEPARATOR,recipeHash,init_recipe_hash=__esm({"../sous-plugin-formats/src/recipe-hash.ts"(){"use strict";init_common();GIT_DIR_NAME=".git",FIELD_SEPARATOR=Buffer.from([0]);recipeHash={hashDirectory,hashDirectorySync,equal:hashesEqual,isHash:isContentHash}}});var package_default8,init_package4=__esm({"../sous-plugin-formats/package.json"(){package_default8={name:"@sous-io/sous-plugin-formats",version:"1.1.6",description:"One parser per on-disk format, reading manifests, and the recipe content hash.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-refs":"workspace:*","jsonc-parser":"^3.3.1",semver:"^7.8.5",yaml:"^2.9.0",zod:"^4.4.3"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*","@types/semver":"^7.8.0"},engines:{node:">=22"}}}});import{definePlugin as definePlugin8,SousError as SousError14}from"@sous-io/sous-plugin-api";function manifestRefChecker(ctx){return ref=>{let resolver;try{resolver=ctx.services.get("refs.resolver")}catch(error51){if(error51 instanceof SousError14&&error51.message.includes("cannot be used while the config is being built"))return;throw error51}resolver.parse(ref,"manifest")}}var PLUGIN_NAME7,formatsPlugin,init_src5=__esm({"../sous-plugin-formats/src/index.ts"(){"use strict";init_manifests();init_parsers();init_recipe_hash();init_package4();init_manifests();init_parsers();init_recipe_hash();init_links_map();init_store_entry();init_common();init_recipe_manifest();PLUGIN_NAME7="@sous-io/sous-plugin-formats";formatsPlugin=definePlugin8({name:PLUGIN_NAME7,version:package_default8.version,description:"One parser per on-disk format, reading manifests, and the recipe content hash.",dependsOn:{"@sous-io/sous-plugin-refs":`^${package_default8.version}`},register(sous){let once2={lifetime:"singleton"};sous.services.add("formats.lockfile",()=>lockfileFormat,once2),sous.services.add("formats.repo-manifest",()=>repoManifestFormat,once2),sous.services.add("formats.index-file",()=>indexFileFormat,once2),sous.services.add("formats.links-map",()=>linksMapFormat,once2),sous.services.add("formats.store-entry",()=>storeEntryFormat,once2),sous.services.add("formats.variable-definition",()=>variableDefinitionFormat,once2),sous.services.add("formats.recipe-hash",()=>recipeHash,once2),sous.services.add("formats.recipe-manifest",(_config,ctx)=>createRecipeManifestFormat(manifestRefChecker(ctx)),once2),sous.services.add("formats.manifests",(_config,ctx)=>createManifests({checkRef:manifestRefChecker(ctx)}),once2)}})}});var require_tiktoken_bg=__commonJS({"../../node_modules/.pnpm/tiktoken@1.0.22/node_modules/tiktoken/tiktoken_bg.cjs"(exports,module2){var wasm;module2.exports.__wbg_set_wasm=function(val){wasm=val};var lTextDecoder=typeof TextDecoder>"u"?(0,module2.require)("util").TextDecoder:TextDecoder,cachedTextDecoder=new lTextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});cachedTextDecoder.decode();var cachedUint8ArrayMemory0=null;function getUint8ArrayMemory0(){return(cachedUint8ArrayMemory0===null||cachedUint8ArrayMemory0.byteLength===0)&&(cachedUint8ArrayMemory0=new Uint8Array(wasm.memory.buffer)),cachedUint8ArrayMemory0}function getStringFromWasm0(ptr,len){return ptr=ptr>>>0,cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr,ptr+len))}var heap=new Array(128).fill(void 0);heap.push(void 0,null,!0,!1);var heap_next=heap.length;function addHeapObject(obj){heap_next===heap.length&&heap.push(heap.length+1);let idx=heap_next;return heap_next=heap[idx],heap[idx]=obj,idx}function handleError(f,args){try{return f.apply(this,args)}catch(e){wasm.__wbindgen_export_0(addHeapObject(e))}}function getObject(idx){return heap[idx]}function dropObject(idx){idx<132||(heap[idx]=heap_next,heap_next=idx)}function takeObject(idx){let ret=getObject(idx);return dropObject(idx),ret}var WASM_VECTOR_LEN=0,lTextEncoder=typeof TextEncoder>"u"?(0,module2.require)("util").TextEncoder:TextEncoder,cachedTextEncoder=new lTextEncoder("utf-8"),encodeString=typeof cachedTextEncoder.encodeInto=="function"?function(arg,view){return cachedTextEncoder.encodeInto(arg,view)}:function(arg,view){let buf=cachedTextEncoder.encode(arg);return view.set(buf),{read:arg.length,written:buf.length}};function passStringToWasm0(arg,malloc,realloc){if(realloc===void 0){let buf=cachedTextEncoder.encode(arg),ptr2=malloc(buf.length,1)>>>0;return getUint8ArrayMemory0().subarray(ptr2,ptr2+buf.length).set(buf),WASM_VECTOR_LEN=buf.length,ptr2}let len=arg.length,ptr=malloc(len,1)>>>0,mem=getUint8ArrayMemory0(),offset2=0;for(;offset2<len;offset2++){let code=arg.charCodeAt(offset2);if(code>127)break;mem[ptr+offset2]=code}if(offset2!==len){offset2!==0&&(arg=arg.slice(offset2)),ptr=realloc(ptr,len,len=offset2+arg.length*3,1)>>>0;let view=getUint8ArrayMemory0().subarray(ptr+offset2,ptr+len),ret=encodeString(arg,view);offset2+=ret.written,ptr=realloc(ptr,len,offset2,1)>>>0}return WASM_VECTOR_LEN=offset2,ptr}function isLikeNone(x2){return x2==null}var cachedDataViewMemory0=null;function getDataViewMemory0(){return(cachedDataViewMemory0===null||cachedDataViewMemory0.buffer.detached===!0||cachedDataViewMemory0.buffer.detached===void 0&&cachedDataViewMemory0.buffer!==wasm.memory.buffer)&&(cachedDataViewMemory0=new DataView(wasm.memory.buffer)),cachedDataViewMemory0}var cachedUint32ArrayMemory0=null;function getUint32ArrayMemory0(){return(cachedUint32ArrayMemory0===null||cachedUint32ArrayMemory0.byteLength===0)&&(cachedUint32ArrayMemory0=new Uint32Array(wasm.memory.buffer)),cachedUint32ArrayMemory0}function getArrayU32FromWasm0(ptr,len){return ptr=ptr>>>0,getUint32ArrayMemory0().subarray(ptr/4,ptr/4+len)}function passArray8ToWasm0(arg,malloc){let ptr=malloc(arg.length*1,1)>>>0;return getUint8ArrayMemory0().set(arg,ptr/1),WASM_VECTOR_LEN=arg.length,ptr}function passArray32ToWasm0(arg,malloc){let ptr=malloc(arg.length*4,4)>>>0;return getUint32ArrayMemory0().set(arg,ptr/4),WASM_VECTOR_LEN=arg.length,ptr}function getArrayU8FromWasm0(ptr,len){return ptr=ptr>>>0,getUint8ArrayMemory0().subarray(ptr/1,ptr/1+len)}module2.exports.get_encoding=function(encoding,extend_special_tokens){if(wasm==null)throw new Error("tiktoken: WASM binary has not been propery initialized.");try{let retptr=wasm.__wbindgen_add_to_stack_pointer(-16),ptr0=passStringToWasm0(encoding,wasm.__wbindgen_export_1,wasm.__wbindgen_export_2),len0=WASM_VECTOR_LEN;wasm.get_encoding(retptr,ptr0,len0,addHeapObject(extend_special_tokens));var r0=getDataViewMemory0().getInt32(retptr+0,!0),r1=getDataViewMemory0().getInt32(retptr+4,!0),r2=getDataViewMemory0().getInt32(retptr+8,!0);if(r2)throw takeObject(r1);return Tiktoken.__wrap(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}};module2.exports.encoding_for_model=function(model,extend_special_tokens){if(wasm==null)throw new Error("tiktoken: WASM binary has not been propery initialized.");try{let retptr=wasm.__wbindgen_add_to_stack_pointer(-16),ptr0=passStringToWasm0(model,wasm.__wbindgen_export_1,wasm.__wbindgen_export_2),len0=WASM_VECTOR_LEN;wasm.encoding_for_model(retptr,ptr0,len0,addHeapObject(extend_special_tokens));var r0=getDataViewMemory0().getInt32(retptr+0,!0),r1=getDataViewMemory0().getInt32(retptr+4,!0),r2=getDataViewMemory0().getInt32(retptr+8,!0);if(r2)throw takeObject(r1);return Tiktoken.__wrap(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}};module2.exports.get_encoding_name_for_model=function(model){if(wasm==null)throw new Error("tiktoken: WASM binary has not been propery initialized.");let deferred3_0,deferred3_1;try{let retptr=wasm.__wbindgen_add_to_stack_pointer(-16),ptr0=passStringToWasm0(model,wasm.__wbindgen_export_1,wasm.__wbindgen_export_2),len0=WASM_VECTOR_LEN;wasm.get_encoding_name_for_model(retptr,ptr0,len0);var r0=getDataViewMemory0().getInt32(retptr+0,!0),r1=getDataViewMemory0().getInt32(retptr+4,!0),r2=getDataViewMemory0().getInt32(retptr+8,!0),r3=getDataViewMemory0().getInt32(retptr+12,!0),ptr2=r0,len2=r1;if(r3)throw ptr2=0,len2=0,takeObject(r2);return deferred3_0=ptr2,deferred3_1=len2,getStringFromWasm0(ptr2,len2)}finally{wasm.__wbindgen_add_to_stack_pointer(16),wasm.__wbindgen_export_3(deferred3_0,deferred3_1,1)}};var TiktokenFinalization=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(ptr=>wasm.__wbg_tiktoken_free(ptr>>>0,1)),Tiktoken=class _Tiktoken{constructor(tiktoken_bfe,special_tokens,pat_str){if(wasm==null)throw new Error("tiktoken: WASM binary has not been propery initialized.");let ptr0=passStringToWasm0(tiktoken_bfe,wasm.__wbindgen_export_1,wasm.__wbindgen_export_2),len0=WASM_VECTOR_LEN,ptr1=passStringToWasm0(pat_str,wasm.__wbindgen_export_1,wasm.__wbindgen_export_2),len1=WASM_VECTOR_LEN,ret=wasm.tiktoken_new(ptr0,len0,addHeapObject(special_tokens),ptr1,len1);return this.__wbg_ptr=ret>>>0,TiktokenFinalization.register(this,this.__wbg_ptr,this),this}get name(){try{let retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.tiktoken_name(retptr,this.__wbg_ptr);var r0=getDataViewMemory0().getInt32(retptr+0,!0),r1=getDataViewMemory0().getInt32(retptr+4,!0);let v1;return r0!==0&&(v1=getStringFromWasm0(r0,r1).slice(),wasm.__wbindgen_export_3(r0,r1*1,1)),v1}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}static __wrap(ptr){ptr=ptr>>>0;let obj=Object.create(_Tiktoken.prototype);return obj.__wbg_ptr=ptr,TiktokenFinalization.register(obj,obj.__wbg_ptr,obj),obj}__destroy_into_raw(){let ptr=this.__wbg_ptr;return this.__wbg_ptr=0,TiktokenFinalization.unregister(this),ptr}free(){if(wasm==null)throw new Error("tiktoken: WASM binary has not been propery initialized.");let ptr=this.__destroy_into_raw();wasm.__wbg_tiktoken_free(ptr,0)}encode(text,allowed_special,disallowed_special){if(wasm==null)throw new Error("tiktoken: WASM binary has not been propery initialized.");try{let retptr=wasm.__wbindgen_add_to_stack_pointer(-16),ptr0=passStringToWasm0(text,wasm.__wbindgen_export_1,wasm.__wbindgen_export_2),len0=WASM_VECTOR_LEN;wasm.tiktoken_encode(retptr,this.__wbg_ptr,ptr0,len0,addHeapObject(allowed_special),addHeapObject(disallowed_special));var r0=getDataViewMemory0().getInt32(retptr+0,!0),r1=getDataViewMemory0().getInt32(retptr+4,!0),r2=getDataViewMemory0().getInt32(retptr+8,!0),r3=getDataViewMemory0().getInt32(retptr+12,!0);if(r3)throw takeObject(r2);var v2=getArrayU32FromWasm0(r0,r1).slice();return wasm.__wbindgen_export_3(r0,r1*4,4),v2}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}encode_ordinary(text){if(wasm==null)throw new Error("tiktoken: WASM binary has not been propery initialized.");try{let retptr=wasm.__wbindgen_add_to_stack_pointer(-16),ptr0=passStringToWasm0(text,wasm.__wbindgen_export_1,wasm.__wbindgen_export_2),len0=WASM_VECTOR_LEN;wasm.tiktoken_encode_ordinary(retptr,this.__wbg_ptr,ptr0,len0);var r0=getDataViewMemory0().getInt32(retptr+0,!0),r1=getDataViewMemory0().getInt32(retptr+4,!0),v2=getArrayU32FromWasm0(r0,r1).slice();return wasm.__wbindgen_export_3(r0,r1*4,4),v2}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}encode_with_unstable(text,allowed_special,disallowed_special){if(wasm==null)throw new Error("tiktoken: WASM binary has not been propery initialized.");try{let retptr=wasm.__wbindgen_add_to_stack_pointer(-16),ptr0=passStringToWasm0(text,wasm.__wbindgen_export_1,wasm.__wbindgen_export_2),len0=WASM_VECTOR_LEN;wasm.tiktoken_encode_with_unstable(retptr,this.__wbg_ptr,ptr0,len0,addHeapObject(allowed_special),addHeapObject(disallowed_special));var r0=getDataViewMemory0().getInt32(retptr+0,!0),r1=getDataViewMemory0().getInt32(retptr+4,!0),r2=getDataViewMemory0().getInt32(retptr+8,!0);if(r2)throw takeObject(r1);return takeObject(r0)}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}encode_single_token(bytes){if(wasm==null)throw new Error("tiktoken: WASM binary has not been propery initialized.");let ptr0=passArray8ToWasm0(bytes,wasm.__wbindgen_export_1),len0=WASM_VECTOR_LEN;return wasm.tiktoken_encode_single_token(this.__wbg_ptr,ptr0,len0)>>>0}decode(tokens){if(wasm==null)throw new Error("tiktoken: WASM binary has not been propery initialized.");try{let retptr=wasm.__wbindgen_add_to_stack_pointer(-16),ptr0=passArray32ToWasm0(tokens,wasm.__wbindgen_export_1),len0=WASM_VECTOR_LEN;wasm.tiktoken_decode(retptr,this.__wbg_ptr,ptr0,len0);var r0=getDataViewMemory0().getInt32(retptr+0,!0),r1=getDataViewMemory0().getInt32(retptr+4,!0),v2=getArrayU8FromWasm0(r0,r1).slice();return wasm.__wbindgen_export_3(r0,r1*1,1),v2}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}decode_single_token_bytes(token){if(wasm==null)throw new Error("tiktoken: WASM binary has not been propery initialized.");try{let retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.tiktoken_decode_single_token_bytes(retptr,this.__wbg_ptr,token);var r0=getDataViewMemory0().getInt32(retptr+0,!0),r1=getDataViewMemory0().getInt32(retptr+4,!0),v1=getArrayU8FromWasm0(r0,r1).slice();return wasm.__wbindgen_export_3(r0,r1*1,1),v1}finally{wasm.__wbindgen_add_to_stack_pointer(16)}}token_byte_values(){if(wasm==null)throw new Error("tiktoken: WASM binary has not been propery initialized.");let ret=wasm.tiktoken_token_byte_values(this.__wbg_ptr);return takeObject(ret)}};module2.exports.Tiktoken=Tiktoken;module2.exports.__wbg_parse_def2e24ef1252aff=function(){return handleError(function(arg0,arg1){let ret=JSON.parse(getStringFromWasm0(arg0,arg1));return addHeapObject(ret)},arguments)};module2.exports.__wbg_stringify_f7ed6987935b4a24=function(){return handleError(function(arg0){let ret=JSON.stringify(getObject(arg0));return addHeapObject(ret)},arguments)};module2.exports.__wbindgen_error_new=function(arg0,arg1){let ret=new Error(getStringFromWasm0(arg0,arg1));return addHeapObject(ret)};module2.exports.__wbindgen_is_undefined=function(arg0){return getObject(arg0)===void 0};module2.exports.__wbindgen_object_drop_ref=function(arg0){takeObject(arg0)};module2.exports.__wbindgen_string_get=function(arg0,arg1){if(wasm==null)throw new Error("tiktoken: WASM binary has not been propery initialized.");let obj=getObject(arg1),ret=typeof obj=="string"?obj:void 0;var ptr1=isLikeNone(ret)?0:passStringToWasm0(ret,wasm.__wbindgen_export_1,wasm.__wbindgen_export_2),len1=WASM_VECTOR_LEN;getDataViewMemory0().setInt32(arg0+4,len1,!0),getDataViewMemory0().setInt32(arg0+0,ptr1,!0)};module2.exports.__wbindgen_throw=function(arg0,arg1){throw new Error(getStringFromWasm0(arg0,arg1))}}});var require_tiktoken=__commonJS({"../../node_modules/.pnpm/tiktoken@1.0.22/node_modules/tiktoken/tiktoken.cjs"(exports){var wasm=require_tiktoken_bg(),imports={};imports["./tiktoken_bg.js"]=wasm;var path122=__require("path"),fs88=__require("fs"),candidates=__dirname.split(path122.sep).reduce((memo,_2,index,array2)=>{let prefix=array2.slice(0,index+1).join(path122.sep)+path122.sep;return prefix.includes("node_modules"+path122.sep)||memo.unshift(path122.join(prefix,"node_modules","tiktoken","","./tiktoken_bg.wasm")),memo},[]);candidates.unshift(path122.join(__dirname,"./tiktoken_bg.wasm"));var bytes=null;for(let candidate of candidates)try{bytes=fs88.readFileSync(candidate);break}catch{}if(bytes==null)throw new Error("Missing tiktoken_bg.wasm");var wasmModule=new WebAssembly.Module(bytes),wasmInstance=new WebAssembly.Instance(wasmModule,imports);wasm.__wbg_set_wasm(wasmInstance.exports);exports.get_encoding=wasm.get_encoding;exports.encoding_for_model=wasm.encoding_for_model;exports.get_encoding_name_for_model=wasm.get_encoding_name_for_model;exports.Tiktoken=wasm.Tiktoken}});import fs29 from"node:fs";import path39 from"node:path";function readConfig(config2,key){return"atPath"in config2?config2.atPath(key).get():config2.get(key)}function isInline(item){return typeof item=="object"&&item!==null&&typeof item.$inline=="string"&&typeof item.path=="string"}function inlineText(item){return item.$inline.split("$${").join("${")}function inlineBase(dir,virtualPath){let[first2,...rest]=virtualPath.split("/");return rest.length===0?dir:path39.join(dir,first2)}function isEntry(value){let entry=value;return typeof value=="object"&&value!==null&&typeof entry.recipe=="string"&&typeof entry.dir=="string"&&typeof entry.kind=="string"&&Array.isArray(entry.include)}function isFile8(candidate){try{return fs29.statSync(candidate).isFile()}catch{return!1}}var RECIPES_CONTENTS_KEY,RecipeContents,init_contents=__esm({"../sous-plugin-recipes/src/part-a/contents.ts"(){"use strict";RECIPES_CONTENTS_KEY="recipes.contents";RecipeContents=class{constructor(services){this.services=services}entries(config2,kind){let value=readConfig(config2,RECIPES_CONTENTS_KEY);return Array.isArray(value)?value.filter(entry=>isEntry(entry)&&entry.kind===kind):[]}of(config2,kind){return this.entries(config2,kind).map(entry=>({recipe:entry.recipe,kind:entry.kind,entry,files:this.files(entry)}))}files(entry){let globs=this.services.get("host.globs"),seen=new Set,files=[];for(let include of entry.include){if(isInline(include)){let absolute=path39.join(entry.dir,include.path),excluded=(entry.exclude??[]).some(pattern=>globs.isMatch(include.path,pattern,{dot:!0}));!seen.has(absolute)&&!excluded&&(seen.add(absolute),files.push({path:include.path,file:absolute,base:inlineBase(entry.dir,include.path),content:inlineText(include)}));continue}let staticBase2=globs.hasGlob(include)?globs.staticBase(include):path39.posix.dirname(include),base=path39.join(entry.dir,staticBase2==="/"?".":staticBase2),relative4=globs.matchSync(include,{cwd:entry.dir,dot:!0,ignore:[...entry.exclude??[]]});for(let file2 of globs.sortBytewise(relative4)){let absolute=path39.join(entry.dir,file2);seen.has(absolute)||!isFile8(absolute)||(seen.add(absolute),files.push({path:globs.toPosix(file2),file:absolute,base}))}}return files}}}});function describeError2(error51){return error51 instanceof Error?error51.message:String(error51)}function compareBytewise2(left,right){let a=Buffer.from(left,"utf8"),b=Buffer.from(right,"utf8");return Buffer.compare(a,b)}function sortBytewise(items2){return[...items2].sort(compareBytewise2)}function isPlainObject4(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function entryMap(value){return isPlainObject4(value)?value:{}}function shortNameFromIdentity2(identity2){let segments=identity2.split("/").map(segment=>segment.trim().toLowerCase()).filter(segment=>segment.length>0),cleaned=(segments[segments.length-1]??"").replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"");return REPO_NAME_PATTERN2.test(cleaned)?cleaned:cleaned.length===0?"repository":`repo-${cleaned}`}function proposeRepoName(taken,identity2){let used=new Set(taken),base=shortNameFromIdentity2(identity2);if(!used.has(base))return base;for(let suffix=2;;suffix++)if(!used.has(`${base}-${suffix}`))return`${base}-${suffix}`}function hasIntent(ctx,name){return ctx.engine.intents.get(name)!==void 0}function nowIso(){return new Date().toISOString()}function resolvedAtPin(recipe,pin){let{variables:_variables,pins:_pins,declares:_declares,dependencies:_dependencies,...rest}=recipe;return{...rest,version:pin.version,hash:pin.hash,tag:pin.tag,...pin.variables===void 0?{}:{variables:pin.variables},...pin.declares===void 0?{}:{declares:pin.declares},...pin.dependencies===void 0?{}:{dependencies:pin.dependencies}}}var REPO_NAME_PATTERN2,init_util2=__esm({"../sous-plugin-recipes/src/part-a/util.ts"(){"use strict";REPO_NAME_PATTERN2=/^[a-z][a-z0-9-]*$/}});import{ConfigError as ConfigError25,jsonSchema as jsonSchema11}from"@sous-io/sous-plugin-api";function registerContentKinds(sous){sous.entities.kinds().includes(CONTENT_KIND)||sous.entities.define(CONTENT_KIND,jsonSchema11({type:"object",properties:{id:{type:"string"},description:{type:"string"}},required:["id","description"]}),{description:"A kind of content a recipe's manifest may publish under contents; the plugin that adds it responds to recipes.contents entries of that kind."});for(let kind of BUILT_IN_CONTENT_KINDS)sous.entities.add(CONTENT_KIND,{...kind})}function manifestLabel(recipe){return`${recipe.id}/sous.recipe.yaml`}function manifestsContributor(services,after){return{id:MANIFESTS_CONTRIBUTOR,after:[...after],contribute(config2){let evaluator=services.has("expressions.evaluator")?services.get("expressions.evaluator"):void 0,recipes=[...config2.entities("active-recipe")].sort((left,right)=>compareBytewise2(left.id,right.id));for(let recipe of recipes){let declared=evaluateManifest(recipe,config2,evaluator);recipe.kind==="subscribes"&&declared.contents.forEach((group,index)=>{config2.atPath(RECIPES_CONTENTS_KEY).append(contentsEntry(recipe,group,index))});for(let edit of declared.edits)config2.atPath(EDITOR_EDITS_KEY).append(editEntry(recipe,edit))}}}}function evaluateManifest(recipe,config2,evaluator){let data={contents:recipe.manifest.contents??[],edits:recipe.manifest.edits??[]};if(evaluator===void 0||!evaluator.hasExpressions(data))return data;let value=evaluator.evaluateLayer(data,{file:manifestLabel(recipe),config:config2,fromRecipe:!0,baseDir:recipe.dir,scopeKey:recipe.id}).value;return{contents:value?.contents??[],edits:value?.edits??[]}}function contentsEntry(recipe,group,index){let checked3=parseRecipeContentGroup(group,`${manifestLabel(recipe)} contents[${index}]`);return{recipe:recipe.id,dir:recipe.dir,kind:checked3.kind,include:checked3.include,...checked3.exclude===void 0?{}:{exclude:checked3.exclude}}}function editEntry(recipe,edit){if(typeof edit!="object"||edit===null||Array.isArray(edit))throw new ConfigError25(`${manifestLabel(recipe)} declares an edit that is not an object, after its expressions were evaluated.`);return{...edit,recipe:recipe.id}}function unknownKindsError(entries,kinds){if(!Array.isArray(entries))return;let known=new Set(kinds.map(kind=>kind.id)),unknown2=entries.filter(entry=>typeof entry?.kind=="string"&&!known.has(entry.kind));if(unknown2.length===0)return;let lines3=[...new Set(unknown2.map(entry=>`The recipe ${entry.recipe} publishes content of the kind "${entry.kind}", which no plugin registers.`))];return new ConfigError25(lines3.join(`
443
443
  `),{details:["The plugin that provides the kind may be missing from npm (a plugin the recipe names under requires.plugins), or may ship as part of a recipe the project does not subscribe to.",`Kinds registered here: ${[...known].sort(compareBytewise2).join(", ")||"none"}.`]})}var MANIFESTS_CONTRIBUTOR,EDITOR_EDITS_KEY,CONTENT_KIND,BUILT_IN_CONTENT_KINDS,recipesContentsConfigKey,init_manifests2=__esm({"../sous-plugin-recipes/src/part-a/manifests.ts"(){"use strict";init_src5();init_contents();init_util2();MANIFESTS_CONTRIBUTOR="recipes.manifests",EDITOR_EDITS_KEY="editor.edits",CONTENT_KIND="content-kind",BUILT_IN_CONTENT_KINDS=[{id:"skills",description:"Skill folders, compiled into every place a harness reads skills from (sous-plugin-skills)."},{id:"memories",description:"Files read into every session, compiled into each memory file (sous-plugin-memories)."},{id:"prompts",description:"Prompt files."},{id:"config",description:"Config layers merged into the subscriber's config, limited to the keys a recipe may set."}];recipesContentsConfigKey={id:RECIPES_CONTENTS_KEY,description:"What each active recipe's manifest publishes, one entry per contents group, added by sous-plugin-recipes (read-only in practice).",schema:jsonSchema11({type:"array",default:[],items:{type:"object",required:["recipe","dir","kind","include"],properties:{recipe:{type:"string"},dir:{type:"string"},kind:{type:"string"},include:{type:"array"},exclude:{type:"array",items:{type:"string"}}}}})}}});var RECIPES_PLUGIN,LOCKFILE_NAME,LINKS_FILE_NAME,PROJECT_REPOS_DIRNAME,TYPES_DIRNAME,PROJECT_HOLDER,BUILT_IN_ADDED_BY,OFFICIAL_REPO_NAME,OFFICIAL_REPO_URL,OFFICIAL_REPO_IDENTITY,OFFICIAL_REPO_PROVIDER,CORE_NAMESPACE,CORE_RECIPE_NAME,CORE_RECIPE_KEY,PACKAGED_RECIPES_DIRNAME,CORE_RECIPE_PATH,DEFAULT_FRESHNESS_SECONDS,DEFAULT_STRATEGY_MEMORY_SECONDS,CONTRIBUTORS,init_constants=__esm({"../sous-plugin-recipes/src/part-b/constants.ts"(){"use strict";RECIPES_PLUGIN="@sous-io/sous-plugin-recipes",LOCKFILE_NAME="sous.lock.json",LINKS_FILE_NAME="sous.links.json",PROJECT_REPOS_DIRNAME="repos",TYPES_DIRNAME="types",PROJECT_HOLDER="project",BUILT_IN_ADDED_BY="sous",OFFICIAL_REPO_NAME="sous-recipes",OFFICIAL_REPO_URL="https://github.com/sous-io/sous-recipes",OFFICIAL_REPO_IDENTITY="github.com/sous-io/sous-recipes",OFFICIAL_REPO_PROVIDER="github",CORE_NAMESPACE="core",CORE_RECIPE_NAME="sous-skills",CORE_RECIPE_KEY=`${CORE_NAMESPACE}/${CORE_RECIPE_NAME}`,PACKAGED_RECIPES_DIRNAME="recipes",CORE_RECIPE_PATH=`${PACKAGED_RECIPES_DIRNAME}/${CORE_NAMESPACE}/${CORE_RECIPE_NAME}`,DEFAULT_FRESHNESS_SECONDS=300,DEFAULT_STRATEGY_MEMORY_SECONDS=10080*60,CONTRIBUTORS={core:"recipes.core",fetch:"recipes.fetch",configLayers:"recipes.config-layers",plugins:"recipes.plugins"}}});import fs30 from"node:fs";import path40 from"node:path";function builtInRepoEntry(){return{url:OFFICIAL_REPO_URL,provider:OFFICIAL_REPO_PROVIDER,addedBy:BUILT_IN_ADDED_BY}}function builtInCoreSubscription(version2){return{range:version2,addedBy:BUILT_IN_ADDED_BY}}function isBuiltInEntry(entry){return entry?.addedBy===BUILT_IN_ADDED_BY}function packagedCoreRecipeDir(packageRoot){let root=path40.resolve(packageRoot);for(let tries=0;tries<4;tries+=1){let candidate=path40.join(root,PACKAGED_RECIPES_DIRNAME,CORE_NAMESPACE,CORE_RECIPE_NAME);if(fs30.existsSync(candidate))return candidate;let parent=path40.dirname(root);if(parent===root)break;root=parent}}function coreIndexOverlay(options2){let warned=!1,packagedHash=()=>typeof options2.hash=="function"?options2.hash():options2.hash;return(identity2,index)=>{if(identity2!==OFFICIAL_REPO_IDENTITY)return index;let hash2=packagedHash();if(hash2===void 0)return index;let recipe=index.recipes[CORE_RECIPE_KEY],published=recipe?.versions[options2.version];if(published!==void 0)return published.hash!==hash2&&!warned&&(warned=!0,options2.onMismatch?.(published.hash,hash2)),index;let description=recipe?.description??(typeof options2.description=="function"?options2.description():options2.description);return{...index,namespaces:{...index.namespaces,[CORE_NAMESPACE]:index.namespaces[CORE_NAMESPACE]??{description:CORE_NAMESPACE_DESCRIPTION}},recipes:{...index.recipes,[CORE_RECIPE_KEY]:{...recipe,path:recipe?.path??CORE_RECIPE_PATH,...description===void 0?{}:{description},versions:{...recipe?.versions,[options2.version]:{hash:hash2,tag:`${CORE_RECIPE_KEY}@${options2.version}`,prerelease:import_semver3.default.prerelease(options2.version)!==null,seeded:!0}}}}}}}var import_semver3,CORE_NAMESPACE_DESCRIPTION,init_core_recipe=__esm({"../sous-plugin-recipes/src/part-b/core/core-recipe.ts"(){"use strict";import_semver3=__toESM(require_semver2(),1);init_constants();CORE_NAMESPACE_DESCRIPTION="Skills that teach an agent about sous itself: what sous manages, how its configuration works, how templates render, and how skills are written. Auto-subscribed in every project, with opt-out-only semantics."}});function publishedOrRetired(index,key){if(Object.hasOwn(index.recipes,key))return{entry:index.recipes[key],retired:!1};let retired=index.retired;return retired!==void 0&&Object.hasOwn(retired,key)?{entry:retired[key],retired:!0}:void 0}function splitStoredKey(key){let slash=key.indexOf("/");return slash===-1?{namespace:key,name:""}:{namespace:key.slice(0,slash),name:key.slice(slash+1)}}function identitySegments2(identity2){return identity2.split("/").filter(segment=>segment.length>0&&segment!=="."&&segment!=="..")}function enabledEntries(entries){let kept={};for(let[key,entry]of Object.entries(entries??{}))entry&&typeof entry=="object"&&entry.enabled!==!1&&(kept[key]=entry);return kept}function trustedWhileBuilding(repos){let kept={};for(let[name,entry]of Object.entries(enabledEntries(repos)))typeof entry.url=="string"&&(kept[name]=entry);return kept}function enabledSubscriptions(subscriptions){return enabledEntries(subscriptions)}function hostFor(hosts,url2,provider){if(provider!==void 0){let named=hosts.find(host=>host.id===provider);if(named)return named}return hosts.find(host=>{try{return host.matches(url2)}catch{return!1}})}function messageOf5(error51){return error51 instanceof Error?error51.message:String(error51)}function sortKeys2(keys){return[...keys].sort((left,right)=>left<right?-1:left>right?1:0)}function plural(count2,one,many=`${one}s`){return`${count2} ${count2===1?one:many}`}var init_support=__esm({"../sous-plugin-recipes/src/part-b/support.ts"(){"use strict"}});import{ConfigError as ConfigError26}from"@sous-io/sous-plugin-api";function emptyLockfile(){return{formatVersion:1,repos:{},recipes:{}}}function lockedVersions(entry){return[{version:entry.version,hash:entry.hash},...sortKeys2(Object.keys(entry.pins??{})).map(holder=>({...entry.pins[holder],holder}))]}function restoredLabel(key,locked){return locked.holder===void 0?key:`${key} version ${locked.version} for ${locked.holder}`}function heldVersions(lock,except=[]){let skipped=new Set(except),keep={},keepPins={};for(let[key,entry]of Object.entries(lock.recipes))skipped.has(key)||(keep[key]=entry.version,entry.pins!==void 0&&Object.keys(entry.pins).length>0&&(keepPins[key]=Object.fromEntries(Object.entries(entry.pins).map(([holder,pin])=>[holder,pin.version]))));return{keep,keepPins}}function withHolders(entry,holders){let{pins:previous,...rest}=entry,pins=Object.fromEntries(Object.entries(previous??{}).filter(([holder])=>holders.includes(holder)));return{...rest,requestedBy:[...holders],...Object.keys(pins).length===0?{}:{pins:sortObjectKeys2(pins)}}}function sortObjectKeys2(value){return Object.fromEntries(sortKeys2(Object.keys(value)).map(key=>[key,value[key]]))}function sortRecipes(recipes){let sorted2={};for(let key of sortKeys2(Object.keys(recipes)))sorted2[key]=recipes[key];return sorted2}function applyResolution(lock,resolved,repos,identityOf3=()=>{}){let recipes={...lock.recipes};for(let recipe of resolved){let previous=lock.recipes[recipe.key],holders=new Set([...previous?.requestedBy??[],...recipe.requestedBy]),pins={};for(let[holder,pin]of Object.entries(previous?.pins??{}))recipe.requestedBy.includes(holder)||(pins[holder]=pin);for(let pin of recipe.pins??[])pins[pin.holder]={version:pin.version,hash:pin.hash};recipes[recipe.key]=withHolders({repo:recipe.repo,version:recipe.version,hash:recipe.hash,requestedBy:[],kind:previous?.kind==="subscribes"||recipe.kind==="subscribes"?"subscribes":"depends",pins},sortKeys2(holders))}let lockedRepos={};for(let name of usedRepos(recipes)){let known=repos[name],previous=lock.repos[name],url2=known?.url??previous?.url;if(url2===void 0)throw new ConfigError26(`The lockfile cannot record the recipes from '${name}' because nothing knows that repository's URL.`,{details:["Add it with 'sous repo add <url>', so the lockfile can name where its recipes came from."]});let identity2=known?.identity??previous?.identity??identityOf3(url2),indexHash=known?.indexHash??previous?.indexHash;lockedRepos[name]={url:url2,...identity2===void 0?{}:{identity:identity2},...indexHash===void 0?{}:{indexHash}}}return{formatVersion:1,repos:lockedRepos,recipes:sortRecipes(recipes)}}function removeHolder(lock,holder,label=LOCKFILE_LABEL){let recipes={};for(let[key,entry]of Object.entries(lock.recipes))recipes[key]={...entry,requestedBy:[...entry.requestedBy]};let pending=[holder];for(;pending.length>0;){let going=new Set(pending);pending=[];for(let[key,entry]of Object.entries(recipes)){let kept=entry.requestedBy.filter(name=>!going.has(name));kept.length!==entry.requestedBy.length&&(kept.length===0?(delete recipes[key],pending.push(key)):recipes[key]=withHolders(entry,kept))}}return withReposOf(lock,recipes,label)}function withReposOf(lock,recipes,label){let lockedRepos={},orphaned=[];for(let name of usedRepos(recipes)){let entry=lock.repos[name];if(entry===void 0){orphaned.push(name);continue}lockedRepos[name]=entry}if(orphaned.length>0)throw new ConfigError26(`The lockfile at ${label} pins recipes to repositories it does not describe: ${orphaned.join(", ")}.`,{details:["Every repository a locked recipe came from needs an entry in the lockfile's 'repos' block.","This usually means the file was edited by hand or merged badly. Run 'sous lock rebuild' to rebuild it from your config."]});return{formatVersion:1,repos:lockedRepos,recipes:sortRecipes(recipes)}}function usedRepos(recipes){return sortKeys2(new Set(Object.values(recipes).map(entry=>entry.repo)))}function lockedClosure(lock,roots){let reached=new Set([...roots].filter(key=>Object.hasOwn(lock.recipes,key))),queue=[...reached];for(;queue.length>0;){let holder=queue.shift();for(let[key,entry]of Object.entries(lock.recipes))!reached.has(key)&&entry.requestedBy.includes(holder)&&(reached.add(key),queue.push(key))}return sortKeys2(reached)}function keysHeldBySubscription(lock,key){let heldByProject=entry=>lock.recipes[entry]?.requestedBy.includes(PROJECT_HOLDER)===!0;return key.includes("/")?heldByProject(key)?[key]:[]:sortKeys2(Object.keys(lock.recipes).filter(entry=>entry.startsWith(`${key}/`)&&heldByProject(entry)))}function byKey(left,right){let one=`${left.key}\0${left.holder??""}`,other=`${right.key}\0${right.holder??""}`;return one<other?-1:one>other?1:0}function diffLockfiles(before,after){let added=[],removed=[],updated=[],changed2=[];for(let[key,entry]of Object.entries(after.recipes)){let previous=before.recipes[key];if(previous===void 0)added.push({key,to:entry.version});else if(previous.version!==entry.version)updated.push({key,from:previous.version,to:entry.version});else{let from=sortKeys2(previous.requestedBy),to=sortKeys2(entry.requestedBy),holdersChanged=from.join(`
444
444
  `)!==to.join(`
445
445
  `),kindChanged=previous.kind!==entry.kind;(holdersChanged||kindChanged)&&changed2.push({key,version:entry.version,...holdersChanged?{requestedBy:{from,to}}:{},...kindChanged?{kind:{from:previous.kind,to:entry.kind}}:{}})}for(let holder of sortKeys2(new Set([...Object.keys(entry.pins??{}),...Object.keys(previous?.pins??{})]))){let from=previous?.pins?.[holder]?.version,to=entry.pins?.[holder]?.version;from!==to&&(from===void 0?added.push({key,holder,to}):to===void 0?removed.push({key,holder,from}):updated.push({key,holder,from,to}))}}for(let[key,entry]of Object.entries(before.recipes))if(!Object.hasOwn(after.recipes,key)){removed.push({key,from:entry.version});for(let[holder,pin]of Object.entries(entry.pins??{}))removed.push({key,holder,from:pin.version})}let reposAdded=sortKeys2(Object.keys(after.repos).filter(name=>!Object.hasOwn(before.repos,name))),reposRemoved=sortKeys2(Object.keys(before.repos).filter(name=>!Object.hasOwn(after.repos,name)));return added.sort(byKey),removed.sort(byKey),updated.sort(byKey),changed2.sort((left,right)=>left.key<right.key?-1:left.key>right.key?1:0),{added,removed,updated,changed:changed2,reposAdded,reposRemoved,unchanged:added.length+removed.length+updated.length+changed2.length+reposAdded.length+reposRemoved.length===0}}function holdersInWords(holders){return holders.length===0?"nothing":holders.map(holder=>holder===PROJECT_HOLDER?"this project":holder).join(", ")}function kindInWords(kind){return kind==="depends"?"a dependency":"a subscription"}function describeEntryChange(change){let lines3=[];return change.requestedBy!==void 0&&lines3.push(`Keeping ${change.key} version ${change.version}, now needed by ${holdersInWords(change.requestedBy.to)} (before: ${holdersInWords(change.requestedBy.from)})`),change.kind!==void 0&&lines3.push(`Keeping ${change.key} version ${change.version}, now pinned as ${kindInWords(change.kind.to)} (before: as ${kindInWords(change.kind.from)})`),lines3}function describeLockDiff(diff){let lines3=[];for(let name of diff.reposAdded)lines3.push(`Repository added: ${name}`);let alone2=change=>change.holder===void 0?"":` for ${change.holder} alone`;for(let change of[...diff.added].sort(byKey))lines3.push(`Adding ${change.key} version ${change.to}${alone2(change)}`);for(let change of[...diff.updated].sort(byKey)){let down=change.from!==void 0&&change.to!==void 0&&import_semver4.default.valid(change.from)!==null&&import_semver4.default.valid(change.to)!==null&&import_semver4.default.lt(change.to,change.from);lines3.push(down?`Moving ${change.key} down from version ${change.from} to version ${change.to}${alone2(change)}`:`Updating ${change.key} from version ${change.from} to version ${change.to}${alone2(change)}`)}for(let change of[...diff.removed].sort(byKey))lines3.push(change.holder===void 0?`Removing ${change.key}, which nothing needs any more`:`Removing the version ${change.from} of ${change.key} pinned for ${change.holder} alone`);for(let change of diff.changed)lines3.push(...describeEntryChange(change));for(let name of diff.reposRemoved)lines3.push(`Repository no longer needed: ${name}`);return diff.unchanged&&lines3.push("Nothing changed."),lines3}var import_semver4,LOCKFILE_LABEL,init_lockfile_ops=__esm({"../sous-plugin-recipes/src/part-b/lock/lockfile-ops.ts"(){"use strict";import_semver4=__toESM(require_semver2(),1);init_constants();init_support();LOCKFILE_LABEL="the lockfile"}});function dropProjectHold(lock,key){let entry=lock.recipes[key];if(entry===void 0)return lock;let kept=entry.requestedBy.filter(holder=>holder!==PROJECT_HOLDER),recipes={...lock.recipes};return kept.length>0?(recipes[key]=withHolders(entry,kept),{...lock,recipes}):(delete recipes[key],removeHolder({...lock,recipes},key))}function covers(cover,key){return cover!==void 0&&(key===cover||key.startsWith(`${cover}/`))}function releaseDroppedHolds(lock,merged,resolvedCovers,otherCovers){let recipes={...lock.recipes},orphaned=[];for(let[key,entry]of Object.entries(lock.recipes)){let settled=merged.get(key),kept=entry.requestedBy.filter(holder=>holder===PROJECT_HOLDER?!resolvedCovers.some(cover=>covers(cover,key))||otherCovers.some(cover=>covers(cover,key))?!0:settled?.requestedBy.includes(PROJECT_HOLDER)===!0:!merged.has(holder)||settled?.requestedBy.includes(holder)===!0);kept.length!==entry.requestedBy.length&&(kept.length===0?(delete recipes[key],orphaned.push(key)):recipes[key]=withHolders(entry,kept))}let result={...lock,recipes};for(let key of orphaned)result=removeHolder(result,key);return result}function stayedAfter(after,held){return[...new Set(held)].filter(key=>Object.hasOwn(after.recipes,key)).sort(compareBytewise2).map(key=>({key,heldBy:[...after.recipes[key].requestedBy]}))}function builtInMoves(lock,subscriptions){let moves=[];for(let subscription of Object.keys(subscriptions).sort(compareBytewise2)){let entry=subscriptions[subscription],to=entry?.range===void 0?null:import_semver5.default.valid(entry.range);if(!(!isBuiltInEntry(entry)||entry?.enabled===!1||to===null))for(let key of keysHeldBySubscription(lock,subscription)){let from=lock.recipes[key].version;import_semver5.default.satisfies(from,to,{includePrerelease:!0,loose:!0})||moves.push({subscription,key,from,to})}}return moves}var import_semver5,init_lock_holds=__esm({"../sous-plugin-recipes/src/part-a/lock-holds.ts"(){"use strict";init_constants();import_semver5=__toESM(require_semver2(),1);init_core_recipe();init_lockfile_ops();init_util2();init_constants();init_lockfile_ops()}});function withoutDisabled(entries){return enabledEntries(typeof entries=="object"&&entries!==null&&!Array.isArray(entries)?entries:void 0)}var USER_ADDED_BY,init_defaults=__esm({"../sous-plugin-recipes/src/part-a/defaults.ts"(){"use strict";init_support();init_constants();init_core_recipe();USER_ADDED_BY="user"}});function configuredRepos(config2){return entryMap(config2.get("repos"))}function trustedRepos(config2){return withoutDisabled(config2.get("repos"))}function configuredSubscriptions(config2){return entryMap(config2.get("subscriptions"))}function enabledSubscriptions2(config2){return withoutDisabled(config2.get("subscriptions"))}function setBy(config2,path122){let layers=config2.layers([...path122]),last2=layers[layers.length-1];return last2===void 0?void 0:contributorLabel(last2.contributor)}function contributorLabel(contributor){return contributor.startsWith("confd/")?`conf.d/${contributor.slice(6)}`:contributor}function managedContributor(file2){return`confd/${file2}`}async function managedEntries(managed,file2,key){let data=await managed.read(file2);return entryMap(data?.[key])}function writeRepoEntry(managed,name,entry,dryRun4=!1){return managed.edit(REPOS_LAYER,root=>root.atPath(["repos",name]).set(entry),{description:REPOS_HEADER,dryRun:dryRun4})}function deleteRepoEntry(managed,name,dryRun4=!1){return managed.edit(REPOS_LAYER,root=>root.atPath(["repos",name]).delete(),{description:REPOS_HEADER,dryRun:dryRun4})}function writeSubscriptionEntry(managed,key,entry,dryRun4=!1){return managed.edit(SUBSCRIPTIONS_LAYER,root=>root.atPath(["subscriptions",key]).set(entry),{description:SUBSCRIPTIONS_HEADER,dryRun:dryRun4})}function deleteSubscriptionEntry(managed,key,dryRun4=!1){return managed.edit(SUBSCRIPTIONS_LAYER,root=>root.atPath(["subscriptions",key]).delete(),{description:SUBSCRIPTIONS_HEADER,dryRun:dryRun4})}async function clearSubscriptionEnabled(managed,key,options2={}){let entry=(await managedEntries(managed,SUBSCRIPTIONS_LAYER,"subscriptions"))[key],holdsEnabled=entry!==null&&typeof entry=="object"&&Object.hasOwn(entry,"enabled"),nothingElse=holdsEnabled&&Object.keys(entry).every(field=>field==="enabled");return managed.edit(SUBSCRIPTIONS_LAYER,root=>{holdsEnabled&&root.atPath(nothingElse&&options2.dropEmpty===!0?["subscriptions",key]:["subscriptions",key,"enabled"]).delete()},{description:SUBSCRIPTIONS_HEADER,dryRun:options2.dryRun===!0})}function setSubscriptionEnabled(managed,key,enabled,dryRun4=!1){return managed.edit(SUBSCRIPTIONS_LAYER,root=>root.atPath(["subscriptions",key,"enabled"]).set(enabled),{description:SUBSCRIPTIONS_HEADER,dryRun:dryRun4})}var REPOS_LAYER,SUBSCRIPTIONS_LAYER,REPOS_HEADER,SUBSCRIPTIONS_HEADER,init_project=__esm({"../sous-plugin-recipes/src/part-a/project.ts"(){"use strict";init_defaults();init_util2();REPOS_LAYER="500-repos.jsonc",SUBSCRIPTIONS_LAYER="510-subscriptions.jsonc",REPOS_HEADER=["The recipe repositories this project trusts, written by `sous repo add`.","Sous edits this file key by key; your own edits outside the keys it touches are kept."],SUBSCRIPTIONS_HEADER=["What this project subscribes to, written by `sous subscription add`.","Sous edits this file key by key; your own edits outside the keys it touches are kept."]}});function reachableKeys(lock,subscriptions){let roots=Object.entries(subscriptions).filter(([,entry])=>entry?.enabled!==!1).flatMap(([key])=>keysHeldBySubscription(lock,key));return lockedClosure(lock,roots)}function joinNames(names2){return names2.length<=1?names2[0]??"":`${names2.slice(0,-1).join(", ")} and ${names2[names2.length-1]}`}function stillBuilt(lock,subscriptions,built,setByOf=()=>{}){let found=[],seen=new Set;for(let subscription of Object.keys(subscriptions).sort(compareBytewise2))if(subscriptions[subscription]?.enabled===!1)for(let key of keysHeldBySubscription(lock,subscription)){let neededBy=[...new Set(lock.recipes[key].requestedBy.filter(holder=>holder!==PROJECT_HOLDER&&built.has(holder)))].sort(compareBytewise2);if(seen.has(key)||!built.has(key)||neededBy.length===0)continue;seen.add(key);let setBy2=setByOf(subscription);found.push({key,subscription,neededBy,...setBy2===void 0?{}:{setBy:setBy2},message:`${key} is switched off but still built: ${joinNames(neededBy)} ${neededBy.length===1?"depends":"depend"} on it.`})}return found}var ActiveRecipes,init_active=__esm({"../sous-plugin-recipes/src/part-a/active.ts"(){"use strict";init_lock_holds();init_project();init_util2();ActiveRecipes=class{constructor(config2,services){this.config=config2;this.services=services}skippedCache;list(){let order=Object.keys(this.lockfile().recipes),position=id=>{let index=order.indexOf(id);return index===-1?order.length:index};return[...this.config.entities.list("active-recipe")].sort((left,right)=>position(left.id)-position(right.id)||compareBytewise2(left.id,right.id))}get(key){return this.config.entities.get("active-recipe",key)}skipped(){return this.skippedCache??=this.findSkipped(),this.skippedCache}switchedOffButBuilt(){let active=new Set(this.config.entities.list("active-recipe").map(entity=>entity.id));return stillBuilt(this.lockfile(),configuredSubscriptions(this.config),active,subscription=>setBy(this.config,["subscriptions",subscription,"enabled"]))}contents(kind){return this.services.get("recipes.contents").of(this.config,kind)}variables(){return this.list().flatMap(recipe=>(recipe.manifest.variables??[]).map(definition2=>({recipe,definition:definition2})))}lockfile(){try{return this.services.get("recipes.lock").read()}catch{return emptyLockfile()}}reachable(lock){try{return new Set(this.services.get("recipes.resolver").reachable(lock))}catch{return new Set(reachableKeys(lock,configuredSubscriptions(this.config)))}}findSkipped(){let lock=this.lockfile(),active=new Set(this.config.entities.list("active-recipe").map(entity=>entity.id)),reachable2=this.reachable(lock),repos=configuredRepos(this.config),subscriptions=configuredSubscriptions(this.config),skipped=[];for(let[key,entry]of Object.entries(lock.recipes)){if(active.has(key))continue;let repo=repos[entry.repo];if(repo===void 0){skipped.push({key,reason:"untrusted",message:`Skipped ${key}: this project does not trust its repository '${entry.repo}'.`});continue}if(repo.enabled===!1){let file2=setBy(this.config,["repos",entry.repo,"enabled"]);skipped.push({key,reason:"repository-disabled",...file2===void 0?{}:{setBy:file2},message:`Skipped ${key}: its repository '${entry.repo}' is switched off${file2===void 0?"":` (${file2})`}.`});continue}if(reachable2.has(key)){skipped.push({key,reason:"missing",message:`Skipped ${key}: its files are not on this machine yet.`});continue}let off=Object.keys(subscriptions).sort(compareBytewise2).find(subscription=>subscriptions[subscription]?.enabled===!1&&lockedClosure(lock,keysHeldBySubscription(lock,subscription)).includes(key));if(off!==void 0){let file2=setBy(this.config,["subscriptions",off,"enabled"]),where3=file2===void 0?"":` (${file2})`,indirect=!keysHeldBySubscription(lock,off).includes(key);skipped.push({key,reason:"subscription-disabled",subscription:off,...indirect?{indirect:!0}:{},...file2===void 0?{}:{setBy:file2},message:indirect?`Skipped ${key}: reached only through ${off}, which is switched off${where3}.`:`Skipped ${key}: its subscription is switched off${where3}.`});continue}skipped.push({key,reason:"not-reached",message:`Skipped ${key}: no subscription in force reaches it.`})}return skipped}}}});import{jsonSchema as jsonSchema12}from"@sous-io/sous-plugin-api";function objectOf2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)?value:void 0}function isRepoUrl(url2){return/^[a-z][a-z0-9+.-]*:\/\/\S+$/i.test(url2)||/^[\w.-]+@[\w.-]+:\S+$/.test(url2)||url2.startsWith("/")||/^[A-Za-z]:[\\/]/.test(url2)}function checked2(schema,more){let standard=jsonSchema12(schema)["~standard"];return{"~standard":{...standard,validate(value){let result=standard.validate(value),object3=objectOf2(value),extra=object3===void 0?[]:more(object3);return extra.length===0?result:{issues:[...result.issues??[],...extra]}}}}}function repoIssues(repos){let issues=[];for(let[name,entry]of Object.entries(repos)){REPO_NAME_PATTERN2.test(name)||issues.push({path:[name],message:"invalid key; a repo name must be lowercase kebab-case: a letter, then letters, digits or hyphens (for example 'sous-recipes')"});let url2=objectOf2(entry)?.url;typeof url2=="string"&&!isRepoUrl(url2)&&issues.push({path:[name,"url"],message:"must be a repository URL, or an absolute path to one on this machine"})}return issues}function subscriptionIssues(subscriptions){let issues=[];for(let[key,entry]of Object.entries(subscriptions)){SUBSCRIPTION_KEY_PATTERN.test(key)||issues.push({path:[key],message:"invalid key; a subscription key must be a namespace ('workflow') or a namespace and recipe ('workflow/task-files'), with no repository qualifier and no version range (the range goes in the entry)"});let range3=objectOf2(entry)?.range;typeof range3=="string"&&import_semver6.default.validRange(range3)===null&&issues.push({path:[key,"range"],message:"must be a semantic version range, such as '^1.2.0', '~2.1', '>=1.0.0 <2.0.0' or '*'"})}return issues}function storeIssues(store2){let issues=[];for(let name of["maxBytes","freshnessSeconds","watchPollSeconds","strategyMemorySeconds"]){let value=store2[name];typeof value=="number"&&(!Number.isInteger(value)||(name==="maxBytes"?value<=0:value<0))&&issues.push({path:[name],message:name==="maxBytes"?"must be a whole number of bytes, above zero":"must be a whole number of seconds, zero or more"})}return issues}function configKeys(){return[{id:"repos",description:"The repositories this project trusts, by short name.",schema:checked2({type:"object",default:{},additionalProperties:repoEntry},repoIssues)},{id:"subscriptions",description:"What this project subscribes to, keyed by namespace or namespace/recipe.",schema:checked2({type:"object",default:{},additionalProperties:subscriptionEntry},subscriptionIssues)},{id:"store",description:"The machine-wide recipe store's settings.",schema:checked2(store,storeIssues)}]}var import_semver6,DEFAULT_STORE_MAX_BYTES,DEFAULT_FRESHNESS_SECONDS2,DEFAULT_WATCH_POLL_SECONDS,repoEntry,subscriptionEntry,store,SUBSCRIPTION_KEY_PATTERN,init_config_keys=__esm({"../sous-plugin-recipes/src/part-a/config-keys.ts"(){"use strict";import_semver6=__toESM(require_semver2(),1);init_constants();init_util2();DEFAULT_STORE_MAX_BYTES=1024*1024*1024,DEFAULT_FRESHNESS_SECONDS2=300,DEFAULT_WATCH_POLL_SECONDS=300,repoEntry={type:"object",description:"One trusted repository. Adding it trusts it.",properties:{url:{type:"string",description:"Where the repository lives."},enabled:{type:"boolean",description:"False opts out of a repository sous provides itself."},provider:{type:"string",description:"The repository host, when the URL does not give it away."},alwaysPull:{type:"boolean",description:"Install a newer in-range version whenever one exists."},addedAt:{type:"string"},addedBy:{type:"string"}},required:["url"],additionalProperties:!1},subscriptionEntry={type:"object",description:"One subscription, to a namespace or to one recipe.",properties:{enabled:{type:"boolean",description:"False switches it off, keeping its pins, wherever the file that sets it applies: for everyone in a committed file, for one machine in a conf.d file kept out of git."},range:{type:"string",description:"The version range. Default `*`."},prerelease:{type:"boolean"},alwaysPull:{type:"boolean"},addedAt:{type:"string"},addedBy:{type:"string"}},additionalProperties:!1},store={type:"object",description:"The machine-wide recipe store.",default:{},properties:{maxBytes:{type:"integer",default:DEFAULT_STORE_MAX_BYTES,description:"Size cap past which old entries are collected."},freshnessSeconds:{type:"integer",default:DEFAULT_FRESHNESS_SECONDS2,description:"How long a fetched index stays fresh."},watchPollSeconds:{type:"integer",default:DEFAULT_WATCH_POLL_SECONDS,description:"How often watch mode checks upstream."},strategyMemorySeconds:{type:"integer",default:DEFAULT_STRATEGY_MEMORY_SECONDS,description:"How long, in seconds, a way of reading a repository's index or downloading its recipes that worked stays the one tried first, counted from when it became first. The default, 604800 (seven days), means a repository read through git because its token failed goes back to trying the token first a week later. 0 always tries the host's usual order first; any whole number of seconds is accepted."}},additionalProperties:!1},SUBSCRIPTION_KEY_PATTERN=/^[a-z][a-z0-9-]*(\/[a-z][a-z0-9-]*)?$/}});function foldDeclaration(before,entry){let keepBefore=before!==void 0&&!entry.named;return{declared:keepBefore?before.declared:entry.written.trim(),ref:keepBefore?before.ref:entry.ref,kind:before?.kind==="subscribes"||entry.kind==="subscribes"?"subscribes":"depends",named:entry.named||before?.named===!0}}function isNamed(ref){return ref.kind==="namespace"||ref.kind==="recipe"}var Declarations,init_declarations=__esm({"../sous-plugin-recipes/src/part-a/declarations.ts"(){"use strict";Declarations=class{constructor(resolver,format3){this.resolver=resolver;this.format=format3}of(source){let found=[];for(let[kind,entries]of this.lists(source))for(let written of entries){let ref=this.readings(written)[0];ref&&found.push({declared:written.trim(),kind,ref,named:ref.kind==="recipe"})}return found}covering(source,key){let format3=this.format(),gathered;for(let[kind,entries]of[...this.lists(source)].reverse())for(let written of entries)for(let ref of this.readings(written)){let named=ref.kind==="recipe";if(named?format3.key(ref)===key:format3.namespaceOfKey(key)===ref.name){gathered=foldDeclaration(gathered,{written,kind,named,ref});break}}return gathered}lists(source){return[["subscribes",source.subscribes??[]],["depends",source.depends??[]]]}readings(written){try{return this.resolver().parse(written,"manifest").refs.filter(isNamed)}catch{return[]}}}}});import{SousError as SousError15}from"@sous-io/sous-plugin-api";function namespaceOfKey3(key){let slash=key.indexOf("/");return slash===-1?key:key.slice(0,slash)}function splitRecipeKey(key){let slash=key.indexOf("/");return{namespace:key.slice(0,slash),name:key.slice(slash+1)}}function listNamespaces(inputs){let subscriptions=new Set(inputs.subscriptions),listings=[];for(let repo of inputs.repos)for(let[namespace,declared]of Object.entries(repo.index.namespaces))listings.push({repo:repo.name,namespace,...declared.description===void 0?{}:{description:declared.description},recipeCount:recipeKeysIn(repo.index,namespace).length,subscribed:coverageOf(namespace,repo.index,subscriptions)});return listings.sort((left,right)=>compareBytewise2(left.namespace,right.namespace)||compareBytewise2(left.repo,right.repo))}function listRecipes(inputs){let subscriptions=new Set(inputs.subscriptions),listings=[];for(let repo of inputs.repos)for(let key of Object.keys(repo.index.recipes))listings.push(recipeListing(key,repo,inputs,subscriptions));return listings.sort((left,right)=>compareBytewise2(left.key,right.key)||compareBytewise2(left.repo,right.repo))}function describeNamespace(inputs,found){let subscriptions=new Set(inputs.subscriptions),declared=found.repo.index.namespaces[found.namespace]??{};return{repo:found.repo.name,...found.repo.url===void 0?{}:{repoUrl:found.repo.url},namespace:found.namespace,...declared.description===void 0?{}:{description:declared.description},subscribed:coverageOf(found.namespace,found.repo.index,subscriptions),recipes:recipeKeysIn(found.repo.index,found.namespace).map(key=>recipeListing(key,found.repo,inputs,subscriptions))}}function describedLocation(inputs,found){let listing=recipeListing(found.key,found.repo,inputs,new Set(inputs.subscriptions)),version2=listing.pinned??listing.latest,entry=found.repo.index.recipes[found.key];return version2===void 0?void 0:{key:found.key,namespace:listing.namespace,name:listing.name,repo:found.repo.name,version:version2,path:entry.path}}function writtenGroup(written){if(isManifestExpression(written)||typeof written!="object"||written===null)return{kind:CONDITIONAL_TEXT,include:[CONDITIONAL_TEXT]};let group=written,include=Array.isArray(group.include)?group.include:[];return{kind:typeof group.kind=="string"?group.kind:CONDITIONAL_TEXT,include:include.map(item=>typeof item=="string"?item:isInline(item)?`(inline) ${item.path}`:CONDITIONAL_TEXT)}}function describeRecipe(inputs,found,manifest){let subscriptions=new Set(inputs.subscriptions),listing=recipeListing(found.key,found.repo,inputs,subscriptions),entry=found.repo.index.recipes[found.key],describing=listing.pinned??listing.latest,published=describing===void 0?void 0:entry.versions[describing];return{...listing,...found.repo.url===void 0?{}:{repoUrl:found.repo.url},path:entry.path,...describing===void 0?{}:{describing},versions:versionListings(entry.versions,listing.latest,listing.pinned),dependencies:dependencyListings(published?.dependencies,manifest,inputs),dependenciesRecorded:published?.dependencies!==void 0,contents:(manifest?.contents??[]).map(written=>{let content=writtenGroup(written);return{...content,destinations:inputs.destinationsFor?.(content.kind)??[]}}),variables:manifest?.variables??published?.variables??[],manifestRead:manifest!==void 0}}function narrowToInstalled(inputs){let repos=inputs.repos.map(repo=>{let recipes=Object.fromEntries(Object.entries(repo.index.recipes).filter(([key])=>inputs.lock.recipes[key]?.repo===repo.name)),held=new Set(Object.keys(recipes).map(namespaceOfKey3)),namespaces=Object.fromEntries(Object.entries(repo.index.namespaces).filter(([namespace])=>held.has(namespace)));return{...repo,index:{...repo.index,recipes,namespaces}}});return{...inputs,repos}}function repoOf2(ref){let repo=ref.kind==="namespace"?ref.repo:ref.namespace?.repo??ref.repo;if(repo!==void 0)return{...repo.name===void 0?{}:{name:repo.name},...repo.location?.identity===void 0?{}:{identity:repo.location.identity}}}function sameText(written,published){return written===published?"exact":written.toLowerCase()===published.toLowerCase()?"folded":void 0}function publishedNamespaceRef(repo,namespace){let declared=repo.index.namespaces[namespace];return{kind:"namespace",name:namespace,repo:{kind:"repo",name:repo.name},...declared?.description===void 0?{}:{description:declared.description}}}function publishedRecipeRef(repo,key){let{namespace,name}=splitRecipeKey(key),description=repo.index.recipes[key]?.description;return{kind:"recipe",name,namespace:{kind:"namespace",name:namespace,repo:{kind:"repo",name:repo.name}},...description===void 0?{}:{description}}}function findInCatalog(inputs,readings,kinds){let matches=new Map,add=match2=>{let id=`${match2.repo.name}:${match2.ref.kind}:${match2.key}`,known=matches.get(id);(known===void 0||!known.exact&&match2.exact)&&matches.set(id,match2)};for(let reading of readings){if(reading.kind!=="namespace"&&reading.kind!=="recipe"||!kinds.includes(reading.kind))continue;let wanted=repoOf2(reading),repos=inputs.repos.filter(repo=>wanted===void 0||wanted.name!==void 0&&sameText(wanted.name,repo.name)!==void 0||wanted.identity!==void 0&&repo.identity!==void 0&&wanted.identity.toLowerCase()===repo.identity.toLowerCase());for(let repo of repos){if(reading.kind==="namespace"){for(let namespace of Object.keys(repo.index.namespaces)){let same=sameText(reading.name,namespace);same&&add({ref:publishedNamespaceRef(repo,namespace),repo,key:namespace,exact:same==="exact"})}continue}for(let key of Object.keys(repo.index.recipes)){let{namespace,name}=splitRecipeKey(key),sameName=sameText(reading.name,name),sameNamespace=reading.namespace===void 0?"exact":sameText(reading.namespace.name,namespace);if(sameName&&sameNamespace){let ref={...publishedRecipeRef(repo,key),...reading.range===void 0?{}:{range:reading.range}};add({ref,repo,key,exact:sameName==="exact"&&sameNamespace==="exact"})}}}}let order=new Map(inputs.repos.map((repo,index)=>[repo.name,index]));return[...matches.values()].sort((left,right)=>Number(right.exact)-Number(left.exact)||(order.get(left.repo.name)??0)-(order.get(right.repo.name)??0)||compareBytewise2(left.key,right.key))}function unknownRefError(inputs,ref,what,notFetched=[]){let searched=inputs.repos.length===0?"none":inputs.repos.map(repo=>repo.name).join(", ");return new SousError15(`No repository this project trusts publishes a ${what} called '${ref}'.`,{details:[`Repositories with an index sous has read: ${searched}.`,...notFetched.length===0?[]:[`These repositories are trusted but their index could not be read, so nothing in them was searched: ${notFetched.join(", ")}.`],`Run 'sous repo search ${ref}' to look for something like it, or 'sous repo add <url>' to add the repository that publishes it.`]})}function recipeKeysIn(index,namespace){return Object.keys(index.recipes).filter(key=>namespaceOfKey3(key)===namespace).sort(compareBytewise2)}function coverageOf(namespace,index,subscriptions){return subscriptions.has(namespace)?"whole namespace":recipeKeysIn(index,namespace).some(key=>subscriptions.has(key))?"some recipes":"none"}function recipeListing(key,repo,inputs,subscriptions){let entry=repo.index.recipes[key],{namespace,name}=splitRecipeKey(key),latest2=latestVersion(entry.versions),locked=inputs.lock.recipes[key],pinned=locked!==void 0&&locked.repo===repo.name?locked.version:void 0,linkedPath=pinned===void 0?void 0:inputs.linked?.[repo.name];return{key,namespace,name,repo:repo.name,...latest2===void 0?{}:{latest:latest2},...pinned===void 0?{}:{pinned},...linkedPath===void 0?{}:{linkedPath},subscribed:subscriptions.has(key)||subscriptions.has(namespace),...entry.description===void 0?{}:{description:entry.description}}}function latestVersion(versions){let all=Object.keys(versions).filter(version2=>import_semver7.default.valid(version2,{loose:!0})!==null),stable=all.filter(version2=>versions[version2]?.prerelease!==!0);return import_semver7.default.maxSatisfying(stable.length>0?stable:all,"*",{includePrerelease:!0,loose:!0})??void 0}function versionListings(versions,latest2,pinned){return Object.keys(versions).sort((left,right)=>{let a=import_semver7.default.valid(left,{loose:!0}),b=import_semver7.default.valid(right,{loose:!0});return a!==null&&b!==null?import_semver7.default.rcompare(a,b,{loose:!0}):compareBytewise2(right,left)}).map(version2=>{let entry=versions[version2];return{version:version2,status:version2===latest2&&version2===pinned?"latest and pinned":version2===latest2?"latest":version2===pinned?"pinned":"other",prerelease:entry.prerelease,...entry.releasedAt===void 0?{}:{releasedAt:entry.releasedAt}}})}function dependencyListings(resolved,manifest,inputs){let rows=new Map,lists=manifest===void 0?void 0:{depends:manifest.depends??[],subscribes:manifest.subscribes??[]};for(let[key,entry]of Object.entries(resolved??{})){let declaration=entry.declared!==void 0&&entry.kind!==void 0?{declared:entry.declared,kind:entry.kind}:lists===void 0?void 0:inputs.declarationFor?.(lists,key);rows.set(key,{key,...entry.version===void 0?{}:{resolvedVersion:entry.version},...entry.range===void 0?{}:{resolvedRange:entry.range},...entry.repo===void 0?{}:{repo:entry.repo},...declaration===void 0?{}:{declared:declaration.declared,kind:declaration.kind}})}let covered=new Set([...rows.values()].map(row=>row.declared));for(let[kind,entries]of[["depends",lists?.depends??[]],["subscribes",lists?.subscribes??[]]])for(let written of entries){if(covered.has(written.trim()))continue;let key=written.trim().replace(/@.*$/,"");rows.set(key,{...rows.get(key)??{key},declared:written,kind})}return[...rows.values()].sort((left,right)=>compareBytewise2(left.key,right.key))}var import_semver7,CONDITIONAL_TEXT,init_catalog=__esm({"../sous-plugin-recipes/src/part-a/catalog.ts"(){"use strict";init_src5();import_semver7=__toESM(require_semver2(),1);init_contents();init_util2();CONDITIONAL_TEXT="(conditional)"}});import path41 from"node:path";function listOf2(ctx,kind){try{return ctx.entities.list(kind)}catch{return[]}}function resolveVariables(ctx,value){if(!value.includes("${")||ctx.services===void 0||!ctx.services.has("variables.resolver"))return value;try{let resolver=ctx.services.get("variables.resolver");return resolver.normalizePath(resolver.substituteStrict(value,resolver.scope({level:"root"}),"recipes.skills.outputs"))}catch{return value}}function withProjectRoot(value,root){return root===void 0?value:value.replace(/\$\{projectRoot\}/g,root)}function underRoot(root,target){return root===void 0||path41.isAbsolute(target)||target.startsWith("${")?target:path41.join(root,target)}function distinct(paths){return[...new Set(paths)].sort(compareBytewise2)}function destinationsFor(ctx,kind){let root=ctx.project?.root;if(kind==="skills"){let targets=listOf2(ctx,"skill-target").map(target=>target.directory).filter(directory=>typeof directory=="string"&&directory.length>0),outputs=ctx.config.get(["recipes","skills","outputs"]),extra=Array.isArray(outputs)?outputs.filter(output=>typeof output=="string"&&output.length>0):[];return distinct([...targets,...extra].map(target=>underRoot(root,resolveVariables(ctx,target))))}return kind==="memories"?distinct(listOf2(ctx,"memory-target").filter(target=>typeof target.outputPath=="string"&&target.outputPath.length>0).map(target=>underRoot(root,resolveVariables(ctx,withProjectRoot(target.outputPath,root))))):[]}var init_destinations=__esm({"../sous-plugin-recipes/src/part-a/destinations.ts"(){"use strict";init_util2()}});import path42 from"node:path";function repoSearchOrder(ctx){let repos=trustedRepos(ctx.config),names2=Object.keys(repos),builtIn=names2.filter(name=>isBuiltInEntry(repos[name]));return[...builtIn,...names2.filter(name=>!builtIn.includes(name))]}function identityOf(ctx,url2){try{return ctx.services.get("refs.locations").identity(url2)}catch{return}}async function readUpstream(ctx,name){let cache2=ctx.services.get("recipes.index-cache"),entry=trustedRepos(ctx.config)[name],identity2=entry===void 0?void 0:identityOf(ctx,entry.url),linked=ctx.services.has("recipes.links")&&ctx.services.get("recipes.links").get(name)!==void 0;if(entry===void 0||identity2===void 0||linked)return cache2.get(name,{latest:!0});let index=await cache2.fetchUpstream({name,url:entry.url,identity:identity2,...entry.provider===void 0?{}:{provider:entry.provider}});return{repo:name,index,source:"network"}}async function readIndexes(ctx,flags){let cache2=ctx.services.get("recipes.index-cache"),sources=new Map,notFetched=[],notChecked=[];for(let name of repoSearchOrder(ctx)){if(flags.latest===!0)try{let read=await readUpstream(ctx,name);read.source==="stale"&&notChecked.push({repo:name,reason:read.problem??"upstream could not be reached"}),sources.set(name,read);continue}catch(error51){notChecked.push({repo:name,reason:describeError2(error51)})}let cached2=cache2.cached(name);cached2===void 0?notFetched.push(name):sources.set(name,cached2)}return{notFetched:notFetched.filter(name=>!sources.has(name)),notChecked,sources}}async function loadCatalog(ctx,flags={}){let read=await readIndexes(ctx,flags),trusted=trustedRepos(ctx.config),repos=[...read.sources.entries()].map(([name,cached2])=>{let url2=trusted[name]?.url,identity2=cached2.meta?.identity??(url2===void 0?void 0:identityOf(ctx,url2));return{name,index:cached2.index,...url2===void 0?{}:{url:url2},...identity2===void 0?{}:{identity:identity2}}}),linked={};if(ctx.services.has("recipes.links"))for(let[name,link]of Object.entries(ctx.services.get("recipes.links").all()))linked[name]=link.path;let lock=emptyLockfile();try{lock=ctx.services.get("recipes.lock").read()}catch{}let declarations=ctx.services.has("recipes.declarations")?ctx.services.get("recipes.declarations"):void 0,inputs={repos,lock,subscriptions:Object.keys(enabledSubscriptions2(ctx.config)).sort(),linked,...ctx.entities===void 0?{}:{destinationsFor:kind=>destinationsFor({entities:ctx.entities,config:ctx.config,project:ctx.project,services:ctx.services},kind)},...declarations===void 0?{}:{declarationFor:(source,key)=>{let found=declarations.covering(source,key);return found===void 0?void 0:{declared:found.declared,kind:found.kind}}}};return{...read,inputs:flags.installed===!0?narrowToInstalled(inputs):inputs}}function recipeFilesDirectory(ctx,catalog,location){let checkout=catalog.linked?.[location.repo];if(checkout!==void 0)return path42.join(checkout,location.path);let identity2=catalog.repos.find(repo=>repo.name===location.repo)?.identity??catalog.lock.repos[location.repo]?.identity;if(identity2!==void 0)try{return ctx.services.get("recipes.store").entryDir({identity:identity2,namespace:location.namespace,name:location.name,version:location.version})}catch{return}}async function readPublishedManifest(ctx,catalog,location){let directory=recipeFilesDirectory(ctx,catalog,location);if(directory!==void 0)try{return(await ctx.services.get("formats.manifests").readRecipe(directory))?.manifest}catch{return}}function readingsOf(ctx,input){return ctx.services.get("refs.resolver").parse(input.trim(),"commandLine").refs}async function pickMatch(ctx,matches,search2,acceptFirst2,none,options2={}){if(matches.length===0)throw none();let exact=matches.filter(match2=>match2.exact),settled=matches.length===1?matches[0]:acceptFirst2===!0?void 0:exact.length===1?exact[0]:void 0;if(options2.announce===!0&&(settled!==void 0||acceptFirst2===!0)){let candidates=settled===void 0?matches:[settled],picked2=await ctx.services.get("refs.picker").pick(candidates.map(match2=>match2.ref),{search:search2,...acceptFirst2===void 0?{}:{acceptFirst:acceptFirst2}},ctx);return candidates.find(match2=>match2.ref===picked2)??candidates[0]}if(settled!==void 0)return settled;if(acceptFirst2===!0)return matches[0];let picked=await ctx.services.get("refs.picker").pick(matches.map(match2=>match2.ref),{search:search2,...acceptFirst2===void 0?{}:{acceptFirst:acceptFirst2}},ctx);return matches.find(match2=>match2.ref===picked)??matches[0]}async function resolveInCatalog(ctx,catalog,input,kinds,acceptFirst2,none){let matches=findInCatalog(catalog.inputs,readingsOf(ctx,input),kinds);return pickMatch(ctx,matches,input.trim(),acceptFirst2,none)}var init_catalog_context=__esm({"../sous-plugin-recipes/src/part-a/catalog-context.ts"(){"use strict";init_catalog();init_defaults();init_destinations();init_lock_holds();init_project();init_util2()}});import{SousError as SousError16}from"@sous-io/sous-plugin-api";function describeUnmet(unmet){return unmet.installed===void 0?`'${unmet.recipe}' requires the plugin ${unmet.plugin} ${unmet.range}, which is not installed.`:`'${unmet.recipe}' requires the plugin ${unmet.plugin} ${unmet.range}, and version ${unmet.installed} is installed.`}function specsOf(unmet){return[...new Set(unmet.map(entry=>`${entry.plugin}@${entry.range}`))]}function unmetRequirements(required2,loaded){let unmet=[];for(let{recipe,plugins}of required2)for(let[plugin,range3]of Object.entries(plugins)){let found=loaded.find(entry=>entry.name===plugin),version2=found?.version;found!==void 0&&(version2===void 0||import_semver8.default.satisfies(version2,range3,{includePrerelease:!0}))||unmet.push({recipe,plugin,range:range3,...found===void 0||version2===void 0?{}:{installed:version2}})}return unmet}async function recipeDirectory(ctx,recipe,download2){let entry=trustedRepos(ctx.config)[recipe.repo];if(!(entry===void 0||!ctx.services.has("recipes.store")||!ctx.services.has("recipes.index-cache"))){if(!download2)try{return(await ctx.services.get("recipes.store").get({identity:recipe.identity,namespace:recipe.namespace,name:recipe.name,version:recipe.version}))?.dir}catch{return}try{return await ensureRecipeFiles(ctx,recipe,entry)}catch{return}}}async function ensureRecipeFiles(ctx,recipe,entry){return(await ctx.services.get("recipes.index-cache").ensureInStore({key:recipe.key,entry:{repo:recipe.repo,version:recipe.version,hash:recipe.hash,requestedBy:recipe.requestedBy,kind:recipe.kind},repo:recipe.repo,url:entry.url,identity:recipe.identity,...entry.provider===void 0?{}:{provider:entry.provider}},{store:ctx.services.get("recipes.store"),hosts:ctx.entities.list("repository-host"),context:{plugin:ctx.plugin,config:ctx.config,services:ctx.services,entities:ctx.entities,project:ctx.project,env:ctx.env,cwd:ctx.cwd,reporter:ctx.reporter}})).dir}async function downloadRecipes(ctx,resolved){if(!ctx.services.has("recipes.store")||!ctx.services.has("recipes.index-cache"))return[];let trusted=trustedRepos(ctx.config),failed=[];for(let recipe of resolved){let entry=trusted[recipe.repo];for(let version2 of[recipe,...(recipe.pins??[]).map(pin=>resolvedAtPin(recipe,pin))]){if(entry===void 0){failed.push({key:recipe.key,version:version2.version,reason:`the repository '${recipe.repo}' is not trusted in this project`});continue}try{await ensureRecipeFiles(ctx,version2,entry)}catch(error51){failed.push({key:recipe.key,version:version2.version,reason:describeError2(error51)})}}}return failed}async function requiredPlugins(ctx,resolved,download2=!0){if(!ctx.services.has("formats.manifests"))return[];let manifests=ctx.services.get("formats.manifests"),required2=[];for(let recipe of resolved){let dir=await recipeDirectory(ctx,recipe,download2);if(dir===void 0)continue;let plugins;try{plugins=(await manifests.readRecipe(dir))?.manifest.requires?.plugins}catch{plugins=void 0}plugins!==void 0&&Object.keys(plugins).length>0&&required2.push({recipe:recipe.key,plugins})}return required2}async function ensureRequiredPlugins(ctx,resolved,flags,ref){let required2=await requiredPlugins(ctx,resolved,flags.dryRun!==!0),unmet=required2.length===0?[]:unmetRequirements(required2,ctx.engine.plugins());if(unmet.length===0)return;let specs=specsOf(unmet);for(let entry of unmet)ctx.reporter.note(describeUnmet(entry));if(flags.dryRun===!0)return{intent:INSTALL_INTENT,skipped:"--dry-run"};let install=flags.installPlugins===!0;if(!install&&ctx.prompter.interactive&&(install=await ctx.prompter.confirm({message:`Install ${specs.join(", ")} now?`,answeredBy:"--install-plugins",default:!0})),!install)throw new SousError16(unmet.length===1?describeUnmet(unmet[0]):`'${ref}' requires plugins that are not installed: ${specs.join(", ")}.`,{details:["Nothing was written.",`Run 'sous subscription add ${ref} --install-plugins' to install ${unmet.length===1?"it":"them"} through this project's package manager, or install ${unmet.length===1?"it":"them"} yourself (for example, 'npm install --save-dev ${specs.join(" ")}').`]});if(!hasIntent(ctx,INSTALL_INTENT))throw new SousError16(`'${ref}' requires ${specs.join(", ")}, and no plugin provides '${INSTALL_INTENT}' to install ${unmet.length===1?"it":"them"}.`,{details:["Nothing was written. Switch on @sous-io/sous-plugin-update, or install the plugins yourself."]});let outputs=await ctx.run(INSTALL_INTENT,{plugins:specs,yes:!0}),result=outputs.toPlain();if(result.declined||result.exitCode!==void 0&&result.exitCode!==0)throw new SousError16(`Sous could not install ${specs.join(", ")}, so nothing was subscribed.`,{details:result.declined?["The install was declined."]:[`${[result.command.command,...result.command.args].join(" ")} exited with code ${result.exitCode}.`,REQUIRED_PLUGIN_HINT]});return{intent:INSTALL_INTENT,result,outputs}}var import_semver8,REQUIRED_PLUGIN_HINT,INSTALL_INTENT,init_required_plugins=__esm({"../sous-plugin-recipes/src/part-a/required-plugins.ts"(){"use strict";import_semver8=__toESM(require_semver2(),1);init_project();init_util2();REQUIRED_PLUGIN_HINT="Perhaps the required plugin ships as part of a recipe?",INSTALL_INTENT="plugins.install"}});import path43 from"node:path";function envFileOf(definition2){return definition2.secret===!0||definition2.scope==="local"?".env.local":".env"}function describeSource(source){let where3=source.file==="shell"?"the shell environment":source.file==="local"?"the .env.local file":"the .env file";return`${source.rung==="bare"?`the ${RUNG_LABELS.bare}`:`the ${RUNG_LABELS[source.rung]??source.rung} name`} ${source.envName}, from ${where3}`}async function variablesOf(ctx,recipe,download2){if(recipe.variables!==void 0)return recipe.variables;if(!ctx.services.has("formats.manifests"))return;let dir=await recipeDirectory(ctx,recipe,download2);if(dir!==void 0)try{return(await ctx.services.get("formats.manifests").readRecipe(dir))?.manifest.variables??[]}catch{return}}async function definedVariables(ctx,resolved,download2=!1){let format3=ctx.services.get("refs.format"),defined=[],unreadable2=[],versions=[...resolved].sort((left,right)=>left.key<right.key?-1:left.key>right.key?1:0).flatMap(one=>{if(one.pins===void 0||one.pins.length===0)return[{recipe:one}];let pinned=new Map;for(let pin of one.pins){let same=pinned.get(pin.version);same===void 0?pinned.set(pin.version,{recipe:resolvedAtPin(one,pin),holders:[pin.holder],pinned:!0}):same.holders.push(pin.holder)}let pinnedHolders=new Set(one.pins.map(pin=>pin.holder));return[{recipe:one,holders:one.requestedBy.filter(holder=>!pinnedHolders.has(holder))},...pinned.values()]});for(let{recipe,...held}of versions){let variables=await variablesOf(ctx,recipe,download2);if(variables===void 0){unreadable2.includes(recipe.key)||unreadable2.push(recipe.key);continue}for(let definition2 of variables)defined.push({definition:definition2,recipe:{repo:recipe.repo,namespace:recipe.namespace,name:recipe.name,version:recipe.version,identity:recipe.identity,...held},ref:{kind:"variable",name:definition2.name,recipe:format3.recipeRef(recipe.namespace,recipe.name,{repo:recipe.repo})},key:`${recipe.key}.${definition2.name}`})}return{defined,unreadable:unreadable2}}function plannedQuestionsOf(ctx,defined){let ladder=ctx.services.has("recipe-answers.ladder")?ctx.services.get("recipe-answers.ladder"):void 0;return settleSharedNames(ctx,defined).map(variable=>{let{definition:definition2}=variable,found,storedAs;try{found=ladder?.resolve(variable),storedAs=ladder?.bareName(variable)}catch{}return{recipe:`${variable.recipe.namespace}/${variable.recipe.name}`,definition:definition2,...storedAs===void 0?{}:{storedAs},...ctx.project===void 0?{}:{storagePath:path43.join(ctx.project.sousDir,envFileOf(definition2))},answered:found!==void 0,...found===void 0?{}:{answeredFrom:describeSource(found.source)},...variable.unanswerable===void 0?{}:{unanswerable:variable.unanswerable}}})}function settleSharedNames(ctx,defined){if(!ctx.services.has("recipe-answers.definitions"))return defined;let definitions2=ctx.services.get("recipe-answers.definitions"),replaced=new Set(defined.map(variable=>`${variable.recipe.namespace}/${variable.recipe.name}`)),active=[];try{active=definitions2.listSync().filter(variable=>!replaced.has(`${variable.recipe.namespace}/${variable.recipe.name}`))}catch{}return definitions2.combine([...active,...defined]).slice(active.length)}async function planQuestions(ctx,resolved){let{defined,unreadable:unreadable2}=await definedVariables(ctx,resolved);return{questions:plannedQuestionsOf(ctx,defined),unreadable:unreadable2}}var RUNG_LABELS,init_questions=__esm({"../sous-plugin-recipes/src/part-a/questions.ts"(){"use strict";init_required_plugins();init_util2();RUNG_LABELS={mapping:"mapping record",recipe:"recipe scope",namespace:"namespace scope",shared:"shared scope",bare:"declared name"}}});import{IntentOutput as IntentOutput5,IntentOutputs as IntentOutputs9,ItemList as ItemList2,ReportEntryStyle as ReportEntryStyle4,Table as Table2,TextBlock as TextBlock5,VariableSet as VariableSet3}from"@sous-io/sous-plugin-api";function describeRange(range3){return range3??"any version"}function sentence(summary2,title2){return new IntentOutput5({...title2===void 0?{}:{title:title2},summary:summary2})}function noteOutput(text,title2){return new IntentOutput5({...title2===void 0?{}:{title:title2},result:new TextBlock5(text),style:ReportEntryStyle4.Note})}function dryRunOutput(text,title2){return new IntentOutput5({...title2===void 0?{}:{title:title2},result:new TextBlock5(text),style:ReportEntryStyle4.DryRun})}function detailOutput(text,title2){return new IntentOutput5({...title2===void 0?{}:{title:title2},result:new TextBlock5(text),style:ReportEntryStyle4.Detail})}function listOutput(items2,options2={}){return new IntentOutput5({...options2.heading===void 0?{}:{title:options2.heading},result:new ItemList2(items2,options2.listTitle===void 0?{}:{title:options2.listTitle})})}function blockOutput(entries,options2={}){return new IntentOutput5({...options2.heading===void 0?{}:{title:options2.heading},result:new VariableSet3(entries,options2.blockTitle===void 0?{}:{title:options2.blockTitle})})}function tableOutput(columns,rows,options2={}){return new IntentOutput5({...options2.heading===void 0?{}:{title:options2.heading},result:new Table2(columns,rows,{...options2.tableTitle===void 0?{}:{title:options2.tableTitle},...options2.empty===void 0?{}:{empty:options2.empty},...options2.rowNotes===void 0?{}:{rowNotes:options2.rowNotes}})})}function retitled(output,title2){return new IntentOutput5({title:title2,...output.summary===void 0?{}:{summary:output.summary},...output.result===void 0?{}:{result:output.result},...output.data===void 0?{}:{data:output.data},...output.style===void 0?{}:{style:output.style}})}function underHeading(heading,outputs){let[first2,...rest]=outputs;return first2===void 0?[new IntentOutput5({title:heading})]:first2.title===void 0?[retitled(first2,heading),...rest]:[new IntentOutput5({title:heading}),first2,...rest]}function varsAskSection(outputs){let shown=outputs.filter(output=>output.result!==void 0||output.summary!==void 0);return shown.length===0?[]:shown[0].title===void 0?underHeading("Variables",shown):shown}function finish2(own,data,options2={}){let exit=options2.exitCode===void 0?{}:{exitCode:options2.exitCode};return new IntentOutputs9([...own,...options2.after??[]],exit).withData(data)}function plainFollowUps(followUps){return followUps.map(entry=>({intent:entry.intent,...entry.result===void 0?{}:{result:entry.result},...entry.skipped===void 0?{}:{skipped:entry.skipped}}))}function plainResult(result){return{...result,followUps:plainFollowUps(result.followUps)}}function followUpOf(result,intent){return result.followUps?.find(entry=>entry.intent===intent)}function rebuilt(result){let build2=followUpOf(result,"build");return build2!==void 0&&build2.skipped===void 0}function buildFailed(entry){return(entry.outputs?.exitCode??0)!==0||entry.result?.ok===!1}function followUpOutputs(result){let outputs=[],failed=!1;for(let entry of result.followUps??[]){if(entry.skipped!==void 0||entry.outputs===void 0)continue;let shown=entry.outputs.toArray();outputs.push(...entry.intent==="vars.ask"?varsAskSection(shown):shown),entry.intent==="build"&&buildFailed(entry)&&(failed=!0)}return{outputs,failed}}function finishWithFollowUps(ctx,own,result,failedMessage){let{outputs,failed}=followUpOutputs(result);return failed&&ctx.reporter.error(failedMessage),finish2(own,plainResult(result),{after:outputs,...failed?{exitCode:1}:{}})}function lockDiffLines(diff){return describeLockDiff(diff)}function lockfileOutput(diff,whenUnchanged){return diff.unchanged?sentence(whenUnchanged,"Lockfile"):listOutput(lockDiffLines(diff),{heading:"Lockfile"})}function describeSize(bytes){if(bytes<1024)return`${bytes} bytes`;let units=["KB","MB","GB","TB"],value=bytes/1024,unit=0;for(;value>=1024&&unit<units.length-1;)value/=1024,unit+=1;return`${value.toFixed(1)} ${units[unit]}`}function firstSentence(text){return(/^.*?[.!?](?=\s|$)/s.exec(text.trim())?.[0]??text.trim()).replace(/\s+/g," ")}function questionCount(count2){return count2===1?"1 question":`${count2} questions`}function usesDefault(question){return!question.answered&&question.unanswerable===void 0&&question.definition.required!==!1&&question.definition.default!==void 0}function questionFacts(question,answerHint){let variable=question.definition,entries=[];return variable.description!==void 0&&variable.description!==""&&entries.push({label:"about",value:firstSentence(variable.description)}),variable.example!==void 0&&entries.push({label:"example",value:String(variable.example)}),question.storedAs!==void 0&&question.storedAs!==""&&entries.push({label:"stored-as",value:question.storedAs}),question.storagePath!==void 0&&question.storagePath!==""&&entries.push({label:"storage-path",value:question.storagePath}),question.unanswerable!==void 0?(entries.push({label:"not-answerable",value:question.unanswerable}),entries):(entries.push({label:"answered",value:question.answered?`yes${question.answeredFrom===void 0?"":`, from ${question.answeredFrom}`}`:variable.required===!1?"no, and an answer is optional":usesDefault(question)?variable.secret===!0?"no, so its default is used":`no, so its default is used: ${String(variable.default)}`:"no, and this recipe requires an answer"}),answerHint&&entries.push({label:"answer-with",value:`--answer ${variable.name}=<value>`}),entries)}function questionPlanOutputs(plan2,options2){let count2=plan2.questions.length,unanswered=plan2.questions.filter(question=>!question.answered&&question.unanswerable===void 0&&!usesDefault(question)).length,unreadable2=plan2.unreadable.length===0?void 0:`Not on this machine yet, and their repository's index does not record their questions, so they cannot be listed: ${plan2.unreadable.join(", ")}.`+(options2.answerHints?" A dry run downloads nothing; run this command again without '--dry-run' to install them and be asked.":"");if(count2===0)return[unreadable2===void 0?sentence("None of these recipes ask any questions, so nothing needs answering."):noteOutput(unreadable2)];let subject2=plan2.unreadable.length===0?"These recipes ask":"The recipes sous could read ask",outputs=[sentence(unanswered===0?`${subject2} ${questionCount(count2)}, and everything they ask is already answered.`:`${subject2} ${questionCount(count2)}, ${unanswered} of which nothing answers yet.`)],groups=new Map;for(let question of plan2.questions)groups.set(question.recipe,[...groups.get(question.recipe)??[],question]);for(let[recipe,questions]of groups)questions.forEach((question,index)=>{outputs.push(blockOutput(questionFacts(question,options2.answerHints),{blockTitle:question.definition.name,...index===0?{heading:`${recipe} asks ${questionCount(questions.length)}`}:{}}))});return unreadable2!==void 0&&outputs.push(noteOutput(unreadable2)),options2.answerHints&&unanswered>0&&outputs.push(noteOutput("Answer them all ahead of time by running this command again without '--dry-run', with one '--answer <name>=<value>' for each, or with '--answers-file <path>'.")),outputs}var init_outputs=__esm({"../sous-plugin-recipes/src/part-a/outputs.ts"(){"use strict";init_lockfile_ops()}});import{commandVariables}from"@sous-io/sous-plugin-api";function recipeColumns(installed2){return installed2?RECIPE_COLUMNS.map(column=>column.key==="pinned"?{...column,header:"Installed"}:column):RECIPE_COLUMNS}function pinnedCell(pinned,linkedPath){return pinned===void 0?"":linkedPath===void 0?pinned:`${pinned} linked`}function recipeRows(listings){return listings.map(entry=>({key:entry.key,repo:entry.repo,latest:entry.latest??"none published",pinned:pinnedCell(entry.pinned,entry.linkedPath),subscribed:entry.subscribed?"yes":"no",description:entry.description??"no description published"}))}function describeCoverage(coverage){return coverage==="whole namespace"?"the whole namespace":coverage==="some recipes"?"some recipes":"no"}function describeVersionStatus(status){switch(status){case"latest and pinned":return"the latest version, and the one pinned here";case"latest":return"the latest version";case"pinned":return"the version pinned here";default:return"an earlier version"}}function describeDependencyKind(kind){return kind==="depends"?"build dependency":kind==="subscribes"?"co-subscription":"not recorded"}function describeOrigin(addedBy){return addedBy===BUILT_IN_ADDED_BY?"built in":addedBy===void 0||addedBy===USER_ADDED_BY?"user":`required by ${addedBy}`}function noDestinationText(kind){switch(kind){case"config":return"loaded as a config layer, so nothing is written";case"memories":return"reaches an agent through an include line in its instructions, so nothing is written";case"skills":return"nowhere: this project sets no 'recipes.skills.outputs' directory";default:return`nowhere: this project has no destination for ${kind} yet`}}function describeDeclaration(declared){let match2=/^(?:([a-z0-9][a-z0-9._-]*):)?([a-z][a-z0-9-]*)(?:@.*)?$/i.exec(declared.trim());return match2===null?declared:match2[1]===void 0?`the whole '${match2[2]}' namespace`:`the whole '${match2[2]}' namespace of ${match2[1]}`}function factIf(label,value){return value===void 0||value.length===0?[]:[{label,value}]}function browsingVariables(ctx,input,asked={}){let extra={};for(let[label,value]of Object.entries(asked))value!==void 0&&(extra[label]=value);return extra.Reading=input.latest===!0?"each repository, upstream":"the cached indexes",input.installed===!0&&(extra.Showing="only what this project has installed"),commandVariables(ctx,extra)}function namespaceListOutputs(ctx,input,result){let installed2=input.installed===!0,columns=installed2?NAMESPACE_COLUMNS.map(column=>column.key==="recipes"?{...column,header:"Installed"}:column):NAMESPACE_COLUMNS;return finish2([browsingVariables(ctx,input),tableOutput(columns,result.map(entry=>({namespace:entry.namespace,repo:entry.repo,recipes:String(entry.recipeCount),subscribed:describeCoverage(entry.subscribed),description:entry.description??"no description published"})),{heading:installed2?"Namespaces this project has installed recipes from":"Namespaces in the repositories this project trusts",empty:installed2?"This project has installed no recipe from the repositories it trusts.":"The repositories this project trusts publish no namespaces."})],{namespaces:[...result]})}function namespaceShowOutputs(ctx,input,detail){let installed2=input.installed===!0,outputs=[browsingVariables(ctx,input,{Namespace:input.ref}),blockOutput([{label:"Repository",value:detail.repo},...factIf("Location",detail.repoUrl),...factIf("About",detail.description),{label:installed2?"Installed recipes":"Recipes",value:String(detail.recipes.length)},{label:"Subscribed",value:describeCoverage(detail.subscribed)}],{heading:`The namespace ${detail.namespace}`}),tableOutput(recipeColumns(installed2),recipeRows(detail.recipes),{tableTitle:`Recipes in ${detail.namespace}`,empty:`The repository ${detail.repo} publishes no recipes in this namespace.`})];return detail.recipes.some(entry=>entry.linkedPath!==void 0)&&outputs.push(noteOutput(LINKED_NOTE)),finish2(outputs,detail)}function recipeListOutputs(ctx,input,result){let installed2=input.installed===!0,outputs=[browsingVariables(ctx,input),tableOutput(recipeColumns(installed2),recipeRows(result),{heading:installed2?"Recipes this project has installed":"Recipes in the repositories this project trusts",empty:installed2?"This project has installed no recipe from the repositories it trusts.":"The repositories this project trusts publish no recipes."})];return result.some(entry=>entry.linkedPath!==void 0)&&outputs.push(noteOutput(LINKED_NOTE)),finish2(outputs,{recipes:[...result]})}function installsOutputs(detail){let outputs=[tableOutput(INSTALLS_COLUMNS,(detail.installs??[]).map(recipe=>{let holders=recipe.requestedBy.filter(holder=>holder!=="project");return{key:recipe.key,version:recipe.version,kind:recipe.requestedBy.includes("project")?"the subscription itself":describeDependencyKind(recipe.kind),neededBy:holders.length===0?"this subscription":holders.join(", ")}}),{tableTitle:"What subscribing installs"})],missing=detail.installsNeed??[];return missing.length>0&&outputs.push(sentence(`Subscribing also needs ${missing.length===1?"a repository":"repositories"} this project does not trust yet, so what ${missing.length===1?"it publishes":"they publish"} is not listed above: `+missing.map(entry=>`${entry.name}${entry.url===void 0?"":` (${entry.url})`}, needed by ${entry.requiredBy.map(holder=>holder.requestedBy).join(", ")}`).join("; ")+".")),outputs}function recipeShowOutputs(ctx,input,detail){let installed2=input.installed===!0,outputs=[browsingVariables(ctx,input,{Recipe:input.ref}),blockOutput([{label:"Repository",value:detail.repo},...factIf("Location",detail.repoUrl),...factIf("About",detail.description),{label:"Folder",value:detail.path},{label:"Latest version",value:detail.latest??"none published"},{label:installed2?"Installed version":"Pinned version",value:detail.pinned??"this project pins none"},...factIf("Linked",detail.linkedPath===void 0?void 0:`builds currently read this recipe from the checkout at ${detail.linkedPath}`),{label:"Subscribed",value:detail.subscribed?"yes":"no"},...factIf("Described below",detail.describing)],{heading:detail.key}),tableOutput(VERSION_COLUMNS,detail.versions.map(entry=>({version:entry.version,status:describeVersionStatus(entry.status),prerelease:entry.prerelease?"yes":"no",released:entry.releasedAt??"not recorded"})),{tableTitle:"Published versions"}),tableOutput(DEPENDENCY_COLUMNS,detail.dependencies.map(entry=>({key:entry.key,declared:entry.declared===void 0?"not recorded in the index":describeDeclaration(entry.declared),resolved:entry.resolvedVersion??(entry.resolvedRange===void 0?"not recorded in the index":`the range ${entry.resolvedRange}`),repo:entry.repo??"this repository",kind:describeDependencyKind(entry.kind)})),{tableTitle:"What it depends on",empty:detail.manifestRead||detail.dependenciesRecorded?"This recipe depends on nothing else.":"The repository's index records no dependencies for this version."})];return detail.describing===void 0?outputs.push(sentence("This recipe publishes no version a subscription would install, so nothing is described below.")):detail.installsProblem!==void 0||detail.installs===void 0||detail.questions===void 0?outputs.push(sentence(detail.installsProblem??"Sous could not work out what subscribing would install.")):outputs.push(...installsOutputs(detail),...underHeading("What subscribing asks you",questionPlanOutputs(detail.questions,{answerHints:!1}))),outputs.push(tableOutput(CONTENT_COLUMNS,detail.manifestRead?detail.contents.map(entry=>({kind:entry.kind,include:entry.include.join(", "),destination:entry.destinations.length>0?entry.destinations.join(", "):noDestinationText(entry.kind)})):[],{tableTitle:"Where its files land in this project",empty:detail.manifestRead?"This recipe publishes no files.":"The recipe's own files are not on this machine, so the files it publishes are not known here. Subscribing to it fetches them."})),finish2(outputs,detail)}function repoSearchOutputs(ctx,input,result){let installed2=input.installed===!0,outputs=[browsingVariables(ctx,input,{Searching:input.text}),tableOutput(installed2?INSTALLED_SEARCH_COLUMNS:SEARCH_COLUMNS,result.map(match2=>({key:match2.key,kind:match2.kind,versions:match2.versions?.join(", ")??"",installed:match2.installed??"",repo:match2.repo,description:match2.description!==void 0&&match2.description.length>0?match2.description:"no description published"})),{heading:"Recipes matching your search",empty:installed2?`Nothing this project has installed matches '${input.text}'.`:`Nothing in the repositories this project trusts matches '${input.text}'.`})],limit2=input.limit??20;return result.length>0&&result.length>=limit2&&outputs.push(sentence(`Only the first ${limit2} matches are shown. Raise the number with '--limit'.`)),finish2(outputs,{matches:[...result]})}function repoNote(entry,verbose){let notes=[];if(entry.enabled||notes.push("Switched off in the config, so nothing is read from it."),verbose){let namespaces=entry.namespaces===void 0?"not fetched":entry.namespaces.length>0?entry.namespaces.join(", "):"none";notes.push(`Namespaces: ${namespaces}`)}return entry.installed!==void 0&&entry.installed.length>0&&notes.push(`Installed: ${entry.installed.map(pin=>`${pin.key} ${pin.version}`).join(", ")}`),notes.length>0?notes.join(" "):void 0}function repoListOutputs(ctx,input,result){let verbose=input.verbose===!0,outputs=[browsingVariables(ctx,input),tableOutput(REPO_COLUMNS,result.map(entry=>({name:entry.name,url:entry.url,provider:entry.provider,origin:describeOrigin(entry.addedBy),linked:entry.linkedPath===void 0?"no":`yes: ${entry.linkedPath}`,recipes:entry.recipeCount===void 0?"not fetched":String(entry.recipeCount)})),{heading:input.installed===!0?"Repositories this project has installed recipes from":"Repositories this project trusts",empty:"This project trusts no repositories yet. Add one with 'sous repo add <url>'; adding a repository is how you trust it.",rowNotes:result.map(entry=>repoNote(entry,verbose))})];for(let entry of result)entry.problem!==void 0&&ctx.reporter.warn(`${entry.name} could not be checked upstream, so it is shown from the cache: ${entry.problem}`);return finish2(outputs,{repos:[...result]})}function describePinned(pinned,enabled){return pinned.length>0?pinned.map(entry=>`${entry.key} ${entry.version}`).join(", "):enabled?"pinned on first build":"not pinned"}function describeLatest(listing){if(listing.pinned.length===0)return"";let published=new Map((listing.latest??[]).map(entry=>[entry.key,entry.version])),newer=new Map((listing.newer??[]).map(entry=>[entry.key,entry.version])),latestOf=(key,pinned)=>listing.latest===void 0?newer.get(key)??pinned:published.get(key)??"not in any index sous has read";if(listing.pinned.length===1){let only=listing.pinned[0];return latestOf(only.key,only.version)}return listing.pinned.map(pin=>`${pin.key} ${latestOf(pin.key,pin.version)}`).join(", ")}function describeSubscriptionOrigin(addedBy){return addedBy===BUILT_IN_ADDED_BY?"built in":addedBy===void 0||addedBy===USER_ADDED_BY?"user":addedBy}function subscriptionListOutputs(ctx,input,result){let installed2=input.installed===!0,listings=result.filter(entry=>!installed2||entry.pinned.length>0),columns=SUBSCRIPTION_COLUMNS.map(column=>installed2&&column.key==="pinned"?{...column,header:"Installed version"}:column);return finish2([browsingVariables(ctx,input),tableOutput(columns,listings.map(entry=>({key:entry.key,range:describeRange(entry.range),pinned:describePinned(entry.pinned,entry.enabled),latest:describeLatest(entry),origin:describeSubscriptionOrigin(entry.addedBy),enabled:entry.enabled?"yes":"no"})),{heading:"Subscriptions",empty:installed2?"No subscription of this project has installed anything yet.":"This project subscribes to nothing yet."})],{subscriptions:listings})}var RECIPE_COLUMNS,NAMESPACE_COLUMNS,VERSION_COLUMNS,DEPENDENCY_COLUMNS,INSTALLS_COLUMNS,CONTENT_COLUMNS,SEARCH_COLUMNS,INSTALLED_SEARCH_COLUMNS,REPO_COLUMNS,SUBSCRIPTION_COLUMNS,LINKED_NOTE,init_catalog_outputs=__esm({"../sous-plugin-recipes/src/part-a/intents/catalog-outputs.ts"(){"use strict";init_defaults();init_outputs();RECIPE_COLUMNS=[{key:"key",header:"Recipe",kind:"path",overflow:"truncate",minWidth:12},{key:"repo",header:"Repository",overflow:"truncate",priority:"medium"},{key:"latest",header:"Latest",overflow:"truncate",minWidth:6},{key:"pinned",header:"Pinned",overflow:"truncate",minWidth:6},{key:"subscribed",header:"Subscribed",priority:"medium"},{key:"description",header:"What it is",overflow:"wrap",maxLines:3,flex:1,priority:"low",minWidth:16}],NAMESPACE_COLUMNS=[{key:"namespace",header:"Namespace",overflow:"truncate",minWidth:10},{key:"repo",header:"Repository",overflow:"truncate",priority:"medium"},{key:"recipes",header:"Recipes",kind:"number",priority:"medium"},{key:"subscribed",header:"Subscribed",priority:"medium"},{key:"description",header:"What it is",overflow:"wrap",flex:1,priority:"low",minWidth:16}],VERSION_COLUMNS=[{key:"version",header:"Version",overflow:"truncate",minWidth:7},{key:"status",header:"What it is",overflow:"wrap",flex:1,minWidth:16},{key:"prerelease",header:"Prerelease",priority:"medium"},{key:"released",header:"Released",overflow:"truncate",priority:"low"}],DEPENDENCY_COLUMNS=[{key:"key",header:"Dependency",kind:"path",overflow:"truncate",minWidth:12},{key:"declared",header:"Declared as",overflow:"wrap",flex:1,minWidth:12},{key:"resolved",header:"Resolved to",overflow:"truncate",minWidth:11},{key:"repo",header:"Repository",overflow:"truncate",priority:"low",minWidth:12},{key:"kind",header:"Kind",overflow:"wrap",priority:"medium",minWidth:16}],INSTALLS_COLUMNS=[{key:"key",header:"Recipe",kind:"path",overflow:"truncate",minWidth:12},{key:"version",header:"Version",overflow:"truncate",minWidth:7},{key:"kind",header:"Kind",overflow:"wrap",minWidth:16},{key:"neededBy",header:"Needed by",overflow:"wrap",flex:1,priority:"low",minWidth:16}],CONTENT_COLUMNS=[{key:"kind",header:"Content",minWidth:7},{key:"include",header:"Files",overflow:"wrap",flex:1,minWidth:14},{key:"destination",header:"Where they land",kind:"path",overflow:"wrap",flex:2,minWidth:16}],SEARCH_COLUMNS=[{key:"key",header:"Match",kind:"path",overflow:"truncate",minWidth:12},{key:"kind",header:"Kind",overflow:"truncate",minWidth:9},{key:"versions",header:"Versions",overflow:"truncate",minWidth:7},{key:"repo",header:"Repository",overflow:"truncate",priority:"medium"},{key:"description",header:"What it is",overflow:"wrap",flex:1,priority:"low",minWidth:16}],INSTALLED_SEARCH_COLUMNS=[{key:"key",header:"Recipe",kind:"path",overflow:"truncate",minWidth:12},{key:"installed",header:"Installed",overflow:"truncate",minWidth:9},{key:"versions",header:"Versions",overflow:"truncate",minWidth:7},{key:"repo",header:"Repository",overflow:"truncate",priority:"medium"},{key:"description",header:"What it is",overflow:"wrap",flex:1,priority:"low",minWidth:16}],REPO_COLUMNS=[{key:"name",header:"Repository",overflow:"truncate",minWidth:8},{key:"provider",header:"Provider",priority:"medium"},{key:"origin",header:"Origin"},{key:"linked",header:"Linked",kind:"path",overflow:"truncate",priority:"medium",minWidth:6},{key:"recipes",header:"Recipes",kind:"number",priority:"low",minWidth:11},{key:"url",header:"URL",kind:"url",overflow:"truncate",truncate:"middle",priority:"low",flex:1,minWidth:12}],SUBSCRIPTION_COLUMNS=[{key:"key",header:"Subscription",kind:"path",overflow:"truncate",minWidth:12},{key:"range",header:"Range",overflow:"truncate",minWidth:7},{key:"pinned",header:"Pinned version",flex:1,minWidth:14},{key:"latest",header:"Latest version",overflow:"wrap",priority:"medium",minWidth:14},{key:"origin",header:"Origin",priority:"medium"},{key:"enabled",header:"Enabled",priority:"medium"}],LINKED_NOTE="A recipe marked linked is pinned at the version shown, but builds currently read it from the linked checkout of its repository."}});import{jsonSchema as jsonSchema13}from"@sous-io/sous-plugin-api";function inputSchema(properties,required2=[]){return jsonSchema13({type:"object",properties,required:required2,additionalProperties:!1})}var dryRun,noBuild,yes,acceptFirst,answer,answersFile,latest,installed,browsing,yesFlag,yesFlagNoTrust,latestFlag,init_schema=__esm({"../sous-plugin-recipes/src/part-a/intents/schema.ts"(){"use strict";dryRun={type:"boolean",description:"Show what would change, writing nothing"},noBuild={type:"boolean",description:"Change it without rebuilding the project afterwards"},yes={type:"boolean",description:"Answer yes to every question, trusting new repositories without asking"},acceptFirst={type:"boolean",description:"When a ref matches several things, take the first one listed"},answer={type:"array",items:{type:"string"},description:"Answer a recipe question ahead of time, as <name>=<value>"},answersFile={type:"string",description:"A file of answers to recipe questions (YAML, JSON, JSONC or .env)"},latest={type:"boolean",description:"Check upstream for newer indexes first"},installed={type:"boolean",description:"Show only what this project has installed, never going upstream"},browsing={latest,installed},yesFlag={short:"y",aliases:["force","trust"]},yesFlagNoTrust={short:"y",aliases:["force"]},latestFlag={aliases:["remote"]}}});import{SousError as SousError17}from"@sous-io/sous-plugin-api";function reportUnread(ctx,catalog){if(catalog.notFetched.length>0&&ctx.reporter.note(`These repositories are trusted and their index has not been fetched yet, so nothing in them is listed: ${catalog.notFetched.join(", ")}.`),catalog.notChecked.length>0){ctx.reporter.note(`These repositories could not be reached, so they are shown from the cache and were not checked: ${catalog.notChecked.map(entry=>entry.repo).join(", ")}.`);for(let entry of catalog.notChecked)ctx.reporter.debug(`${entry.repo}: ${entry.reason}`)}}async function showNamespace(input,ctx){let catalog=await loadCatalog(ctx,input);reportUnread(ctx,catalog);let readings=readingsOf(ctx,input.ref);if(readings.every(reading=>reading.kind==="recipe"&&reading.namespace!==void 0)){let recipe=findInCatalog(catalog.inputs,readings,["recipe"])[0];if(recipe!==void 0)throw new SousError17(`'${input.ref}' names the recipe '${recipe.key}', not a namespace.`,{details:[`The namespace it belongs to is '${recipe.key.split("/")[0]}'.`]})}let found=await resolveInCatalog(ctx,catalog,input.ref,["namespace"],input.acceptFirst,()=>{let asRecipe=findInCatalog(catalog.inputs,readings,["recipe"]);return input.installed!==!0&&asRecipe.length>0&&!readings.some(reading=>reading.kind==="namespace"&&reading.repo!==void 0)?new SousError17(`No repository this project trusts publishes a namespace called '${input.ref}'.`,{details:["It is the name of a recipe:",...asRecipe.map(match2=>` ${match2.repo.name}:${match2.key}`)]}):installedError(input,"namespace")??unknownRefError(catalog.inputs,input.ref,"namespace",catalog.notFetched)});return describeNamespace(catalog.inputs,{repo:found.repo,namespace:found.key})}async function showRecipe(input,ctx){let catalog=await loadCatalog(ctx,input);reportUnread(ctx,catalog);let found=await resolveInCatalog(ctx,catalog,input.ref,["recipe"],input.acceptFirst,()=>{let asNamespace=findInCatalog(catalog.inputs,readingsOf(ctx,input.ref),["namespace"]);return asNamespace.length>0?new SousError17(`No repository this project trusts publishes a recipe called '${input.ref}'.`,{details:["It is the name of a namespace:",...asNamespace.map(match2=>` ${match2.repo.name}:${match2.key}`)]}):installedError(input,"recipe")??unknownRefError(catalog.inputs,input.ref,"recipe",catalog.notFetched)}),location=describedLocation(catalog.inputs,{repo:found.repo,key:found.key}),manifest=location===void 0?void 0:await readPublishedManifest(ctx,catalog.inputs,location),detail=describeRecipe(catalog.inputs,{repo:found.repo,key:found.key},manifest);return{...detail,...await previewSubscription(ctx,catalog,detail)}}async function previewSubscription(ctx,catalog,detail){if(detail.describing===void 0)return{};let prerelease=import_semver9.default.prerelease(detail.describing)!==null;try{let result=await ctx.services.get("recipes.resolver").resolve([{ref:ctx.services.get("refs.format").recipeRef(detail.namespace,detail.name,{repo:detail.repo,range:detail.describing}),range:detail.describing,requestedBy:PROJECT_HOLDER,kind:"subscribes",...prerelease?{prerelease:!0}:{}}],{indexes:new Map(catalog.inputs.repos.map(repo=>[repo.name,repo.index])),...prerelease?{prerelease:!0}:{}});return{installs:result.resolved.map(recipe=>({key:recipe.key,version:recipe.version,kind:recipe.kind,requestedBy:recipe.requestedBy})),installsNeed:result.missingRepos,questions:await planQuestions(ctx,result.resolved)}}catch(error51){return{installsProblem:`Sous could not work out what subscribing to version ${detail.describing} would install. ${describeError2(error51)}`}}}function installedError(input,what){if(input.installed===!0)return new SousError17(what==="namespace"?`This project has installed no recipe from the namespace '${input.ref}', so there is nothing to show with '--installed'.`:`This project has not installed the recipe '${input.ref}', so there is nothing to show with '--installed'.`)}function registerCatalogIntents(sous){sous.intents.add({intent:"namespace.list",needsRecipeFiles:!0,requiresProject:!0,summary:"List the namespaces in the repositories this project trusts",input:inputSchema(browsing),parallel:!0,cli:{aliases:[["namespace","ls"]],...browsingCli},agent:{usage:"Call this before subscribing, to find which namespaces exist."},handle:async(input,ctx)=>{let catalog=await loadCatalog(ctx,input);return reportUnread(ctx,catalog),namespaceListOutputs(ctx,input,listNamespaces(catalog.inputs))}}),sous.intents.add({intent:"namespace.show",needsRecipeFiles:!0,requiresProject:!0,summary:"Show one namespace and every recipe in it",input:inputSchema({ref:{type:"string",description:"The namespace, optionally as repository:namespace"},...browsing,acceptFirst},["ref"]),parallel:!0,cli:{positional:["ref"],...browsingCli},handle:async(input,ctx)=>namespaceShowOutputs(ctx,input,await showNamespace(input,ctx))}),sous.intents.add({intent:"recipe.list",requiresProject:!0,summary:"List the recipes in the repositories this project trusts",input:inputSchema(browsing),parallel:!0,cli:{aliases:[["recipe","ls"]],...browsingCli},handle:async(input,ctx)=>{let catalog=await loadCatalog(ctx,input);return reportUnread(ctx,catalog),recipeListOutputs(ctx,input,listRecipes(catalog.inputs))}}),sous.intents.add({intent:"recipe.show",requiresProject:!0,summary:"Show one recipe: its versions, dependencies, contents and questions",input:inputSchema({ref:{type:"string",description:"The recipe: namespace/recipe, a bare name, or either as repository:ref"},...browsing,acceptFirst},["ref"]),parallel:!0,cli:{positional:["ref"],...browsingCli},handle:async(input,ctx)=>recipeShowOutputs(ctx,input,await showRecipe(input,ctx))})}var import_semver9,browsingCli,init_catalog2=__esm({"../sous-plugin-recipes/src/part-a/intents/catalog.ts"(){"use strict";import_semver9=__toESM(require_semver2(),1);init_catalog();init_catalog_context();init_lock_holds();init_questions();init_util2();init_catalog_outputs();init_schema();browsingCli={flags:{latest:latestFlag}}}});async function askFollowUp(ctx,flags,recipes){if(flags.dryRun===!0)return{intent:"vars.ask",skipped:"--dry-run"};if(!hasIntent(ctx,"vars.ask"))return{intent:"vars.ask",skipped:"no plugin provides vars.ask"};if(recipes.length===0&&flags.answer===void 0&&flags.answersFile===void 0)return{intent:"vars.ask",skipped:"nothing new to ask"};let result=await ctx.run("vars.ask",{...recipes.length===0?{}:{within:[...recipes]},...flags.answer===void 0?{}:{answer:flags.answer},...flags.answersFile===void 0?{}:{answersFile:flags.answersFile}});return ctx.chain!==void 0&&!ctx.chain.parallel&&await ctx.refreshConfig(),{intent:"vars.ask",result:result.toPlain(),outputs:result}}async function buildFollowUp(ctx,flags){if(flags.dryRun===!0)return{intent:"build",skipped:"--dry-run"};if(flags.noBuild===!0)return{intent:"build",skipped:"--no-build"};if(!hasIntent(ctx,"build"))return{intent:"build",skipped:"no plugin provides build"};let built=await ctx.run("build",{});return{intent:"build",result:built.toPlain(),outputs:built}}var init_followups=__esm({"../sous-plugin-recipes/src/part-a/followups.ts"(){"use strict";init_util2()}});import{SousError as SousError18}from"@sous-io/sous-plugin-api";function isShortNamed(ref){if(ref.kind!=="namespace"&&ref.kind!=="recipe")return!1;let named=ref;return(named.kind==="namespace"?named.repo:named.namespace?.repo??named.repo)?.location===void 0}async function subscriptionKeyFor(ctx,written,keys){let readings=readingsOf(ctx,written),short=readings.find(isShortNamed);if(short!==void 0){let key=ctx.services.get("refs.format").key(short);return keys.find(candidate=>candidate===key)??keys.find(candidate=>candidate.toLowerCase()===key.toLowerCase())??key}let catalog=await loadCatalog(ctx);return(await pickMatch(ctx,findInCatalog(catalog.inputs,readings,["namespace","recipe"]),written.trim(),void 0,()=>new SousError18(`'${written.trim()}' names no namespace or recipe this project knows.`))).key}async function planSubscriptionRemoval(ctx,key,lock){let configured=configuredSubscriptions(ctx.config),managed=await managedEntries(ctx.services.get("confd.managed"),SUBSCRIPTIONS_LAYER,"subscriptions"),held=keysHeldBySubscription(lock,key),removable=Object.hasOwn(managed,key)&&managed[key]?.enabled!==!1,builtIn=!removable&&isBuiltInEntry(configured[key]);if(!removable&&!builtIn){if(!Object.hasOwn(configured,key)&&held.length===0){let known=sortBytewise(Object.keys(configured).filter(entry=>configured[entry]?.enabled!==!1));throw new SousError18(`This project does not subscribe to '${key}'.`,{details:[known.length>0?`It subscribes to: ${known.join(", ")}.`:"It has no subscriptions yet."]})}if(Object.hasOwn(configured,key))throw new SousError18(`The subscription to '${key}' is written in one of this project's own config files, not in the file sous manages.`,{details:["Remove its entry from the 'subscriptions' block of that file; sous never deletes what you wrote.",`To switch it off on this machine instead, run 'sous subscription disable ${key}'.`]})}if(builtIn)return{key,optedOut:!0,after:lock,stayed:[]};let after=lock;for(let heldKey of held)after=dropProjectHold(after,heldKey);return{key,optedOut:!1,after,stayed:stayedAfter(after,held)}}async function writeSubscriptionRemoval(ctx,removal){let managed=ctx.services.get("confd.managed");removal.optedOut?await writeSubscriptionEntry(managed,removal.key,{enabled:!1}):await deleteSubscriptionEntry(managed,removal.key)}var init_subscriptions=__esm({"../sous-plugin-recipes/src/part-a/subscriptions.ts"(){"use strict";init_catalog();init_catalog_context();init_defaults();init_lock_holds();init_project();init_util2()}});function repoAddOutputs(result){let heading="Adding a repository";return result.dryRun?finish2([dryRunOutput("Nothing will be trusted, written or downloaded.",heading),noteOutput(`The repository would be added as '${result.name}', read through the ${result.provider} provider, and its index would be fetched.`)],result):finish2([blockOutput({Repository:result.name,Location:result.url,Provider:result.provider,Namespaces:result.namespaces.length>0?result.namespaces.join(", "):"none; this repository publishes nothing yet",Recipes:String(result.recipeCount)},{heading}),noteOutput(result.alreadyTrusted?`This project already trusted '${result.name}', so only its index was refreshed.`:`This project now trusts '${result.name}'. Nothing from it has been installed.`)],result)}function repoRemoveOutputs(ctx,result){let pruneHint=rebuilt(result)?"":" Run 'sous build' to prune what it used to write.",outputs=[];result.dryRun&&outputs.push(dryRunOutput("Nothing will be written."));let[first2,...rest]=result.plan??[];return first2!==void 0&&(outputs.push(sentence(first2)),rest.length>0&&outputs.push(listOutput(rest,{listTitle:"Here is what goes with it:"}))),outputs.push(lockfileOutput(result.diff,"Nothing changed; nothing was locked because of this repository.")),result.stayed.length>0&&outputs.push(tableOutput(STAYED_COLUMNS,result.stayed.map(entry=>({key:entry.key,heldBy:entry.heldBy.join(", ")})),{tableTitle:"What stayed, and why"})),result.dryRun?outputs.push(dryRunOutput("Nothing was written. Run the same command without '--dry-run' to remove it.")):outputs.push(sentence(result.optedOut?`The repository '${result.name}' is one sous provides itself, so it was switched off rather than deleted: this project's config now records '${result.name}: { enabled: false }'.${pruneHint}`:`This project no longer trusts '${result.name}'. Nothing is read from it any more, and its entry is gone from the repositories layer.${pruneHint}`)),finishWithFollowUps(ctx,underHeading("Removing a repository",outputs),result,`The repository '${result.name}' was removed, but the build that followed it failed, so this project may still hold files its recipes used to write. The removal itself is recorded and locked; fix what the build reported above and run 'sous build' again.`)}function repoTrustOutputs(result){let outputs=[];return result.dryRun&&outputs.push(dryRunOutput("Nothing will be written.")),outputs.push(blockOutput({Repository:result.name,Location:result.url})),result.alreadyTrusted?outputs.push(noteOutput(`This project already trusts '${result.name}'; nothing changed.`)):result.dryRun?outputs.push(dryRunOutput(`Nothing was written. Run the same command without '--dry-run' to trust '${result.name}'.`)):outputs.push(noteOutput(result.trusted?`This project now trusts '${result.name}'. Nothing from it has been installed.`:`'${result.name}' was not trusted; nothing changed.`)),finish2(underHeading("Trusting a repository",outputs),result)}var STAYED_COLUMNS,init_repo_outputs=__esm({"../sous-plugin-recipes/src/part-a/intents/repo-outputs.ts"(){"use strict";init_outputs();STAYED_COLUMNS=[{key:"key",header:"Recipe",kind:"path",overflow:"truncate",minWidth:12},{key:"heldBy",header:"Still held by",overflow:"wrap",flex:1,minWidth:16}]}});import fs31 from"node:fs";import os6 from"node:os";import path44 from"node:path";import{ConfigError as ConfigError27,LogLevel as LogLevel6,SousError as SousError19}from"@sous-io/sous-plugin-api";function looksLikeLocalPath(typed){return typed.startsWith("/")||typed.startsWith("./")||typed.startsWith("../")||typed==="."||typed===".."||typed.startsWith("~")}function resolveLocalPath(typed,base,home){let expanded=typed==="~"||typed.startsWith("~/")?path44.join(home??os6.homedir(),typed.slice(1)):typed;return path44.resolve(base,expanded)}async function addRepo(input,ctx){let locations=ctx.services.get("refs.locations"),typed=input.url.trim(),url2=typed;if(looksLikeLocalPath(typed)){url2=resolveLocalPath(typed,ctx.cwd??ctx.project?.root??".",ctx.env.HOME);let id=input.provider??locations.hostFor(url2)?.id,host=ctx.entities.list("repository-host").find(entry=>entry.id===id);if(host?.checkTypedPath!==void 0)await host.checkTypedPath(typed,url2,ctx);else if(!fs31.existsSync(url2)||!fs31.statSync(url2).isDirectory())throw new SousError19(`'${typed}' is not a directory on this machine, so it cannot be added as a repository.`,{details:[`Sous looked at ${url2}.`]})}if(input.provider!==void 0&&locations.host(input.provider)===void 0)throw new SousError19(`'${input.provider}' is not a repository host sous knows.`,{details:[`The hosts loaded now: ${sortBytewise(locations.hosts().map(host=>host.id)).join(", ")||"none"}. A plugin can add another.`]});let canonical=locations.canonicalize(url2,input.provider),provider=input.provider??locations.hostFor(url2)?.id??"unknown",name=input.name??canonical.name.toLowerCase();if(!REPO_NAME_PATTERN2.test(name))throw new SousError19(`'${name}' is not a usable short name for a repository.`,{details:["A short name is lowercase kebab case: a letter, then letters, digits or hyphens. Refs use it as the 'repo:' qualifier.",`Choose one with --name, for example 'sous repo add ${typed} --name my-recipes'.`]});let existing=configuredRepos(ctx.config)[name],wanted=locations.identityOf(canonical),sameRepository=existing!==void 0&&identityOf(ctx,existing.url)===wanted,alreadyTrusted=sameRepository&&existing.enabled!==!1;if(existing!==void 0&&!sameRepository)throw new SousError19(`This project already has a repository called '${name}', and it is a different one.`,{details:[`Already added: ${existing.url}`,`Being added: ${url2}`,`Give this one a name of its own with --name, for example --name ${name}-2.`]});let result={name,url:url2,provider,alreadyTrusted,namespaces:[],recipeCount:0,dryRun:input.dryRun===!0};if(input.dryRun===!0)return result;alreadyTrusted||await ctx.services.get("recipes.trust").confirm([{name,url:url2,identity:wanted,provider,requiredBy:[{ref:name,requestedBy:"project"}]}],{...input.yes===void 0?{}:{yes:input.yes}},ctx),await writeRepoEntry(ctx.services.get("confd.managed"),name,{url:url2,...input.provider===void 0?{}:{provider:input.provider},addedAt:nowIso(),addedBy:USER_ADDED_BY}),ctx.configChanged();try{let cached2=await(await ctx.refreshConfig()).services.get("recipes.index-cache").get(name,{latest:!0});result.namespaces=sortBytewise(Object.keys(cached2.index.namespaces)),result.recipeCount=Object.keys(cached2.index.recipes).length}catch(error51){ctx.reporter.warning(`Trusted ${name}, but its index could not be read yet: ${describeError2(error51)}`)}return result}async function subscriptionsInto(ctx,name,lock){let fromRepo=new Set(Object.entries(lock.recipes).filter(([,recipe])=>recipe.repo===name).map(([key])=>key)),subscriptions=configuredSubscriptions(ctx.config),managed=await managedEntries(ctx.services.get("confd.managed"),SUBSCRIPTIONS_LAYER,"subscriptions"),format3=ctx.services.get("refs.format"),removable=[],kept=[];for(let key of sortBytewise(Object.keys(subscriptions))){if(subscriptions[key]?.enabled===!1)continue;let qualifier;try{qualifier=format3.partsOf(format3.parseNamedRef(key,"config")).repo?.name}catch{continue}qualifier!==name&&!keysHeldBySubscription(lock,key).some(held=>fromRepo.has(held))||(Object.hasOwn(managed,key)||isBuiltInEntry(subscriptions[key])?removable.push(key):kept.push(key))}return{removable,kept}}function removalPlan(result){let lines3=[result.optedOut?`The repository '${result.name}' at ${result.url} is one sous provides itself, so it is switched off instead, by recording '${result.name}: { enabled: false }' in conf.d/500-repos.jsonc.`:`The entry for '${result.name}' at ${result.url} is removed from conf.d/500-repos.jsonc, so sous stops reading anything from it.`];lines3.push(result.subscriptions.length===0?"Nothing this project subscribes to resolves into it.":`${result.subscriptions.length===1?"One subscription resolves into it and is":`${result.subscriptions.length} subscriptions resolve into it and are`} removed: ${result.subscriptions.join(", ")}.`),result.removedRecipes.length>0&&lines3.push(`These locked recipes were held only through those subscriptions and leave the lockfile: ${result.removedRecipes.join(", ")}.`);for(let stayed of result.stayed)lines3.push(`The recipe '${stayed.key}' stays, because ${stayed.heldBy.join(", ")} still holds it.`);result.outputs.length>0&&lines3.push(`Removing ${result.name} deletes ${result.outputs.length} built ${result.outputs.length===1?"file":"files"} on the next build:`,...result.outputs.map(file2=>` ${file2}`)),result.linkedPath!==void 0&&lines3.push(result.linkIsGlobal?`A machine-wide link points this repository at ${result.linkedPath}. Other projects share it, so it is left as it is.`:`This project links the repository to ${result.linkedPath}. The link is removed; the checkout stays on disk.`);for(let key of result.keptSubscriptions)lines3.push(`The subscription to '${key}' resolves into it and is written in this project's own config, which sous never edits, so it stays.`);return lines3}function reportRemovalPlan(reporter,plan2){for(let index=0;index<plan2.length;index++){let line=plan2[index],items2=[];for(;plan2[index+1]?.startsWith(" ")===!0;)items2.push(plan2[++index].trim());items2.length>0?reporter.list(items2,{title:line},LogLevel6.Notice):reporter.note(line)}}async function removeRepo(input,ctx){let name=input.repo,trusted=ctx.services.get("recipes.trust").trusted(),entry=trusted[name];if(entry===void 0){let known=sortBytewise(Object.keys(trusted));throw new SousError19(`This project does not trust a repository called '${name}'.`,{details:[known.length>0?`It trusts: ${known.join(", ")}.`:"It trusts no repositories yet."]})}let managedRepos=await managedEntries(ctx.services.get("confd.managed"),REPOS_LAYER,"repos"),builtIn=!Object.hasOwn(managedRepos,name)&&isBuiltInEntry(entry);if(!Object.hasOwn(managedRepos,name)&&!builtIn)throw new SousError19(`The repository '${name}' is written in one of this project's own config files, not in the file sous manages.`,{details:["Remove its entry from the 'repos' block of that file; sous never deletes what you wrote."]});let lockService=ctx.services.get("recipes.lock"),before=lockService.read(),{removable,kept}=await subscriptionsInto(ctx,name,before),removals=[],after=before,held=[];for(let key of removable){let removal=await planSubscriptionRemoval(ctx,key,after);held.push(...keysHeldBySubscription(after,key)),after=removal.after,removals.push(removal)}let diff=lockService.diff(before,after),outputs=ctx.services.has("compiler.state")?sortBytewise(new Set(ctx.services.get("compiler.state").filesFrom({repository:name}).map(file2=>file2.dest))):[],link=ctx.services.has("recipes.links")?ctx.services.get("recipes.links").get(name):void 0,planned={name,url:entry.url,optedOut:builtIn,subscriptions:removable,keptSubscriptions:kept,removedRecipes:diff.removed.map(change=>change.key),stayed:stayedAfter(after,held),outputs,diff,...link===void 0?{}:{linkedPath:link.path},linkIsGlobal:link?.scope==="global",dryRun:input.dryRun===!0},plan2=removalPlan(planned);if(input.dryRun===!0)return{...planned,plan:plan2,followUps:[{intent:"build",skipped:"--dry-run"}]};if(input.yes!==!0&&(reportRemovalPlan(ctx.reporter,plan2),!await ctx.prompter.confirm({message:`Stop trusting '${name}'?`,answeredBy:"--yes",default:!1})))throw new SousError19(`Nothing was written: the repository '${name}' is still trusted.`);for(let removal of removals)await writeSubscriptionRemoval(ctx,removal);let written=await lockService.write(after);link!==void 0&&link.scope==="project"&&await ctx.services.get("recipes.links").remove(name,"project");let managed=ctx.services.get("confd.managed");return builtIn?await writeRepoEntry(managed,name,{enabled:!1}):await deleteRepoEntry(managed,name),ctx.configChanged(),input.noBuild!==!0&&await ctx.refreshConfig(),{...planned,...input.yes===!0?{plan:plan2}:{},diff:written,followUps:[await buildFollowUp(ctx,input)]}}async function trustRepo(input,ctx){let trust=ctx.services.get("recipes.trust"),already=trust.nameOf(input.repo),dry=input.dryRun===!0;if(already!==void 0)return{name:already,url:trust.trusted()[already].url,trusted:!0,alreadyTrusted:!0,dryRun:dry};let configured=configuredRepos(ctx.config),off=configured[input.repo];if(off!==void 0&&off.enabled===!1&&input.url===void 0)return dry||(await ctx.services.get("confd.managed").edit(REPOS_LAYER,root=>root.atPath(["repos",input.repo,"enabled"]).set(!0)),ctx.configChanged()),{name:input.repo,url:off.url,trusted:!dry,alreadyTrusted:!1,dryRun:dry};let url2=input.url??(REPO_NAME_PATTERN2.test(input.repo)?void 0:input.repo);if(url2===void 0)throw new ConfigError27(`Sous does not know where the repository '${input.repo}' lives.`,{details:[`Pass its URL: 'sous repo trust ${input.repo} --url <url>', or add it with 'sous repo add <url> --name ${input.repo}'.`]});let identity2=identityOf(ctx,url2),name=REPO_NAME_PATTERN2.test(input.repo)?input.repo:proposeRepoName(Object.keys(configured),identity2??url2),provider=ctx.services.get("refs.locations").hostFor(url2)?.id,done2=await trust.confirm([{name,url:url2,...identity2===void 0?{}:{identity:identity2},...provider===void 0?{}:{provider},requiredBy:[{ref:input.repo,requestedBy:"project"}]}],{...input.yes===void 0?{}:{yes:input.yes},dryRun:dry},ctx);return dry||ctx.configChanged(),{name,url:url2,trusted:done2.added.includes(name)&&!dry,alreadyTrusted:!1,dryRun:dry}}async function listRepos(input,ctx){let cache2=ctx.services.get("recipes.index-cache"),links=ctx.services.has("recipes.links")?ctx.services.get("recipes.links").all():{},locations=ctx.services.get("refs.locations"),listings=[];for(let[name,entry]of Object.entries(configuredRepos(ctx.config))){let enabled=entry.enabled!==!1,problem,cached2=cachedOrNothing(cache2,name);if(enabled&&input.latest===!0&&input.installed!==!0)try{cached2=await readUpstream(ctx,name)}catch(error51){problem=describeError2(error51),cached2=cachedOrNothing(cache2,name)}let installed2=input.installed===!0?pinsFrom(ctx,name):void 0;if(installed2!==void 0&&installed2.length===0)continue;let provider=entry.provider;try{provider??=locations.hostFor(entry.url)?.id}catch{}listings.push({name,url:entry.url,provider:provider??"unknown",enabled,alwaysPull:entry.alwaysPull===!0,...entry.addedBy===void 0?{}:{addedBy:entry.addedBy},...entry.addedAt===void 0?{}:{addedAt:entry.addedAt},...cached2===void 0?{}:{namespaces:sortBytewise(Object.keys(cached2.index.namespaces)),recipeCount:Object.keys(cached2.index.recipes).length,indexSource:cached2.source,...cached2.meta?.lastCheckedAt===void 0?{}:{lastCheckedAt:cached2.meta.lastCheckedAt}},...links[name]===void 0?{}:{linkedPath:links[name].path},...problem===void 0?{}:{problem},...installed2===void 0?{}:{installed:installed2}})}let repos=configuredRepos(ctx.config);return listings.sort((left,right)=>Number(isBuiltInEntry(repos[right.name]))-Number(isBuiltInEntry(repos[left.name]))||(left.name<right.name?-1:left.name>right.name?1:0))}function cachedOrNothing(cache2,name){try{return cache2.cached(name)}catch{return}}function pinsFrom(ctx,repo){let recipes;try{recipes=ctx.services.get("recipes.lock").read().recipes}catch{return[]}return sortBytewise(Object.keys(recipes).filter(key=>recipes[key].repo===repo)).map(key=>({key,version:recipes[key].version}))}function matchScore(text,name,description){let wanted=text.toLowerCase(),candidate=name.toLowerCase();return candidate===wanted?100:candidate.startsWith(wanted)?75:candidate.includes(wanted)?50:description?.toLowerCase().includes(wanted)===!0?20:0}function sortVersions(versions){return[...versions].sort((left,right)=>{let a=import_semver10.default.valid(left,{loose:!0}),b=import_semver10.default.valid(right,{loose:!0});return a!==null&&b!==null?import_semver10.default.compare(a,b):a!==null?-1:b!==null?1:left<right?-1:left>right?1:0})}async function searchRepos(input,ctx){let catalog=await loadCatalog(ctx,input),matches=[],lock=catalog.inputs.lock;for(let repo of catalog.inputs.repos){for(let[namespace,declared]of input.installed===!0?[]:Object.entries(repo.index.namespaces)){let score=matchScore(input.text,namespace,declared.description);score>0&&matches.push({ref:publishedNamespaceRef(repo,namespace),key:namespace,kind:"namespace",repo:repo.name,...declared.description===void 0?{}:{description:declared.description},score})}for(let[key,recipe]of Object.entries(repo.index.recipes)){let score=Math.max(matchScore(input.text,splitRecipeKey(key).name,recipe.description),matchScore(input.text,key)),pinned=lock.recipes[key]?.repo===repo.name?lock.recipes[key].version:void 0;if(score>0&&matches.push({ref:publishedRecipeRef(repo,key),key,kind:"recipe",repo:repo.name,...recipe.description===void 0?{}:{description:recipe.description},score,versions:sortVersions(Object.keys(recipe.versions)),...pinned===void 0?{}:{installed:pinned}}),input.installed===!0)continue;let version2=latestVersion(recipe.versions);for(let variable of(version2===void 0?void 0:recipe.versions[version2]?.variables)??[]){let variableScore=matchScore(input.text,variable.name,variable.description);if(variableScore>0){let ref={kind:"variable",name:variable.name,recipe:publishedRecipeRef(repo,key),description:variable.description};matches.push({ref,key:`${key}.${variable.name}`,kind:"variable",repo:repo.name,description:variable.description,score:variableScore-5})}}}}return matches.sort((left,right)=>right.score-left.score||(left.key<right.key?-1:left.key>right.key?1:0)).slice(0,input.limit??20)}function registerRepoIntents(sous){sous.intents.add({intent:"repo.add",requiresProject:!0,summary:"Add a recipe repository, which trusts it",input:inputSchema({url:{type:"string",description:"The repository's URL, or a path on this machine"},name:{type:"string",description:"The short name refs use for it; default from the URL"},provider:{type:"string",minLength:1,description:`The repository host, when the URL does not give it away: ${BUILT_IN_PROVIDERS.join(", ")}, or any host a plugin adds`},yes,dryRun},["url"]),changesConfig:!0,cli:{positional:["url"],flags:{yes:yesFlag}},handle:async(input,ctx)=>repoAddOutputs(await addRepo(input,ctx))}),sous.intents.add({intent:"repo.remove",requiresProject:!0,summary:"Stop trusting a repository, removing the subscriptions that resolve into it",input:inputSchema({repo:{type:"string",description:"The repository's short name"},yes,dryRun,noBuild},["repo"]),changesConfig:!0,cli:{aliases:[["repo","rm"]],positional:["repo"],flags:{yes:yesFlagNoTrust}},handle:async(input,ctx)=>repoRemoveOutputs(ctx,await removeRepo(input,ctx))}),sous.intents.add({intent:"repo.trust",requiresProject:!0,summary:"Trust a repository by name, URL or identity",input:inputSchema({repo:{type:"string",description:"A short name, URL or identity"},url:{type:"string",description:"Its URL, when the name has none recorded"},yes,dryRun},["repo"]),changesConfig:!0,cli:{positional:["repo"],flags:{yes:yesFlag}},handle:async(input,ctx)=>repoTrustOutputs(await trustRepo(input,ctx))}),sous.intents.add({intent:"repo.list",requiresProject:!0,summary:"List the repositories this project trusts",input:inputSchema({latest,installed,verbose:{type:"boolean",description:"Show more about each repository"}}),parallel:!0,cli:{aliases:[["repo","ls"]],flags:{latest:latestFlag}},handle:async(input,ctx)=>repoListOutputs(ctx,input,await listRepos(input,ctx))}),sous.intents.add({intent:"repo.search",requiresProject:!0,summary:"Search the trusted repositories for namespaces, recipes and variables",input:inputSchema({text:{type:"string",description:"What to look for"},latest,installed,limit:{type:"integer",description:"At most this many matches (default 20)"}},["text"]),parallel:!0,cli:{aliases:[["search"]],positional:["text"],flags:{latest:latestFlag}},handle:async(input,ctx)=>repoSearchOutputs(ctx,input,await searchRepos(input,ctx))})}var import_semver10,BUILT_IN_PROVIDERS,init_repo=__esm({"../sous-plugin-recipes/src/part-a/intents/repo.ts"(){"use strict";import_semver10=__toESM(require_semver2(),1);init_catalog();init_catalog_context();init_defaults();init_followups();init_lock_holds();init_project();init_subscriptions();init_util2();init_catalog_outputs();init_repo_outputs();init_schema();BUILT_IN_PROVIDERS=["github","gitlab","local"]}});import{SousError as SousError20}from"@sous-io/sous-plugin-api";async function checkProvidedAnswers(ctx,resolved,flags,download2){if((flags.answer===void 0||flags.answer.length===0)&&flags.answersFile===void 0||!ctx.services.has("recipe-answers.preanswers"))return;let preanswers=ctx.services.get("recipe-answers.preanswers"),{defined}=await definedVariables(ctx,resolved,download2),keys=new Set(defined.map(variable=>variable.key)),existing=[];try{existing=ctx.services.has("recipe-answers.definitions")?ctx.services.get("recipe-answers.definitions").listSync():[]}catch{existing=[]}try{let answers=await preanswers.read({...flags.answer===void 0?{}:{answer:flags.answer},...flags.answersFile===void 0?{}:{answersFile:flags.answersFile}});preanswers.match(answers,[...defined,...existing.filter(variable=>!keys.has(variable.key))])}catch(error51){if(error51 instanceof SousError20&&error51.details.length>0){let[first2,...rest]=error51.details;throw new SousError20(first2??error51.message,{details:rest})}throw error51}}async function holdAnswers(ctx,resolved,flags){if(!ctx.services.has("recipe-answers.asking")||!ctx.services.has("recipe-answers.definitions"))return;let definitions2=ctx.services.get("recipe-answers.definitions"),{defined}=await definedVariables(ctx,resolved),replaced=new Set(defined.map(variable=>`${variable.recipe.namespace}/${variable.recipe.name}`)),active=[];try{active=definitions2.listSync().filter(variable=>!replaced.has(`${variable.recipe.namespace}/${variable.recipe.name}`))}catch{active=[]}return ctx.services.get("recipe-answers.asking").hold(definitions2.combine([...active,...defined]),{within:resolved.map(recipe=>recipe.key),...flags.answer===void 0?{}:{answer:flags.answer},...flags.answersFile===void 0?{}:{answersFile:flags.answersFile}},ctx)}var init_provided_answers=__esm({"../sous-plugin-recipes/src/part-a/provided-answers.ts"(){"use strict";init_questions()}});import{LogLevel as LogLevel7,NonInteractiveError as NonInteractiveError3,SousError as SousError21}from"@sous-io/sous-plugin-api";function trustEntry(repo){let requesters=[...new Set(repo.requiredBy.map(entry=>entry.requestedBy))].sort(compareBytewise2);return{url:repo.url??"",...repo.provider===void 0?{}:{provider:repo.provider},addedAt:nowIso(),addedBy:requesters.length>0?requesters.join(", "):USER_ADDED_BY}}function trustQuestion(missing){return missing.length===1?`Do you trust the repository '${missing[0].name}'?`:`Do you trust these ${missing.length} repositories?`}function reportTrustNotice(reporter,missing){reporter.notice(missing.length===1?"One repository has to be trusted before this can continue.":`${missing.length} repositories have to be trusted before this can continue.`);for(let repo of missing){let entries=[{label:"Location",value:repo.url??"not known to sous; a ref named it by its short name only"}];repo.identity!==void 0&&entries.push({label:"Identity",value:repo.identity});for(let entry of repo.requiredBy)entries.push({label:"Required",value:`${entry.ref} (required by ${entry.requestedBy==="project"?"this project":`'${entry.requestedBy}'`})`});reporter.variables(entries,repo.name,LogLevel7.Notice)}reporter.note("Trusting a repository trusts every namespace and every recipe in it, including ones published later. Trusting on its own runs nothing; subscribing to something inside it can, and probably will, run scripts on this machine."),reporter.note("Sous cannot tell you whether a repository deserves trust. Look at the location above, and at who publishes it, before answering.")}function nonInteractiveDetails(missing){let lines3=[];for(let repo of missing){let provenance=repo.requiredBy.map(entry=>`${entry.ref} (required by ${entry.requestedBy})`).join(", ");lines3.push(`${repo.name}: ${repo.url??"URL not known to sous"}`,` ${provenance}`)}return lines3.push("Trusting a repository trusts every namespace and recipe in it, and subscribing to something inside it can run scripts on this machine.","Add each repository deliberately, with its URL:",...missing.map(repo=>` sous repo add ${repo.url??"<url>"} --name ${repo.name} --yes`)),lines3}function needUrlError(names2){return new SousError21(names2.length===1?`Sous does not know where the repository '${names2[0]}' lives, so it cannot add it for you.`:`Sous does not know where these repositories live, so it cannot add them for you: ${names2.map(name=>`'${name}'`).join(", ")}.`,{details:["A recipe names the repository it depends on by its short name only; the URL has to come from you.","Add each one with its URL, then run this command again:",...names2.map(name=>` sous repo add <url> --name ${name}`)]})}var Trust,init_trust=__esm({"../sous-plugin-recipes/src/part-a/trust.ts"(){"use strict";init_defaults();init_project();init_util2();Trust=class{constructor(config2,services){this.config=config2;this.services=services}trusted(){return trustedRepos(this.config)}isTrusted(repository){return this.nameOf(repository)!==void 0}nameOf(repository){let trusted=this.trusted();if(Object.hasOwn(trusted,repository))return repository;let wanted=this.identityOf(repository);if(wanted!==void 0)return Object.keys(trusted).find(name=>this.identityOf(trusted[name].url)===wanted)}async confirm(missing,options2,io){await this.decide(missing,options2,io);let{added,needUrl}=await this.record(missing,options2);return{accepted:[...missing],added,needUrl}}async decide(missing,options2,io){if(missing.length>0&&options2.yes!==!0&&options2.dryRun!==!0){if(!io.prompter.interactive)throw new NonInteractiveError3(trustQuestion(missing),"--yes",{details:nonInteractiveDetails(missing)});if(reportTrustNotice(io.reporter,missing),!await io.prompter.confirm({message:trustQuestion(missing),answeredBy:"--yes",default:!1}))throw new SousError21(`Nothing was installed: trust was declined for ${missing.map(repo=>`'${repo.name}'`).join(", ")}.`,{details:["Sous installs a dependency closure whole or not at all, so declining any repository in it stops the install."]})}}async record(missing,options2={}){let managed=this.services.get("confd.managed"),added=[],needUrl=[];for(let repo of missing){if(repo.url===void 0){needUrl.push(repo.name);continue}await writeRepoEntry(managed,repo.name,trustEntry(repo),options2.dryRun===!0),added.push(repo.name)}return{added,needUrl}}identityOf(repository){try{return this.services.get("refs.locations").identity(repository).toLowerCase()}catch{return repository.includes("/")&&!repository.includes("://")?repository.toLowerCase():void 0}}}}});function recordedRange(recorded,declared){if(recorded?.version!==void 0){let caret=`^${recorded.version}`;return declared===void 0?caret:intersectRanges(caret,declared)}return declared??recorded?.range}function intersectRanges(left,right){try{if(import_semver11.default.subset(left,right))return left;if(import_semver11.default.subset(right,left))return right;let sets=range3=>new import_semver11.default.Range(range3).set.map(comparators=>comparators.map(comparator=>comparator.value).join(" "));return sets(left).flatMap(one=>sets(right).map(other=>`${one} ${other}`.trim()||"*")).join(" || ")}catch{return left}}function declaredRange(declared,parse6){if(declared!==void 0){for(let reading of parse6(declared))if(reading.kind==="recipe"&&reading.range!==void 0)return reading.range}}var import_semver11,init_ranges=__esm({"../sous-plugin-recipes/src/part-b/resolver/ranges.ts"(){"use strict";import_semver11=__toESM(require_semver2(),1)}});import{ConfigError as ConfigError28}from"@sous-io/sous-plugin-api";async function resolveWanted(requests,context){let resolved=new Map,missingRepos=new Map,unreadable2=new Set,cycles=[],parents=new Map,walked=new Map,walkedPins=new Set,queue=requests.map(request=>({...request,kind:request.kind??"subscribes",written:request.written??describeWanted(request)}));for(;queue.length>0;){let item=queue.shift();if(item.repo!==void 0&&!Object.hasOwn(context.repos,item.repo)&&item.remote===void 0){recordMissing(missingRepos,{name:item.repo,requiredBy:[{ref:item.written,requestedBy:item.requestedBy}]});continue}if(item.remote!==void 0){let added=repoNamedByIdentity(context.repos,item.remote.identity);if(added===void 0){recordMissing(missingRepos,{name:proposeRepoName2(context.repos,item.remote.identity),url:item.remote.url,identity:item.remote.identity,...item.remote.provider===void 0?{}:{provider:item.remote.provider},requiredBy:[{ref:item.written,requestedBy:item.requestedBy}]});continue}item.repo=added,item.remote.browsed!==void 0&&settleBrowsedItem(item,context.indexes.get(added))}if(item.name===void 0){queue.push(...expandNamespace(item,context));continue}let recipe=resolveRecipe(item,context,resolved);resolved.set(recipe.key,recipe),item.requestedBy!==PROJECT_HOLDER&&!parents.has(recipe.key)&&parents.set(recipe.key,item.requestedBy);for(let pin of recipe.pins??[]){if(pin.version===recipe.version||walkedPins.has(`${recipe.key}@${pin.version}`))continue;walkedPins.add(`${recipe.key}@${pin.version}`);let view=pinnedView(recipe,pin),pinLists=await safeLoad(context,view)??view.declares;if(pinLists===void 0){unreadable2.add(recipe.key);continue}queue.push(...dependencyRequests(pinLists,view,context))}if(walked.get(recipe.key)===recipe.version){let cycle=findCycle(recipe.key,item.requestedBy,parents);cycle!==void 0&&cycles.push(cycle);continue}walked.set(recipe.key,recipe.version);let lists=await safeLoad(context,recipe)??recipe.declares;if(lists===void 0){unreadable2.add(recipe.key);continue}queue.push(...dependencyRequests(lists,recipe,context))}return await keepOnlyReachable(resolved,context),{resolved:sortKeys2(resolved.keys()).map(key=>{let recipe=resolved.get(key);return recipe.requestedBy.sort(),recipe}),missingRepos:[...missingRepos.values()].sort((left,right)=>left.name<right.name?-1:left.name>right.name?1:0),unreadable:sortKeys2(unreadable2),cycles}}function dependencyRequests(lists,parent,context){return[...lists.depends.map(written=>dependencyRequest(written,parent,"depends",context)),...lists.subscribes.map(written=>dependencyRequest(written,parent,"subscribes",context))]}function pinnedView(recipe,pin){let{dependencies:_dependencies,variables:_variables,declares:_declares,...rest}=recipe;return{...rest,version:pin.version,hash:pin.hash,tag:pin.tag,...pin.dependencies===void 0?{}:{dependencies:pin.dependencies},...pin.variables===void 0?{}:{variables:pin.variables},...pin.declares===void 0?{}:{declares:{depends:[...pin.declares.depends],subscribes:[...pin.declares.subscribes]}}}}async function safeLoad(context,recipe){try{return await context.loadManifest(recipe)}catch{return}}function repoNamedByIdentity(repos,identity2){return Object.entries(repos).find(([,entry])=>entry.identity===identity2)?.[0]}function proposeRepoName2(repos,identity2){let base=identitySegments2(identity2).at(-1)??"repository";if(!Object.hasOwn(repos,base))return base;for(let suffix=2;;suffix+=1)if(!Object.hasOwn(repos,`${base}-${suffix}`))return`${base}-${suffix}`}function indexDependencyLists(version2){if(!(version2===void 0||version2.depends===void 0&&version2.subscribes===void 0))return{depends:version2.depends??[],subscribes:version2.subscribes??[]}}function wantedOf(ref){if(ref.kind==="namespace")return{namespace:ref.name,...repoParts(ref.repo)};if(ref.kind==="recipe"){let repo=ref.namespace?.repo??ref.repo;return ref.namespace===void 0?void 0:{namespace:ref.namespace.name,name:ref.name,...ref.range===void 0?{}:{range:ref.range},...repoParts(repo)}}if(ref.kind==="repo"&&ref.browsed!==void 0)return{namespace:"",...repoParts(ref),browsed:{path:ref.browsed,...ref.range===void 0?{}:{range:ref.range}}}}function repoParts(repo){return{...repo?.name===void 0?{}:{repo:repo.name},...repo?.location===void 0?{}:{location:repo.location}}}function describeWanted(wanted){let key=wanted.name===void 0?wanted.namespace:`${wanted.namespace}/${wanted.name}`;return`${wanted.repo===void 0?"":`${wanted.repo}:`}${key}${wanted.range===void 0?"":`@${wanted.range}`}`}function dependencyRequest(written,parent,kind,context){let reading=settleDependency(written,parent,context),base={requestedBy:parent.key,kind,written:written.trim(),...parent.prerelease?{prerelease:!0}:{}},wanted=reading===void 0?void 0:wantedOf(reading);if(wanted===void 0)throw unsettledDependencyError(written,parent,context);if(wanted.browsed!==void 0&&wanted.location!==void 0)return{namespace:"",...base,remote:{identity:wanted.location.identity,url:wanted.location.url,provider:wanted.location.provider,browsed:wanted.browsed,...parent.dependencies===void 0?{}:{pins:parent.dependencies}}};let key=wanted.name===void 0?void 0:`${wanted.namespace}/${wanted.name}`,pinned=key===void 0?void 0:parent.dependencies?.[key],range3=wanted.name===void 0?void 0:recordedRange(pinned,wanted.range),target={namespace:wanted.namespace,...wanted.name===void 0?{}:{name:wanted.name},...range3===void 0?{}:{range:range3}};return wanted.location===void 0?{...target,...base,repo:wanted.repo??parent.repo}:{...target,...base,remote:{identity:pinned?.repo??wanted.location.identity,url:wanted.location.url,provider:wanted.location.provider}}}function settleDependency(written,parent,context){let readings=context.parseDependency(written);if(readings.length===1)return readings[0];let confirmed=readings.filter(reading=>isConfirmedByRecord(reading,parent.dependencies));if(confirmed.length===1)return confirmed[0];let known=readings.filter(reading=>knownLocally(reading,context));return known.length===1?known[0]:void 0}function isConfirmedByRecord(candidate,recorded){let wanted=wantedOf(candidate);if(wanted===void 0)return!1;let identity2=wanted.location?.identity,records=Object.entries(recorded??{}).filter(([,record2])=>identity2===void 0?record2?.repo===void 0:record2?.repo===identity2);return wanted.browsed!==void 0?identity2!==void 0&&records.length>0:wanted.name===void 0?records.some(([key])=>key.startsWith(`${wanted.namespace}/`)):records.some(([key])=>key===`${wanted.namespace}/${wanted.name}`)}function knownLocally(reading,context){let wanted=wantedOf(reading);if(wanted?.location===void 0)return!1;let added=repoNamedByIdentity(context.repos,wanted.location.identity),index=added===void 0?void 0:context.indexes.get(added);return index===void 0?!1:wanted.browsed!==void 0?settleBrowsed(wanted.browsed.path,index).length>0:wanted.name===void 0?Object.hasOwn(index.namespaces,wanted.namespace):publishedOrRetired(index,`${wanted.namespace}/${wanted.name}`)!==void 0}function settleBrowsed(browsed,index){let segments=browsed.split("/").filter(segment=>segment.length>0),recipes=Object.entries(index.recipes).map(([key,recipe])=>({key,path:(recipe.path??"").replace(/^\.?\/+|\/+$/g,"")})).filter(entry=>entry.path.length>0),found=new Map;for(let start2=1;start2<segments.length;start2+=1){let folder=segments.slice(start2).join("/"),deepest=recipes.filter(entry=>folder===entry.path||folder.startsWith(`${entry.path}/`)).sort((left,right)=>right.path.length-left.path.length)[0];deepest!==void 0&&found.set(deepest.key,splitStoredKey(deepest.key))}if(found.size>0)return[...found.values()];for(let start2=1;start2<segments.length;start2+=1){let folder=segments.slice(start2).join("/"),namespaces=new Set(recipes.filter(entry=>entry.path.startsWith(`${folder}/`)).map(entry=>splitStoredKey(entry.key).namespace));if(namespaces.size===1){let[namespace]=namespaces;found.set(namespace,{namespace})}}return[...found.values()]}function settleBrowsedItem(item,index){let remote=item.remote,browsed=remote.browsed,settled=index===void 0?[]:settleBrowsed(browsed.path,index),found=settled.length===1?settled[0]:void 0;if(found===void 0){let recorded=Object.keys(remote.pins??{}).filter(key2=>remote.pins?.[key2]?.repo===remote.identity);recorded.length===1&&(found=splitStoredKey(recorded[0]))}if(found===void 0)throw new ConfigError28(`The dependency '${item.written}' names a folder, and the index of the repository at ${remote.url} ${settled.length===0?"publishes no recipe there":"publishes several recipes there"}.`,{details:[`It was required by the recipe '${item.requestedBy}'. Write the dependency as the recipe it means, such as '${remote.url}/<namespace>/<recipe>'.`]});let key=found.name===void 0?void 0:`${found.namespace}/${found.name}`,pinned=key===void 0?void 0:remote.pins?.[key];item.namespace=found.namespace,item.name=found.name,item.range=found.name===void 0?void 0:recordedRange(pinned,browsed.range)}function unsettledDependencyError(written,parent,context){let readings=context.parseDependency(written);return new ConfigError28(`The dependency '${written.trim()}' of the recipe '${parent.key}' can be read ${readings.length} ways, and nothing says which one it means.`,{details:[`A release records which one it settled on in the index; the index of '${parent.repo}' records none for this version.`,"Release the recipe again with this version of sous, or write the dependency so it reads one way."]})}function expandNamespace(item,context){let expanded=[],seen=new Set,found=!1;for(let[repoName,index]of context.indexes)if(!(item.repo!==void 0&&repoName!==item.repo||!Object.hasOwn(index.namespaces,item.namespace))){found=!0;for(let key of Object.keys(index.recipes))!key.startsWith(`${item.namespace}/`)||seen.has(key)||(seen.add(key),expanded.push({namespace:item.namespace,name:key.slice(item.namespace.length+1),...item.range===void 0?{}:{range:item.range},...item.repo===void 0?{}:{repo:item.repo},requestedBy:item.requestedBy,kind:item.kind,written:item.written,...item.prerelease===void 0?{}:{prerelease:item.prerelease}}))}if(!found)throw unknownRefError2(item,context,"namespace");return expanded}function resolveRecipe(item,context,resolved){let key=`${item.namespace}/${item.name}`,candidates=[];for(let[repoName,index]of context.indexes)(item.repo===void 0||repoName===item.repo)&&Object.hasOwn(index.recipes,key)&&candidates.push(repoName);if(candidates.length===0)for(let[repoName,index]of context.indexes)(item.repo===void 0||repoName===item.repo)&&publishedOrRetired(index,key)!==void 0&&candidates.push(repoName);if(candidates.length===0)throw unknownRefError2(item,context,"recipe");if(candidates.length>1)throw ambiguousRefError(item,key,candidates);let repo=candidates[0],entry=publishedOrRetired(context.indexes.get(repo),key).entry,previous=resolved.get(key);if(previous!==void 0&&previous.repo!==repo)throw new ConfigError28(`The recipe '${key}' is being taken from two repositories at once: '${previous.repo}' and '${repo}'.`,{details:["Qualify the refs that ask for it, so each one says which repository it means."]});let ranges=[...previous?.ranges??[]],range3=item.range??"*",known=ranges.findIndex(one=>one.range===range3&&one.requestedBy===item.requestedBy);known===-1?ranges.push({range:range3,requestedBy:item.requestedBy,kind:item.kind}):item.kind==="subscribes"&&ranges[known].kind==="depends"&&(ranges[known]={...ranges[known],kind:"subscribes"});let prerelease=(previous?.prerelease??!1)||(item.prerelease??context.prerelease??!1),settled=settleVersions(key,entry,ranges,prerelease,context.keep?.[key],context.keepPins?.[key]),version2=settled.version,versionEntry=entry.versions[version2],declares2=indexDependencyLists(versionEntry),pins=Object.entries(settled.pins).sort(([left],[right])=>left<right?-1:left>right?1:0).map(([holder,pinned])=>{let pinnedEntry=entry.versions[pinned],pinnedDeclares=indexDependencyLists(pinnedEntry);return{holder,version:pinned,hash:pinnedEntry.hash,tag:pinnedEntry.tag,...pinnedEntry.dependencies===void 0?{}:{dependencies:pinnedEntry.dependencies},...pinnedEntry.variables===void 0?{}:{variables:pinnedEntry.variables},...pinnedDeclares===void 0?{}:{declares:{depends:[...pinnedDeclares.depends],subscribes:[...pinnedDeclares.subscribes]}}}}),requestedBy=[...previous?.requestedBy??[]];return requestedBy.includes(item.requestedBy)||requestedBy.push(item.requestedBy),{key,namespace:item.namespace,name:item.name,repo,identity:context.repos[repo]?.identity??repo,version:version2,hash:versionEntry.hash,tag:versionEntry.tag,path:entry.path,...versionEntry.dependencies===void 0?{}:{dependencies:versionEntry.dependencies},...versionEntry.variables===void 0?{}:{variables:versionEntry.variables},...declares2===void 0?{}:{declares:{depends:[...declares2.depends],subscribes:[...declares2.subscribes]}},kind:previous?.kind==="subscribes"||item.kind==="subscribes"?"subscribes":"depends",requestedBy,ranges,prerelease,...pins.length===0?{}:{pins}}}function settleVersions(key,entry,ranges,prerelease,keep,keepPins){let conflict;try{return{version:pickVersion(key,entry,ranges,prerelease,keep),pins:{}}}catch(error51){if(!(error51 instanceof NoVersionSatisfiesError))throw error51;conflict=error51}let holders=new Map;for(let one of ranges){let holder=holders.get(one.requestedBy)??{ranges:[],subscribes:!1};holder.ranges.push(one),holder.subscribes||=one.kind!=="depends",holders.set(one.requestedBy,holder)}let sharing=[...holders.values()].filter(holder=>holder.subscribes),allows=(version3,holder)=>holder.ranges.every(({range:range3})=>import_semver12.default.satisfies(version3,range3,{includePrerelease:prerelease})),version2;if(sharing.length>0)version2=pickVersion(key,entry,sharing.flatMap(holder=>holder.ranges),prerelease,keep);else{let counted=Object.keys(entry.versions).filter(one=>prerelease||entry.versions[one].prerelease!==!0).map(one=>({version:one,count:[...holders.values()].filter(holder=>allows(one,holder)).length})),most=Math.max(0,...counted.map(one=>one.count));if(most===0)throw conflict;let best=counted.filter(one=>one.count===most).map(one=>one.version);version2=keep!==void 0&&best.includes(keep)?keep:best.sort((left,right)=>import_semver12.default.rcompare(left,right,{loose:!0}))[0]}let pins={};for(let[name,holder]of holders)!holder.subscribes&&!allows(version2,holder)&&(pins[name]=pickVersion(key,entry,holder.ranges,prerelease,keepPins?.[name]));return{version:version2,pins}}function pickVersion(key,entry,ranges,prerelease,keep){let published=Object.keys(entry.versions),candidates=prerelease?published:published.filter(version2=>entry.versions[version2].prerelease!==!0);for(let{range:range3}of ranges)candidates=candidates.filter(version2=>import_semver12.default.satisfies(version2,range3,{includePrerelease:prerelease}));if(keep!==void 0&&Object.hasOwn(entry.versions,keep)&&ranges.every(({range:range3})=>import_semver12.default.satisfies(keep,range3,{includePrerelease:!0})))return keep;let best=import_semver12.default.maxSatisfying(candidates,"*",{includePrerelease:prerelease});if(best!==null)return best;let asked=ranges.map(({range:range3,requestedBy})=>` ${range3} (required by ${requestedBy})`),available=[...published].sort((left,right)=>import_semver12.default.rcompare(left,right,{loose:!0})).join(", ");throw new NoVersionSatisfiesError(key,ranges,`No published version of '${key}' satisfies what was asked for.`,{details:[`Version ${ranges.length===1?"range":"ranges"} asked for:`,...asked,`Versions this repository publishes: ${available}.`,...prerelease?[]:["Prerelease versions were not considered. A subscription may opt into them with 'prerelease: true', and 'sous subscribe' with '--prerelease'."]]})}function unknownRefError2(item,context,what){let searched=[...context.indexes.keys()],index=item.repo===void 0?void 0:context.indexes.get(item.repo),search2=what==="namespace"?item.namespace:item.name??item.namespace;if(searched.length===0)return new UnknownRefError(what,item.written,`No repository publishes the ${what} '${item.written}', because this project has added none yet.`,{details:[...item.requestedBy===PROJECT_HOLDER?[]:[`It was required by the recipe '${item.requestedBy}'.`],"Add the repository that publishes it with 'sous repo add <url>', then try again."]});let checked3=context.checkedNow,now=checked3===void 0?[]:searched.filter(name=>checked3.has(name)),cached2=searched.filter(name=>!now.includes(name)),details=[...now.length===0?[]:[`Checked just now: ${now.join(", ")}.`],...cached2.length===0?[]:[checked3===void 0?`Searched the copies of these indexes that sous already had: ${cached2.join(", ")}.`:`Could not be checked just now, so the copies of their indexes that sous already had were searched: ${cached2.join(", ")}.`],...item.requestedBy===PROJECT_HOLDER?[]:[`It was required by the recipe '${item.requestedBy}'.`],...index===void 0?[]:[`The repository '${item.repo}' publishes: ${Object.keys(index.recipes).length===0?"nothing yet":sortKeys2(Object.keys(index.recipes)).join(", ")}.`],item.repo===void 0?`Check the spelling, or run 'sous repo search ${search2}' to look for it. If a repository this project has not added publishes it, add that one with 'sous repo add <url>'.`:`Check the spelling, or run 'sous repo search ${search2}' to look for it.`];return new UnknownRefError(what,item.written,`None of this project's repositories publishes the ${what} '${item.written}'.`,{details})}function ambiguousRefError(item,key,repos){let range3=item.range===void 0||item.range==="*"?"":`@${item.range}`;return new ConfigError28(`The ref '${key}' is published by more than one added repository: ${repos.join(", ")}.`,{details:[...item.requestedBy===PROJECT_HOLDER?[]:[`It was required by the recipe '${item.requestedBy}'.`],"Say which repository you mean by qualifying the ref with its name:",...repos.map(repo=>` ${repo}:${key}${range3}`)]})}function recordMissing(into,missing){let existing=into.get(missing.name);if(existing===void 0){into.set(missing.name,missing);return}for(let entry of missing.requiredBy)existing.requiredBy.some(known=>known.ref===entry.ref&&known.requestedBy===entry.requestedBy)||existing.requiredBy.push(entry)}function findCycle(key,from,parents){if(from===PROJECT_HOLDER)return;let chain=[key],guard2=new Set,current=from;for(;current!==void 0&&current!==PROJECT_HOLDER;){if(chain.push(current),current===key)return chain.reverse();if(guard2.has(current))return;guard2.add(current),current=parents.get(current)}}async function keepOnlyReachable(resolved,context){let holders=new Map,pinQueue=[],declare=(parent,child2,kind)=>{let existing=holders.get(child2);if(existing?.has(parent)!==!0&&resolved.get(child2)?.pins?.some(pin=>pin.holder===parent)===!0&&pinQueue.push([child2,parent]),existing===void 0)return holders.set(child2,new Map([[parent,kind]])),!0;let previous=existing.get(parent);return existing.set(parent,previous==="subscribes"||kind==="subscribes"?"subscribes":kind),!1},queue=[],declareTargets=(lists,holder,key)=>{for(let[kind,refs]of[["depends",lists.depends],["subscribes",lists.subscribes]])for(let written of refs)for(let target of dependencyTargets(written,holder,context,resolved))resolved.has(target)&&declare(key,target,kind)&&queue.push(target)};for(let recipe of resolved.values())recipe.requestedBy.includes(PROJECT_HOLDER)&&declare(PROJECT_HOLDER,recipe.key,"subscribes")&&queue.push(recipe.key);for(;queue.length>0||pinQueue.length>0;){if(queue.length===0){let[key2,holder]=pinQueue.shift(),recipe2=resolved.get(key2),pin=recipe2.pins?.find(one=>one.holder===holder),view=pinnedView(recipe2,pin),lists2=await safeLoad(context,view)??view.declares;lists2!==void 0&&declareTargets(lists2,view,key2);continue}let key=queue.shift(),recipe=resolved.get(key);if(recipe===void 0)continue;let lists=await safeLoad(context,recipe)??recipe.declares;if(lists===void 0){for(let other of resolved.values())other.requestedBy.includes(key)&&declare(key,other.key,other.kind)&&queue.push(other.key);continue}declareTargets(lists,recipe,key)}for(let[key,recipe]of[...resolved]){let reached=holders.get(key);if(reached===void 0){resolved.delete(key);continue}recipe.requestedBy=[...reached.keys()],recipe.ranges=recipe.ranges.filter(entry=>reached.has(entry.requestedBy)),recipe.kind=[...reached.values()].includes("subscribes")?"subscribes":"depends";let pins=(recipe.pins??[]).filter(pin=>reached.has(pin.holder));pins.length===0?delete recipe.pins:recipe.pins=pins}}function dependencyTargets(written,holder,context,resolved){let item;try{if(item=dependencyRequest(written,holder,"depends",context),item.remote?.browsed!==void 0){let added=repoNamedByIdentity(context.repos,item.remote.identity);settleBrowsedItem(item,added===void 0?void 0:context.indexes.get(added))}}catch{return[]}return item.name===void 0?[...resolved.keys()].filter(key=>key.startsWith(`${item.namespace}/`)):[`${item.namespace}/${item.name}`]}var import_semver12,NoVersionSatisfiesError,UnknownRefError,init_resolve=__esm({"../sous-plugin-recipes/src/part-b/resolver/resolve.ts"(){"use strict";import_semver12=__toESM(require_semver2(),1);init_constants();init_support();init_ranges();NoVersionSatisfiesError=class extends ConfigError28{constructor(key,ranges,message2,options2){super(message2,options2);this.key=key;this.ranges=ranges}};UnknownRefError=class extends ConfigError28{constructor(what,written,message2,options2){super(message2,options2);this.what=what;this.written=written}}}});import fs32 from"node:fs";import path45 from"node:path";import{ConfigError as ConfigError29}from"@sous-io/sous-plugin-api";function stillFirst(since,now,memorySeconds){let at2=since===void 0?Number.NaN:Date.parse(since);return Number.isFinite(at2)&&now.getTime()-at2<memorySeconds*1e3}function formatReadFailure(failure){let lines3=[`could not read ${failure.repo}.`,...failure.attempts.map(attempt2=>` ${attempt2.strategy.padEnd(ATTEMPT_LABEL_WIDTH)} ${attempt2.reason}`)];return failure.fixes.length>0&&lines3.push("Fix one of these:",...failure.fixes.map(fix=>` ${fix}`)),lines3.join(`
@@ -462,8 +462,8 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
462
462
  `)[0]??"").trim(),newer:[]}}return{checked:!0,newer}}function subscriptionRange(key,subscriptions){let namespace=key.slice(0,key.indexOf("/"));for(let[subscription,entry]of Object.entries(subscriptions)){let stored=plainSubscriptionKey(subscription);if(stored===key||stored===namespace)return entry?.range??"*"}}function notLinkedMessage(links,name,scope){let other=scope==="global"?"project":"global",searched=scope==="global"?"the machine-wide links map":"this project's links map",elsewhere;try{elsewhere=links.getIn(name,other)}catch{elsewhere=void 0}if(elsewhere!==void 0)return`'${name}' is not linked in ${searched}. It is linked in the ${other==="project"?"project":"machine-wide"} map, at ${elsewhere.path}. Run the same command ${scope==="global"?"without":"with"} --global to remove that one.`;let linked=Object.keys(links.read(scope).links).sort();return`'${name}' is not linked in ${searched}. ${linked.length>0?`Linked there: ${linked.join(", ")}.`:"Nothing is linked there."} Run 'sous repo link ${name}' to link it.`}function unlinkOutputs(ctx,result){let outputs=[];if(result.dryRun?outputs.push(...(result.wouldDo??[]).map(line=>dryRunOutput(line))):outputs.push(blockOutput({Repository:result.repo,Checkout:result.path,Scope:result.scope==="global"?"every project on this machine":"this project",...result.recordedIn===void 0?{}:{Updated:result.recordedIn}}),sentence(`'${result.repo}' is read from the versions the lockfile pins again.`)),result.published!==void 0){let published=result.published,section2=[];published.checked?published.newer.length===0?section2.push(sentence(`Every pin from '${result.repo}' is the newest published version its range allows.`)):section2.push(sentence(`'${result.repo}' publishes newer versions within range. The lockfile still pins the older ones:`),blockOutput(published.newer.map(entry=>({label:entry.key,value:`${entry.from} pinned${entry.holder===void 0?"":` for ${entry.holder} alone`}, ${entry.to} published`})))):section2.push(noteOutput(`Sous could not check '${result.repo}' for newer published versions. ${published.reason??""}`.trim())),outputs.push(...underHeading("Published versions",section2))}for(let entry of result.followUps)entry.intent==="update"&&entry.outputs!==void 0&&outputs.push(...underHeading("Updating the pins",entry.outputs.toArray()));result.checkoutNote!==void 0&&outputs.push(sentence(result.checkoutNote));let rest=followUpOutputs({followUps:result.followUps.filter(entry=>entry.intent!=="update")});return rest.failed&&ctx.reporter.error(`The repository '${result.repo}' was unlinked, but the build that followed it failed; fix what the build reported above and run 'sous build' again.`),finish2(underHeading("Unlinking a repository",outputs),plainResult(result),{after:rest.outputs,...rest.failed?{exitCode:1}:{}})}var init_unlink_intent=__esm({"../sous-plugin-recipes/src/part-b/links/unlink-intent.ts"(){"use strict";init_constants();init_outputs();init_freshness();init_lock_service();init_lockfile_ops();init_ranges();init_reachable();init_support();init_checkout()}});function matchPinned(candidate,lockfile,isMatch){let entries=sortKeys2(Object.keys(lockfile.recipes)).map(key=>({key,...splitStoredKey(key),repo:lockfile.recipes[key].repo})),name=(written,known)=>isMatch(known,written,!1)?"exact":isMatch(known,written,!0)?"folded":void 0,both3=(...matches)=>matches.includes(void 0)?void 0:matches.every(match2=>match2==="exact")?"exact":"folded",found=[];if(candidate.kind==="namespace"){let seen=new Set;for(let entry of entries){let match2=both3(name(candidate.name,entry.namespace),candidate.repo?.name===void 0?"exact":name(candidate.repo.name,entry.repo));match2!==void 0&&!seen.has(entry.namespace)&&(seen.add(entry.namespace),found.push({ref:{kind:"namespace",name:entry.namespace,repo:{kind:"repo",name:entry.repo}},exactSpelling:match2==="exact"}))}return found}let recipe=candidate.kind==="recipe"?candidate:candidate.kind==="recipeFile"?candidate.recipe:void 0;if(recipe?.namespace===void 0)return found;let repo=recipe.namespace.repo?.name??recipe.repo?.name;for(let entry of entries){let match2=both3(name(recipe.namespace.name,entry.namespace),name(recipe.name,entry.name),repo===void 0?"exact":name(repo,entry.repo));if(match2===void 0)continue;let known={kind:"recipe",name:entry.name,namespace:{kind:"namespace",name:entry.namespace,repo:{kind:"repo",name:entry.repo}},...recipe.range===void 0?{}:{range:recipe.range}},ref=candidate.kind==="recipeFile"?{kind:"recipeFile",path:candidate.path,recipe:known,...candidate.glob?{glob:!0}:{},...candidate.vars?{vars:candidate.vars}:{}}:known;found.push({ref,exactSpelling:match2==="exact"})}return found}function lockfileLookup(){let findSync=(candidate,ctx)=>{if(ctx.project===void 0||!ctx.services.has("recipes.lock"))return[];let globs=ctx.services.get("host.globs");return matchPinned(candidate,ctx.services.get("recipes.lock").read(),(known,written,nocase)=>globs.isMatch(known,written,{nocase}))};return{id:LOCKFILE_LOOKUP_ID,description:"the recipes this project's lockfile pins",kinds:["namespace","recipe","recipeFile"],tags:["lockfile","installed"],optIn:!0,find:async(candidate,ctx)=>findSync(candidate,ctx),findSync}}var LOCKFILE_LOOKUP_ID,init_lockfile_lookup=__esm({"../sous-plugin-recipes/src/part-b/lookups/lockfile-lookup.ts"(){"use strict";init_support();LOCKFILE_LOOKUP_ID="recipes.lockfile"}});function explainMissing(recipe,input){let namespace=recipe.slice(0,recipe.indexOf("/"));for(let[key,entry]of Object.entries(input.subscriptions??{})){if(entry?.enabled!==!1)continue;let stored;try{stored=input.keyOf(key)}catch{continue}if(stored===recipe||stored===namespace)return{by:"disabled-subscription",subscription:key}}let lock;try{lock=input.lockfile()}catch{return}let published=new Map;for(let identity2 of sortKeys2(new Set(Object.values(lock.repos).flatMap(repo=>repo.identity===void 0?[]:[repo.identity]))))for(let[key,entry]of Object.entries(input.cachedIndex(identity2)?.recipes??{}))published.has(key)||published.set(key,entry.versions);let declaredBy=(key,version2)=>Object.keys(published.get(key)?.[version2]?.dependencies??{}),queue=[];for(let holder of sortKeys2(Object.keys(lock.recipes))){let pinned=lock.recipes[holder].version,versions=Object.keys(published.get(holder)??{}).filter(version2=>version2!==pinned&&import_semver16.default.valid(version2)!==null).sort(import_semver16.default.rcompare);for(let version2 of versions)for(let key of declaredBy(holder,version2))queue.push({key,root:{recipe:holder,version:version2},through:[]})}let seen=new Set;for(;queue.length>0;){let step=queue.shift();if(step.key===recipe)return{by:"recipe",recipe:step.root.recipe,declaredAt:step.root.version,pinned:lock.recipes[step.root.recipe].version,...step.through.length>0?{through:step.through}:{}};if(!(Object.hasOwn(lock.recipes,step.key)||seen.has(step.key))){seen.add(step.key);for(let version2 of Object.keys(published.get(step.key)??{}))for(let key of declaredBy(step.key,version2))queue.push({key,root:step.root,through:[...step.through,step.key]})}}}var import_semver16,init_explain_missing=__esm({"../sous-plugin-recipes/src/part-b/namespaces/explain-missing.ts"(){"use strict";import_semver16=__toESM(require_semver2(),1);init_support()}});import path58 from"node:path";function combine(left,right){if(!(left===void 0||right===void 0))return left==="exact"&&right==="exact"?"exact":"folded"}function climbs(pattern){return pattern.split(/[/{},]/).some(part=>part==="."||part==="..")}function escapeGlob(dir){return dir.replace(/[*?[\]{}()!+@\\]/g,char=>`\\${char}`)}var ActiveNamespaceResolver,init_namespace_resolver=__esm({"../sous-plugin-recipes/src/part-b/namespaces/namespace-resolver.ts"(){"use strict";init_support();ActiveNamespaceResolver=class{constructor(options2){this.options=options2;for(let recipe of options2.recipes){this.dirs.set(recipe.id,path58.resolve(recipe.dir)),this.repos.set(recipe.id,recipe.repo),this.versionDirs.push({key:recipe.id,dir:path58.resolve(recipe.dir)});for(let pin of recipe.pins??[]){let byHolder=this.pinDirs.get(recipe.id)??new Map;byHolder.set(pin.holder,path58.resolve(pin.dir)),this.pinDirs.set(recipe.id,byHolder),this.versionDirs.push({key:recipe.id,dir:path58.resolve(pin.dir)})}for(let holder of recipe.requestedBy){let held=this.dependencies.get(holder)??[];held.push(recipe.id),this.dependencies.set(holder,held)}}}dirs=new Map;repos=new Map;dependencies=new Map;pinDirs=new Map;versionDirs=[];includingRecipe(fromFile){return this.including(fromFile)?.key??null}including(fromFile){let target=path58.resolve(fromFile),best;for(let entry of this.versionDirs)(target===entry.dir||target.startsWith(entry.dir+path58.sep))&&entry.dir.length>(best?.dir.length??-1)&&(best=entry);return best}dirFor(key,including){return including!==void 0&&including.key===key?including.dir:(including===void 0?void 0:this.pinDirs.get(key)?.get(including.key))??this.dirs.get(key)}resolve(request){let{reference,fromFile}=request,parsed;try{parsed=this.options.parse(reference)}catch(error51){return{kind:"invalid",reference,message:error51 instanceof Error?error51.message:String(error51)}}let kept=parsed.refs.filter(ref=>ref.kind==="recipeFile");if(kept.length===0)return this.refused(reference,parsed);let written=kept.find(ref=>ref.vars!==void 0)??kept[0],namespace=written.recipe.namespace?.name??"",wanted=`${namespace}/${written.recipe.name}`,matched=this.match(written);if(matched.length===0)return written.glob===!0?{kind:"candidates",candidates:[],glob:!0}:this.knowsNamespace(namespace)?{kind:"unknown-recipe",recipe:wanted,known:this.recipesInNamespace(namespace),...this.droppedFor(wanted,fromFile)}:{kind:"unknown-namespace",namespace,recipe:wanted,known:this.namespaces(),...this.droppedFor(wanted,fromFile)};let holder=this.including(fromFile),including=holder?.key??null,declared=including===null?void 0:[including,...this.dependencies.get(including)??[]],candidates=[],roots=[];for(let key of matched){let dir=this.dirFor(key,holder);if(declared!==void 0&&!declared.some(entry=>entry===key||entry===key.slice(0,key.indexOf("/")))){if(written.glob===!0)continue;return{kind:"not-a-dependency",recipe:key,includingRecipe:including}}if(written.glob===!0){if(climbs(written.path))return{kind:"escapes-recipe",recipe:key,reference};candidates.push(`${escapeGlob(dir)}/${written.path}`),roots.push({recipe:key,dir});continue}let resolved=path58.resolve(dir,written.path),relative4=path58.relative(dir,resolved);if(resolved!==dir&&(relative4===""||relative4.startsWith("..")||path58.isAbsolute(relative4)))return{kind:"escapes-recipe",recipe:key,reference};candidates.push(resolved),roots.push({recipe:key,dir})}return written.glob===!0?{kind:"candidates",candidates,glob:!0,roots}:{kind:"candidates",candidates,roots}}namespaces(){return sortKeys2(new Set([...this.dirs.keys()].map(key=>key.slice(0,key.indexOf("/")))))}recipesInNamespace(written){let hits=[...this.dirs.keys()].map(key=>({key,match:this.matchName(written,key.slice(0,key.indexOf("/")))})).filter(hit=>hit.match!==void 0),exact=hits.filter(hit=>hit.match==="exact");return sortKeys2((exact.length>0?exact:hits).map(hit=>hit.key))}knowsNamespace(written){return[...this.dirs.keys()].some(key=>this.matchName(written,key.slice(0,key.indexOf("/")))!==void 0)}match(ref){let namespace=ref.recipe.namespace?.name;if(namespace===void 0)return[];let repo=ref.recipe.namespace?.repo?.name??ref.recipe.repo?.name,hits=[];for(let key of this.dirs.keys()){let slash=key.indexOf("/"),match2=combine(this.matchName(namespace,key.slice(0,slash)),this.matchName(ref.recipe.name,key.slice(slash+1)));if(repo!==void 0){let known=this.repos.get(key);match2=combine(match2,known===void 0?void 0:this.matchName(repo,known))}match2!==void 0&&hits.push({key,match:match2})}let exact=hits.filter(hit=>hit.match==="exact");return sortKeys2((exact.length>0?exact:hits).map(hit=>hit.key))}matchName(written,known){return this.options.isMatch(known,written,{nocase:!1})?"exact":this.options.isMatch(known,written,{nocase:!0})?"folded":void 0}refused(reference,parsed){for(let entry of parsed.dropped){let ref=entry.ref;if(ref.kind==="recipeFile"&&ref.path.split("/").some(part=>part==="."||part===".."))return{kind:"escapes-recipe",recipe:`${ref.recipe.namespace?.name??""}/${ref.recipe.name}`,reference}}let reasons=parsed.dropped.map(entry=>entry.instead===void 0?entry.reason:`${entry.reason} Write ${entry.instead}.`);return{kind:"invalid",reference,message:reasons.length>0?[...new Set(reasons)].join(`
463
463
  `):`'~${reference}' does not name a file inside a recipe.`}}droppedFor(recipe,fromFile){if(this.options.explainMissing===void 0||this.includingRecipe(fromFile)!==null)return{};let dropped=this.options.explainMissing(recipe);return dropped===void 0?{}:{dropped}}}}});import fs47 from"node:fs";import path59 from"node:path";import{pathToFileURL as pathToFileURL5}from"node:url";function pluginBundleOf(recipe){let entry=recipe.manifest.plugin;if(entry===void 0)return;let file2=insideRecipe(recipe.dir,entry.bundle);if(file2===void 0)return{problem:`The recipe ${recipe.id} names a plugin bundle outside its own files (${entry.bundle}), so it was not loaded.`};if(!fs47.existsSync(file2))return{problem:`The recipe ${recipe.id} names a plugin bundle that is not there (${entry.bundle}), so it was not loaded.`};let types2=entry.types===void 0?void 0:insideRecipe(recipe.dir,entry.types);return{file:file2,...types2!==void 0&&fs47.existsSync(types2)?{types:types2}:{}}}function insideRecipe(dir,relative4){if(path59.isAbsolute(relative4))return;let file2=path59.resolve(dir,relative4),real3,root;try{root=fs47.realpathSync(dir),real3=fs47.existsSync(file2)?fs47.realpathSync(file2):file2}catch{return}let from=path59.relative(root,real3);return from===""||from.startsWith("..")||path59.isAbsolute(from)?void 0:file2}function pluginsContributor(){return{id:CONTRIBUTORS.plugins,after:[CONTRIBUTORS.fetch],contribute(config2){let repos=config2.atPath("repos").get()??{};for(let recipe of config2.entities("active-recipe")){let repo=repos[recipe.repo];if(repo===void 0||repo.enabled===!1)continue;let bundle=pluginBundleOf(recipe);if(bundle!==void 0){if("problem"in bundle){config2.warn(bundle.problem);continue}config2.atPath(["plugins","load"]).append(pathToFileURL5(bundle.file).href)}}}}}function writeRecipeTypes(sousDir,recipes){let directory=path59.join(sousDir,TYPES_DIRNAME),wanted=new Map;for(let recipe of recipes){let bundle=pluginBundleOf(recipe);bundle!==void 0&&!("problem"in bundle)&&bundle.types!==void 0&&wanted.set(path59.join(recipe.namespace,`${recipe.name}.d.ts`),bundle.types)}let written=[],removed=[];if(wanted.size===0&&!fs47.existsSync(directory))return{directory,written,removed};for(let existing of listDeclarations(directory))existing!=="index.d.ts"&&!wanted.has(existing)&&(fs47.rmSync(path59.join(directory,existing),{force:!0}),removed.push(existing));let references2=[];for(let relative4 of[...wanted.keys()].sort()){let target=path59.join(directory,relative4),text=fs47.readFileSync(wanted.get(relative4),"utf8");writeIfChanged(target,text)&&written.push(relative4),references2.push(`/// <reference path="./${relative4.split(path59.sep).join("/")}" />`)}let index=["// Written by sous on every build: the types of the plugins the active recipes ship.",...references2,""].join(`
464
464
  `);return writeIfChanged(path59.join(directory,"index.d.ts"),index)&&written.push("index.d.ts"),{directory,written,removed}}function listDeclarations(directory){try{return fs47.readdirSync(directory,{recursive:!0}).filter(entry=>entry.endsWith(".d.ts"))}catch{return[]}}function writeIfChanged(file2,text){try{if(fs47.readFileSync(file2,"utf8")===text)return!1}catch{}return fs47.mkdirSync(path59.dirname(file2),{recursive:!0}),fs47.writeFileSync(file2,text,"utf8"),!0}var init_recipe_plugins=__esm({"../sous-plugin-recipes/src/part-b/plugins/recipe-plugins.ts"(){"use strict";init_constants()}});var ResolverService,init_resolver_service=__esm({"../sous-plugin-recipes/src/part-b/resolver/resolver-service.ts"(){"use strict";init_constants();init_linked_recipes();init_restore();init_util2();init_lock_service();init_lockfile_ops();init_reachable();init_support();init_resolve();ResolverService=class{constructor(ctx,runtime){this.ctx=ctx;this.runtime=runtime}linked=new Map;upstream=new Map;async resolve(requests,options2={}){let result=await this.resolveOnce(requests,options2);if(options2.download!==!0)return result;let tried=new Set,downloaded=[],failures=new Map;for(;;){let waiting=result.unreadable.filter(key=>!tried.has(key));if(waiting.length===0)break;let got=await this.download(result.resolved,waiting,tried,failures);if(got.length===0)break;downloaded.push(...got),result=await this.resolveOnce(requests,options2)}let unreadable2=new Set(result.unreadable);return{...result,downloaded:sortKeys2(new Set(downloaded)),downloadFailures:sortKeys2(failures.keys()).filter(key=>unreadable2.has(key)).map(key=>({key,reason:failures.get(key)}))}}async download(resolved,keys,tried,failures){let trusted=trustedRepos2(this.ctx),downloaded=[],deps={store:this.ctx.services.get("recipes.store"),cache:this.runtime.indexCore(),hosts:this.ctx.entities.list("repository-host"),context:this.runtime.hostContext(),freshnessSeconds:this.ctx.config.get("store")?.freshnessSeconds};for(let key of keys){tried.add(key);let recipe=resolved.find(entry=>entry.key===key),repo=recipe===void 0?void 0:trusted[recipe.repo];if(recipe===void 0||repo===void 0)continue;let versions=[{version:recipe},...(recipe.pins??[]).map(pin=>({version:resolvedAtPin(recipe,pin),holder:pin.holder}))];for(let{version:version2,holder}of versions)try{if((await ensureInStore({key,entry:{repo:version2.repo,version:version2.version,hash:version2.hash,requestedBy:version2.requestedBy,kind:version2.kind},repo:version2.repo,url:repo.url,identity:version2.identity,...repo.provider===void 0?{}:{provider:repo.provider}},deps)).downloaded){let label=restoredLabel(key,{version:version2.version,hash:version2.hash,...holder===void 0?{}:{holder}});downloaded.push(label),this.runtime.noteFetched([label])}}catch(error51){failures.set(key,error51 instanceof Error?error51.message:String(error51))}}return downloaded}async resolveOnce(requests,options2){let trusted=trustedRepos2(this.ctx),repos={};for(let[name,entry]of Object.entries(trusted)){let identity2=this.runtime.tryIdentity(entry.url);identity2!==void 0&&(repos[name]={url:entry.url,identity:identity2,...entry.provider===void 0?{}:{provider:entry.provider}})}let wanted=[];for(let request of requests){let parts=wantedOf(request.ref);parts!==void 0&&wanted.push({...parts,...request.range!==void 0&&parts.range===void 0?{range:request.range}:{},requestedBy:request.requestedBy,...request.kind===void 0?{}:{kind:request.kind},...request.prerelease===void 0?{}:{prerelease:request.prerelease},written:this.format(request)})}let run=(indexes,checkedNow)=>resolveWanted(wanted,{indexes,repos,loadManifest:recipe=>this.loadManifest(recipe),parseDependency:written=>this.parseDependency(written),...options2.prerelease===void 0?{}:{prerelease:options2.prerelease},...options2.keep===void 0?{}:{keep:options2.keep},...options2.keepPins===void 0?{}:{keepPins:options2.keepPins},...checkedNow===void 0?{}:{checkedNow}});if(options2.indexes!==void 0)return run(options2.indexes);let names2=Object.keys(repos),latest2=options2.latest===!0,read=await this.indexes(names2,latest2,options2.quiet===!0);try{return await run(read.found,latest2?read.checked:void 0)}catch(error51){if(latest2||!(error51 instanceof UnknownRefError||error51 instanceof NoVersionSatisfiesError))throw error51;let fresh=await this.readUpstreamOnce(names2,options2.quiet===!0);return run(fresh.found,fresh.checked)}}readUpstreamOnce(names2,quiet){let key=sortKeys2(names2).join(`
465
- `),read=this.upstream.get(key);return read===void 0&&(read=this.indexes(names2,!0,quiet),this.upstream.set(key,read)),read}async resolveSubscriptions(options2={}){let subscriptions=enabledSubscriptions(this.ctx.config.get("subscriptions"));return this.resolve(sortKeys2(Object.keys(subscriptions)).map(key=>this.subscriptionRequest(key)),options2)}subscriptionRequest(key){let entry=this.ctx.config.get("subscriptions")?.[key]??{};return{ref:this.ctx.services.get("refs.format").parseNamedRef(key,"config"),...entry.range===void 0?{}:{range:entry.range},...entry.prerelease===!0?{prerelease:!0}:{},requestedBy:PROJECT_HOLDER,kind:"subscribes"}}reachable(lockfile){return reachability({lockfile,subscriptions:this.ctx.config.get("subscriptions"),repos:this.ctx.config.get("repos"),keyOf:key=>this.keyOf(key)}).reached}keyOf(subscription){try{let format3=this.ctx.services.get("refs.format");return format3.key(format3.parseNamedRef(subscription,"config"))}catch{return plainSubscriptionKey(subscription)}}async indexes(names2,latest2,quiet){let cache2=this.ctx.services.get("recipes.index-cache"),found=new Map,checked3=new Set;for(let name of sortKeys2(names2))try{let read=await cache2.get(name,{latest:latest2});if(read.source==="stale"&&!quiet&&cache2.firstStaleNotice(name)){let problem=read.problem;this.runtime.host.reporter.problem(`Sous could not check the repository '${name}' for updates, so it is using the copy of its index that it already had.`,problem===void 0?{}:{cause:problem})}found.set(name,read.index),latest2&&read.source!=="stale"&&checked3.add(name)}catch{let cached2=cache2.cached(name);cached2!==void 0&&found.set(name,cached2.index)}return{found,checked:checked3}}async loadManifest(recipe){let manifests=this.ctx.services.get("formats.manifests"),link=this.ctx.services.get("recipes.links").get(recipe.repo);if(link!==void 0){let map3=this.linked.get(link.path);map3===void 0&&(map3=mapLinkedRecipes(link.path,manifests),this.linked.set(link.path,map3));let found=(await map3).get(recipe.key);if(found!==void 0)return{depends:found.manifest.depends??[],subscribes:found.manifest.subscribes??[]}}let hit=await this.ctx.services.get("recipes.store").get(storeKeyOf2(recipe.key,recipe.identity,recipe.version));if(hit===void 0)return;let manifest=await manifests.readRecipe(hit.dir);return manifest===void 0?void 0:{depends:manifest.manifest.depends??[],subscribes:manifest.manifest.subscribes??[]}}parseDependency(written){try{return this.ctx.services.get("refs.resolver").resolveSync({input:written,from:"manifest",lookups:!1,refusedIsEmpty:!0}).refs}catch{return[]}}format(request){try{return this.ctx.services.get("refs.format").format(request.ref)}catch{return request.ref.name}}}}});import{nullReporter as nullReporter3}from"@sous-io/sous-plugin-api";var PartBRuntime,init_runtime=__esm({"../sous-plugin-recipes/src/part-b/runtime.ts"(){"use strict";init_constants();init_index_cache();init_support();PartBRuntime=class{constructor(host){this.host=host}core;fetched=new Set;recipeFilesWanted=!1;leftOut=0;noteFetched(keys){for(let key of keys)this.fetched.add(key)}downloadsRecipeFiles(plan2){return this.recipeFilesWanted||plan2===void 0||plan2.intent?.needsRecipeFiles===!0}noteLeftOut(count2){this.leftOut=count2}leftOutRecipeFiles(){return this.leftOut>0}wantRecipeFiles(){this.recipeFilesWanted=!0}takeFetched(among){let keys=[...this.fetched].filter(key=>among===void 0||among.includes(key));for(let key of keys)this.fetched.delete(key);return keys}get services(){return this.host.services}get entities(){return this.host.entities}homePaths(){return this.services.get("host.sous-home").paths(this.host.env)}hosts(){return this.entities.list("repository-host")}identity(url2){return this.services.get("refs.locations").identity(url2)}tryIdentity(url2,hosts){try{return this.identity(url2)}catch{}try{let host=hostFor(hosts??this.hosts(),url2);if(host===void 0)return;let canonical=host.canonicalize(url2);return`${canonical.host}/${canonical.owner}/${canonical.name.replace(/\.git$/i,"")}`.split("/").filter(segment=>segment.length>0).map(segment=>segment.toLowerCase()).join("/")}catch{return}}indexCore(){if(this.core===void 0){let paths=this.homePaths();this.core=new IndexCacheCore({directory:paths.indexCache,strategiesFile:paths.readStrategies,parser:this.services.get("formats.index-file"),hosts:()=>this.hosts(),hostContext:()=>this.hostContext(this.host.reporter),strategyMemorySeconds:()=>this.host.engine.config.get("store")?.strategyMemorySeconds??DEFAULT_STRATEGY_MEMORY_SECONDS})}return this.core}hostContext(reporter=nullReporter3,signal){return{plugin:RECIPES_PLUGIN,config:this.host.engine.config,services:this.services,entities:this.entities,project:this.host.project,env:this.host.env,cwd:this.host.project?.root??process.cwd(),reporter,...signal===void 0?{}:{signal}}}async emit(name,payload){try{await this.host.emit(name,payload)}catch{}}}}});import{jsonSchema as jsonSchema15}from"@sous-io/sous-plugin-api";var dryRun2,yes2,lockRebuildInputSchema,lockShowInputSchema,repoGcInputSchema,repoLinkInputSchema,repoUnlinkInputSchema,activeRecipeSchema,init_schemas3=__esm({"../sous-plugin-recipes/src/part-b/schemas.ts"(){"use strict";dryRun2={type:"boolean",description:"Print what would change without writing anything"},yes2={type:"boolean",description:"Answer yes to every question this command can ask (trusting a repository, discarding work)"},lockRebuildInputSchema=jsonSchema15({type:"object",properties:{dryRun:{...dryRun2,description:"Print what would change without writing the lockfile"}},additionalProperties:!1}),lockShowInputSchema=jsonSchema15({type:"object",properties:{},additionalProperties:!1}),repoGcInputSchema=jsonSchema15({type:"object",properties:{maxBytes:{type:"integer",description:"The size cap to collect down to, instead of the one this project's config sets"},dryRun:{...dryRun2,description:"Print what would be evicted without removing anything"}},additionalProperties:!1}),repoLinkInputSchema=jsonSchema15({type:"object",properties:{repo:{type:"string",description:"The repository's short name from this project's config, its full URL, or the path of a checkout to link in place"},path:{type:"string",description:"An existing checkout to link. Without it, the repository is cloned."},global:{type:"boolean",description:"Link for every project on this machine, sharing one checkout, rather than for this project"},yes:yes2,dryRun:{...dryRun2,description:"Print what would change without cloning or writing anything"},branch:{type:"string",description:"Switch the checkout to this existing branch, fetching it from upstream first"},createBranch:{type:"string",description:"Create this new branch in the checkout and switch to it"},generateBranch:{type:"boolean",description:"Create a new branch named sous/edit-<date>-<time> in the checkout and switch to it"},from:{type:"string",description:"Start the new branch from this branch instead of the repository's default branch"},latest:{type:"boolean",description:"Make the branch being worked from match upstream's, after listing any local work that would be discarded"}},required:["repo"],additionalProperties:!1}),repoUnlinkInputSchema=jsonSchema15({type:"object",properties:{repo:{type:"string",description:"The repository's short name, as it appears in the links map"},global:{type:"boolean",description:"Remove the machine-wide link rather than this project's link"},update:{type:"boolean",description:"Move this repository's pins to the newest versions their ranges allow before rebuilding"},remove:{type:"boolean",description:"Delete the checkout as well, when sous cloned it"},yes:yes2,dryRun:dryRun2,noBuild:{type:"boolean",description:"Unlink without rebuilding the project"},answer:{type:"array",items:{type:"string"},description:"Answer a recipe question ahead of time, as <name>=<value>"},answersFile:{type:"string",description:"A file of answers to recipe questions"}},required:["repo"],additionalProperties:!1}),activeRecipeSchema=jsonSchema15({type:"object",properties:{id:{type:"string"},namespace:{type:"string"},name:{type:"string"},repo:{type:"string"},identity:{type:"string"},version:{type:"string"},hash:{type:"string"},kind:{enum:["subscribes","depends"]},requestedBy:{type:"array",items:{type:"string"}},dir:{type:"string"},source:{enum:["store","link","core","project"]},manifest:{type:"object"}},required:["id","namespace","name","repo","identity","version","hash","kind","requestedBy","dir","source","manifest"]})}});import fs48 from"node:fs";async function registerPartB(sous){let runtime=new PartBRuntime(sous),seeder=new CoreSeeder(runtime);sous.entities.kinds().includes("active-recipe")||sous.entities.define("active-recipe",activeRecipeSchema,{description:"A locked recipe reached from the subscriptions switched on on this machine, its files on disk."}),registerServices(sous,runtime),registerContributors(sous,runtime,seeder),registerIntents(sous,runtime),sous.entities.add("ref-lookup",lockfileLookup()),sous.on("*.before",async(event,ctx)=>{!runtime.leftOutRecipeFiles()||ctx.chain===void 0||ctx.chain.parallel||ctx.engine.intents.get(event.intent)?.definition.needsRecipeFiles===!0&&(runtime.wantRecipeFiles(),await ctx.refreshConfig())}),sous.on("config.built",event=>{let project=sous.project;if(!(project===void 0||!fs48.existsSync(project.sousDir)||runtime.leftOutRecipeFiles()))try{writeRecipeTypes(project.sousDir,event.payload.config.entities.list("active-recipe"))}catch(error51){sous.reporter.warning(`Sous could not write the recipe plugin types into ${project.sousDir}/types: ${error51 instanceof Error?error51.message:String(error51)}`)}})}function registerServices(sous,runtime){sous.services.add("recipes.lock",(_config,ctx)=>new LockService(ctx,runtime),{lifetime:"config"}),sous.services.add("recipes.resolver",(_config,ctx)=>new ResolverService(ctx,runtime),{lifetime:"config"}),sous.services.add("recipes.links",(_config,ctx)=>new LinksFiles({sousDir:ctx.project?.sousDir,globalFile:runtime.homePaths().links,parser:ctx.services.get("formats.links-map")}),{lifetime:"config"}),sous.services.add("recipes.index-cache",()=>{let core=runtime.indexCore();return installPackagedOverlay(runtime),new IndexCacheService(core,{trusted:()=>trustedRepos2({services:sous.services,config:sous.engine.config}),identity:url2=>runtime.tryIdentity(url2)??url2,freshnessSeconds:()=>sous.engine.config.get("store")?.freshnessSeconds??DEFAULT_FRESHNESS_SECONDS,linkedPath:repo=>{try{return sous.services.get("recipes.links").get(repo)?.path}catch{return}}})},{lifetime:"singleton"}),sous.services.add("compiler.namespace-resolver",(_config,ctx)=>{let resolver=ctx.services.get("refs.resolver"),globs=ctx.services.get("host.globs"),recipesResolver=ctx.services.get("recipes.resolver");return new ActiveNamespaceResolver({recipes:ctx.entities.list("active-recipe"),parse:reference=>resolver.resolveSync({input:reference,from:"include",kinds:["recipeFile"],lookups:!1,refusedIsEmpty:!0}),isMatch:(name,pattern,options2)=>globs.isMatch(name,pattern,{nocase:options2.nocase,dot:!0}),explainMissing:recipe=>explainMissing(recipe,{subscriptions:ctx.config.get("subscriptions"),keyOf:key=>recipesResolver.keyOf(key),lockfile:()=>ctx.services.get("recipes.lock").read(),cachedIndex:identity2=>runtime.indexCore().readCached(identity2)})})},{lifetime:"config"})}function installPackagedOverlay(runtime){let hash2;try{let identity2=runtime.services.get("host.package").identity(),dir=packagedCoreRecipeDir(identity2.root);if(dir===void 0)return;runtime.indexCore().setOverlayIfNone(coreIndexOverlay({version:identity2.version,hash:()=>{if(hash2===void 0)try{hash2=runtime.services.get("formats.recipe-hash").hashDirectorySync(dir)}catch{hash2=null}return hash2??void 0}}))}catch{}}function registerContributors(sous,runtime,seeder){sous.config.contribute(coreContributor(runtime,seeder)),sous.config.contribute(fetchContributor(runtime)),sous.config.contribute(configLayersContributor(runtime)),sous.config.contribute(pluginsContributor())}function registerIntents(sous,runtime){sous.intents.add({intent:"lock.rebuild",requiresProject:!0,summary:"Rebuild this project's lockfile from its subscriptions and the cached repository indexes",input:lockRebuildInputSchema,changesConfig:!0,cli:{examples:["sous lock rebuild","sous lock rebuild --dry-run"]},handle:async(input,ctx)=>rebuildLock(input,ctx)}),sous.intents.add({intent:"lock.show",requiresProject:!0,summary:"Show every recipe version this project's lockfile pins",input:lockShowInputSchema,parallel:!0,cli:{examples:["sous lock show"]},handle:(_input,ctx)=>lockShowOutputs(showLock(ctx))}),sous.intents.add({intent:"repo.gc",requiresProject:!0,summary:"Collect the machine-wide recipe store back down to its size cap",input:repoGcInputSchema,cli:{examples:["sous repo gc","sous repo gc --dry-run","sous repo gc --max-bytes 268435456"]},handle:async(input,ctx)=>storeGcOutputs(await collectStore(input,ctx))}),sous.intents.add({intent:"repo.link",requiresProject:!0,summary:"Point a repository at a working copy on this machine instead of a published version",description:"'sous repo link <path>' links the checkout already at that path, where it is, adding the repository to this project first if it has not been added yet. 'sous repo link <name-or-url>' clones the repository into .sous/repos and links that clone. 'sous repo link <name-or-url> <path>' links the checkout at that path to that repository, and clones nothing. A checkout that was already on disk is fetched and compared with upstream; only the branch flags and --latest change it.",input:repoLinkInputSchema,changesConfig:!0,cli:{positional:["repo","path"],flags:{yes:{short:"y",aliases:["force","trust"]}},examples:["sous repo link ../sous-recipes","sous repo link sous-recipes","sous repo link sous-recipes ~/Projects/sous-recipes","sous repo link https://github.com/sous-io/sous-recipes","sous repo link sous-recipes --global","sous repo link sous-recipes --latest","sous repo link sous-recipes --generate-branch","sous repo link sous-recipes --branch my-change --latest"]},agent:{usage:"Use to edit a repository's recipes in a working copy. Pass yes: true to trust a repository the project does not trust yet."},handle:async(input,ctx)=>linkOutputs(await linkRepo(input,ctx,runtime))}),sous.intents.add({intent:"repo.unlink",requiresProject:!0,summary:"Stop reading a repository from a working copy and go back to its pinned versions",input:repoUnlinkInputSchema,changesConfig:!0,cli:{positional:["repo"],flags:{yes:{short:"y",aliases:["force","trust"]}},examples:["sous repo unlink sous-recipes","sous repo unlink sous-recipes --update","sous repo unlink sous-recipes --remove","sous repo unlink sous-recipes --global"]},handle:async(input,ctx)=>unlinkOutputs(ctx,await unlinkRepo(input,ctx,runtime))})}var init_part_b=__esm({"../sous-plugin-recipes/src/part-b/index.ts"(){"use strict";init_constants();init_config_layers();init_core_recipe();init_core_contributor();init_fetch_contributor();init_index_cache();init_lock_intents();init_link_intent();init_links_service();init_unlink_intent();init_lock_service();init_lockfile_lookup();init_explain_missing();init_namespace_resolver();init_recipe_plugins();init_resolver_service();init_runtime();init_schemas3()}});var package_default12,init_package5=__esm({"../sous-plugin-recipes/package.json"(){package_default12={name:"@sous-io/sous-plugin-recipes",version:"1.1.4",description:"Repositories, trust, subscriptions, the lockfile, the store, the index cache, links, the core recipe, the catalog and recipe plugins.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-compiler":"workspace:*","@sous-io/sous-plugin-confd":"workspace:*","@sous-io/sous-plugin-formats":"workspace:*","@sous-io/sous-plugin-git":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@sous-io/sous-plugin-refs":"workspace:*","@sous-io/sous-plugin-variables":"workspace:*",semver:"^7.8.5"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*","@sous-io/sous-plugin-update":"workspace:*","@types/semver":"^7.8.0",glob:"^13.0.6",yaml:"^2.9.0"},engines:{node:">=22"}}}});import{definePlugin as definePlugin12}from"@sous-io/sous-plugin-api";var PLUGIN_NAME11,recipesPlugin,init_src6=__esm({"../sous-plugin-recipes/src/index.ts"(){"use strict";init_part_a();init_part_b();init_package5();init_contents();init_recipe_plugins();init_config_layers();init_manifests2();PLUGIN_NAME11="@sous-io/sous-plugin-recipes",recipesPlugin=definePlugin12({name:PLUGIN_NAME11,version:package_default12.version,description:"Repositories, trust, subscriptions, the lockfile, the store, the index cache, links, the core recipe, the catalog and recipe plugins.",dependsOn:{"@sous-io/sous-plugin-confd":`^${package_default12.version}`,"@sous-io/sous-plugin-formats":`^${package_default12.version}`,"@sous-io/sous-plugin-refs":`^${package_default12.version}`,"@sous-io/sous-plugin-variables":`^${package_default12.version}`,"@sous-io/sous-plugin-git":`^${package_default12.version}`,"@sous-io/sous-plugin-compiler":`^${package_default12.version}`,"@sous-io/sous-plugin-host":`^${package_default12.version}`},async register(sous){await registerPartB(sous),defineEntityKinds(sous),registerPartA(sous)}})}});import fs51 from"node:fs";import{pathToFileURL as pathToFileURL6}from"node:url";import{HANDLER_PURPOSES,SousError as SousError25}from"@sous-io/sous-plugin-api";function handlerRecipes(config2){let repos=config2.atPath("repos").get()??{};return config2.entities("active-recipe").filter(recipe=>{let repo=repos[recipe.repo];return recipe.kind==="subscribes"&&repo!==void 0&&repo.enabled!==!1})}function recipeDeclarationsContributor(){return{id:RECIPE_DECLARATIONS_CONTRIBUTOR,after:[FETCH_CONTRIBUTOR],contribute(config2){for(let recipe of handlerRecipes(config2)){let handlers=recipe.manifest.handlers;if(handlers!==void 0)for(let purpose of HANDLER_PURPOSES)for(let entry of handlers[purpose]??[]){let declaration={recipe:recipe.id,purpose,file:entry.file,handler:entry.handler};config2.atPath(RECIPE_HANDLERS_KEY).append(declaration)}}}}}function recipeHandlerId(declaration){return`${declaration.recipe}/${declaration.purpose}/${declaration.file}#${declaration.handler}`}function loadRecipeHandler(declaration,file2){return(async(sous,input)=>{if(!fs51.existsSync(file2))throw new SousError25(`The recipe ${declaration.recipe} lists the handler file ${declaration.file}, which is not there.`);let handle9=(await import(pathToFileURL6(file2).href))[declaration.handler];if(typeof handle9!="function")throw new SousError25(`The recipe ${declaration.recipe} lists the handler ${declaration.handler} in ${declaration.file}, which does not export a function by that name.`);return handle9(sous,input)})}function recipeHandlersContributor(){return{id:RECIPE_HANDLERS_CONTRIBUTOR,after:[RECIPE_DECLARATIONS_CONTRIBUTOR,FETCH_CONTRIBUTOR],contribute(config2){let recipes=new Map(handlerRecipes(config2).map(recipe=>[recipe.id,recipe])),declarations=config2.atPath(RECIPE_HANDLERS_KEY).get()??[],seen=new Set;for(let declaration of declarations){let recipe=recipes.get(declaration.recipe);if(recipe===void 0)continue;let identity2=JSON.stringify([declaration.recipe,declaration.purpose,declaration.file,declaration.handler]);if(seen.has(identity2))continue;seen.add(identity2);let file2=insideRecipe(recipe.dir,declaration.file);if(file2===void 0){config2.warn(`The recipe ${recipe.id} names a handler file outside its own files (${declaration.file}), so its handler ${declaration.handler} was not added.`);continue}let entity={id:recipeHandlerId(declaration),purpose:declaration.purpose,recipe:recipe.id,source:`${declaration.file}#${declaration.handler}`,handle:loadRecipeHandler(declaration,file2)};config2.addEntity("handler",entity)}}}}var RECIPE_DECLARATIONS_CONTRIBUTOR,RECIPE_HANDLERS_CONTRIBUTOR,RECIPE_HANDLERS_KEY,FETCH_CONTRIBUTOR,init_recipes=__esm({"../sous-plugin-handlers/src/recipes.ts"(){"use strict";init_src6();RECIPE_DECLARATIONS_CONTRIBUTOR="handlers/recipe-declarations",RECIPE_HANDLERS_CONTRIBUTOR="handlers/recipes",RECIPE_HANDLERS_KEY="recipes.handlers",FETCH_CONTRIBUTOR="recipes.fetch"}});import fs52 from"node:fs/promises";import path69 from"node:path";import{SousError as SousError26}from"@sous-io/sous-plugin-api";function inProject(project,file2){return path69.resolve(project.root,file2)}function needService(services,name,plugin){if(services===void 0||!services.has(name))throw new SousError26(`This helper needs the "${name}" service, which ${plugin} provides, and it is not available here.`);return services.get(name)}function createHelpers(sources,report){let{project}=sources,system=()=>needService(sources.services(),"handlers.system","@sous-io/sous-plugin-handlers");return{report,utils:{system:{isAppAvailable:name=>system().isAppAvailable(name),appVersion:name=>system().appVersion(name)},process:{run(command,args=[],options2={}){return needService(sources.services(),"host.processes","@sous-io/sous-plugin-host").run(command,args,{cwd:options2.cwd===void 0?project.root:inProject(project,options2.cwd),env:sources.env,label:`${command} ${args.slice(0,1).join(" ")}`.trim(),...options2.input===void 0?{}:{input:options2.input},...options2.timeoutMs===void 0?{}:{timeoutMs:options2.timeoutMs}})}},file:{async exists(file2){try{return await fs52.access(inProject(project,file2)),!0}catch{return!1}},async read(file2){try{return await fs52.readFile(inProject(project,file2),"utf8")}catch(error51){if(error51.code==="ENOENT")return;throw error51}},async remove(file2){let absolute=inProject(project,file2);try{return await fs52.rm(absolute),!0}catch(error51){if(error51.code==="ENOENT")return!1;throw error51}}},files:{async removeMatching(pattern){let matched=await needService(sources.services(),"host.globs","@sous-io/sous-plugin-host").match(pattern,{cwd:project.root,dot:!0,onlyFiles:!0});for(let file2 of matched)await fs52.rm(inProject(project,file2),{force:!0});return matched}}},editor:{file(file2){let services=sources.services();if(sources.editorUnavailable!==void 0)throw new SousError26(sources.editorUnavailable);if(services===void 0||!services.has(EDITOR_SERVICE))throw new SousError26('sous.editor.file needs the document editor (the "editor" service of @sous-io/sous-plugin-editor), and it is not loaded.',{details:["Load @sous-io/sous-plugin-editor, or remove it from plugins.disabled."]});return services.get(EDITOR_SERVICE).file(file2)}},vars:{get:name=>sources.vars(name)},project,config:sources.config,env:sources.env}}function answerFrom(services,recipe,name){if(!services.has("recipe-answers.answers"))return;let answers=services.get("recipe-answers.answers");return recipe===void 0?answers.get().merged[name]:answers.forRecipe(recipe)[name]}function createTools(ctx,project,recipe,report){let helpers=createHelpers({project,env:ctx.env,services:()=>ctx.services,config:{get:key=>ctx.config.get(key)},vars:name=>answerFrom(ctx.services,recipe,name)},report),{config:_config,...own}={...helpers,project};return new Proxy(ctx,{get(target,property){if(typeof property=="string"&&Object.hasOwn(own,property))return own[property];let value=Reflect.get(target,property,target);return typeof value=="function"?value.bind(target):value},has(target,property){return typeof property=="string"&&Object.hasOwn(own,property)||Reflect.has(target,property)}})}function createConfigureTools(config2,services,recipe,report){let project=config2.project;return createHelpers({project,env:config2.env,services,config:{get:key=>config2.atPath(key).get()},vars:name=>configureAnswer(config2,recipe,name),editorUnavailable:"sous.editor.file edits a document directly, which cannot happen while the config is built. In a configure handler, declare the edit instead: add it to editor.edits through the config builder."},report)}function configureAnswer(config2,recipe,name){let source=config2.entity("variable-source","recipe-answers");if(source===void 0)return;let lookup={project:config2.project,env:config2.env,config:{get:key=>config2.atPath(key).get()}};return(recipe===void 0?void 0:source.scoped?.(recipe,lookup)?.[name])??source.variables(lookup)[name]}var EDITOR_SERVICE,ReportCollector,init_tools=__esm({"../sous-plugin-handlers/src/tools.ts"(){"use strict";EDITOR_SERVICE="editor",ReportCollector=class{constructor(handler){this.handler=handler}entries=[];report={error:message2=>this.add("error",message2),warn:message2=>this.add("warn",message2),info:message2=>this.add("info",message2)};add(level,message2){this.entries.push({level,message:String(message2),handler:this.handler})}}}});import{IntentOutput as IntentOutput10,IntentOutputs as IntentOutputs11,messageText as messageText2,SousError as SousError27}from"@sous-io/sous-plugin-api";function orderHandlers(items2,purpose,entryOf){let mine=items2.filter(item=>entryOf(item).purpose===purpose);return[...mine.filter(item=>entryOf(item).recipe===void 0),...mine.filter(item=>entryOf(item).recipe!==void 0)].map((item,index)=>({item,index})).sort((a,b)=>(entryOf(a.item).order??DEFAULT_ORDER)-(entryOf(b.item).order??DEFAULT_ORDER)||a.index-b.index).map(({item})=>item)}function describeThrown(error51){return error51 instanceof Error?messageText2(error51):String(error51)}function handlerLabel(entry){if(entry.recipe!==void 0){let name=entry.source===void 0?entry.id:entry.source.slice(entry.source.lastIndexOf("#")+1);return`${entry.recipe} (${entry.purpose}: ${name})`}return entry.plugin===void 0?`${entry.purpose}: ${entry.id}`:`${entry.plugin} (${entry.purpose}: ${entry.id})`}function reportLine(label,message2){return`${label}: ${message2}`}async function runHandlers(ctx,purpose,options2={}){let project=ctx.project,only=options2.recipes===void 0?void 0:new Set(options2.recipes),ignoring=purpose==="check"&&options2.ignoreFailedChecks===!0,records=ctx.entities.kinds().includes("handler")?ctx.entities.describe("handler"):[],ran=[],errors=0,warnings=0;if(project===void 0)return{purpose,ran,errors,warnings,ignoredErrors:0,failed:!1};for(let record2 of orderHandlers(records,purpose,one=>one.entry)){let{entry}=record2;if(only!==void 0&&(entry.recipe===void 0||!only.has(entry.recipe)))continue;let label=handlerLabel({...entry,plugin:entry.plugin??record2.plugin}),collector=new ReportCollector(entry.id),tools=createTools(ctx,project,entry.recipe,collector.report),threw;try{await entry.handle(tools,options2.input)}catch(error51){threw=describeThrown(error51),collector.entries.push({level:"error",message:`failed: ${threw}`,handler:entry.id})}for(let report of collector.entries)forward(ctx,label,report,ignoring),errors+=report.level==="error"?1:0,warnings+=report.level==="warn"?1:0;ran.push({id:entry.id,plugin:record2.plugin,label,...entry.recipe===void 0?{}:{recipe:entry.recipe},reports:collector.entries,...threw===void 0?{}:{threw}})}return{purpose,ran,errors,warnings,ignoredErrors:ignoring?errors:0,failed:errors>0&&!ignoring}}function forward(ctx,label,report,ignoring){let details={handler:report.handler},line=reportLine(label,report.message);report.level==="error"?ignoring?ctx.reporter.warning(`${line} (a failed check, ignored)`,details):ctx.reporter.error(line,details):report.level==="warn"?ctx.reporter.warning(line,details):ctx.reporter.info(line,details)}function checksFailedError(result){let failing=result.ran.filter(run=>run.reports.some(report=>report.level==="error")).map(run=>run.id),count2=result.errors===1?"an error":`${result.errors} errors`;return new SousError27(`The checks reported ${count2} (${failing.join(", ")}), so nothing was built.`,{details:["Fix what they report, or pass --ignore-failed-checks to build anyway."]})}function handlerOutputs(result){return new IntentOutputs11([new IntentOutput10({data:result})],result.purpose==="check"&&result.failed?{exitCode:1}:{})}var DEFAULT_ORDER,init_run=__esm({"../sous-plugin-handlers/src/run.ts"(){"use strict";init_tools();DEFAULT_ORDER=500}});import"@sous-io/sous-plugin-api";function configureContributor(services){return{id:CONFIGURE_CONTRIBUTOR,after:[RECIPE_HANDLERS_CONTRIBUTOR],async contribute(config2){for(let entry of orderHandlers(config2.entities("handler"),"configure",one=>one)){let label=handlerLabel(entry),collector=new ReportCollector(entry.id),tools=createConfigureTools(config2,services,entry.recipe,collector.report);try{await entry.handle(tools,{config:config2})}catch(error51){collector.entries.push({level:"error",message:`failed: ${describeThrown(error51)}`,handler:entry.id})}for(let report of collector.entries)forward2(config2,label,report)}}}}function forward2(config2,label,report){let details={handler:report.handler},line=reportLine(label,report.message);report.level==="error"?config2.error(line,details):report.level==="warn"?config2.warning(line,details):config2.info(line,details)}var CONFIGURE_CONTRIBUTOR,init_configure=__esm({"../sous-plugin-handlers/src/configure.ts"(){"use strict";init_recipes();init_run();init_tools();CONFIGURE_CONTRIBUTOR="handlers/configure"}});var DOCTOR_CHECK_ORDER,init_types=__esm({"../sous-plugin-doctor/src/types.ts"(){"use strict";DOCTOR_CHECK_ORDER={config:100,lockfile:200,variables:300,migrations:400,gitHooks:500,checkHandlers:600,assertions:700,outputs:800}}});import crypto2 from"node:crypto";import fs53 from"node:fs";import{SousError as SousError28}from"@sous-io/sous-plugin-api";function messageOf6(error51){return error51 instanceof Error?error51.message:String(error51)}function has2(ctx,name){return ctx.services.has(name)}function holdersInWords2(holders){return holders.length===0?"nothing":holders.map(holder=>holder==="project"?"this project":holder).join(", ")}function describeEntryChange2(change){let lines3=[],kindInWords2=kind=>kind==="depends"?"a dependency":"a subscription";return change.requestedBy!==void 0&&lines3.push(`${change.key} ${change.version} is pinned for ${holdersInWords2(change.requestedBy.from)}, and the subscriptions now need it for ${holdersInWords2(change.requestedBy.to)}`),change.kind!==void 0&&lines3.push(`${change.key} ${change.version} is pinned as ${kindInWords2(change.kind.from)}, and the subscriptions now need it as ${kindInWords2(change.kind.to)}`),lines3}function describeChange(change,kind){let forHolder=change.holder===void 0?"":` for ${change.holder}`;switch(kind){case"added":return`${change.key} ${change.to??""}${forHolder} is not pinned, and a subscription needs it`;case"removed":return`${change.key} ${change.from??""}${forHolder} is pinned, and no subscription needs it`;default:return`${change.key}${forHolder} is pinned at ${change.from??"?"}, and the subscriptions now need ${change.to??"?"}`}}async function lockfileTheSubscriptionsMake(ctx){let lock=ctx.services.get("recipes.lock"),before=lock.read(),result=await ctx.services.get("recipes.resolver").resolveSubscriptions({...lock.held(before),quiet:!0,download:!0}),after=lock.fromResolved(result.resolved,before);return{lock,before,after,result,diff:lock.diff(before,after)}}async function downloadedToLook(ctx){let lock=ctx.services.get("recipes.lock"),restored=Object.keys(lock.read().recipes).length===0?{restored:[],failed:[]}:await lock.restore(),downloaded=[...restored.restored].sort();return{notes:downloaded.length===0?[]:[`Sous downloaded ${downloaded.length===1?"this recipe":"these recipes"} into this machine's recipe store to read ${downloaded.length===1?"it":"them"}: ${downloaded.join(", ")}.`],failed:restored.failed.map(failure=>`${failure.key}: ${failure.reason}`)}}function variableAnswers(ctx,answers){if(!ctx.entities.kinds().includes("migration"))return[...answers];let migrations=ctx.entities.list("migration"),ids=new Set(migrations.flatMap(migration=>(migration.questions??[]).map(question=>question.id)));return answers.filter(entry=>!ids.has(entry.slice(0,Math.max(0,entry.indexOf("="))).trim()))}function hashOf2(file2){return crypto2.createHash("sha256").update(fs53.readFileSync(file2,"utf8"),"utf8").digest("hex")}var CONFIG_FAILED,NO_PROJECT,configCheck,lockfileCheck,variablesCheck,outputsCheck,BUILT_IN_CHECKS,init_checks3=__esm({"../sous-plugin-doctor/src/checks.ts"(){"use strict";init_types();CONFIG_FAILED={status:"skipped",summary:"Skipped: the config did not load."},NO_PROJECT={status:"skipped",summary:"Skipped: sous is not running in a project."};configCheck={id:"config",order:DOCTOR_CHECK_ORDER.config,description:"The config loads",check(ctx){let error51=ctx.engine.configError;if(error51===void 0)return{status:"ok"};let details=error51 instanceof SousError28?[...error51.details]:[];return{status:"problem",summary:`The config did not load: ${messageOf6(error51)}`,details,...ctx.project?.configPath===void 0?{}:{hint:`The config file is ${ctx.project.configPath}.`}}}};lockfileCheck={id:"lockfile",order:DOCTOR_CHECK_ORDER.lockfile,description:"The lockfile agrees with the subscriptions",async check(ctx,run){if(run.configFailed)return CONFIG_FAILED;if(ctx.project===void 0)return NO_PROJECT;if(!has2(ctx,"recipes.lock")||!has2(ctx,"recipes.resolver"))return{status:"skipped",summary:"Skipped: the recipes plugin is not loaded."};let{result,diff,lock}=await lockfileTheSubscriptionsMake(ctx),looked=await downloadedToLook(ctx),notes=looked.notes.length===0?{}:{notes:looked.notes};if(result.missingRepos.length>0)return{status:"problem",summary:"The subscriptions need repositories this project does not trust.",details:result.missingRepos.map(missing=>`${missing.name}${missing.url===void 0?"":` (${missing.url})`}, needed by ${missing.requiredBy.map(entry=>entry.ref).join(", ")}`),hint:"Trusting a repository is a decision for a person: add each with 'sous repo add <url>'.",...notes};if(result.unreadable.length>0){let reasons=new Map((result.downloadFailures??[]).map(failure=>[failure.key,failure.reason]));return{status:"problem",summary:`Sous cannot tell whether the lockfile matches the subscriptions: it could not read what ${result.unreadable.length===1?"this recipe depends":"these recipes depend"} on.`,details:[...result.unreadable.map(key=>reasons.has(key)?`${key}: ${reasons.get(key)}`:key),...looked.failed],hint:"Their files could not be downloaded into this machine's recipe store, and their repository's index does not record what they depend on. Check the network and that the repositories are reachable, then run sous doctor again.",...notes}}return diff.unchanged?{status:"ok",...notes}:{status:"problem",summary:`The lockfile (${lock.path()}) does not match the subscriptions.`,details:[...diff.added.map(change=>describeChange(change,"added")),...diff.removed.map(change=>describeChange(change,"removed")),...diff.updated.map(change=>describeChange(change,"updated")),...diff.changed.flatMap(change=>describeEntryChange2(change)),...diff.reposAdded.map(name=>`The repository ${name} is not in the lockfile, and a subscription needs it`),...diff.reposRemoved.map(name=>`The repository ${name} is in the lockfile, and no subscription needs it`)],fix:"Write the lockfile the subscriptions make, keeping every pin their ranges still allow",...notes}},async fix(ctx){let{lock,after,diff,result}=await lockfileTheSubscriptionsMake(ctx);if(result.unreadable.length>0)throw new SousError28(`The lockfile was not written: sous could not read what ${result.unreadable.join(", ")} ${result.unreadable.length===1?"depends":"depend"} on.`);await lock.write(after),ctx.configChanged();let changes=diff.added.length+diff.removed.length+diff.updated.length+diff.changed.length;return{summary:`The lockfile was written again with ${changes===1?"1 change":`${changes} changes`}: ${lock.path()}.`}}};variablesCheck={id:"variables",order:DOCTOR_CHECK_ORDER.variables,description:"Required recipe variables have answers",async check(ctx,run){if(run.configFailed)return CONFIG_FAILED;if(ctx.project===void 0)return NO_PROJECT;if(ctx.engine.intents.get("vars.list")===void 0)return{status:"skipped",summary:"Skipped: no plugin lists recipe variables."};let missing=((await ctx.run("vars.list",{})).toPlain().variables??[]).filter(entry=>entry.variable.definition.required===!0&&!entry.answered&&entry.value===void 0&&entry.variable.unanswerable===void 0);return missing.length===0?{status:"ok"}:{status:"problem",summary:missing.length===1?"1 required recipe variable has no answer.":`${missing.length} required recipe variables have no answer.`,details:missing.map(entry=>entry.variable.key),fix:"Answer them now",hint:"Answer each with 'sous vars ask', or pass --answer <name>=<value> to sous doctor."}},async fix(ctx,run){let answers=variableAnswers(ctx,run.answers);return await ctx.run("vars.ask",{...answers.length===0?{}:{answer:answers},...run.yes?{yes:!0}:{}}),{summary:"The variables were asked."}}};outputsCheck={id:"outputs",order:DOCTOR_CHECK_ORDER.outputs,description:"The files sous wrote are present and unchanged",check(ctx,run){if(run.configFailed)return CONFIG_FAILED;if(ctx.project===void 0)return NO_PROJECT;if(!has2(ctx,"compiler.state"))return{status:"skipped",summary:"Skipped: the compiler is not loaded."};let missing=[],changed2=[];for(let entry of ctx.services.get("compiler.state").entries()){if(!fs53.existsSync(entry.dest)){missing.push(entry.dest);continue}try{hashOf2(entry.dest)!==entry.destHash&&changed2.push(entry.dest)}catch{changed2.push(entry.dest)}}if(missing.length===0&&changed2.length===0)return{status:"ok"};let count2=missing.length+changed2.length;return{status:"problem",summary:`${count2===1?"1 file":`${count2} files`} sous wrote ${count2===1?"is":"are"} missing or no longer what sous wrote.`,details:[...missing.map(file2=>`${file2} is missing`),...changed2.map(file2=>`${file2} has changed since sous wrote it`)],fix:"Build the project, which writes them again"}},async fix(ctx){return await ctx.run("build",{}),{summary:"The project was built."}}},BUILT_IN_CHECKS=[configCheck,lockfileCheck,variablesCheck,outputsCheck]}});var package_default16,init_package6=__esm({"../sous-plugin-doctor/package.json"(){package_default16={name:"@sous-io/sous-plugin-doctor",version:"1.1.4",description:"sous doctor: runs every check a plugin adds, reports what it found, and offers to fix what it can.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*","@sous-io/sous-plugin-build":"workspace:*","@sous-io/sous-plugin-compiler":"workspace:*","@sous-io/sous-plugin-formats":"workspace:*","@sous-io/sous-plugin-recipe-answers":"workspace:*","@sous-io/sous-plugin-recipes":"workspace:*"},engines:{node:">=22"}}}});var doctor_exports={};__export(doctor_exports,{default:()=>doctor_default,doctorOutputs:()=>doctorOutputs,handle:()=>handle,orderChecks:()=>orderChecks});import{IntentOutput as IntentOutput11,IntentOutputs as IntentOutputs12,ReportEntryStyle as ReportEntryStyle6,TextBlock as TextBlock7,Tree as Tree2}from"@sous-io/sous-plugin-api";function orderChecks(checks){return checks.map((check3,index)=>({check:check3,index})).sort((left,right)=>(left.check.order??500)-(right.check.order??500)||left.index-right.index).map(entry=>entry.check)}async function look(check3,ctx,run){try{return await check3.check(ctx,run)}catch(error51){return{status:"problem",summary:`The check could not run: ${messageOf7(error51)}`}}}function messageOf7(error51){return error51 instanceof Error?error51.message:String(error51)}function detailLines(details){return details.flatMap(detail=>typeof detail=="string"?[detail]:[detail.text,...detail.details.map(line=>` ${line}`)])}function detailNodes(details){return details.map(detail=>typeof detail=="string"?{label:detail}:{label:detail.text,children:detail.details.map(line=>({label:line}))})}function needsFix(found){return found.status==="problem"||found.status==="warning"||found.status==="pending"}async function mayFix(check3,found,ctx,run){return check3.confirm===!1||run.yes?"yes":ctx.prompter.interactive?(ctx.reporter.problem(found.summary,found.details===void 0||found.details.length===0?{}:{cause:detailLines(found.details).join(`
466
- `)}),await ctx.prompter.confirm({message:`${found.fix}?`,default:!0,answeredBy:YES_FLAG})?"yes":"declined"):"cannot-ask"}async function examine(check3,ctx,run){let found=await look(check3,ctx,run),base={id:check3.id,description:check3.description,found};if(!needsFix(found)||found.fix===void 0||check3.fix===void 0)return{...base,problem:found.status==="problem"};if(run.dryRun)return{...base,fix:{result:"dry-run"},problem:found.status==="problem"};let decision=await mayFix(check3,found,ctx,run);if(decision!=="yes")return{...base,fix:{result:decision},problem:found.status==="problem"};try{let fixed=await check3.fix(ctx,run),after=await look(check3,ctx,run);return{...base,fix:{result:"applied",summary:fixed.summary,...fixed.details===void 0?{}:{details:fixed.details}},after,problem:after.status==="problem"}}catch(error51){return{...base,fix:{result:"failed",error:messageOf7(error51)},problem:found.status==="problem"}}}async function configLoadsNow(ctx){try{await ctx.refreshConfig()}catch{}return ctx.engine.configError===void 0}async function recheckAfterConfigLoads(reports,checks,resolvedBy,ctx,run){let updated=[];for(let report of reports){let check3=checks.find(entry=>entry.id===report.id);if(check3===void 0||!report.problem&&report.found.status!=="skipped")updated.push(report);else if(report.fix===void 0&&report.found.status==="problem"){let after=await look(check3,ctx,run);updated.push({...report,after,problem:after.status==="problem",...after.status==="ok"?{resolvedBy}:{}})}else report.found.status==="skipped"?updated.push(await examine(check3,ctx,run)):updated.push(report)}return updated}async function handle(input,ctx){let run={dryRun:input.dryRun===!0,yes:input.yes===!0,answers:input.answer??[],configFailed:ctx.engine.configError!==void 0},only=input.only===void 0||input.only.length===0?void 0:new Set(input.only),checks=orderChecks(ctx.entities.list("doctor-check")).filter(check3=>only===void 0||only.has(check3.id)),reports=[];for(let check3 of checks){let report=await examine(check3,ctx,run);reports.push(report),run.configFailed&&report.fix?.result==="applied"&&await configLoadsNow(ctx)&&(run={...run,configFailed:!1},reports=[...await recheckAfterConfigLoads(reports.slice(0,-1),checks,report.description,ctx,run),report])}let result={checks:reports,problems:reports.filter(report=>report.problem).length,pending:waitingOf(reports).count,dryRun:run.dryRun};return doctorOutputs(result)}function statusOf(found){switch(found.status){case"ok":return"ok";case"skipped":return"skipped";case"pending":return"waiting for an answer";default:return found.status}}function nodeOf(report){let final=report.after??report.found,children=[];for(let note of report.found.status==="skipped"?[]:report.found.notes??[])children.push({label:note});switch(report.found.status!=="ok"&&children.push({label:report.found.summary??"",children:detailNodes(("details"in report.found?report.found.details:void 0)??[])}),report.fix?.result){case"applied":children.push({label:`Fixed: ${report.fix.summary}`,children:(report.fix.details??[]).map(line=>({label:line}))}),report.after!==void 0&&report.after.status!=="ok"&&children.push({label:`Still found: ${report.after.summary??""}`});break;case"failed":children.push({label:`The fix failed: ${report.fix.error}`});break;case"declined":children.push({label:"Not fixed: the fix was declined."});break;case"cannot-ask":children.push({label:`Not fixed: sous could not ask without a terminal. Pass ${YES_FLAG} to apply the fix.`});break;case"dry-run":children.push({label:`Would fix: ${"fix"in report.found?report.found.fix??"":""}`});break;default:break}report.resolvedBy!==void 0&&children.push({label:`Fixed by: ${report.resolvedBy}`});let hint="hint"in final?final.hint:void 0;hint!==void 0&&final.status!=="ok"&&children.push({label:hint});let fixed=(report.fix?.result==="applied"||report.resolvedBy!==void 0)&&final.status==="ok";return{label:report.description,detail:fixed?"fixed":statusOf(final),children}}function waitingOf(reports){let count2=0,labels=[];for(let report of reports){let final=report.after??report.found;if(final.status!=="pending")continue;let waiting=final.waiting??{count:1,label:"1 check"};count2+=waiting.count,labels.push(waiting.label)}return{count:count2,labels}}function closingOf(result){let{labels}=waitingOf(result.checks),waiting=labels.length===0?void 0:`${labels.join(" and ")} ${labels.length===1&&result.pending===1?"is":"are"} waiting for an answer`,dryRun4=result.dryRun?" Nothing was changed (--dry-run).":"";return result.problems===0?waiting!==void 0?`Nothing failed, but ${waiting}.${dryRun4}`:result.dryRun?"No problem was found. Nothing was changed (--dry-run).":"No problem remains.":`${result.problems===1?"1 problem remains":`${result.problems} problems remain`}${waiting===void 0?"":`, and ${waiting}`}.${dryRun4}`}function doctorOutputs(result){let closing=closingOf(result),outputs=new IntentOutputs12([new IntentOutput11({title:"Checks",result:new Tree2(result.checks.map(nodeOf)),style:ReportEntryStyle6.Tree}),new IntentOutput11({result:new TextBlock7(closing),style:result.dryRun?ReportEntryStyle6.DryRun:ReportEntryStyle6.Plain})]).withData(result);return result.problems>0?outputs.withExitCode(1):outputs}var YES_FLAG,doctor_default,init_doctor=__esm({"../sous-plugin-doctor/src/doctor.ts"(){"use strict";YES_FLAG="--yes (also -y)";doctor_default=handle}});import{definePlugin as definePlugin16,jsonSchema as jsonSchema21}from"@sous-io/sous-plugin-api";var PLUGIN_NAME15,doctorCheckSchema,doctorInput,doctorPlugin,init_src7=__esm({"../sous-plugin-doctor/src/index.ts"(){"use strict";init_checks3();init_types();init_package6();init_checks3();init_types();PLUGIN_NAME15="@sous-io/sous-plugin-doctor",doctorCheckSchema=jsonSchema21({type:"object",required:["id","order","description"],properties:{id:{type:"string",description:"Names the check in the report and in --json."},order:{type:"number",description:"Lower runs first; the built-in checks use 100 to 800."},description:{type:"string",description:"One sentence saying what is checked, stated as the healthy state."},confirm:{type:"boolean",description:"Whether sous doctor asks before running the fix. Default: true."}}}),doctorInput=jsonSchema21({type:"object",properties:{dryRun:{type:"boolean",default:!1,description:"Report what every check finds and change nothing."},yes:{type:"boolean",default:!1,description:"Apply every fix without asking, and take the default answer to every migration's question."},answer:{type:"array",items:{type:"string"},description:"Answer a question ahead of time, as <name>=<value>: a migration's question or a recipe variable."},only:{type:"array",items:{type:"string"},description:"Run only this check, by id."}},additionalProperties:!1}),doctorPlugin=definePlugin16({name:PLUGIN_NAME15,version:package_default16.version,description:"sous doctor: runs every check, reports what it found, and offers to fix what it can.",register(sous){sous.entities.define("doctor-check",doctorCheckSchema,{description:"A check sous doctor runs: what it looks at, and how to fix what it finds."});for(let check3 of BUILT_IN_CHECKS)sous.entities.add("doctor-check",check3);sous.intents.add({intent:"doctor",summary:"Check this project's health, run pending migrations, and offer to fix each problem found",input:doctorInput,toleratesConfigErrors:!0,needsRecipeFiles:!0,cli:{examples:["sous doctor","sous doctor --dry-run","sous doctor --yes","sous doctor --only outputs","sous doctor --answer memories.location=keep"],flags:{yes:{short:"y",aliases:["force"]}}},agent:{usage:"Run with dryRun first to see every problem; pass yes (and answer for a question whose default is not wanted) to fix them without prompts."},load:()=>Promise.resolve().then(()=>(init_doctor(),doctor_exports))})}})}});import{BufferedReporter as BufferedReporter3}from"@sous-io/sous-plugin-api";async function checkHandlers(ctx,run){if(run.configFailed)return{status:"skipped",summary:"The config did not load, so the check handlers it declares could not run."};let quiet=Object.create(ctx,{reporter:{value:new BufferedReporter3}}),result=await runHandlers(quiet,"check");if(result.ran.length===0)return{status:"ok",summary:"No recipe or plugin declares a check handler."};let lines3=level=>result.ran.flatMap(one=>one.reports.filter(report=>report.level===level).map(report=>reportLine(one.label,report.message))),ran=`${result.ran.length} check ${result.ran.length===1?"handler":"handlers"} ran`;return result.errors>0?{status:"problem",summary:`${ran}, and ${result.errors===1?"one reported an error":`they reported ${result.errors} errors`}, which would stop a build.`,details:[...lines3("error"),...lines3("warn")],hint:"Put right what each one reports; 'sous build --ignore-failed-checks' builds anyway."}:result.warnings>0?{status:"warning",summary:`${ran}, with ${result.warnings===1?"a warning":`${result.warnings} warnings`}.`,details:lines3("warn")}:{status:"ok",summary:`${ran}, and found nothing wrong.`}}var checkHandlersCheck,init_doctor_check=__esm({"../sous-plugin-handlers/src/doctor-check.ts"(){"use strict";init_src7();init_run();checkHandlersCheck={id:"check-handlers",order:DOCTOR_CHECK_ORDER.checkHandlers,description:"The check handlers of the recipes and plugins report no errors",check:(ctx,run)=>checkHandlers(ctx,run)}}});function recordMoves(pending,updated){for(let change of updated){if(change.holder!==void 0||change.from===void 0||change.to===void 0||change.from===change.to)continue;let from=pending.get(change.key)?.from??change.from;from===change.to?pending.delete(change.key):pending.set(change.key,{from,to:change.to})}}function registerLifecycle(sous){let pending=new Map,removing=new Map,subscribing=new Map;sous.on("recipes.locked",async(event,ctx)=>{let{diff}=event.payload;recordMoves(pending,diff.updated);let chain=ctx.chain?.id;if(chain===void 0)return;for(let change of[...diff.added,...diff.updated])change.holder===void 0&&subscribing.get(chain)?.add(change.key);let done2=removing.get(chain);if(done2!==void 0){let keys=diff.removed.filter(change=>change.holder===void 0&&!done2.has(change.key)).map(change=>change.key);keys.length>0&&(keys.forEach(key=>done2.add(key)),await ctx.run("handlers.uninstall",{recipes:keys}))}}),sous.on("config.built",async(_event,ctx)=>{pending.size!==0&&await runPendingMigrations(pending,ctx)}),sous.on("subscription.remove.before",(event,ctx)=>{event.input.dryRun!==!0&&ctx.chain!==void 0&&removing.set(ctx.chain.id,new Set)}),sous.on(/^subscription\.remove\.(after|error)$/,(_event,ctx)=>{ctx.chain!==void 0&&removing.delete(ctx.chain.id)}),sous.on("subscription.add.before",(event,ctx)=>{event.input.dryRun!==!0&&event.input.noBuild===!0&&ctx.chain!==void 0&&subscribing.set(ctx.chain.id,new Set)}),sous.on("subscription.add.error",(_event,ctx)=>{ctx.chain!==void 0&&subscribing.delete(ctx.chain.id)}),sous.on("subscription.add.after",async(_event,ctx)=>{let chain=ctx.chain?.id,keys=chain===void 0?void 0:subscribing.get(chain);chain===void 0||keys===void 0||(subscribing.delete(chain),keys.size>0&&await ctx.run("handlers.check",{recipes:[...keys]}))})}async function runPendingMigrations(pending,ctx){let active=ctx.entities.kinds().includes("active-recipe")?ctx.entities.list("active-recipe"):[];for(let recipe of active){let waiting=pending.get(recipe.id);waiting===void 0||recipe.version!==waiting.to||(pending.delete(recipe.id),await ctx.run("handlers.migrate",{recipe:recipe.id,from:waiting.from,to:waiting.to}))}}var init_lifecycle=__esm({"../sous-plugin-handlers/src/lifecycle.ts"(){"use strict"}});function versionIn(text){return VERSION_PATTERN.exec(text)?.[0]}function createHandlersSystem(processes,env){let found=new Map,versions=new Map,locate3=name=>{let answer2=found.get(name);return answer2===void 0&&(answer2=processes().which(name,env),found.set(name,answer2)),answer2};return{async isAppAvailable(name){return await locate3(name)!==void 0},appVersion(name){let answer2=versions.get(name);return answer2===void 0&&(answer2=(async()=>{let file2=await locate3(name);if(file2===void 0)return;let shim=/\.(cmd|bat)$/i.test(file2),result=await processes().run(shim?name:file2,["--version"],{env,timeoutMs:5e3,label:`${name} --version`,...shim?{windowsShell:!0}:{}});if(!result.timedOut)return versionIn(result.stdout)??versionIn(result.stderr)})(),versions.set(name,answer2)),answer2}}}var VERSION_PATTERN,init_system=__esm({"../sous-plugin-handlers/src/system.ts"(){"use strict";VERSION_PATTERN=/\d+\.\d+(?:\.\d+)?(?:-[0-9A-Za-z.-]+)?/}});var package_default17,init_package7=__esm({"../sous-plugin-handlers/package.json"(){package_default17={name:"@sous-io/sous-plugin-handlers",version:"1.1.4",description:"Handlers: functions a recipe or plugin provides for a purpose (check, configure, beforeBuild, afterBuild, uninstall, migrate), the helpers they receive, and the intents that run them.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-doctor":"workspace:*","@sous-io/sous-plugin-formats":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@sous-io/sous-plugin-recipe-answers":"workspace:*","@sous-io/sous-plugin-recipes":"workspace:*","@sous-io/sous-plugin-variables":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}}}});import{definePlugin as definePlugin17,HANDLER_PURPOSES as HANDLER_PURPOSES2,jsonSchema as jsonSchema22}from"@sous-io/sous-plugin-api";function handlersIntent(purpose){return`handlers.${purpose}`}async function runHandlerPurpose(ctx,purpose,input={}){return(await ctx.run(handlersIntent(purpose),input)).toPlain()}var PLUGIN_NAME16,handlerSchema,recipeHandlersKeySchema,intentInputSchema,migrateInputSchema,SUMMARIES,handlersPlugin,init_src8=__esm({"../sous-plugin-handlers/src/index.ts"(){"use strict";init_configure();init_doctor_check();init_lifecycle();init_recipes();init_run();init_system();init_package7();init_run();init_system();init_recipes();init_lifecycle();init_configure();init_doctor_check();PLUGIN_NAME16="@sous-io/sous-plugin-handlers",handlerSchema=(()=>{let standard=jsonSchema22({type:"object",required:["id","purpose"],properties:{id:{type:"string",description:"Names the handler in timings and reports."},purpose:{enum:[...HANDLER_PURPOSES2],description:"What it is for."},order:{type:"number",description:"Lower runs earlier within the purpose. Default 500."},recipe:{type:"string",description:"The recipe that lists it, for a handler from a manifest."},plugin:{type:"string",description:"The plugin that added it, for a handler from a plugin."},source:{type:"string",description:"Where it came from: the file and export."}}})["~standard"];return{"~standard":{...standard,validate(value){let result=standard.validate(value);return result.issues===void 0&&typeof value?.handle!="function"?{issues:[{path:["handle"],message:"Expected a function."}]}:result}}}})(),recipeHandlersKeySchema=jsonSchema22({type:"array",items:{type:"object",required:["recipe","purpose","file","handler"],properties:{recipe:{type:"string"},purpose:{enum:[...HANDLER_PURPOSES2]},file:{type:"string"},handler:{type:"string"}}}});intentInputSchema=jsonSchema22({type:"object",properties:{recipes:{type:"array",items:{type:"string"},description:"Only the handlers of these recipes"},ignoreFailedChecks:{type:"boolean",description:"Report errors from checks as warnings"}}}),migrateInputSchema=jsonSchema22({type:"object",required:["recipe","from","to"],properties:{recipe:{type:"string",description:"The recipe that moved: namespace/recipe"},from:{type:"string",description:"The version it moved from"},to:{type:"string",description:"The version it moved to"}}}),SUMMARIES={check:"Run the check handlers: prerequisites such as installed commands",beforeBuild:"Run the handlers that run before a build",afterBuild:"Run the handlers that run after a build",uninstall:"Run the uninstall handlers of recipes being removed",migrate:"Run a recipe's migrate handlers after it moved to a new version"},handlersPlugin=definePlugin17({name:PLUGIN_NAME16,version:package_default17.version,description:"Handlers: functions a recipe or plugin provides for a purpose, the helpers they receive, and the intents that run them.",dependsOn:{"@sous-io/sous-plugin-host":`^${package_default17.version}`,"@sous-io/sous-plugin-recipes":`^${package_default17.version}`,"@sous-io/sous-plugin-doctor":`^${package_default17.version}`},register(sous){sous.entities.define("handler",handlerSchema,{description:"A function a recipe or plugin provides for a purpose: check, configure, beforeBuild, afterBuild, uninstall or migrate."}),sous.entities.add("config-key",{id:RECIPE_HANDLERS_KEY,schema:recipeHandlersKeySchema,description:"The handlers the active recipes' manifests list, one entry each."}),sous.services.add("handlers.system",(_config,ctx)=>createHandlersSystem(()=>ctx.services.get("host.processes"),ctx.env),{lifetime:"singleton"}),sous.config.contribute(recipeDeclarationsContributor()),sous.config.contribute(recipeHandlersContributor()),sous.config.contribute(configureContributor(()=>sous.services));for(let purpose of["check","beforeBuild","afterBuild","uninstall"])sous.intents.add({intent:handlersIntent(purpose),summary:SUMMARIES[purpose],input:intentInputSchema,requiresProject:!0,internal:!0,handle:async(given,ctx)=>{let input=given;return handlerOutputs(await runHandlers(ctx,purpose,{...input.recipes===void 0?{}:{recipes:input.recipes},...purpose==="check"&&input.ignoreFailedChecks===!0?{ignoreFailedChecks:!0}:{}}))}});sous.intents.add({intent:"handlers.migrate",summary:SUMMARIES.migrate,input:migrateInputSchema,requiresProject:!0,internal:!0,handle:async(input,ctx)=>handlerOutputs(await runHandlers(ctx,"migrate",{recipes:[input.recipe],input:{from:input.from,to:input.to}}))}),registerLifecycle(sous),sous.entities.add("doctor-check",checkHandlersCheck)}})}});import fs54 from"node:fs";import path70 from"node:path";function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(error51){return error51.code==="EPERM"}}function projectLabel(project,pidFile){if(project)return path70.basename(project.root);let dir=path70.dirname(pidFile);return path70.basename(dir)===".sous"&&(dir=path70.dirname(dir)),path70.basename(dir)}var PID_FILE_NAME,PidFile,init_pid=__esm({"../sous-plugin-build/src/pid.ts"(){"use strict";PID_FILE_NAME="sous.pid";PidFile=class{file;isAlive;constructor(options2){this.file=options2.explicitPath??(options2.project?path70.join(options2.project.sousDir,PID_FILE_NAME):path70.join(options2.cwd,PID_FILE_NAME)),this.isAlive=options2.isAlive??isProcessAlive}path(){return this.file}read(){let raw2;try{raw2=fs54.readFileSync(this.file,"utf8")}catch{return}let pid=Number.parseInt(raw2.trim(),10);return Number.isNaN(pid)?void 0:pid}write(pid=process.pid){fs54.mkdirSync(path70.dirname(this.file),{recursive:!0}),fs54.writeFileSync(this.file,String(pid),"utf8")}remove(){fs54.rmSync(this.file,{force:!0})}isRunning(){let pid=this.read();return pid!==void 0&&this.isAlive(pid)}}}});import{jsonSchema as jsonSchema23}from"@sous-io/sous-plugin-api";var DEFAULT_DEBOUNCE_MS,DEFAULT_BRANCH_PATTERN,watchSettingsSchema,runtimeContextSchema,boolean4,buildInputSchema,compileInputSchema,prepareInputSchema,pruneInputSchema,clearInputSchema,watchInputSchema,init_schemas4=__esm({"../sous-plugin-build/src/schemas.ts"(){"use strict";DEFAULT_DEBOUNCE_MS=200,DEFAULT_BRANCH_PATTERN="PT-",watchSettingsSchema=jsonSchema23({type:"object",properties:{pollSeconds:{type:"integer",description:"How often watch mode checks upstream for newer recipes, in seconds; 0 never. Default: store.watchPollSeconds."},paths:{type:"array",items:{type:"string"},default:[],description:"More files, directories or globs whose change triggers a full rebuild."},debounceMs:{type:"integer",default:DEFAULT_DEBOUNCE_MS,description:"How long to wait for more changes before building, in milliseconds."}},additionalProperties:!1}),runtimeContextSchema=jsonSchema23({type:"object",properties:{gitRoot:{type:"string",description:"The git repository branch detection reads (${var} allowed)."},outputPath:{type:"string",description:"Where the runtime context file is written."},taskFileRoot:{type:"string",description:"The directory task files live in."},branchPattern:{type:"string",description:"A regular expression; only matching branches look for a task file."}},required:["gitRoot","outputPath","taskFileRoot"],additionalProperties:!1}),boolean4=description=>({type:"boolean",description}),buildInputSchema=jsonSchema23({type:"object",properties:{noPrune:boolean4("Skip the prune step"),noCompile:boolean4("Skip the compile step (prune only)"),rebuild:boolean4("Ignore cached hashes and reprocess all outputs"),dryRun:boolean4("Print what would be written/pruned without making changes"),reportRemoved:boolean4("Report each removed file as progress. Default: true"),strict:boolean4("Treat compile warnings as errors"),watch:boolean4("Watch source files and rebuild on changes"),changedFiles:{type:"array",items:{type:"string"},description:"Only rebuild the targets that include one of these files, preparing nothing"},ignoreFailedAssertions:boolean4("Print a failed assertion as a warning and end the build as successful"),ignoreFailedChecks:boolean4("Print an error from a check handler as a warning and build anyway"),keepGoing:boolean4("Ignore failed assertions and failed checks: the same as passing both flags above")},additionalProperties:!1}),compileInputSchema=jsonSchema23({type:"object",properties:{strict:boolean4("Treat compile warnings as errors"),rebuild:boolean4("Ignore cached hashes and reprocess all outputs"),dryRun:boolean4("Print what would be written without making changes"),watch:boolean4("Watch source files and recompile on changes"),changedFiles:{type:"array",items:{type:"string"},description:"Only recompile the targets that include one of these files"}},additionalProperties:!1}),prepareInputSchema=jsonSchema23({type:"object",properties:{dryRun:boolean4("Show what preparing would change, writing nothing"),offline:boolean4("Never go upstream")},additionalProperties:!1}),pruneInputSchema=jsonSchema23({type:"object",properties:{dryRun:boolean4("Print what would be pruned without deleting")},additionalProperties:!1}),clearInputSchema=jsonSchema23({type:"object",properties:{force:boolean4("Delete without asking"),dryRun:boolean4("Print what would be deleted without deleting")},additionalProperties:!1}),watchInputSchema=jsonSchema23({type:"object",properties:{compileOnly:boolean4("Submit compile chains instead of build chains"),strict:boolean4("Treat compile warnings as errors"),pollSeconds:{type:"integer",description:"How often to check upstream for newer recipes, in seconds; 0 never"},rebuild:boolean4("Reprocess all outputs on every change"),noPrune:boolean4("Skip the prune step on every build"),dryRun:boolean4("Write nothing on any build"),ignoreFailedAssertions:boolean4("Print failed assertions as warnings on every build"),ignoreFailedChecks:boolean4("Print errors from check handlers as warnings on every build")},additionalProperties:!1})}});import{LogLevel as LogLevel12}from"@sous-io/sous-plugin-api";function reportUnincludedMemories(missing,reporter){if(missing.length===0)return;let one=missing.length===1;reporter.list(missing.map(memory=>`${memory.recipe}: memories/${memory.name}`),{title:`${missing.length} ${one?"memory":"memories"} published by your subscribed recipes ${one?"is":"are"} not included in any output, so no agent will read ${one?"it":"them"}:`,footer:`To include every memory, add the line "@#memories/**/*.md" to your project's instruction source (the file your AGENTS.md or CLAUDE.md is built from). To leave a recipe's memories out on purpose, list the recipe in "recipes.memories.exclude" in your sous config.`},LogLevel12.Warning)}function reportLinkedRepos(links,reporter,level){let names2=Object.keys(links).sort();if(names2.length===0)return;let lead=names2.length===1?"One repository is LINKED to a working copy on this machine. Its recipes are read from that checkout, so versions, the lockfile and freshness checks do not apply to it.":`${names2.length} repositories are LINKED to working copies on this machine. Their recipes are read from those checkouts, so versions, the lockfile and freshness checks do not apply to them.`;reporter.list(names2.map(name=>`${name} -> ${links[name].path}`),{title:lead,footer:"Run 'sous repo unlink <name>' to go back to the published versions."},level)}function reportRetired(retired,reporter,asking2){for(let recipe of retired??[]){let usedBy=recipe.subscription!==void 0?[`this project's subscription to '${recipe.subscription}'`]:[],dependents=recipe.requestedBy.filter(holder=>holder!=="project");dependents.length>0&&usedBy.push(`${dependents.length===1?"the recipe":"the recipes"} ${dependents.join(", ")}, which ${dependents.length===1?"depends":"depend"} on it`);let items2=[`Pinned version: ${recipe.version}`,...usedBy.length===0?[]:[`Used by: ${usedBy.join("; ")}`],...recipe.replacements.map(replacement=>replacement.repo===void 0?`Replacement: ${replacement.ref}, in a repository this project has not added`:`Replacement: ${replacement.ref}`)];reporter.list(items2,{title:`The repository '${recipe.repo}' retired '${recipe.key}'. This project still builds it at the pinned version, and it gets no more updates:`,...asking2&&offered(recipe)?{}:retiredFooter(recipe)},LogLevel12.Warning)}}function offered(recipe){return recipe.subscription!==void 0&&recipe.replacements.length>0}function retiredFooter(recipe){return recipe.subscription===void 0?{}:recipe.replacements.length===0?{footer:`To stop using it, run 'sous subscription remove ${recipe.subscription}'.`}:recipe.replacements.some(replacement=>replacement.key===recipe.key)?{footer:"To swap it, run 'sous subscribe' with the replacement you want."}:{footer:`To swap it, run 'sous subscription remove ${recipe.subscription}', then 'sous subscribe' with each replacement you want.`}}function alone(change){return change.holder===void 0?"":` for ${change.holder} alone`}function whyMoved(change,followsSous){let follows=change.holder===void 0?followsSous?.find(entry=>entry.key===change.key&&entry.version===change.to):void 0;return follows===void 0?"":`, because the subscription to '${follows.subscription}' follows the installed sous, version ${follows.version}`}function reportLocked(diff,reporter,followsSous){diff.unchanged||diff.added.length===0&&diff.updated.length===0||reporter.list([...diff.added.map(change=>`pinned: ${change.key} at version ${change.to??"?"}${alone(change)}.`),...diff.updated.map(change=>`${change.key} moved from version ${change.from??"?"} to version ${change.to??"?"}${alone(change)}${whyMoved(change,followsSous)}.`)],{title:"Locking subscribed recipes",footer:"The lockfile has been updated. Commit it, so everyone building this project gets exactly these versions."},LogLevel12.Notice)}function reportRestored(report,reporter){report.restored.length!==0&&(reporter.stepStart("Restoring recipes",LogLevel12.Notice),reporter.note("This project's lockfile pins recipes that were not in the store on this machine, so they were fetched at exactly the versions it records."),reporter.list(report.restored.map(key=>`restored: ${key}`),{},LogLevel12.Notice))}function reportRestoreFailures(report,reporter){for(let failure of report.failed)reporter.problem(`Sous could not restore '${failure.key}' at the version the lockfile pins, so nothing from it was compiled.`,{subject:failure.key,cause:failure.reason})}function reportNewer(newer,reporter){newer.length!==0&&(reporter.variables(newer.map(entry=>({label:entry.key,value:entry.to,detail:`this project pins ${entry.from}${alone(entry)}${entry.staleIndex===!0?"; seen in the copy of the index sous already had, which may be out of date":""}`})),"Newer versions published",LogLevel12.Notice),reporter.note(newer.length===1?"This version is within the range declared for the recipe. No pin was changed, so this build uses the pinned version.":"Each version is within the range declared for its recipe. No pin was changed, so this build uses the pinned versions."))}function skippedLine(skipped){let where3=skipped.setBy?` (${skipped.setBy})`:"";switch(skipped.reason){case"subscription-disabled":return skipped.indirect===!0&&skipped.subscription!==void 0?`Skipped ${skipped.key}: reached only through ${skipped.subscription}, which is switched off${where3}.`:`Skipped ${skipped.key}: its subscription is switched off${where3}.`;case"repository-disabled":return`Skipped ${skipped.key}: its repository is switched off${where3}.`;default:return skipped.message.startsWith("Skipped ")?skipped.message:`Skipped ${skipped.key}: ${lowerFirst(skipped.message.replace(/\.$/u,""))}.`}}function prunedForSkippedLine(count2,dryRun4){let outputs=count2===1?"output":"outputs";return dryRun4?`Would prune ${count2} ${outputs} it had written.`:`Pruned ${count2} ${outputs} it had written.`}function unansweredWarning2(unanswered){if(unanswered.length===0)return;let count2=unanswered.length,pronoun=count2===1?"it":"them";return{title:`${count2} required recipe ${count2===1?"variable":"variables"} ${count2===1?"has":"have"} no answer, so the templates that use ${pronoun} render an empty value:`,items:unanswered.map(defined=>`${defined.definition.name} (asked by ${defined.recipe.namespace}/${defined.recipe.name})`),footer:`Run 'sous vars ask' to answer ${pronoun}.`}}function reportUnanswered(unanswered,reporter){let warning=unansweredWarning2(unanswered);warning!==void 0&&reporter.list(warning.items,{title:warning.title,footer:warning.footer},LogLevel12.Warning)}function reportUnanswerable(unanswerable,reporter){for(let warning of new Set(unanswerable.map(defined=>defined.unanswerable??"")))warning!==""&&reporter.warning(warning)}function reportPrepared(result,reporter){reportLocked(result.locked,reporter,result.followsSous),reportRestored(result.restored,reporter),reportRestoreFailures(result.restored,reporter),reportNewer(result.newer,reporter),reportUnanswered(result.unanswered,reporter),reportUnanswerable(result.unanswerable,reporter)}function lowerFirst(text){return text.length===0?text:text[0].toLowerCase()+text.slice(1)}function filesSummaryLine(input){let count2=(...actions)=>input.outputs.filter(output=>actions.includes(output.action)).length,created=count2("created","would-create"),updated=count2("updated","would-update"),written=created+updated,breakdown=[created>0?`${created} new`:"",updated>0?`${updated} updated`:""].filter(part=>part!=="").join(", "),writtenFiles=new Set(input.outputs.filter(output=>output.action!=="skipped-untracked").map(output=>output.file)),removed=new Set((input.removed??[]).filter(file2=>!writtenFiles.has(file2))).size,notWritten=new Set(input.notWritten??[]).size;return`Files: ${[`${written} ${input.dryRun?"would be written":"written"}${breakdown===""?"":` (${breakdown})`}`,`${count2("unchanged")} unchanged`,...removed>0?[`${removed} ${input.dryRun?"would be removed":"removed"}`]:[],...notWritten>0?[`${notWritten} not written`]:[]].join(", ")}.`}var init_report=__esm({"../sous-plugin-build/src/report.ts"(){"use strict"}});var prepare_exports={};__export(prepare_exports,{NOTHING_RESTORED:()=>NOTHING_RESTORED,NO_CHANGE:()=>NO_CHANGE,builtInPins:()=>builtInPins,isLocked:()=>isLocked,mergeDiffs:()=>mergeDiffs,prepare:()=>prepare,switchedOn:()=>switchedOn});import{IntentOutputs as IntentOutputs13}from"@sous-io/sous-plugin-api";async function prepare(input,ctx){return IntentOutputs13.of(await prepareProject(input,ctx))}async function prepareProject(input,ctx){let dryRun4=input.dryRun===!0,lock=ctx.services.get("recipes.lock"),resolver=ctx.services.get("recipes.resolver"),active=ctx.services.get("recipes.active"),subscriptions=switchedOn(ctx.config.get("subscriptions")??{}),seeded=active.list().filter(recipe=>recipe.source==="core").map(recipe=>recipe.id),current=lock.read(),locked=NO_CHANGE,unlocked=Object.entries(subscriptions).filter(([key,entry])=>!isLocked(key,entry,current));if(unlocked.length>0)try{let resolved=await resolver.resolveSubscriptions({...lock.held(current),...dryRun4?{}:{download:!0}});if(warnAboutProblems(resolved,ctx),resolved.unreadable.length===0){let next=lock.fromResolved(resolved.resolved,current);locked=await lock.write(next,{dryRun:dryRun4}),current=next}else ctx.reporter.problem(unreadableNotWritten(resolved.unreadable))}catch(error51){let keys=unlocked.map(([key])=>`'${key}'`).join(", ");ctx.reporter.problem(`Sous could not work out which version of ${keys} to use, so nothing from it was compiled.`,{cause:describe4(error51)})}let restored=NOTHING_RESTORED;if(!dryRun4&&Object.keys(current.recipes).length>0)try{restored=await lock.restore()}catch(error51){ctx.reporter.problem("Sous could not restore the recipes this project's lockfile pins.",{cause:describe4(error51)})}let checkedUpstream=!1,newer=[];if(!dryRun4&&input.offline!==!0&&Object.keys(current.recipes).length>0){let upstream=await checkUpstream(ctx,current,subscriptions);if(checkedUpstream=upstream.checked,newer.push(...upstream.newer),upstream.moved.length>0){let movedKeys=new Set(upstream.moved.map(change=>change.key));try{let resolved=await resolver.resolveSubscriptions({...lock.held(current,movedKeys),download:!0});if(resolved.unreadable.length>0)throw new Error(unreadableNotWritten(resolved.unreadable));let next=lock.fromResolved(resolved.resolved,current);locked=mergeDiffs(locked,await lock.write(next)),current=next,restored=mergeRestores(restored,await lock.restore({keys:[...movedKeys]}))}catch(error51){ctx.reporter.problem("Sous could not move to the newer recipe versions, so this build uses the versions it already had.",{cause:describe4(error51)})}}}let hashed=lock.withIndexHashes(current);hashed!==current&&!dryRun4&&await lock.write(hashed),!locked.unchanged&&!dryRun4&&ctx.configChanged();let skipped=active.skipped(),{unanswered,unanswerable}=ctx.services.get("recipe-answers.answers").get(),followsSous=builtInPins(subscriptions,current),notBuilt=new Set(skipped.map(recipe=>recipe.key)),retired=lock.retired(current).filter(recipe=>!notBuilt.has(recipe.key)),result={seeded,locked,restored,newer,checkedUpstream,skipped,unanswered,unanswerable,...followsSous.length===0?{}:{followsSous},...retired.length===0?{}:{retired}};return await ctx.emit("build.prepared",result),result}async function checkUpstream(ctx,current,subscriptions){let report={checked:!1,moved:[],newer:[]},indexes;try{indexes=await ctx.services.get("recipes.index-cache").getAll()}catch(error51){return ctx.reporter.problem("Sous could not check upstream for newer recipe versions, so this build uses the versions it already had.",{cause:describe4(error51)}),report}report.checked=indexes.indexes.some(index=>index.source==="network");let stale=new Set;for(let index of indexes.indexes)index.source==="stale"&&(stale.add(index.repo),ctx.services.get("recipes.index-cache").firstStaleNotice(index.repo)&&ctx.reporter.problem(`Sous could not check the repository '${index.repo}' for a newer version, so this build uses the copy of its index that it already had.`,{subject:index.repo,...index.problem?{cause:index.problem}:{}}));for(let failure of indexes.failed){let reasons=failure.attempts.map(attempt2=>`${attempt2.strategy}: ${attempt2.reason}`).join(`
465
+ `),read=this.upstream.get(key);return read===void 0&&(read=this.indexes(names2,!0,quiet),this.upstream.set(key,read)),read}async resolveSubscriptions(options2={}){let subscriptions=enabledSubscriptions(this.ctx.config.get("subscriptions"));return this.resolve(sortKeys2(Object.keys(subscriptions)).map(key=>this.subscriptionRequest(key)),options2)}subscriptionRequest(key){let entry=this.ctx.config.get("subscriptions")?.[key]??{};return{ref:this.ctx.services.get("refs.format").parseNamedRef(key,"config"),...entry.range===void 0?{}:{range:entry.range},...entry.prerelease===!0?{prerelease:!0}:{},requestedBy:PROJECT_HOLDER,kind:"subscribes"}}reachable(lockfile){return reachability({lockfile,subscriptions:this.ctx.config.get("subscriptions"),repos:this.ctx.config.get("repos"),keyOf:key=>this.keyOf(key)}).reached}keyOf(subscription){try{let format3=this.ctx.services.get("refs.format");return format3.key(format3.parseNamedRef(subscription,"config"))}catch{return plainSubscriptionKey(subscription)}}async indexes(names2,latest2,quiet){let cache2=this.ctx.services.get("recipes.index-cache"),found=new Map,checked3=new Set;for(let name of sortKeys2(names2))try{let read=await cache2.get(name,{latest:latest2});if(read.source==="stale"&&!quiet&&cache2.firstStaleNotice(name)){let problem=read.problem;this.runtime.host.reporter.problem(`Sous could not check the repository '${name}' for updates, so it is using the copy of its index that it already had.`,problem===void 0?{}:{cause:problem})}found.set(name,read.index),latest2&&read.source!=="stale"&&checked3.add(name)}catch{let cached2=cache2.cached(name);cached2!==void 0&&found.set(name,cached2.index)}return{found,checked:checked3}}async loadManifest(recipe){let manifests=this.ctx.services.get("formats.manifests"),link=this.ctx.services.get("recipes.links").get(recipe.repo);if(link!==void 0){let map3=this.linked.get(link.path);map3===void 0&&(map3=mapLinkedRecipes(link.path,manifests),this.linked.set(link.path,map3));let found=(await map3).get(recipe.key);if(found!==void 0)return{depends:found.manifest.depends??[],subscribes:found.manifest.subscribes??[]}}let hit=await this.ctx.services.get("recipes.store").get(storeKeyOf2(recipe.key,recipe.identity,recipe.version));if(hit===void 0)return;let manifest=await manifests.readRecipe(hit.dir);return manifest===void 0?void 0:{depends:manifest.manifest.depends??[],subscribes:manifest.manifest.subscribes??[]}}parseDependency(written){try{return this.ctx.services.get("refs.resolver").resolveSync({input:written,from:"manifest",lookups:!1,refusedIsEmpty:!0}).refs}catch{return[]}}format(request){try{return this.ctx.services.get("refs.format").format(request.ref)}catch{return request.ref.name}}}}});import{nullReporter as nullReporter3}from"@sous-io/sous-plugin-api";var PartBRuntime,init_runtime=__esm({"../sous-plugin-recipes/src/part-b/runtime.ts"(){"use strict";init_constants();init_index_cache();init_support();PartBRuntime=class{constructor(host){this.host=host}core;fetched=new Set;recipeFilesWanted=!1;leftOut=0;noteFetched(keys){for(let key of keys)this.fetched.add(key)}downloadsRecipeFiles(plan2){return this.recipeFilesWanted||plan2===void 0||plan2.intent?.needsRecipeFiles===!0}noteLeftOut(count2){this.leftOut=count2}leftOutRecipeFiles(){return this.leftOut>0}wantRecipeFiles(){this.recipeFilesWanted=!0}takeFetched(among){let keys=[...this.fetched].filter(key=>among===void 0||among.includes(key));for(let key of keys)this.fetched.delete(key);return keys}get services(){return this.host.services}get entities(){return this.host.entities}homePaths(){return this.services.get("host.sous-home").paths(this.host.env)}hosts(){return this.entities.list("repository-host")}identity(url2){return this.services.get("refs.locations").identity(url2)}tryIdentity(url2,hosts){try{return this.identity(url2)}catch{}try{let host=hostFor(hosts??this.hosts(),url2);if(host===void 0)return;let canonical=host.canonicalize(url2);return`${canonical.host}/${canonical.owner}/${canonical.name.replace(/\.git$/i,"")}`.split("/").filter(segment=>segment.length>0).map(segment=>segment.toLowerCase()).join("/")}catch{return}}indexCore(){if(this.core===void 0){let paths=this.homePaths();this.core=new IndexCacheCore({directory:paths.indexCache,strategiesFile:paths.readStrategies,parser:this.services.get("formats.index-file"),hosts:()=>this.hosts(),hostContext:()=>this.hostContext(this.host.reporter),strategyMemorySeconds:()=>this.host.engine.config.get("store")?.strategyMemorySeconds??DEFAULT_STRATEGY_MEMORY_SECONDS})}return this.core}hostContext(reporter=nullReporter3,signal){return{plugin:RECIPES_PLUGIN,config:this.host.engine.config,services:this.services,entities:this.entities,project:this.host.project,env:this.host.env,cwd:this.host.project?.root??process.cwd(),reporter,...signal===void 0?{}:{signal}}}async emit(name,payload){try{await this.host.emit(name,payload)}catch{}}}}});import{jsonSchema as jsonSchema15}from"@sous-io/sous-plugin-api";var dryRun2,yes2,lockRebuildInputSchema,lockShowInputSchema,repoGcInputSchema,repoLinkInputSchema,repoUnlinkInputSchema,activeRecipeSchema,init_schemas3=__esm({"../sous-plugin-recipes/src/part-b/schemas.ts"(){"use strict";dryRun2={type:"boolean",description:"Print what would change without writing anything"},yes2={type:"boolean",description:"Answer yes to every question this command can ask (trusting a repository, discarding work)"},lockRebuildInputSchema=jsonSchema15({type:"object",properties:{dryRun:{...dryRun2,description:"Print what would change without writing the lockfile"}},additionalProperties:!1}),lockShowInputSchema=jsonSchema15({type:"object",properties:{},additionalProperties:!1}),repoGcInputSchema=jsonSchema15({type:"object",properties:{maxBytes:{type:"integer",description:"The size cap to collect down to, instead of the one this project's config sets"},dryRun:{...dryRun2,description:"Print what would be evicted without removing anything"}},additionalProperties:!1}),repoLinkInputSchema=jsonSchema15({type:"object",properties:{repo:{type:"string",description:"The repository's short name from this project's config, its full URL, or the path of a checkout to link in place"},path:{type:"string",description:"An existing checkout to link. Without it, the repository is cloned."},global:{type:"boolean",description:"Link for every project on this machine, sharing one checkout, rather than for this project"},yes:yes2,dryRun:{...dryRun2,description:"Print what would change without cloning or writing anything"},branch:{type:"string",description:"Switch the checkout to this existing branch, fetching it from upstream first"},createBranch:{type:"string",description:"Create this new branch in the checkout and switch to it"},generateBranch:{type:"boolean",description:"Create a new branch named sous/edit-<date>-<time> in the checkout and switch to it"},from:{type:"string",description:"Start the new branch from this branch instead of the repository's default branch"},latest:{type:"boolean",description:"Make the branch being worked from match upstream's, after listing any local work that would be discarded"}},required:["repo"],additionalProperties:!1}),repoUnlinkInputSchema=jsonSchema15({type:"object",properties:{repo:{type:"string",description:"The repository's short name, as it appears in the links map"},global:{type:"boolean",description:"Remove the machine-wide link rather than this project's link"},update:{type:"boolean",description:"Move this repository's pins to the newest versions their ranges allow before rebuilding"},remove:{type:"boolean",description:"Delete the checkout as well, when sous cloned it"},yes:yes2,dryRun:dryRun2,noBuild:{type:"boolean",description:"Unlink without rebuilding the project"},answer:{type:"array",items:{type:"string"},description:"Answer a recipe question ahead of time, as <name>=<value>"},answersFile:{type:"string",description:"A file of answers to recipe questions"}},required:["repo"],additionalProperties:!1}),activeRecipeSchema=jsonSchema15({type:"object",properties:{id:{type:"string"},namespace:{type:"string"},name:{type:"string"},repo:{type:"string"},identity:{type:"string"},version:{type:"string"},hash:{type:"string"},kind:{enum:["subscribes","depends"]},requestedBy:{type:"array",items:{type:"string"}},dir:{type:"string"},source:{enum:["store","link","core","project"]},manifest:{type:"object"}},required:["id","namespace","name","repo","identity","version","hash","kind","requestedBy","dir","source","manifest"]})}});import fs48 from"node:fs";async function registerPartB(sous){let runtime=new PartBRuntime(sous),seeder=new CoreSeeder(runtime);sous.entities.kinds().includes("active-recipe")||sous.entities.define("active-recipe",activeRecipeSchema,{description:"A locked recipe reached from the subscriptions switched on on this machine, its files on disk."}),registerServices(sous,runtime),registerContributors(sous,runtime,seeder),registerIntents(sous,runtime),sous.entities.add("ref-lookup",lockfileLookup()),sous.on("*.before",async(event,ctx)=>{!runtime.leftOutRecipeFiles()||ctx.chain===void 0||ctx.chain.parallel||ctx.engine.intents.get(event.intent)?.definition.needsRecipeFiles===!0&&(runtime.wantRecipeFiles(),await ctx.refreshConfig())}),sous.on("config.built",event=>{let project=sous.project;if(!(project===void 0||!fs48.existsSync(project.sousDir)||runtime.leftOutRecipeFiles()))try{writeRecipeTypes(project.sousDir,event.payload.config.entities.list("active-recipe"))}catch(error51){sous.reporter.warning(`Sous could not write the recipe plugin types into ${project.sousDir}/types: ${error51 instanceof Error?error51.message:String(error51)}`)}})}function registerServices(sous,runtime){sous.services.add("recipes.lock",(_config,ctx)=>new LockService(ctx,runtime),{lifetime:"config"}),sous.services.add("recipes.resolver",(_config,ctx)=>new ResolverService(ctx,runtime),{lifetime:"config"}),sous.services.add("recipes.links",(_config,ctx)=>new LinksFiles({sousDir:ctx.project?.sousDir,globalFile:runtime.homePaths().links,parser:ctx.services.get("formats.links-map")}),{lifetime:"config"}),sous.services.add("recipes.index-cache",()=>{let core=runtime.indexCore();return installPackagedOverlay(runtime),new IndexCacheService(core,{trusted:()=>trustedRepos2({services:sous.services,config:sous.engine.config}),identity:url2=>runtime.tryIdentity(url2)??url2,freshnessSeconds:()=>sous.engine.config.get("store")?.freshnessSeconds??DEFAULT_FRESHNESS_SECONDS,linkedPath:repo=>{try{return sous.services.get("recipes.links").get(repo)?.path}catch{return}}})},{lifetime:"singleton"}),sous.services.add("compiler.namespace-resolver",(_config,ctx)=>{let resolver=ctx.services.get("refs.resolver"),globs=ctx.services.get("host.globs"),recipesResolver=ctx.services.get("recipes.resolver");return new ActiveNamespaceResolver({recipes:ctx.entities.list("active-recipe"),parse:reference=>resolver.resolveSync({input:reference,from:"include",kinds:["recipeFile"],lookups:!1,refusedIsEmpty:!0}),isMatch:(name,pattern,options2)=>globs.isMatch(name,pattern,{nocase:options2.nocase,dot:!0}),explainMissing:recipe=>explainMissing(recipe,{subscriptions:ctx.config.get("subscriptions"),keyOf:key=>recipesResolver.keyOf(key),lockfile:()=>ctx.services.get("recipes.lock").read(),cachedIndex:identity2=>runtime.indexCore().readCached(identity2)})})},{lifetime:"config"})}function installPackagedOverlay(runtime){let hash2;try{let identity2=runtime.services.get("host.package").identity(),dir=packagedCoreRecipeDir(identity2.root);if(dir===void 0)return;runtime.indexCore().setOverlayIfNone(coreIndexOverlay({version:identity2.version,hash:()=>{if(hash2===void 0)try{hash2=runtime.services.get("formats.recipe-hash").hashDirectorySync(dir)}catch{hash2=null}return hash2??void 0}}))}catch{}}function registerContributors(sous,runtime,seeder){sous.config.contribute(coreContributor(runtime,seeder)),sous.config.contribute(fetchContributor(runtime)),sous.config.contribute(configLayersContributor(runtime)),sous.config.contribute(pluginsContributor())}function registerIntents(sous,runtime){sous.intents.add({intent:"lock.rebuild",requiresProject:!0,summary:"Rebuild this project's lockfile from its subscriptions and the cached repository indexes",input:lockRebuildInputSchema,changesConfig:!0,cli:{examples:["sous lock rebuild","sous lock rebuild --dry-run"]},handle:async(input,ctx)=>rebuildLock(input,ctx)}),sous.intents.add({intent:"lock.show",requiresProject:!0,summary:"Show every recipe version this project's lockfile pins",input:lockShowInputSchema,parallel:!0,cli:{examples:["sous lock show"]},handle:(_input,ctx)=>lockShowOutputs(showLock(ctx))}),sous.intents.add({intent:"repo.gc",requiresProject:!0,summary:"Collect the machine-wide recipe store back down to its size cap",input:repoGcInputSchema,cli:{examples:["sous repo gc","sous repo gc --dry-run","sous repo gc --max-bytes 268435456"]},handle:async(input,ctx)=>storeGcOutputs(await collectStore(input,ctx))}),sous.intents.add({intent:"repo.link",requiresProject:!0,summary:"Point a repository at a working copy on this machine instead of a published version",description:"'sous repo link <path>' links the checkout already at that path, where it is, adding the repository to this project first if it has not been added yet. 'sous repo link <name-or-url>' clones the repository into .sous/repos and links that clone. 'sous repo link <name-or-url> <path>' links the checkout at that path to that repository, and clones nothing. A checkout that was already on disk is fetched and compared with upstream; only the branch flags and --latest change it.",input:repoLinkInputSchema,changesConfig:!0,cli:{positional:["repo","path"],flags:{yes:{short:"y",aliases:["force","trust"]}},examples:["sous repo link ../sous-recipes","sous repo link sous-recipes","sous repo link sous-recipes ~/Projects/sous-recipes","sous repo link https://github.com/sous-io/sous-recipes","sous repo link sous-recipes --global","sous repo link sous-recipes --latest","sous repo link sous-recipes --generate-branch","sous repo link sous-recipes --branch my-change --latest"]},agent:{usage:"Use to edit a repository's recipes in a working copy. Pass yes: true to trust a repository the project does not trust yet."},handle:async(input,ctx)=>linkOutputs(await linkRepo(input,ctx,runtime))}),sous.intents.add({intent:"repo.unlink",requiresProject:!0,summary:"Stop reading a repository from a working copy and go back to its pinned versions",input:repoUnlinkInputSchema,changesConfig:!0,cli:{positional:["repo"],flags:{yes:{short:"y",aliases:["force","trust"]}},examples:["sous repo unlink sous-recipes","sous repo unlink sous-recipes --update","sous repo unlink sous-recipes --remove","sous repo unlink sous-recipes --global"]},handle:async(input,ctx)=>unlinkOutputs(ctx,await unlinkRepo(input,ctx,runtime))})}var init_part_b=__esm({"../sous-plugin-recipes/src/part-b/index.ts"(){"use strict";init_constants();init_config_layers();init_core_recipe();init_core_contributor();init_fetch_contributor();init_index_cache();init_lock_intents();init_link_intent();init_links_service();init_unlink_intent();init_lock_service();init_lockfile_lookup();init_explain_missing();init_namespace_resolver();init_recipe_plugins();init_resolver_service();init_runtime();init_schemas3()}});var package_default12,init_package5=__esm({"../sous-plugin-recipes/package.json"(){package_default12={name:"@sous-io/sous-plugin-recipes",version:"1.1.6",description:"Repositories, trust, subscriptions, the lockfile, the store, the index cache, links, the core recipe, the catalog and recipe plugins.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-compiler":"workspace:*","@sous-io/sous-plugin-confd":"workspace:*","@sous-io/sous-plugin-formats":"workspace:*","@sous-io/sous-plugin-git":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@sous-io/sous-plugin-refs":"workspace:*","@sous-io/sous-plugin-variables":"workspace:*",semver:"^7.8.5"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*","@sous-io/sous-plugin-update":"workspace:*","@types/semver":"^7.8.0",glob:"^13.0.6",yaml:"^2.9.0"},engines:{node:">=22"}}}});import{definePlugin as definePlugin12}from"@sous-io/sous-plugin-api";var PLUGIN_NAME11,recipesPlugin,init_src6=__esm({"../sous-plugin-recipes/src/index.ts"(){"use strict";init_part_a();init_part_b();init_package5();init_contents();init_recipe_plugins();init_config_layers();init_manifests2();PLUGIN_NAME11="@sous-io/sous-plugin-recipes",recipesPlugin=definePlugin12({name:PLUGIN_NAME11,version:package_default12.version,description:"Repositories, trust, subscriptions, the lockfile, the store, the index cache, links, the core recipe, the catalog and recipe plugins.",dependsOn:{"@sous-io/sous-plugin-confd":`^${package_default12.version}`,"@sous-io/sous-plugin-formats":`^${package_default12.version}`,"@sous-io/sous-plugin-refs":`^${package_default12.version}`,"@sous-io/sous-plugin-variables":`^${package_default12.version}`,"@sous-io/sous-plugin-git":`^${package_default12.version}`,"@sous-io/sous-plugin-compiler":`^${package_default12.version}`,"@sous-io/sous-plugin-host":`^${package_default12.version}`},async register(sous){await registerPartB(sous),defineEntityKinds(sous),registerPartA(sous)}})}});import fs51 from"node:fs";import{pathToFileURL as pathToFileURL6}from"node:url";import{HANDLER_PURPOSES,SousError as SousError25}from"@sous-io/sous-plugin-api";function handlerRecipes(config2){let repos=config2.atPath("repos").get()??{};return config2.entities("active-recipe").filter(recipe=>{let repo=repos[recipe.repo];return recipe.kind==="subscribes"&&repo!==void 0&&repo.enabled!==!1})}function recipeDeclarationsContributor(){return{id:RECIPE_DECLARATIONS_CONTRIBUTOR,after:[FETCH_CONTRIBUTOR],contribute(config2){for(let recipe of handlerRecipes(config2)){let handlers=recipe.manifest.handlers;if(handlers!==void 0)for(let purpose of HANDLER_PURPOSES)for(let entry of handlers[purpose]??[]){let declaration={recipe:recipe.id,purpose,file:entry.file,handler:entry.handler};config2.atPath(RECIPE_HANDLERS_KEY).append(declaration)}}}}}function recipeHandlerId(declaration){return`${declaration.recipe}/${declaration.purpose}/${declaration.file}#${declaration.handler}`}function loadRecipeHandler(declaration,file2){return(async(sous,input)=>{if(!fs51.existsSync(file2))throw new SousError25(`The recipe ${declaration.recipe} lists the handler file ${declaration.file}, which is not there.`);let handle9=(await import(pathToFileURL6(file2).href))[declaration.handler];if(typeof handle9!="function")throw new SousError25(`The recipe ${declaration.recipe} lists the handler ${declaration.handler} in ${declaration.file}, which does not export a function by that name.`);return handle9(sous,input)})}function recipeHandlersContributor(){return{id:RECIPE_HANDLERS_CONTRIBUTOR,after:[RECIPE_DECLARATIONS_CONTRIBUTOR,FETCH_CONTRIBUTOR],contribute(config2){let recipes=new Map(handlerRecipes(config2).map(recipe=>[recipe.id,recipe])),declarations=config2.atPath(RECIPE_HANDLERS_KEY).get()??[],seen=new Set;for(let declaration of declarations){let recipe=recipes.get(declaration.recipe);if(recipe===void 0)continue;let identity2=JSON.stringify([declaration.recipe,declaration.purpose,declaration.file,declaration.handler]);if(seen.has(identity2))continue;seen.add(identity2);let file2=insideRecipe(recipe.dir,declaration.file);if(file2===void 0){config2.warn(`The recipe ${recipe.id} names a handler file outside its own files (${declaration.file}), so its handler ${declaration.handler} was not added.`);continue}let entity={id:recipeHandlerId(declaration),purpose:declaration.purpose,recipe:recipe.id,source:`${declaration.file}#${declaration.handler}`,handle:loadRecipeHandler(declaration,file2)};config2.addEntity("handler",entity)}}}}var RECIPE_DECLARATIONS_CONTRIBUTOR,RECIPE_HANDLERS_CONTRIBUTOR,RECIPE_HANDLERS_KEY,FETCH_CONTRIBUTOR,init_recipes=__esm({"../sous-plugin-handlers/src/recipes.ts"(){"use strict";init_src6();RECIPE_DECLARATIONS_CONTRIBUTOR="handlers/recipe-declarations",RECIPE_HANDLERS_CONTRIBUTOR="handlers/recipes",RECIPE_HANDLERS_KEY="recipes.handlers",FETCH_CONTRIBUTOR="recipes.fetch"}});import fs52 from"node:fs/promises";import path69 from"node:path";import{SousError as SousError26}from"@sous-io/sous-plugin-api";function inProject(project,file2){return path69.resolve(project.root,file2)}function needService(services,name,plugin){if(services===void 0||!services.has(name))throw new SousError26(`This helper needs the "${name}" service, which ${plugin} provides, and it is not available here.`);return services.get(name)}function createHelpers(sources,report){let{project}=sources,system=()=>needService(sources.services(),"handlers.system","@sous-io/sous-plugin-handlers");return{report,utils:{system:{isAppAvailable:name=>system().isAppAvailable(name),appVersion:name=>system().appVersion(name)},process:{run(command,args=[],options2={}){return needService(sources.services(),"host.processes","@sous-io/sous-plugin-host").run(command,args,{cwd:options2.cwd===void 0?project.root:inProject(project,options2.cwd),env:sources.env,label:`${command} ${args.slice(0,1).join(" ")}`.trim(),...options2.input===void 0?{}:{input:options2.input},...options2.timeoutMs===void 0?{}:{timeoutMs:options2.timeoutMs}})}},file:{async exists(file2){try{return await fs52.access(inProject(project,file2)),!0}catch{return!1}},async read(file2){try{return await fs52.readFile(inProject(project,file2),"utf8")}catch(error51){if(error51.code==="ENOENT")return;throw error51}},async remove(file2){let absolute=inProject(project,file2);try{return await fs52.rm(absolute),!0}catch(error51){if(error51.code==="ENOENT")return!1;throw error51}}},files:{async removeMatching(pattern){let matched=await needService(sources.services(),"host.globs","@sous-io/sous-plugin-host").match(pattern,{cwd:project.root,dot:!0,onlyFiles:!0});for(let file2 of matched)await fs52.rm(inProject(project,file2),{force:!0});return matched}}},editor:{file(file2){let services=sources.services();if(sources.editorUnavailable!==void 0)throw new SousError26(sources.editorUnavailable);if(services===void 0||!services.has(EDITOR_SERVICE))throw new SousError26('sous.editor.file needs the document editor (the "editor" service of @sous-io/sous-plugin-editor), and it is not loaded.',{details:["Load @sous-io/sous-plugin-editor, or remove it from plugins.disabled."]});return services.get(EDITOR_SERVICE).file(file2)}},vars:{get:name=>sources.vars(name)},project,config:sources.config,env:sources.env}}function answerFrom(services,recipe,name){if(!services.has("recipe-answers.answers"))return;let answers=services.get("recipe-answers.answers");return recipe===void 0?answers.get().merged[name]:answers.forRecipe(recipe)[name]}function createTools(ctx,project,recipe,report){let helpers=createHelpers({project,env:ctx.env,services:()=>ctx.services,config:{get:key=>ctx.config.get(key)},vars:name=>answerFrom(ctx.services,recipe,name)},report),{config:_config,...own}={...helpers,project};return new Proxy(ctx,{get(target,property){if(typeof property=="string"&&Object.hasOwn(own,property))return own[property];let value=Reflect.get(target,property,target);return typeof value=="function"?value.bind(target):value},has(target,property){return typeof property=="string"&&Object.hasOwn(own,property)||Reflect.has(target,property)}})}function createConfigureTools(config2,services,recipe,report){let project=config2.project;return createHelpers({project,env:config2.env,services,config:{get:key=>config2.atPath(key).get()},vars:name=>configureAnswer(config2,recipe,name),editorUnavailable:"sous.editor.file edits a document directly, which cannot happen while the config is built. In a configure handler, declare the edit instead: add it to editor.edits through the config builder."},report)}function configureAnswer(config2,recipe,name){let source=config2.entity("variable-source","recipe-answers");if(source===void 0)return;let lookup={project:config2.project,env:config2.env,config:{get:key=>config2.atPath(key).get()}};return(recipe===void 0?void 0:source.scoped?.(recipe,lookup)?.[name])??source.variables(lookup)[name]}var EDITOR_SERVICE,ReportCollector,init_tools=__esm({"../sous-plugin-handlers/src/tools.ts"(){"use strict";EDITOR_SERVICE="editor",ReportCollector=class{constructor(handler){this.handler=handler}entries=[];report={error:message2=>this.add("error",message2),warn:message2=>this.add("warn",message2),info:message2=>this.add("info",message2)};add(level,message2){this.entries.push({level,message:String(message2),handler:this.handler})}}}});import{IntentOutput as IntentOutput10,IntentOutputs as IntentOutputs11,messageText as messageText2,SousError as SousError27}from"@sous-io/sous-plugin-api";function orderHandlers(items2,purpose,entryOf){let mine=items2.filter(item=>entryOf(item).purpose===purpose);return[...mine.filter(item=>entryOf(item).recipe===void 0),...mine.filter(item=>entryOf(item).recipe!==void 0)].map((item,index)=>({item,index})).sort((a,b)=>(entryOf(a.item).order??DEFAULT_ORDER)-(entryOf(b.item).order??DEFAULT_ORDER)||a.index-b.index).map(({item})=>item)}function describeThrown(error51){return error51 instanceof Error?messageText2(error51):String(error51)}function handlerLabel(entry){if(entry.recipe!==void 0){let name=entry.source===void 0?entry.id:entry.source.slice(entry.source.lastIndexOf("#")+1);return`${entry.recipe} (${entry.purpose}: ${name})`}return entry.plugin===void 0?`${entry.purpose}: ${entry.id}`:`${entry.plugin} (${entry.purpose}: ${entry.id})`}function reportLine(label,message2){return`${label}: ${message2}`}async function runHandlers(ctx,purpose,options2={}){let project=ctx.project,only=options2.recipes===void 0?void 0:new Set(options2.recipes),ignoring=purpose==="check"&&options2.ignoreFailedChecks===!0,records=ctx.entities.kinds().includes("handler")?ctx.entities.describe("handler"):[],ran=[],errors=0,warnings=0;if(project===void 0)return{purpose,ran,errors,warnings,ignoredErrors:0,failed:!1};for(let record2 of orderHandlers(records,purpose,one=>one.entry)){let{entry}=record2;if(only!==void 0&&(entry.recipe===void 0||!only.has(entry.recipe)))continue;let label=handlerLabel({...entry,plugin:entry.plugin??record2.plugin}),collector=new ReportCollector(entry.id),tools=createTools(ctx,project,entry.recipe,collector.report),threw;try{await entry.handle(tools,options2.input)}catch(error51){threw=describeThrown(error51),collector.entries.push({level:"error",message:`failed: ${threw}`,handler:entry.id})}for(let report of collector.entries)forward(ctx,label,report,ignoring),errors+=report.level==="error"?1:0,warnings+=report.level==="warn"?1:0;ran.push({id:entry.id,plugin:record2.plugin,label,...entry.recipe===void 0?{}:{recipe:entry.recipe},reports:collector.entries,...threw===void 0?{}:{threw}})}return{purpose,ran,errors,warnings,ignoredErrors:ignoring?errors:0,failed:errors>0&&!ignoring}}function forward(ctx,label,report,ignoring){let details={handler:report.handler},line=reportLine(label,report.message);report.level==="error"?ignoring?ctx.reporter.warning(`${line} (a failed check, ignored)`,details):ctx.reporter.error(line,details):report.level==="warn"?ctx.reporter.warning(line,details):ctx.reporter.info(line,details)}function checksFailedError(result){let failing=result.ran.filter(run=>run.reports.some(report=>report.level==="error")).map(run=>run.id),count2=result.errors===1?"an error":`${result.errors} errors`;return new SousError27(`The checks reported ${count2} (${failing.join(", ")}), so nothing was built.`,{details:["Fix what they report, or pass --ignore-failed-checks to build anyway."]})}function handlerOutputs(result){return new IntentOutputs11([new IntentOutput10({data:result})],result.purpose==="check"&&result.failed?{exitCode:1}:{})}var DEFAULT_ORDER,init_run=__esm({"../sous-plugin-handlers/src/run.ts"(){"use strict";init_tools();DEFAULT_ORDER=500}});import"@sous-io/sous-plugin-api";function configureContributor(services){return{id:CONFIGURE_CONTRIBUTOR,after:[RECIPE_HANDLERS_CONTRIBUTOR],async contribute(config2){for(let entry of orderHandlers(config2.entities("handler"),"configure",one=>one)){let label=handlerLabel(entry),collector=new ReportCollector(entry.id),tools=createConfigureTools(config2,services,entry.recipe,collector.report);try{await entry.handle(tools,{config:config2})}catch(error51){collector.entries.push({level:"error",message:`failed: ${describeThrown(error51)}`,handler:entry.id})}for(let report of collector.entries)forward2(config2,label,report)}}}}function forward2(config2,label,report){let details={handler:report.handler},line=reportLine(label,report.message);report.level==="error"?config2.error(line,details):report.level==="warn"?config2.warning(line,details):config2.info(line,details)}var CONFIGURE_CONTRIBUTOR,init_configure=__esm({"../sous-plugin-handlers/src/configure.ts"(){"use strict";init_recipes();init_run();init_tools();CONFIGURE_CONTRIBUTOR="handlers/configure"}});var DOCTOR_CHECK_ORDER,init_types=__esm({"../sous-plugin-doctor/src/types.ts"(){"use strict";DOCTOR_CHECK_ORDER={config:100,lockfile:200,variables:300,migrations:400,gitHooks:500,checkHandlers:600,assertions:700,outputs:800}}});import crypto2 from"node:crypto";import fs53 from"node:fs";import{SousError as SousError28}from"@sous-io/sous-plugin-api";function messageOf6(error51){return error51 instanceof Error?error51.message:String(error51)}function has2(ctx,name){return ctx.services.has(name)}function holdersInWords2(holders){return holders.length===0?"nothing":holders.map(holder=>holder==="project"?"this project":holder).join(", ")}function describeEntryChange2(change){let lines3=[],kindInWords2=kind=>kind==="depends"?"a dependency":"a subscription";return change.requestedBy!==void 0&&lines3.push(`${change.key} ${change.version} is pinned for ${holdersInWords2(change.requestedBy.from)}, and the subscriptions now need it for ${holdersInWords2(change.requestedBy.to)}`),change.kind!==void 0&&lines3.push(`${change.key} ${change.version} is pinned as ${kindInWords2(change.kind.from)}, and the subscriptions now need it as ${kindInWords2(change.kind.to)}`),lines3}function describeChange(change,kind){let forHolder=change.holder===void 0?"":` for ${change.holder}`;switch(kind){case"added":return`${change.key} ${change.to??""}${forHolder} is not pinned, and a subscription needs it`;case"removed":return`${change.key} ${change.from??""}${forHolder} is pinned, and no subscription needs it`;default:return`${change.key}${forHolder} is pinned at ${change.from??"?"}, and the subscriptions now need ${change.to??"?"}`}}async function lockfileTheSubscriptionsMake(ctx){let lock=ctx.services.get("recipes.lock"),before=lock.read(),result=await ctx.services.get("recipes.resolver").resolveSubscriptions({...lock.held(before),quiet:!0,download:!0}),after=lock.fromResolved(result.resolved,before);return{lock,before,after,result,diff:lock.diff(before,after)}}async function downloadedToLook(ctx){let lock=ctx.services.get("recipes.lock"),restored=Object.keys(lock.read().recipes).length===0?{restored:[],failed:[]}:await lock.restore(),downloaded=[...restored.restored].sort();return{notes:downloaded.length===0?[]:[`Sous downloaded ${downloaded.length===1?"this recipe":"these recipes"} into this machine's recipe store to read ${downloaded.length===1?"it":"them"}: ${downloaded.join(", ")}.`],failed:restored.failed.map(failure=>`${failure.key}: ${failure.reason}`)}}function variableAnswers(ctx,answers){if(!ctx.entities.kinds().includes("migration"))return[...answers];let migrations=ctx.entities.list("migration"),ids=new Set(migrations.flatMap(migration=>(migration.questions??[]).map(question=>question.id)));return answers.filter(entry=>!ids.has(entry.slice(0,Math.max(0,entry.indexOf("="))).trim()))}function hashOf2(file2){return crypto2.createHash("sha256").update(fs53.readFileSync(file2,"utf8"),"utf8").digest("hex")}var CONFIG_FAILED,NO_PROJECT,configCheck,lockfileCheck,variablesCheck,outputsCheck,BUILT_IN_CHECKS,init_checks3=__esm({"../sous-plugin-doctor/src/checks.ts"(){"use strict";init_types();CONFIG_FAILED={status:"skipped",summary:"Skipped: the config did not load."},NO_PROJECT={status:"skipped",summary:"Skipped: sous is not running in a project."};configCheck={id:"config",order:DOCTOR_CHECK_ORDER.config,description:"The config loads",check(ctx){let error51=ctx.engine.configError;if(error51===void 0)return{status:"ok"};let details=error51 instanceof SousError28?[...error51.details]:[];return{status:"problem",summary:`The config did not load: ${messageOf6(error51)}`,details,...ctx.project?.configPath===void 0?{}:{hint:`The config file is ${ctx.project.configPath}.`}}}};lockfileCheck={id:"lockfile",order:DOCTOR_CHECK_ORDER.lockfile,description:"The lockfile agrees with the subscriptions",async check(ctx,run){if(run.configFailed)return CONFIG_FAILED;if(ctx.project===void 0)return NO_PROJECT;if(!has2(ctx,"recipes.lock")||!has2(ctx,"recipes.resolver"))return{status:"skipped",summary:"Skipped: the recipes plugin is not loaded."};let{result,diff,lock}=await lockfileTheSubscriptionsMake(ctx),looked=await downloadedToLook(ctx),notes=looked.notes.length===0?{}:{notes:looked.notes};if(result.missingRepos.length>0)return{status:"problem",summary:"The subscriptions need repositories this project does not trust.",details:result.missingRepos.map(missing=>`${missing.name}${missing.url===void 0?"":` (${missing.url})`}, needed by ${missing.requiredBy.map(entry=>entry.ref).join(", ")}`),hint:"Trusting a repository is a decision for a person: add each with 'sous repo add <url>'.",...notes};if(result.unreadable.length>0){let reasons=new Map((result.downloadFailures??[]).map(failure=>[failure.key,failure.reason]));return{status:"problem",summary:`Sous cannot tell whether the lockfile matches the subscriptions: it could not read what ${result.unreadable.length===1?"this recipe depends":"these recipes depend"} on.`,details:[...result.unreadable.map(key=>reasons.has(key)?`${key}: ${reasons.get(key)}`:key),...looked.failed],hint:"Their files could not be downloaded into this machine's recipe store, and their repository's index does not record what they depend on. Check the network and that the repositories are reachable, then run sous doctor again.",...notes}}return diff.unchanged?{status:"ok",...notes}:{status:"problem",summary:`The lockfile (${lock.path()}) does not match the subscriptions.`,details:[...diff.added.map(change=>describeChange(change,"added")),...diff.removed.map(change=>describeChange(change,"removed")),...diff.updated.map(change=>describeChange(change,"updated")),...diff.changed.flatMap(change=>describeEntryChange2(change)),...diff.reposAdded.map(name=>`The repository ${name} is not in the lockfile, and a subscription needs it`),...diff.reposRemoved.map(name=>`The repository ${name} is in the lockfile, and no subscription needs it`)],fix:"Write the lockfile the subscriptions make, keeping every pin their ranges still allow",...notes}},async fix(ctx){let{lock,after,diff,result}=await lockfileTheSubscriptionsMake(ctx);if(result.unreadable.length>0)throw new SousError28(`The lockfile was not written: sous could not read what ${result.unreadable.join(", ")} ${result.unreadable.length===1?"depends":"depend"} on.`);await lock.write(after),ctx.configChanged();let changes=diff.added.length+diff.removed.length+diff.updated.length+diff.changed.length;return{summary:`The lockfile was written again with ${changes===1?"1 change":`${changes} changes`}: ${lock.path()}.`}}};variablesCheck={id:"variables",order:DOCTOR_CHECK_ORDER.variables,description:"Required recipe variables have answers",async check(ctx,run){if(run.configFailed)return CONFIG_FAILED;if(ctx.project===void 0)return NO_PROJECT;if(ctx.engine.intents.get("vars.list")===void 0)return{status:"skipped",summary:"Skipped: no plugin lists recipe variables."};let missing=((await ctx.run("vars.list",{})).toPlain().variables??[]).filter(entry=>entry.variable.definition.required===!0&&!entry.answered&&entry.value===void 0&&entry.variable.unanswerable===void 0);return missing.length===0?{status:"ok"}:{status:"problem",summary:missing.length===1?"1 required recipe variable has no answer.":`${missing.length} required recipe variables have no answer.`,details:missing.map(entry=>entry.variable.key),fix:"Answer them now",hint:"Answer each with 'sous vars ask', or pass --answer <name>=<value> to sous doctor."}},async fix(ctx,run){let answers=variableAnswers(ctx,run.answers);return await ctx.run("vars.ask",{...answers.length===0?{}:{answer:answers},...run.yes?{yes:!0}:{}}),{summary:"The variables were asked."}}};outputsCheck={id:"outputs",order:DOCTOR_CHECK_ORDER.outputs,description:"The files sous wrote are present and unchanged",check(ctx,run){if(run.configFailed)return CONFIG_FAILED;if(ctx.project===void 0)return NO_PROJECT;if(!has2(ctx,"compiler.state"))return{status:"skipped",summary:"Skipped: the compiler is not loaded."};let missing=[],changed2=[];for(let entry of ctx.services.get("compiler.state").entries()){if(!fs53.existsSync(entry.dest)){missing.push(entry.dest);continue}try{hashOf2(entry.dest)!==entry.destHash&&changed2.push(entry.dest)}catch{changed2.push(entry.dest)}}if(missing.length===0&&changed2.length===0)return{status:"ok"};let count2=missing.length+changed2.length;return{status:"problem",summary:`${count2===1?"1 file":`${count2} files`} sous wrote ${count2===1?"is":"are"} missing or no longer what sous wrote.`,details:[...missing.map(file2=>`${file2} is missing`),...changed2.map(file2=>`${file2} has changed since sous wrote it`)],fix:"Build the project, which writes them again"}},async fix(ctx){return await ctx.run("build",{}),{summary:"The project was built."}}},BUILT_IN_CHECKS=[configCheck,lockfileCheck,variablesCheck,outputsCheck]}});var package_default16,init_package6=__esm({"../sous-plugin-doctor/package.json"(){package_default16={name:"@sous-io/sous-plugin-doctor",version:"1.1.6",description:"sous doctor: runs every check a plugin adds, reports what it found, and offers to fix what it can.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*","@sous-io/sous-plugin-build":"workspace:*","@sous-io/sous-plugin-compiler":"workspace:*","@sous-io/sous-plugin-formats":"workspace:*","@sous-io/sous-plugin-recipe-answers":"workspace:*","@sous-io/sous-plugin-recipes":"workspace:*"},engines:{node:">=22"}}}});var doctor_exports={};__export(doctor_exports,{default:()=>doctor_default,doctorOutputs:()=>doctorOutputs,handle:()=>handle,orderChecks:()=>orderChecks});import{IntentOutput as IntentOutput11,IntentOutputs as IntentOutputs12,ReportEntryStyle as ReportEntryStyle6,TextBlock as TextBlock7,Tree as Tree2}from"@sous-io/sous-plugin-api";function orderChecks(checks){return checks.map((check3,index)=>({check:check3,index})).sort((left,right)=>(left.check.order??500)-(right.check.order??500)||left.index-right.index).map(entry=>entry.check)}async function look(check3,ctx,run){try{return await check3.check(ctx,run)}catch(error51){return{status:"problem",summary:`The check could not run: ${messageOf7(error51)}`}}}function messageOf7(error51){return error51 instanceof Error?error51.message:String(error51)}function detailLines(details){return details.flatMap(detail=>typeof detail=="string"?[detail]:[detail.text,...detail.details.map(line=>` ${line}`)])}function detailNodes(details){return details.map(detail=>typeof detail=="string"?{label:detail}:{label:detail.text,children:detail.details.map(line=>({label:line}))})}function needsFix(found){return found.status==="problem"||found.status==="warning"||found.status==="pending"}async function mayFix(check3,found,ctx,run){return check3.confirm===!1||run.yes?"yes":ctx.prompter.interactive?(ctx.reporter.problem(found.summary,found.details===void 0||found.details.length===0?{}:{cause:detailLines(found.details).join(`
466
+ `)}),await ctx.prompter.confirm({message:`${found.fix}?`,default:!0,answeredBy:YES_FLAG})?"yes":"declined"):"cannot-ask"}async function examine(check3,ctx,run){let found=await look(check3,ctx,run),base={id:check3.id,description:check3.description,found};if(!needsFix(found)||found.fix===void 0||check3.fix===void 0)return{...base,problem:found.status==="problem"};if(run.dryRun)return{...base,fix:{result:"dry-run"},problem:found.status==="problem"};let decision=await mayFix(check3,found,ctx,run);if(decision!=="yes")return{...base,fix:{result:decision},problem:found.status==="problem"};try{let fixed=await check3.fix(ctx,run),after=await look(check3,ctx,run);return{...base,fix:{result:"applied",summary:fixed.summary,...fixed.details===void 0?{}:{details:fixed.details}},after,problem:after.status==="problem"}}catch(error51){return{...base,fix:{result:"failed",error:messageOf7(error51)},problem:found.status==="problem"}}}async function configLoadsNow(ctx){try{await ctx.refreshConfig()}catch{}return ctx.engine.configError===void 0}async function recheckAfterConfigLoads(reports,checks,resolvedBy,ctx,run){let updated=[];for(let report of reports){let check3=checks.find(entry=>entry.id===report.id);if(check3===void 0||!report.problem&&report.found.status!=="skipped")updated.push(report);else if(report.fix===void 0&&report.found.status==="problem"){let after=await look(check3,ctx,run);updated.push({...report,after,problem:after.status==="problem",...after.status==="ok"?{resolvedBy}:{}})}else report.found.status==="skipped"?updated.push(await examine(check3,ctx,run)):updated.push(report)}return updated}async function handle(input,ctx){let run={dryRun:input.dryRun===!0,yes:input.yes===!0,answers:input.answer??[],configFailed:ctx.engine.configError!==void 0},only=input.only===void 0||input.only.length===0?void 0:new Set(input.only),checks=orderChecks(ctx.entities.list("doctor-check")).filter(check3=>only===void 0||only.has(check3.id)),reports=[];for(let check3 of checks){let report=await examine(check3,ctx,run);reports.push(report),run.configFailed&&report.fix?.result==="applied"&&await configLoadsNow(ctx)&&(run={...run,configFailed:!1},reports=[...await recheckAfterConfigLoads(reports.slice(0,-1),checks,report.description,ctx,run),report])}let result={checks:reports,problems:reports.filter(report=>report.problem).length,pending:waitingOf(reports).count,dryRun:run.dryRun};return doctorOutputs(result)}function statusOf(found){switch(found.status){case"ok":return"ok";case"skipped":return"skipped";case"pending":return"waiting for an answer";default:return found.status}}function nodeOf(report){let final=report.after??report.found,children=[];for(let note of report.found.status==="skipped"?[]:report.found.notes??[])children.push({label:note});switch(report.found.status!=="ok"&&children.push({label:report.found.summary??"",children:detailNodes(("details"in report.found?report.found.details:void 0)??[])}),report.fix?.result){case"applied":children.push({label:`Fixed: ${report.fix.summary}`,children:(report.fix.details??[]).map(line=>({label:line}))}),report.after!==void 0&&report.after.status!=="ok"&&children.push({label:`Still found: ${report.after.summary??""}`});break;case"failed":children.push({label:`The fix failed: ${report.fix.error}`});break;case"declined":children.push({label:"Not fixed: the fix was declined."});break;case"cannot-ask":children.push({label:`Not fixed: sous could not ask without a terminal. Pass ${YES_FLAG} to apply the fix.`});break;case"dry-run":children.push({label:`Would fix: ${"fix"in report.found?report.found.fix??"":""}`});break;default:break}report.resolvedBy!==void 0&&children.push({label:`Fixed by: ${report.resolvedBy}`});let hint="hint"in final?final.hint:void 0;hint!==void 0&&final.status!=="ok"&&children.push({label:hint});let fixed=(report.fix?.result==="applied"||report.resolvedBy!==void 0)&&final.status==="ok";return{label:report.description,detail:fixed?"fixed":statusOf(final),children}}function waitingOf(reports){let count2=0,labels=[];for(let report of reports){let final=report.after??report.found;if(final.status!=="pending")continue;let waiting=final.waiting??{count:1,label:"1 check"};count2+=waiting.count,labels.push(waiting.label)}return{count:count2,labels}}function closingOf(result){let{labels}=waitingOf(result.checks),waiting=labels.length===0?void 0:`${labels.join(" and ")} ${labels.length===1&&result.pending===1?"is":"are"} waiting for an answer`,dryRun4=result.dryRun?" Nothing was changed (--dry-run).":"";return result.problems===0?waiting!==void 0?`Nothing failed, but ${waiting}.${dryRun4}`:result.dryRun?"No problem was found. Nothing was changed (--dry-run).":"No problem remains.":`${result.problems===1?"1 problem remains":`${result.problems} problems remain`}${waiting===void 0?"":`, and ${waiting}`}.${dryRun4}`}function doctorOutputs(result){let closing=closingOf(result),outputs=new IntentOutputs12([new IntentOutput11({title:"Checks",result:new Tree2(result.checks.map(nodeOf)),style:ReportEntryStyle6.Tree}),new IntentOutput11({result:new TextBlock7(closing),style:result.dryRun?ReportEntryStyle6.DryRun:ReportEntryStyle6.Plain})]).withData(result);return result.problems>0?outputs.withExitCode(1):outputs}var YES_FLAG,doctor_default,init_doctor=__esm({"../sous-plugin-doctor/src/doctor.ts"(){"use strict";YES_FLAG="--yes (also -y)";doctor_default=handle}});import{definePlugin as definePlugin16,jsonSchema as jsonSchema21}from"@sous-io/sous-plugin-api";var PLUGIN_NAME15,doctorCheckSchema,doctorInput,doctorPlugin,init_src7=__esm({"../sous-plugin-doctor/src/index.ts"(){"use strict";init_checks3();init_types();init_package6();init_checks3();init_types();PLUGIN_NAME15="@sous-io/sous-plugin-doctor",doctorCheckSchema=jsonSchema21({type:"object",required:["id","order","description"],properties:{id:{type:"string",description:"Names the check in the report and in --json."},order:{type:"number",description:"Lower runs first; the built-in checks use 100 to 800."},description:{type:"string",description:"One sentence saying what is checked, stated as the healthy state."},confirm:{type:"boolean",description:"Whether sous doctor asks before running the fix. Default: true."}}}),doctorInput=jsonSchema21({type:"object",properties:{dryRun:{type:"boolean",default:!1,description:"Report what every check finds and change nothing."},yes:{type:"boolean",default:!1,description:"Apply every fix without asking, and take the default answer to every migration's question."},answer:{type:"array",items:{type:"string"},description:"Answer a question ahead of time, as <name>=<value>: a migration's question or a recipe variable."},only:{type:"array",items:{type:"string"},description:"Run only this check, by id."}},additionalProperties:!1}),doctorPlugin=definePlugin16({name:PLUGIN_NAME15,version:package_default16.version,description:"sous doctor: runs every check, reports what it found, and offers to fix what it can.",register(sous){sous.entities.define("doctor-check",doctorCheckSchema,{description:"A check sous doctor runs: what it looks at, and how to fix what it finds."});for(let check3 of BUILT_IN_CHECKS)sous.entities.add("doctor-check",check3);sous.intents.add({intent:"doctor",summary:"Check this project's health, run pending migrations, and offer to fix each problem found",input:doctorInput,toleratesConfigErrors:!0,needsRecipeFiles:!0,cli:{examples:["sous doctor","sous doctor --dry-run","sous doctor --yes","sous doctor --only outputs","sous doctor --answer memories.location=keep"],flags:{yes:{short:"y",aliases:["force"]}}},agent:{usage:"Run with dryRun first to see every problem; pass yes (and answer for a question whose default is not wanted) to fix them without prompts."},load:()=>Promise.resolve().then(()=>(init_doctor(),doctor_exports))})}})}});import{BufferedReporter as BufferedReporter3}from"@sous-io/sous-plugin-api";async function checkHandlers(ctx,run){if(run.configFailed)return{status:"skipped",summary:"The config did not load, so the check handlers it declares could not run."};let quiet=Object.create(ctx,{reporter:{value:new BufferedReporter3}}),result=await runHandlers(quiet,"check");if(result.ran.length===0)return{status:"ok",summary:"No recipe or plugin declares a check handler."};let lines3=level=>result.ran.flatMap(one=>one.reports.filter(report=>report.level===level).map(report=>reportLine(one.label,report.message))),ran=`${result.ran.length} check ${result.ran.length===1?"handler":"handlers"} ran`;return result.errors>0?{status:"problem",summary:`${ran}, and ${result.errors===1?"one reported an error":`they reported ${result.errors} errors`}, which would stop a build.`,details:[...lines3("error"),...lines3("warn")],hint:"Put right what each one reports; 'sous build --ignore-failed-checks' builds anyway."}:result.warnings>0?{status:"warning",summary:`${ran}, with ${result.warnings===1?"a warning":`${result.warnings} warnings`}.`,details:lines3("warn")}:{status:"ok",summary:`${ran}, and found nothing wrong.`}}var checkHandlersCheck,init_doctor_check=__esm({"../sous-plugin-handlers/src/doctor-check.ts"(){"use strict";init_src7();init_run();checkHandlersCheck={id:"check-handlers",order:DOCTOR_CHECK_ORDER.checkHandlers,description:"The check handlers of the recipes and plugins report no errors",check:(ctx,run)=>checkHandlers(ctx,run)}}});function recordMoves(pending,updated){for(let change of updated){if(change.holder!==void 0||change.from===void 0||change.to===void 0||change.from===change.to)continue;let from=pending.get(change.key)?.from??change.from;from===change.to?pending.delete(change.key):pending.set(change.key,{from,to:change.to})}}function registerLifecycle(sous){let pending=new Map,removing=new Map,subscribing=new Map;sous.on("recipes.locked",async(event,ctx)=>{let{diff}=event.payload;recordMoves(pending,diff.updated);let chain=ctx.chain?.id;if(chain===void 0)return;for(let change of[...diff.added,...diff.updated])change.holder===void 0&&subscribing.get(chain)?.add(change.key);let done2=removing.get(chain);if(done2!==void 0){let keys=diff.removed.filter(change=>change.holder===void 0&&!done2.has(change.key)).map(change=>change.key);keys.length>0&&(keys.forEach(key=>done2.add(key)),await ctx.run("handlers.uninstall",{recipes:keys}))}}),sous.on("config.built",async(_event,ctx)=>{pending.size!==0&&await runPendingMigrations(pending,ctx)}),sous.on("subscription.remove.before",(event,ctx)=>{event.input.dryRun!==!0&&ctx.chain!==void 0&&removing.set(ctx.chain.id,new Set)}),sous.on(/^subscription\.remove\.(after|error)$/,(_event,ctx)=>{ctx.chain!==void 0&&removing.delete(ctx.chain.id)}),sous.on("subscription.add.before",(event,ctx)=>{event.input.dryRun!==!0&&event.input.noBuild===!0&&ctx.chain!==void 0&&subscribing.set(ctx.chain.id,new Set)}),sous.on("subscription.add.error",(_event,ctx)=>{ctx.chain!==void 0&&subscribing.delete(ctx.chain.id)}),sous.on("subscription.add.after",async(_event,ctx)=>{let chain=ctx.chain?.id,keys=chain===void 0?void 0:subscribing.get(chain);chain===void 0||keys===void 0||(subscribing.delete(chain),keys.size>0&&await ctx.run("handlers.check",{recipes:[...keys]}))})}async function runPendingMigrations(pending,ctx){let active=ctx.entities.kinds().includes("active-recipe")?ctx.entities.list("active-recipe"):[];for(let recipe of active){let waiting=pending.get(recipe.id);waiting===void 0||recipe.version!==waiting.to||(pending.delete(recipe.id),await ctx.run("handlers.migrate",{recipe:recipe.id,from:waiting.from,to:waiting.to}))}}var init_lifecycle=__esm({"../sous-plugin-handlers/src/lifecycle.ts"(){"use strict"}});function versionIn(text){return VERSION_PATTERN.exec(text)?.[0]}function createHandlersSystem(processes,env){let found=new Map,versions=new Map,locate3=name=>{let answer2=found.get(name);return answer2===void 0&&(answer2=processes().which(name,env),found.set(name,answer2)),answer2};return{async isAppAvailable(name){return await locate3(name)!==void 0},appVersion(name){let answer2=versions.get(name);return answer2===void 0&&(answer2=(async()=>{let file2=await locate3(name);if(file2===void 0)return;let shim=/\.(cmd|bat)$/i.test(file2),result=await processes().run(shim?name:file2,["--version"],{env,timeoutMs:5e3,label:`${name} --version`,...shim?{windowsShell:!0}:{}});if(!result.timedOut)return versionIn(result.stdout)??versionIn(result.stderr)})(),versions.set(name,answer2)),answer2}}}var VERSION_PATTERN,init_system=__esm({"../sous-plugin-handlers/src/system.ts"(){"use strict";VERSION_PATTERN=/\d+\.\d+(?:\.\d+)?(?:-[0-9A-Za-z.-]+)?/}});var package_default17,init_package7=__esm({"../sous-plugin-handlers/package.json"(){package_default17={name:"@sous-io/sous-plugin-handlers",version:"1.1.6",description:"Handlers: functions a recipe or plugin provides for a purpose (check, configure, beforeBuild, afterBuild, uninstall, migrate), the helpers they receive, and the intents that run them.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-doctor":"workspace:*","@sous-io/sous-plugin-formats":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@sous-io/sous-plugin-recipe-answers":"workspace:*","@sous-io/sous-plugin-recipes":"workspace:*","@sous-io/sous-plugin-variables":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}}}});import{definePlugin as definePlugin17,HANDLER_PURPOSES as HANDLER_PURPOSES2,jsonSchema as jsonSchema22}from"@sous-io/sous-plugin-api";function handlersIntent(purpose){return`handlers.${purpose}`}async function runHandlerPurpose(ctx,purpose,input={}){return(await ctx.run(handlersIntent(purpose),input)).toPlain()}var PLUGIN_NAME16,handlerSchema,recipeHandlersKeySchema,intentInputSchema,migrateInputSchema,SUMMARIES,handlersPlugin,init_src8=__esm({"../sous-plugin-handlers/src/index.ts"(){"use strict";init_configure();init_doctor_check();init_lifecycle();init_recipes();init_run();init_system();init_package7();init_run();init_system();init_recipes();init_lifecycle();init_configure();init_doctor_check();PLUGIN_NAME16="@sous-io/sous-plugin-handlers",handlerSchema=(()=>{let standard=jsonSchema22({type:"object",required:["id","purpose"],properties:{id:{type:"string",description:"Names the handler in timings and reports."},purpose:{enum:[...HANDLER_PURPOSES2],description:"What it is for."},order:{type:"number",description:"Lower runs earlier within the purpose. Default 500."},recipe:{type:"string",description:"The recipe that lists it, for a handler from a manifest."},plugin:{type:"string",description:"The plugin that added it, for a handler from a plugin."},source:{type:"string",description:"Where it came from: the file and export."}}})["~standard"];return{"~standard":{...standard,validate(value){let result=standard.validate(value);return result.issues===void 0&&typeof value?.handle!="function"?{issues:[{path:["handle"],message:"Expected a function."}]}:result}}}})(),recipeHandlersKeySchema=jsonSchema22({type:"array",items:{type:"object",required:["recipe","purpose","file","handler"],properties:{recipe:{type:"string"},purpose:{enum:[...HANDLER_PURPOSES2]},file:{type:"string"},handler:{type:"string"}}}});intentInputSchema=jsonSchema22({type:"object",properties:{recipes:{type:"array",items:{type:"string"},description:"Only the handlers of these recipes"},ignoreFailedChecks:{type:"boolean",description:"Report errors from checks as warnings"}}}),migrateInputSchema=jsonSchema22({type:"object",required:["recipe","from","to"],properties:{recipe:{type:"string",description:"The recipe that moved: namespace/recipe"},from:{type:"string",description:"The version it moved from"},to:{type:"string",description:"The version it moved to"}}}),SUMMARIES={check:"Run the check handlers: prerequisites such as installed commands",beforeBuild:"Run the handlers that run before a build",afterBuild:"Run the handlers that run after a build",uninstall:"Run the uninstall handlers of recipes being removed",migrate:"Run a recipe's migrate handlers after it moved to a new version"},handlersPlugin=definePlugin17({name:PLUGIN_NAME16,version:package_default17.version,description:"Handlers: functions a recipe or plugin provides for a purpose, the helpers they receive, and the intents that run them.",dependsOn:{"@sous-io/sous-plugin-host":`^${package_default17.version}`,"@sous-io/sous-plugin-recipes":`^${package_default17.version}`,"@sous-io/sous-plugin-doctor":`^${package_default17.version}`},register(sous){sous.entities.define("handler",handlerSchema,{description:"A function a recipe or plugin provides for a purpose: check, configure, beforeBuild, afterBuild, uninstall or migrate."}),sous.entities.add("config-key",{id:RECIPE_HANDLERS_KEY,schema:recipeHandlersKeySchema,description:"The handlers the active recipes' manifests list, one entry each."}),sous.services.add("handlers.system",(_config,ctx)=>createHandlersSystem(()=>ctx.services.get("host.processes"),ctx.env),{lifetime:"singleton"}),sous.config.contribute(recipeDeclarationsContributor()),sous.config.contribute(recipeHandlersContributor()),sous.config.contribute(configureContributor(()=>sous.services));for(let purpose of["check","beforeBuild","afterBuild","uninstall"])sous.intents.add({intent:handlersIntent(purpose),summary:SUMMARIES[purpose],input:intentInputSchema,requiresProject:!0,internal:!0,handle:async(given,ctx)=>{let input=given;return handlerOutputs(await runHandlers(ctx,purpose,{...input.recipes===void 0?{}:{recipes:input.recipes},...purpose==="check"&&input.ignoreFailedChecks===!0?{ignoreFailedChecks:!0}:{}}))}});sous.intents.add({intent:"handlers.migrate",summary:SUMMARIES.migrate,input:migrateInputSchema,requiresProject:!0,internal:!0,handle:async(input,ctx)=>handlerOutputs(await runHandlers(ctx,"migrate",{recipes:[input.recipe],input:{from:input.from,to:input.to}}))}),registerLifecycle(sous),sous.entities.add("doctor-check",checkHandlersCheck)}})}});import fs54 from"node:fs";import path70 from"node:path";function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(error51){return error51.code==="EPERM"}}function projectLabel(project,pidFile){if(project)return path70.basename(project.root);let dir=path70.dirname(pidFile);return path70.basename(dir)===".sous"&&(dir=path70.dirname(dir)),path70.basename(dir)}var PID_FILE_NAME,PidFile,init_pid=__esm({"../sous-plugin-build/src/pid.ts"(){"use strict";PID_FILE_NAME="sous.pid";PidFile=class{file;isAlive;constructor(options2){this.file=options2.explicitPath??(options2.project?path70.join(options2.project.sousDir,PID_FILE_NAME):path70.join(options2.cwd,PID_FILE_NAME)),this.isAlive=options2.isAlive??isProcessAlive}path(){return this.file}read(){let raw2;try{raw2=fs54.readFileSync(this.file,"utf8")}catch{return}let pid=Number.parseInt(raw2.trim(),10);return Number.isNaN(pid)?void 0:pid}write(pid=process.pid){fs54.mkdirSync(path70.dirname(this.file),{recursive:!0}),fs54.writeFileSync(this.file,String(pid),"utf8")}remove(){fs54.rmSync(this.file,{force:!0})}isRunning(){let pid=this.read();return pid!==void 0&&this.isAlive(pid)}}}});import{jsonSchema as jsonSchema23}from"@sous-io/sous-plugin-api";var DEFAULT_DEBOUNCE_MS,DEFAULT_BRANCH_PATTERN,watchSettingsSchema,runtimeContextSchema,boolean4,buildInputSchema,compileInputSchema,prepareInputSchema,pruneInputSchema,clearInputSchema,watchInputSchema,init_schemas4=__esm({"../sous-plugin-build/src/schemas.ts"(){"use strict";DEFAULT_DEBOUNCE_MS=200,DEFAULT_BRANCH_PATTERN="PT-",watchSettingsSchema=jsonSchema23({type:"object",properties:{pollSeconds:{type:"integer",description:"How often watch mode checks upstream for newer recipes, in seconds; 0 never. Default: store.watchPollSeconds."},paths:{type:"array",items:{type:"string"},default:[],description:"More files, directories or globs whose change triggers a full rebuild."},debounceMs:{type:"integer",default:DEFAULT_DEBOUNCE_MS,description:"How long to wait for more changes before building, in milliseconds."}},additionalProperties:!1}),runtimeContextSchema=jsonSchema23({type:"object",properties:{gitRoot:{type:"string",description:"The git repository branch detection reads (${var} allowed)."},outputPath:{type:"string",description:"Where the runtime context file is written."},taskFileRoot:{type:"string",description:"The directory task files live in."},branchPattern:{type:"string",description:"A regular expression; only matching branches look for a task file."}},required:["gitRoot","outputPath","taskFileRoot"],additionalProperties:!1}),boolean4=description=>({type:"boolean",description}),buildInputSchema=jsonSchema23({type:"object",properties:{noPrune:boolean4("Skip the prune step"),noCompile:boolean4("Skip the compile step (prune only)"),rebuild:boolean4("Ignore cached hashes and reprocess all outputs"),dryRun:boolean4("Print what would be written/pruned without making changes"),reportRemoved:boolean4("Report each removed file as progress. Default: true"),strict:boolean4("Treat compile warnings as errors"),watch:boolean4("Watch source files and rebuild on changes"),changedFiles:{type:"array",items:{type:"string"},description:"Only rebuild the targets that include one of these files, preparing nothing"},ignoreFailedAssertions:boolean4("Print a failed assertion as a warning and end the build as successful"),ignoreFailedChecks:boolean4("Print an error from a check handler as a warning and build anyway"),keepGoing:boolean4("Ignore failed assertions and failed checks: the same as passing both flags above")},additionalProperties:!1}),compileInputSchema=jsonSchema23({type:"object",properties:{strict:boolean4("Treat compile warnings as errors"),rebuild:boolean4("Ignore cached hashes and reprocess all outputs"),dryRun:boolean4("Print what would be written without making changes"),watch:boolean4("Watch source files and recompile on changes"),changedFiles:{type:"array",items:{type:"string"},description:"Only recompile the targets that include one of these files"}},additionalProperties:!1}),prepareInputSchema=jsonSchema23({type:"object",properties:{dryRun:boolean4("Show what preparing would change, writing nothing"),offline:boolean4("Never go upstream")},additionalProperties:!1}),pruneInputSchema=jsonSchema23({type:"object",properties:{dryRun:boolean4("Print what would be pruned without deleting")},additionalProperties:!1}),clearInputSchema=jsonSchema23({type:"object",properties:{force:boolean4("Delete without asking"),dryRun:boolean4("Print what would be deleted without deleting")},additionalProperties:!1}),watchInputSchema=jsonSchema23({type:"object",properties:{compileOnly:boolean4("Submit compile chains instead of build chains"),strict:boolean4("Treat compile warnings as errors"),pollSeconds:{type:"integer",description:"How often to check upstream for newer recipes, in seconds; 0 never"},rebuild:boolean4("Reprocess all outputs on every change"),noPrune:boolean4("Skip the prune step on every build"),dryRun:boolean4("Write nothing on any build"),ignoreFailedAssertions:boolean4("Print failed assertions as warnings on every build"),ignoreFailedChecks:boolean4("Print errors from check handlers as warnings on every build")},additionalProperties:!1})}});import{LogLevel as LogLevel12}from"@sous-io/sous-plugin-api";function reportUnincludedMemories(missing,reporter){if(missing.length===0)return;let one=missing.length===1;reporter.list(missing.map(memory=>`${memory.recipe}: memories/${memory.name}`),{title:`${missing.length} ${one?"memory":"memories"} published by your subscribed recipes ${one?"is":"are"} not included in any output, so no agent will read ${one?"it":"them"}:`,footer:`To include every memory, add the line "@#memories/**/*.md" to your project's instruction source (the file your AGENTS.md or CLAUDE.md is built from). To leave a recipe's memories out on purpose, list the recipe in "recipes.memories.exclude" in your sous config.`},LogLevel12.Warning)}function reportLinkedRepos(links,reporter,level){let names2=Object.keys(links).sort();if(names2.length===0)return;let lead=names2.length===1?"One repository is LINKED to a working copy on this machine. Its recipes are read from that checkout, so versions, the lockfile and freshness checks do not apply to it.":`${names2.length} repositories are LINKED to working copies on this machine. Their recipes are read from those checkouts, so versions, the lockfile and freshness checks do not apply to them.`;reporter.list(names2.map(name=>`${name} -> ${links[name].path}`),{title:lead,footer:"Run 'sous repo unlink <name>' to go back to the published versions."},level)}function reportRetired(retired,reporter,asking2){for(let recipe of retired??[]){let usedBy=recipe.subscription!==void 0?[`this project's subscription to '${recipe.subscription}'`]:[],dependents=recipe.requestedBy.filter(holder=>holder!=="project");dependents.length>0&&usedBy.push(`${dependents.length===1?"the recipe":"the recipes"} ${dependents.join(", ")}, which ${dependents.length===1?"depends":"depend"} on it`);let items2=[`Pinned version: ${recipe.version}`,...usedBy.length===0?[]:[`Used by: ${usedBy.join("; ")}`],...recipe.replacements.map(replacement=>replacement.repo===void 0?`Replacement: ${replacement.ref}, in a repository this project has not added`:`Replacement: ${replacement.ref}`)];reporter.list(items2,{title:`The repository '${recipe.repo}' retired '${recipe.key}'. This project still builds it at the pinned version, and it gets no more updates:`,...asking2&&offered(recipe)?{}:retiredFooter(recipe)},LogLevel12.Warning)}}function offered(recipe){return recipe.subscription!==void 0&&recipe.replacements.length>0}function retiredFooter(recipe){return recipe.subscription===void 0?{}:recipe.replacements.length===0?{footer:`To stop using it, run 'sous subscription remove ${recipe.subscription}'.`}:recipe.replacements.some(replacement=>replacement.key===recipe.key)?{footer:"To swap it, run 'sous subscribe' with the replacement you want."}:{footer:`To swap it, run 'sous subscription remove ${recipe.subscription}', then 'sous subscribe' with each replacement you want.`}}function alone(change){return change.holder===void 0?"":` for ${change.holder} alone`}function whyMoved(change,followsSous){let follows=change.holder===void 0?followsSous?.find(entry=>entry.key===change.key&&entry.version===change.to):void 0;return follows===void 0?"":`, because the subscription to '${follows.subscription}' follows the installed sous, version ${follows.version}`}function reportLocked(diff,reporter,followsSous){diff.unchanged||diff.added.length===0&&diff.updated.length===0||reporter.list([...diff.added.map(change=>`pinned: ${change.key} at version ${change.to??"?"}${alone(change)}.`),...diff.updated.map(change=>`${change.key} moved from version ${change.from??"?"} to version ${change.to??"?"}${alone(change)}${whyMoved(change,followsSous)}.`)],{title:"Locking subscribed recipes",footer:"The lockfile has been updated. Commit it, so everyone building this project gets exactly these versions."},LogLevel12.Notice)}function reportRestored(report,reporter){report.restored.length!==0&&(reporter.stepStart("Restoring recipes",LogLevel12.Notice),reporter.note("This project's lockfile pins recipes that were not in the store on this machine, so they were fetched at exactly the versions it records."),reporter.list(report.restored.map(key=>`restored: ${key}`),{},LogLevel12.Notice))}function reportRestoreFailures(report,reporter){for(let failure of report.failed)reporter.problem(`Sous could not restore '${failure.key}' at the version the lockfile pins, so nothing from it was compiled.`,{subject:failure.key,cause:failure.reason})}function reportNewer(newer,reporter){newer.length!==0&&(reporter.variables(newer.map(entry=>({label:entry.key,value:entry.to,detail:`this project pins ${entry.from}${alone(entry)}${entry.staleIndex===!0?"; seen in the copy of the index sous already had, which may be out of date":""}`})),"Newer versions published",LogLevel12.Notice),reporter.note(newer.length===1?"This version is within the range declared for the recipe. No pin was changed, so this build uses the pinned version.":"Each version is within the range declared for its recipe. No pin was changed, so this build uses the pinned versions."))}function skippedLine(skipped){let where3=skipped.setBy?` (${skipped.setBy})`:"";switch(skipped.reason){case"subscription-disabled":return skipped.indirect===!0&&skipped.subscription!==void 0?`Skipped ${skipped.key}: reached only through ${skipped.subscription}, which is switched off${where3}.`:`Skipped ${skipped.key}: its subscription is switched off${where3}.`;case"repository-disabled":return`Skipped ${skipped.key}: its repository is switched off${where3}.`;default:return skipped.message.startsWith("Skipped ")?skipped.message:`Skipped ${skipped.key}: ${lowerFirst(skipped.message.replace(/\.$/u,""))}.`}}function prunedForSkippedLine(count2,dryRun4){let outputs=count2===1?"output":"outputs";return dryRun4?`Would prune ${count2} ${outputs} it had written.`:`Pruned ${count2} ${outputs} it had written.`}function unansweredWarning2(unanswered){if(unanswered.length===0)return;let count2=unanswered.length,pronoun=count2===1?"it":"them";return{title:`${count2} required recipe ${count2===1?"variable":"variables"} ${count2===1?"has":"have"} no answer, so the templates that use ${pronoun} render an empty value:`,items:unanswered.map(defined=>`${defined.definition.name} (asked by ${defined.recipe.namespace}/${defined.recipe.name})`),footer:`Run 'sous vars ask' to answer ${pronoun}.`}}function reportUnanswered(unanswered,reporter){let warning=unansweredWarning2(unanswered);warning!==void 0&&reporter.list(warning.items,{title:warning.title,footer:warning.footer},LogLevel12.Warning)}function reportUnanswerable(unanswerable,reporter){for(let warning of new Set(unanswerable.map(defined=>defined.unanswerable??"")))warning!==""&&reporter.warning(warning)}function reportPrepared(result,reporter){reportLocked(result.locked,reporter,result.followsSous),reportRestored(result.restored,reporter),reportRestoreFailures(result.restored,reporter),reportNewer(result.newer,reporter),reportUnanswered(result.unanswered,reporter),reportUnanswerable(result.unanswerable,reporter)}function lowerFirst(text){return text.length===0?text:text[0].toLowerCase()+text.slice(1)}function filesSummaryLine(input){let count2=(...actions)=>input.outputs.filter(output=>actions.includes(output.action)).length,created=count2("created","would-create"),updated=count2("updated","would-update"),written=created+updated,breakdown=[created>0?`${created} new`:"",updated>0?`${updated} updated`:""].filter(part=>part!=="").join(", "),writtenFiles=new Set(input.outputs.filter(output=>output.action!=="skipped-untracked").map(output=>output.file)),removed=new Set((input.removed??[]).filter(file2=>!writtenFiles.has(file2))).size,notWritten=new Set(input.notWritten??[]).size;return`Files: ${[`${written} ${input.dryRun?"would be written":"written"}${breakdown===""?"":` (${breakdown})`}`,`${count2("unchanged")} unchanged`,...removed>0?[`${removed} ${input.dryRun?"would be removed":"removed"}`]:[],...notWritten>0?[`${notWritten} not written`]:[]].join(", ")}.`}var init_report=__esm({"../sous-plugin-build/src/report.ts"(){"use strict"}});var prepare_exports={};__export(prepare_exports,{NOTHING_RESTORED:()=>NOTHING_RESTORED,NO_CHANGE:()=>NO_CHANGE,builtInPins:()=>builtInPins,isLocked:()=>isLocked,mergeDiffs:()=>mergeDiffs,prepare:()=>prepare,switchedOn:()=>switchedOn});import{IntentOutputs as IntentOutputs13}from"@sous-io/sous-plugin-api";async function prepare(input,ctx){return IntentOutputs13.of(await prepareProject(input,ctx))}async function prepareProject(input,ctx){let dryRun4=input.dryRun===!0,lock=ctx.services.get("recipes.lock"),resolver=ctx.services.get("recipes.resolver"),active=ctx.services.get("recipes.active"),subscriptions=switchedOn(ctx.config.get("subscriptions")??{}),seeded=active.list().filter(recipe=>recipe.source==="core").map(recipe=>recipe.id),current=lock.read(),locked=NO_CHANGE,unlocked=Object.entries(subscriptions).filter(([key,entry])=>!isLocked(key,entry,current));if(unlocked.length>0)try{let resolved=await resolver.resolveSubscriptions({...lock.held(current),...dryRun4?{}:{download:!0}});if(warnAboutProblems(resolved,ctx),resolved.unreadable.length===0){let next=lock.fromResolved(resolved.resolved,current);locked=await lock.write(next,{dryRun:dryRun4}),current=next}else ctx.reporter.problem(unreadableNotWritten(resolved.unreadable))}catch(error51){let keys=unlocked.map(([key])=>`'${key}'`).join(", ");ctx.reporter.problem(`Sous could not work out which version of ${keys} to use, so nothing from it was compiled.`,{cause:describe4(error51)})}let restored=NOTHING_RESTORED;if(!dryRun4&&Object.keys(current.recipes).length>0)try{restored=await lock.restore()}catch(error51){ctx.reporter.problem("Sous could not restore the recipes this project's lockfile pins.",{cause:describe4(error51)})}let checkedUpstream=!1,newer=[];if(!dryRun4&&input.offline!==!0&&Object.keys(current.recipes).length>0){let upstream=await checkUpstream(ctx,current,subscriptions);if(checkedUpstream=upstream.checked,newer.push(...upstream.newer),upstream.moved.length>0){let movedKeys=new Set(upstream.moved.map(change=>change.key));try{let resolved=await resolver.resolveSubscriptions({...lock.held(current,movedKeys),download:!0});if(resolved.unreadable.length>0)throw new Error(unreadableNotWritten(resolved.unreadable));let next=lock.fromResolved(resolved.resolved,current);locked=mergeDiffs(locked,await lock.write(next)),current=next,restored=mergeRestores(restored,await lock.restore({keys:[...movedKeys]}))}catch(error51){ctx.reporter.problem("Sous could not move to the newer recipe versions, so this build uses the versions it already had.",{cause:describe4(error51)})}}}let hashed=lock.withIndexHashes(current);hashed!==current&&!dryRun4&&await lock.write(hashed),!locked.unchanged&&!dryRun4&&ctx.configChanged();let skipped=active.skipped(),{unanswered,unanswerable}=ctx.services.get("recipe-answers.answers").get(),followsSous=builtInPins(subscriptions,current),notBuilt=new Set(skipped.map(recipe=>recipe.key)),retired=lock.retired(current).filter(recipe=>!notBuilt.has(recipe.key)),result={seeded,locked,restored,newer,checkedUpstream,skipped,unanswered,unanswerable,...followsSous.length===0?{}:{followsSous},...retired.length===0?{}:{retired}};return await ctx.emit("build.prepared",result),result}async function checkUpstream(ctx,current,subscriptions){let report={checked:!1,moved:[],newer:[]},indexes;try{indexes=await ctx.services.get("recipes.index-cache").getAll()}catch(error51){return ctx.reporter.problem("Sous could not check upstream for newer recipe versions, so this build uses the versions it already had.",{cause:describe4(error51)}),report}report.checked=indexes.indexes.some(index=>index.source==="network");let stale=new Set;for(let index of indexes.indexes)index.source==="stale"&&(stale.add(index.repo),ctx.services.get("recipes.index-cache").firstStaleNotice(index.repo)&&ctx.reporter.problem(`Sous could not check the repository '${index.repo}' for a newer version, so this build uses the copy of its index that it already had.`,{subject:index.repo,...index.problem?{cause:index.problem}:{}}));for(let failure of indexes.failed){let reasons=failure.attempts.map(attempt2=>`${attempt2.strategy}: ${attempt2.reason}`).join(`
467
467
  `);ctx.reporter.problem(`Sous could not check the repository '${failure.repo}' for a newer version, so this build uses the versions it already had.`,{subject:failure.repo,...reasons?{cause:reasons}:{}})}let latest2;try{latest2=await ctx.services.get("recipes.resolver").resolveSubscriptions({quiet:!0})}catch(error51){return ctx.reporter.problem("Sous could not work out the newest recipe versions, so this build uses the versions it already had.",{cause:describe4(error51)}),report}let repos=ctx.config.get("repos")??{};for(let recipe of latest2.resolved){let pinned=current.recipes[recipe.key];if(!pinned)continue;let preferred=prefersNewer(recipe,subscriptions,repos[recipe.repo]?.alwaysPull===!0);for(let change of newerVersions2(recipe,pinned))(preferred?report.moved:report.newer).push(stale.has(recipe.repo)?{...change,staleIndex:!0}:change)}return report}function newerVersions2(latest2,locked){let found=[];isNewer(latest2.version,locked.version)&&found.push({key:latest2.key,from:locked.version,to:latest2.version});for(let[holder,pin]of Object.entries(locked.pins??{})){if(!latest2.requestedBy.includes(holder))continue;let to=latest2.pins?.find(candidate=>candidate.holder===holder)?.version??latest2.version;isNewer(to,pin.version)&&found.push({key:latest2.key,from:pin.version,to,holder})}return found}function prefersNewer(recipe,subscriptions,repoPrefers){return repoPrefers||subscriptions[recipe.key]?.alwaysPull===!0||subscriptions[recipe.namespace]?.alwaysPull===!0}function isNewer(candidate,pinned){let a=import_semver17.default.valid(candidate),b=import_semver17.default.valid(pinned);return a!==null&&b!==null&&import_semver17.default.gt(a,b)}function switchedOn(subscriptions){return Object.fromEntries(Object.entries(subscriptions).filter(([,entry])=>entry.enabled!==!1))}function builtInPins(subscriptions,lockfile){return Object.entries(subscriptions).filter(([,entry])=>entry.addedBy===BUILT_IN_ADDED_BY2&&entry.range!==void 0).flatMap(([subscription,entry])=>Object.keys(lockfile.recipes).filter(key=>(key===subscription||key.startsWith(`${subscription}/`))&&lockfile.recipes[key].requestedBy.includes(PROJECT_HOLDER2)).map(key=>({key,subscription,version:entry.range})))}function isLocked(key,entry,lockfile){let matches=key.includes("/")?[lockfile.recipes[key]].filter(locked=>locked!==void 0):Object.entries(lockfile.recipes).filter(([lockedKey])=>lockedKey.startsWith(`${key}/`)).map(([,locked])=>locked);if(matches.length===0)return!1;let range3=entry.range,includePrerelease=entry.prerelease===!0;return matches.every(locked=>locked.requestedBy.includes(PROJECT_HOLDER2)?range3===void 0||range3==="*"?!0:import_semver17.default.satisfies(locked.version,range3,{includePrerelease}):!1)}function warnAboutProblems(resolved,ctx){for(let missing of resolved.missingRepos){let by2=missing.requiredBy.map(entry=>entry.ref).join(", ");ctx.reporter.problem(`Sous could not lock ${by2||"a subscription"}: it needs the repository '${missing.name}', which this project does not trust yet, so nothing from it was compiled.`,{subject:missing.name,hint:`Run 'sous repo add ${missing.url??missing.name}' to trust it.`})}for(let key of resolved.unreadable)ctx.reporter.problem(`Sous could not read the manifest of '${key}', so nothing from it was compiled.`,{subject:key});for(let cycle of resolved.cycles)ctx.reporter.warn(`These recipes depend on each other in a cycle: ${cycle.join(" -> ")}.`)}function unreadableNotWritten(keys){return`The lockfile was not written, because sous could not read what ${keys.length===1?`${keys[0]} depends`:`${keys.join(", ")} depend`} on.`}function mergeDiffs(first2,second){return first2.unchanged?second:second.unchanged?first2:{added:[...first2.added,...second.added],removed:[...first2.removed,...second.removed],updated:[...first2.updated,...second.updated],changed:[...first2.changed,...second.changed],reposAdded:[...new Set([...first2.reposAdded,...second.reposAdded])],reposRemoved:[...new Set([...first2.reposRemoved,...second.reposRemoved])],unchanged:!1}}function mergeRestores(first2,second){return{restored:[...new Set([...first2.restored,...second.restored])],alreadyPresent:[...new Set([...first2.alreadyPresent,...second.alreadyPresent])],failed:[...first2.failed,...second.failed]}}function describe4(error51){return error51 instanceof Error?error51.message:String(error51)}var import_semver17,PROJECT_HOLDER2,BUILT_IN_ADDED_BY2,NO_CHANGE,NOTHING_RESTORED,init_prepare=__esm({"../sous-plugin-build/src/prepare.ts"(){"use strict";import_semver17=__toESM(require_semver2(),1),PROJECT_HOLDER2="project",BUILT_IN_ADDED_BY2="sous",NO_CHANGE=Object.freeze({added:[],removed:[],updated:[],changed:[],reposAdded:[],reposRemoved:[],unchanged:!0}),NOTHING_RESTORED=Object.freeze({restored:[],alreadyPresent:[],failed:[]})}});var build_exports={};__export(build_exports,{build:()=>build,clear:()=>clear,compile:()=>compile2,nestedBuildHeading:()=>nestedBuildHeading,prune:()=>prune2,watcherRunningError:()=>watcherRunningError,writeRuntimeContext:()=>writeRuntimeContext});import fs56 from"node:fs";import path72 from"node:path";import{commandVariables as commandVariables3,ConfigError as ConfigError45,IntentOutput as IntentOutput12,IntentOutputs as IntentOutputs14,ItemList as ItemList3,LogLevel as LogLevel13,NotFoundError as NotFoundError8,ReportEntryStyle as ReportEntryStyle7,SousError as SousError29,VariableSet as VariableSet5}from"@sous-io/sous-plugin-api";async function build(input,ctx){reportCommandVariables(input,ctx,"build");let result=await runBuild(input,ctx);return buildOutputs(result)}function buildOutputs(result){return new IntentOutputs14([new IntentOutput12({data:result})],result.ok?{}:{exitCode:1})}function reportCommandVariables(input,ctx,command){if(ctx.chain?.intent!==command||input.changedFiles!==void 0)return;let flags={},given=input;for(let[label,key]of[["Rebuild","rebuild"],["Dry Run","dryRun"],["No Compile","noCompile"],["No Prune","noPrune"],["Keep Going","keepGoing"],["Ignore Failed Assertions","ignoreFailedAssertions"],["Ignore Failed Checks","ignoreFailedChecks"]])given[key]===!0&&(flags[label]=!0);let block=commandVariables3(ctx,flags).result;block instanceof VariableSet5&&ctx.reporter.commandVariables(block.entries)}async function runBuild(input,ctx){let dryRun4=input.dryRun===!0,report=input.reportRemoved===!1?{report:!1}:{},partial2=(input.changedFiles?.length??0)>0&&input.rebuild!==!0;input.watch&&ensureNoWatcher(ctx);let heading=nestedBuildHeading(ctx);heading!==void 0&&!partial2&&ctx.reporter.operationStart(heading);let prepared;if(partial2)prepared=nothingPrepared();else{reportLinkedRepos(ctx.services.get("recipes.links").all(),ctx.reporter,LogLevel13.Warning),prepared=(await ctx.run("build.prepare",{dryRun:dryRun4})).toPlain(),reportPrepared(prepared,ctx.reporter);let asking2=!dryRun4&&input.watch!==!0&&ctx.prompter.interactive;reportRetired(prepared.retired,ctx.reporter,asking2),(asking2&&await offerReplacements(ctx,prepared.retired??[])||!prepared.locked.unchanged)&&!dryRun4&&(ctx.chain&&!ctx.chain.parallel?(await ctx.refreshConfig(),prepared={...prepared,skipped:ctx.services.get("recipes.active").skipped()}):ctx.reporter.notice("The lockfile changed while preparing; the recipes it now pins are compiled from the next build on."))}let skipped=partial2?[]:prepared.skipped,skippedFiles=filesOfSkipped(ctx,skipped),ignoreFailedChecks=input.ignoreFailedChecks===!0||input.keepGoing===!0,ignoreFailedAssertions=input.ignoreFailedAssertions===!0||input.keepGoing===!0,compiling=input.noCompile!==!0,checks,beforeBuild;if(compiling){if(checks=await runHandlers2(ctx,"check",ignoreFailedChecks?{ignoreFailedChecks:!0}:{}),checks?.failed)throw checksFailedError(checks);beforeBuild=dryRun4?void 0:await runHandlers2(ctx,"beforeBuild")}let ok=!0,compiled,runtimeContext,cleared;compiling&&(input.rebuild&&!dryRun4&&(cleared=(await ctx.run("compiler.prune",{all:!0,...report})).toPlain()),runtimeContext=await writeRuntimeContext(ctx,dryRun4),compiled=(await ctx.run("compiler.compile",{...input.strict?{strict:!0}:{},...input.rebuild?{rebuild:!0}:{},...dryRun4?{dryRun:!0}:{},...partial2?{changedFiles:input.changedFiles}:{},reportEnd:!1})).toPlain(),ok=compiled.ok,partial2||warnUnincludedMemories(ctx,compiled));let pruned;!input.noPrune&&ok&&(pruned=(await ctx.run("compiler.prune",{dryRun:dryRun4,...report})).toPlain());let edits,afterBuild;if(compiling&&ok&&(hasIntent2(ctx,"editor.apply")&&(edits=(await ctx.run("editor.apply",{dryRun:dryRun4,ignoreFailedAssertions})).toPlain(),ok=edits.ok),afterBuild=dryRun4?void 0:await runHandlers2(ctx,"afterBuild")),reportSkipped(ctx,skipped,skippedFiles,[...cleared?.removed??[],...pruned?.removed??[]],dryRun4),!partial2)for(let recipe of ctx.services.get("recipes.active").switchedOffButBuilt?.()??[])ctx.reporter.notice(recipe.message);if(compiled){let errors=compiled.problems.filter(problem=>problem.level==="error").length,failedAssertions=edits===void 0||edits.ok?0:failedAssertionCount(edits);ctx.reporter.operationSummary(filesSummaryLine({outputs:compiled.outputs,notWritten:compiled.notWritten??[],removed:[...cleared?.removed??[],...pruned?.removed??[]],dryRun:dryRun4})),errors>0?ctx.reporter.operationEnd(`Done with ${errors} error(s).`,!1):failedAssertions>0?ctx.reporter.operationEnd(`Done, but ${failedAssertions===1?"an assertion":`${failedAssertions} assertions`} failed, and the file${failedAssertions===1?" it checks was":"s they check were"} not written.`,!1):ctx.reporter.operationEnd("Done.",!0)}let watching=input.watch===!0;return watching&&startWatch(ctx,{...input.strict?{strict:!0}:{},...input.rebuild?{rebuild:!0}:{},...input.noPrune?{noPrune:!0}:{},...dryRun4?{dryRun:!0}:{},...ignoreFailedChecks?{ignoreFailedChecks:!0}:{},...ignoreFailedAssertions?{ignoreFailedAssertions:!0}:{}}),{ok,prepared,...compiled?{compiled}:{},...pruned?{pruned}:{},...runtimeContext?{runtimeContext}:{},...checks?{checks}:{},...beforeBuild?{beforeBuild}:{},...edits?{edits}:{},...afterBuild?{afterBuild}:{},dryRun:dryRun4,watching}}function hasIntent2(ctx,intent){return ctx.engine.intents.get(intent)!==void 0}function failedAssertionCount(edits){return edits.assertions.filter(outcome=>!outcome.passed&&outcome.silenced!==!0&&outcome.level==="error").length}async function runHandlers2(ctx,purpose,input={}){if(hasIntent2(ctx,`handlers.${purpose}`))return runHandlerPurpose(ctx,purpose,input)}function nestedBuildHeading(ctx){let command=ctx.chain?.intent;if(!(command===void 0||OWN_BUILD_COMMANDS.has(command)))return command==="launch"?"Building":"Building the project"}async function compile2(input,ctx){return reportCommandVariables(input,ctx,"compile"),buildOutputs(await runCompile(input,ctx))}async function runCompile(input,ctx){let dryRun4=input.dryRun===!0;if((ctx.config.get("compilation")?.targets??[]).length===0)throw new ConfigError45(`No compilation config found in ${ctx.project?.configPath??"the config"}.`);input.watch&&ensureNoWatcher(ctx),reportLinkedRepos(ctx.services.get("recipes.links").all(),ctx.reporter,LogLevel13.Notice);let runtimeContext=await writeRuntimeContext(ctx,dryRun4),partial2=(input.changedFiles?.length??0)>0&&input.rebuild!==!0,compiled=(await ctx.run("compiler.compile",{...input.strict?{strict:!0}:{},...input.rebuild?{rebuild:!0}:{},...dryRun4?{dryRun:!0}:{},...partial2?{changedFiles:input.changedFiles}:{},reportEnd:!1})).toPlain();partial2||warnUnincludedMemories(ctx,compiled);let errors=compiled.problems.filter(problem=>problem.level==="error").length;ctx.reporter.operationSummary(filesSummaryLine({outputs:compiled.outputs,notWritten:compiled.notWritten??[],dryRun:dryRun4})),ctx.reporter.operationEnd(errors>0?`Done with ${errors} error(s).`:"Done.",errors===0);let watching=input.watch===!0;return watching&&startWatch(ctx,{compileOnly:!0,...input.strict?{strict:!0}:{},...input.rebuild?{rebuild:!0}:{},...dryRun4?{dryRun:!0}:{}}),{ok:compiled.ok,compiled,...runtimeContext?{runtimeContext}:{},dryRun:dryRun4,watching}}function warnUnincludedMemories(ctx,compiled){if(!compiled.ok||compiled.included===void 0||!ctx.services.has("memories.selection"))return;let included=new Set(compiled.included),missing=ctx.services.get("memories.selection").selected().filter(memory=>!included.has(realPath(memory.path)));reportUnincludedMemories(missing,ctx.reporter)}function realPath(file2){try{return fs56.realpathSync(file2)}catch{return file2}}async function prune2(input,ctx){let dryRun4=input.dryRun===!0,result=(await ctx.run("build",{noCompile:!0,reportRemoved:!1,...dryRun4?{dryRun:!0}:{}})).toPlain();return removalOutputs(result.pruned??{removed:[],dirsRemoved:[],dryRun:dryRun4})}function removalOutputs(result){let files=`${result.removed.length} ${result.removed.length===1?"file":"files"}`,directories=`${result.dirsRemoved.length} ${result.dirsRemoved.length===1?"directory":"directories"}`,what=result.dirsRemoved.length===0?files:`${files} and ${directories}`,summary2=result.removed.length===0&&result.dirsRemoved.length===0?"Nothing to remove.":`${result.dryRun?"Would remove":"Removed"} ${what}.`,outputs=[];return result.removed.length>0&&outputs.push(new IntentOutput12({result:new ItemList3(result.removed,{title:result.dryRun?"Files that would be removed":"Files removed"})})),result.dirsRemoved.length>0&&outputs.push(new IntentOutput12({result:new ItemList3(result.dirsRemoved,{title:result.dryRun?"Directories that would be removed":"Directories removed"})})),outputs.push(new IntentOutput12({summary:summary2})),new IntentOutputs14(outputs).withData(result)}async function clear(input,ctx){let dryRun4=input.dryRun===!0,state=ctx.services.get("compiler.state"),stateFile=state.path();if(!fs56.existsSync(stateFile))throw new NotFoundError8("state file",stateFile,`No state file found at ${stateFile}. Run 'sous build' first, then 'sous clear' to recover.`);let{files,dirs}=state.read();if(!input.force&&!dryRun4&&!await ctx.prompter.confirm({message:`Delete ${files.length} file(s) and ${dirs.length} director(ies) for '${projectLabel(ctx.project,stateFile)}'?`,default:!1,answeredBy:"--force"})){let aborted2={removed:[],dirsRemoved:[],dryRun:dryRun4,confirmed:!1};return new IntentOutputs14(new IntentOutput12({summary:"Aborted.",data:aborted2,style:ReportEntryStyle7.Note}))}let result=(await ctx.run("compiler.prune",{all:!0,report:!1,...dryRun4?{dryRun:!0}:{}})).toPlain();return removalOutputs({...result,confirmed:!0})}async function offerReplacements(ctx,retired){let changed2=!1;for(let recipe of retired){let subscription=recipe.subscription;if(subscription===void 0||recipe.replacements.length===0)continue;let added=0,sameName=!1;for(let replacement of recipe.replacements)if(await ctx.prompter.confirm({message:`Subscribe to '${replacement.ref}' in place of '${recipe.key}'?`,default:!1}))try{await ctx.run("subscription.add",{ref:replacement.ref,noBuild:!0,...replacement.repo===void 0?{}:{yes:!0}}),ctx.reporter.notice(`Subscribed to '${replacement.ref}' in place of '${recipe.key}'.`),added+=1,sameName||=replacement.key===recipe.key,changed2=!0}catch(error51){ctx.reporter.problem(`Sous did not subscribe to '${replacement.ref}'.`,{subject:replacement.ref,cause:error51 instanceof Error?error51.message:String(error51)})}added===0||sameName||await ctx.prompter.confirm({message:`Remove the subscription to '${subscription}'?`,default:!0})&&(await ctx.run("subscription.remove",{ref:subscription,noBuild:!0}),ctx.reporter.notice(`Removed the subscription to '${subscription}'.`))}return changed2}function nothingPrepared(){return{seeded:[],locked:NO_CHANGE,restored:NOTHING_RESTORED,newer:[],checkedUpstream:!1,skipped:[],unanswered:[],unanswerable:[]}}async function writeRuntimeContext(ctx,dryRun4){if(!(ctx.config.get("compilation")?.targets??[]).some(target=>target.generateRuntimeContext===!0))return;let service=ctx.services.get("build.runtime-context");if(!service.settings()){ctx.reporter.warn("A compilation target asks for the runtime context (generateRuntimeContext), but the config sets no runtimeContext, so none was written.");return}let generated=await service.generate();generated&&generated.branch===void 0&&ctx.reporter.warn(`Sous could not read the current git branch, so the runtime context says "unknown".${generated.branchProblem===void 0?"":` Git said: ${generated.branchProblem}`}`);let written=await service.write({dryRun:dryRun4,...ctx.chain===void 0?{}:{run:ctx.chain.id}});return written?.backup!==void 0&&ctx.reporter.operation(dryRun4?"would-back-up":"backed-up",written.file,{note:`${dryRun4?"would back up":"backed up"} to ${written.backup}`}),await ctx.services.get("compiler.writer").commit({dryRun:dryRun4}),written}function filesOfSkipped(ctx,skipped){let files=new Map;if(skipped.length===0)return files;let state=ctx.services.get("compiler.state");for(let recipe of skipped)files.set(recipe.key,new Set(state.filesFrom({recipe:recipe.key}).map(entry=>path72.resolve(entry.dest))));return files}function reportSkipped(ctx,skipped,files,removedFiles,dryRun4){let removed=new Set(removedFiles.map(file2=>path72.resolve(file2)));for(let recipe of skipped){let count2=[...files.get(recipe.key)??new Set].filter(file2=>removed.has(file2)).length;ctx.reporter.notice(skippedLine(recipe)),count2>0&&ctx.reporter.detail(prunedForSkippedLine(count2,dryRun4),LogLevel13.Notice)}}function ensureNoWatcher(ctx){let pid=ctx.services.get("build.pid"),recorded=pid.read();if(recorded!==void 0&&recorded!==process.pid&&pid.isRunning())throw watcherRunningError(projectLabel(ctx.project,pid.path()),recorded,pid.path())}function watcherRunningError(label,pid,file2){return new SousError29(`A watcher is already running for project '${label}' (PID ${pid}). Stop it first or delete ${file2}.`)}function startWatch(ctx,input){ctx.engine.submit({intent:"build.watch",input},{reporter:ctx.reporter,prompter:ctx.prompter,globals:ctx.globals}).catch(error51=>{ctx.reporter.error(`Watch mode stopped: ${error51 instanceof Error?error51.message:String(error51)}`)})}var OWN_BUILD_COMMANDS,init_build=__esm({"../sous-plugin-build/src/build.ts"(){"use strict";init_src8();init_pid();init_prepare();init_report();OWN_BUILD_COMMANDS=new Set(["build","compile","prune","build.watch","upgrade"])}});import path73 from"node:path";function watchSet(config2,project,globs,options2){let services=config2.services,resolver=services.get("variables.resolver"),aliases2=services.has("compiler.aliases")?services.get("compiler.aliases"):void 0,targets=config2.get("compilation")?.targets??[],base=project?.root??options2.cwd,absolute=value=>path73.resolve(base,resolver.normalizePath(value)),files=new Set,patterns=new Set;targets.forEach((target,index)=>{if(target.origin?.recipe!==void 0)return;let scope=resolver.scope({level:"target",target:index});if(target.entryPoint&&files.add(absolute(resolver.substituteStrict(target.entryPoint,scope,`compilation.targets[${index}].entryPoint`))),target.entryGlob){let pattern=resolver.substituteStrict(target.entryGlob,scope,`compilation.targets[${index}].entryGlob`),split3=aliases2?.split(pattern);if(split3)for(let dir of aliases2?.get(split3.alias)??[])patterns.add(globs.toPosix(path73.join(dir,split3.rest)));else patterns.add(globs.toPosix(absolute(pattern)))}});let rootScope=resolver.scope(),fullRebuildPaths=new Set;if(project?.configPath&&fullRebuildPaths.add(project.configPath),project?.confDir&&fullRebuildPaths.add(project.confDir),services.has("recipes.links"))for(let link of Object.values(services.get("recipes.links").all()))fullRebuildPaths.add(link.path);if(services.has("expressions.evaluator")){let evaluator=services.get("expressions.evaluator");for(let file2 of evaluator.files?.()??[])fullRebuildPaths.add(file2)}for(let extra of config2.get("watch")?.paths??[]){let resolved=absolute(resolver.substitute(extra,rootScope));fullRebuildPaths.add(globs.hasGlob(resolved)?globs.staticBase(resolved):resolved)}return{files:[...files],globs:[...patterns],fullRebuildPaths:[...fullRebuildPaths],ignored:[...options2.ignored??[]]}}function pathsToWatch(set2,globs){return[...new Set([...set2.files,...set2.globs.map(pattern=>globs.staticBase(pattern)),...set2.fullRebuildPaths])]}function classifyChange(file2,set2,globs){let resolved=path73.resolve(file2);if(set2.ignored.some(ignored=>path73.resolve(ignored)===resolved))return"ignored";if(set2.fullRebuildPaths.some(full=>isInside2(resolved,path73.resolve(full))))return"full";if(set2.files.some(exact=>path73.resolve(exact)===resolved))return"partial";let posix3=globs.toPosix(resolved);return set2.globs.some(pattern=>globs.isMatch(posix3,pattern))?"partial":"ignored"}function changesListing(event,file2,set2,globs){if(event!=="add"&&event!=="unlink")return!1;let posix3=globs.toPosix(path73.resolve(file2));return set2.globs.some(pattern=>globs.isMatch(posix3,pattern))}function isInside2(child2,parent){return child2===parent||child2.startsWith(parent.endsWith(path73.sep)?parent:parent+path73.sep)}var init_paths=__esm({"../sous-plugin-build/src/watch/paths.ts"(){"use strict"}});import{lstat,readdir,realpath,stat as stat2}from"node:fs/promises";import{join as pjoin,relative as prelative,resolve as presolve,sep as psep}from"node:path";import{Readable}from"node:stream";function readdirp(root,options2={}){let type=options2.entryType||options2.type;if(type==="both"&&(type=EntryTypes.FILE_DIR_TYPE),type&&(options2.type=type),root){if(typeof root!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(type&&!ALL_TYPES.includes(type))throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return options2.root=root,new ReaddirpStream(options2)}var EntryTypes,defaultOptions2,RECURSIVE_ERROR_CODE,NORMAL_FLOW_ERRORS,ALL_TYPES,DIR_TYPES,FILE_TYPES,isNormalFlowError,wantBigintFsStats,emptyFn,normalizeFilter,ReaddirpStream,init_readdirp=__esm({"../../node_modules/.pnpm/readdirp@5.0.0/node_modules/readdirp/index.js"(){EntryTypes={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},defaultOptions2={root:".",fileFilter:_entryInfo=>!0,directoryFilter:_entryInfo=>!0,type:EntryTypes.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(defaultOptions2);RECURSIVE_ERROR_CODE="READDIRP_RECURSIVE_ERROR",NORMAL_FLOW_ERRORS=new Set(["ENOENT","EPERM","EACCES","ELOOP",RECURSIVE_ERROR_CODE]),ALL_TYPES=[EntryTypes.DIR_TYPE,EntryTypes.EVERYTHING_TYPE,EntryTypes.FILE_DIR_TYPE,EntryTypes.FILE_TYPE],DIR_TYPES=new Set([EntryTypes.DIR_TYPE,EntryTypes.EVERYTHING_TYPE,EntryTypes.FILE_DIR_TYPE]),FILE_TYPES=new Set([EntryTypes.EVERYTHING_TYPE,EntryTypes.FILE_DIR_TYPE,EntryTypes.FILE_TYPE]),isNormalFlowError=error51=>NORMAL_FLOW_ERRORS.has(error51.code),wantBigintFsStats=process.platform==="win32",emptyFn=_entryInfo=>!0,normalizeFilter=filter3=>{if(filter3===void 0)return emptyFn;if(typeof filter3=="function")return filter3;if(typeof filter3=="string"){let fl=filter3.trim();return entry=>entry.basename===fl}if(Array.isArray(filter3)){let trItems=filter3.map(item=>item.trim());return entry=>trItems.some(f=>entry.basename===f)}return emptyFn},ReaddirpStream=class extends Readable{parents;reading;parent;_stat;_maxDepth;_wantsDir;_wantsFile;_wantsEverything;_root;_isDirent;_statsProp;_rdOptions;_fileFilter;_directoryFilter;constructor(options2={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:options2.highWaterMark});let opts={...defaultOptions2,...options2},{root,type}=opts;this._fileFilter=normalizeFilter(opts.fileFilter),this._directoryFilter=normalizeFilter(opts.directoryFilter);let statMethod=opts.lstat?lstat:stat2;wantBigintFsStats?this._stat=path122=>statMethod(path122,{bigint:!0}):this._stat=statMethod,this._maxDepth=opts.depth!=null&&Number.isSafeInteger(opts.depth)?opts.depth:defaultOptions2.depth,this._wantsDir=type?DIR_TYPES.has(type):!1,this._wantsFile=type?FILE_TYPES.has(type):!1,this._wantsEverything=type===EntryTypes.EVERYTHING_TYPE,this._root=presolve(root),this._isDirent=!opts.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(root,1)],this.reading=!1,this.parent=void 0}async _read(batch){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&batch>0;){let par=this.parent,fil=par&&par.files;if(fil&&fil.length>0){let{path:path122,depth}=par,slice2=fil.splice(0,batch).map(dirent=>this._formatEntry(dirent,path122)),awaited=await Promise.all(slice2);for(let entry of awaited){if(!entry)continue;if(this.destroyed)return;let entryType=await this._getEntryType(entry);entryType==="directory"&&this._directoryFilter(entry)?(depth<=this._maxDepth&&this.parents.push(this._exploreDir(entry.fullPath,depth+1)),this._wantsDir&&(this.push(entry),batch--)):(entryType==="file"||this._includeAsFile(entry))&&this._fileFilter(entry)&&this._wantsFile&&(this.push(entry),batch--)}}else{let parent=this.parents.pop();if(!parent){this.push(null);break}if(this.parent=await parent,this.destroyed)return}}}catch(error51){this.destroy(error51)}finally{this.reading=!1}}}async _exploreDir(path122,depth){let files;try{files=await readdir(path122,this._rdOptions)}catch(error51){this._onError(error51)}return{files,depth,path:path122}}async _formatEntry(dirent,path122){let entry,basename3=this._isDirent?dirent.name:dirent;try{let fullPath=presolve(pjoin(path122,basename3));entry={path:prelative(this._root,fullPath),fullPath,basename:basename3},entry[this._statsProp]=this._isDirent?dirent:await this._stat(fullPath)}catch(err){this._onError(err);return}return entry}_onError(err){isNormalFlowError(err)&&!this.destroyed?this.emit("warn",err):this.destroy(err)}async _getEntryType(entry){if(!entry&&this._statsProp in entry)return"";let stats=entry[this._statsProp];if(stats.isFile())return"file";if(stats.isDirectory())return"directory";if(stats&&stats.isSymbolicLink()){let full=entry.fullPath;try{let entryRealPath=await realpath(full),entryRealPathStats=await lstat(entryRealPath);if(entryRealPathStats.isFile())return"file";if(entryRealPathStats.isDirectory()){let len=entryRealPath.length;if(full.startsWith(entryRealPath)&&full.substr(len,1)===psep){let recursiveError=new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);return recursiveError.code=RECURSIVE_ERROR_CODE,this._onError(recursiveError)}return"directory"}}catch(error51){return this._onError(error51),""}}}_includeAsFile(entry){let stats=entry&&entry[this._statsProp];return stats&&this._wantsEverything&&!stats.isDirectory()}}}});import{watch as fs_watch,unwatchFile,watchFile}from"node:fs";import{realpath as fsrealpath,lstat as lstat2,open,stat as stat3}from"node:fs/promises";import{type as osType}from"node:os";import*as sp from"node:path";function createFsWatchInstance(path122,options2,listener,errHandler,emitRaw){let handleEvent=(rawEvent,evPath)=>{listener(path122),emitRaw(rawEvent,evPath,{watchedPath:path122}),evPath&&path122!==evPath&&fsWatchBroadcast(sp.resolve(path122,evPath),KEY_LISTENERS,sp.join(path122,evPath))};try{return fs_watch(path122,{persistent:options2.persistent},handleEvent)}catch(error51){errHandler(error51);return}}var STR_DATA,STR_END,STR_CLOSE,EMPTY_FN,pl,isWindows,isMacos,isLinux,isFreeBSD,isIBMi,EVENTS,EV,THROTTLE_MODE_WATCH,statMethods,KEY_LISTENERS,KEY_ERR,KEY_RAW,HANDLER_KEYS,binaryExtensions,isBinaryPath,foreach,addAndConvert,clearItem,delFromSet,isEmptySet,FsWatchInstances,fsWatchBroadcast,setFsWatchListener,FsWatchFileInstances,setFsWatchFileListener,NodeFsHandler,init_handler=__esm({"../../node_modules/.pnpm/chokidar@5.0.0/node_modules/chokidar/handler.js"(){STR_DATA="data",STR_END="end",STR_CLOSE="close",EMPTY_FN=()=>{},pl=process.platform,isWindows=pl==="win32",isMacos=pl==="darwin",isLinux=pl==="linux",isFreeBSD=pl==="freebsd",isIBMi=osType()==="OS400",EVENTS={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},EV=EVENTS,THROTTLE_MODE_WATCH="watch",statMethods={lstat:lstat2,stat:stat3},KEY_LISTENERS="listeners",KEY_ERR="errHandlers",KEY_RAW="rawEmitters",HANDLER_KEYS=[KEY_LISTENERS,KEY_ERR,KEY_RAW],binaryExtensions=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),isBinaryPath=filePath=>binaryExtensions.has(sp.extname(filePath).slice(1).toLowerCase()),foreach=(val,fn)=>{val instanceof Set?val.forEach(fn):fn(val)},addAndConvert=(main2,prop,item)=>{let container=main2[prop];container instanceof Set||(main2[prop]=container=new Set([container])),container.add(item)},clearItem=cont=>key=>{let set2=cont[key];set2 instanceof Set?set2.clear():delete cont[key]},delFromSet=(main2,prop,item)=>{let container=main2[prop];container instanceof Set?container.delete(item):container===item&&delete main2[prop]},isEmptySet=val=>val instanceof Set?val.size===0:!val,FsWatchInstances=new Map;fsWatchBroadcast=(fullPath,listenerType,val1,val2,val3)=>{let cont=FsWatchInstances.get(fullPath);cont&&foreach(cont[listenerType],listener=>{listener(val1,val2,val3)})},setFsWatchListener=(path122,fullPath,options2,handlers)=>{let{listener,errHandler,rawEmitter}=handlers,cont=FsWatchInstances.get(fullPath),watcher;if(!options2.persistent)return watcher=createFsWatchInstance(path122,options2,listener,errHandler,rawEmitter),watcher?watcher.close.bind(watcher):void 0;if(cont)addAndConvert(cont,KEY_LISTENERS,listener),addAndConvert(cont,KEY_ERR,errHandler),addAndConvert(cont,KEY_RAW,rawEmitter);else{if(watcher=createFsWatchInstance(path122,options2,fsWatchBroadcast.bind(null,fullPath,KEY_LISTENERS),errHandler,fsWatchBroadcast.bind(null,fullPath,KEY_RAW)),!watcher)return;watcher.on(EV.ERROR,async error51=>{let broadcastErr=fsWatchBroadcast.bind(null,fullPath,KEY_ERR);if(cont&&(cont.watcherUnusable=!0),isWindows&&error51.code==="EPERM")try{await(await open(path122,"r")).close(),broadcastErr(error51)}catch{}else broadcastErr(error51)}),cont={listeners:listener,errHandlers:errHandler,rawEmitters:rawEmitter,watcher},FsWatchInstances.set(fullPath,cont)}return()=>{delFromSet(cont,KEY_LISTENERS,listener),delFromSet(cont,KEY_ERR,errHandler),delFromSet(cont,KEY_RAW,rawEmitter),isEmptySet(cont.listeners)&&(cont.watcher.close(),FsWatchInstances.delete(fullPath),HANDLER_KEYS.forEach(clearItem(cont)),cont.watcher=void 0,Object.freeze(cont))}},FsWatchFileInstances=new Map,setFsWatchFileListener=(path122,fullPath,options2,handlers)=>{let{listener,rawEmitter}=handlers,cont=FsWatchFileInstances.get(fullPath),copts=cont&&cont.options;return copts&&(copts.persistent<options2.persistent||copts.interval>options2.interval)&&(unwatchFile(fullPath),cont=void 0),cont?(addAndConvert(cont,KEY_LISTENERS,listener),addAndConvert(cont,KEY_RAW,rawEmitter)):(cont={listeners:listener,rawEmitters:rawEmitter,options:options2,watcher:watchFile(fullPath,options2,(curr,prev)=>{foreach(cont.rawEmitters,rawEmitter2=>{rawEmitter2(EV.CHANGE,fullPath,{curr,prev})});let currmtime=curr.mtimeMs;(curr.size!==prev.size||currmtime>prev.mtimeMs||currmtime===0)&&foreach(cont.listeners,listener2=>listener2(path122,curr))})},FsWatchFileInstances.set(fullPath,cont)),()=>{delFromSet(cont,KEY_LISTENERS,listener),delFromSet(cont,KEY_RAW,rawEmitter),isEmptySet(cont.listeners)&&(FsWatchFileInstances.delete(fullPath),unwatchFile(fullPath),cont.options=cont.watcher=void 0,Object.freeze(cont))}},NodeFsHandler=class{fsw;_boundHandleError;constructor(fsW){this.fsw=fsW,this._boundHandleError=error51=>fsW._handleError(error51)}_watchWithNodeFs(path122,listener){let opts=this.fsw.options,directory=sp.dirname(path122),basename3=sp.basename(path122);this.fsw._getWatchedDir(directory).add(basename3);let absolutePath=sp.resolve(path122),options2={persistent:opts.persistent};listener||(listener=EMPTY_FN);let closer;if(opts.usePolling){let enableBin=opts.interval!==opts.binaryInterval;options2.interval=enableBin&&isBinaryPath(basename3)?opts.binaryInterval:opts.interval,closer=setFsWatchFileListener(path122,absolutePath,options2,{listener,rawEmitter:this.fsw._emitRaw})}else closer=setFsWatchListener(path122,absolutePath,options2,{listener,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return closer}_handleFile(file2,stats,initialAdd){if(this.fsw.closed)return;let dirname4=sp.dirname(file2),basename3=sp.basename(file2),parent=this.fsw._getWatchedDir(dirname4),prevStats=stats;if(parent.has(basename3))return;let listener=async(path122,newStats)=>{if(this.fsw._throttle(THROTTLE_MODE_WATCH,file2,5)){if(!newStats||newStats.mtimeMs===0)try{let newStats2=await stat3(file2);if(this.fsw.closed)return;let at2=newStats2.atimeMs,mt2=newStats2.mtimeMs;if((!at2||at2<=mt2||mt2!==prevStats.mtimeMs)&&this.fsw._emit(EV.CHANGE,file2,newStats2),(isMacos||isLinux||isFreeBSD)&&prevStats.ino!==newStats2.ino){this.fsw._closeFile(path122),prevStats=newStats2;let closer2=this._watchWithNodeFs(file2,listener);closer2&&this.fsw._addPathCloser(path122,closer2)}else prevStats=newStats2}catch{this.fsw._remove(dirname4,basename3)}else if(parent.has(basename3)){let at2=newStats.atimeMs,mt2=newStats.mtimeMs;(!at2||at2<=mt2||mt2!==prevStats.mtimeMs)&&this.fsw._emit(EV.CHANGE,file2,newStats),prevStats=newStats}}},closer=this._watchWithNodeFs(file2,listener);if(!(initialAdd&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(file2)){if(!this.fsw._throttle(EV.ADD,file2,0))return;this.fsw._emit(EV.ADD,file2,stats)}return closer}async _handleSymlink(entry,directory,path122,item){if(this.fsw.closed)return;let full=entry.fullPath,dir=this.fsw._getWatchedDir(directory);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let linkPath;try{linkPath=await fsrealpath(path122)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(dir.has(item)?this.fsw._symlinkPaths.get(full)!==linkPath&&(this.fsw._symlinkPaths.set(full,linkPath),this.fsw._emit(EV.CHANGE,path122,entry.stats)):(dir.add(item),this.fsw._symlinkPaths.set(full,linkPath),this.fsw._emit(EV.ADD,path122,entry.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(full))return!0;this.fsw._symlinkPaths.set(full,!0)}_handleRead(directory,initialAdd,wh,target,dir,depth,throttler){directory=sp.join(directory,"");let throttleKey=target?`${directory}:${target}`:directory;if(throttler=this.fsw._throttle("readdir",throttleKey,1e3),!throttler)return;let previous=this.fsw._getWatchedDir(wh.path),current=new Set,stream=this.fsw._readdirp(directory,{fileFilter:entry=>wh.filterPath(entry),directoryFilter:entry=>wh.filterDir(entry)});if(stream)return stream.on(STR_DATA,async entry=>{if(this.fsw.closed){stream=void 0;return}let item=entry.path,path122=sp.join(directory,item);if(current.add(item),!(entry.stats.isSymbolicLink()&&await this._handleSymlink(entry,directory,path122,item))){if(this.fsw.closed){stream=void 0;return}(item===target||!target&&!previous.has(item))&&(this.fsw._incrReadyCount(),path122=sp.join(dir,sp.relative(dir,path122)),this._addToNodeFs(path122,initialAdd,wh,depth+1))}}).on(EV.ERROR,this._boundHandleError),new Promise((resolve4,reject2)=>{if(!stream)return reject2();stream.once(STR_END,()=>{if(this.fsw.closed){stream=void 0;return}let wasThrottled=throttler?throttler.clear():!1;resolve4(void 0),previous.getChildren().filter(item=>item!==directory&&!current.has(item)).forEach(item=>{this.fsw._remove(directory,item)}),stream=void 0,wasThrottled&&this._handleRead(directory,!1,wh,target,dir,depth,throttler)})})}async _handleDir(dir,stats,initialAdd,depth,target,wh,realpath2){let parentDir=this.fsw._getWatchedDir(sp.dirname(dir)),tracked=parentDir.has(sp.basename(dir));!(initialAdd&&this.fsw.options.ignoreInitial)&&!target&&!tracked&&this.fsw._emit(EV.ADD_DIR,dir,stats),parentDir.add(sp.basename(dir)),this.fsw._getWatchedDir(dir);let throttler,closer,oDepth=this.fsw.options.depth;if((oDepth==null||depth<=oDepth)&&!this.fsw._symlinkPaths.has(realpath2)){if(!target&&(await this._handleRead(dir,initialAdd,wh,target,dir,depth,throttler),this.fsw.closed))return;closer=this._watchWithNodeFs(dir,(dirPath,stats2)=>{stats2&&stats2.mtimeMs===0||this._handleRead(dirPath,!1,wh,target,dir,depth,throttler)})}return closer}async _addToNodeFs(path122,initialAdd,priorWh,depth,target){let ready2=this.fsw._emitReady;if(this.fsw._isIgnored(path122)||this.fsw.closed)return ready2(),!1;let wh=this.fsw._getWatchHelpers(path122);priorWh&&(wh.filterPath=entry=>priorWh.filterPath(entry),wh.filterDir=entry=>priorWh.filterDir(entry));try{let stats=await statMethods[wh.statMethod](wh.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(wh.watchPath,stats))return ready2(),!1;let follow=this.fsw.options.followSymlinks,closer;if(stats.isDirectory()){let absPath=sp.resolve(path122),targetPath=follow?await fsrealpath(path122):path122;if(this.fsw.closed||(closer=await this._handleDir(wh.watchPath,stats,initialAdd,depth,target,wh,targetPath),this.fsw.closed))return;absPath!==targetPath&&targetPath!==void 0&&this.fsw._symlinkPaths.set(absPath,targetPath)}else if(stats.isSymbolicLink()){let targetPath=follow?await fsrealpath(path122):path122;if(this.fsw.closed)return;let parent=sp.dirname(wh.watchPath);if(this.fsw._getWatchedDir(parent).add(wh.watchPath),this.fsw._emit(EV.ADD,wh.watchPath,stats),closer=await this._handleDir(parent,stats,initialAdd,depth,path122,wh,targetPath),this.fsw.closed)return;targetPath!==void 0&&this.fsw._symlinkPaths.set(sp.resolve(path122),targetPath)}else closer=this._handleFile(wh.watchPath,stats,initialAdd);return ready2(),closer&&this.fsw._addPathCloser(path122,closer),!1}catch(error51){if(this.fsw._handleError(error51))return ready2(),path122}}}}});var chokidar_exports={};__export(chokidar_exports,{FSWatcher:()=>FSWatcher,WatchHelper:()=>WatchHelper,default:()=>chokidar_default,watch:()=>watch});import{EventEmitter}from"node:events";import{stat as statcb}from"node:fs";import{readdir as readdir2,stat as stat4}from"node:fs/promises";import*as sp2 from"node:path";function arrify(item){return Array.isArray(item)?item:[item]}function createPattern(matcher2){return typeof matcher2=="function"?matcher2:typeof matcher2=="string"?string4=>matcher2===string4:matcher2 instanceof RegExp?string4=>matcher2.test(string4):typeof matcher2=="object"&&matcher2!==null?string4=>{if(matcher2.path===string4)return!0;if(matcher2.recursive){let relative4=sp2.relative(matcher2.path,string4);return relative4?!relative4.startsWith("..")&&!sp2.isAbsolute(relative4):!1}return!1}:()=>!1}function normalizePath3(path122){if(typeof path122!="string")throw new Error("string expected");path122=sp2.normalize(path122),path122=path122.replace(/\\/g,"/");let prepend2=!1;return path122.startsWith("//")&&(prepend2=!0),path122=path122.replace(DOUBLE_SLASH_RE,"/"),prepend2&&(path122="/"+path122),path122}function matchPatterns(patterns,testString,stats){let path122=normalizePath3(testString);for(let index=0;index<patterns.length;index++){let pattern=patterns[index];if(pattern(path122,stats))return!0}return!1}function anymatch(matchers,testString){if(matchers==null)throw new TypeError("anymatch: specify first argument");let patterns=arrify(matchers).map(matcher2=>createPattern(matcher2));return testString==null?(testString2,stats)=>matchPatterns(patterns,testString2,stats):matchPatterns(patterns,testString)}function watch(paths,options2={}){let watcher=new FSWatcher(options2);return watcher.add(paths),watcher}var SLASH,SLASH_SLASH,ONE_DOT,TWO_DOTS,STRING_TYPE,BACK_SLASH_RE,DOUBLE_SLASH_RE,DOT_RE,REPLACER_RE,isMatcherObject,unifyPaths,toUnix,normalizePathToUnix,normalizeIgnored,getAbsolutePath,EMPTY_SET,DirEntry,STAT_METHOD_F,STAT_METHOD_L,WatchHelper,FSWatcher,chokidar_default,init_chokidar=__esm({"../../node_modules/.pnpm/chokidar@5.0.0/node_modules/chokidar/index.js"(){init_readdirp();init_handler();SLASH="/",SLASH_SLASH="//",ONE_DOT=".",TWO_DOTS="..",STRING_TYPE="string",BACK_SLASH_RE=/\\/g,DOUBLE_SLASH_RE=/\/\//g,DOT_RE=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,REPLACER_RE=/^\.[/\\]/;isMatcherObject=matcher2=>typeof matcher2=="object"&&matcher2!==null&&!(matcher2 instanceof RegExp);unifyPaths=paths_=>{let paths=arrify(paths_).flat();if(!paths.every(p=>typeof p===STRING_TYPE))throw new TypeError(`Non-string provided as watch path: ${paths}`);return paths.map(normalizePathToUnix)},toUnix=string4=>{let str=string4.replace(BACK_SLASH_RE,SLASH),prepend2=!1;return str.startsWith(SLASH_SLASH)&&(prepend2=!0),str=str.replace(DOUBLE_SLASH_RE,SLASH),prepend2&&(str=SLASH+str),str},normalizePathToUnix=path122=>toUnix(sp2.normalize(toUnix(path122))),normalizeIgnored=(cwd="")=>path122=>typeof path122=="string"?normalizePathToUnix(sp2.isAbsolute(path122)?path122:sp2.join(cwd,path122)):path122,getAbsolutePath=(path122,cwd)=>sp2.isAbsolute(path122)?path122:sp2.join(cwd,path122),EMPTY_SET=Object.freeze(new Set),DirEntry=class{path;_removeWatcher;items;constructor(dir,removeWatcher){this.path=dir,this._removeWatcher=removeWatcher,this.items=new Set}add(item){let{items:items2}=this;items2&&item!==ONE_DOT&&item!==TWO_DOTS&&items2.add(item)}async remove(item){let{items:items2}=this;if(!items2||(items2.delete(item),items2.size>0))return;let dir=this.path;try{await readdir2(dir)}catch{this._removeWatcher&&this._removeWatcher(sp2.dirname(dir),sp2.basename(dir))}}has(item){let{items:items2}=this;if(items2)return items2.has(item)}getChildren(){let{items:items2}=this;return items2?[...items2.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=EMPTY_FN,this.items=EMPTY_SET,Object.freeze(this)}},STAT_METHOD_F="stat",STAT_METHOD_L="lstat",WatchHelper=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(path122,follow,fsw){this.fsw=fsw;let watchPath=path122;this.path=path122=path122.replace(REPLACER_RE,""),this.watchPath=watchPath,this.fullWatchPath=sp2.resolve(watchPath),this.dirParts=[],this.dirParts.forEach(parts=>{parts.length>1&&parts.pop()}),this.followSymlinks=follow,this.statMethod=follow?STAT_METHOD_F:STAT_METHOD_L}entryPath(entry){return sp2.join(this.watchPath,sp2.relative(this.watchPath,entry.fullPath))}filterPath(entry){let{stats}=entry;if(stats&&stats.isSymbolicLink())return this.filterDir(entry);let resolvedPath=this.entryPath(entry);return this.fsw._isntIgnored(resolvedPath,stats)&&this.fsw._hasReadPermissions(stats)}filterDir(entry){return this.fsw._isntIgnored(this.entryPath(entry),entry.stats)}},FSWatcher=class extends EventEmitter{closed;options;_closers;_ignoredPaths;_throttled;_streams;_symlinkPaths;_watched;_pendingWrites;_pendingUnlinks;_readyCount;_emitReady;_closePromise;_userIgnored;_readyEmitted;_emitRaw;_boundRemove;_nodeFsHandler;constructor(_opts={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let awf=_opts.awaitWriteFinish,DEF_AWF={stabilityThreshold:2e3,pollInterval:100},opts={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,..._opts,ignored:_opts.ignored?arrify(_opts.ignored):arrify([]),awaitWriteFinish:awf===!0?DEF_AWF:typeof awf=="object"?{...DEF_AWF,...awf}:!1};isIBMi&&(opts.usePolling=!0),opts.atomic===void 0&&(opts.atomic=!opts.usePolling);let envPoll=process.env.CHOKIDAR_USEPOLLING;if(envPoll!==void 0){let envLower=envPoll.toLowerCase();envLower==="false"||envLower==="0"?opts.usePolling=!1:envLower==="true"||envLower==="1"?opts.usePolling=!0:opts.usePolling=!!envLower}let envInterval=process.env.CHOKIDAR_INTERVAL;envInterval&&(opts.interval=Number.parseInt(envInterval,10));let readyCalls=0;this._emitReady=()=>{readyCalls++,readyCalls>=this._readyCount&&(this._emitReady=EMPTY_FN,this._readyEmitted=!0,process.nextTick(()=>this.emit(EVENTS.READY)))},this._emitRaw=(...args)=>this.emit(EVENTS.RAW,...args),this._boundRemove=this._remove.bind(this),this.options=opts,this._nodeFsHandler=new NodeFsHandler(this),Object.freeze(opts)}_addIgnoredPath(matcher2){if(isMatcherObject(matcher2)){for(let ignored of this._ignoredPaths)if(isMatcherObject(ignored)&&ignored.path===matcher2.path&&ignored.recursive===matcher2.recursive)return}this._ignoredPaths.add(matcher2)}_removeIgnoredPath(matcher2){if(this._ignoredPaths.delete(matcher2),typeof matcher2=="string")for(let ignored of this._ignoredPaths)isMatcherObject(ignored)&&ignored.path===matcher2&&this._ignoredPaths.delete(ignored)}add(paths_,_origAdd,_internal){let{cwd}=this.options;this.closed=!1,this._closePromise=void 0;let paths=unifyPaths(paths_);return cwd&&(paths=paths.map(path122=>getAbsolutePath(path122,cwd))),paths.forEach(path122=>{this._removeIgnoredPath(path122)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=paths.length,Promise.all(paths.map(async path122=>{let res=await this._nodeFsHandler._addToNodeFs(path122,!_internal,void 0,0,_origAdd);return res&&this._emitReady(),res})).then(results=>{this.closed||results.forEach(item=>{item&&this.add(sp2.dirname(item),sp2.basename(_origAdd||item))})}),this}unwatch(paths_){if(this.closed)return this;let paths=unifyPaths(paths_),{cwd}=this.options;return paths.forEach(path122=>{!sp2.isAbsolute(path122)&&!this._closers.has(path122)&&(cwd&&(path122=sp2.join(cwd,path122)),path122=sp2.resolve(path122)),this._closePath(path122),this._addIgnoredPath(path122),this._watched.has(path122)&&this._addIgnoredPath({path:path122,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let closers=[];return this._closers.forEach(closerList=>closerList.forEach(closer=>{let promise2=closer();promise2 instanceof Promise&&closers.push(promise2)})),this._streams.forEach(stream=>stream.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(dirent=>dirent.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=closers.length?Promise.all(closers).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let watchList={};return this._watched.forEach((entry,dir)=>{let index=(this.options.cwd?sp2.relative(this.options.cwd,dir):dir)||ONE_DOT;watchList[index]=entry.getChildren().sort()}),watchList}emitWithAll(event,args){this.emit(event,...args),event!==EVENTS.ERROR&&this.emit(EVENTS.ALL,event,...args)}async _emit(event,path122,stats){if(this.closed)return;let opts=this.options;isWindows&&(path122=sp2.normalize(path122)),opts.cwd&&(path122=sp2.relative(opts.cwd,path122));let args=[path122];stats!=null&&args.push(stats);let awf=opts.awaitWriteFinish,pw;if(awf&&(pw=this._pendingWrites.get(path122)))return pw.lastChange=new Date,this;if(opts.atomic){if(event===EVENTS.UNLINK)return this._pendingUnlinks.set(path122,[event,...args]),setTimeout(()=>{this._pendingUnlinks.forEach((entry,path123)=>{this.emit(...entry),this.emit(EVENTS.ALL,...entry),this._pendingUnlinks.delete(path123)})},typeof opts.atomic=="number"?opts.atomic:100),this;event===EVENTS.ADD&&this._pendingUnlinks.has(path122)&&(event=EVENTS.CHANGE,this._pendingUnlinks.delete(path122))}if(awf&&(event===EVENTS.ADD||event===EVENTS.CHANGE)&&this._readyEmitted){let awfEmit=(err,stats2)=>{err?(event=EVENTS.ERROR,args[0]=err,this.emitWithAll(event,args)):stats2&&(args.length>1?args[1]=stats2:args.push(stats2),this.emitWithAll(event,args))};return this._awaitWriteFinish(path122,awf.stabilityThreshold,event,awfEmit),this}if(event===EVENTS.CHANGE&&!this._throttle(EVENTS.CHANGE,path122,50))return this;if(opts.alwaysStat&&stats===void 0&&(event===EVENTS.ADD||event===EVENTS.ADD_DIR||event===EVENTS.CHANGE)){let fullPath=opts.cwd?sp2.join(opts.cwd,path122):path122,stats2;try{stats2=await stat4(fullPath)}catch{}if(!stats2||this.closed)return;args.push(stats2)}return this.emitWithAll(event,args),this}_handleError(error51){let code=error51&&error51.code;return error51&&code!=="ENOENT"&&code!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||code!=="EPERM"&&code!=="EACCES")&&this.emit(EVENTS.ERROR,error51),error51||this.closed}_throttle(actionType,path122,timeout){this._throttled.has(actionType)||this._throttled.set(actionType,new Map);let action=this._throttled.get(actionType);if(!action)throw new Error("invalid throttle");let actionPath=action.get(path122);if(actionPath)return actionPath.count++,!1;let timeoutObject,clear2=()=>{let item=action.get(path122),count2=item?item.count:0;return action.delete(path122),clearTimeout(timeoutObject),item&&clearTimeout(item.timeoutObject),count2};timeoutObject=setTimeout(clear2,timeout);let thr={timeoutObject,clear:clear2,count:0};return action.set(path122,thr),thr}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(path122,threshold,event,awfEmit){let awf=this.options.awaitWriteFinish;if(typeof awf!="object")return;let pollInterval=awf.pollInterval,timeoutHandler,fullPath=path122;this.options.cwd&&!sp2.isAbsolute(path122)&&(fullPath=sp2.join(this.options.cwd,path122));let now=new Date,writes=this._pendingWrites;function awaitWriteFinishFn(prevStat){statcb(fullPath,(err,curStat)=>{if(err||!writes.has(path122)){err&&err.code!=="ENOENT"&&awfEmit(err);return}let now2=Number(new Date);prevStat&&curStat.size!==prevStat.size&&(writes.get(path122).lastChange=now2);let pw=writes.get(path122);now2-pw.lastChange>=threshold?(writes.delete(path122),awfEmit(void 0,curStat)):timeoutHandler=setTimeout(awaitWriteFinishFn,pollInterval,curStat)})}writes.has(path122)||(writes.set(path122,{lastChange:now,cancelWait:()=>(writes.delete(path122),clearTimeout(timeoutHandler),event)}),timeoutHandler=setTimeout(awaitWriteFinishFn,pollInterval))}_isIgnored(path122,stats){if(this.options.atomic&&DOT_RE.test(path122))return!0;if(!this._userIgnored){let{cwd}=this.options,ignored=(this.options.ignored||[]).map(normalizeIgnored(cwd)),list2=[...[...this._ignoredPaths].map(normalizeIgnored(cwd)),...ignored];this._userIgnored=anymatch(list2,void 0)}return this._userIgnored(path122,stats)}_isntIgnored(path122,stat6){return!this._isIgnored(path122,stat6)}_getWatchHelpers(path122){return new WatchHelper(path122,this.options.followSymlinks,this)}_getWatchedDir(directory){let dir=sp2.resolve(directory);return this._watched.has(dir)||this._watched.set(dir,new DirEntry(dir,this._boundRemove)),this._watched.get(dir)}_hasReadPermissions(stats){return this.options.ignorePermissionErrors?!0:!!(Number(stats.mode)&256)}_remove(directory,item,isDirectory7){let path122=sp2.join(directory,item),fullPath=sp2.resolve(path122);if(isDirectory7=isDirectory7??(this._watched.has(path122)||this._watched.has(fullPath)),!this._throttle("remove",path122,100))return;!isDirectory7&&this._watched.size===1&&this.add(directory,item,!0),this._getWatchedDir(path122).getChildren().forEach(nested=>this._remove(path122,nested));let parent=this._getWatchedDir(directory),wasTracked=parent.has(item);parent.remove(item),this._symlinkPaths.has(fullPath)&&this._symlinkPaths.delete(fullPath);let relPath=path122;if(this.options.cwd&&(relPath=sp2.relative(this.options.cwd,path122)),this.options.awaitWriteFinish&&this._pendingWrites.has(relPath)&&this._pendingWrites.get(relPath).cancelWait()===EVENTS.ADD)return;this._watched.delete(path122),this._watched.delete(fullPath);let eventName=isDirectory7?EVENTS.UNLINK_DIR:EVENTS.UNLINK;wasTracked&&!this._isIgnored(path122)&&this._emit(eventName,path122),this._closePath(path122)}_closePath(path122){this._closeFile(path122);let dir=sp2.dirname(path122);this._getWatchedDir(dir).remove(sp2.basename(path122))}_closeFile(path122){let closers=this._closers.get(path122);closers&&(closers.forEach(closer=>closer()),this._closers.delete(path122))}_addPathCloser(path122,closer){if(!closer)return;let list2=this._closers.get(path122);list2||(list2=[],this._closers.set(path122,list2)),list2.push(closer)}_readdirp(root,opts){if(this.closed)return;let options2={type:EVENTS.ALL,alwaysStat:!0,lstat:!0,...opts,depth:0},stream=readdirp(root,options2);return this._streams.add(stream),stream.once(STR_CLOSE,()=>{stream=void 0}),stream.once(STR_END,()=>{stream&&(this._streams.delete(stream),stream=void 0)}),stream}};chokidar_default={watch,FSWatcher}}});var watcher_exports={};__export(watcher_exports,{ChangeBatcher:()=>ChangeBatcher,RELEVANT_EVENTS:()=>RELEVANT_EVENTS,chokidarWatcher:()=>chokidarWatcher,realTimers:()=>realTimers});var RELEVANT_EVENTS,chokidarWatcher,realTimers,ChangeBatcher,init_watcher=__esm({"../sous-plugin-build/src/watch/watcher.ts"(){"use strict";init_paths();RELEVANT_EVENTS=new Set(["add","change","unlink"]),chokidarWatcher=async(paths,options2,onEvent)=>{let{default:chokidar}=await Promise.resolve().then(()=>(init_chokidar(),chokidar_exports)),watcher=chokidar.watch([...paths],{ignoreInitial:!0,persistent:!0,ignored:options2.ignored});return watcher.on("all",(event,file2)=>onEvent(event,file2)),{close:()=>watcher.close()}},realTimers={setTimeout:(callback,ms3)=>setTimeout(callback,ms3),clearTimeout:handle9=>clearTimeout(handle9)},ChangeBatcher=class{constructor(set2,globs,debounceMs,onBatch,timers=realTimers){this.set=set2;this.globs=globs;this.debounceMs=debounceMs;this.onBatch=onBatch;this.timers=timers}files=[];full=!1;listed=[];fullOtherwise=!1;timer;handle(event,file2){if(!RELEVANT_EVENTS.has(event))return;let classified=classifyChange(file2,this.set,this.globs),relists=classified==="partial"&&changesListing(event,file2,this.set,this.globs),kind=relists?"full":classified;kind!=="ignored"&&(this.files.includes(file2)||this.files.push(file2),relists&&!this.listed.includes(file2)&&this.listed.push(file2),this.full||=kind==="full",this.fullOtherwise||=kind==="full"&&!relists,this.timer!==void 0&&this.timers.clearTimeout(this.timer),this.timer=this.timers.setTimeout(()=>this.flush(),this.debounceMs))}cancel(){this.timer!==void 0&&(this.timers.clearTimeout(this.timer),this.timer=void 0),this.files=[],this.full=!1,this.listed=[],this.fullOtherwise=!1}flush(){let reason=this.listed.length>0&&!this.fullOtherwise?`Files were added or removed where a compilation target's glob looks (${this.listed.join(", ")}), so the config lists other files; reloading settings and restarting watcher...`:void 0,batch={files:this.files,full:this.full,...reason===void 0?{}:{reason}};this.timer=void 0,this.files=[],this.full=!1,this.listed=[],this.fullOtherwise=!1,this.onBatch(batch)}}}});import path74 from"node:path";import{LogLevel as LogLevel14}from"@sous-io/sous-plugin-api";function merge2(first2,second){let files=[...first2.files,...second.files.filter(file2=>!first2.files.includes(file2))],reason=second.reason??first2.reason,details=second.reason===void 0?first2.details:second.details;return{files,full:first2.full||second.full,...reason===void 0?{}:{reason},...details===void 0?{}:{details}}}function message(error51){return error51 instanceof Error?error51.message:String(error51)}var DEFAULT_POLL_SECONDS,WatchSession,init_session=__esm({"../sous-plugin-build/src/watch/session.ts"(){"use strict";init_paths();init_watcher();init_schemas4();DEFAULT_POLL_SECONDS=300,WatchSession=class{constructor(options2){this.options=options2;this.timers=options2.timers??realTimers,this.done=new Promise(resolve4=>{this.resolveDone=resolve4})}done;builds=0;failed=0;stopped=!1;busy;pending;watcher;batcher;lastSet;pollTimer;resolveDone;timers;get ctx(){return this.options.ctx}async start(){await this.openWatcher(!0),this.schedulePoll()}trigger(reason,details){this.enqueue({files:[],full:!0,reason,...details===void 0?{}:{details}})}async stop(stoppedBy="closed"){this.stopped||(this.stopped=!0,this.pending=void 0,this.batcher?.cancel(),this.pollTimer!==void 0&&this.timers.clearTimeout(this.pollTimer),await this.closeWatcher(),await this.busy,this.resolveDone({builds:this.builds,failed:this.failed,stoppedBy}))}async openWatcher(first2){let ctx=this.ctx,globs=ctx.services.get("host.globs"),set2;try{set2=watchSet(ctx.config,ctx.project,globs,{cwd:this.options.cwd,ignored:this.ignoredFiles()})}catch(error51){if(first2||!this.lastSet)throw error51;ctx.reporter.problem("Sous could not work out what to watch from the new config, so it keeps watching what it watched before.",{cause:message(error51)},LogLevel14.Error),set2=this.lastSet}this.lastSet=set2;let debounceMs=ctx.config.get("watch")?.debounceMs??DEFAULT_DEBOUNCE_MS,batcher=new ChangeBatcher(set2,globs,debounceMs,batch=>this.onBatch(batch),this.timers),ignored=new Set(set2.ignored.map(file2=>path74.resolve(file2))),paths=pathsToWatch(set2,globs);this.batcher=batcher,this.watcher=await this.options.createWatcher(paths,{ignored:file2=>ignored.has(path74.resolve(file2))},(event,file2)=>batcher.handle(event,file2)),ctx.reporter.notice(`Watching ${set2.files.length+set2.globs.length+set2.fullRebuildPaths.length} pattern(s) for changes...`)}async closeWatcher(){let watcher=this.watcher;this.watcher=void 0,this.batcher?.cancel(),await watcher?.close()}ignoredFiles(){let services=this.ctx.services,files=[services.get("build.pid").path()];return services.has("compiler.state")&&files.push(services.get("compiler.state").path()),files}onBatch(batch){this.enqueue({files:batch.files,full:batch.full,...batch.reason===void 0?{}:{reason:batch.reason}})}enqueue(trigger){this.stopped||(this.pending=this.pending?merge2(this.pending,trigger):trigger,this.busy||(this.busy=this.drain().finally(()=>{this.busy=void 0})))}async drain(){for(;this.pending&&!this.stopped;){let trigger=this.pending;this.pending=void 0,await this.run(trigger)}}async run(trigger){let ctx=this.ctx;if(await ctx.emit("build.files-changed",{files:trigger.files,full:trigger.full}),trigger.full){let why2=trigger.reason??`Config changed (${trigger.files.join(", ")}), reloading settings and restarting watcher...`;trigger.details===void 0?ctx.reporter.notice(why2):ctx.reporter.list(trigger.details,{title:why2},LogLevel14.Notice),await this.closeWatcher(),ctx.configChanged()}else ctx.reporter.notice(`Change detected: ${trigger.files.join(", ")}`);try{let result=await this.submitBuild(trigger.full?void 0:trigger.files);this.builds+=1,result.ok||(this.failed+=1)}catch(error51){this.builds+=1,this.failed+=1,trigger.full?ctx.reporter.problem("Config reload failed; keeping the last-good config.",{cause:message(error51),hint:"Fix the config and save again to retry."},LogLevel14.Error):ctx.reporter.error(`Rebuild failed: ${message(error51)}`)}finally{trigger.full&&!this.stopped&&await this.openWatcher(!1)}}submitBuild(changedFiles){let{input}=this.options,ctx=this.ctx,flags={...input.strict?{strict:!0}:{},...input.rebuild?{rebuild:!0}:{},...input.dryRun?{dryRun:!0}:{},...changedFiles&&!input.rebuild?{changedFiles}:{}},ignoring={...input.ignoreFailedAssertions?{ignoreFailedAssertions:!0}:{},...input.ignoreFailedChecks?{ignoreFailedChecks:!0}:{}},io={reporter:ctx.reporter,prompter:ctx.prompter,globals:ctx.globals};return input.compileOnly?ctx.engine.submit({intent:"compile",input:flags},io).then(outputs=>outputs.toPlain()):ctx.engine.submit({intent:"build",input:{...flags,...ignoring,...input.noPrune?{noPrune:!0}:{}}},io).then(outputs=>outputs.toPlain())}pollSeconds(){if(this.options.input.compileOnly)return 0;let config2=this.ctx.config;return this.options.input.pollSeconds??config2.get("watch")?.pollSeconds??config2.get("store")?.watchPollSeconds??DEFAULT_POLL_SECONDS}schedulePoll(){let seconds=this.pollSeconds();seconds<=0||this.stopped||(this.pollTimer=this.timers.setTimeout(()=>{this.poll().finally(()=>this.schedulePoll())},seconds*1e3))}async poll(){if(this.stopped||this.busy)return;let ctx=this.ctx;try{let prepared=(await ctx.engine.submit({intent:"build.prepare",input:{}},{reporter:ctx.reporter,prompter:ctx.prompter,globals:ctx.globals})).toPlain();if(prepared.locked.unchanged)return;let moved=prepared.locked.updated.map(change=>`${change.key} moved from ${change.from??"?"} to ${change.to??"?"}.`);this.trigger("A newer recipe version arrived upstream.",moved)}catch(error51){ctx.reporter.problem(`Sous could not check upstream for newer recipes; it tries again in ${this.pollSeconds()} seconds.`,{cause:message(error51)})}}}}});var intent_exports={};__export(intent_exports,{STOP_SIGNALS:()=>STOP_SIGNALS,createWatchHandler:()=>createWatchHandler,processSignals:()=>processSignals});import{IntentOutputs as IntentOutputs15}from"@sous-io/sous-plugin-api";function createWatchHandler(options2){return async(input,ctx)=>{let pid=ctx.services.get("build.pid"),recorded=pid.read();if(recorded!==void 0&&recorded!==process.pid&&pid.isRunning())throw watcherRunningError(projectLabel(ctx.project,pid.path()),recorded,pid.path());pid.write();let session=new WatchSession({ctx,input,createWatcher:options2.createWatcher,cwd:options2.cwd?.()??ctx.cwd,...options2.timers?{timers:options2.timers}:{}}),onSignal=()=>{session.stop("signal")};for(let signal of STOP_SIGNALS)options2.signals.on(signal,onSignal);try{try{await session.start()}catch(error51){throw await session.stop("error"),error51}return options2.onSession?.(session),ctx.reporter.notice("Watching for changes. Press Ctrl+C to stop."),IntentOutputs15.of(await session.done)}finally{for(let signal of STOP_SIGNALS)options2.signals.off(signal,onSignal);pid.remove()}}}var STOP_SIGNALS,processSignals,init_intent=__esm({"../sous-plugin-build/src/watch/intent.ts"(){"use strict";init_build();init_pid();init_session();STOP_SIGNALS=["SIGINT","SIGTERM"],processSignals={on:(signal,listener)=>{process.on(signal,listener)},off:(signal,listener)=>{process.off(signal,listener)}}}});var launch_exports={};__export(launch_exports,{handle:()=>handle2,launchable:()=>launchable,meant:()=>meant});import{ConfigError as ConfigError47,IntentOutputs as IntentOutputs16,NotFoundError as NotFoundError9,SousError as SousError31}from"@sous-io/sous-plugin-api";function launchable(ctx){return ctx.entities.list("harness").filter(harness=>typeof harness.launch=="function").map(harness=>harness.id)}function meant(id,available){let close=available.filter(candidate=>candidate.startsWith(`${id}-`));return close.length===0?[]:[`Did you mean: ${close.map(candidate=>`sous launch ${candidate}`).join(", or ")}`]}async function handle2(input,ctx){let[id,...passThrough]=input.tool;if(id===void 0)throw new ConfigError47("Name the tool to launch, such as: sous launch claude-code",{details:[`Available tools: ${launchable(ctx).join(", ")||"(none)"}`]});let harness=ctx.entities.get("harness",id);if(harness?.launch===void 0){let where3=ctx.project?.configPath?` in ${ctx.project.configPath}`:"";throw new NotFoundError9("harness",id,`Tool '${id}' not found${where3}.`,{details:[...meant(id,launchable(ctx)),`Available tools: ${launchable(ctx).join(", ")||"(none)"}`]})}let build2,last2,sessions=0;do{if(!input.noBuild&&(build2=(await ctx.run("build")).toPlain(),!build2.ok))throw new ConfigError47(`The build failed, so ${id} was not started. Fix the errors listed above, or pass --no-build to start it with the outputs as they are.`);sessions++,await ctx.emit("harnesses.launched",{harness:id,args:passThrough,session:sessions}),ctx.reporter.notice(`Launching ${id}`);try{last2=await harness.launch(passThrough,ctx)}catch(error51){throw error51 instanceof SousError31?error51:new SousError31(`Failed to launch '${id}': ${error51 instanceof Error?error51.message:String(error51)}`,{cause:error51})}input.continuous&&await new Promise(resolve4=>setTimeout(resolve4,RESTART_DELAY_MS))}while(input.continuous);return IntentOutputs16.of({harness:id,last:last2,sessions,...build2===void 0?{}:{build:build2}})}var RESTART_DELAY_MS,init_launch=__esm({"../sous-plugin-harnesses/src/launch.ts"(){"use strict";RESTART_DELAY_MS=150}});var run_headless_exports={};__export(run_headless_exports,{handle:()=>handle3});import{ConfigError as ConfigError48,IntentOutputs as IntentOutputs17,NotFoundError as NotFoundError10}from"@sous-io/sous-plugin-api";async function handle3(input,ctx){let capable=ctx.entities.list("harness").filter(harness2=>typeof harness2.runHeadless=="function"),names2=capable.map(harness2=>harness2.id).join(", ")||"(none)",harness=input.harness===void 0?void 0:ctx.entities.get("harness",input.harness);if(input.harness===void 0){if(capable.length!==1)throw new ConfigError48(capable.length===0?"No harness can run headless.":"Several harnesses can run headless; name one with --harness.",{details:[`Harnesses that can: ${names2}`]});harness=capable[0]}if(harness===void 0)throw new NotFoundError10("harness",input.harness,`No harness named '${input.harness}'.`,{details:[`Harnesses that can run headless: ${names2}`]});if(harness.runHeadless===void 0)throw new ConfigError48(`The harness '${harness.id}' cannot run headless.`,{details:[`Harnesses that can: ${names2}`]});let run=await harness.runHeadless({prompt:input.prompt,...input.cwd===void 0?{}:{cwd:input.cwd},...input.model===void 0?{}:{model:input.model},...input.timeoutMs===void 0?{}:{timeoutMs:input.timeoutMs}},ctx);if(!input.transcript)return IntentOutputs17.of({run});if(harness.readTranscript===void 0)throw new ConfigError48(`The harness '${harness.id}' cannot read a transcript.`);return IntentOutputs17.of({run,transcript:await harness.readTranscript(run,ctx)})}var init_run_headless=__esm({"../sous-plugin-harnesses/src/run-headless.ts"(){"use strict"}});import path76 from"node:path";import{commandVariables as commandVariables4,IntentOutput as IntentOutput13,IntentOutputs as IntentOutputs18,ItemList as ItemList4,ReportEntryStyle as ReportEntryStyle8,TextBlock as TextBlock8}from"@sous-io/sous-plugin-api";function toolsFrom(ctx){let services=ctx.services,lazy2=get=>{let value,made=!1;return()=>(made||(value=get(),made=!0),value)},git2=lazy2(()=>services.get("git.runner")),manifests=lazy2(()=>services.get("formats.manifests")),recipeManifest=lazy2(()=>services.get("formats.recipe-manifest")),repoManifest=lazy2(()=>services.get("formats.repo-manifest")),indexFile=lazy2(()=>services.get("formats.index-file")),hash2=lazy2(()=>services.get("formats.recipe-hash")),refs=lazy2(()=>services.get("refs.resolver")),format3=lazy2(()=>services.get("refs.format")),locations=lazy2(()=>services.get("refs.locations")),names2=lazy2(()=>services.get("variables.names")),declarations=lazy2(()=>services.has("recipes.declarations")?services.get("recipes.declarations"):void 0);return{get git(){return git2()},get manifests(){return manifests()},get recipeManifest(){return recipeManifest()},get repoManifest(){return repoManifest()},get indexFile(){return indexFile()},get hash(){return hash2()},get refs(){return refs()},get format(){return format3()},get locations(){return locations()},get declarations(){return declarations()},get names(){return names2()},entities:ctx.entities,env:ctx.env,reporter:ctx.reporter,prompter:ctx.prompter,results:[],commandVariables:extra=>commandVariables4(ctx,extra),sousVersion:ctx.engine.app.version,hostContext:()=>({plugin:ctx.plugin,config:ctx.config,services:ctx.services,entities:ctx.entities,project:ctx.project,env:ctx.env,reporter:ctx.reporter}),links:()=>ctx.project!==void 0&&services.has("recipes.links")?services.get("recipes.links"):void 0,picker:()=>services.has("refs.picker")?services.get("refs.picker"):void 0,cloneDirectories:()=>{let directories=[];return ctx.project!==void 0&&directories.push(path76.join(ctx.project.sousDir,PROJECT_REPOS_DIRNAME2)),services.has("host.sous-home")&&directories.push(services.get("host.sous-home").paths(ctx.env).repos),directories}}}function outputsOf(tools,data,options2={}){return new IntentOutputs18([...tools.results,new IntentOutput13({data})],options2)}function textOutput(text,style){return new IntentOutput13({result:new TextBlock8(text),...style===void 0?{}:{style}})}function listOutput2(items2,options2={}){return new IntentOutput13({...options2.heading===void 0?{}:{title:options2.heading},result:new ItemList4(items2,{...options2.title===void 0?{}:{title:options2.title},...options2.footer===void 0?{}:{footer:options2.footer}}),style:ReportEntryStyle8.List})}var PROJECT_REPOS_DIRNAME2,init_tools2=__esm({"../sous-plugin-authoring/src/tools.ts"(){"use strict";PROJECT_REPOS_DIRNAME2="repos"}});function hasErrors(problems){return problems.some(problem=>problem.level==="error")}function errorsIn(problems){return problems.filter(problem=>problem.level==="error")}function warningsIn(problems){return problems.filter(problem=>problem.level==="warning")}function describeError3(error51){return error51 instanceof Error?error51.message:String(error51)}function describeCount(count2,noun2){return`${count2} ${noun2}${count2===1?"":"s"}`}function renderProblems(problems){return problems.map(problem=>` ${problem.where}: ${problem.message}`).join(`
468
468
  `)}var init_problems=__esm({"../sous-plugin-authoring/src/shared/problems.ts"(){"use strict"}});import fs58 from"node:fs";import path77 from"node:path";import{ConfigError as ConfigError49}from"@sous-io/sous-plugin-api";function findRepoRoot(tools,startDir){let found=repoRootAround(tools,startDir);if(found!==void 0)return found;throw new ConfigError49(`${path77.resolve(startDir)} is not inside a sous recipe repository.
469
469
  A recipe repository has a '${REPO_MANIFEST_FILE}' file at its root, and sous looked in that directory and in every directory above it.
@@ -989,12 +989,12 @@ SKILLS_ROOT=${PROJECT_SKILLS_ROOT}
989
989
  # with a comment saying what it is for.
990
990
  `}var SOUS_DIR_NAME,CONFD_DIR_NAME,ENV_DEFAULTS_NAME2,ENV_LOCAL_NAME3,CONFIG_FILE_NAME,MEMORIES_SOURCE_RELATIVE_PATH,MEMORIES_DEFAULT_LINES,STARTER_MEMORY_RELATIVE_PATH,ROOT_IGNORE_LINES,PROJECT_SKILLS_ROOT,init_templates2=__esm({"../sous-plugin-init/src/templates.ts"(){"use strict";SOUS_DIR_NAME=".sous",CONFD_DIR_NAME="conf.d",ENV_DEFAULTS_NAME2=".env",ENV_LOCAL_NAME3=".env.local",CONFIG_FILE_NAME="sous.config.jsonc",MEMORIES_SOURCE_RELATIVE_PATH="MEMORIES.tpl.md",MEMORIES_DEFAULT_LINES=["@memories/**/*.md","@#memories/**/*.md"],STARTER_MEMORY_RELATIVE_PATH="memories/project.tpl.md",ROOT_IGNORE_LINES=["/.claude/rules/SOUS-MEMORIES.md","/.claude/skills/","/.claude/agents/","/AGENTS.override.md"];PROJECT_SKILLS_ROOT=`${SOUS_DIR_NAME}/skills`}});import fs66 from"node:fs";import path89 from"node:path";function posix2(file2){return file2.split(path89.sep).join("/")}function inside(root,file2){let relative4=path89.relative(root,file2);return relative4!==""&&!relative4.startsWith("..")&&!path89.isAbsolute(relative4)}function findReferences(content){let found=[],fence=null;for(let[index,line]of content.split(`
991
991
  `).entries()){if(fence!==null){let close=FENCE_CLOSE.exec(line);close&&close[1][0]===fence[0]&&close[1].length>=fence.length&&(fence=null);continue}let open2=FENCE_OPEN2.exec(line);if(open2){fence=open2[1];continue}let trimmed=line.trim();if(/^@\S+$/.test(trimmed)){found.push({line:index,whole:!0,token:trimmed.slice(1),start:line.indexOf("@")+1});continue}let code=[];for(let span of line.matchAll(/`+[^`]*`+/g))code.push([span.index,span.index+span[0].length]);for(let mention of line.matchAll(/(^|[\s(])@([^\s`()[\]<>"']+)/g)){let at2=mention.index+mention[1].length;if(code.some(([from,to])=>at2>=from&&at2<to))continue;let token=mention[2].replace(/[.,;:!?]+$/,"");token!==""&&found.push({line:index,whole:!1,token,start:at2+1})}}return found}function resolveReference(token,fromDir){if(/^[~#$]/.test(token)||/[*?[\]{}]/.test(token)||token.includes("${"))return;let file2=path89.isAbsolute(token)?token:path89.resolve(fromDir,token);try{return fs66.statSync(file2).isFile()?file2:void 0}catch{return}}function isMarkdown(token){return token.toLowerCase().endsWith(".md")}function onlyPointsAt(content,other){return content.split(`
992
- `).filter(line=>line.trim()!=="").length<=POINTER_MAX_LINES&&content.replace(/\s+/g,"").length<=POINTER_MAX_CHARACTERS&&content.includes(other)}function scanInstructions(root,sousDir){let present=INSTRUCTION_FILES.map(name=>({name,source:path89.join(root,name)})).filter(({source})=>{try{return fs66.statSync(source).isFile()}catch{return!1}}),instructions=[],skipped=[],real3=file2=>fs66.realpathSync(file2),text=file2=>fs66.readFileSync(file2,"utf8");for(let{name,source}of present){let other=present.find(candidate=>candidate.name!==name);if(other!==void 0){if(fs66.lstatSync(source).isSymbolicLink()&&real3(source)===real3(other.source)){skipped.push({source,reason:`a link to ${other.name}`});continue}if(instructions.find(candidate=>candidate.name===other.name)!==void 0&&text(source)===text(other.source)){skipped.push({source,reason:`the same text as ${other.name}`});continue}if(onlyPointsAt(text(source),other.name)&&!onlyPointsAt(text(other.source),name)){skipped.push({source,reason:`it only points at ${other.name}`});continue}}instructions.push({name,source,dest:path89.join(sousDir,IMPORTED_DIR,name)})}return{instructions,skipped}}function scanSkills(root,sousDir){let directory=path89.join(root,CLAUDE_SKILLS_DIR);return fs66.existsSync(directory)?fs66.readdirSync(directory,{withFileTypes:!0}).filter(entry=>entry.isDirectory()).map(entry=>entry.name).sort().map(name=>({name,source:path89.join(directory,name),dest:path89.join(sousDir,PROJECT_SKILLS_DIR,name)})):[]}function scanImport(root,sousDir){let{instructions,skipped}=scanInstructions(root,sousDir),includes=new Map,instructionSources=new Set(INSTRUCTION_FILES.map(name=>path89.join(root,name))),queue=instructions.map(instruction=>instruction.source);for(;queue.length>0;){let file2=queue.shift(),content=fs66.readFileSync(file2,"utf8");for(let reference of findReferences(content)){if(!reference.whole||!isMarkdown(reference.token))continue;let target=resolveReference(reference.token,path89.dirname(file2));if(target===void 0||instructionSources.has(target))continue;let known=includes.get(target);if(known!==void 0){known.includedBy.includes(file2)||known.includedBy.push(file2);continue}let included={source:target,relative:posix2(path89.relative(root,target)),includedBy:[file2]};inside(root,target)?path89.basename(target).toLowerCase()==="readme.md"&&(included.pinned="a README stays where people look for it"):included.pinned="it is outside the project",includes.set(target,included),queue.push(target)}}return{root,sousDir,instructions,skipped,includes:[...includes.values()],skills:scanSkills(root,sousDir)}}async function settleFates(scan,answer2,choose2){let fates=new Map,stays=file2=>fates.get(file2)==="leave";for(let file2 of scan.includes){if(file2.pinned!==void 0){fates.set(file2.source,"leave");continue}let fate=answer2==="choose"?await choose2(file2):answer2;fate==="move"&&file2.includedBy.some(stays)&&(fate="copy"),fates.set(file2.source,fate)}return fates}function finalPlace(scan,fates,file2){let instruction=scan.instructions.find(candidate=>candidate.source===file2);if(instruction!==void 0)return instruction.dest;let fate=fates.get(file2);return fate==="move"||fate==="copy"?path89.join(scan.sousDir,INCLUDES_DIR,path89.relative(scan.root,file2)):file2}function fromRoot(root,file2){return inside(root,file2)?posix2(path89.relative(root,file2)):file2}function looksLikeInclude(line){if(!/^@\S+$/.test(line))return!1;let word=line.slice(1);return word.includes("/")||/\.md\b/.test(word)||/^[~#.$]/.test(word)}function rewriteReferences(scan,fates,source,dest,content){let lines3=content.split(`
993
- `),turnedOff=[],references2=findReferences(content),importedInstructions=new Set(scan.instructions.map(instruction=>instruction.source));for(let reference of[...references2].reverse()){let line=lines3[reference.line],target=resolveReference(reference.token,path89.dirname(source));if(reference.whole){if(target===void 0){(isMarkdown(reference.token)||looksLikeInclude(line.trim()))&&(lines3[reference.line]=`<!-- ${line.trim()} (sous init turned this include off: no such file) -->`,turnedOff.push(reference.token));continue}if(isMarkdown(reference.token)&&importedInstructions.has(target)){lines3[reference.line]="";continue}if(isMarkdown(reference.token)){let place=finalPlace(scan,fates,target),rewritten3=place!==target?posix2(path89.relative(path89.dirname(dest),place)):inside(scan.root,target)?`#project/${posix2(path89.relative(scan.root,target))}`:target;lines3[reference.line]=`@${rewritten3}`;continue}let rewritten2=`@${fromRoot(scan.root,finalPlace(scan,fates,target))}`;lines3[reference.line]=looksLikeInclude(rewritten2)?`See ${rewritten2}`:rewritten2;continue}if(target===void 0)continue;let rewritten=fromRoot(scan.root,finalPlace(scan,fates,target));lines3[reference.line]=line.slice(0,reference.start)+rewritten+line.slice(reference.start+reference.token.length)}return{content:lines3.join(`
992
+ `).filter(line=>line.trim()!=="").length<=POINTER_MAX_LINES&&content.replace(/\s+/g,"").length<=POINTER_MAX_CHARACTERS&&content.includes(other)}function scanInstructions(root,sousDir){let present=INSTRUCTION_FILES.map(name=>({name,source:path89.join(root,name)})).filter(({source})=>{try{return fs66.statSync(source).isFile()}catch{return!1}}),instructions=[],skipped=[],real3=file2=>fs66.realpathSync(file2),text=file2=>fs66.readFileSync(file2,"utf8");for(let{name,source}of present){let other=present.find(candidate=>candidate.name!==name);if(other!==void 0){if(fs66.lstatSync(source).isSymbolicLink()&&real3(source)===real3(other.source)){skipped.push({source,reason:`a link to ${other.name}`});continue}if(instructions.find(candidate=>candidate.name===other.name)!==void 0&&text(source)===text(other.source)){skipped.push({source,reason:`the same text as ${other.name}`});continue}if(onlyPointsAt(text(source),other.name)&&!onlyPointsAt(text(other.source),name)){skipped.push({source,reason:`it only points at ${other.name}`});continue}}instructions.push({name,source,dest:path89.join(sousDir,IMPORTED_DIR,name)})}return{instructions,skipped}}function scanSkills(root,sousDir){let directory=path89.join(root,CLAUDE_SKILLS_DIR);return fs66.existsSync(directory)?fs66.readdirSync(directory,{withFileTypes:!0}).filter(entry=>entry.isDirectory()).map(entry=>entry.name).sort().map(name=>({name,source:path89.join(directory,name),dest:path89.join(sousDir,PROJECT_SKILLS_DIR,name)})):[]}function scanImport(root,sousDir){let{instructions,skipped}=scanInstructions(root,sousDir),includes=new Map,instructionSources=new Set(INSTRUCTION_FILES.map(name=>path89.join(root,name))),queue=instructions.map(instruction=>instruction.source);for(;queue.length>0;){let file2=queue.shift(),content=fs66.readFileSync(file2,"utf8");for(let reference of findReferences(content)){if(!reference.whole||!isMarkdown(reference.token))continue;let target=resolveReference(reference.token,path89.dirname(file2));if(target===void 0||instructionSources.has(target))continue;let known=includes.get(target);if(known!==void 0){known.includedBy.includes(file2)||known.includedBy.push(file2);continue}let included={source:target,relative:posix2(path89.relative(root,target)),includedBy:[file2]};inside(root,target)?path89.basename(target).toLowerCase()==="readme.md"&&(included.pinned="a README stays where people look for it"):included.pinned="it is outside the project",includes.set(target,included),queue.push(target)}}return{root,sousDir,instructions,skipped,includes:[...includes.values()],skills:scanSkills(root,sousDir)}}async function settleFates(scan,answer2,choose2){let fates=new Map,stays=file2=>fates.get(file2)==="leave";for(let file2 of scan.includes){if(file2.pinned!==void 0){fates.set(file2.source,"leave");continue}let fate=answer2==="choose"?await choose2(file2):answer2;fate==="move"&&file2.includedBy.some(stays)&&(fate="copy"),fates.set(file2.source,fate)}return fates}function finalPlace(scan,fates,file2){let instruction=scan.instructions.find(candidate=>candidate.source===file2);if(instruction!==void 0)return instruction.dest;let fate=fates.get(file2);return fate==="move"||fate==="copy"?path89.join(scan.sousDir,INCLUDES_DIR,path89.relative(scan.root,file2)):file2}function fromRoot(root,file2){return posix2(inside(root,file2)?path89.relative(root,file2):file2)}function looksLikeInclude(line){if(!/^@\S+$/.test(line))return!1;let word=line.slice(1);return word.includes("/")||/\.md\b/.test(word)||/^[~#.$]/.test(word)}function rewriteReferences(scan,fates,source,dest,content){let lines3=content.split(`
993
+ `),turnedOff=[],references2=findReferences(content),importedInstructions=new Set(scan.instructions.map(instruction=>instruction.source));for(let reference of[...references2].reverse()){let line=lines3[reference.line],target=resolveReference(reference.token,path89.dirname(source));if(reference.whole){if(target===void 0){(isMarkdown(reference.token)||looksLikeInclude(line.trim()))&&(lines3[reference.line]=`<!-- ${line.trim()} (sous init turned this include off: no such file) -->`,turnedOff.push(reference.token));continue}if(isMarkdown(reference.token)&&importedInstructions.has(target)){lines3[reference.line]="";continue}if(isMarkdown(reference.token)){let place=finalPlace(scan,fates,target),rewritten3=place!==target?posix2(path89.relative(path89.dirname(dest),place)):inside(scan.root,target)?`#project/${posix2(path89.relative(scan.root,target))}`:posix2(target);lines3[reference.line]=`@${rewritten3}`;continue}let rewritten2=`@${fromRoot(scan.root,finalPlace(scan,fates,target))}`;lines3[reference.line]=looksLikeInclude(rewritten2)?`See ${rewritten2}`:rewritten2;continue}if(target===void 0)continue;let rewritten=fromRoot(scan.root,finalPlace(scan,fates,target));lines3[reference.line]=line.slice(0,reference.start)+rewritten+line.slice(reference.start+reference.token.length)}return{content:lines3.join(`
994
994
  `),turnedOff:turnedOff.reverse()}}function backupFolder(sousDir,now){let pad2=value=>String(value).padStart(2,"0"),day=`${now.getFullYear()}-${pad2(now.getMonth()+1)}-${pad2(now.getDate())}`,time3=`${pad2(now.getHours())}${pad2(now.getMinutes())}-${pad2(now.getSeconds())}`;return path89.join(sousDir,BACKUPS_DIR,day,time3)}function filesUnder(directory){return fs66.readdirSync(directory,{withFileTypes:!0,recursive:!0}).filter(entry=>entry.isFile()).map(entry=>path89.join(entry.parentPath,entry.name))}function applyImport(scan,fates,options2){let steps=[],written=[],removed=[],untrack2=[],backups=backupFolder(scan.sousDir,options2.now??new Date),write=(file2,content)=>{options2.dryRun||(fs66.mkdirSync(path89.dirname(file2),{recursive:!0}),fs66.writeFileSync(file2,content,"utf8")),written.push(file2)},backUp=file2=>{let backup=path89.join(backups,path89.relative(scan.root,file2));return options2.dryRun||(fs66.mkdirSync(path89.dirname(backup),{recursive:!0}),fs66.cpSync(file2,backup,{recursive:!0})),backup},copyOver=(source,dest,kind,note)=>{let rewritten=rewriteReferences(scan,fates,source,dest,fs66.readFileSync(source,"utf8"));write(dest,rewritten.content);for(let token of rewritten.turnedOff)steps.push({kind:"turned-off",source,note:`the include @${token} names no file, so it is now a comment`});return{kind,source,dest,...note===void 0?{}:{note}}},moveAway=file2=>{let backup=backUp(file2);return options2.dryRun||fs66.rmSync(file2),removed.push(file2),untrack2.push(posix2(path89.relative(scan.root,file2))),backup};for(let skip of scan.skipped){let backup=moveAway(skip.source);steps.push({kind:"skipped",source:skip.source,backup,note:skip.reason})}for(let instruction of scan.instructions){let step=copyOver(instruction.source,instruction.dest,"imported");steps.push({...step,backup:moveAway(instruction.source)})}for(let file2 of scan.includes){let fate=fates.get(file2.source)??"leave";if(fate==="leave"){steps.push({kind:"left",source:file2.source,...file2.pinned===void 0?{}:{note:`left where it is: ${file2.pinned}`}});continue}let dest=finalPlace(scan,fates,file2.source),step=copyOver(file2.source,dest,fate==="move"?"moved":"copied");if(fate==="move"){let backup=backUp(file2.source);options2.dryRun||fs66.rmSync(file2.source),removed.push(file2.source),steps.push({...step,backup})}else steps.push(step)}for(let skill of scan.skills){if(fs66.existsSync(skill.dest)){steps.push({kind:"skipped",source:skill.source,note:`${posix2(path89.relative(scan.root,skill.dest))} already exists`});continue}for(let file2 of filesUnder(skill.source))written.push(path89.join(skill.dest,path89.relative(skill.source,file2)));let backup=backUp(skill.source);options2.dryRun||(fs66.mkdirSync(path89.dirname(skill.dest),{recursive:!0}),fs66.cpSync(skill.source,skill.dest,{recursive:!0}),fs66.rmSync(skill.source,{recursive:!0})),removed.push(skill.source),untrack2.push(posix2(path89.relative(scan.root,skill.source))),steps.push({kind:"moved",source:skill.source,dest:skill.dest,backup})}return{steps,written,removed,untrack:untrack2,nothingImported:scan.instructions.length===0}}var INSTRUCTION_FILES,IMPORTED_DIR,INCLUDES_DIR,PROJECT_SKILLS_DIR,CLAUDE_SKILLS_DIR,BACKUPS_DIR,FENCE_OPEN2,FENCE_CLOSE,POINTER_MAX_CHARACTERS,POINTER_MAX_LINES,init_import=__esm({"../sous-plugin-init/src/import.ts"(){"use strict";INSTRUCTION_FILES=["CLAUDE.md","AGENTS.md"],IMPORTED_DIR="memories/imported",INCLUDES_DIR="includes",PROJECT_SKILLS_DIR="skills",CLAUDE_SKILLS_DIR=".claude/skills",BACKUPS_DIR="backups",FENCE_OPEN2=/^ {0,3}(`{3,}|~{3,})/,FENCE_CLOSE=/^ {0,3}(`{3,}|~{3,})[ \t]*$/,POINTER_MAX_CHARACTERS=400,POINTER_MAX_LINES=3}});import fs67 from"node:fs";import path90 from"node:path";import{ConfigError as ConfigError58}from"@sous-io/sous-plugin-api";function planPackageJson(projectRoot,packageName,version2){let file2=path90.join(projectRoot,"package.json");if(!fs67.existsSync(file2))return{outcome:{kind:"no-package-json"}};let raw2=fs67.readFileSync(file2,"utf8"),parsed;try{parsed=JSON.parse(raw2)}catch(error51){throw new ConfigError58(`'sous init' would add ${packageName} to ${file2}, but could not read it as JSON.`,{details:[error51.message,"Fix the file, or run 'sous init' in a directory without a package.json."],cause:error51})}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new ConfigError58(`'sous init' would add ${packageName} to ${file2}, but it does not hold a JSON object.`);let pkg=parsed;for(let section2 of["dependencies","devDependencies"]){let deps=pkg[section2];if(typeof deps=="object"&&deps!==null&&packageName in deps)return{file:file2,outcome:{kind:"already-declared",section:section2,range:String(deps[packageName])}}}return{file:file2,contents:serialize(raw2,{...pkg,devDependencies:withDevDependency(pkg,packageName,version2)}),outcome:{kind:"added",section:"devDependencies",range:version2}}}function withDevDependency(pkg,name,range3){let existing=typeof pkg.devDependencies=="object"&&pkg.devDependencies!==null?pkg.devDependencies:{};return Object.fromEntries(Object.entries({...existing,[name]:range3}).sort(([a],[b])=>a<b?-1:a>b?1:0))}function serialize(raw2,pkg){let indent2=raw2.match(/^(\s+)"/m)?.[1]??" ",newline=raw2.endsWith(`
995
995
  `)?`
996
996
  `:"";return JSON.stringify(pkg,null,indent2)+newline}function declares(pkg,name){return["dependencies","devDependencies"].some(section2=>{let deps=pkg[section2];return typeof deps=="object"&&deps!==null&&name in deps})}function planHooksPackageJson(projectRoot,scriptName,huskyRange,compose){let file2=path90.join(projectRoot,"package.json"),raw2=fs67.readFileSync(file2,"utf8"),pkg;try{pkg=JSON.parse(raw2)}catch(error51){throw new ConfigError58(`'sous init hooks' would add a script to ${file2}, but could not read it as JSON.`,{details:[error51.message],cause:error51})}if(typeof pkg!="object"||pkg===null||Array.isArray(pkg))throw new ConfigError58(`'sous init hooks' would add a script to ${file2}, but it does not hold a JSON object.`);let scripts=typeof pkg.scripts=="object"&&pkg.scripts!==null?pkg.scripts:{},current=typeof scripts[scriptName]=="string"?scripts[scriptName]:void 0,composed=compose(current),huskyAdded=!declares(pkg,"husky"),next=pkg;return huskyAdded&&(next={...next,devDependencies:withDevDependency(next,"husky",huskyRange)}),composed!==void 0&&(next={...next,scripts:{...scripts,[scriptName]:composed}}),{file:file2,...next===pkg?{}:{contents:serialize(raw2,next)},huskyAdded,script:{name:scriptName,text:composed??current??"",changed:composed!==void 0}}}var init_package_json=__esm({"../sous-plugin-init/src/package-json.ts"(){"use strict"}});import fs68 from"node:fs";import path91 from"node:path";import{ConfigError as ConfigError59}from"@sous-io/sous-plugin-api";function isRecipeRepository(root){return REPO_MANIFEST_NAMES.some(name=>fs68.existsSync(path91.join(root,name)))}function sousDirFor(root){return path91.join(path91.resolve(root),SOUS_DIR_NAME)}function ancestors(start2){let found=[],directory=path91.resolve(start2);for(;;){found.push(directory);let parent=path91.dirname(directory);if(parent===directory)return found;directory=parent}}function assertNoExistingConfig(ctx,root){let existing=ctx.services.get("config-files.loader").findMain(sousDirFor(root));if(existing!==void 0)throw new ConfigError59(`${root} is already set up for sous.`,{details:[`${existing} exists, and sous will not overwrite it.`,"Edit that config instead, or run 'sous init' in another directory."]})}function findEnclosingProject(ctx,root){let loader=ctx.services.get("config-files.loader");for(let directory of ancestors(root).slice(1)){let configPath3=loader.findMain(sousDirFor(directory));if(configPath3!==void 0)return{root:directory,configPath:configPath3}}}async function scaffoldProject(ctx,options2){let identity2=ctx.services.get("host.package").identity(),root=path91.resolve(options2.root),sousDir=sousDirFor(root),configPath3=path91.join(sousDir,CONFIG_FILE_NAME),context={name:options2.name,sousVersion:identity2.version};assertNoExistingConfig(ctx,root);let dependency=planPackageJson(root,identity2.name,identity2.version),planned=[{file:configPath3,contents:buildConfigJsonc(context)},{file:path91.join(sousDir,MEMORIES_SOURCE_RELATIVE_PATH),contents:buildMemoriesSource()},...options2.starterMemory===!0?[{file:path91.join(sousDir,STARTER_MEMORY_RELATIVE_PATH),contents:isRecipeRepository(root)?buildRepoStarterMemory(context):buildStarterMemory(context)}]:[],{file:path91.join(sousDir,ENV_DEFAULTS_NAME2),contents:buildEnvDefaults(context)},{file:path91.join(sousDir,`${ENV_LOCAL_NAME3}.example`),contents:buildEnvLocalExample(context)}],files=[],kept=[];if(!options2.dryRun)for(let[kind,directory]of[["sous-dir",sousDir],["confd",path91.join(sousDir,CONFD_DIR_NAME)]]){let ensured=await ctx.services.get("host.directories").ensureKnown(kind,directory);files.push(...ensured.wrote.map(name=>path91.join(ensured.path,name)))}for(let{file:file2,contents}of planned){if(fs68.existsSync(file2)){kept.push(file2);continue}options2.dryRun||(fs68.mkdirSync(path91.dirname(file2),{recursive:!0}),fs68.writeFileSync(file2,contents,"utf8")),files.push(file2)}let ignore=await ctx.services.get("host.gitignore").write(path91.join(sousDir,".gitignore"),IGNORE_BLOCK_LINES,{dryRun:options2.dryRun});ignore.changed&&files.push(ignore.file);let rootIgnore=await ctx.services.get("host.gitignore").write(path91.join(root,".gitignore"),ROOT_IGNORE_LINES,{dryRun:options2.dryRun});rootIgnore.changed&&files.push(rootIgnore.file),dependency.contents!==void 0&&dependency.file!==void 0&&(options2.dryRun||fs68.writeFileSync(dependency.file,dependency.contents,"utf8"),files.push(dependency.file));let lockfile=stampMigratedVersion(ctx,sousDir,identity2.version,options2.dryRun);return lockfile!==void 0&&files.push(lockfile),!options2.dryRun&&!kept.includes(configPath3)&&await verifyScaffold2(ctx,configPath3),{sousDir,configPath:configPath3,files,kept,packageJson:dependency.outcome}}function stampMigratedVersion(ctx,sousDir,version2,dryRun4){let format3=ctx.services.get("formats.lockfile"),file2=path91.join(sousDir,LOCKFILE_NAME2),existing=fs68.existsSync(file2)?format3.parse(JSON.parse(fs68.readFileSync(file2,"utf8")),file2):format3.empty();if(existing.migratedVersion!==version2)return dryRun4||(fs68.mkdirSync(sousDir,{recursive:!0}),fs68.writeFileSync(file2,format3.stringify({...existing,migratedVersion:version2}),"utf8")),file2}async function verifyScaffold2(ctx,configPath3){try{await ctx.services.get("config-files.loader").load(configPath3)}catch(error51){throw new ConfigError59(`The config 'sous init' wrote at ${configPath3} does not load.`,{details:["This is a bug in sous; please report it. The loader said:",...(error51 instanceof Error?error51.message:String(error51)).split(`
997
- `).map(line=>` ${line}`)],cause:error51})}}var LOCKFILE_NAME2,IGNORE_BLOCK_LINES,REPO_MANIFEST_NAMES,init_scaffold2=__esm({"../sous-plugin-init/src/scaffold.ts"(){"use strict";init_package_json();init_templates2();LOCKFILE_NAME2="sous.lock.json",IGNORE_BLOCK_LINES=["sous.links.json","sous.state.json","sous.edits.json","sous.pid",ENV_LOCAL_NAME3,"repos/","backups/"],REPO_MANIFEST_NAMES=["sous.repo.yaml","sous.repo.yml","sous.repo.json","sous.repo.jsonc"]}});function scanContext(sous){return{plugin:sous.plugin.name,get config(){return sous.engine.config},services:sous.services,entities:sous.entities,project:sous.project,env:sous.env}}function scanContributor(sous){return{id:SCAN_CONTRIBUTOR2,monitors:["plugins.discover","plugins.load",{entities:"package-manager"}],async contribute(config2){if(config2.atPath("plugins.discover").valueOr("dependencies")!=="scan"||config2.project===void 0)return;let ctx=scanContext(sous),root=config2.project.root,load=config2.atPath("plugins.load"),known=new Set(load.valueOr([])),found=new Set;for(let manager of config2.entities("package-manager"))try{if(await manager.detect(root,ctx)===void 0)continue;for(let pkg of await manager.installed("project",root,ctx))pkg.isSousPlugin&&!known.has(pkg.name)&&found.add(pkg.name)}catch(error51){config2.warn(`${manager.id} could not list the installed packages: ${error51 instanceof Error?error51.message:String(error51)}`)}for(let name of[...found].sort())load.append(name)}}}var SCAN_CONTRIBUTOR2,init_scan=__esm({"../sous-plugin-update/src/scan.ts"(){"use strict";SCAN_CONTRIBUTOR2="update.scan"}});var package_default22,init_package8=__esm({"../sous-plugin-update/package.json"(){package_default22={name:"@sous-io/sous-plugin-update",version:"1.1.4",description:"Updating sous itself, installing plugins a recipe requires, the package-manager entity, scanning for installed plugins.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-host":"workspace:*",semver:"^7.8.5"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*","@types/semver":"^7.8.0"},engines:{node:">=22"}}}});import fs69 from"node:fs";import path92 from"node:path";function readPackageJson2(directory){try{let parsed=JSON.parse(fs69.readFileSync(path92.join(directory,"package.json"),"utf8"));return typeof parsed=="object"&&parsed!==null&&!Array.isArray(parsed)?parsed:void 0}catch{return}}function realpathOr2(target){try{return fs69.realpathSync(target)}catch{return target}}function versionOf(pkg){return typeof pkg?.version=="string"?pkg.version:UNKNOWN_VERSION}function declaredDependency(pkg){if(!(pkg===null||typeof pkg!="object"))for(let section2 of["devDependencies","dependencies"]){let block=pkg[section2];if(block===null||typeof block!="object")continue;let range3=block[PACKAGE_NAME2];if(typeof range3=="string")return{section:section2,range:range3}}}function ancestors2(start2){let found=[],directory=path92.resolve(start2);for(;;){found.push(directory);let parent=path92.dirname(directory);if(parent===directory)return found;directory=parent}}async function discoverInstalls(options2,ctx){let managers=ctx.entities.list("package-manager"),project=await findProjectInstall2(options2.cwd,managers,ctx),globals=await findGlobalInstalls(managers,ctx);return{...project===void 0?{}:{project},globals,running:classifyRunning(options2.ownRoot,project,globals)}}async function ownerOf(directory,managers,ctx){let answers=[];for(let entity of managers)try{let detection=await entity.detect(directory,ctx);detection!==void 0&&answers.push({entity,detection})}catch{}return answers.find(answer2=>answer2.detection.detected)??answers[0]}async function findProjectInstall2(cwd,managers,ctx){for(let directory of ancestors2(cwd)){let owner=await ownerOf(directory,managers,ctx);if(owner===void 0){let location=path92.join(directory,"node_modules",...PACKAGE_NAME2.split("/")),copy=readPackageJson2(location);if(copy?.name===PACKAGE_NAME2)return describeProject(directory,{supported:!1},{location,realPath:realpathOr2(location),installed:versionOf(copy)});continue}let packages;try{packages=await owner.entity.installed("project",directory,ctx)}catch{continue}let found=packages.find(candidate=>candidate.name===PACKAGE_NAME2);if(found===void 0)continue;let manager={supported:!0,id:owner.detection.id,entity:owner.entity,detected:owner.detection.detected,detection:owner.detection};return describeProject(directory,manager,{location:found.location,realPath:found.realPath,installed:found.version},found)}}function describeProject(projectRoot,manager,copy,found){let declared=found?.declared??declaredDependency(readPackageJson2(projectRoot)),detection=manager.supported?manager.detection:void 0,info={projectRoot,...copy,manager,workspaceRoot:detection?.workspaceRoot!==void 0&&realpathOr2(detection.workspaceRoot)===realpathOr2(projectRoot)};return declared!==void 0&&(info.declared=declared),detection?.pnpRoot!==void 0&&(info.pnpRoot=detection.pnpRoot),info}async function findGlobalInstalls(managers,ctx){let installs=[];for(let manager of managers){if(manager.globalInstallCommand===void 0)continue;let packages;try{packages=await manager.installed("global",void 0,ctx)}catch{continue}let found=packages.find(candidate=>candidate.name===PACKAGE_NAME2);found===void 0||installs.some(install=>install.realPath===found.realPath)||installs.push({manager,location:found.location,realPath:found.realPath,installed:found.version})}return installs}function classifyRunning(ownRoot2,project,globals){let realPath2=realpathOr2(ownRoot2),installed2=versionOf(readPackageJson2(ownRoot2));if(project!==void 0&&(project.realPath===realPath2||isPnpCopy(project,realPath2)))return{kind:"project",realPath:realPath2,installed:installed2};let global2=globals.find(install=>install.realPath===realPath2);if(global2!==void 0)return{kind:"global",manager:global2.manager.id,realPath:realPath2,installed:installed2};let slashed=realPath2.split(path92.sep).join("/");return slashed.includes("/_npx/")?{kind:"npx",realPath:realPath2,installed:installed2}:slashed.includes("/.volta/")?{kind:"volta",realPath:realPath2,installed:installed2}:{kind:"unknown",realPath:realPath2,installed:installed2}}function isPnpCopy(project,realPath2){if(project.pnpRoot===void 0)return!1;let relative4=path92.relative(path92.join(realpathOr2(project.pnpRoot),".yarn","unplugged"),realPath2);return relative4.length>0&&!relative4.startsWith("..")&&!path92.isAbsolute(relative4)}var PACKAGE_NAME2,UNKNOWN_VERSION,init_installs=__esm({"../sous-plugin-update/src/installs.ts"(){"use strict";PACKAGE_NAME2="@sous-io/sous",UNKNOWN_VERSION="unknown"}});import{ConfigError as ConfigError60}from"@sous-io/sous-plugin-api";function parseRegistryMetadata(text,source){let raw2;try{raw2=JSON.parse(text)}catch(error51){throw new ConfigError60(`The registry's answer from ${source} is not JSON.
997
+ `).map(line=>` ${line}`)],cause:error51})}}var LOCKFILE_NAME2,IGNORE_BLOCK_LINES,REPO_MANIFEST_NAMES,init_scaffold2=__esm({"../sous-plugin-init/src/scaffold.ts"(){"use strict";init_package_json();init_templates2();LOCKFILE_NAME2="sous.lock.json",IGNORE_BLOCK_LINES=["sous.links.json","sous.state.json","sous.edits.json","sous.pid",ENV_LOCAL_NAME3,"repos/","backups/"],REPO_MANIFEST_NAMES=["sous.repo.yaml","sous.repo.yml","sous.repo.json","sous.repo.jsonc"]}});function scanContext(sous){return{plugin:sous.plugin.name,get config(){return sous.engine.config},services:sous.services,entities:sous.entities,project:sous.project,env:sous.env}}function scanContributor(sous){return{id:SCAN_CONTRIBUTOR2,monitors:["plugins.discover","plugins.load",{entities:"package-manager"}],async contribute(config2){if(config2.atPath("plugins.discover").valueOr("dependencies")!=="scan"||config2.project===void 0)return;let ctx=scanContext(sous),root=config2.project.root,load=config2.atPath("plugins.load"),known=new Set(load.valueOr([])),found=new Set;for(let manager of config2.entities("package-manager"))try{if(await manager.detect(root,ctx)===void 0)continue;for(let pkg of await manager.installed("project",root,ctx))pkg.isSousPlugin&&!known.has(pkg.name)&&found.add(pkg.name)}catch(error51){config2.warn(`${manager.id} could not list the installed packages: ${error51 instanceof Error?error51.message:String(error51)}`)}for(let name of[...found].sort())load.append(name)}}}var SCAN_CONTRIBUTOR2,init_scan=__esm({"../sous-plugin-update/src/scan.ts"(){"use strict";SCAN_CONTRIBUTOR2="update.scan"}});var package_default22,init_package8=__esm({"../sous-plugin-update/package.json"(){package_default22={name:"@sous-io/sous-plugin-update",version:"1.1.6",description:"Updating sous itself, installing plugins a recipe requires, the package-manager entity, scanning for installed plugins.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-host":"workspace:*",semver:"^7.8.5"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*","@types/semver":"^7.8.0"},engines:{node:">=22"}}}});import fs69 from"node:fs";import path92 from"node:path";function readPackageJson2(directory){try{let parsed=JSON.parse(fs69.readFileSync(path92.join(directory,"package.json"),"utf8"));return typeof parsed=="object"&&parsed!==null&&!Array.isArray(parsed)?parsed:void 0}catch{return}}function realpathOr2(target){try{return fs69.realpathSync(target)}catch{return target}}function versionOf(pkg){return typeof pkg?.version=="string"?pkg.version:UNKNOWN_VERSION}function declaredDependency(pkg){if(!(pkg===null||typeof pkg!="object"))for(let section2 of["devDependencies","dependencies"]){let block=pkg[section2];if(block===null||typeof block!="object")continue;let range3=block[PACKAGE_NAME2];if(typeof range3=="string")return{section:section2,range:range3}}}function ancestors2(start2){let found=[],directory=path92.resolve(start2);for(;;){found.push(directory);let parent=path92.dirname(directory);if(parent===directory)return found;directory=parent}}async function discoverInstalls(options2,ctx){let managers=ctx.entities.list("package-manager"),project=await findProjectInstall2(options2.cwd,managers,ctx),globals=await findGlobalInstalls(managers,ctx);return{...project===void 0?{}:{project},globals,running:classifyRunning(options2.ownRoot,project,globals)}}async function ownerOf(directory,managers,ctx){let answers=[];for(let entity of managers)try{let detection=await entity.detect(directory,ctx);detection!==void 0&&answers.push({entity,detection})}catch{}return answers.find(answer2=>answer2.detection.detected)??answers[0]}async function findProjectInstall2(cwd,managers,ctx){for(let directory of ancestors2(cwd)){let owner=await ownerOf(directory,managers,ctx);if(owner===void 0){let location=path92.join(directory,"node_modules",...PACKAGE_NAME2.split("/")),copy=readPackageJson2(location);if(copy?.name===PACKAGE_NAME2)return describeProject(directory,{supported:!1},{location,realPath:realpathOr2(location),installed:versionOf(copy)});continue}let packages;try{packages=await owner.entity.installed("project",directory,ctx)}catch{continue}let found=packages.find(candidate=>candidate.name===PACKAGE_NAME2);if(found===void 0)continue;let manager={supported:!0,id:owner.detection.id,entity:owner.entity,detected:owner.detection.detected,detection:owner.detection};return describeProject(directory,manager,{location:found.location,realPath:found.realPath,installed:found.version},found)}}function describeProject(projectRoot,manager,copy,found){let declared=found?.declared??declaredDependency(readPackageJson2(projectRoot)),detection=manager.supported?manager.detection:void 0,info={projectRoot,...copy,manager,workspaceRoot:detection?.workspaceRoot!==void 0&&realpathOr2(detection.workspaceRoot)===realpathOr2(projectRoot)};return declared!==void 0&&(info.declared=declared),detection?.pnpRoot!==void 0&&(info.pnpRoot=detection.pnpRoot),info}async function findGlobalInstalls(managers,ctx){let installs=[];for(let manager of managers){if(manager.globalInstallCommand===void 0)continue;let packages;try{packages=await manager.installed("global",void 0,ctx)}catch{continue}let found=packages.find(candidate=>candidate.name===PACKAGE_NAME2);found===void 0||installs.some(install=>install.realPath===found.realPath)||installs.push({manager,location:found.location,realPath:found.realPath,installed:found.version})}return installs}function classifyRunning(ownRoot2,project,globals){let realPath2=realpathOr2(ownRoot2),installed2=versionOf(readPackageJson2(ownRoot2));if(project!==void 0&&(project.realPath===realPath2||isPnpCopy(project,realPath2)))return{kind:"project",realPath:realPath2,installed:installed2};let global2=globals.find(install=>install.realPath===realPath2);if(global2!==void 0)return{kind:"global",manager:global2.manager.id,realPath:realPath2,installed:installed2};let slashed=realPath2.split(path92.sep).join("/");return slashed.includes("/_npx/")?{kind:"npx",realPath:realPath2,installed:installed2}:slashed.includes("/.volta/")?{kind:"volta",realPath:realPath2,installed:installed2}:{kind:"unknown",realPath:realPath2,installed:installed2}}function isPnpCopy(project,realPath2){if(project.pnpRoot===void 0)return!1;let relative4=path92.relative(path92.join(realpathOr2(project.pnpRoot),".yarn","unplugged"),realPath2);return relative4.length>0&&!relative4.startsWith("..")&&!path92.isAbsolute(relative4)}var PACKAGE_NAME2,UNKNOWN_VERSION,init_installs=__esm({"../sous-plugin-update/src/installs.ts"(){"use strict";PACKAGE_NAME2="@sous-io/sous",UNKNOWN_VERSION="unknown"}});import{ConfigError as ConfigError60}from"@sous-io/sous-plugin-api";function parseRegistryMetadata(text,source){let raw2;try{raw2=JSON.parse(text)}catch(error51){throw new ConfigError60(`The registry's answer from ${source} is not JSON.
998
998
  ${error51.message}`)}let problems=[],document=isRecord2(raw2)?raw2:void 0;document===void 0&&problems.push("(top level): expected an object"),typeof document?.name!="string"&&problems.push("name: expected a string"),isRecord2(document?.versions)||problems.push("versions: expected an object");let rawTags=document?.["dist-tags"];if(rawTags!==void 0&&!isRecord2(rawTags)&&problems.push("dist-tags: expected an object"),problems.length>0||document===void 0)throw new ConfigError60([`The registry's answer from ${source} is not a package document.`,...problems.map(problem=>` ${problem}`)].join(`
999
999
  `));let versions=Object.keys(document.versions).filter(version2=>import_semver22.default.valid(version2)===version2).sort(import_semver22.default.rcompare),distTags={};for(let[tag,version2]of Object.entries(rawTags??{}))typeof version2=="string"&&import_semver22.default.valid(version2)===version2&&(distTags[tag]=version2);return{name:document.name,versions,distTags}}function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function defaultRange(current){return`>=${current} <${import_semver22.default.major(current)+1}.0.0-0`}function chooseVersion(input){let current=import_semver22.default.valid(input.current);if(current===null)throw new ConfigError60(`The installed version "${input.current}" is not a version sous can compare with the published ones.`);let prerelease=input.prerelease??import_semver22.default.prerelease(current)!==null,published=input.versions.filter(version2=>import_semver22.default.valid(version2)===version2),candidates=prerelease?published:published.filter(version2=>import_semver22.default.prerelease(version2)===null),range3={includePrerelease:!0},settle=(target,specKind)=>{let choice={target:target??current,direction:directionOf(target??current,current),prerelease};return specKind!==void 0&&(choice.specKind=specKind),choice},noDowngrade=target=>target!==null&&import_semver22.default.gt(target,current)?target:null,{request}=input;if(request.kind==="default")return settle(noDowngrade(import_semver22.default.maxSatisfying(candidates,defaultRange(current),range3)));if(request.kind==="major")return settle(noDowngrade(import_semver22.default.maxSatisfying(candidates,"*",range3)));let spec=request.spec.trim(),exact=import_semver22.default.valid(spec);if(exact!==null){if(!published.includes(exact))throw noMatch(spec,"is not a published version",input);return settle(exact,"version")}let tagged=input.distTags[spec];if(tagged!==void 0)return settle(tagged,"dist-tag");if(import_semver22.default.validRange(spec)!==null){let newest=import_semver22.default.maxSatisfying(candidates,spec,range3);if(newest===null)throw noMatch(spec,prerelease?"matches no published version":"matches no published version that is not a prerelease",input);return settle(newest,"range")}throw noMatch(spec,"is not a version, a range or a dist-tag",input)}function directionOf(target,current){let order=import_semver22.default.compare(target,current);return order>0?"upgrade":order<0?"downgrade":"current"}function noMatch(spec,why2,input){let lines3=[`The requested version "${spec}" ${why2}.`],tags2=Object.entries(input.distTags).sort(([a],[b])=>a.localeCompare(b));if(tags2.length>0){lines3.push(" The dist-tags point at:");for(let[tag,version2]of tags2)lines3.push(` ${tag}: ${version2}`)}let newest=input.versions.filter(version2=>import_semver22.default.valid(version2)===version2).sort(import_semver22.default.rcompare).slice(0,NEWEST_LISTED);return newest.length>0?lines3.push(` The newest published versions are ${newest.join(", ")}.`):lines3.push(" The registry lists no published versions."),new ConfigError60(lines3.join(`
1000
1000
  `))}var import_semver22,NEWEST_LISTED,init_versions2=__esm({"../sous-plugin-update/src/versions.ts"(){"use strict";import_semver22=__toESM(require_semver2(),1),NEWEST_LISTED=5}});function packageSpec(version2){return`${PACKAGE_NAME2}@${version2}`}function buildUpdatePlans(discovery,metadata,options2){let plans=[],notices=[],wants=scope=>options2.only===void 0||options2.only===scope;if(wants("global"))for(let install of discovery.globals){let planned=planGlobal(install,metadata,options2);"kind"in planned?notices.push(planned):plans.push(planned)}if(wants("project")&&discovery.project!==void 0){let planned=planProject(discovery.project,metadata,options2);"kind"in planned?notices.push(planned):plans.push(planned)}return notices.push(...runningNotices(discovery,metadata,options2)),options2.only==="global"&&discovery.globals.length===0&&notices.push({kind:"not-found",scope:"global",message:`No global install of ${PACKAGE_NAME2} was found with any package manager.`}),options2.only==="project"&&discovery.project===void 0&&notices.push({kind:"not-found",scope:"project",message:`No project install of ${PACKAGE_NAME2} was found in this directory or above it.`}),{plans,notices}}function planGlobal(install,metadata,options2){if(import_semver23.default.valid(install.installed)===null)return unknownVersion("global",install.location,install.installed);let choice=choose(install.installed,metadata,options2);return{scope:"global",location:install.location,manager:install.manager.id,managerAssumed:!1,installed:install.installed,target:choice.target,direction:choice.direction,command:install.manager.globalInstallCommand([packageSpec(choice.target)])}}function planProject(install,metadata,options2){if(install.declared===void 0)return{kind:"undeclared",scope:"project",location:install.location,message:`The project at ${install.projectRoot} has ${PACKAGE_NAME2} in node_modules, but its package.json does not declare it, so sous leaves it alone.`};if(import_semver23.default.valid(install.installed)===null)return unknownVersion("project",install.location,install.installed);let choice=choose(install.installed,metadata,options2);if(!install.manager.supported)return{kind:"unsupported-manager",scope:"project",location:install.location,message:`The project at ${install.projectRoot} uses a package manager that no loaded plugin drives, so it has to be updated by hand.`};let command=install.manager.entity.addCommand([packageSpec(choice.target)],{section:install.declared.section,workspaceRoot:install.workspaceRoot,cwd:install.projectRoot});return{scope:"project",location:install.location,projectRoot:install.projectRoot,manager:install.manager.id,managerAssumed:!install.manager.detected,installed:install.installed,target:choice.target,direction:choice.direction,declaredIn:install.declared,command:{...command,cwd:install.projectRoot},...install.pnpRoot===void 0?{}:{pnpRoot:install.pnpRoot}}}function runningNotices(discovery,metadata,options2){let{running}=discovery;if(running.kind==="npx")return[{kind:"npx",location:running.realPath,message:"This sous is running through npx, which is not an install: npx keeps its own cache, and no install sous updates changes it."}];if(options2.only==="project")return[];if(running.kind==="volta"){let notice={kind:"volta",scope:"global",location:running.realPath,message:"This sous is managed by Volta, which sous does not drive, so Volta has to update it."};if(import_semver23.default.valid(running.installed)!==null){let{target}=choose(running.installed,metadata,options2);return[{...notice,manualCommand:{command:"volta",args:["install",packageSpec(target)]}}]}return[notice]}return running.kind==="unknown"?[{kind:"unknown-location",scope:"global",location:running.realPath,message:"This sous is not the project install or a global install of a package manager sous drives (it may be a source checkout), so sous does not update it."}]:[]}function choose(installed2,metadata,options2){return chooseVersion({current:installed2,versions:metadata.versions,distTags:metadata.distTags,request:options2.request,...options2.prerelease===void 0?{}:{prerelease:options2.prerelease}})}function unknownVersion(scope,location,installed2){return{kind:"unknown-version",scope,location,message:`The ${scope} install at ${location} names its version as "${installed2}", which sous cannot compare with the published versions, so it has to be updated by hand.`}}var import_semver23,init_plan2=__esm({"../sous-plugin-update/src/plan.ts"(){"use strict";import_semver23=__toESM(require_semver2(),1);init_installs();init_versions2()}});import{ConfigError as ConfigError61}from"@sous-io/sous-plugin-api";function registryBaseUrl(env){for(let name of REGISTRY_ENV_NAMES){let value=env[name]?.trim();if(value!==void 0&&value.length>0)return value.endsWith("/")?value:`${value}/`}return DEFAULT_REGISTRY}function packageMetadataUrl(base){return`${base}${PACKAGE_NAME2.replace("/","%2f")}`}function registryUrl(env){return packageMetadataUrl(registryBaseUrl(env))}async function fetchPublishedVersions(http,env){let url2=registryUrl(env),text;try{let response=await http.get(url2,{headers:{accept:ABBREVIATED_METADATA_TYPE},timeoutMs:REGISTRY_TIMEOUT_MS,label:`list of published ${PACKAGE_NAME2} versions`});if(response.status<200||response.status>=300)throw new ConfigError61(`The registry answered ${response.status} ${response.statusText} for ${url2}.`,{details:statusHints(response.status)});text=await response.text()}catch(error51){throw error51 instanceof ConfigError61?error51:new ConfigError61(`Could not read the list of published ${PACKAGE_NAME2} versions from ${url2}.`,{details:[error51 instanceof Error?error51.message:String(error51)],cause:error51})}return parseRegistryMetadata(text,url2)}function statusHints(status){return status===404?[`The registry has no package named ${PACKAGE_NAME2}. When npm_config_registry names a mirror, the mirror may not carry it.`]:status===401||status===403?["The registry refused the request without credentials, and sous sends none."]:[]}var DEFAULT_REGISTRY,ABBREVIATED_METADATA_TYPE,REGISTRY_TIMEOUT_MS,REGISTRY_ENV_NAMES,init_registry=__esm({"../sous-plugin-update/src/registry.ts"(){"use strict";init_installs();init_versions2();DEFAULT_REGISTRY="https://registry.npmjs.org/",ABBREVIATED_METADATA_TYPE="application/vnd.npm.install-v1+json",REGISTRY_TIMEOUT_MS=15e3,REGISTRY_ENV_NAMES=["npm_config_registry","NPM_CONFIG_REGISTRY"]}});import{IntentOutput as IntentOutput18,ReportEntryStyle as ReportEntryStyle14,TextBlock as TextBlock10,VariableSet as VariableSet9}from"@sous-io/sous-plugin-api";function formatCommand(command){return[command.command,...command.args].join(" ")}function planTitle(plan2,globalCount){return plan2.scope==="project"?"Project install":globalCount>1?`Global install (${plan2.manager})`:"Global install"}function commandFact(label,command){return command.cwd===void 0?{label,value:formatCommand(command)}:{label,value:formatCommand(command),detail:`in ${command.cwd}`}}function planFacts(plan2){let facts=[];return plan2.projectRoot!==void 0&&facts.push({label:"Project",value:plan2.projectRoot}),facts.push(plan2.pnpRoot===void 0?{label:"Location",value:plan2.location}:{label:"Location",value:plan2.location,detail:"Yarn Plug'n'Play, which keeps no node_modules copy"}),facts.push(plan2.managerAssumed?{label:"Package manager",value:plan2.manager,detail:"assumed, because the project's files name no package manager"}:{label:"Package manager",value:plan2.manager}),plan2.declaredIn!==void 0&&facts.push({label:"Declared in",value:plan2.declaredIn.section,detail:`as ${plan2.declaredIn.range}`}),facts.push({label:"Installed",value:plan2.installed}),plan2.direction==="current"?(facts.push({label:"Will install",value:"nothing",detail:`${plan2.installed} is already the version this update chooses`}),facts):(facts.push(plan2.direction==="downgrade"?{label:"Will install",value:plan2.target,detail:`a downgrade from ${plan2.installed}`}:{label:"Will install",value:plan2.target}),facts)}function buildFact(noBuild2,buildDirectory){return noBuild2?{label:"Then builds",value:"no",detail:"--no-build was passed"}:buildDirectory===void 0?{label:"Then builds",value:"no",detail:"the project has no sous config"}:{label:"Then builds",value:"yes",detail:`with the new copy, in ${buildDirectory}`}}function updateCommandEntries(result,input,cwd){let installs=input.global===!0?"global only":input.project===!0?"project only":"global and project",version2=typeof input.version=="string"?input.version:input.major===!0?"the newest published, whatever its major version":"the newest in each install's major version",prereleases=input.prerelease===void 0?"counted when the installed version is one":input.prerelease===!0?"counted":"not counted";return{...cwd===void 0?{}:{Directory:cwd},Installs:installs,Version:version2,Prereleases:prereleases,...result.registry===void 0?{}:{Registry:result.registry},"Dry Run":input.dryRun===!0}}function summaryRows(result,globalCount){let rows=result.outcomes.map(({plan:plan2,result:outcome,exitCode})=>{let label=planTitle(plan2,globalCount);switch(outcome){case"updated":return{label,value:`updated to ${plan2.target}`,detail:`from ${plan2.installed}`};case"failed":return{label,value:"failed",detail:`${plan2.manager} exited with code ${exitCode}`};case"declined":return{label,value:"skipped",detail:`left at ${plan2.installed}`};default:return{label,value:`up to date at ${plan2.installed}`}}}),migrations=result.migrations;if(migrations!==void 0){let label="Project migrations";switch(migrations.result){case"migrated":rows.push({label,value:"ran",detail:"the new copy ran every pending migration it could"});break;case"failed":rows.push({label,value:"failed",detail:`exited with code ${migrations.exitCode}`});break;case"no-bin":rows.push({label,value:"failed",detail:"the new copy names no bin"});break;case"unsupported":rows.push({label,value:"none",detail:"the new copy has no migrations to run"});break;case"skipped":rows.push({label,value:"not run",detail:"a downgrade keeps the version the project migrated to"});break;case"no-config":rows.push({label,value:"not run",detail:"the project has no sous config"});break}}let build2=result.build;if(build2!==void 0){let label="Project build";switch(build2.result){case"built":rows.push({label,value:"succeeded",detail:`in ${build2.directory}`});break;case"failed":rows.push({label,value:"failed",detail:`exited with code ${build2.exitCode}`});break;case"no-bin":rows.push({label,value:"failed",detail:"the new copy names no bin"});break;case"skipped":rows.push({label,value:"skipped",detail:"--no-build was passed"});break;case"no-config":rows.push({label,value:"not run",detail:"the project has no sous config"});break}}return rows}function updateOutputs(result,input,opening){let plans=result.outcomes.map(outcome=>outcome.plan),globalCount=plans.filter(plan2=>plan2.scope==="global").length,dryRun4=input.dryRun===!0,outputs=[opening];if(result.notices.length>0){outputs.push(new IntentOutput18({title:"Not updated"}));for(let notice of result.notices){outputs.push(new IntentOutput18({result:new TextBlock10(notice.message),style:ReportEntryStyle14.Note}));let facts=[];notice.location!==void 0&&facts.push({label:"Location",value:notice.location}),notice.manualCommand!==void 0&&facts.push(commandFact("Run by hand",notice.manualCommand)),facts.length>0&&outputs.push(new IntentOutput18({result:new VariableSet9(facts)}))}}if(plans.length===0)return outputs.push(new IntentOutput18({result:new TextBlock10("There is no install of sous here that sous can update."),style:ReportEntryStyle14.Note})),outputs;outputs.push(new IntentOutput18({title:dryRun4?"Update plan":"Updating"}));for(let outcome of result.outcomes){let plan2=outcome.plan,title2=planTitle(plan2,globalCount),facts=planFacts(plan2);plan2.direction!=="current"&&plan2.scope==="project"&&facts.push(buildFact(input.noBuild===!0,result.buildDirectory)),dryRun4&&plan2.direction!=="current"&&facts.push(commandFact("Would run",plan2.command)),outputs.push(new IntentOutput18({result:new VariableSet9(facts,{title:title2})})),outcome.result==="declined"&&outputs.push(new IntentOutput18({result:new TextBlock10(`The ${title2.toLowerCase()} was left at ${plan2.installed}.`)}))}return dryRun4?(outputs.push(new IntentOutput18({result:new TextBlock10("Nothing was installed. Run the same command without '--dry-run' to update."),style:ReportEntryStyle14.DryRun})),outputs):(outputs.push(new IntentOutput18({title:"Summary",result:new VariableSet9(summaryRows(result,globalCount))})),outputs)}function pluginsInstallOutputs(result){if(result.declined)return[new IntentOutput18({result:new TextBlock10("Nothing was installed.")})];let outputs=[new IntentOutput18({title:result.dryRun?"Plugins to install":"Installed plugins",result:new VariableSet9([...result.installed.map(plugin=>({label:plugin.name,value:plugin.range})),{label:"Package manager",value:result.manager}])})];return result.dryRun&&outputs.push(new IntentOutput18({result:new TextBlock10("Nothing was installed. Run the same command without '--dry-run' to install."),style:ReportEntryStyle14.DryRun})),outputs}var init_report2=__esm({"../sous-plugin-update/src/report.ts"(){"use strict"}});var update_exports={};__export(update_exports,{NO_DELEGATE_ENV:()=>NO_DELEGATE_ENV2,binEntryOf:()=>binEntryOf2,default:()=>update_default,handle:()=>handle4,requestOf:()=>requestOf});import fs70 from"node:fs";import path93 from"node:path";import{commandVariables as commandVariables5,ConfigError as ConfigError62,InputError as InputError6,IntentOutputs as IntentOutputs22,LogLevel as LogLevel15,SousError as SousError32}from"@sous-io/sous-plugin-api";function requestOf(input){return input.version!==void 0?{kind:"spec",spec:input.version}:input.major?{kind:"major"}:{kind:"default"}}function checkInput(input){if(input.major&&input.version!==void 0)throw new InputError6("upgrade",[{path:"major",message:"cannot be combined with version"}]);if(input.global&&input.project)throw new InputError6("upgrade",[{path:"global",message:"cannot be combined with project"}])}function questionFor(plan2,title2){return`${plan2.direction==="downgrade"?"Downgrade":"Update"} the ${title2.toLowerCase()} from ${plan2.installed} to ${plan2.target}?`}function holdsPrimaryConfig(sousDir){try{return fs70.readdirSync(sousDir).some(name=>/^sous\.config\./.test(name))}catch{return!1}}function buildDirFor(projectRoot,ctx){let found=ctx.project;if(found?.configPath!==void 0){let relative4=path93.relative(projectRoot,found.root);if(!relative4.startsWith("..")&&!path93.isAbsolute(relative4))return found.root}return holdsPrimaryConfig(path93.join(projectRoot,".sous"))?projectRoot:void 0}function binEntryOf2(pkg){let bin=pkg?.bin;if(typeof bin=="string")return bin;if(typeof bin=="object"&&bin!==null){let entries=bin,named=entries.sous??Object.values(entries)[0];return typeof named=="string"?named:void 0}}async function execute(ctx,command,env=ctx.env){return ctx.reporter.command(command.command,command.args,command.cwd===void 0?{}:{cwd:command.cwd}),(await ctx.services.get("host.processes").runInteractive(command.command,command.args,{...command.cwd===void 0?{}:{cwd:command.cwd},env,label:formatCommand(command),windowsShell:!0})).exitCode??1}async function buildProject(plan2,directory,input,ctx){if(input.noBuild)return{result:"skipped"};if(directory===void 0)return{result:"no-config"};let command=newCopyCommand(plan2,["build"],directory);if(command===void 0)return ctx.reporter.problem(`The update stands, but the new copy at ${realpathOr2(plan2.location)} names no bin sous can run, so the project was not built.`,{hint:"Run 'sous build' in the project."},LogLevel15.Error),{result:"no-bin",directory};ctx.reporter.operationStart("Building the project");let exitCode=await execute(ctx,command,{...ctx.env,[NO_DELEGATE_ENV2]:"1"});return exitCode!==0?(ctx.reporter.problem(`The update stands, but the build that followed it exited with code ${exitCode}.`,{hint:`Fix what the build reported above and run 'sous build' again.${plan2.pnpRoot===void 0?"":PNP_BUILD_HINT}`},LogLevel15.Error),{result:"failed",directory,command,exitCode}):{result:"built",directory,command,exitCode}}async function migrateProject(plan2,directory,input,ctx){if(plan2.direction==="downgrade")return{result:"skipped"};if(directory===void 0)return{result:"no-config"};let args=["migrations","run",...input.yes===!0?["--yes"]:[],...(input.answer??[]).flatMap(answer2=>["--answer",answer2])],command=newCopyCommand(plan2,args,directory);if(command===void 0)return ctx.reporter.problem(`The update stands, but the new copy at ${realpathOr2(plan2.location)} names no bin sous can run, so no migration ran.`,{hint:"Run 'sous doctor' in the project."},LogLevel15.Error),{result:"no-bin",directory};ctx.reporter.operationStart("Running the migrations of the new version");let exitCode=await execute(ctx,command,{...ctx.env,[NO_DELEGATE_ENV2]:"1"});return exitCode===USAGE_EXIT_CODE?{result:"unsupported",directory,command,exitCode}:exitCode!==0?(ctx.reporter.problem(`The update stands, but the migrations that followed it exited with code ${exitCode}.`,{hint:"Fix what the migrations reported above and run 'sous doctor', which runs the ones still pending."},LogLevel15.Error),{result:"failed",directory,command,exitCode}):{result:"migrated",directory,command,exitCode}}function newCopyCommand(plan2,args,directory){if(plan2.pnpRoot!==void 0)return{command:"yarn",args:["run","--binaries-only","sous",...args],cwd:directory};let root=realpathOr2(plan2.location),entry=binEntryOf2(readPackageJson2(root));return entry===void 0?void 0:{command:process.execPath,args:[path93.resolve(root,entry),...args],cwd:directory}}function configProblemOf(ctx){let error51=ctx.engine.configError;if(error51===void 0)return;let message2=error51 instanceof Error?error51.message:String(error51),details=error51 instanceof SousError32?error51.details:[],configPath3=ctx.project?.configPath;return{...configPath3===void 0?{}:{configPath:configPath3},message:[message2,...details.map(detail=>` ${detail}`)].join(`
@@ -1029,7 +1029,7 @@ ${problem}`}throw new CancelledError2(question.message,`the answer was not accep
1029
1029
  })`),!0}catch{return!1}}function isEsModuleSource(source){return!parsesAsCommonJs(source)}function declareConfigModule(file2,url2){let hooks=module.registerHooks;typeof hooks!="function"||!file2.endsWith(".js")||(registered.add(url2.split("?")[0]),!hooked&&(hooked=!0,hooks({load(loadUrl,context,nextLoad){if(!registered.has(loadUrl.split("?")[0])||!(context.format===void 0||context.format===null||context.format==="commonjs"))return nextLoad(loadUrl,context);let source;try{source=fs3.readFileSync(fileURLToPath(loadUrl.split("?")[0]),"utf8")}catch{return nextLoad(loadUrl,context)}return isEsModuleSource(source)?{format:"module",source,shortCircuit:!0}:nextLoad(loadUrl,context)}})))}var ConfigFilesLoaderImpl=class{constructor(host){this.host=host}cache=new Map;stamps=new Map;formatOf(fileName){return formatOf(fileName)}findMain(sousDir){return mainCandidates(sousDir)[0]}findPatches(directory,baseName2=MAIN_CONFIG_BASE_NAME){let names2;try{names2=fs4.readdirSync(directory)}catch{return[]}let matches=names2.filter(name=>{let format3=formatOf(name);return(format3==="patch-json"||format3==="patch-jsonl")&&name.startsWith(`${baseName2}.`)&&isFile(path6.join(directory,name))});return this.host.globs().sortBytewise(matches).map(name=>path6.join(directory,name))}forget(file2){file2===void 0?this.cache.clear():this.cache.delete(path6.resolve(file2))}async load(file2){let resolved=path6.resolve(file2),cached2=this.cache.get(resolved);if(cached2!==void 0)return cached2;let loaded=await this.read(resolved);return this.cache.set(resolved,loaded),loaded}async contribute(file2,config2,options2={}){let label=options2.label??this.label(file2.path);try{switch(file2.kind){case"data":this.mergeData(config2,file2.data,label,options2.fromRecipe===!0,path6.dirname(file2.path));break;case"patch":config2.apply(file2.patches);break;case"module":await file2.configure(config2);break}}catch(error51){throw namingFile(error51,label,file2.path)}}label(file2){let sousDir=this.host.project?.sousDir;if(sousDir!==void 0){let relative4=path6.relative(sousDir,file2);if(relative4!==""&&!relative4.startsWith("..")&&!path6.isAbsolute(relative4))return relative4.split(path6.sep).join("/")}return file2}mergeData(config2,data,label,fromRecipe=!1,baseDir){let evaluated=this.evaluate(config2,data,label,fromRecipe,baseDir);if(evaluated!=null){if(!isJsonObject(evaluated))throw new ConfigError6(`${label} did not produce a plain object (got ${Array.isArray(evaluated)?"an array":typeof evaluated}).`);assertNotOldSchema(evaluated,label),config2.root().merge(evaluated)}}evaluate(config2,data,label,fromRecipe,baseDir){let evaluator=this.host.evaluator();return evaluator===void 0||!evaluator.hasExpressions(data)?data:evaluator.evaluateLayer(data,{file:label,config:config2,ownVars:ownVars(data),fromRecipe,...baseDir===void 0?{}:{baseDir}}).value}async read(file2){let label=this.label(file2),format3=formatOf(path6.basename(file2));if(format3===void 0)throw new ConfigError6(`${label} is not a kind of file sous reads as config.`,{details:["Config files end in .json, .jsonc, .yaml, .yml, .js, .mjs, .ts, .patch.json or .patch.jsonl."]});let text;try{text=fs4.readFileSync(file2,"utf8")}catch(error51){throw new ConfigError6(`Could not read the config file ${label}.`,{cause:error51,details:[error51.message]})}try{switch(format3){case"json":case"jsonc":case"yaml":{let data=parseDocument2(text,format3).value()??{};return{kind:"data",path:file2,format:format3,data,text}}case"patch-json":case"patch-jsonl":{let set2=parsePatchFile(text,format3==="patch-json"?"json":"jsonl",label);return{kind:"patch",path:file2,format:format3,patches:set2.patches,text}}case"js":case"ts":{let exports=moduleExports(await this.importFile(file2,format3),label),configure=moduleConfigure(exports,{label,path:file2,sousDir:this.host.project?.sousDir,confDir:this.host.project?.confDir,mergeData:(config2,data)=>this.mergeData(config2,data,label,!1,path6.dirname(file2)),loadInto:(draft,specifier,glob,run)=>this.loadInto(draft,specifier,glob,run,file2)});return{kind:"module",path:file2,format:format3,configure,text}}}}catch(error51){throw namingFile(error51,label,file2)}}async importFile(file2,format3){let stat6=fs4.statSync(file2),stamp=`${stat6.mtimeMs}:${stat6.size}`,previous=this.stamps.get(file2),version2=previous===void 0?0:previous.stamp===stamp?previous.version:previous.version+1;this.stamps.set(file2,{stamp,version:version2});let base=pathToFileURL3(file2).href,url2=version2===0?base:`${base}?sous-reload=${version2}`;if(this.host.importModule!==void 0)return this.host.importModule(url2,file2);declareConfigModule(file2,url2);try{return await import(url2)}catch(error51){throw format3==="ts"&&needsTypeStripping(error51)?new ConfigError6(`${this.label(file2)} is TypeScript that this Node.js (${process.version}) cannot run.`,{details:["Node 22.18 or later runs TypeScript whose types can simply be removed; enums, namespaces and parameter properties need a compiler.","Use a newer Node, write the config without those, or write it as sous.config.js."]}):error51}}async loadInto(draft,specifier,glob,run,from){let where3=`${glob?"loadConfigs":"loadConfig"}(${JSON.stringify(specifier)}) in ${this.label(from)}`,variables=this.host.pathVariables(),substituted=String(specifier).replace(/\$\{([^}]+)\}/g,(_match,name)=>{let value=variables[name];if(value===void 0)throw new ConfigError6(`${where3}: \${${name}} cannot be used in a builder path.`,{details:["Builder paths are read before variables are resolved, so only these can be used:",Object.keys(variables).map(key=>`\${${key}}`).join(", ")]});return value}),resolved=path6.isAbsolute(substituted)?path6.normalize(substituted):path6.resolve(path6.dirname(from),substituted),files=glob?this.matchFiles(resolved):[resolved];for(let file2 of files){if(!isFile(file2))throw new ConfigError6(`${where3}: no config file at ${file2}.`);let loaded=await this.load(file2);switch(loaded.kind){case"data":mergeLegacy(draft,loaded.data,this.label(file2));break;case"module":{let exports=moduleExports(await this.importFile(file2,loaded.format),this.label(file2));await run(exports,file2);break}case"patch":throw new ConfigError6(`${where3}: ${this.label(file2)} is a patch file; list it in conf.d instead.`)}}}matchFiles(pattern){let globs=this.host.globs(),posix3=globs.toPosix(pattern),base=globs.staticBase(posix3);return globs.matchSync(path6.posix.relative(base,posix3),{cwd:base,absolute:!0})}};function mainCandidates(sousDir){return MAIN_CONFIG_FILE_NAMES.map(name=>path6.join(sousDir,name)).filter(isFile)}function ownVars(data){if(!isJsonObject(data)||!isJsonObject(data._vars))return;let result={};for(let[key,value]of Object.entries(data._vars))typeof value=="string"&&(result[key]=value);return result}function assertNotOldSchema(data,label){if("projects"in data||"defaultProject"in data)throw new ConfigError6(`${label} uses the removed multi-project schema ('projects' / 'defaultProject').`,{details:["A sous config now describes exactly one project. To migrate:"," 1. Move your single project's fields (name, _vars, _aliases, compilation,"," runtimeContext, tools) to the top level of the config."," 2. Delete the 'projects' and 'defaultProject' keys.","A config with several projects must be split into one config per project."]})}function namingFile(error51,label,file2){let message2=error51 instanceof Error?error51.message:String(error51);return message2.includes(label)||message2.includes(file2)?error51:isSousError(error51)?new ConfigError6(`${label}: ${message2}`,{cause:error51,details:error51.details}):new ConfigError6(`${label} failed to load: ${message2}`,{cause:error51})}function needsTypeStripping(error51){let code=error51?.code;return code==="ERR_UNKNOWN_FILE_EXTENSION"||code==="ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX"||code==="ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING"||code==="ERR_INVALID_TYPESCRIPT_SYNTAX"||error51 instanceof SyntaxError&&/typescript|type annotation|Unexpected token/i.test(error51.message)}function isFile(file2){try{return fs4.statSync(file2).isFile()}catch{return!1}}init_src();import fs5 from"node:fs";import path7 from"node:path";import{InputError as InputError2,IntentOutputs as IntentOutputs2,SousError as SousError6}from"@sous-io/sous-plugin-api";var CONFIG_SET="config.set",NEW_MAIN_NAME="sous.config.jsonc";function parseCliValue(text){try{return toPlainJson(JSON.parse(text))??text}catch{return text}}function resolveSetTarget(project,file2){if(file2===void 0||file2==="")return project.configPath??mainCandidates(project.sousDir)[0]??path7.join(project.sousDir,NEW_MAIN_NAME);if(path7.isAbsolute(file2))return file2;if(!file2.includes("/")&&!file2.includes(path7.sep)){let inConfd=path7.join(project.confDir,file2);return fs5.existsSync(inConfd)||!MAIN_CONFIG_FILE_NAMES.includes(file2)?inConfd:path7.join(project.sousDir,file2)}return path7.resolve(project.root,file2)}function describeSet(result){let removing=result.value===void 0;if(!result.changed)return removing?`${result.path} is not set in ${result.file}, so nothing changed.`:`${result.path} already has that value in ${result.file}, so nothing changed.`;let change=removing?`${result.path} removed`:`${result.path} set to ${JSON.stringify(result.value)}`;return result.dryRun?`Would change ${result.file}: ${change}.`:`Changed ${result.file}: ${change}.`}async function configSet(input,ctx){let project=ctx.project;if(project===void 0)throw new SousError6("There is no sous project here, so there is no config file to change.",{details:["Run sous init in the project root first."]});let segments;try{segments=parsePath(input.path)}catch(error51){throw new InputError2(CONFIG_SET,[{path:"path",message:error51.message}])}if(segments.length===0)throw new InputError2(CONFIG_SET,[{path:"path",message:"Name a key, such as compilation.includeSourceComments."}]);if(input.unset!==!0&&input.value===void 0)throw new InputError2(CONFIG_SET,[{path:"value",message:"Give a value, or --unset to remove the key."}]);let file2=resolveSetTarget(project,input.file),format3=formatOf(path7.basename(file2));if(format3!=="json"&&format3!=="jsonc"&&format3!=="yaml"){let name=path7.basename(file2),message2=input.file===void 0||input.file===""?`The main config ${name} is code, so sous cannot edit it. Pass --file with a JSON, JSONC or YAML file to write the value to, such as --file 600-settings.jsonc (created in .sous/conf.d/).`:`${name} is not a JSON, JSONC or YAML file, so sous cannot edit it. Pass --file with one that is, such as --file 600-settings.jsonc (created in .sous/conf.d/).`;throw new InputError2(CONFIG_SET,[{path:"file",message:message2}])}let text=fs5.existsSync(file2)?fs5.readFileSync(file2,"utf8"):format3==="yaml"?"":`{}
1030
1030
  `,document;try{document=parseDocument2(text,format3)}catch(error51){throw new SousError6(`Could not read ${file2}: ${error51.message}`,{cause:error51})}let node=document.atPath(segments),previous=node.get(),value=input.unset===!0?void 0:parseCliValue(input.value);value===void 0?previous!==void 0&&node.delete():node.set(value);let after=document.toString();after!==""&&!after.endsWith(`
1031
1031
  `)&&(after+=`
1032
- `);let changed2=after!==text,dryRun4=input.dryRun===!0;changed2&&!dryRun4&&writeFileAtomically(file2,after,420);let result={file:file2,path:input.path,previous,value,changed:changed2,dryRun:dryRun4};return IntentOutputs2.of(result,{summary:describeSet(result)})}var package_default={name:"@sous-io/sous-plugin-config-files",version:"1.1.4",description:"sous.config.* as a contributor, config.set, and the .env files.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-lib-documents":"workspace:*","@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-expressions":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@sous-io/sous-plugin-variables":"workspace:*",tsx:"^4.21.0"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};import fs6 from"node:fs";import path8 from"node:path";function loadEnvFile(filePath,env){if(!fs6.existsSync(filePath))return{filePath,loaded:!1,applied:[],skipped:[]};let applied=[],skipped=[];for(let[key,value]of Object.entries(parseEnv(fs6.readFileSync(filePath,"utf8")))){if(env[key]!==void 0){skipped.push(key);continue}env[key]=value,applied.push(key)}return{filePath,loaded:!0,applied,skipped}}function loadEnvDefaults(sousDir,env){return loadEnvFile(path8.join(sousDir,ENV_SHARED_NAME),env)}function loadEnvLocal(sousDir,env){return loadEnvFile(path8.join(sousDir,ENV_LOCAL_NAME),env)}function loadEnvFiles(sousDir,env){let local2=loadEnvLocal(sousDir,env),defaults2=loadEnvDefaults(sousDir,env);return{local:local2,defaults:defaults2}}function projectEnvironment(project,env){let result={...env};return project!==void 0&&loadEnvFiles(project.sousDir,result),Object.freeze(result)}var PLUGIN_NAME="@sous-io/sous-plugin-config-files",MAIN_CONTRIBUTOR="config-files.main",PATCH_CONTRIBUTOR_PREFIX="config-files/",MAIN_APPLY_ORDER=89900,configFilesPlugin=definePlugin({name:PLUGIN_NAME,version:package_default.version,description:"sous.config.* as a contributor, config.set, and the .env files.",dependsOn:{"@sous-io/sous-plugin-expressions":`^${package_default.version}`,"@sous-io/sous-plugin-variables":`^${package_default.version}`,"@sous-io/sous-plugin-host":`^${package_default.version}`},register(sous){let loader=createLoader(sous);if(sous.services.add("config-files.loader",()=>loader,{lifetime:"singleton"}),sous.services.add("config-files.env",(_config,ctx)=>new EnvFilesService(ctx.project,ctx.env),{lifetime:"singleton"}),sous.config.contribute(mainContributor(loader,sous.project)),sous.project!==void 0)for(let file2 of loader.findPatches(sous.project.sousDir,MAIN_CONFIG_BASE_NAME))sous.config.contribute(fileContributor(loader,file2,`${PATCH_CONTRIBUTOR_PREFIX}${path9.basename(file2)}`));sous.intents.add({intent:CONFIG_SET,requiresProject:!0,summary:"Set one value in a config file",description:"Writes one value into sous.config.* (or the file --file names), changing only that key: comments, key order and formatting stay. The value is read as JSON when it is valid JSON, else as text. A main config written as code (sous.config.js or .ts) cannot be edited; name a JSON, JSONC or YAML file with --file.",input:jsonSchema2({type:"object",properties:{path:{type:"string",description:'The key path: compilation.includeSourceComments, subscriptions."workflow/x".enabled.'},value:{type:"string",description:"The value: JSON when it is valid JSON, else text."},unset:{type:"boolean",description:"Remove the key instead."},file:{type:"string",description:"The file to write: a conf.d file name, or a path from the project root. Default: sous.config.* when it is JSON, JSONC or YAML; a code config needs this."},dryRun:{type:"boolean",description:"Show what would change, writing nothing."}},required:["path"]}),changesConfig:!0,cli:{command:["config","set"],positional:["path","value"],examples:["sous config set compilation.includeSourceComments false",'sous config set subscriptions."workflow/x".enabled false --file 610-mac.jsonc',"sous config set name --unset"]},agent:{tool:"sous_config_set",usage:"Call this to change one config value without rewriting the file.",whenNotToUse:"Not for subscriptions or repositories: use their own intents, which keep the lockfile in step."},handle:(input,ctx)=>configSet(input,ctx)}),sous.entities.add("config-key",{id:"$schema",description:"The JSON Schema the file declares, for editors. Sous ignores it.",schema:jsonSchema2({type:"string"})}),sous.entities.add("config-key",{id:"version",description:"The config format version. This sous understands version 1.",schema:jsonSchema2({const:1})}),sous.entities.add("config-key",{id:"name",description:"A display name for the project.",schema:jsonSchema2({type:"string"})})}});function createLoader(sous){return new ConfigFilesLoaderImpl({get project(){return sous.project},globs:()=>sous.services.get("host.globs"),evaluator:()=>sous.services.has("expressions.evaluator")?sous.services.get("expressions.evaluator"):void 0,pathVariables:()=>{let variables={};if(sous.project!==void 0&&(variables.sousDir=sous.project.sousDir,variables.sousConfDir=sous.project.confDir),sous.services.has("host.package")){let identity2=sous.services.get("host.package").identity();variables.sousRootPath=identity2.root,variables.sousVersion=identity2.version}return variables}})}function mainContributor(loader,project){let source=project===void 0?void 0:project.configPath??mainCandidates(project.sousDir)[0];return{id:MAIN_CONTRIBUTOR,...source===void 0?{}:{source},applyOrder:MAIN_APPLY_ORDER,async contribute(config2){let project2=config2.project;if(project2===void 0)return;let candidates=mainCandidates(project2.sousDir),file2=project2.configPath??candidates[0];if(file2!==void 0){if(config2.contributor.run===1){if(candidates.length>1)throw new ConfigError7(`Duplicate config file baseName '${MAIN_CONFIG_BASE_NAME}':`,{details:[...candidates.map(candidate=>` ${candidate}`),"Two config files in one directory must not share a name once the final extension is removed. Delete or rename one of them."]});loader.forget(file2)}await applyFile(loader,file2,config2)}}}}function fileContributor(loader,file2,id){let format3=loader.formatOf(path9.basename(file2));return{id,source:file2,applyOrder:MAIN_APPLY_ORDER,...format3==="patch-json"||format3==="patch-jsonl"?{monitors:[""]}:{},async contribute(config2){config2.contributor.run===1&&loader.forget(file2),await applyFile(loader,file2,config2)}}}async function applyFile(loader,file2,config2){isFile2(file2)&&await loader.contribute(await loader.load(file2),config2)}function isFile2(file2){try{return fs7.statSync(file2).isFile()}catch{return!1}}import{definePlugin as definePlugin35}from"@sous-io/sous-plugin-api";import os from"node:os";import{definePlugin as definePlugin2,IntentOutput as IntentOutput4,IntentOutputs as IntentOutputs7,jsonSchema as jsonSchema5,LOG_LEVELS,TextBlock as TextBlock4,VariableSet as VariableSet2}from"@sous-io/sous-plugin-api";import{ConflictError as ConflictError3,toJsonSchema}from"@sous-io/sous-plugin-api";function toKebab(name){return name.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}function suggest(typed,candidates){let limit2=Math.max(2,Math.floor(typed.length/3)),scored=[];for(let word of new Set(candidates)){let distance=editDistance(typed.toLowerCase(),word.toLowerCase());distance<=limit2?scored.push({word,score:distance}):typed.length>=2&&word.startsWith(typed)&&scored.push({word,score:limit2+1})}return scored.sort((a,b)=>a.score-b.score||(a.word<b.word?-1:1)).slice(0,3).map(item=>item.word)}function editDistance(a,b){let previous=Array.from({length:b.length+1},(_2,index)=>index);for(let i=1;i<=a.length;i++){let current=[i];for(let j2=1;j2<=b.length;j2++){let cost=a[i-1]===b[j2-1]?0:1;current[j2]=Math.min(previous[j2]+1,current[j2-1]+1,previous[j2-1]+cost)}previous=current}return previous[b.length]}function argumentsFromSchema(schema,cli={}){let properties=schema?.properties??{},required2=new Set(schema?.required??[]),flags=[];for(let[field,property]of Object.entries(properties)){let options2=cli.flags?.[field]??{},{kind,multiple}=kindOf(property),name=toKebab(field),aliases2=(options2.aliases??[]).filter(alias2=>alias2.length>1),shorts=extraShorts(kind,[name,...aliases2],options2).filter(letter=>letter!==options2.short);flags.push({field,name,aliases:aliases2,short:options2.short??shorts[0],shorts:options2.short?shorts:shorts.slice(1),kind,multiple,description:property.description,defaultValue:property.default,choices:choicesOf(property),required:required2.has(field)&&property.default===void 0,hidden:options2.hidden??!1})}let names2=cli.positional??[],positionals=names2.map((field,index)=>{let property=properties[field]??{},{kind,multiple}=kindOf(property);return{field,name:toKebab(field),kind,variadic:multiple&&index===names2.length-1,required:required2.has(field)&&property.default===void 0,description:property.description}});return{flags,positionals}}var CONFIRMATION_SHORTS={yes:"y",force:"f"};function extraShorts(kind,names2,options2){let letters=(options2.aliases??[]).filter(alias2=>alias2.length===1);if(kind==="boolean")for(let name of names2){let letter=CONFIRMATION_SHORTS[name];letter&&letters.push(letter)}return[...new Set(letters)]}function kindOf(property){let type=primaryType(property);if(type==="array"){let itemType=property.items?primaryType(property.items):"string";return{kind:scalarKind(itemType),multiple:!0}}return type===void 0&&property.enum?{kind:property.enum.every(item=>typeof item=="number")?"number":"string",multiple:!1}:{kind:scalarKind(type),multiple:!1}}function scalarKind(type){switch(type){case"boolean":case"number":case"integer":case"string":return type;case"object":return"json";default:return"string"}}function primaryType(property){if(Array.isArray(property.type))return property.type.find(type=>type!=="null");if(property.type)return property.type;let option=property.anyOf?.find(item=>item.type!=="null");return option?primaryType(option):void 0}function choicesOf(property){if(property.enum)return property.enum;if(property.items?.enum)return property.items.enum}function convertValue(raw2,kind,flag){switch(kind){case"number":case"integer":{let value=Number(raw2);return raw2.trim()===""||Number.isNaN(value)||kind==="integer"&&!Number.isInteger(value)?{error:`${flag} takes ${kind==="integer"?"a whole number":"a number"}, not "${raw2}".`}:{value}}case"json":try{return{value:JSON.parse(raw2)}}catch{return{error:`${flag} takes JSON, and "${raw2}" is not valid JSON.`}}case"boolean":return{value:raw2===""||raw2==="true"};default:return{value:raw2}}}var CommandTree=class _CommandTree{root=newNode([]);warnings=[];static build(intents,groups,picks={}){let tree=new _CommandTree,claims=new Map;for(let info of intents){let definition2=info.definition;if(definition2.internal)continue;let cli=definition2.cli??{},path122=cli.command??definition2.intent.split("."),command={intent:definition2.intent,plugin:info.plugin,info,path:path122,aliases:cli.aliases??[],hidden:cli.hidden??!1,...argumentsFromSchema(toJsonSchema(definition2.input),cli)};for(let[words2,viaAlias]of[[path122,!1],...command.aliases.map(alias2=>[alias2,!0])]){let key=words2.join(" "),list2=claims.get(key)??[];list2.push({command,viaAlias}),claims.set(key,list2)}}for(let[key,list2]of claims){let winner=tree.pick(key,list2,picks),node=tree.ensure(key.split(" "));node.command=winner.command,node.viaAlias=winner.viaAlias}for(let group of groups)tree.ensure(group.command).group=group;return markCanonical(tree.root),tree.shareAliasedGroups(groups),tree}find(words2){let node=this.root,used=0;for(let word of words2){let next=node.children.get(word);if(!next)break;node=next,used+=1}return{node,used}}commands(){let found=new Set,visit3=node=>{node.command&&!node.viaAlias&&found.add(node.command),node.children.forEach(visit3)};return visit3(this.root),[...found]}aliasesOf(command){let found=[...command.aliases],seen=new Set([command.path.join(" "),...found.map(words2=>words2.join(" "))]);for(let length=1;length<command.path.length;length+=1){let group=this.groupAt(command.path.slice(0,length));for(let alias2 of group?.aliases??[]){let words2=[...alias2,...command.path.slice(length)],key=words2.join(" ");!seen.has(key)&&this.find(words2).node.command===command&&(seen.add(key),found.push(words2))}}return found}groupAt(words2){let{node,used}=this.find(words2);return used===words2.length&&node.group?.command.join(" ")===words2.join(" ")?node.group:void 0}shareAliasedGroups(groups){for(let group of groups){let canonical=this.find(group.command);if(canonical.used===group.command.length)for(let alias2 of group.aliases??[]){let node=this.ensure(alias2);node.group??=group,node.canonical=!1;for(let[word,child2]of canonical.node.children)(child2.canonical||!node.children.has(word))&&node.children.set(word,child2);node.command??=canonical.node.command,node.viaAlias||=canonical.node.command!==void 0}}}pick(key,list2,picks){let distinct2=list2.filter((claim,index)=>list2.findIndex(other=>other.command===claim.command)===index);if(distinct2.length===1)return distinct2[0];let plugins=distinct2.map(claim=>claim.command.plugin),described=distinct2.map(claim=>`intent "${claim.command.intent}" (${claim.command.plugin})`).join(" and "),picked=picks[key],chosen=distinct2.find(claim=>claim.command.plugin===picked);if(!chosen)throw new ConflictError3(`cli:${key}`,plugins,`Two commands claim "${key}": ${described}.`,{details:[`Choose one in the config: cli.pick."${key}": "${plugins[0]}"`]});let others=distinct2.filter(claim=>claim!==chosen).map(claim=>claim.command.plugin).join(" and ");return this.warnings.push(`cli.pick picks ${chosen.command.plugin} for "${key}". ${others}'s command is ignored there, and may not work as expected.`),chosen}ensure(words2){let node=this.root;for(let word of words2){let next=node.children.get(word);next||(next=newNode([...node.path,word]),node.children.set(word,next)),node=next}return node}};function newNode(path122){return{path:path122,children:new Map,command:void 0,viaAlias:!1,group:void 0,canonical:!1}}function markCanonical(node){let canonical=node.command!==void 0&&!node.viaAlias;for(let child2 of node.children.values())canonical=markCanonical(child2)||canonical;return node.canonical=canonical||node.group!==void 0,node.canonical}import{isSousError as isSousError2,isSousErrorOfKind,SousError as SousError7}from"@sous-io/sous-plugin-api";function describeError(error51,options2={}){if(isSousError2(error51)){let details2=isSousErrorOfKind(error51,"input")&&options2.command?inputDetails(error51,options2.command):[...error51.details];return options2.debug&&error51.stack&&details2.push(...stackLines(error51.stack)),{summary:error51.message,details:details2,exitCode:error51.exitCode}}let details=options2.debug&&error51 instanceof Error&&error51.stack?stackLines(error51.stack):[];return{summary:error51 instanceof Error?error51.message:String(error51),details,exitCode:1}}function errorForDisplay(error51,command){if(!(error51 instanceof Error))return new Error(String(error51));if(command&&isSousErrorOfKind(error51,"input")){let input=error51,copy=new SousError7(input.message,{details:inputDetails(input,command),exitCode:input.exitCode,...input.cause===void 0?{}:{cause:input.cause}});return copy.stack=input.stack,copy}return error51}function viewError(error51,options2={}){let parts=describeError(error51,options2);return{lines:[`Error: ${parts.summary}`,...parts.details.map(line=>` ${line}`)],exitCode:parts.exitCode}}function inputDetails(error51,command){return error51.issues.map(issue2=>{let field=issue2.path.split(/[.[]/)[0]??"",positional=command.positionals.find(spec=>spec.field===field),flag=command.flags.find(spec=>spec.field===field),rest=issue2.path.slice(field.length),where3=positional?`<${positional.name}>${rest}`:flag?`--${flag.name}${rest}`:issue2.path;return where3?`${where3}: ${issue2.message}`:issue2.message})}function stackLines(stack){return stack.split(`
1032
+ `);let changed2=after!==text,dryRun4=input.dryRun===!0;changed2&&!dryRun4&&writeFileAtomically(file2,after,420);let result={file:file2,path:input.path,previous,value,changed:changed2,dryRun:dryRun4};return IntentOutputs2.of(result,{summary:describeSet(result)})}var package_default={name:"@sous-io/sous-plugin-config-files",version:"1.1.6",description:"sous.config.* as a contributor, config.set, and the .env files.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-lib-documents":"workspace:*","@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-expressions":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@sous-io/sous-plugin-variables":"workspace:*",tsx:"^4.21.0"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};import fs6 from"node:fs";import path8 from"node:path";function loadEnvFile(filePath,env){if(!fs6.existsSync(filePath))return{filePath,loaded:!1,applied:[],skipped:[]};let applied=[],skipped=[];for(let[key,value]of Object.entries(parseEnv(fs6.readFileSync(filePath,"utf8")))){if(env[key]!==void 0){skipped.push(key);continue}env[key]=value,applied.push(key)}return{filePath,loaded:!0,applied,skipped}}function loadEnvDefaults(sousDir,env){return loadEnvFile(path8.join(sousDir,ENV_SHARED_NAME),env)}function loadEnvLocal(sousDir,env){return loadEnvFile(path8.join(sousDir,ENV_LOCAL_NAME),env)}function loadEnvFiles(sousDir,env){let local2=loadEnvLocal(sousDir,env),defaults2=loadEnvDefaults(sousDir,env);return{local:local2,defaults:defaults2}}function projectEnvironment(project,env){let result={...env};return project!==void 0&&loadEnvFiles(project.sousDir,result),Object.freeze(result)}var PLUGIN_NAME="@sous-io/sous-plugin-config-files",MAIN_CONTRIBUTOR="config-files.main",PATCH_CONTRIBUTOR_PREFIX="config-files/",MAIN_APPLY_ORDER=89900,configFilesPlugin=definePlugin({name:PLUGIN_NAME,version:package_default.version,description:"sous.config.* as a contributor, config.set, and the .env files.",dependsOn:{"@sous-io/sous-plugin-expressions":`^${package_default.version}`,"@sous-io/sous-plugin-variables":`^${package_default.version}`,"@sous-io/sous-plugin-host":`^${package_default.version}`},register(sous){let loader=createLoader(sous);if(sous.services.add("config-files.loader",()=>loader,{lifetime:"singleton"}),sous.services.add("config-files.env",(_config,ctx)=>new EnvFilesService(ctx.project,ctx.env),{lifetime:"singleton"}),sous.config.contribute(mainContributor(loader,sous.project)),sous.project!==void 0)for(let file2 of loader.findPatches(sous.project.sousDir,MAIN_CONFIG_BASE_NAME))sous.config.contribute(fileContributor(loader,file2,`${PATCH_CONTRIBUTOR_PREFIX}${path9.basename(file2)}`));sous.intents.add({intent:CONFIG_SET,requiresProject:!0,summary:"Set one value in a config file",description:"Writes one value into sous.config.* (or the file --file names), changing only that key: comments, key order and formatting stay. The value is read as JSON when it is valid JSON, else as text. A main config written as code (sous.config.js or .ts) cannot be edited; name a JSON, JSONC or YAML file with --file.",input:jsonSchema2({type:"object",properties:{path:{type:"string",description:'The key path: compilation.includeSourceComments, subscriptions."workflow/x".enabled.'},value:{type:"string",description:"The value: JSON when it is valid JSON, else text."},unset:{type:"boolean",description:"Remove the key instead."},file:{type:"string",description:"The file to write: a conf.d file name, or a path from the project root. Default: sous.config.* when it is JSON, JSONC or YAML; a code config needs this."},dryRun:{type:"boolean",description:"Show what would change, writing nothing."}},required:["path"]}),changesConfig:!0,cli:{command:["config","set"],positional:["path","value"],examples:["sous config set compilation.includeSourceComments false",'sous config set subscriptions."workflow/x".enabled false --file 610-mac.jsonc',"sous config set name --unset"]},agent:{tool:"sous_config_set",usage:"Call this to change one config value without rewriting the file.",whenNotToUse:"Not for subscriptions or repositories: use their own intents, which keep the lockfile in step."},handle:(input,ctx)=>configSet(input,ctx)}),sous.entities.add("config-key",{id:"$schema",description:"The JSON Schema the file declares, for editors. Sous ignores it.",schema:jsonSchema2({type:"string"})}),sous.entities.add("config-key",{id:"version",description:"The config format version. This sous understands version 1.",schema:jsonSchema2({const:1})}),sous.entities.add("config-key",{id:"name",description:"A display name for the project.",schema:jsonSchema2({type:"string"})})}});function createLoader(sous){return new ConfigFilesLoaderImpl({get project(){return sous.project},globs:()=>sous.services.get("host.globs"),evaluator:()=>sous.services.has("expressions.evaluator")?sous.services.get("expressions.evaluator"):void 0,pathVariables:()=>{let variables={};if(sous.project!==void 0&&(variables.sousDir=sous.project.sousDir,variables.sousConfDir=sous.project.confDir),sous.services.has("host.package")){let identity2=sous.services.get("host.package").identity();variables.sousRootPath=identity2.root,variables.sousVersion=identity2.version}return variables}})}function mainContributor(loader,project){let source=project===void 0?void 0:project.configPath??mainCandidates(project.sousDir)[0];return{id:MAIN_CONTRIBUTOR,...source===void 0?{}:{source},applyOrder:MAIN_APPLY_ORDER,async contribute(config2){let project2=config2.project;if(project2===void 0)return;let candidates=mainCandidates(project2.sousDir),file2=project2.configPath??candidates[0];if(file2!==void 0){if(config2.contributor.run===1){if(candidates.length>1)throw new ConfigError7(`Duplicate config file baseName '${MAIN_CONFIG_BASE_NAME}':`,{details:[...candidates.map(candidate=>` ${candidate}`),"Two config files in one directory must not share a name once the final extension is removed. Delete or rename one of them."]});loader.forget(file2)}await applyFile(loader,file2,config2)}}}}function fileContributor(loader,file2,id){let format3=loader.formatOf(path9.basename(file2));return{id,source:file2,applyOrder:MAIN_APPLY_ORDER,...format3==="patch-json"||format3==="patch-jsonl"?{monitors:[""]}:{},async contribute(config2){config2.contributor.run===1&&loader.forget(file2),await applyFile(loader,file2,config2)}}}async function applyFile(loader,file2,config2){isFile2(file2)&&await loader.contribute(await loader.load(file2),config2)}function isFile2(file2){try{return fs7.statSync(file2).isFile()}catch{return!1}}import{definePlugin as definePlugin35}from"@sous-io/sous-plugin-api";import os from"node:os";import{definePlugin as definePlugin2,IntentOutput as IntentOutput4,IntentOutputs as IntentOutputs7,jsonSchema as jsonSchema5,LOG_LEVELS,TextBlock as TextBlock4,VariableSet as VariableSet2}from"@sous-io/sous-plugin-api";import{ConflictError as ConflictError3,toJsonSchema}from"@sous-io/sous-plugin-api";function toKebab(name){return name.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}function suggest(typed,candidates){let limit2=Math.max(2,Math.floor(typed.length/3)),scored=[];for(let word of new Set(candidates)){let distance=editDistance(typed.toLowerCase(),word.toLowerCase());distance<=limit2?scored.push({word,score:distance}):typed.length>=2&&word.startsWith(typed)&&scored.push({word,score:limit2+1})}return scored.sort((a,b)=>a.score-b.score||(a.word<b.word?-1:1)).slice(0,3).map(item=>item.word)}function editDistance(a,b){let previous=Array.from({length:b.length+1},(_2,index)=>index);for(let i=1;i<=a.length;i++){let current=[i];for(let j2=1;j2<=b.length;j2++){let cost=a[i-1]===b[j2-1]?0:1;current[j2]=Math.min(previous[j2]+1,current[j2-1]+1,previous[j2-1]+cost)}previous=current}return previous[b.length]}function argumentsFromSchema(schema,cli={}){let properties=schema?.properties??{},required2=new Set(schema?.required??[]),flags=[];for(let[field,property]of Object.entries(properties)){let options2=cli.flags?.[field]??{},{kind,multiple}=kindOf(property),name=toKebab(field),aliases2=(options2.aliases??[]).filter(alias2=>alias2.length>1),shorts=extraShorts(kind,[name,...aliases2],options2).filter(letter=>letter!==options2.short);flags.push({field,name,aliases:aliases2,short:options2.short??shorts[0],shorts:options2.short?shorts:shorts.slice(1),kind,multiple,description:property.description,defaultValue:property.default,choices:choicesOf(property),required:required2.has(field)&&property.default===void 0,hidden:options2.hidden??!1})}let names2=cli.positional??[],positionals=names2.map((field,index)=>{let property=properties[field]??{},{kind,multiple}=kindOf(property);return{field,name:toKebab(field),kind,variadic:multiple&&index===names2.length-1,required:required2.has(field)&&property.default===void 0,description:property.description}});return{flags,positionals}}var CONFIRMATION_SHORTS={yes:"y",force:"f"};function extraShorts(kind,names2,options2){let letters=(options2.aliases??[]).filter(alias2=>alias2.length===1);if(kind==="boolean")for(let name of names2){let letter=CONFIRMATION_SHORTS[name];letter&&letters.push(letter)}return[...new Set(letters)]}function kindOf(property){let type=primaryType(property);if(type==="array"){let itemType=property.items?primaryType(property.items):"string";return{kind:scalarKind(itemType),multiple:!0}}return type===void 0&&property.enum?{kind:property.enum.every(item=>typeof item=="number")?"number":"string",multiple:!1}:{kind:scalarKind(type),multiple:!1}}function scalarKind(type){switch(type){case"boolean":case"number":case"integer":case"string":return type;case"object":return"json";default:return"string"}}function primaryType(property){if(Array.isArray(property.type))return property.type.find(type=>type!=="null");if(property.type)return property.type;let option=property.anyOf?.find(item=>item.type!=="null");return option?primaryType(option):void 0}function choicesOf(property){if(property.enum)return property.enum;if(property.items?.enum)return property.items.enum}function convertValue(raw2,kind,flag){switch(kind){case"number":case"integer":{let value=Number(raw2);return raw2.trim()===""||Number.isNaN(value)||kind==="integer"&&!Number.isInteger(value)?{error:`${flag} takes ${kind==="integer"?"a whole number":"a number"}, not "${raw2}".`}:{value}}case"json":try{return{value:JSON.parse(raw2)}}catch{return{error:`${flag} takes JSON, and "${raw2}" is not valid JSON.`}}case"boolean":return{value:raw2===""||raw2==="true"};default:return{value:raw2}}}var CommandTree=class _CommandTree{root=newNode([]);warnings=[];static build(intents,groups,picks={}){let tree=new _CommandTree,claims=new Map;for(let info of intents){let definition2=info.definition;if(definition2.internal)continue;let cli=definition2.cli??{},path122=cli.command??definition2.intent.split("."),command={intent:definition2.intent,plugin:info.plugin,info,path:path122,aliases:cli.aliases??[],hidden:cli.hidden??!1,...argumentsFromSchema(toJsonSchema(definition2.input),cli)};for(let[words2,viaAlias]of[[path122,!1],...command.aliases.map(alias2=>[alias2,!0])]){let key=words2.join(" "),list2=claims.get(key)??[];list2.push({command,viaAlias}),claims.set(key,list2)}}for(let[key,list2]of claims){let winner=tree.pick(key,list2,picks),node=tree.ensure(key.split(" "));node.command=winner.command,node.viaAlias=winner.viaAlias}for(let group of groups)tree.ensure(group.command).group=group;return markCanonical(tree.root),tree.shareAliasedGroups(groups),tree}find(words2){let node=this.root,used=0;for(let word of words2){let next=node.children.get(word);if(!next)break;node=next,used+=1}return{node,used}}commands(){let found=new Set,visit3=node=>{node.command&&!node.viaAlias&&found.add(node.command),node.children.forEach(visit3)};return visit3(this.root),[...found]}aliasesOf(command){let found=[...command.aliases],seen=new Set([command.path.join(" "),...found.map(words2=>words2.join(" "))]);for(let length=1;length<command.path.length;length+=1){let group=this.groupAt(command.path.slice(0,length));for(let alias2 of group?.aliases??[]){let words2=[...alias2,...command.path.slice(length)],key=words2.join(" ");!seen.has(key)&&this.find(words2).node.command===command&&(seen.add(key),found.push(words2))}}return found}groupAt(words2){let{node,used}=this.find(words2);return used===words2.length&&node.group?.command.join(" ")===words2.join(" ")?node.group:void 0}shareAliasedGroups(groups){for(let group of groups){let canonical=this.find(group.command);if(canonical.used===group.command.length)for(let alias2 of group.aliases??[]){let node=this.ensure(alias2);node.group??=group,node.canonical=!1;for(let[word,child2]of canonical.node.children)(child2.canonical||!node.children.has(word))&&node.children.set(word,child2);node.command??=canonical.node.command,node.viaAlias||=canonical.node.command!==void 0}}}pick(key,list2,picks){let distinct2=list2.filter((claim,index)=>list2.findIndex(other=>other.command===claim.command)===index);if(distinct2.length===1)return distinct2[0];let plugins=distinct2.map(claim=>claim.command.plugin),described=distinct2.map(claim=>`intent "${claim.command.intent}" (${claim.command.plugin})`).join(" and "),picked=picks[key],chosen=distinct2.find(claim=>claim.command.plugin===picked);if(!chosen)throw new ConflictError3(`cli:${key}`,plugins,`Two commands claim "${key}": ${described}.`,{details:[`Choose one in the config: cli.pick."${key}": "${plugins[0]}"`]});let others=distinct2.filter(claim=>claim!==chosen).map(claim=>claim.command.plugin).join(" and ");return this.warnings.push(`cli.pick picks ${chosen.command.plugin} for "${key}". ${others}'s command is ignored there, and may not work as expected.`),chosen}ensure(words2){let node=this.root;for(let word of words2){let next=node.children.get(word);next||(next=newNode([...node.path,word]),node.children.set(word,next)),node=next}return node}};function newNode(path122){return{path:path122,children:new Map,command:void 0,viaAlias:!1,group:void 0,canonical:!1}}function markCanonical(node){let canonical=node.command!==void 0&&!node.viaAlias;for(let child2 of node.children.values())canonical=markCanonical(child2)||canonical;return node.canonical=canonical||node.group!==void 0,node.canonical}import{isSousError as isSousError2,isSousErrorOfKind,SousError as SousError7}from"@sous-io/sous-plugin-api";function describeError(error51,options2={}){if(isSousError2(error51)){let details2=isSousErrorOfKind(error51,"input")&&options2.command?inputDetails(error51,options2.command):[...error51.details];return options2.debug&&error51.stack&&details2.push(...stackLines(error51.stack)),{summary:error51.message,details:details2,exitCode:error51.exitCode}}let details=options2.debug&&error51 instanceof Error&&error51.stack?stackLines(error51.stack):[];return{summary:error51 instanceof Error?error51.message:String(error51),details,exitCode:1}}function errorForDisplay(error51,command){if(!(error51 instanceof Error))return new Error(String(error51));if(command&&isSousErrorOfKind(error51,"input")){let input=error51,copy=new SousError7(input.message,{details:inputDetails(input,command),exitCode:input.exitCode,...input.cause===void 0?{}:{cause:input.cause}});return copy.stack=input.stack,copy}return error51}function viewError(error51,options2={}){let parts=describeError(error51,options2);return{lines:[`Error: ${parts.summary}`,...parts.details.map(line=>` ${line}`)],exitCode:parts.exitCode}}function inputDetails(error51,command){return error51.issues.map(issue2=>{let field=issue2.path.split(/[.[]/)[0]??"",positional=command.positionals.find(spec=>spec.field===field),flag=command.flags.find(spec=>spec.field===field),rest=issue2.path.slice(field.length),where3=positional?`<${positional.name}>${rest}`:flag?`--${flag.name}${rest}`:issue2.path;return where3?`${where3}: ${issue2.message}`:issue2.message})}function stackLines(stack){return stack.split(`
1033
1033
  `).slice(1).map(line=>line.trim())}import{IntentOutput as IntentOutput2,IntentOutputs as IntentOutputs5,isLogLevel,isSousErrorOfKind as isSousErrorOfKind2,LogLevel as LogLevel3,SousError as SousError8,TextBlock as TextBlock3}from"@sous-io/sous-plugin-api";import{IntentOutput,IntentOutputs as IntentOutputs3,jsonSchema as jsonSchema3,TextBlock}from"@sous-io/sous-plugin-api";import{toJsonSchema as toJsonSchema2}from"@sous-io/sous-plugin-api";function globalSpecs(entities){return entities.map(entity=>{let schema=toJsonSchema2(entity.schema)??{},type=Array.isArray(schema.type)?schema.type[0]:schema.type,kind=type==="boolean"||type==="number"||type==="integer"?type:(schema.enum||type==="string","string");return{field:entity.id,name:entity.id,aliases:[],short:entity.short,shorts:[],kind,multiple:type==="array",description:entity.description,defaultValue:schema.default,choices:schema.enum,required:!1,hidden:entity.hidden??!1,valueName:entity.valueName??"value"}})}var COMPLETION_SHELLS=["bash","zsh","fish"],COMPLETE_COMMAND="__complete";function completeWords(tree,words2,globalNames){let typed=words2.at(-1)??"",node=tree.root;for(let word of words2.slice(0,-1)){if(word.startsWith("-"))continue;let next=node.children.get(word);if(!next)break;node=next}let candidates=typed.startsWith("-")?[...(node.command?.flags??[]).filter(flag=>!flag.hidden).flatMap(flag=>[`--${flag.name}`,...flag.aliases.map(alias2=>`--${alias2}`)]),...globalNames.map(name=>`--${name}`),"--help"]:[...node.children.values()].filter(child2=>child2.canonical&&!child2.group?.hidden&&!child2.command?.hidden).map(child2=>child2.path.at(-1));return[...new Set(candidates)].filter(word=>word.startsWith(typed)).sort()}function completionScript(shell,appName){let fn=`_${appName.replace(/[^A-Za-z0-9_]/g,"_")}_complete`;switch(shell){case"bash":return[`# ${appName} completion for bash. Add to ~/.bashrc: eval "$(${appName} completion bash)"`,`${fn}() {`," local IFS=$'\\n'",` COMPREPLY=($(${appName} ${COMPLETE_COMMAND} "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))`,"}",`complete -o default -F ${fn} ${appName}`,""].join(`
1034
1034
  `);case"zsh":return[`# ${appName} completion for zsh. Add to ~/.zshrc: eval "$(${appName} completion zsh)"`,`${fn}() {`," local -a words_next",` words_next=("\${(@f)$(${appName} ${COMPLETE_COMMAND} "\${(@)words[2,CURRENT]}" 2>/dev/null)}")`," compadd -a words_next","}",`compdef ${fn} ${appName}`,""].join(`
1035
1035
  `);case"fish":return[`# ${appName} completion for fish. Add to ~/.config/fish/config.fish: ${appName} completion fish | source`,`function ${fn}`," set -l words (commandline -opc) (commandline -ct)",` ${appName} ${COMPLETE_COMMAND} $words[2..-1] 2>/dev/null`,"end",`complete -c ${appName} -f -a '(${fn})'`,""].join(`
@@ -1041,13 +1041,14 @@ ${problem}`}throw new CancelledError2(question.message,`the answer was not accep
1041
1041
  `}function aliasLines(node,context){let lines3=[],group=node.group;if(group!==void 0&&(group.aliases??[]).length>0){let here=node.path.join(" ");lines3.push(...[group.command,...group.aliases??[]].filter(words2=>words2.join(" ")!==here))}let command=node.command;return command!==void 0&&!(node.viaAlias&&group!==void 0&&lines3.length>0)&&lines3.push(...context.tree?.aliasesOf(command)??command.aliases),lines3}function argumentName(spec){return spec.name.toUpperCase().replaceAll("-","_")}function visibleChildren(node){return sortedChildren(node).filter(child2=>!child2.group?.hidden&&(child2.group!==void 0||child2.viaAlias&&child2.command?.hidden!==!0||countCommands(child2)>0))}function hiddenChildren(node){return sortedChildren(node).filter(child2=>child2.command!==void 0)}function sortedChildren(node){return[...node.children.values()].filter(child2=>child2.canonical).sort((a,b)=>a.path.at(-1)<b.path.at(-1)?-1:1)}function summaryOf(node){if(node.group)return node.group.summary;if(node.command&&!node.viaAlias)return node.command.info.definition.summary??"";let count2=countCommands(node);return`${count2} command${count2===1?"":"s"}`}function countCommands(node){let count2=node.command&&!node.viaAlias&&!node.command.hidden?1:0;for(let child2 of node.children.values())count2+=countCommands(child2);return count2}function positionalUsage(positionals){return positionals.map(spec=>{let name=spec.variadic?`${argumentName(spec)}...`:argumentName(spec);return spec.required?` ${name}`:` [${name}]`}).join("")}function positionalText(spec){return spec.description??""}function flagLabel(flag){let value=flag.kind==="boolean"?"":` <${valueName(flag)}>`;return`${flag.short?`-${flag.short}, `:""}--${flag.name}${value}`}function globalLabel(spec){let value=spec.kind==="boolean"?"":` <${spec.valueName}>`;return`${spec.short?`-${spec.short}, `:""}--${spec.name}${value}`}function valueName(flag){switch(flag.kind){case"number":case"integer":return"number";case"json":return"json";default:return flag.choices?"choice":"value"}}function flagText(flag){let parts=[flag.description??""],others=[...flag.shorts.map(letter=>`-${letter}`),...flag.aliases.map(alias2=>`--${alias2}`)];others.length>0&&parts.push(`(also ${others.join(", ")})`),flag.choices&&flag.choices.length>0&&parts.push(`One of: ${flag.choices.map(String).join(", ")}.`),flag.required?parts.push("Required."):flag.defaultValue!==void 0&&!(flag.kind==="boolean"&&flag.defaultValue===!1)&&parts.push(`Default: ${JSON.stringify(flag.defaultValue)}.`),flag.multiple&&parts.push("May be given more than once.");let head=parts.slice(0,others.length>0?2:1).filter(part=>part!=="").join(" "),sentences=parts.slice(others.length>0?2:1);return[sentences.length>0&&head!==""&&!/[.!?]$/.test(head)?`${head}.`:head,...sentences].filter(part=>part!=="").join(" ")}function section(style,title2,lines3){return[style.heading(title2),...lines3.map(line=>` ${line.startsWith("$ ")?style.value(line):line}`)].join(`
1042
1042
  `)}function rowsSection(style,title2,rows){let width=Math.min(32,Math.max(...rows.map(([left])=>left.length)));return[style.heading(title2),...rows.map(([left,right])=>right===""?` ${style.label(left)}`:left.length>width?` ${style.label(left)}
1043
1043
  ${" ".repeat(width)} ${right}`:` ${style.label(left.padEnd(width))} ${right}`)].join(`
1044
- `)}var HelpPage=class extends Payload{constructor(node,context){super();this.node=node;this.context=context}kind="help-page";render(style){return renderHelp(this.node,{...this.context,style})}toText(){return renderHelp(this.node,this.context)}toPlain(){return{text:this.toText()}}};import{parseArgs}from"node:util";function parseLine(argv2,tree,globalSpecs2,appName="sous"){let globalsByToken=tokenMap(globalSpecs2),words2=[],rest=[],node=tree.root,index=0;for(;index<argv2.length;index++){let token=argv2[index];if(token==="--")break;if(token.startsWith("-")){let spec=globalsByToken.get(token.split("=")[0]);rest.push(token),spec&&spec.kind!=="boolean"&&!token.includes("=")&&index+1<argv2.length&&rest.push(argv2[++index]);continue}let next=node.children.get(token);if(!next)break;node=next,words2.push(token)}rest.push(...argv2.slice(index));let command=node.command,flags=command?mergeFlags(command.flags,globalSpecs2):[...globalSpecs2],passThrough=command?.info.definition.cli?.passThrough===!0?splitPassThrough(rest,flags):void 0,parsed=runParseArgs(passThrough?.own??rest,flags);passThrough&&(parsed.positionals=passThrough.passed);let globals=collectValues(globalSpecs2,parsed.values);if(parsed.error)return{kind:"error",message:parsed.error.message,details:parsed.error.details,node,globals:globals.values,showHelp:!0};if(globals.error)return{kind:"error",message:globals.error,details:[],node,globals:globals.values,showHelp:!0};if(parsed.values.help===!0)return{kind:"help",node,globals:globals.values};if(parsed.values.version===!0&&node===tree.root)return{kind:"version",globals:globals.values};if(!command){let typed=parsed.positionals[0];if(typed===void 0)return{kind:"help",node,globals:globals.values};let prefix=node.path.length>0?`${node.path.join(" ")} `:"",options2=suggest(typed,[...node.children.keys()]);return{kind:"error",message:`There is no command "${prefix}${typed}".`,details:options2.length>0?[`Did you mean ${options2.map(option=>`"${prefix}${option}"`).join(" or ")}?`]:[],node,globals:globals.values}}let input=collectValues(command.flags,parsed.values,!0);if(input.error)return{kind:"error",message:input.error,details:[],node,globals:globals.values,showHelp:!0};let positional=assignPositionals(command,parsed.positionals,input.values,appName);if(positional.error){let options2=node.children.size>0?suggest(parsed.positionals[0]??"",[...node.children.keys()]):[];return{kind:"error",message:positional.error,details:[...positional.details??[],...options2.length>0?[`Did you mean "${[...node.path,options2[0]].join(" ")}"?`]:[]],node,globals:globals.values,showHelp:!0}}let missing=missingRequired(command,input.values);return missing?{kind:"error",...missing,node,globals:globals.values,showHelp:!0}:{kind:"run",command,node,input:input.values,globals:globals.values}}function tokenMap(specs){let map3=new Map;for(let spec of specs){map3.set(`--${spec.name}`,spec),spec.kind==="boolean"&&map3.set(`--no-${spec.name}`,spec);for(let letter of[spec.short,...spec.shorts])letter&&map3.set(`-${letter}`,spec)}return map3}function splitPassThrough(args,flags){let known=tokenMap(flags),own=[],passed2=[];for(let flag of flags)for(let alias2 of flag.aliases)known.set(`--${alias2}`,flag);for(let index=0;index<args.length;index++){let token=args[index];if(token==="--"){passed2.push(...args.slice(index+1));break}let name=token.split("=")[0],spec=known.get(name);if(!token.startsWith("-")||token==="-"||spec===void 0&&!["-h","--help","--version"].includes(name)){passed2.push(token);continue}own.push(token),spec&&spec.kind!=="boolean"&&!token.includes("=")&&index+1<args.length&&own.push(args[++index])}return{own,passed:passed2}}function mergeFlags(own,globals){let names2=new Set(own.flatMap(flag=>[flag.name,...flag.aliases]));return[...own,...globals.filter(flag=>!names2.has(flag.name))]}function runParseArgs(args,flags){let options2={help:{type:"boolean",short:"h"},version:{type:"boolean"}},used=new Set(["h",...flags.flatMap(flag=>flag.short?[flag.short]:[])]),extraNames=new Map;for(let flag of flags){let option={type:flag.kind==="boolean"?"boolean":"string",multiple:flag.multiple,...flag.short?{short:flag.short}:{}};options2[flag.name]=option;let names2=[...flag.aliases];for(let alias2 of flag.aliases)options2[alias2]={type:option.type,multiple:option.multiple};for(let letter of flag.shorts)used.has(letter)||(used.add(letter),names2.push(`\0${flag.name}:${letter}`),options2[`\0${flag.name}:${letter}`]={type:option.type,multiple:option.multiple,short:letter});extraNames.set(flag.name,names2)}try{let{values,positionals}=parseArgs({args,options:options2,strict:!0,allowPositionals:!0,allowNegative:!0});for(let flag of flags){let positive=flag.name.startsWith("no-")?flag.name.slice(3):void 0;flag.kind==="boolean"&&positive!==void 0&&options2[positive]===void 0&&values[positive]!==void 0&&(values[flag.name]=!values[positive],delete values[positive])}for(let flag of flags)for(let alias2 of extraNames.get(flag.name)??[])values[alias2]!==void 0&&values[flag.name]===void 0&&(values[flag.name]=values[alias2]),alias2.startsWith("\0")&&delete values[alias2];return{values,positionals}}catch(error51){return{values:{},positionals:[],error:describeParseError(error51,flags)}}}function describeParseError(error51,flags){let message2=error51 instanceof Error?error51.message:String(error51),unknown2=/Unknown option '(-{1,2}[^']+)'/.exec(message2)?.[1];if(unknown2){let names2=flags.flatMap(flag=>[`--${flag.name}`,...flag.aliases.map(alias2=>`--${alias2}`)]),options2=suggest(unknown2,[...names2,"--help"]);return{message:`Nonexistent flag: ${unknown2}`,details:options2.length>0?[`Did you mean ${options2.join(" or ")}?`]:[]}}let missingValue2=/Option '(-{1,2}[^' ]+)(?: [^']*)?' argument missing/.exec(message2)?.[1];return missingValue2?{message:`Flag ${missingValue2} expects a value`,details:[]}:{message:message2.replace(/\. To specify a positional argument.*$/,"."),details:[]}}function missingRequired(command,input){let args=command.positionals.filter(spec=>spec.required&&input[spec.field]===void 0);if(args.length>0){let width=Math.max(...args.map(spec=>spec.name.length));return{message:`Missing ${args.length} required arg${args.length===1?"":"s"}:`,details:args.map(spec=>spec.description?`${spec.name.padEnd(width)} ${spec.description}`:spec.name)}}let flag=command.flags.find(spec=>spec.required&&input[spec.field]===void 0&&!command.positionals.some(p=>p.field===spec.field));return flag?{message:`Missing required flag --${flag.name}`,details:[]}:void 0}function collectValues(specs,values,checkChoices=!1){let out={};for(let spec of specs){let raw2=values[spec.name];if(raw2===void 0)continue;if(spec.kind==="boolean"){out[spec.field]=raw2;continue}let items2=Array.isArray(raw2)?raw2:[raw2],converted=[];for(let item of items2){let result=convertValue(String(item),spec.kind,`--${spec.name}`);if("error"in result)return{values:out,error:result.error};if(checkChoices&&spec.choices&&spec.choices.length>0&&!spec.choices.includes(result.value))return{values:out,error:`Expected --${spec.name}=${String(item)} to be one of: ${spec.choices.map(String).join(", ")}`};converted.push(result.value)}out[spec.field]=spec.multiple?converted:converted[0]}return{values:out}}function assignPositionals(command,positionals,input,appName){let index=0;for(let spec of command.positionals){if(index>=positionals.length)break;let taken=spec.variadic?positionals.slice(index):[positionals[index]],converted=[];for(let raw2 of taken){let result=convertValue(raw2,spec.kind,`<${spec.name}>`);if("error"in result)return{error:result.error};converted.push(result.value)}if(input[spec.field]!==void 0)return{error:`<${spec.name}> was given both as an argument and as --${spec.name}.`};input[spec.field]=spec.variadic?converted:converted[0],index+=taken.length}if(index<positionals.length){let extra=positionals[index],words2=[appName,...command.path].join(" ");return{error:`Unexpected argument: ${extra}`,details:[`"${words2}" takes ${command.positionals.length===0?"no arguments":`at most ${command.positionals.length} argument${command.positionals.length===1?"":"s"}`}.`]}}return{}}import{createInterface}from"node:readline";import{NonInteractiveError}from"@sous-io/sous-plugin-api";var TerminalPrompter=class{constructor(input,output,interactive,reason){this.input=input;this.output=output;this.interactive=interactive;this.reason=reason}reader;lines=[];waiting=[];closed=!1;async askValue(question){for(this.refuseUnlessInteractive(question);;){let suffix=question.default!==void 0&&question.secret!==!0?` (${question.default})`:"",answer2=(await this.ask(`${question.message}${suffix} `,question)).trim()||question.default||"",problem=question.validate?.(answer2);if(!problem)return answer2;this.output.write(`${problem}
1045
- `)}}async askChoice(question){this.refuseUnlessInteractive(question);let lines3=question.choices.map((choice,index)=>` ${index+1}. ${choice.label}${choice.description?`: ${choice.description}`:""}`);for(this.output.write(`${question.message}
1044
+ `)}var HelpPage=class extends Payload{constructor(node,context){super();this.node=node;this.context=context}kind="help-page";render(style){return renderHelp(this.node,{...this.context,style})}toText(){return renderHelp(this.node,this.context)}toPlain(){return{text:this.toText()}}};import{parseArgs}from"node:util";function parseLine(argv2,tree,globalSpecs2,appName="sous"){let globalsByToken=tokenMap(globalSpecs2),words2=[],rest=[],node=tree.root,index=0;for(;index<argv2.length;index++){let token=argv2[index];if(token==="--")break;if(token.startsWith("-")){let spec=globalsByToken.get(token.split("=")[0]);rest.push(token),spec&&spec.kind!=="boolean"&&!token.includes("=")&&index+1<argv2.length&&rest.push(argv2[++index]);continue}let next=node.children.get(token);if(!next)break;node=next,words2.push(token)}rest.push(...argv2.slice(index));let command=node.command,flags=command?mergeFlags(command.flags,globalSpecs2):[...globalSpecs2],passThrough=command?.info.definition.cli?.passThrough===!0?splitPassThrough(rest,flags):void 0,parsed=runParseArgs(passThrough?.own??rest,flags);passThrough&&(parsed.positionals=passThrough.passed);let globals=collectValues(globalSpecs2,parsed.values);if(parsed.error)return{kind:"error",message:parsed.error.message,details:parsed.error.details,node,globals:globals.values,showHelp:!0};if(globals.error)return{kind:"error",message:globals.error,details:[],node,globals:globals.values,showHelp:!0};if(parsed.values.help===!0)return{kind:"help",node,globals:globals.values};if(parsed.values.version===!0&&node===tree.root)return{kind:"version",globals:globals.values};if(!command){let typed=parsed.positionals[0];if(typed===void 0)return{kind:"help",node,globals:globals.values};let prefix=node.path.length>0?`${node.path.join(" ")} `:"",options2=suggest(typed,[...node.children.keys()]);return{kind:"error",message:`There is no command "${prefix}${typed}".`,details:options2.length>0?[`Did you mean ${options2.map(option=>`"${prefix}${option}"`).join(" or ")}?`]:[],node,globals:globals.values}}let input=collectValues(command.flags,parsed.values,!0);if(input.error)return{kind:"error",message:input.error,details:[],node,globals:globals.values,showHelp:!0};let positional=assignPositionals(command,parsed.positionals,input.values,appName);if(positional.error){let options2=node.children.size>0?suggest(parsed.positionals[0]??"",[...node.children.keys()]):[];return{kind:"error",message:positional.error,details:[...positional.details??[],...options2.length>0?[`Did you mean "${[...node.path,options2[0]].join(" ")}"?`]:[]],node,globals:globals.values,showHelp:!0}}let missing=missingRequired(command,input.values);return missing?{kind:"error",...missing,node,globals:globals.values,showHelp:!0}:{kind:"run",command,node,input:input.values,globals:globals.values}}function tokenMap(specs){let map3=new Map;for(let spec of specs){map3.set(`--${spec.name}`,spec),spec.kind==="boolean"&&map3.set(`--no-${spec.name}`,spec);for(let letter of[spec.short,...spec.shorts])letter&&map3.set(`-${letter}`,spec)}return map3}function splitPassThrough(args,flags){let known=tokenMap(flags),own=[],passed2=[];for(let flag of flags)for(let alias2 of flag.aliases)known.set(`--${alias2}`,flag);for(let index=0;index<args.length;index++){let token=args[index];if(token==="--"){passed2.push(...args.slice(index+1));break}let name=token.split("=")[0],spec=known.get(name);if(!token.startsWith("-")||token==="-"||spec===void 0&&!["-h","--help","--version"].includes(name)){passed2.push(token);continue}own.push(token),spec&&spec.kind!=="boolean"&&!token.includes("=")&&index+1<args.length&&own.push(args[++index])}return{own,passed:passed2}}function mergeFlags(own,globals){let names2=new Set(own.flatMap(flag=>[flag.name,...flag.aliases]));return[...own,...globals.filter(flag=>!names2.has(flag.name))]}function runParseArgs(args,flags){let options2={help:{type:"boolean",short:"h"},version:{type:"boolean"}},used=new Set(["h",...flags.flatMap(flag=>flag.short?[flag.short]:[])]),extraNames=new Map;for(let flag of flags){let option={type:flag.kind==="boolean"?"boolean":"string",multiple:flag.multiple,...flag.short?{short:flag.short}:{}};options2[flag.name]=option;let names2=[...flag.aliases];for(let alias2 of flag.aliases)options2[alias2]={type:option.type,multiple:option.multiple};for(let letter of flag.shorts)used.has(letter)||(used.add(letter),names2.push(`\0${flag.name}:${letter}`),options2[`\0${flag.name}:${letter}`]={type:option.type,multiple:option.multiple,short:letter});extraNames.set(flag.name,names2)}try{let{values,positionals}=parseArgs({args,options:options2,strict:!0,allowPositionals:!0,allowNegative:!0});for(let flag of flags){let positive=flag.name.startsWith("no-")?flag.name.slice(3):void 0;flag.kind==="boolean"&&positive!==void 0&&options2[positive]===void 0&&values[positive]!==void 0&&(values[flag.name]=!values[positive],delete values[positive])}for(let flag of flags)for(let alias2 of extraNames.get(flag.name)??[])values[alias2]!==void 0&&values[flag.name]===void 0&&(values[flag.name]=values[alias2]),alias2.startsWith("\0")&&delete values[alias2];return{values,positionals}}catch(error51){return{values:{},positionals:[],error:describeParseError(error51,flags)}}}function describeParseError(error51,flags){let message2=error51 instanceof Error?error51.message:String(error51),unknown2=/Unknown option '(-{1,2}[^']+)'/.exec(message2)?.[1];if(unknown2){let names2=flags.flatMap(flag=>[`--${flag.name}`,...flag.aliases.map(alias2=>`--${alias2}`)]),options2=suggest(unknown2,[...names2,"--help"]);return{message:`Nonexistent flag: ${unknown2}`,details:options2.length>0?[`Did you mean ${options2.join(" or ")}?`]:[]}}let missingValue2=/Option '(-{1,2}[^' ]+)(?: [^']*)?' argument missing/.exec(message2)?.[1];return missingValue2?{message:`Flag ${missingValue2} expects a value`,details:[]}:{message:message2.replace(/\. To specify a positional argument.*$/,"."),details:[]}}function missingRequired(command,input){let args=command.positionals.filter(spec=>spec.required&&input[spec.field]===void 0);if(args.length>0){let width=Math.max(...args.map(spec=>spec.name.length));return{message:`Missing ${args.length} required arg${args.length===1?"":"s"}:`,details:args.map(spec=>spec.description?`${spec.name.padEnd(width)} ${spec.description}`:spec.name)}}let flag=command.flags.find(spec=>spec.required&&input[spec.field]===void 0&&!command.positionals.some(p=>p.field===spec.field));return flag?{message:`Missing required flag --${flag.name}`,details:[]}:void 0}function collectValues(specs,values,checkChoices=!1){let out={};for(let spec of specs){let raw2=values[spec.name];if(raw2===void 0)continue;if(spec.kind==="boolean"){out[spec.field]=raw2;continue}let items2=Array.isArray(raw2)?raw2:[raw2],converted=[];for(let item of items2){let result=convertValue(String(item),spec.kind,`--${spec.name}`);if("error"in result)return{values:out,error:result.error};if(checkChoices&&spec.choices&&spec.choices.length>0&&!spec.choices.includes(result.value))return{values:out,error:`Expected --${spec.name}=${String(item)} to be one of: ${spec.choices.map(String).join(", ")}`};converted.push(result.value)}out[spec.field]=spec.multiple?converted:converted[0]}return{values:out}}function assignPositionals(command,positionals,input,appName){let index=0;for(let spec of command.positionals){if(index>=positionals.length)break;let taken=spec.variadic?positionals.slice(index):[positionals[index]],converted=[];for(let raw2 of taken){let result=convertValue(raw2,spec.kind,`<${spec.name}>`);if("error"in result)return{error:result.error};converted.push(result.value)}if(input[spec.field]!==void 0)return{error:`<${spec.name}> was given both as an argument and as --${spec.name}.`};input[spec.field]=spec.variadic?converted:converted[0],index+=taken.length}if(index<positionals.length){let extra=positionals[index],words2=[appName,...command.path].join(" ");return{error:`Unexpected argument: ${extra}`,details:[`"${words2}" takes ${command.positionals.length===0?"no arguments":`at most ${command.positionals.length} argument${command.positionals.length===1?"":"s"}`}.`]}}return{}}import{createInterface}from"node:readline";import{NonInteractiveError}from"@sous-io/sous-plugin-api";var TerminalPrompter=class{constructor(input,output,interactive,reason){this.input=input;this.output=output;this.interactive=interactive;this.reason=reason}reader;lines=[];waiting=[];closed=!1;async askValue(question){for(this.refuseUnlessInteractive(question),this.setApart();;){let suffix=question.default!==void 0&&question.secret!==!0?` (${question.default})`:"",answer2=(await this.ask(`${question.message}${suffix} `,question)).trim()||question.default||"",problem=question.validate?.(answer2);if(!problem)return answer2;this.output.write(`${problem}
1045
+ `)}}async askChoice(question){this.refuseUnlessInteractive(question);let lines3=question.choices.map((choice,index)=>` ${index+1}. ${choice.label}${choice.description?`: ${choice.description}`:""}`);for(this.setApart(),this.output.write(`${question.message}
1046
1046
  ${lines3.join(`
1047
1047
  `)}
1048
1048
  `);;){let fallback2=question.defaultIndex!==void 0?` (${question.defaultIndex+1})`:"",answer2=(await this.ask(`Pick a number${fallback2}: `,question)).trim(),index=answer2===""&&question.defaultIndex!==void 0?question.defaultIndex:Number(answer2)-1,choice=question.choices[index];if(Number.isInteger(index)&&choice)return choice.value;this.output.write(`Pick a number from 1 to ${question.choices.length}.
1049
- `)}}async confirm(question){this.refuseUnlessInteractive(question);let hint=question.default===!0?"[Y/n]":question.default===!1?"[y/N]":"[y/n]";for(;;){let answer2=(await this.ask(`${question.message} ${hint} `,question)).trim().toLowerCase();if(answer2===""&&question.default!==void 0)return question.default;if(answer2==="y"||answer2==="yes")return!0;if(answer2==="n"||answer2==="no")return!1;this.output.write(`Answer yes or no.
1050
- `)}}refuseUnlessInteractive(question){if(!this.interactive)throw new NonInteractiveError(question.message,question.answeredBy,this.reason===void 0?{}:{details:[`Why: ${this.reason}.`]})}ask(prompt,question){if(question.secret===!0&&this.input.isTTY===!0&&typeof this.input.setRawMode=="function"&&this.lines.length===0)return this.askSecret(prompt,question);this.output.write(prompt);let buffered=this.lines.shift();if(buffered!==void 0)return Promise.resolve(buffered);let ended=()=>new NonInteractiveError(question.message,question.answeredBy,{details:["Standard input ended before it was answered."]});return this.closed?Promise.reject(ended()):(this.reader??=this.openReader(),this.reader.resume(),new Promise((resolve4,reject2)=>this.waiting.push(line=>line===void 0?reject2(ended()):resolve4(line))))}askSecret(prompt,question){let input=this.input;return this.output.write(prompt),this.reader?.pause(),input.setRawMode(!0),input.resume(),new Promise((resolve4,reject2)=>{let value="",finish4=error51=>{input.off("data",onData),input.setRawMode(!1),input.pause(),this.output.write(`
1049
+ `)}}async confirm(question){this.refuseUnlessInteractive(question);let hint=question.default===!0?"[Y/n]":question.default===!1?"[y/N]":"[y/n]";for(this.setApart();;){let answer2=(await this.ask(`${question.message} ${hint} `,question)).trim().toLowerCase();if(answer2===""&&question.default!==void 0)return question.default;if(answer2==="y"||answer2==="yes")return!0;if(answer2==="n"||answer2==="no")return!1;this.output.write(`Answer yes or no.
1050
+ `)}}refuseUnlessInteractive(question){if(!this.interactive)throw new NonInteractiveError(question.message,question.answeredBy,this.reason===void 0?{}:{details:[`Why: ${this.reason}.`]})}setApart(){this.output.write(`
1051
+ `)}ask(prompt,question){if(question.secret===!0&&this.input.isTTY===!0&&typeof this.input.setRawMode=="function"&&this.lines.length===0)return this.askSecret(prompt,question);this.output.write(prompt);let buffered=this.lines.shift();if(buffered!==void 0)return Promise.resolve(buffered);let ended=()=>new NonInteractiveError(question.message,question.answeredBy,{details:["Standard input ended before it was answered."]});return this.closed?Promise.reject(ended()):(this.reader??=this.openReader(),this.reader.resume(),new Promise((resolve4,reject2)=>this.waiting.push(line=>line===void 0?reject2(ended()):resolve4(line))))}askSecret(prompt,question){let input=this.input;return this.output.write(prompt),this.reader?.pause(),input.setRawMode(!0),input.resume(),new Promise((resolve4,reject2)=>{let value="",finish4=error51=>{input.off("data",onData),input.setRawMode(!1),input.pause(),this.output.write(`
1051
1052
  `),error51?reject2(error51):resolve4(value)},onData=chunk=>{for(let char of chunk.toString()){if(char==="\r"||char===`
1052
1053
  `){finish4();return}if(char===""||char===""){finish4(new NonInteractiveError(question.message,question.answeredBy,{details:["The question was stopped before it was answered."]}));return}if(char==="\x7F"||char==="\b"){value.length>0&&(value=value.slice(0,-1),this.output.write("\b \b"));continue}value+=char,this.output.write("*")}};input.on("data",onData)})}openReader(){let reader=createInterface({input:this.input,terminal:!1});return reader.on("line",line=>{let next=this.waiting.shift();next?next(line):this.lines.push(line),this.waiting.length===0&&reader.pause()}),reader.on("close",()=>{this.closed=!0;for(let next of this.waiting.splice(0))next(void 0)}),reader}};function canPrompt(io,env,globals={}){return whyCannotPrompt(io,env,globals)===void 0}function whyCannotPrompt(io,env,globals={}){if(globals["non-interactive"]===!0)return"the '--non-interactive' flag was passed";let ci2=env.CI;if(ci2!==void 0&&!["","0","false"].includes(ci2.trim().toLowerCase()))return`the 'CI' environment variable is set to '${ci2}'`;let stdin=io.stdin.isTTY===!0,stdout=io.stdout.isTTY===!0;return!stdin&&!stdout?"neither input nor output is a terminal":stdin?stdout?void 0:"output is not a terminal":"input is not a terminal"}import{BaseReporter as BaseReporter2,LogLevel as LogLevel2,messageText,ReportEntryStyle as ReportEntryStyle2}from"@sous-io/sous-plugin-api";var SGR_PATTERN=/\u001B\[[0-9;]*m/g;function columnsFromEnvironment(env){let text=env?.COLUMNS?.trim()??"",columns=/^\d+$/.test(text)?Number(text):0;return columns>0?columns:void 0}var RIGHT_MARGIN=2,BULLET="\u2022";function stripAnsi(text){return String(text??"").replace(SGR_PATTERN,"")}function displayWidth(text){return stripAnsi(text).length}function terminalColumns(stream){let columns=stream?.columns;return typeof columns=="number"&&columns>0?columns:100}function wrapColumnsOf(columns){return Math.max(20,columns-RIGHT_MARGIN)}function indent(text,count2=2,char=" "){return text.split(`
1053
1054
  `).map(line=>char.repeat(count2)+line).join(`
@@ -1071,7 +1072,7 @@ ${lines3.join(`
1071
1072
  ${help(line.node)}`,LogLevel3.Error);break}case"run":{let prompter=new TerminalPrompter(io.stdin,io.stderr,canPrompt(io,env,line.globals),whyCannotPrompt(io,env,line.globals)),intent=line.command.intent,submitOptions={reporter,prompter,globals:line.globals,...options2.cwd===void 0?{}:{cwd:options2.cwd}},background=engine.intents.get(intent)?.definition.background===!0,show2=async outputs=>{showOutputs(outputs,{reporter,stdout:io.stdout,json:line.globals.json===!0}),reporter.finish(),outputs.exitCode!==void 0&&outputs.exitCode!==0&&io.setExitCode(outputs.exitCode)},fail=error51=>{reportError(reporter,error51,{debug,command:line.command},io),wantsHelp(error51)&&reporter.text(`
1072
1073
  ${help(line.node)}`,LogLevel3.Error)};io.stderr.isTTY===!0&&!json3&&engine.intents.get(intent)?.definition.runsWithoutConfig!==!0&&reporter.banner();try{let outputs=await engine.submit({intent,input:line.input},submitOptions);background||await show2(outputs),startedWatching(outputs)&&await watchUntilStopped(engine,io,reporter,intent,line.input,submitOptions,show2,fail)}catch(error51){fail(error51)}break}}line.globals.timings===!0&&reportTimings(reporter,engine.timings.entries())}catch(error51){handedOver||engine.setReporter(reporter),reportError(reporter,engine.configError??error51,{debug},io)}finally{reporter.finish()}}function commandLineNeedsConfig(engine,argv2){let tree=engine.config.services.get("cli.commands"),specs=globalSpecs(engine.config.entities.list("cli-global-argument")),line=parseLine(versionArgv(argv2,tree),tree,specs,engine.app.name);switch(line.kind){case"help":case"version":return!1;case"run":return engine.intents.get(line.command.intent)?.definition.runsWithoutConfig!==!0;default:return!0}}function commandLinePlan(engine,argv2){let tree=engine.config.services.get("cli.commands"),specs=globalSpecs(engine.config.entities.list("cli-global-argument")),line=parseLine(versionArgv(argv2,tree),tree,specs,engine.app.name);switch(line.kind){case"help":case"version":return{intent:void 0};case"run":{let definition2=engine.intents.get(line.command.intent)?.definition;return definition2===void 0?void 0:{intent:definition2}}default:return}}function reportError(reporter,error51,options2,io){let parts=describeError(error51,{...options2,debug:!1});reporter.critical(errorForDisplay(error51,options2.command)),options2.debug&&error51 instanceof Error&&error51.stack&&reporter.text(error51.stack.split(`
1073
1074
  `).slice(1).join(`
1074
- `),LogLevel3.Error),io.setExitCode(parts.exitCode)}var DEBUG_OFF=new Set(["","0","false","no","off"]);function debugRequested(env){let raw2=env.SOUS_DEBUG;return raw2!==void 0&&!DEBUG_OFF.has(raw2.trim().toLowerCase())}function wantsHelp(error51){return isSousErrorOfKind2(error51,"input")}function versionArgv(argv2,tree){return argv2[0]===COMPLETE_COMMAND?[COMPLETE_COMMAND,"--",...argv2.slice(1)]:argv2[0]==="--version"&&argv2.length>1&&argv2.slice(1).every(token=>token==="--verbose")&&tree.root.children.get("version")?.command?["version","--verbose"]:argv2}function thresholdOf(globals){if(globals.debug===!0)return LogLevel3.Debug;let level=globals["log-level"];return isLogLevel(level)?level:LogLevel3.Info}async function watchUntilStopped(engine,io,reporter,intent,input,submitOptions,show2,fail){if(io.stdin.isTTY!==!0){await engine.whenBackgroundIntentsReturn();return}reporter.note(WATCH_KEYS_HINT);let rebuilding,stop=listenForWatchKeys(io.stdin,{quit:()=>{stop(),io.interrupt?.()},rebuild:()=>{rebuilding||(reporter.notice("Manual rebuild triggered."),rebuilding=engine.submit({intent,input:{...input,watch:!1}},submitOptions).then(show2,fail).finally(()=>{rebuilding=void 0}))}});try{await engine.whenBackgroundIntentsReturn(),await rebuilding}finally{stop()}}var BUILT_IN_GROUPS=[{id:"config",command:["config"],summary:"Inspect the merged configuration",aliases:[["configs"],["cfg"]]},{id:"repo",command:["repo"],summary:"Manage the recipe repositories this project trusts",aliases:[["repos"]]},{id:"lock",command:["lock"],summary:"Inspect and repair this project's lockfile",aliases:[["locks"]]},{id:"namespace",command:["namespace"],summary:"Browse the namespaces the trusted repositories publish",aliases:[["namespaces"],["ns"]]},{id:"recipe",command:["recipe"],summary:"Browse the recipes the trusted repositories publish",aliases:[["recipes"],["rc"]]},{id:"subscription",command:["subscription"],summary:"Manage which recipes this project subscribes to",aliases:[["subscriptions"],["sub"]]},{id:"vars",command:["vars"],summary:"Recipe variables and their answers",aliases:[["var"]]},{id:"plugins",command:["plugins"],summary:"Show and install the plugins sous loads"},{id:"timings",command:["timings"],summary:"Show how long each step of this run took"}];import{IntentOutput as IntentOutput3,IntentOutputs as IntentOutputs6,jsonSchema as jsonSchema4,SousError as SousError9}from"@sous-io/sous-plugin-api";var helpIntent={intent:"help",summary:"Print the help for sous, or for one command or topic",input:jsonSchema4({type:"object",properties:{command:{type:"array",items:{type:"string"},description:"The command to show help for."}}}),cli:{positional:["command"],examples:["sous help repo add"]},parallel:!0,runsWithoutConfig:!0,handle:(rawInput,ctx)=>{let input=rawInput,tree=ctx.services.get("cli.commands"),words2=input.command??[],{node,used}=tree.find(words2);if(used<words2.length){let prefix=used>0?`${words2.slice(0,used).join(" ")} `:"",options2=suggest(words2[used],[...node.children.keys()]);throw new SousError9(`There is no command "${prefix}${words2[used]}".`,{exitCode:2,details:options2.length>0?[`Did you mean ${options2.map(option=>`"${prefix}${option}"`).join(" or ")}?`]:[]})}let page=new HelpPage(node,{appName:ctx.engine.app.name,globals:globalSpecs(ctx.entities.list("cli-global-argument")),tree});return new IntentOutputs6(new IntentOutput3({result:page,data:{text:page.toText()}}))}};function processIo(){return{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin,setExitCode(code){process.exitCode=code},interrupt(){process.kill(process.pid,"SIGINT")}}}var package_default2={name:"@sous-io/sous-plugin-cli",version:"1.1.4",description:"The sous command-line front end, generated from intents",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*",zod:"^4.4.3"},engines:{node:">=22"}};var CLI_PLUGIN_NAME="@sous-io/sous-plugin-cli",BUILT_IN_GLOBAL_ARGUMENTS=[{id:"config",short:"c",schema:jsonSchema5({type:"string"}),description:"Path to a sous config file (or a directory containing one). Overrides .sous/ discovery.",valueName:"path"},{id:"sous-config",schema:jsonSchema5({type:"string"}),description:"Alias of --config: path to a sous config file (or a directory containing one).",valueName:"path"},{id:"sous-dir",schema:jsonSchema5({type:"string"}),description:"Path to the .sous directory to use (overrides walk-up discovery).",valueName:"path"},{id:"sous-confd",schema:jsonSchema5({type:"string"}),description:"Path to the conf.d drop-in layer directory (overrides <sousDir>/conf.d).",valueName:"path"},{id:"debug",schema:jsonSchema5({type:"boolean",default:!1}),description:"Show every message, debug ones included (the same as --log-level debug)."},{id:"log-level",schema:jsonSchema5({type:"string",enum:[...LOG_LEVELS]}),description:"Show messages at this level and above.",valueName:"level"},{id:"timings",schema:jsonSchema5({type:"boolean",default:!1}),description:"Print every timing when the command finishes."},{id:"json",schema:jsonSchema5({type:"boolean",default:!1}),description:"Print the result as JSON instead of the formatted output."},{id:"non-interactive",schema:jsonSchema5({type:"boolean",default:!1}),description:"Never ask a question; fail with the flag that answers it instead."}];function createCliPlugin(options2={}){let io=options2.io??processIo;return definePlugin2({name:CLI_PLUGIN_NAME,version:package_default2.version,description:"The command-line front end, generated from intents.",register(sous){sous.entities.define("cli-global-argument",jsonSchema5({type:"object",properties:{id:{type:"string"},description:{type:"string"},short:{type:"string"},valueName:{type:"string"},hidden:{type:"boolean"}},required:["id","schema","description"]}),{description:"An argument every command accepts."}),sous.entities.define("cli-group",jsonSchema5({type:"object",properties:{id:{type:"string"},command:{type:"array",items:{type:"string"}},summary:{type:"string"},description:{type:"string"},hidden:{type:"boolean"},aliases:{type:"array",items:{type:"array",items:{type:"string"}}}},required:["id","command","summary"]}),{description:"The help of a command group."});for(let argument of BUILT_IN_GLOBAL_ARGUMENTS)sous.entities.add("cli-global-argument",argument);sous.entities.add("config-key",{id:"cli",description:'CLI settings: cli.pick."<command words>": "<plugin>" picks between two commands claiming the same words.',schema:jsonSchema5({type:"object",properties:{pick:{type:"object",additionalProperties:{type:"string"},default:{}}}})});for(let group of BUILT_IN_GROUPS)sous.entities.add("cli-group",group);sous.services.add("cli.commands",(config2,ctx)=>CommandTree.build(sous.engine.intents.list(),ctx.entities.list("cli-group"),config2.get("cli.pick")??{}),{lifetime:"config"}),sous.services.add("cli.interactivity",()=>({canPrompt:globals=>canPrompt(io(),sous.env,globals)}),{lifetime:"singleton"}),sous.services.add("cli.errors",()=>({view:(error51,viewOptions)=>viewError(error51,viewOptions)}),{lifetime:"singleton"}),sous.intents.add(helpIntent),sous.intents.add(completionIntent),sous.intents.add(completeIntent),sous.intents.add({intent:"version",summary:"Print the version",input:jsonSchema5({type:"object",properties:{verbose:{type:"boolean",default:!1,description:"Also print the package, where it is installed, the platform and the Node build."}}}),parallel:!0,runsWithoutConfig:!0,agent:{tool:"sous_version",usage:"Call this to learn which sous version serves this project."},handle:(input,ctx)=>{let{name,version:version2}=ctx.engine.app,text=new TextBlock4(`v${version2}`,{verbatim:!0});if(!input.verbose)return new IntentOutputs7(new IntentOutput4({result:text,data:{name,version:version2}}));let identity2=ctx.services.has("host.package")?ctx.services.get("host.package").identity():void 0,platform=`${os.platform()}-${os.arch()}`,facts={Package:identity2?.name??name,...identity2===void 0?{}:{Install:identity2.root},Platform:platform,Node:process.version};return new IntentOutputs7([new IntentOutput4({result:text}),new IntentOutput4({result:new VariableSet2(facts),data:{name:identity2?.name??name,version:version2,...identity2===void 0?{}:{root:identity2.root},platform,node:process.version}})])}}),sous.frontEnds.add({id:"cli",start:(engine,argv2)=>runCommandLine(engine,argv2,{io:io(),env:sous.env,cwd:process.cwd()}),needsConfig:(engine,argv2)=>commandLineNeedsConfig(engine,argv2),plan:(engine,argv2)=>commandLinePlan(engine,argv2)})}})}var cliPlugin=createCliPlugin();init_src2();init_src3();init_src4();import{definePlugin as definePlugin6}from"@sous-io/sous-plugin-api";var AUTO_VARIABLE_NAMES=["projectRoot","sousDir","sousConfigPath","sousConfDir","sousHome","sousRootPath","sousVersion"],NAMES=new Set(AUTO_VARIABLE_NAMES);function isAutoVariable(name){return NAMES.has(name)}function buildAutoVariables(inputs){let vars={sousRootPath:inputs.packageRoot,sousVersion:inputs.version,sousHome:inputs.sousHome},project=inputs.project;return project&&(vars.projectRoot=project.root,vars.sousDir=project.sousDir,vars.sousConfDir=project.confDir,project.configPath!==void 0&&(vars.sousConfigPath=project.configPath)),vars}var ENV_PREFIX="SOUS_VAR_",VARIABLE_NAME_PATTERN=/^[a-z][a-zA-Z0-9]*$/,ENV_NAME_PATTERN=/^[A-Z][A-Z0-9_]*$/;function toUpperSnake(name){return name.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/[-\s.]+/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"").toUpperCase()}function sharedName(variable){return`${ENV_PREFIX}${toUpperSnake(variable)}`}function recipeScopedName(namespace,recipe,variable){return`${ENV_PREFIX}${toUpperSnake(namespace)}_${toUpperSnake(recipe)}_${toUpperSnake(variable)}`}function namespaceScopedName(namespace,variable){return`${ENV_PREFIX}${toUpperSnake(namespace)}_${toUpperSnake(variable)}`}function bareName(definition2){return definition2.env??sharedName(definition2.name)}var variablesNames={envPrefix:ENV_PREFIX,toUpperSnake,sharedName,recipeScopedName,namespaceScopedName,bareName,isVariableName:text=>VARIABLE_NAME_PATTERN.test(text),isEnvName:text=>ENV_NAME_PATTERN.test(text)};init_src();import path19 from"node:path";import{ConfigError as ConfigError17}from"@sous-io/sous-plugin-api";import path18 from"node:path";import{ConfigError as ConfigError16}from"@sous-io/sous-plugin-api";var REFERENCE=/(\$?)\$\{([^}]+)\}/g;function substitute(text,scope){return text.replace(REFERENCE,(match2,escape4,name)=>escape4!==""?match2.slice(1):Object.hasOwn(scope,name)?scope[name]:match2)}function references(text){return[...new Set([...text.matchAll(REFERENCE)].filter(match2=>match2[1]==="").map(match2=>match2[2]))]}function unresolved(text,scope={}){return references(text).filter(name=>!Object.hasOwn(scope,name))}function substituteStrict(text,scope,context){let missing=unresolved(text,scope),result=substitute(text,scope);if(missing.length===0)return result;let names2=missing.map(name=>`\${${name}}`).join(", "),one=missing.length===1,available=Object.keys(scope).sort();throw new ConfigError16(`Unresolved ${one?"variable":"variables"} ${names2} in ${context}`,{details:[`raw value: ${text}`,`Define ${one?"it":"them"} in a _vars block, or map ${one?"it":"them"} from the environment via the top-level _env block (values can come from .sous/.env.local or .sous/.env).`,`Variables in scope here: ${available.length>0?available.join(", "):"(none)"}`]})}function substituteValue(value,scope,context){return walk2(value,scope,context)}function walk2(value,scope,context){if(typeof value=="string")return substituteStrict(value,scope,context);if(Array.isArray(value))return value.map((item,index)=>walk2(item,scope,`${context}[${index}]`));if(value!==null&&typeof value=="object"){let out={};for(let[key,item]of Object.entries(value))out[key]=walk2(item,scope,context===""?key:`${context}.${key}`);return out}return value}function normalizePath2(value,home){let result=value;return home!==void 0&&home!==""&&(result==="~"?result=home:result.startsWith("~/")&&(result=path18.join(home,result.slice(2)))),path18.isAbsolute(result)?path18.normalize(result):result}function resolveBlock(block,inherited,context,options2={}){let entries=new Map;for(let[key,value]of Object.entries(block))if(value!=null){if(isAutoVariable(key)){if(options2.partial||restatesAutoVariable(key,value,inherited))continue;throw autoVariableError(key,context)}entries.set(key,typeof value=="string"?value:String(value))}let scope={...inherited},waiting=new Set(entries.keys()),resolved=[],progressed=!0;for(;progressed&&waiting.size>0;){progressed=!1;for(let key of waiting){let written=entries.get(key);references(written).every(name=>Object.hasOwn(scope,name))&&(scope[key]=substitute(written,scope),waiting.delete(key),resolved.push(key),progressed=!0)}}if(waiting.size>0&&!options2.partial)throw unresolvedBlockError(entries,scope,waiting,context);return{scope,resolved,pending:[...waiting]}}function restatesAutoVariable(name,value,inherited){let own=inherited[name];if(own===void 0||typeof value!="string")return!1;let written=substitute(value,inherited);return written===own||references(written).length===0&&path19.resolve(written)===path19.resolve(own)}function autoVariableError(name,context){return new ConfigError17(`${context} sets "${name}", which sous sets itself.`,{details:[`Remove "${name}" from ${context}; \${${name}} always holds the value sous gives it.`]})}function unresolvedBlockError(entries,scope,waiting,context){let needs=new Map;for(let key of waiting)needs.set(key,references(entries.get(key)).filter(name=>!Object.hasOwn(scope,name)));let edges=new Map;for(let key of waiting)edges.set(key,needs.get(key).filter(name=>waiting.has(name)));let cycles=findCycles([...waiting],edges),undefinedRefs=new Map;for(let key of waiting)for(let name of needs.get(key))if(!waiting.has(name)){let referrers=undefinedRefs.get(name)??new Set;referrers.add(key),undefinedRefs.set(name,referrers)}let details=[];for(let key of[...waiting].sort()){let names2=needs.get(key).map(name=>`\${${name}}`).join(", ");details.push(`- ${key} still needs ${names2||"(nothing resolvable)"}`)}if(cycles.length>0){details.push("","Reference cycles (these variables reference each other):");for(let cycle of cycles){let sorted2=[...cycle].sort();details.push(`- ${[...sorted2,sorted2[0]].join(" -> ")}`)}}if(undefinedRefs.size>0){details.push("","Undefined references (names defined nowhere: no _vars, _env, or auto-variable):");for(let name of[...undefinedRefs.keys()].sort())details.push(`- \${${name}} (needed by ${[...undefinedRefs.get(name)].sort().join(", ")})`)}let inScope=Object.keys(scope).sort();return details.push("",`Variables in scope here: ${inScope.length>0?inScope.join(", "):"(none)"}`),new ConfigError17(`Unresolved variables in ${context}:`,{details})}function findCycles(nodes,edges){let index=new Map,low=new Map,onStack=new Set,stack=[],components=[],counter=0,connect=node=>{index.set(node,counter),low.set(node,counter),counter++,stack.push(node),onStack.add(node);for(let next of edges.get(node)??[])index.has(next)?onStack.has(next)&&low.set(node,Math.min(low.get(node),index.get(next))):(connect(next),low.set(node,Math.min(low.get(node),low.get(next))));if(low.get(node)===index.get(node)){let component=[],member;do member=stack.pop(),onStack.delete(member),component.push(member);while(member!==node);components.push(component)}};for(let node of nodes)index.has(node)||connect(node);return components.filter(component=>component.length>1||(edges.get(component[0])??[]).includes(component[0]))}import{ConfigError as ConfigError18,SousError as SousError13}from"@sous-io/sous-plugin-api";var ENV_LOCAL_NAME2=".env.local",ENV_DEFAULTS_NAME=".env";function buildScope(view,autoVariables,request,partial2){let scope={},origins={},lay=(values,from,skipAuto)=>{for(let[name,value]of Object.entries(values??{}))typeof value!="string"||skipAuto&&isAutoVariable(name)||(scope[name]=value,origins[name]={from,value})};lay(autoVariables,"auto",!1);let sources=view.sources(),context={project:view.project,env:view.env,config:view.lookup};for(let source of sources)lay(source.variables(context),source.id,!0);if(request.scopeKey!==void 0)for(let source of sources)lay(source.scoped?.(request.scopeKey,context),source.id,!0);lay(envScope(view,partial2),"_env",!1);let current=scope,block=(path122,values)=>{if(!isRecord(values))return;let result=resolveBlock(values,current,path122,{partial:partial2});for(let name of result.resolved)origins[name]={from:path122,value:result.scope[name]};current=result.scope};block("_vars",view.get("_vars"));let level=request.level??"root";if(level!=="root"&&block("compilation._vars",view.get("compilation._vars")),level==="target"||level==="output"){let targetPath=`compilation.targets[${requireIndex(request.target,"target",level)}]`;if(block(`${targetPath}._vars`,view.get(`${targetPath}._vars`)),level==="output"){let output=requireIndex(request.output,"output",level),outputPath=`${targetPath}.outputs[${output}]`;block(`${outputPath}._vars`,view.get(`${outputPath}._vars`))}}request.extra!==void 0&&block("extra",request.extra);let kept={};for(let name of Object.keys(current))kept[name]=origins[name];return{scope:current,origins:kept}}function envScope(view,partial2){let mapping=view.get("_env"),scope={};if(!isRecord(mapping))return scope;for(let[name,envName]of Object.entries(mapping)){if(typeof envName!="string")continue;if(isAutoVariable(name)){if(partial2)continue;throw autoVariableError(name,"_env")}let value=view.env[envName];if(value===void 0){if(partial2)continue;throw unsetEnvError(name,envName,view.project)}scope[name]=value}return scope}function unsetEnvError(name,envName,project){let sousDir=project?.sousDir,local2=sousDir?`${sousDir}/${ENV_LOCAL_NAME2}`:`.sous/${ENV_LOCAL_NAME2}`,defaults2=sousDir?`${sousDir}/${ENV_DEFAULTS_NAME}`:`.sous/${ENV_DEFAULTS_NAME}`;return new ConfigError18(`_env resolution failed: environment variable '${envName}' (mapped to config var '${name}') is not set.`,{details:[`Define it in ${local2} as:`,` ${envName}=<value>`,`...or, if the value is shared by the whole team and is not a secret, in ${defaults2} (committed).`,"...or export it in your shell before running sous."]})}function requireIndex(index,what,level){if(index===void 0||!Number.isInteger(index)||index<0)throw new SousError13(`A scope at the ${level} level needs the ${what} index.`);return index}function isRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}var Resolver=class{constructor(deps){this.deps=deps}cache=new WeakMap;substitute(text,scope){return substitute(text,scope)}substituteStrict(text,scope,context){return substituteStrict(text,scope,context)}substituteValue(value,scope,context){return substituteValue(value,scope,context)}references(text){return references(text)}unresolved(text,scope){return unresolved(text,scope)}normalizePath(value){return normalizePath2(value,this.deps.env.HOME??this.deps.env.USERPROFILE)}resolveBlock(block,inherited,context){return resolveBlock(block,inherited,context).scope}autoVariables(){return this.autoFor(this.deps.env,this.deps.project)}isAutoVariable(name){return isAutoVariable(name)}scope(request={}){return this.build(this.deps.engine.config,request).scope}scopeIn(config2,request={}){return this.build(config2,request).scope}origins(request={}){return this.build(this.deps.engine.config,request).origins}originsIn(config2,request={}){return this.build(config2,request).origins}requestAt(path122){let segments=typeof path122=="string"?parsePath(path122):path122;if(segments[0]!=="compilation")return{level:"root"};let target=segments[2];if(segments[1]!=="targets"||typeof target!="number")return{level:"compilation"};let output=segments[4];return segments[3]!=="outputs"||typeof output!="number"?{level:"target",target}:{level:"output",target,output}}build(config2,request){if(isBuilder(config2)){let view2=builderView(config2);return buildScope(view2,this.autoFor(view2.env,view2.project),request,request.partial??!0)}let cacheable=isBuiltConfig(config2),partial2=request.partial??!cacheable,key=JSON.stringify([request.level,request.target,request.output,request.scopeKey,request.extra,partial2]),cached2=cacheable?this.cache.get(config2)?.get(key):void 0;if(cached2)return cached2;let entities=cacheable?config2.entities:this.deps.engine.config.entities,view=lookupView(config2,entities,this.deps.env,this.deps.project),built=buildScope(view,this.autoFor(view.env,view.project),request,partial2);if(cacheable){let forConfig=this.cache.get(config2)??new Map;forConfig.set(key,built),this.cache.set(config2,forConfig)}return built}autoFor(env,project){let identity2=this.deps.services.get("host.package").identity();return buildAutoVariables({project,sousHome:this.deps.services.get("host.sous-home").paths(env).root,packageRoot:identity2.root,version:identity2.version})}};function isBuilder(config2){let candidate=config2;return typeof candidate.atPath=="function"&&typeof candidate.entities=="function"}function isBuiltConfig(config2){let candidate=config2;return typeof candidate.hash=="string"&&typeof candidate.entities?.list=="function"}function builderView(builder){let lookup={get:path122=>builder.atPath(path122).get()};return{get:path122=>lookup.get(path122),sources:()=>builder.entities("variable-source"),lookup,env:builder.env,project:builder.project}}function lookupView(config2,entities,env,project){return{get:path122=>config2.get(path122),sources:()=>entities.list("variable-source"),lookup:config2,env,project}}function variableMap(what){return{"~standard":{version:1,vendor:"sous",validate(value){if(value===void 0)return{value:void 0};if(value===null||typeof value!="object"||Array.isArray(value))return{issues:[{message:`Expected an object of ${what}.`}]};let issues=[];for(let[name,item]of Object.entries(value))isAutoVariable(name)&&name!=="projectRoot"?issues.push({message:`"${name}" is set by sous; it cannot be set here. Remove it: \${${name}} always holds the value sous gives it.`,path:[name]}):typeof item!="string"&&issues.push({message:`Expected a string (${what}), got ${item===null?"null":typeof item}.`,path:[name]});return issues.length>0?{issues}:{value}}}}}var CONFIG_KEYS=[{id:"_vars",description:"Config variables, used as ${name}. Values may refer to each other in any order.",schema:variableMap("variable values")},{id:"_env",description:"Config variables read from the environment: each name mapped to an environment variable.",schema:variableMap("environment variable names")}],VARIABLE_SOURCE_SCHEMA={"~standard":{version:1,vendor:"sous",validate(value){let entry=value,issues=[];(typeof entry?.id!="string"||entry.id==="")&&issues.push({message:"A variable-source entity needs an id.",path:["id"]}),typeof entry?.description!="string"&&issues.push({message:"A variable-source entity needs a description.",path:["description"]}),typeof entry?.variables!="function"&&issues.push({message:"A variable-source entity needs a variables function.",path:["variables"]});for(let name of["scoped","secrets"])entry?.[name]!==void 0&&typeof entry[name]!="function"&&issues.push({message:`A variable-source entity's ${name} must be a function.`,path:[name]});return entry?.forbiddenUnder!==void 0&&!Array.isArray(entry.forbiddenUnder)&&issues.push({message:"A variable-source entity's forbiddenUnder must be a list of keys.",path:["forbiddenUnder"]}),issues.length>0?{issues}:{value}}}};var HIDDEN_VALUE="(hidden)",SECRET_NAME_ENDINGS=[["token"],["secret"],["secrets"],["password"],["passwd"],["passphrase"],["credential"],["credentials"],["apikey"],["api","key"],["private","key"],["access","key"],["secret","key"],["signing","key"],["encryption","key"]],SECRET_VALUE_PATTERNS=[/-----BEGIN [A-Z ]*PRIVATE KEY-----/,/\bgh[pousr]_[A-Za-z0-9]{36,}/,/\bgithub_pat_[A-Za-z0-9_]{22,}/,/\bglpat-[A-Za-z0-9_-]{20,}/,/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/,/\bxox[abposr]-[A-Za-z0-9-]{10,}/,/\b[rs]k_live_[A-Za-z0-9]{16,}/,/\bsk-ant-[A-Za-z0-9_-]{20,}/,/\bsk-(?:proj-)?[A-Za-z0-9_-]{32,}/,/\bAIza[0-9A-Za-z_-]{35}/,/\bnpm_[A-Za-z0-9]{36}\b/,/\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/,/^[a-z][a-z0-9+.-]*:\/\/[^/\s:@]+:[^/\s@]+@/i],PLAIN_VALUE=/^(?:|-?\d+(?:\.\d+)?|true|false|yes|no|on|off)$/i;function nameWords(name){return name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).filter(word=>word.length>0).map(word=>word.toLowerCase())}function hasSecretName(name){let words2=nameWords(name);return SECRET_NAME_ENDINGS.some(ending=>words2.length>=ending.length&&ending.every((word,i)=>words2[words2.length-ending.length+i]===word))}function hasSecretValue(value){return SECRET_VALUE_PATTERNS.some(pattern=>pattern.test(value))}function looksLikeSecret(name,value){return hasSecretValue(value)?!0:hasSecretName(name)&&!PLAIN_VALUE.test(value.trim())}function isSecret(name,value,declared=new Set){return typeof value!="string"?!1:declared.has(name)?value.length>0:looksLikeSecret(name,value)}function hideSecrets(scope,declared=new Set){let out={};for(let[name,value]of Object.entries(scope))out[name]=isSecret(name,value,declared)?HIDDEN_VALUE:value;return out}var Secrets=class{constructor(sources,context){this.sources=sources;this.context=context}hiddenValue=HIDDEN_VALUE;cached;declared(){if(!this.cached){let names2=new Set,context=this.context();for(let source of this.sources())for(let name of source.secrets?.(context)??[])names2.add(name);this.cached=names2}return this.cached}isSecret(name,value,declared=this.declared()){return isSecret(name,value,declared)}hasSecretName(name){return hasSecretName(name)}hasSecretValue(value){return hasSecretValue(value)}hide(scope,declared=this.declared()){return hideSecrets(scope,declared)}};var package_default6={name:"@sous-io/sous-plugin-variables",version:"1.1.4",description:"${var} substitution, _vars resolution, auto-variables, variable names and secrets.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-lib-documents":"workspace:*","@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-host":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME5="@sous-io/sous-plugin-variables",RESERVED_NAMES_CONTRIBUTOR="variables/reserved-names",variablesPlugin=definePlugin6({name:PLUGIN_NAME5,version:package_default6.version,description:"${var} substitution, _vars resolution, auto-variables, variable names and secrets.",dependsOn:{"@sous-io/sous-plugin-host":`^${package_default6.version}`},register(sous){sous.services.add("variables.resolver",(_config,ctx)=>new Resolver({services:sous.services,engine:sous.engine,env:ctx.env,get project(){return ctx.project}}),{lifetime:"singleton"}),sous.services.add("variables.names",()=>variablesNames,{lifetime:"singleton"}),sous.services.add("variables.secrets",(config2,ctx)=>new Secrets(()=>ctx.entities.list("variable-source"),()=>({project:ctx.project,env:ctx.env,config:config2})),{lifetime:"config"}),sous.services.add("variables.booleans",(config2,ctx)=>({declared:()=>declaredBooleans(ctx.entities.list("variable-source"),{project:ctx.project,env:ctx.env,config:config2})}),{lifetime:"config"}),sous.entities.define("variable-source",VARIABLE_SOURCE_SCHEMA,{description:"An extra source of config variables, such as recipe answers."});for(let key of CONFIG_KEYS)sous.entities.add("config-key",key);sous.config.contribute({id:RESERVED_NAMES_CONTRIBUTOR,contribute(config2){let vars=config2.atPath("_vars");for(let name of vars.isObject()?vars.keys():[])name.startsWith("sous")&&!isAutoVariable(name)&&config2.warn(`The variable "${name}" uses the reserved "sous*" namespace and may clash with a variable sous sets.`)}})}});function declaredBooleans(sources,ctx){return new Set(sources.flatMap(source=>source.booleans?.(ctx)??[]))}import{definePlugin as definePlugin7}from"@sous-io/sous-plugin-api";import{PassThrough}from"stream";import{sep as sep2,extname,resolve as resolve$1,dirname as dirname$1}from"path";import{statSync,readFileSync as readFileSync$1,stat,readFile as readFile$1}from"fs";import{createRequire as createRequire2}from"module";var Token=class{constructor(kind,input,begin,end,file2){this.kind=kind,this.input=input,this.begin=begin,this.end=end,this.file=file2}getText(){return this.input.slice(this.begin,this.end)}getPosition(){let[row,col]=[1,1];for(let i=0;i<this.begin;i++)this.input[i]===`
1075
+ `),LogLevel3.Error),io.setExitCode(parts.exitCode)}var DEBUG_OFF=new Set(["","0","false","no","off"]);function debugRequested(env){let raw2=env.SOUS_DEBUG;return raw2!==void 0&&!DEBUG_OFF.has(raw2.trim().toLowerCase())}function wantsHelp(error51){return isSousErrorOfKind2(error51,"input")}function versionArgv(argv2,tree){return argv2[0]===COMPLETE_COMMAND?[COMPLETE_COMMAND,"--",...argv2.slice(1)]:argv2[0]==="--version"&&argv2.length>1&&argv2.slice(1).every(token=>token==="--verbose")&&tree.root.children.get("version")?.command?["version","--verbose"]:argv2}function thresholdOf(globals){if(globals.debug===!0)return LogLevel3.Debug;let level=globals["log-level"];return isLogLevel(level)?level:LogLevel3.Info}async function watchUntilStopped(engine,io,reporter,intent,input,submitOptions,show2,fail){if(io.stdin.isTTY!==!0){await engine.whenBackgroundIntentsReturn();return}reporter.note(WATCH_KEYS_HINT);let rebuilding,stop=listenForWatchKeys(io.stdin,{quit:()=>{stop(),io.interrupt?.()},rebuild:()=>{rebuilding||(reporter.notice("Manual rebuild triggered."),rebuilding=engine.submit({intent,input:{...input,watch:!1}},submitOptions).then(show2,fail).finally(()=>{rebuilding=void 0}))}});try{await engine.whenBackgroundIntentsReturn(),await rebuilding}finally{stop()}}var BUILT_IN_GROUPS=[{id:"config",command:["config"],summary:"Inspect the merged configuration",aliases:[["configs"],["cfg"]]},{id:"repo",command:["repo"],summary:"Manage the recipe repositories this project trusts",aliases:[["repos"]]},{id:"lock",command:["lock"],summary:"Inspect and repair this project's lockfile",aliases:[["locks"]]},{id:"namespace",command:["namespace"],summary:"Browse the namespaces the trusted repositories publish",aliases:[["namespaces"],["ns"]]},{id:"recipe",command:["recipe"],summary:"Browse the recipes the trusted repositories publish",aliases:[["recipes"],["rc"]]},{id:"subscription",command:["subscription"],summary:"Manage which recipes this project subscribes to",aliases:[["subscriptions"],["sub"]]},{id:"vars",command:["vars"],summary:"Recipe variables and their answers",aliases:[["var"]]},{id:"plugins",command:["plugins"],summary:"Show and install the plugins sous loads"},{id:"timings",command:["timings"],summary:"Show how long each step of this run took"}];import{IntentOutput as IntentOutput3,IntentOutputs as IntentOutputs6,jsonSchema as jsonSchema4,SousError as SousError9}from"@sous-io/sous-plugin-api";var helpIntent={intent:"help",summary:"Print the help for sous, or for one command or topic",input:jsonSchema4({type:"object",properties:{command:{type:"array",items:{type:"string"},description:"The command to show help for."}}}),cli:{positional:["command"],examples:["sous help repo add"]},parallel:!0,runsWithoutConfig:!0,handle:(rawInput,ctx)=>{let input=rawInput,tree=ctx.services.get("cli.commands"),words2=input.command??[],{node,used}=tree.find(words2);if(used<words2.length){let prefix=used>0?`${words2.slice(0,used).join(" ")} `:"",options2=suggest(words2[used],[...node.children.keys()]);throw new SousError9(`There is no command "${prefix}${words2[used]}".`,{exitCode:2,details:options2.length>0?[`Did you mean ${options2.map(option=>`"${prefix}${option}"`).join(" or ")}?`]:[]})}let page=new HelpPage(node,{appName:ctx.engine.app.name,globals:globalSpecs(ctx.entities.list("cli-global-argument")),tree});return new IntentOutputs6(new IntentOutput3({result:page,data:{text:page.toText()}}))}};function processIo(){return{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin,setExitCode(code){process.exitCode=code},interrupt(){process.kill(process.pid,"SIGINT")}}}var package_default2={name:"@sous-io/sous-plugin-cli",version:"1.1.6",description:"The sous command-line front end, generated from intents",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*",zod:"^4.4.3"},engines:{node:">=22"}};var CLI_PLUGIN_NAME="@sous-io/sous-plugin-cli",BUILT_IN_GLOBAL_ARGUMENTS=[{id:"config",short:"c",schema:jsonSchema5({type:"string"}),description:"Path to a sous config file (or a directory containing one). Overrides .sous/ discovery.",valueName:"path"},{id:"sous-config",schema:jsonSchema5({type:"string"}),description:"Alias of --config: path to a sous config file (or a directory containing one).",valueName:"path"},{id:"sous-dir",schema:jsonSchema5({type:"string"}),description:"Path to the .sous directory to use (overrides walk-up discovery).",valueName:"path"},{id:"sous-confd",schema:jsonSchema5({type:"string"}),description:"Path to the conf.d drop-in layer directory (overrides <sousDir>/conf.d).",valueName:"path"},{id:"debug",schema:jsonSchema5({type:"boolean",default:!1}),description:"Show every message, debug ones included (the same as --log-level debug)."},{id:"log-level",schema:jsonSchema5({type:"string",enum:[...LOG_LEVELS]}),description:"Show messages at this level and above.",valueName:"level"},{id:"timings",schema:jsonSchema5({type:"boolean",default:!1}),description:"Print every timing when the command finishes."},{id:"json",schema:jsonSchema5({type:"boolean",default:!1}),description:"Print the result as JSON instead of the formatted output."},{id:"non-interactive",schema:jsonSchema5({type:"boolean",default:!1}),description:"Never ask a question; fail with the flag that answers it instead."}];function createCliPlugin(options2={}){let io=options2.io??processIo;return definePlugin2({name:CLI_PLUGIN_NAME,version:package_default2.version,description:"The command-line front end, generated from intents.",register(sous){sous.entities.define("cli-global-argument",jsonSchema5({type:"object",properties:{id:{type:"string"},description:{type:"string"},short:{type:"string"},valueName:{type:"string"},hidden:{type:"boolean"}},required:["id","schema","description"]}),{description:"An argument every command accepts."}),sous.entities.define("cli-group",jsonSchema5({type:"object",properties:{id:{type:"string"},command:{type:"array",items:{type:"string"}},summary:{type:"string"},description:{type:"string"},hidden:{type:"boolean"},aliases:{type:"array",items:{type:"array",items:{type:"string"}}}},required:["id","command","summary"]}),{description:"The help of a command group."});for(let argument of BUILT_IN_GLOBAL_ARGUMENTS)sous.entities.add("cli-global-argument",argument);sous.entities.add("config-key",{id:"cli",description:'CLI settings: cli.pick."<command words>": "<plugin>" picks between two commands claiming the same words.',schema:jsonSchema5({type:"object",properties:{pick:{type:"object",additionalProperties:{type:"string"},default:{}}}})});for(let group of BUILT_IN_GROUPS)sous.entities.add("cli-group",group);sous.services.add("cli.commands",(config2,ctx)=>CommandTree.build(sous.engine.intents.list(),ctx.entities.list("cli-group"),config2.get("cli.pick")??{}),{lifetime:"config"}),sous.services.add("cli.interactivity",()=>({canPrompt:globals=>canPrompt(io(),sous.env,globals)}),{lifetime:"singleton"}),sous.services.add("cli.errors",()=>({view:(error51,viewOptions)=>viewError(error51,viewOptions)}),{lifetime:"singleton"}),sous.intents.add(helpIntent),sous.intents.add(completionIntent),sous.intents.add(completeIntent),sous.intents.add({intent:"version",summary:"Print the version",input:jsonSchema5({type:"object",properties:{verbose:{type:"boolean",default:!1,description:"Also print the package, where it is installed, the platform and the Node build."}}}),parallel:!0,runsWithoutConfig:!0,agent:{tool:"sous_version",usage:"Call this to learn which sous version serves this project."},handle:(input,ctx)=>{let{name,version:version2}=ctx.engine.app,text=new TextBlock4(`v${version2}`,{verbatim:!0});if(!input.verbose)return new IntentOutputs7(new IntentOutput4({result:text,data:{name,version:version2}}));let identity2=ctx.services.has("host.package")?ctx.services.get("host.package").identity():void 0,platform=`${os.platform()}-${os.arch()}`,facts={Package:identity2?.name??name,...identity2===void 0?{}:{Install:identity2.root},Platform:platform,Node:process.version};return new IntentOutputs7([new IntentOutput4({result:text}),new IntentOutput4({result:new VariableSet2(facts),data:{name:identity2?.name??name,version:version2,...identity2===void 0?{}:{root:identity2.root},platform,node:process.version}})])}}),sous.frontEnds.add({id:"cli",start:(engine,argv2)=>runCommandLine(engine,argv2,{io:io(),env:sous.env,cwd:process.cwd()}),needsConfig:(engine,argv2)=>commandLineNeedsConfig(engine,argv2),plan:(engine,argv2)=>commandLinePlan(engine,argv2)})}})}var cliPlugin=createCliPlugin();init_src2();init_src3();init_src4();import{definePlugin as definePlugin6}from"@sous-io/sous-plugin-api";var AUTO_VARIABLE_NAMES=["projectRoot","sousDir","sousConfigPath","sousConfDir","sousHome","sousRootPath","sousVersion"],NAMES=new Set(AUTO_VARIABLE_NAMES);function isAutoVariable(name){return NAMES.has(name)}function buildAutoVariables(inputs){let vars={sousRootPath:inputs.packageRoot,sousVersion:inputs.version,sousHome:inputs.sousHome},project=inputs.project;return project&&(vars.projectRoot=project.root,vars.sousDir=project.sousDir,vars.sousConfDir=project.confDir,project.configPath!==void 0&&(vars.sousConfigPath=project.configPath)),vars}var ENV_PREFIX="SOUS_VAR_",VARIABLE_NAME_PATTERN=/^[a-z][a-zA-Z0-9]*$/,ENV_NAME_PATTERN=/^[A-Z][A-Z0-9_]*$/;function toUpperSnake(name){return name.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/[-\s.]+/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"").toUpperCase()}function sharedName(variable){return`${ENV_PREFIX}${toUpperSnake(variable)}`}function recipeScopedName(namespace,recipe,variable){return`${ENV_PREFIX}${toUpperSnake(namespace)}_${toUpperSnake(recipe)}_${toUpperSnake(variable)}`}function namespaceScopedName(namespace,variable){return`${ENV_PREFIX}${toUpperSnake(namespace)}_${toUpperSnake(variable)}`}function bareName(definition2){return definition2.env??sharedName(definition2.name)}var variablesNames={envPrefix:ENV_PREFIX,toUpperSnake,sharedName,recipeScopedName,namespaceScopedName,bareName,isVariableName:text=>VARIABLE_NAME_PATTERN.test(text),isEnvName:text=>ENV_NAME_PATTERN.test(text)};init_src();import path19 from"node:path";import{ConfigError as ConfigError17}from"@sous-io/sous-plugin-api";import path18 from"node:path";import{ConfigError as ConfigError16}from"@sous-io/sous-plugin-api";var REFERENCE=/(\$?)\$\{([^}]+)\}/g;function substitute(text,scope){return text.replace(REFERENCE,(match2,escape4,name)=>escape4!==""?match2.slice(1):Object.hasOwn(scope,name)?scope[name]:match2)}function references(text){return[...new Set([...text.matchAll(REFERENCE)].filter(match2=>match2[1]==="").map(match2=>match2[2]))]}function unresolved(text,scope={}){return references(text).filter(name=>!Object.hasOwn(scope,name))}function substituteStrict(text,scope,context){let missing=unresolved(text,scope),result=substitute(text,scope);if(missing.length===0)return result;let names2=missing.map(name=>`\${${name}}`).join(", "),one=missing.length===1,available=Object.keys(scope).sort();throw new ConfigError16(`Unresolved ${one?"variable":"variables"} ${names2} in ${context}`,{details:[`raw value: ${text}`,`Define ${one?"it":"them"} in a _vars block, or map ${one?"it":"them"} from the environment via the top-level _env block (values can come from .sous/.env.local or .sous/.env).`,`Variables in scope here: ${available.length>0?available.join(", "):"(none)"}`]})}function substituteValue(value,scope,context){return walk2(value,scope,context)}function walk2(value,scope,context){if(typeof value=="string")return substituteStrict(value,scope,context);if(Array.isArray(value))return value.map((item,index)=>walk2(item,scope,`${context}[${index}]`));if(value!==null&&typeof value=="object"){let out={};for(let[key,item]of Object.entries(value))out[key]=walk2(item,scope,context===""?key:`${context}.${key}`);return out}return value}function normalizePath2(value,home){let result=value;return home!==void 0&&home!==""&&(result==="~"?result=home:result.startsWith("~/")&&(result=path18.join(home,result.slice(2)))),path18.isAbsolute(result)?path18.normalize(result):result}function resolveBlock(block,inherited,context,options2={}){let entries=new Map;for(let[key,value]of Object.entries(block))if(value!=null){if(isAutoVariable(key)){if(options2.partial||restatesAutoVariable(key,value,inherited))continue;throw autoVariableError(key,context)}entries.set(key,typeof value=="string"?value:String(value))}let scope={...inherited},waiting=new Set(entries.keys()),resolved=[],progressed=!0;for(;progressed&&waiting.size>0;){progressed=!1;for(let key of waiting){let written=entries.get(key);references(written).every(name=>Object.hasOwn(scope,name))&&(scope[key]=substitute(written,scope),waiting.delete(key),resolved.push(key),progressed=!0)}}if(waiting.size>0&&!options2.partial)throw unresolvedBlockError(entries,scope,waiting,context);return{scope,resolved,pending:[...waiting]}}function restatesAutoVariable(name,value,inherited){let own=inherited[name];if(own===void 0||typeof value!="string")return!1;let written=substitute(value,inherited);return written===own||references(written).length===0&&path19.resolve(written)===path19.resolve(own)}function autoVariableError(name,context){return new ConfigError17(`${context} sets "${name}", which sous sets itself.`,{details:[`Remove "${name}" from ${context}; \${${name}} always holds the value sous gives it.`]})}function unresolvedBlockError(entries,scope,waiting,context){let needs=new Map;for(let key of waiting)needs.set(key,references(entries.get(key)).filter(name=>!Object.hasOwn(scope,name)));let edges=new Map;for(let key of waiting)edges.set(key,needs.get(key).filter(name=>waiting.has(name)));let cycles=findCycles([...waiting],edges),undefinedRefs=new Map;for(let key of waiting)for(let name of needs.get(key))if(!waiting.has(name)){let referrers=undefinedRefs.get(name)??new Set;referrers.add(key),undefinedRefs.set(name,referrers)}let details=[];for(let key of[...waiting].sort()){let names2=needs.get(key).map(name=>`\${${name}}`).join(", ");details.push(`- ${key} still needs ${names2||"(nothing resolvable)"}`)}if(cycles.length>0){details.push("","Reference cycles (these variables reference each other):");for(let cycle of cycles){let sorted2=[...cycle].sort();details.push(`- ${[...sorted2,sorted2[0]].join(" -> ")}`)}}if(undefinedRefs.size>0){details.push("","Undefined references (names defined nowhere: no _vars, _env, or auto-variable):");for(let name of[...undefinedRefs.keys()].sort())details.push(`- \${${name}} (needed by ${[...undefinedRefs.get(name)].sort().join(", ")})`)}let inScope=Object.keys(scope).sort();return details.push("",`Variables in scope here: ${inScope.length>0?inScope.join(", "):"(none)"}`),new ConfigError17(`Unresolved variables in ${context}:`,{details})}function findCycles(nodes,edges){let index=new Map,low=new Map,onStack=new Set,stack=[],components=[],counter=0,connect=node=>{index.set(node,counter),low.set(node,counter),counter++,stack.push(node),onStack.add(node);for(let next of edges.get(node)??[])index.has(next)?onStack.has(next)&&low.set(node,Math.min(low.get(node),index.get(next))):(connect(next),low.set(node,Math.min(low.get(node),low.get(next))));if(low.get(node)===index.get(node)){let component=[],member;do member=stack.pop(),onStack.delete(member),component.push(member);while(member!==node);components.push(component)}};for(let node of nodes)index.has(node)||connect(node);return components.filter(component=>component.length>1||(edges.get(component[0])??[]).includes(component[0]))}import{ConfigError as ConfigError18,SousError as SousError13}from"@sous-io/sous-plugin-api";var ENV_LOCAL_NAME2=".env.local",ENV_DEFAULTS_NAME=".env";function buildScope(view,autoVariables,request,partial2){let scope={},origins={},lay=(values,from,skipAuto)=>{for(let[name,value]of Object.entries(values??{}))typeof value!="string"||skipAuto&&isAutoVariable(name)||(scope[name]=value,origins[name]={from,value})};lay(autoVariables,"auto",!1);let sources=view.sources(),context={project:view.project,env:view.env,config:view.lookup};for(let source of sources)lay(source.variables(context),source.id,!0);if(request.scopeKey!==void 0)for(let source of sources)lay(source.scoped?.(request.scopeKey,context),source.id,!0);lay(envScope(view,partial2),"_env",!1);let current=scope,block=(path122,values)=>{if(!isRecord(values))return;let result=resolveBlock(values,current,path122,{partial:partial2});for(let name of result.resolved)origins[name]={from:path122,value:result.scope[name]};current=result.scope};block("_vars",view.get("_vars"));let level=request.level??"root";if(level!=="root"&&block("compilation._vars",view.get("compilation._vars")),level==="target"||level==="output"){let targetPath=`compilation.targets[${requireIndex(request.target,"target",level)}]`;if(block(`${targetPath}._vars`,view.get(`${targetPath}._vars`)),level==="output"){let output=requireIndex(request.output,"output",level),outputPath=`${targetPath}.outputs[${output}]`;block(`${outputPath}._vars`,view.get(`${outputPath}._vars`))}}request.extra!==void 0&&block("extra",request.extra);let kept={};for(let name of Object.keys(current))kept[name]=origins[name];return{scope:current,origins:kept}}function envScope(view,partial2){let mapping=view.get("_env"),scope={};if(!isRecord(mapping))return scope;for(let[name,envName]of Object.entries(mapping)){if(typeof envName!="string")continue;if(isAutoVariable(name)){if(partial2)continue;throw autoVariableError(name,"_env")}let value=view.env[envName];if(value===void 0){if(partial2)continue;throw unsetEnvError(name,envName,view.project)}scope[name]=value}return scope}function unsetEnvError(name,envName,project){let sousDir=project?.sousDir,local2=sousDir?`${sousDir}/${ENV_LOCAL_NAME2}`:`.sous/${ENV_LOCAL_NAME2}`,defaults2=sousDir?`${sousDir}/${ENV_DEFAULTS_NAME}`:`.sous/${ENV_DEFAULTS_NAME}`;return new ConfigError18(`_env resolution failed: environment variable '${envName}' (mapped to config var '${name}') is not set.`,{details:[`Define it in ${local2} as:`,` ${envName}=<value>`,`...or, if the value is shared by the whole team and is not a secret, in ${defaults2} (committed).`,"...or export it in your shell before running sous."]})}function requireIndex(index,what,level){if(index===void 0||!Number.isInteger(index)||index<0)throw new SousError13(`A scope at the ${level} level needs the ${what} index.`);return index}function isRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}var Resolver=class{constructor(deps){this.deps=deps}cache=new WeakMap;substitute(text,scope){return substitute(text,scope)}substituteStrict(text,scope,context){return substituteStrict(text,scope,context)}substituteValue(value,scope,context){return substituteValue(value,scope,context)}references(text){return references(text)}unresolved(text,scope){return unresolved(text,scope)}normalizePath(value){return normalizePath2(value,this.deps.env.HOME??this.deps.env.USERPROFILE)}resolveBlock(block,inherited,context){return resolveBlock(block,inherited,context).scope}autoVariables(){return this.autoFor(this.deps.env,this.deps.project)}isAutoVariable(name){return isAutoVariable(name)}scope(request={}){return this.build(this.deps.engine.config,request).scope}scopeIn(config2,request={}){return this.build(config2,request).scope}origins(request={}){return this.build(this.deps.engine.config,request).origins}originsIn(config2,request={}){return this.build(config2,request).origins}requestAt(path122){let segments=typeof path122=="string"?parsePath(path122):path122;if(segments[0]!=="compilation")return{level:"root"};let target=segments[2];if(segments[1]!=="targets"||typeof target!="number")return{level:"compilation"};let output=segments[4];return segments[3]!=="outputs"||typeof output!="number"?{level:"target",target}:{level:"output",target,output}}build(config2,request){if(isBuilder(config2)){let view2=builderView(config2);return buildScope(view2,this.autoFor(view2.env,view2.project),request,request.partial??!0)}let cacheable=isBuiltConfig(config2),partial2=request.partial??!cacheable,key=JSON.stringify([request.level,request.target,request.output,request.scopeKey,request.extra,partial2]),cached2=cacheable?this.cache.get(config2)?.get(key):void 0;if(cached2)return cached2;let entities=cacheable?config2.entities:this.deps.engine.config.entities,view=lookupView(config2,entities,this.deps.env,this.deps.project),built=buildScope(view,this.autoFor(view.env,view.project),request,partial2);if(cacheable){let forConfig=this.cache.get(config2)??new Map;forConfig.set(key,built),this.cache.set(config2,forConfig)}return built}autoFor(env,project){let identity2=this.deps.services.get("host.package").identity();return buildAutoVariables({project,sousHome:this.deps.services.get("host.sous-home").paths(env).root,packageRoot:identity2.root,version:identity2.version})}};function isBuilder(config2){let candidate=config2;return typeof candidate.atPath=="function"&&typeof candidate.entities=="function"}function isBuiltConfig(config2){let candidate=config2;return typeof candidate.hash=="string"&&typeof candidate.entities?.list=="function"}function builderView(builder){let lookup={get:path122=>builder.atPath(path122).get()};return{get:path122=>lookup.get(path122),sources:()=>builder.entities("variable-source"),lookup,env:builder.env,project:builder.project}}function lookupView(config2,entities,env,project){return{get:path122=>config2.get(path122),sources:()=>entities.list("variable-source"),lookup:config2,env,project}}function variableMap(what){return{"~standard":{version:1,vendor:"sous",validate(value){if(value===void 0)return{value:void 0};if(value===null||typeof value!="object"||Array.isArray(value))return{issues:[{message:`Expected an object of ${what}.`}]};let issues=[];for(let[name,item]of Object.entries(value))isAutoVariable(name)&&name!=="projectRoot"?issues.push({message:`"${name}" is set by sous; it cannot be set here. Remove it: \${${name}} always holds the value sous gives it.`,path:[name]}):typeof item!="string"&&issues.push({message:`Expected a string (${what}), got ${item===null?"null":typeof item}.`,path:[name]});return issues.length>0?{issues}:{value}}}}}var CONFIG_KEYS=[{id:"_vars",description:"Config variables, used as ${name}. Values may refer to each other in any order.",schema:variableMap("variable values")},{id:"_env",description:"Config variables read from the environment: each name mapped to an environment variable.",schema:variableMap("environment variable names")}],VARIABLE_SOURCE_SCHEMA={"~standard":{version:1,vendor:"sous",validate(value){let entry=value,issues=[];(typeof entry?.id!="string"||entry.id==="")&&issues.push({message:"A variable-source entity needs an id.",path:["id"]}),typeof entry?.description!="string"&&issues.push({message:"A variable-source entity needs a description.",path:["description"]}),typeof entry?.variables!="function"&&issues.push({message:"A variable-source entity needs a variables function.",path:["variables"]});for(let name of["scoped","secrets"])entry?.[name]!==void 0&&typeof entry[name]!="function"&&issues.push({message:`A variable-source entity's ${name} must be a function.`,path:[name]});return entry?.forbiddenUnder!==void 0&&!Array.isArray(entry.forbiddenUnder)&&issues.push({message:"A variable-source entity's forbiddenUnder must be a list of keys.",path:["forbiddenUnder"]}),issues.length>0?{issues}:{value}}}};var HIDDEN_VALUE="(hidden)",SECRET_NAME_ENDINGS=[["token"],["secret"],["secrets"],["password"],["passwd"],["passphrase"],["credential"],["credentials"],["apikey"],["api","key"],["private","key"],["access","key"],["secret","key"],["signing","key"],["encryption","key"]],SECRET_VALUE_PATTERNS=[/-----BEGIN [A-Z ]*PRIVATE KEY-----/,/\bgh[pousr]_[A-Za-z0-9]{36,}/,/\bgithub_pat_[A-Za-z0-9_]{22,}/,/\bglpat-[A-Za-z0-9_-]{20,}/,/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/,/\bxox[abposr]-[A-Za-z0-9-]{10,}/,/\b[rs]k_live_[A-Za-z0-9]{16,}/,/\bsk-ant-[A-Za-z0-9_-]{20,}/,/\bsk-(?:proj-)?[A-Za-z0-9_-]{32,}/,/\bAIza[0-9A-Za-z_-]{35}/,/\bnpm_[A-Za-z0-9]{36}\b/,/\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/,/^[a-z][a-z0-9+.-]*:\/\/[^/\s:@]+:[^/\s@]+@/i],PLAIN_VALUE=/^(?:|-?\d+(?:\.\d+)?|true|false|yes|no|on|off)$/i;function nameWords(name){return name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).filter(word=>word.length>0).map(word=>word.toLowerCase())}function hasSecretName(name){let words2=nameWords(name);return SECRET_NAME_ENDINGS.some(ending=>words2.length>=ending.length&&ending.every((word,i)=>words2[words2.length-ending.length+i]===word))}function hasSecretValue(value){return SECRET_VALUE_PATTERNS.some(pattern=>pattern.test(value))}function looksLikeSecret(name,value){return hasSecretValue(value)?!0:hasSecretName(name)&&!PLAIN_VALUE.test(value.trim())}function isSecret(name,value,declared=new Set){return typeof value!="string"?!1:declared.has(name)?value.length>0:looksLikeSecret(name,value)}function hideSecrets(scope,declared=new Set){let out={};for(let[name,value]of Object.entries(scope))out[name]=isSecret(name,value,declared)?HIDDEN_VALUE:value;return out}var Secrets=class{constructor(sources,context){this.sources=sources;this.context=context}hiddenValue=HIDDEN_VALUE;cached;declared(){if(!this.cached){let names2=new Set,context=this.context();for(let source of this.sources())for(let name of source.secrets?.(context)??[])names2.add(name);this.cached=names2}return this.cached}isSecret(name,value,declared=this.declared()){return isSecret(name,value,declared)}hasSecretName(name){return hasSecretName(name)}hasSecretValue(value){return hasSecretValue(value)}hide(scope,declared=this.declared()){return hideSecrets(scope,declared)}};var package_default6={name:"@sous-io/sous-plugin-variables",version:"1.1.6",description:"${var} substitution, _vars resolution, auto-variables, variable names and secrets.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-lib-documents":"workspace:*","@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-host":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME5="@sous-io/sous-plugin-variables",RESERVED_NAMES_CONTRIBUTOR="variables/reserved-names",variablesPlugin=definePlugin6({name:PLUGIN_NAME5,version:package_default6.version,description:"${var} substitution, _vars resolution, auto-variables, variable names and secrets.",dependsOn:{"@sous-io/sous-plugin-host":`^${package_default6.version}`},register(sous){sous.services.add("variables.resolver",(_config,ctx)=>new Resolver({services:sous.services,engine:sous.engine,env:ctx.env,get project(){return ctx.project}}),{lifetime:"singleton"}),sous.services.add("variables.names",()=>variablesNames,{lifetime:"singleton"}),sous.services.add("variables.secrets",(config2,ctx)=>new Secrets(()=>ctx.entities.list("variable-source"),()=>({project:ctx.project,env:ctx.env,config:config2})),{lifetime:"config"}),sous.services.add("variables.booleans",(config2,ctx)=>({declared:()=>declaredBooleans(ctx.entities.list("variable-source"),{project:ctx.project,env:ctx.env,config:config2})}),{lifetime:"config"}),sous.entities.define("variable-source",VARIABLE_SOURCE_SCHEMA,{description:"An extra source of config variables, such as recipe answers."});for(let key of CONFIG_KEYS)sous.entities.add("config-key",key);sous.config.contribute({id:RESERVED_NAMES_CONTRIBUTOR,contribute(config2){let vars=config2.atPath("_vars");for(let name of vars.isObject()?vars.keys():[])name.startsWith("sous")&&!isAutoVariable(name)&&config2.warn(`The variable "${name}" uses the reserved "sous*" namespace and may clash with a variable sous sets.`)}})}});function declaredBooleans(sources,ctx){return new Set(sources.flatMap(source=>source.booleans?.(ctx)??[]))}import{definePlugin as definePlugin7}from"@sous-io/sous-plugin-api";import{PassThrough}from"stream";import{sep as sep2,extname,resolve as resolve$1,dirname as dirname$1}from"path";import{statSync,readFileSync as readFileSync$1,stat,readFile as readFile$1}from"fs";import{createRequire as createRequire2}from"module";var Token=class{constructor(kind,input,begin,end,file2){this.kind=kind,this.input=input,this.begin=begin,this.end=end,this.file=file2}getText(){return this.input.slice(this.begin,this.end)}getPosition(){let[row,col]=[1,1];for(let i=0;i<this.begin;i++)this.input[i]===`
1075
1076
  `?(row++,col=1):col++;return[row,col]}size(){return this.end-this.begin}},Drop=class{liquidMethodMissing(key,context){}},toString$1=Object.prototype.toString,toLowerCase=String.prototype.toLowerCase,hasOwnProperty=Object.hasOwnProperty;function isString(value){return typeof value=="string"}function isFunction(value){return typeof value=="function"}function isPromise(val){return val&&isFunction(val.then)}function isIterator(val){return val&&isFunction(val.next)&&isFunction(val.throw)&&isFunction(val.return)}function escapeRegex(str){return str.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&")}function promisify(fn){return function(...args){return new Promise((resolve4,reject2)=>{fn(...args,(err,result)=>{err?reject2(err):resolve4(result)})})}}function stringify2(value){return value=toValue(value),isString(value)?value:isNil(value)?"":isArray(value)?value.map(x2=>stringify2(x2)).join(""):String(value)}function toEnumerable(val){return val=toValue(val),isArray(val)?val:isString(val)&&val.length>0?[val]:isIterable(val)?Array.from(val):isObject2(val)?Object.keys(val).map(key=>[key,val[key]]):[]}function toArray(val){return val=toValue(val),isNil(val)?[]:isArray(val)?val:[val]}function toValue(value){return value instanceof Drop&&isFunction(value.valueOf)?value.valueOf():value}function toNumber(value){return+toValue(value)||0}function isNumber(value){return typeof value=="number"}function toLiquid(value){return value&&isFunction(value.toLiquid)?toLiquid(value.toLiquid()):value}function isNil(value){return value==null}function isUndefined(value){return value===void 0}function isArray(value){return toString$1.call(value)==="[object Array]"}function isArrayLike(value){return value&&isNumber(value.length)}function isIterable(value){return isObject2(value)&&Symbol.iterator in value}function forOwn(obj,iteratee){obj=obj||{};for(let k2 in obj)if(hasOwnProperty.call(obj,k2)&&iteratee(obj[k2],k2,obj)===!1)break;return obj}function last(arr){return arr[arr.length-1]}function isObject2(value){let type=typeof value;return value!==null&&(type==="object"||type==="function")}function range2(start2,stop,step=1){let arr=[];for(let i=start2;i<stop;i+=step)arr.push(i);return arr}function padStart(str,length,ch=" "){return pad(str,length,ch,(str2,ch2)=>ch2+str2)}function padEnd(str,length,ch=" "){return pad(str,length,ch,(str2,ch2)=>str2+ch2)}function pad(str,length,ch,add){str=String(str);let n7=length-str.length;for(;n7-- >0;)str=add(str,ch);return str}function identify(val){return val}function changeCase(str){return[...str].some(ch=>ch>="a"&&ch<="z")?str.toUpperCase():str.toLowerCase()}function ellipsis(str,N2){return str.length>N2?str.slice(0,N2-3)+"...":str}function caseInsensitiveCompare(a,b){return a==null&&b==null?0:a==null?1:b==null||(a=toLowerCase.call(a),b=toLowerCase.call(b),a<b)?-1:a>b?1:0}function argumentsToValue(fn){return function(...args){return fn.call(this,...args.map(toValue))}}function argumentsToNumber(fn){return function(...args){return fn.call(this,...args.map(toNumber))}}function escapeRegExp2(text){return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}function*strictUniq(array2){let seen=new Set;for(let element of array2){let key=JSON.stringify(element);seen.has(key)||(seen.add(key),yield element)}}var TRAIT="__liquidClass__",LiquidError=class extends Error{constructor(err,token){super(typeof err=="string"?err:err.message),this.context="",typeof err!="string"&&Object.defineProperty(this,"originalError",{value:err,enumerable:!1}),Object.defineProperty(this,"token",{value:token,enumerable:!1}),Object.defineProperty(this,TRAIT,{value:"LiquidError",enumerable:!1})}update(){Object.defineProperty(this,"context",{value:mkContext(this.token),enumerable:!1}),this.message=mkMessage(this.message,this.token),this.stack=this.message+`
1076
1077
  `+this.context+`
1077
1078
  `+this.stack,this.originalError&&(this.stack+=`
@@ -1084,14 +1085,14 @@ From `+this.originalError.stack)}static is(obj){return obj?.[TRAIT]==="LiquidErr
1084
1085
  `)}function strip_html(v2){let str=stringify2(v2);return this.context.memoryLimit.use(str.length),str.replace(/<script[\s\S]*?<\/script>|<style[\s\S]*?<\/style>|<.*?>|<!--[\s\S]*?-->/g,"")}var htmlFilters=Object.freeze({__proto__:null,escape:escape3,xml_escape,escape_once,newline_to_br,strip_html}),MapFS=class{constructor(mapping){this.mapping=mapping,this.sep="/"}exists(filepath){return __awaiter(this,void 0,void 0,function*(){return this.existsSync(filepath)})}existsSync(filepath){return!isNil(this.mapping[filepath])}readFile(filepath){return __awaiter(this,void 0,void 0,function*(){return this.readFileSync(filepath)})}readFileSync(filepath){let content=this.mapping[filepath];if(isNil(content))throw new Error(`ENOENT: ${filepath}`);return content}dirname(filepath){let segments=filepath.split(this.sep);return segments.pop(),segments.join(this.sep)}resolve(dir,file2,ext2){if(file2+=ext2,dir===".")return file2;let segments=dir.split(/\/+/);for(let segment of file2.split(this.sep))segment==="."||segment===""||(segment===".."?(segments.length>1||segments[0]!=="")&&segments.pop():segments.push(segment));return segments.join(this.sep)}},defaultOptions={root:["."],layouts:["."],partials:["."],relativeReference:!0,jekyllInclude:!1,keyValueSeparator:":",cache:void 0,extname:"",fs:fs13,dynamicPartials:!0,jsTruthy:!1,dateFormat:"%A, %B %-e, %Y at %-l:%M %P %z",locale:"",trimTagRight:!1,trimTagLeft:!1,trimOutputRight:!1,trimOutputLeft:!1,greedy:!0,tagDelimiterLeft:"{%",tagDelimiterRight:"%}",outputDelimiterLeft:"{{",outputDelimiterRight:"}}",preserveTimezones:!1,strictFilters:!1,strictVariables:!1,ownPropertyOnly:!0,lenientIf:!1,globals:{},keepOutputType:!1,operators:defaultOperators,memoryLimit:1/0,parseLimit:1/0,renderLimit:1/0};function normalize2(options2){var _a4,_b;if(options2.hasOwnProperty("root")&&(options2.hasOwnProperty("partials")||(options2.partials=options2.root),options2.hasOwnProperty("layouts")||(options2.layouts=options2.root)),options2.hasOwnProperty("cache")){let cache2;typeof options2.cache=="number"?cache2=options2.cache>0?new LRU(options2.cache):void 0:typeof options2.cache=="object"?cache2=options2.cache:cache2=options2.cache?new LRU(1024):void 0,options2.cache=cache2}return options2=Object.assign(Object.assign(Object.assign({},defaultOptions),options2.jekyllInclude?{dynamicPartials:!1}:{}),options2),(!options2.fs.dirname||!options2.fs.sep)&&options2.relativeReference&&(console.warn("[LiquidJS] `fs.dirname` and `fs.sep` are required for relativeReference, set relativeReference to `false` to suppress this warning"),options2.relativeReference=!1),options2.root=normalizeDirectoryList(options2.root),options2.partials=normalizeDirectoryList(options2.partials),options2.layouts=normalizeDirectoryList(options2.layouts),options2.outputEscape=options2.outputEscape&&getOutputEscapeFunction(options2.outputEscape),options2.locale||(options2.locale=(_b=(_a4=getDateTimeFormat())===null||_a4===void 0?void 0:_a4().resolvedOptions().locale)!==null&&_b!==void 0?_b:"en-US"),options2.templates&&(options2.fs=new MapFS(options2.templates),options2.relativeReference=!0,options2.root=options2.partials=options2.layouts="."),options2}function getOutputEscapeFunction(nameOrFunction){return nameOrFunction==="escape"?escape3:nameOrFunction==="json"?misc.json:(assert(isFunction(nameOrFunction),"`outputEscape` need to be of type string or function"),nameOrFunction)}function normalizeDirectoryList(value){let list2=[];return isArray(value)&&(list2=value),isString(value)&&(list2=[value]),list2}function whiteSpaceCtrl(tokens,options2){let inRaw=!1;for(let i=0;i<tokens.length;i++){let token=tokens[i];isDelimitedToken(token)&&(!inRaw&&token.trimLeft&&trimLeft(tokens[i-1],options2.greedy),isTagToken(token)&&(token.name==="raw"?inRaw=!0:token.name==="endraw"&&(inRaw=!1)),!inRaw&&token.trimRight&&trimRight(tokens[i+1],options2.greedy))}}function trimLeft(token,greedy){if(!token||!isHTMLToken(token))return;let mask=greedy?BLANK2:INLINE_BLANK;for(;TYPES[token.input.charCodeAt(token.end-1-token.trimRight)]&mask;)token.trimRight++}function trimRight(token,greedy){if(!token||!isHTMLToken(token))return;let mask=greedy?BLANK2:INLINE_BLANK;for(;TYPES[token.input.charCodeAt(token.begin+token.trimLeft)]&mask;)token.trimLeft++;token.input.charAt(token.begin+token.trimLeft)===`
1085
1086
  `&&token.trimLeft++}var Tokenizer=class{constructor(input,operators=defaultOptions.operators,file2,range3){this.input=input,this.file=file2,this.rawBeginAt=-1,this.p=range3?range3[0]:0,this.N=range3?range3[1]:input.length,this.opTrie=createTrie(operators),this.literalTrie=createTrie(literalValues)}readExpression(){return new Expression(this.readExpressionTokens())}*readExpressionTokens(){for(;this.p<this.N;){let operator=this.readOperator();if(operator){yield operator;continue}let operand=this.readValue();if(operand){yield operand;continue}return}}readOperator(){this.skipBlank();let end=this.matchTrie(this.opTrie);if(end!==-1)return new OperatorToken(this.input,this.p,this.p=end,this.file)}matchTrie(trie){let node=trie,i=this.p,info;for(;node[this.input[i]]&&i<this.N;)node=node[this.input[i++]],node.end&&(info=node);return!info||info.needBoundary&&isWord(this.peek(i-this.p))?-1:i}readFilteredValue(){let begin=this.p,initial=this.readExpression();this.assert(initial.valid(),`invalid value expression: ${this.snapshot()}`);let filters2=this.readFilters();return new FilteredValueToken(initial,filters2,this.input,begin,this.p,this.file)}readFilters(){let filters2=[];for(;;){let filter3=this.readFilter();if(!filter3)return filters2;filters2.push(filter3)}}readFilter(){if(this.skipBlank(),this.end())return null;this.assert(this.read()==="|",'expected "|" before filter');let name=this.readIdentifier();if(!name.size())return this.assert(this.end(),"expected filter name"),null;let args=[];if(this.skipBlank(),this.peek()===":")do{++this.p;let arg=this.readFilterArg();arg&&args.push(arg),this.skipBlank(),this.assert(this.end()||this.peek()===","||this.peek()==="|",()=>`unexpected character ${this.snapshot()}`)}while(this.peek()===",");else if(!(this.peek()==="|"||this.end()))throw this.error('expected ":" after filter name');return new FilterToken(name.getText(),args,this.input,name.begin,this.p,this.file)}readFilterArg(){let key=this.readValue();if(!key)return;if(this.skipBlank(),this.peek()!==":")return key;++this.p;let value=this.readValue();return[key.getText(),value]}readTopLevelTokens(options2=defaultOptions){let tokens=[];for(;this.p<this.N;){let token=this.readTopLevelToken(options2);tokens.push(token)}return whiteSpaceCtrl(tokens,options2),tokens}readTopLevelToken(options2){let{tagDelimiterLeft,outputDelimiterLeft}=options2;return this.rawBeginAt>-1?this.readEndrawOrRawContent(options2):this.match(tagDelimiterLeft)?this.readTagToken(options2):this.match(outputDelimiterLeft)?this.readOutputToken(options2):this.readHTMLToken([tagDelimiterLeft,outputDelimiterLeft])}readHTMLToken(stopStrings){let begin=this.p;for(;this.p<this.N&&!stopStrings.some(str=>this.match(str));)++this.p;return new HTMLToken(this.input,begin,this.p,this.file)}readTagToken(options2){let{file:file2,input}=this,begin=this.p;if(this.readToDelimiter(options2.tagDelimiterRight)===-1)throw this.error(`tag ${this.snapshot(begin)} not closed`,begin);let token=new TagToken(input,begin,this.p,options2,file2);return token.name==="raw"&&(this.rawBeginAt=begin),token}readToDelimiter(delimiter2,respectQuoted=!1){for(this.skipBlank();this.p<this.N;){if(respectQuoted&&this.peekType()&QUOTE){this.readQuoted();continue}if(++this.p,this.rmatch(delimiter2))return this.p}return-1}readOutputToken(options2=defaultOptions){let{file:file2,input}=this,{outputDelimiterRight}=options2,begin=this.p;if(this.readToDelimiter(outputDelimiterRight,!0)===-1)throw this.error(`output ${this.snapshot(begin)} not closed`,begin);return new OutputToken(input,begin,this.p,options2,file2)}readEndrawOrRawContent(options2){let{tagDelimiterLeft,tagDelimiterRight}=options2,begin=this.p,leftPos=this.readTo(tagDelimiterLeft)-tagDelimiterLeft.length;for(;this.p<this.N;){if(this.readIdentifier().getText()!=="endraw"){leftPos=this.readTo(tagDelimiterLeft)-tagDelimiterLeft.length;continue}for(;this.p<=this.N;){if(this.rmatch(tagDelimiterRight)){let end=this.p;return begin===leftPos?(this.rawBeginAt=-1,new TagToken(this.input,begin,end,options2,this.file)):(this.p=leftPos,new HTMLToken(this.input,begin,leftPos,this.file))}if(this.rmatch(tagDelimiterLeft))break;this.p++}}throw this.error(`raw ${this.snapshot(this.rawBeginAt)} not closed`,begin)}readLiquidTagTokens(options2=defaultOptions){let tokens=[];for(;this.p<this.N;){let token=this.readLiquidTagToken(options2);token&&tokens.push(token)}return tokens}readLiquidTagToken(options2){if(this.skipBlank(),this.end())return;let begin=this.p;this.readToDelimiter(`
1086
1087
  `);let end=this.p;return new LiquidTagToken(this.input,begin,end,options2,this.file)}error(msg,pos=this.p){return new TokenizationError(msg,new IdentifierToken(this.input,pos,this.N,this.file))}assert(pred,msg,pos){if(!pred)throw this.error(typeof msg=="function"?msg():msg,pos)}snapshot(begin=this.p){return JSON.stringify(ellipsis(this.input.slice(begin,this.N),32))}readWord(){return this.readIdentifier()}readIdentifier(){this.skipBlank();let begin=this.p;for(;!this.end()&&isWord(this.peek());)++this.p;return new IdentifierToken(this.input,begin,this.p,this.file)}readNonEmptyIdentifier(){let id=this.readIdentifier();return id.size()?id:void 0}readTagName(){return this.skipBlank(),this.input[this.p]==="#"?this.input.slice(this.p,++this.p):this.readIdentifier().getText()}readHashes(jekyllStyle){let hashes=[];for(;;){let hash2=this.readHash(jekyllStyle);if(!hash2)return hashes;hashes.push(hash2)}}readHash(jekyllStyle){this.skipBlank(),this.peek()===","&&++this.p;let begin=this.p,name=this.readNonEmptyIdentifier();if(!name)return;let value;this.skipBlank();let sep3=isString(jekyllStyle)?jekyllStyle:jekyllStyle?"=":":";return this.peek()===sep3&&(++this.p,value=this.readValue()),new HashToken(this.input,begin,this.p,name,value,this.file)}remaining(){return this.input.slice(this.p,this.N)}advance(step=1){this.p+=step}end(){return this.p>=this.N}read(){return this.input[this.p++]}readTo(end){for(;this.p<this.N;)if(++this.p,this.rmatch(end))return this.p;return-1}readValue(){this.skipBlank();let begin=this.p,variable=this.readLiteral()||this.readQuoted()||this.readRange()||this.readNumber(),props=this.readProperties(!variable);return props.length?new PropertyAccessToken(variable,props,this.input,begin,this.p):variable}readScopeValue(){this.skipBlank();let begin=this.p,props=this.readProperties();if(props.length)return new PropertyAccessToken(void 0,props,this.input,begin,this.p)}readProperties(isBegin=!0){let props=[];for(;;){if(this.peek()==="["){this.p++;let prop=this.readValue()||new IdentifierToken(this.input,this.p,this.p,this.file);this.assert(this.readTo("]")!==-1,"[ not closed"),props.push(prop);continue}if(isBegin&&!props.length){let prop=this.readNonEmptyIdentifier();if(prop){props.push(prop);continue}}if(this.peek()==="."&&this.peek(1)!=="."){this.p++;let prop=this.readNonEmptyIdentifier();if(!prop)break;props.push(prop);continue}break}return props}readNumber(){this.skipBlank();let decimalFound=!1,digitFound=!1,n7=0;for(this.peekType()&SIGN&&n7++;this.p+n7<=this.N;)if(this.peekType(n7)&NUMBER)digitFound=!0,n7++;else if(this.peek(n7)==="."&&this.peek(n7+1)!=="."){if(decimalFound||!digitFound)return;decimalFound=!0,n7++}else break;if(digitFound&&!isWord(this.peek(n7))){let num=new NumberToken(this.input,this.p,this.p+n7,this.file);return this.advance(n7),num}}readLiteral(){this.skipBlank();let end=this.matchTrie(this.literalTrie);if(end===-1)return;let literal2=new LiteralToken(this.input,this.p,end,this.file);return this.p=end,literal2}readRange(){this.skipBlank();let begin=this.p;if(this.peek()!=="(")return;++this.p;let lhs=this.readValueOrThrow();this.skipBlank(),this.assert(this.read()==="."&&this.read()===".","invalid range syntax");let rhs=this.readValueOrThrow();return this.skipBlank(),this.assert(this.read()===")","invalid range syntax"),new RangeToken(this.input,begin,this.p,lhs,rhs,this.file)}readValueOrThrow(){let value=this.readValue();return this.assert(value,()=>`unexpected token ${this.snapshot()}, value expected`),value}readQuoted(){this.skipBlank();let begin=this.p;if(!(this.peekType()&QUOTE))return;++this.p;let escaped=!1;for(;this.p<this.N&&(++this.p,!(this.input[this.p-1]===this.input[begin]&&!escaped));)escaped?escaped=!1:this.input[this.p-1]==="\\"&&(escaped=!0);return new QuotedToken(this.input,begin,this.p,this.file)}*readFileNameTemplate(options2){let{outputDelimiterLeft}=options2,htmlStopStrings=[","," ","\r",`
1087
- `," ",outputDelimiterLeft],htmlStopStringSet=new Set(htmlStopStrings);for(;this.p<this.N&&!htmlStopStringSet.has(this.peek());)yield this.match(outputDelimiterLeft)?this.readOutputToken(options2):this.readHTMLToken(htmlStopStrings)}match(word){for(let i=0;i<word.length;i++)if(word[i]!==this.input[this.p+i])return!1;return!0}rmatch(pattern){for(let i=0;i<pattern.length;i++)if(pattern[pattern.length-1-i]!==this.input[this.p-1-i])return!1;return!0}peekType(n7=0){return this.p+n7>=this.N?0:TYPES[this.input.charCodeAt(this.p+n7)]}peek(n7=0){return this.p+n7>=this.N?"":this.input[this.p+n7]}skipBlank(){for(;this.peekType()&BLANK2;)++this.p}},ParseStream=class{constructor(tokens,parseToken){this.handlers={},this.stopRequested=!1,this.tokens=tokens,this.parseToken=parseToken}on(name,cb){return this.handlers[name]=cb,this}trigger(event,arg){let h=this.handlers[event];return h?(h.call(this,arg),!0):!1}start(){this.trigger("start");let token;for(;!this.stopRequested&&(token=this.tokens.shift());){if(this.trigger("token",token)||isTagToken(token)&&this.trigger(`tag:${token.name}`,token))continue;let template=this.parseToken(token,this.tokens);this.trigger("template",template)}return this.stopRequested||this.trigger("end"),this}stop(){return this.stopRequested=!0,this}},TemplateImpl=class{constructor(token){this.token=token}},Tag=class extends TemplateImpl{constructor(token,remainTokens,liquid){super(token),this.name=token.name,this.liquid=liquid,this.tokenizer=token.tokenizer}},Hash=class{constructor(input,jekyllStyle){this.hash={};let tokenizer=input instanceof Tokenizer?input:new Tokenizer(input,{});for(let hash2 of tokenizer.readHashes(jekyllStyle))this.hash[hash2.name.content]=hash2.value}*render(ctx){let hash2={};for(let key of Object.keys(this.hash))hash2[key]=this.hash[key]===void 0?!0:yield evalToken(this.hash[key],ctx);return hash2}};function createTagClass(options2){return class extends Tag{constructor(token,tokens,liquid){super(token,tokens,liquid),isFunction(options2.parse)&&options2.parse.call(this,token,tokens)}*render(ctx,emitter){let hash2=yield new Hash(this.token.args,ctx.opts.keyValueSeparator).render(ctx);return yield options2.render.call(this,ctx,emitter,hash2)}}}function isKeyValuePair(arr){return isArray(arr)}var Filter=class{constructor(token,options2,liquid){this.token=token,this.name=token.name,this.handler=isFunction(options2)?options2:isFunction(options2?.handler)?options2.handler:identify,this.raw=!isFunction(options2)&&!!options2?.raw,this.args=token.args,this.liquid=liquid}*render(value,context){let argv2=[];for(let arg of this.args)isKeyValuePair(arg)?argv2.push([arg[0],yield evalToken(arg[1],context)]):argv2.push(yield evalToken(arg,context));return yield this.handler.apply({context,token:this.token,liquid:this.liquid},[value,...argv2])}},Value=class{constructor(input,liquid){this.filters=[];let token=typeof input=="string"?new Tokenizer(input,liquid.options.operators).readFilteredValue():input;this.initial=token.initial,this.filters=token.filters.map(token2=>new Filter(token2,this.getFilter(liquid,token2.name),liquid))}*value(ctx,lenient){lenient=lenient||ctx.opts.lenientIf&&this.filters.length>0&&this.filters[0].name==="default";let val=yield this.initial.evaluate(ctx,lenient);for(let filter3 of this.filters)val=yield filter3.render(val,ctx);return val}getFilter(liquid,name){let impl=liquid.filters[name];return assert(impl||!liquid.options.strictFilters,()=>`undefined filter: ${name}`),impl}},Output=class extends TemplateImpl{constructor(token,liquid){var _a4;super(token);let tokenizer=new Tokenizer(token.input,liquid.options.operators,token.file,token.contentRange);this.value=new Value(tokenizer.readFilteredValue(),liquid);let filters2=this.value.filters,outputEscape=liquid.options.outputEscape;if(!(!((_a4=filters2[filters2.length-1])===null||_a4===void 0)&&_a4.raw)&&outputEscape){let token2=new FilterToken(toString.call(outputEscape),[],"",0,0);filters2.push(new Filter(token2,outputEscape,liquid))}}*render(ctx,emitter){let val=yield this.value.value(ctx,!1);emitter.write(val)}*arguments(){yield this.value}},HTML=class extends TemplateImpl{constructor(token){super(token),this.str=token.getContent()}*render(ctx,emitter){emitter.write(this.str)}},Variable=class _Variable{constructor(segments,location){this.segments=segments,this.location=location}toString(){return segmentsString(this.segments,!0)}toArray(){function*_visit(...segments){for(let segment of segments)segment instanceof _Variable?yield Array.from(_visit(...segment.segments)):yield segment}return Array.from(_visit(...this.segments))}},VariableMap=class{constructor(){this.map=new Map}get(key){let k2=segmentsString([key.segments[0]]);return this.map.has(k2)||this.map.set(k2,[]),this.map.get(k2)}has(key){return this.map.has(segmentsString([key.segments[0]]))}push(variable){this.get(variable).push(variable)}asObject(){return Object.fromEntries(this.map)}},defaultStaticAnalysisOptions={partials:!0};function*_analyze(templates,partials,sync){let variables=new VariableMap,globals=new VariableMap,locals=new VariableMap,rootScope=new DummyScope(new Set),seen=new Set;function updateVariables(variable,scope){variables.push(variable);let aliased=scope.alias(variable);if(aliased!==void 0){let root=aliased.segments[0];isString(root)&&!rootScope.has(root)&&globals.push(aliased)}else{let root=variable.segments[0];isString(root)&&!scope.has(root)&&globals.push(variable)}for(let segment of variable.segments)segment instanceof Variable&&updateVariables(segment,scope)}function*visit3(template,scope){if(template.arguments)for(let arg of template.arguments())for(let variable of extractVariables(arg))updateVariables(variable,scope);if(template.localScope)for(let ident of template.localScope()){scope.add(ident.content),scope.deleteAlias(ident.content);let[row,col]=ident.getPosition();locals.push(new Variable([ident.content],{row,col,file:ident.file}))}if(template.children)if(template.partialScope){let partial2=template.partialScope();if(partial2===void 0){for(let child2 of yield template.children(partials,sync))yield visit3(child2,scope);return}if(seen.has(partial2.name))return;let partialScopeNames=new Set,partialScope=partial2.isolated?new DummyScope(partialScopeNames):scope.push(partialScopeNames);for(let name of partial2.scope)if(isString(name))partialScopeNames.add(name);else{let[alias2,argument]=name;partialScopeNames.add(alias2);let variables2=Array.from(extractVariables(argument));variables2.length&&partialScope.setAlias(alias2,variables2[0].segments)}for(let child2 of yield template.children(partials,sync))yield visit3(child2,partialScope),seen.add(partial2.name);partialScope.pop()}else{template.blockScope&&scope.push(new Set(template.blockScope()));for(let child2 of yield template.children(partials,sync))yield visit3(child2,scope);template.blockScope&&scope.pop()}}for(let template of templates)yield visit3(template,rootScope);return{variables:variables.asObject(),globals:globals.asObject(),locals:locals.asObject()}}function analyze(template,options2={}){let opts=Object.assign(Object.assign({},defaultStaticAnalysisOptions),options2);return toPromise(_analyze(template,opts.partials,!1))}function analyzeSync(template,options2={}){let opts=Object.assign(Object.assign({},defaultStaticAnalysisOptions),options2);return toValueSync(_analyze(template,opts.partials,!0))}var DummyScope=class{constructor(globals){this.stack=[{names:globals,aliases:new Map}]}has(name){for(let scope of this.stack)if(scope.names.has(name))return!0;return!1}push(scope){return this.stack.push({names:scope,aliases:new Map}),this}pop(){var _a4;return(_a4=this.stack.pop())===null||_a4===void 0?void 0:_a4.names}add(name){this.stack[0].names.add(name)}alias(variable){let root=variable.segments[0];if(!isString(root))return;let alias2=this.getAlias(root);if(alias2!==void 0)return new Variable([...alias2,...variable.segments.slice(1)],variable.location)}setAlias(from,to){this.stack[this.stack.length-1].aliases.set(from,to)}deleteAlias(name){this.stack[this.stack.length-1].aliases.delete(name)}getAlias(name){for(let scope of this.stack){if(scope.aliases.has(name))return scope.aliases.get(name);if(scope.names.has(name))return}}};function*extractVariables(value){isValueToken(value)?yield*extractValueTokenVariables(value):value instanceof Value&&(yield*extractFilteredValueVariables(value))}function*extractFilteredValueVariables(value){for(let token of value.initial.postfix)isValueToken(token)&&(yield*extractValueTokenVariables(token));for(let filter3 of value.filters)for(let arg of filter3.args)isKeyValuePair(arg)&&arg[1]?yield*extractValueTokenVariables(arg[1]):isValueToken(arg)&&(yield*extractValueTokenVariables(arg))}function*extractValueTokenVariables(token){isRangeToken(token)?(yield*extractValueTokenVariables(token.lhs),yield*extractValueTokenVariables(token.rhs)):isPropertyAccessToken(token)&&(yield extractPropertyAccessVariable(token))}function extractPropertyAccessVariable(token){let segments=[],file2=token.file,root=token.props[0];file2=file2||root.file,isQuotedToken(root)||isNumberToken(root)||isWordToken(root)?segments.push(root.content):isPropertyAccessToken(root)&&segments.push(...extractPropertyAccessVariable(root).segments);for(let prop of token.props.slice(1))file2=file2||prop.file,isQuotedToken(prop)||isNumberToken(prop)||isWordToken(prop)?segments.push(prop.content):isPropertyAccessToken(prop)&&segments.push(extractPropertyAccessVariable(prop));let[row,col]=token.getPosition();return new Variable(segments,{row,col,file:file2})}var RE_PROPERTY=/^[\u0080-\uFFFFa-zA-Z_][\u0080-\uFFFFa-zA-Z0-9_-]*$/;function segmentsString(segments,bracketedRoot=!1){let buf=[],root=segments[0];isString(root)&&(!bracketedRoot||root.match(RE_PROPERTY)?buf.push(`${root}`):buf.push(`['${root}']`));for(let segment of segments.slice(1))segment instanceof Variable?buf.push(`[${segmentsString(segment.segments)}]`):isString(segment)?segment.match(RE_PROPERTY)?buf.push(`.${segment}`):buf.push(`['${segment}']`):buf.push(`[${segment}]`);return buf.join("")}var LookupType;(function(LookupType2){LookupType2.Partials="partials",LookupType2.Layouts="layouts",LookupType2.Root="root"})(LookupType||(LookupType={}));var Loader=class{constructor(options2){if(this.options=options2,options2.relativeReference){let sep3=options2.fs.sep;assert(sep3,"`fs.sep` is required for relative reference");let rRelativePath=new RegExp(["."+sep3,".."+sep3,"./","../"].map(prefix=>escapeRegex(prefix)).join("|"));this.shouldLoadRelative=referencedFile=>rRelativePath.test(referencedFile)}else this.shouldLoadRelative=_referencedFile=>!1;this.contains=this.options.fs.contains||(()=>!0)}*lookup(file2,type,sync,currentFile){let{fs:fs88}=this.options,dirs=this.options[type];for(let filepath of this.candidates(file2,dirs,currentFile,type!==LookupType.Root))if(sync?fs88.existsSync(filepath):yield fs88.exists(filepath))return filepath;throw this.lookupError(file2,dirs)}*candidates(file2,dirs,currentFile,enforceRoot){let{fs:fs88,extname:extname3}=this.options,isAllowed=filepath=>{if(!enforceRoot)return!0;for(let dir of dirs)if(this.contains(dir,filepath))return!0;return!1};if(this.shouldLoadRelative(file2)&&currentFile){let referenced=fs88.resolve(this.dirname(currentFile),file2,extname3);isAllowed(referenced)&&(yield referenced)}for(let dir of dirs){let referenced=fs88.resolve(dir,file2,extname3);isAllowed(referenced)&&(yield referenced)}if(fs88.fallback!==void 0){let filepath=fs88.fallback(file2);filepath!==void 0&&isAllowed(filepath)&&(yield filepath)}}dirname(path122){let fs88=this.options.fs;return assert(fs88.dirname,"`fs.dirname` is required for relative reference"),fs88.dirname(path122)}lookupError(file2,roots){let err=new Error("ENOENT");return err.message=`ENOENT: Failed to lookup "${file2}" in "${roots}"`,err.code="ENOENT",err}},Parser=class{constructor(liquid){this.liquid=liquid,this.cache=this.liquid.options.cache,this.fs=this.liquid.options.fs,this.parseFile=this.cache?this._parseFileCached:this._parseFile,this.loader=new Loader(this.liquid.options),this.parseLimit=new Limiter("parse length",liquid.options.parseLimit)}parse(html,filepath){html=String(html),this.parseLimit.use(html.length);let tokens=new Tokenizer(html,this.liquid.options.operators,filepath).readTopLevelTokens(this.liquid.options);return this.parseTokens(tokens)}parseTokens(tokens){let token,templates=[],errors=[];for(;token=tokens.shift();)try{templates.push(this.parseToken(token,tokens))}catch(err){if(this.liquid.options.catchAllErrors)errors.push(err);else throw err}if(errors.length)throw new LiquidErrors(errors);return templates}parseToken(token,remainTokens){try{if(isTagToken(token)){let TagClass=this.liquid.tags[token.name];return assert(TagClass,`tag "${token.name}" not found`),new TagClass(token,remainTokens,this.liquid,this)}return isOutputToken(token)?new Output(token,this.liquid):new HTML(token)}catch(e){throw LiquidError.is(e)?e:new ParseError(e,token)}}parseStream(tokens){return new ParseStream(tokens,(token,tokens2)=>this.parseToken(token,tokens2))}*_parseFileCached(file2,sync,type=LookupType.Root,currentFile){let cache2=this.cache,key=this.loader.shouldLoadRelative(file2)?currentFile+","+file2:type+":"+file2,tpls=yield cache2.read(key);if(tpls)return tpls;let task=this._parseFile(file2,sync,type,currentFile),taskOrTpl=sync?yield task:toPromise(task);cache2.write(key,taskOrTpl);try{return yield taskOrTpl}catch(err){throw cache2.remove(key),err}}*_parseFile(file2,sync,type=LookupType.Root,currentFile){let filepath=yield this.loader.lookup(file2,type,sync,currentFile);return this.parse(sync?this.fs.readFileSync(filepath):yield this.fs.readFile(filepath),filepath)}},TokenKind;(function(TokenKind2){TokenKind2[TokenKind2.Number=1]="Number",TokenKind2[TokenKind2.Literal=2]="Literal",TokenKind2[TokenKind2.Tag=4]="Tag",TokenKind2[TokenKind2.Output=8]="Output",TokenKind2[TokenKind2.HTML=16]="HTML",TokenKind2[TokenKind2.Filter=32]="Filter",TokenKind2[TokenKind2.Hash=64]="Hash",TokenKind2[TokenKind2.PropertyAccess=128]="PropertyAccess",TokenKind2[TokenKind2.Word=256]="Word",TokenKind2[TokenKind2.Range=512]="Range",TokenKind2[TokenKind2.Quoted=1024]="Quoted",TokenKind2[TokenKind2.Operator=2048]="Operator",TokenKind2[TokenKind2.FilteredValue=4096]="FilteredValue",TokenKind2[TokenKind2.Delimited=12]="Delimited"})(TokenKind||(TokenKind={}));function isDelimitedToken(val){return!!(getKind(val)&TokenKind.Delimited)}function isOperatorToken(val){return getKind(val)===TokenKind.Operator}function isHTMLToken(val){return getKind(val)===TokenKind.HTML}function isOutputToken(val){return getKind(val)===TokenKind.Output}function isTagToken(val){return getKind(val)===TokenKind.Tag}function isQuotedToken(val){return getKind(val)===TokenKind.Quoted}function isNumberToken(val){return getKind(val)===TokenKind.Number}function isPropertyAccessToken(val){return getKind(val)===TokenKind.PropertyAccess}function isWordToken(val){return getKind(val)===TokenKind.Word}function isRangeToken(val){return getKind(val)===TokenKind.Range}function isValueToken(val){return(getKind(val)&1667)>0}function getKind(val){return val?val.kind:-1}var Context=class _Context{constructor(env={},opts=defaultOptions,renderOptions={},{memoryLimit,renderLimit}={}){var _a4,_b,_c,_d,_e2;this.scopes=[{}],this.registers={},this.breakCalled=!1,this.continueCalled=!1,this.sync=!!renderOptions.sync,this.opts=opts,this.globals=(_a4=renderOptions.globals)!==null&&_a4!==void 0?_a4:opts.globals,this.environments=isObject2(env)?env:Object(env),this.strictVariables=(_b=renderOptions.strictVariables)!==null&&_b!==void 0?_b:this.opts.strictVariables,this.ownPropertyOnly=(_c=renderOptions.ownPropertyOnly)!==null&&_c!==void 0?_c:opts.ownPropertyOnly,this.memoryLimit=memoryLimit??new Limiter("memory alloc",(_d=renderOptions.memoryLimit)!==null&&_d!==void 0?_d:opts.memoryLimit),this.renderLimit=renderLimit??new Limiter("template render",getPerformance().now()+((_e2=renderOptions.renderLimit)!==null&&_e2!==void 0?_e2:opts.renderLimit))}getRegister(key){return this.registers[key]=this.registers[key]||{}}setRegister(key,value){return this.registers[key]=value}saveRegister(...keys){return keys.map(key=>[key,this.getRegister(key)])}restoreRegister(keyValues){return keyValues.forEach(([key,value])=>this.setRegister(key,value))}getAll(){return[this.globals,this.environments,...this.scopes].reduce((ctx,val)=>__assign(ctx,val),{})}get(paths){return this.getSync(paths)}getSync(paths){return toValueSync(this._get(paths))}*_get(paths){let scope=this.findScope(paths[0]);return yield this._getFromScope(scope,paths)}getFromScope(scope,paths){return toValueSync(this._getFromScope(scope,paths))}*_getFromScope(scope,paths,strictVariables=this.strictVariables){isString(paths)&&(paths=paths.split("."));for(let i=0;i<paths.length;i++)if(scope=yield this.readProperty(scope,paths[i]),strictVariables&&isUndefined(scope))throw new InternalUndefinedVariableError(paths.slice(0,i+1).join("."));return scope}push(ctx){return this.scopes.push(ctx)}pop(){return this.scopes.pop()}bottom(){return this.scopes[0]}spawn(scope={}){return new _Context(scope,this.opts,{sync:this.sync,globals:this.globals,strictVariables:this.strictVariables},{renderLimit:this.renderLimit,memoryLimit:this.memoryLimit})}findScope(key){for(let i=this.scopes.length-1;i>=0;i--){let candidate=this.scopes[i];if(key in candidate)return candidate}return key in this.environments?this.environments:this.globals}readProperty(obj,key){if(obj=toLiquid(obj),key=toValue(key),isNil(obj))return obj;if(isArray(obj)&&key<0)return obj[obj.length+ +key];let value=readJSProperty(obj,key,this.ownPropertyOnly);return value===void 0&&obj instanceof Drop?obj.liquidMethodMissing(key,this):isFunction(value)?value.call(obj):key==="size"?readSize(obj):key==="first"?readFirst(obj):key==="last"?readLast(obj):value}};function readJSProperty(obj,key,ownPropertyOnly){if(!(ownPropertyOnly&&!hasOwnProperty.call(obj,key)&&!(obj instanceof Drop)))return obj[key]}function readFirst(obj){return isArray(obj)?obj[0]:obj.first}function readLast(obj){return isArray(obj)?obj[obj.length-1]:obj.last}function readSize(obj){if(hasOwnProperty.call(obj,"size")||obj.size!==void 0)return obj.size;if(isArray(obj)||isString(obj))return obj.length;if(typeof obj=="object")return Object.keys(obj).length}var BlockMode;(function(BlockMode2){BlockMode2[BlockMode2.OUTPUT=0]="OUTPUT",BlockMode2[BlockMode2.STORE=1]="STORE"})(BlockMode||(BlockMode={}));var abs=argumentsToNumber(Math.abs),at_least=argumentsToNumber(Math.max),at_most=argumentsToNumber(Math.min),ceil=argumentsToNumber(Math.ceil),divided_by=argumentsToNumber((dividend,divisor,integerArithmetic=!1)=>integerArithmetic?Math.floor(dividend/divisor):dividend/divisor),floor=argumentsToNumber(Math.floor),minus=argumentsToNumber((v2,arg)=>v2-arg),plus=argumentsToNumber((lhs,rhs)=>lhs+rhs),modulo=argumentsToNumber((v2,arg)=>v2%arg),times=argumentsToNumber((v2,arg)=>v2*arg);function round(v2,arg=0){v2=toNumber(v2),arg=toNumber(arg);let amp=Math.pow(10,arg);return Math.round(v2*amp)/amp}var mathFilters=Object.freeze({__proto__:null,abs,at_least,at_most,ceil,divided_by,floor,minus,plus,modulo,times,round}),url_decode=x2=>decodeURIComponent(stringify2(x2)).replace(/\+/g," "),url_encode=x2=>encodeURIComponent(stringify2(x2)).replace(/%20/g,"+"),cgi_escape=x2=>encodeURIComponent(stringify2(x2)).replace(/%20/g,"+").replace(/[!'()*]/g,c=>"%"+c.charCodeAt(0).toString(16).toUpperCase()),uri_escape=x2=>encodeURI(stringify2(x2)).replace(/%5B/g,"[").replace(/%5D/g,"]"),rSlugifyDefault=/[^\p{M}\p{L}\p{Nd}]+/ug,rSlugifyReplacers={raw:/\s+/g,default:rSlugifyDefault,pretty:/[^\p{M}\p{L}\p{Nd}._~!$&'()+,;=@]+/ug,ascii:/[^A-Za-z0-9]+/g,latin:rSlugifyDefault,none:null};function slugify(str,mode="default",cased=!1){str=stringify2(str);let replacer=rSlugifyReplacers[mode];return replacer&&(mode==="latin"&&(str=removeAccents(str)),str=str.replace(replacer,"-").replace(/^-|-$/g,"")),cased?str:str.toLowerCase()}function removeAccents(str){return str.replace(/[àáâãäå]/g,"a").replace(/[æ]/g,"ae").replace(/[ç]/g,"c").replace(/[èéêë]/g,"e").replace(/[ìíîï]/g,"i").replace(/[ð]/g,"d").replace(/[ñ]/g,"n").replace(/[òóôõöø]/g,"o").replace(/[ùúûü]/g,"u").replace(/[ýÿ]/g,"y").replace(/[ß]/g,"ss").replace(/[œ]/g,"oe").replace(/[þ]/g,"th").replace(/[ẞ]/g,"SS").replace(/[Œ]/g,"OE").replace(/[Þ]/g,"TH")}var urlFilters=Object.freeze({__proto__:null,url_decode,url_encode,cgi_escape,uri_escape,slugify}),join=argumentsToValue(function(v2,arg){let array2=toArray(v2),sep3=isNil(arg)?" ":stringify2(arg),complexity=array2.length*(1+sep3.length);return this.context.memoryLimit.use(complexity),array2.join(sep3)}),last$1=argumentsToValue(v2=>isArrayLike(v2)?last(v2):""),first=argumentsToValue(v2=>isArrayLike(v2)?v2[0]:""),reverse=argumentsToValue(function(v2){let array2=toArray(v2);return this.context.memoryLimit.use(array2.length),[...array2].reverse()});function*sort(arr,property){let values=[],array2=toArray(arr);this.context.memoryLimit.use(array2.length);for(let item of array2)values.push([item,property?yield this.context._getFromScope(item,stringify2(property).split("."),!1):item]);return values.sort((lhs,rhs)=>{let lvalue=lhs[1],rvalue=rhs[1];return lvalue<rvalue?-1:lvalue>rvalue?1:0}).map(tuple2=>tuple2[0])}function sort_natural(input,property){let propertyString=stringify2(property),compare=property===void 0?caseInsensitiveCompare:(lhs,rhs)=>caseInsensitiveCompare(lhs[propertyString],rhs[propertyString]),array2=toArray(input);return this.context.memoryLimit.use(array2.length),[...array2].sort(compare)}var size=v2=>v2&&v2.length||0;function*map(arr,property){let results=[],array2=toArray(arr);this.context.memoryLimit.use(array2.length);for(let item of array2)results.push(yield this.context._getFromScope(item,stringify2(property),!1));return results}function*sum2(arr,property){let sum3=0,array2=toArray(arr);for(let item of array2){let data=Number(property?yield this.context._getFromScope(item,stringify2(property),!1):item);sum3+=Number.isNaN(data)?0:data}return sum3}function compact(arr){let array2=toArray(arr);return this.context.memoryLimit.use(array2.length),array2.filter(x2=>!isNil(toValue(x2)))}function concat(v2,arg=[]){let lhs=toArray(v2),rhs=toArray(arg);return this.context.memoryLimit.use(lhs.length+rhs.length),lhs.concat(rhs)}function push(v2,arg){return concat.call(this,v2,[arg])}function unshift(v2,arg){let array2=toArray(v2);this.context.memoryLimit.use(array2.length);let clone2=[...array2];return clone2.unshift(arg),clone2}function pop(v2){let clone2=[...toArray(v2)];return clone2.pop(),clone2}function shift(v2){let array2=toArray(v2);this.context.memoryLimit.use(array2.length);let clone2=[...array2];return clone2.shift(),clone2}function slice(v2,begin,length=1){return v2=toValue(v2),isNil(v2)?[]:(isArray(v2)||(v2=stringify2(v2)),begin=begin<0?v2.length+begin:begin,this.context.memoryLimit.use(length),v2.slice(begin,begin+length))}function expectedMatcher(expected){return this.context.opts.jekyllWhere?v2=>EmptyDrop.is(expected)?equals(v2,expected):isArray(v2)?arrayIncludes(v2,expected):equals(v2,expected):expected===void 0?v2=>isTruthy(v2,this.context):v2=>equals(v2,expected)}function*filter2(include,arr,property,expected){let values=[];arr=toArray(arr),this.context.memoryLimit.use(arr.length);let token=new Tokenizer(stringify2(property)).readScopeValue();for(let item of arr)values.push(yield evalToken(token,this.context.spawn(item)));let matcher2=expectedMatcher.call(this,expected);return arr.filter((_2,i)=>matcher2(values[i])===include)}function*filter_exp(include,arr,itemName,exp){let filtered=[],keyTemplate=new Value(stringify2(exp),this.liquid),array2=toArray(arr);this.context.memoryLimit.use(array2.length);for(let item of array2){this.context.push({[itemName]:item});let value=yield keyTemplate.value(this.context);this.context.pop(),value===include&&filtered.push(item)}return filtered}function*where2(arr,property,expected){return yield*filter2.call(this,!0,arr,property,expected)}function*reject(arr,property,expected){return yield*filter2.call(this,!1,arr,property,expected)}function*where_exp(arr,itemName,exp){return yield*filter_exp.call(this,!0,arr,itemName,exp)}function*reject_exp(arr,itemName,exp){return yield*filter_exp.call(this,!1,arr,itemName,exp)}function*group_by(arr,property){let map3=new Map;arr=toEnumerable(arr);let token=new Tokenizer(stringify2(property)).readScopeValue();this.context.memoryLimit.use(arr.length);for(let item of arr){let key=yield evalToken(token,this.context.spawn(item));map3.has(key)||map3.set(key,[]),map3.get(key).push(item)}return[...map3.entries()].map(([name,items2])=>({name,items:items2}))}function*group_by_exp(arr,itemName,exp){let map3=new Map,keyTemplate=new Value(stringify2(exp),this.liquid);arr=toEnumerable(arr),this.context.memoryLimit.use(arr.length);for(let item of arr){this.context.push({[itemName]:item});let key=yield keyTemplate.value(this.context);this.context.pop(),map3.has(key)||map3.set(key,[]),map3.get(key).push(item)}return[...map3.entries()].map(([name,items2])=>({name,items:items2}))}function*search(arr,property,expected){let token=new Tokenizer(stringify2(property)).readScopeValue(),array2=toArray(arr),matcher2=expectedMatcher.call(this,expected);for(let index=0;index<array2.length;index++){let value=yield evalToken(token,this.context.spawn(array2[index]));if(matcher2(value))return[index,array2[index]]}}function*search_exp(arr,itemName,exp){let predicate=new Value(stringify2(exp),this.liquid),array2=toArray(arr);for(let index=0;index<array2.length;index++){this.context.push({[itemName]:array2[index]});let value=yield predicate.value(this.context);if(this.context.pop(),value)return[index,array2[index]]}}function*has(arr,property,expected){return!!(yield*search.call(this,arr,property,expected))}function*has_exp(arr,itemName,exp){return!!(yield*search_exp.call(this,arr,itemName,exp))}function*find_index(arr,property,expected){let result=yield*search.call(this,arr,property,expected);return result?result[0]:void 0}function*find_index_exp(arr,itemName,exp){let result=yield*search_exp.call(this,arr,itemName,exp);return result?result[0]:void 0}function*find(arr,property,expected){let result=yield*search.call(this,arr,property,expected);return result?result[1]:void 0}function*find_exp(arr,itemName,exp){let result=yield*search_exp.call(this,arr,itemName,exp);return result?result[1]:void 0}function uniq(arr){return arr=toArray(arr),this.context.memoryLimit.use(arr.length),[...new Set(arr)]}function sample(v2,count2=1){if(v2=toValue(v2),isNil(v2))return[];isArray(v2)||(v2=stringify2(v2)),this.context.memoryLimit.use(count2);let shuffled=[...v2].sort(()=>Math.random()-.5);return count2===1?shuffled[0]:shuffled.slice(0,count2)}var arrayFilters=Object.freeze({__proto__:null,join,last:last$1,first,reverse,sort,sort_natural,size,map,sum:sum2,compact,concat,push,unshift,pop,shift,slice,where:where2,reject,where_exp,reject_exp,group_by,group_by_exp,has,has_exp,find_index,find_index_exp,find,find_exp,uniq,sample});function date(v2,format3,timezoneOffset){var _a4,_b,_c;let size2=((_a4=v2?.length)!==null&&_a4!==void 0?_a4:0)+((_b=format3?.length)!==null&&_b!==void 0?_b:0)+((_c=timezoneOffset?.length)!==null&&_c!==void 0?_c:0);this.context.memoryLimit.use(size2);let date6=parseDate(v2,this.context.opts,timezoneOffset);return date6?(format3=toValue(format3),format3=isNil(format3)?this.context.opts.dateFormat:stringify2(format3),strftime(date6,format3)):v2}function date_to_xmlschema(v2){return date.call(this,v2,"%Y-%m-%dT%H:%M:%S%:z")}function date_to_rfc822(v2){return date.call(this,v2,"%a, %d %b %Y %H:%M:%S %z")}function date_to_string(v2,type,style){return stringify_date.call(this,v2,"%b",type,style)}function date_to_long_string(v2,type,style){return stringify_date.call(this,v2,"%B",type,style)}function stringify_date(v2,month_type,type,style){let date6=parseDate(v2,this.context.opts);if(!date6)return v2;if(type==="ordinal"){let d=date6.getDate();return style==="US"?strftime(date6,`${month_type} ${d}%q, %Y`):strftime(date6,`${d}%q ${month_type} %Y`)}return strftime(date6,`%d ${month_type} %Y`)}function parseDate(v2,opts,timezoneOffset){let date6,defaultTimezoneOffset=timezoneOffset??opts.timezoneOffset,locale=opts.locale;return v2=toValue(v2),v2==="now"||v2==="today"?date6=new LiquidDate(Date.now(),locale,defaultTimezoneOffset):isNumber(v2)?date6=new LiquidDate(v2*1e3,locale,defaultTimezoneOffset):isString(v2)?/^\d+$/.test(v2)?date6=new LiquidDate(+v2*1e3,locale,defaultTimezoneOffset):opts.preserveTimezones&&timezoneOffset===void 0?date6=LiquidDate.createDateFixedToTimezone(v2,locale):date6=new LiquidDate(v2,locale,defaultTimezoneOffset):date6=new LiquidDate(v2,locale,defaultTimezoneOffset),date6.valid()?date6:void 0}var dateFilters=Object.freeze({__proto__:null,date,date_to_xmlschema,date_to_rfc822,date_to_string,date_to_long_string}),rCJKWord=/[\u4E00-\u9FFF\uF900-\uFAFF\u3400-\u4DBF\u3040-\u309F\u30A0-\u30FF\uAC00-\uD7AF]/gu,rNonCJKWord=/[^\u4E00-\u9FFF\uF900-\uFAFF\u3400-\u4DBF\u3040-\u309F\u30A0-\u30FF\uAC00-\uD7AF\s]+/gu;function append(v2,arg){assert(arguments.length===2,"append expect 2 arguments");let lhs=stringify2(v2),rhs=stringify2(arg);return this.context.memoryLimit.use(lhs.length+rhs.length),lhs+rhs}function prepend(v2,arg){assert(arguments.length===2,"prepend expect 2 arguments");let lhs=stringify2(v2),rhs=stringify2(arg);return this.context.memoryLimit.use(lhs.length+rhs.length),rhs+lhs}function lstrip(v2,chars){let str=stringify2(v2);return this.context.memoryLimit.use(str.length),chars?(chars=escapeRegExp2(stringify2(chars)),str.replace(new RegExp(`^[${chars}]+`,"g"),"")):str.replace(/^\s+/,"")}function downcase(v2){let str=stringify2(v2);return this.context.memoryLimit.use(str.length),str.toLowerCase()}function upcase(v2){let str=stringify2(v2);return this.context.memoryLimit.use(str.length),stringify2(str).toUpperCase()}function remove(v2,arg){let str=stringify2(v2);return this.context.memoryLimit.use(str.length),str.split(stringify2(arg)).join("")}function remove_first(v2,l){let str=stringify2(v2);return this.context.memoryLimit.use(str.length),str.replace(stringify2(l),"")}function remove_last(v2,l){let str=stringify2(v2);this.context.memoryLimit.use(str.length);let pattern=stringify2(l),index=str.lastIndexOf(pattern);return index===-1?str:str.substring(0,index)+str.substring(index+pattern.length)}function rstrip(str,chars){return str=stringify2(str),this.context.memoryLimit.use(str.length),chars?(chars=escapeRegExp2(stringify2(chars)),str.replace(new RegExp(`[${chars}]+$`,"g"),"")):str.replace(/\s+$/,"")}function split2(v2,arg){let str=stringify2(v2);this.context.memoryLimit.use(str.length);let arr=str.split(stringify2(arg));for(;arr.length&&arr[arr.length-1]==="";)arr.pop();return arr}function strip(v2,chars){let str=stringify2(v2);return this.context.memoryLimit.use(str.length),chars?(chars=escapeRegExp2(stringify2(chars)),str.replace(new RegExp(`^[${chars}]+`,"g"),"").replace(new RegExp(`[${chars}]+$`,"g"),"")):str.trim()}function strip_newlines(v2){let str=stringify2(v2);return this.context.memoryLimit.use(str.length),str.replace(/\r?\n/gm,"")}function capitalize(str){return str=stringify2(str),this.context.memoryLimit.use(str.length),str.charAt(0).toUpperCase()+str.slice(1).toLowerCase()}function replace2(v2,pattern,replacement){let str=stringify2(v2);return this.context.memoryLimit.use(str.length),str.split(stringify2(pattern)).join(replacement)}function replace_first(v2,arg1,arg2){let str=stringify2(v2);return this.context.memoryLimit.use(str.length),str.replace(stringify2(arg1),arg2)}function replace_last(v2,arg1,arg2){let str=stringify2(v2);this.context.memoryLimit.use(str.length);let pattern=stringify2(arg1),index=str.lastIndexOf(pattern);if(index===-1)return str;let replacement=stringify2(arg2);return str.substring(0,index)+replacement+str.substring(index+pattern.length)}function truncate(v2,l=50,o="..."){let str=stringify2(v2);return this.context.memoryLimit.use(str.length),str.length<=l?v2:str.substring(0,l-o.length)+o}function truncatewords(v2,words2=15,o="..."){let str=stringify2(v2);this.context.memoryLimit.use(str.length);let arr=str.split(/\s+/);words2<=0&&(words2=1);let ret=arr.slice(0,words2).join(" ");return arr.length>=words2&&(ret+=o),ret}function normalize_whitespace(v2){let str=stringify2(v2);return this.context.memoryLimit.use(str.length),str.replace(/\s+/g," ")}function number_of_words(input,mode){let str=stringify2(input);if(this.context.memoryLimit.use(str.length),input=str.trim(),!input)return 0;switch(mode){case"cjk":return(input.match(rCJKWord)||[]).length+(input.match(rNonCJKWord)||[]).length;case"auto":return rCJKWord.test(input)?input.match(rCJKWord).length+(input.match(rNonCJKWord)||[]).length:input.split(/\s+/).length;default:return input.split(/\s+/).length}}function array_to_sentence_string(array2,connector="and"){switch(this.context.memoryLimit.use(array2.length),array2.length){case 0:return"";case 1:return array2[0];case 2:return`${array2[0]} ${connector} ${array2[1]}`;default:return`${array2.slice(0,-1).join(", ")}, ${connector} ${array2[array2.length-1]}`}}var stringFilters=Object.freeze({__proto__:null,append,prepend,lstrip,downcase,upcase,remove,remove_first,remove_last,rstrip,split:split2,strip,strip_newlines,capitalize,replace:replace2,replace_first,replace_last,truncate,truncatewords,normalize_whitespace,number_of_words,array_to_sentence_string});function base64Encode(str){return Buffer.from(str,"utf8").toString("base64")}function base64Decode(str){return Buffer.from(str,"base64").toString("utf8")}function base64_encode(value){let str=stringify2(value);return this.context.memoryLimit.use(str.length),base64Encode(str)}function base64_decode(value){let str=stringify2(value);return this.context.memoryLimit.use(str.length),base64Decode(str)}var base64Filters=Object.freeze({__proto__:null,base64_encode,base64_decode}),filters=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},htmlFilters),mathFilters),urlFilters),arrayFilters),dateFilters),stringFilters),base64Filters),misc),AssignTag=class extends Tag{constructor(token,remainTokens,liquid){super(token,remainTokens,liquid),this.identifier=this.tokenizer.readIdentifier(),this.key=this.identifier.content,this.tokenizer.assert(this.key,"expected variable name"),this.tokenizer.skipBlank(),this.tokenizer.assert(this.tokenizer.peek()==="=",'expected "="'),this.tokenizer.advance(),this.value=new Value(this.tokenizer.readFilteredValue(),this.liquid)}*render(ctx){ctx.bottom()[this.key]=yield this.value.value(ctx,this.liquid.options.lenientIf)}*arguments(){yield this.value}*localScope(){yield this.identifier}},MODIFIERS=["offset","limit","reversed"],ForTag=class extends Tag{constructor(token,remainTokens,liquid,parser){super(token,remainTokens,liquid);let variable=this.tokenizer.readIdentifier(),inStr=this.tokenizer.readIdentifier(),collection=this.tokenizer.readValue();if(!variable.size()||inStr.content!=="in"||!collection)throw new Error(`illegal tag: ${token.getText()}`);this.variable=variable.content,this.collection=collection,this.hash=new Hash(this.tokenizer,liquid.options.keyValueSeparator),this.templates=[],this.elseTemplates=[];let p,stream=parser.parseStream(remainTokens).on("start",()=>p=this.templates).on("tag:else",tag=>{assertEmpty(tag.args),p=this.elseTemplates}).on("tag:endfor",tag=>{assertEmpty(tag.args),stream.stop()}).on("template",tpl=>p.push(tpl)).on("end",()=>{throw new Error(`tag ${token.getText()} not closed`)});stream.start()}*render(ctx,emitter){let r=this.liquid.renderer,collection=toEnumerable(yield evalToken(this.collection,ctx));if(!collection.length){yield r.renderTemplates(this.elseTemplates,ctx,emitter);return}let continueKey="continue-"+this.variable+"-"+this.collection.getText();ctx.push({continue:ctx.getRegister(continueKey)});let hash2=yield this.hash.render(ctx);ctx.pop(),collection=(this.liquid.options.orderedFilterParameters?Object.keys(hash2).filter(x2=>MODIFIERS.includes(x2)):MODIFIERS.filter(x2=>hash2[x2]!==void 0)).reduce((collection2,modifier)=>modifier==="offset"?offset(collection2,hash2.offset):modifier==="limit"?limit(collection2,hash2.limit):reversed(collection2),collection),ctx.setRegister(continueKey,(hash2.offset||0)+collection.length);let scope={forloop:new ForloopDrop(collection.length,this.collection.getText(),this.variable)};ctx.push(scope);for(let item of collection){if(scope[this.variable]=item,ctx.continueCalled=ctx.breakCalled=!1,yield r.renderTemplates(this.templates,ctx,emitter),ctx.breakCalled)break;scope.forloop.next()}ctx.continueCalled=ctx.breakCalled=!1,ctx.pop()}*children(){let templates=this.templates.slice();return this.elseTemplates&&templates.push(...this.elseTemplates),templates}*arguments(){yield this.collection;for(let v2 of Object.values(this.hash.hash))isValueToken(v2)&&(yield v2)}blockScope(){return[this.variable,"forloop"]}};function reversed(arr){return[...arr].reverse()}function offset(arr,count2){return arr.slice(count2)}function limit(arr,count2){return arr.slice(0,count2)}var CaptureTag=class extends Tag{constructor(tagToken,remainTokens,liquid,parser){for(super(tagToken,remainTokens,liquid),this.templates=[],this.identifier=this.readVariable(),this.variable=this.identifier.content;remainTokens.length;){let token=remainTokens.shift();if(isTagToken(token)&&token.name==="endcapture")return;this.templates.push(parser.parseToken(token,remainTokens))}throw new Error(`tag ${tagToken.getText()} not closed`)}readVariable(){let ident=this.tokenizer.readIdentifier();if(ident.content||(ident=this.tokenizer.readQuoted(),ident))return ident;throw this.tokenizer.error("invalid capture name")}*render(ctx){let html=yield this.liquid.renderer.renderTemplates(this.templates,ctx);ctx.bottom()[this.variable]=html}*children(){return this.templates}*localScope(){yield this.identifier}},CaseTag=class extends Tag{constructor(tagToken,remainTokens,liquid,parser){super(tagToken,remainTokens,liquid),this.branches=[],this.elseTemplates=[],this.value=new Value(this.tokenizer.readFilteredValue(),this.liquid),this.elseTemplates=[];let p=[],elseCount=0,stream=parser.parseStream(remainTokens).on("tag:when",token=>{if(elseCount>0)return;p=[];let values=[];for(;!token.tokenizer.end();)values.push(token.tokenizer.readValueOrThrow()),token.tokenizer.skipBlank(),token.tokenizer.peek()===","?token.tokenizer.readTo(","):token.tokenizer.readTo("or");this.branches.push({values,templates:p})}).on("tag:else",()=>{elseCount++,p=this.elseTemplates}).on("tag:endcase",()=>stream.stop()).on("template",tpl=>{(p!==this.elseTemplates||elseCount===1)&&p.push(tpl)}).on("end",()=>{throw new Error(`tag ${tagToken.getText()} not closed`)});stream.start()}*render(ctx,emitter){let r=this.liquid.renderer,target=toValue(yield this.value.value(ctx,ctx.opts.lenientIf)),branchHit=!1;for(let branch of this.branches)for(let valueToken of branch.values){let value=yield evalToken(valueToken,ctx,ctx.opts.lenientIf);if(equals(target,value)){yield r.renderTemplates(branch.templates,ctx,emitter),branchHit=!0;break}}branchHit||(yield r.renderTemplates(this.elseTemplates,ctx,emitter))}*arguments(){yield this.value,yield*this.branches.flatMap(b=>b.values)}*children(){let templates=this.branches.flatMap(b=>b.templates);return this.elseTemplates&&templates.push(...this.elseTemplates),templates}},CommentTag=class extends Tag{constructor(tagToken,remainTokens,liquid){for(super(tagToken,remainTokens,liquid);remainTokens.length;){let token=remainTokens.shift();if(isTagToken(token)&&token.name==="endcomment")return}throw new Error(`tag ${tagToken.getText()} not closed`)}render(){}},RenderTag=class extends Tag{constructor(token,remainTokens,liquid,parser){super(token,remainTokens,liquid);let tokenizer=this.tokenizer;for(this.file=parseFilePath(tokenizer,this.liquid,parser),this.currentFile=token.file;!tokenizer.end();){tokenizer.skipBlank();let begin=tokenizer.p,keyword=tokenizer.readIdentifier();if((keyword.content==="with"||keyword.content==="for")&&(tokenizer.skipBlank(),tokenizer.peek()!==":")){let value=tokenizer.readValue();if(value){let beforeAs=tokenizer.p,asStr=tokenizer.readIdentifier(),alias2;asStr.content==="as"?alias2=tokenizer.readIdentifier():tokenizer.p=beforeAs,this[keyword.content]={value,alias:alias2&&alias2.content},tokenizer.skipBlank(),tokenizer.peek()===","&&tokenizer.advance();continue}}tokenizer.p=begin;break}this.hash=new Hash(tokenizer,liquid.options.keyValueSeparator)}*render(ctx,emitter){let{liquid,hash:hash2}=this,filepath=yield renderFilePath(this.file,ctx,liquid);assert(filepath,()=>`illegal file path "${filepath}"`);let childCtx=ctx.spawn(),scope=childCtx.bottom();if(__assign(scope,yield hash2.render(ctx)),this.with){let{value,alias:alias2}=this.with;scope[alias2||filepath]=yield evalToken(value,ctx)}if(this.for){let{value,alias:alias2}=this.for,collection=toEnumerable(yield evalToken(value,ctx));scope.forloop=new ForloopDrop(collection.length,value.getText(),alias2);for(let item of collection){scope[alias2]=item;let templates=yield liquid._parsePartialFile(filepath,childCtx.sync,this.currentFile);yield liquid.renderer.renderTemplates(templates,childCtx,emitter),scope.forloop.next()}}else{let templates=yield liquid._parsePartialFile(filepath,childCtx.sync,this.currentFile);yield liquid.renderer.renderTemplates(templates,childCtx,emitter)}}*children(partials,sync){return partials&&isString(this.file)?yield this.liquid._parsePartialFile(this.file,sync,this.currentFile):[]}partialScope(){if(isString(this.file)){let names2=Object.keys(this.hash.hash);if(this.with){let{value,alias:alias2}=this.with;isString(alias2)?names2.push([alias2,value]):isString(this.file)&&names2.push([this.file,value])}if(this.for){let{value,alias:alias2}=this.for;isString(alias2)?names2.push([alias2,value]):isString(this.file)&&names2.push([this.file,value])}return{name:this.file,isolated:!0,scope:names2}}}*arguments(){for(let v2 of Object.values(this.hash.hash))isValueToken(v2)&&(yield v2);if(this.with){let{value}=this.with;isValueToken(value)&&(yield value)}if(this.for){let{value}=this.for;isValueToken(value)&&(yield value)}}};function parseFilePath(tokenizer,liquid,parser){if(liquid.options.dynamicPartials){let file2=tokenizer.readValue();if(tokenizer.assert(file2,"illegal file path"),file2.getText()==="none")return;if(isQuotedToken(file2)){let templates2=parser.parse(evalQuotedToken(file2));return optimize(templates2)}return file2}let tokens=[...tokenizer.readFileNameTemplate(liquid.options)],templates=optimize(parser.parseTokens(tokens));return templates==="none"?void 0:templates}function optimize(templates){return templates.length===1&&isHTMLToken(templates[0].token)?templates[0].token.getContent():templates}function*renderFilePath(file2,ctx,liquid){return typeof file2=="string"?file2:Array.isArray(file2)?liquid.renderer.renderTemplates(file2,ctx):yield evalToken(file2,ctx)}var IncludeTag=class extends Tag{constructor(token,remainTokens,liquid,parser){super(token,remainTokens,liquid);let{tokenizer}=token;this.file=parseFilePath(tokenizer,this.liquid,parser),this.currentFile=token.file;let begin=tokenizer.p;tokenizer.readIdentifier().content==="with"?(tokenizer.skipBlank(),tokenizer.peek()!==":"?this.withVar=tokenizer.readValue():tokenizer.p=begin):tokenizer.p=begin,this.hash=new Hash(tokenizer,liquid.options.jekyllInclude||liquid.options.keyValueSeparator)}*render(ctx,emitter){let{liquid,hash:hash2,withVar}=this,{renderer}=liquid,filepath=yield renderFilePath(this.file,ctx,liquid);assert(filepath,()=>`illegal file path "${filepath}"`);let saved=ctx.saveRegister("blocks","blockMode");ctx.setRegister("blocks",{}),ctx.setRegister("blockMode",BlockMode.OUTPUT);let scope=yield hash2.render(ctx);withVar&&(scope[filepath]=yield evalToken(withVar,ctx));let templates=yield liquid._parsePartialFile(filepath,ctx.sync,this.currentFile);ctx.push(ctx.opts.jekyllInclude?{include:scope}:scope),yield renderer.renderTemplates(templates,ctx,emitter),ctx.pop(),ctx.restoreRegister(saved)}*children(partials,sync){return partials&&isString(this.file)?yield this.liquid._parsePartialFile(this.file,sync,this.currentFile):[]}partialScope(){if(isString(this.file)){let names2;return this.liquid.options.jekyllInclude?names2=["include"]:(names2=Object.keys(this.hash.hash),this.withVar&&names2.push([this.file,this.withVar])),{name:this.file,isolated:!1,scope:names2}}}*arguments(){yield*Object.values(this.hash.hash).filter(isValueToken),isValueToken(this.file)&&(yield this.file),isValueToken(this.withVar)&&(yield this.withVar)}},DecrementTag=class extends Tag{constructor(token,remainTokens,liquid){super(token,remainTokens,liquid),this.identifier=this.tokenizer.readIdentifier(),this.variable=this.identifier.content}render(context,emitter){let scope=context.environments;isNumber(scope[this.variable])||(scope[this.variable]=0),emitter.write(stringify2(--scope[this.variable]))}*localScope(){yield this.identifier}},CycleTag=class extends Tag{constructor(token,remainTokens,liquid){super(token,remainTokens,liquid),this.candidates=[];let group=this.tokenizer.readValue();for(this.tokenizer.skipBlank(),group&&(this.tokenizer.peek()===":"?(this.group=group,this.tokenizer.advance()):this.candidates.push(group));!this.tokenizer.end();){let value=this.tokenizer.readValue();value&&this.candidates.push(value),this.tokenizer.readTo(",")}this.tokenizer.assert(this.candidates.length,()=>`empty candidates: "${token.getText()}"`)}*render(ctx,emitter){let fingerprint2=`cycle:${yield evalToken(this.group,ctx)}:`+this.candidates.join(","),groups=ctx.getRegister("cycle"),idx=groups[fingerprint2];idx===void 0&&(idx=groups[fingerprint2]=0);let candidate=this.candidates[idx];return idx=(idx+1)%this.candidates.length,groups[fingerprint2]=idx,yield evalToken(candidate,ctx)}*arguments(){yield*this.candidates,this.group&&(yield this.group)}},IfTag=class extends Tag{constructor(tagToken,remainTokens,liquid,parser){super(tagToken,remainTokens,liquid),this.branches=[];let p=[];parser.parseStream(remainTokens).on("start",()=>this.branches.push({value:new Value(tagToken.tokenizer.readFilteredValue(),this.liquid),templates:p=[]})).on("tag:elsif",token=>{assert(!this.elseTemplates,"unexpected elsif after else"),this.branches.push({value:new Value(token.tokenizer.readFilteredValue(),this.liquid),templates:p=[]})}).on("tag:else",tag=>{assertEmpty(tag.args),assert(!this.elseTemplates,"duplicated else"),p=this.elseTemplates=[]}).on("tag:endif",function(tag){assertEmpty(tag.args),this.stop()}).on("template",tpl=>p.push(tpl)).on("end",()=>{throw new Error(`tag ${tagToken.getText()} not closed`)}).start()}*render(ctx,emitter){let r=this.liquid.renderer;for(let{value,templates}of this.branches){let v2=yield value.value(ctx,ctx.opts.lenientIf);if(isTruthy(v2,ctx)){yield r.renderTemplates(templates,ctx,emitter);return}}yield r.renderTemplates(this.elseTemplates||[],ctx,emitter)}*children(){let templates=this.branches.flatMap(b=>b.templates);return this.elseTemplates&&templates.push(...this.elseTemplates),templates}arguments(){return this.branches.map(b=>b.value)}},IncrementTag=class extends Tag{constructor(token,remainTokens,liquid){super(token,remainTokens,liquid),this.identifier=this.tokenizer.readIdentifier(),this.variable=this.identifier.content}render(context,emitter){let scope=context.environments;isNumber(scope[this.variable])||(scope[this.variable]=0);let val=scope[this.variable];scope[this.variable]++,emitter.write(stringify2(val))}*localScope(){yield this.identifier}},LayoutTag=class extends Tag{constructor(token,remainTokens,liquid,parser){super(token,remainTokens,liquid),this.file=parseFilePath(this.tokenizer,this.liquid,parser),this.currentFile=token.file,this.args=new Hash(this.tokenizer,liquid.options.keyValueSeparator),this.templates=parser.parseTokens(remainTokens)}*render(ctx,emitter){let{liquid,args,file:file2}=this,{renderer}=liquid;if(file2===void 0){ctx.setRegister("blockMode",BlockMode.OUTPUT),yield renderer.renderTemplates(this.templates,ctx,emitter);return}let filepath=yield renderFilePath(this.file,ctx,liquid);assert(filepath,()=>`illegal file path "${filepath}"`);let templates=yield liquid._parseLayoutFile(filepath,ctx.sync,this.currentFile);ctx.setRegister("blockMode",BlockMode.STORE);let html=yield renderer.renderTemplates(this.templates,ctx),blocks=ctx.getRegister("blocks");blocks[""]===void 0&&(blocks[""]=(parent,emitter2)=>emitter2.write(html)),ctx.setRegister("blockMode",BlockMode.OUTPUT),ctx.push(yield args.render(ctx)),yield renderer.renderTemplates(templates,ctx,emitter),ctx.pop()}*children(partials){let templates=this.templates.slice();return partials&&isString(this.file)&&templates.push(...yield this.liquid._parsePartialFile(this.file,!0,this.currentFile)),templates}*arguments(){for(let v2 of Object.values(this.args.hash))isValueToken(v2)&&(yield v2);isValueToken(this.file)&&(yield this.file)}partialScope(){if(isString(this.file))return{name:this.file,isolated:!1,scope:Object.keys(this.args.hash)}}},BlockTag=class extends Tag{constructor(token,remainTokens,liquid,parser){super(token,remainTokens,liquid),this.templates=[];let match2=/\w+/.exec(token.args);for(this.block=match2?match2[0]:"";remainTokens.length;){let token2=remainTokens.shift();if(isTagToken(token2)&&token2.name==="endblock")return;let template=parser.parseToken(token2,remainTokens);this.templates.push(template)}throw new Error(`tag ${token.getText()} not closed`)}*render(ctx,emitter){let blockRender=this.getBlockRender(ctx);ctx.getRegister("blockMode")===BlockMode.STORE?ctx.getRegister("blocks")[this.block]=blockRender:yield blockRender(new BlockDrop,emitter)}getBlockRender(ctx){let{liquid,templates}=this,renderChild=ctx.getRegister("blocks")[this.block],renderCurrent=function*(superBlock,emitter){ctx.push({block:superBlock}),yield liquid.renderer.renderTemplates(templates,ctx,emitter),ctx.pop()};return renderChild?(superBlock,emitter)=>renderChild(new BlockDrop(emitter2=>renderCurrent(superBlock,emitter2)),emitter):renderCurrent}*children(){return this.templates}blockScope(){return["block"]}},RawTag=class extends Tag{constructor(tagToken,remainTokens,liquid){for(super(tagToken,remainTokens,liquid),this.tokens=[];remainTokens.length;){let token=remainTokens.shift();if(isTagToken(token)&&token.name==="endraw")return;this.tokens.push(token)}throw new Error(`tag ${tagToken.getText()} not closed`)}render(){return this.tokens.map(token=>token.getText()).join("")}},TablerowloopDrop=class extends ForloopDrop{constructor(length,cols,collection,variable){super(length,collection,variable),this.length=length,this.cols=cols}row(){return Math.floor(this.i/this.cols)+1}col0(){return this.i%this.cols}col(){return this.col0()+1}col_first(){return this.col0()===0}col_last(){return this.col()===this.cols}},TablerowTag=class extends Tag{constructor(tagToken,remainTokens,liquid,parser){super(tagToken,remainTokens,liquid);let variable=this.tokenizer.readIdentifier();this.tokenizer.skipBlank();let predicate=this.tokenizer.readIdentifier(),collectionToken=this.tokenizer.readValue();if(predicate.content!=="in"||!collectionToken)throw new Error(`illegal tag: ${tagToken.getText()}`);this.variable=variable.content,this.collection=collectionToken,this.args=new Hash(this.tokenizer,liquid.options.keyValueSeparator),this.templates=[];let p,stream=parser.parseStream(remainTokens).on("start",()=>p=this.templates).on("tag:endtablerow",()=>stream.stop()).on("template",tpl=>p.push(tpl)).on("end",()=>{throw new Error(`tag ${tagToken.getText()} not closed`)});stream.start()}*render(ctx,emitter){let collection=toEnumerable(yield evalToken(this.collection,ctx)),args=yield this.args.render(ctx),offset2=args.offset||0,limit2=args.limit===void 0?collection.length:args.limit;collection=collection.slice(offset2,offset2+limit2);let cols=args.cols||collection.length,r=this.liquid.renderer,tablerowloop=new TablerowloopDrop(collection.length,cols,this.collection.getText(),this.variable),scope={tablerowloop};ctx.push(scope);for(let idx=0;idx<collection.length;idx++,tablerowloop.next())scope[this.variable]=collection[idx],tablerowloop.col0()===0&&(tablerowloop.row()!==1&&emitter.write("</tr>"),emitter.write(`<tr class="row${tablerowloop.row()}">`)),emitter.write(`<td class="col${tablerowloop.col()}">`),yield r.renderTemplates(this.templates,ctx,emitter),emitter.write("</td>");collection.length&&emitter.write("</tr>"),ctx.pop()}*children(){return this.templates}*arguments(){yield this.collection;for(let v2 of Object.values(this.args.hash))isValueToken(v2)&&(yield v2)}blockScope(){return[this.variable,"tablerowloop"]}},UnlessTag=class extends Tag{constructor(tagToken,remainTokens,liquid,parser){super(tagToken,remainTokens,liquid),this.branches=[],this.elseTemplates=[];let p=[],elseCount=0;parser.parseStream(remainTokens).on("start",()=>this.branches.push({value:new Value(tagToken.tokenizer.readFilteredValue(),this.liquid),test:isFalsy,templates:p=[]})).on("tag:elsif",token=>{if(elseCount>0){p=[];return}this.branches.push({value:new Value(token.tokenizer.readFilteredValue(),this.liquid),test:isTruthy,templates:p=[]})}).on("tag:else",()=>{elseCount++,p=this.elseTemplates}).on("tag:endunless",function(){this.stop()}).on("template",tpl=>{(p!==this.elseTemplates||elseCount===1)&&p.push(tpl)}).on("end",()=>{throw new Error(`tag ${tagToken.getText()} not closed`)}).start()}*render(ctx,emitter){let r=this.liquid.renderer;for(let{value,test,templates}of this.branches){let v2=yield value.value(ctx,ctx.opts.lenientIf);if(test(v2,ctx)){yield r.renderTemplates(templates,ctx,emitter);return}}yield r.renderTemplates(this.elseTemplates,ctx,emitter)}*children(){let children=this.branches.flatMap(b=>b.templates);return this.elseTemplates&&children.push(...this.elseTemplates),children}arguments(){return this.branches.map(b=>b.value)}},BreakTag=class extends Tag{render(ctx,_emitter){ctx.breakCalled=!0}},ContinueTag=class extends Tag{render(ctx,_emitter){ctx.continueCalled=!0}},EchoTag=class extends Tag{constructor(token,remainTokens,liquid){super(token,remainTokens,liquid),this.tokenizer.skipBlank(),this.tokenizer.end()||(this.value=new Value(this.tokenizer.readFilteredValue(),this.liquid))}*render(ctx,emitter){if(!this.value)return;let val=yield this.value.value(ctx,!1);emitter.write(val)}*arguments(){this.value&&(yield this.value)}},LiquidTag=class extends Tag{constructor(token,remainTokens,liquid,parser){super(token,remainTokens,liquid);let tokens=this.tokenizer.readLiquidTagTokens(this.liquid.options);this.templates=parser.parseTokens(tokens)}*render(ctx,emitter){yield this.liquid.renderer.renderTemplates(this.templates,ctx,emitter)}*children(){return this.templates}},InlineCommentTag=class extends Tag{constructor(tagToken,remainTokens,liquid){if(super(tagToken,remainTokens,liquid),tagToken.args.search(/\n\s*[^#\s]/g)!==-1)throw new Error("every line of an inline comment must start with a '#' character")}render(){}},tags={assign:AssignTag,for:ForTag,capture:CaptureTag,case:CaseTag,comment:CommentTag,include:IncludeTag,render:RenderTag,decrement:DecrementTag,increment:IncrementTag,cycle:CycleTag,if:IfTag,layout:LayoutTag,block:BlockTag,raw:RawTag,tablerow:TablerowTag,unless:UnlessTag,break:BreakTag,continue:ContinueTag,echo:EchoTag,liquid:LiquidTag,"#":InlineCommentTag},Liquid=class _Liquid{constructor(opts={}){this.renderer=new Render,this.filters={},this.tags={},this.options=normalize2(opts),this.parser=new Parser(this),forOwn(tags,(conf,name)=>this.registerTag(name,conf)),forOwn(filters,(handler,name)=>this.registerFilter(name,handler))}parse(html,filepath){return new Parser(this).parse(html,filepath)}_render(tpl,scope,renderOptions){let ctx=scope instanceof Context?scope:new Context(scope,this.options,renderOptions);return this.renderer.renderTemplates(tpl,ctx)}render(tpl,scope,renderOptions){return __awaiter(this,void 0,void 0,function*(){return toPromise(this._render(tpl,scope,Object.assign(Object.assign({},renderOptions),{sync:!1})))})}renderSync(tpl,scope,renderOptions){return toValueSync(this._render(tpl,scope,Object.assign(Object.assign({},renderOptions),{sync:!0})))}renderToNodeStream(tpl,scope,renderOptions={}){let ctx=new Context(scope,this.options,renderOptions);return this.renderer.renderTemplatesToNodeStream(tpl,ctx)}_parseAndRender(html,scope,renderOptions){let tpl=this.parse(html);return this._render(tpl,scope,renderOptions)}parseAndRender(html,scope,renderOptions){return __awaiter(this,void 0,void 0,function*(){return toPromise(this._parseAndRender(html,scope,Object.assign(Object.assign({},renderOptions),{sync:!1})))})}parseAndRenderSync(html,scope,renderOptions){return toValueSync(this._parseAndRender(html,scope,Object.assign(Object.assign({},renderOptions),{sync:!0})))}_parsePartialFile(file2,sync,currentFile){return new Parser(this).parseFile(file2,sync,LookupType.Partials,currentFile)}_parseLayoutFile(file2,sync,currentFile){return new Parser(this).parseFile(file2,sync,LookupType.Layouts,currentFile)}_parseFile(file2,sync,lookupType,currentFile){return new Parser(this).parseFile(file2,sync,lookupType,currentFile)}parseFile(file2,lookupType){return __awaiter(this,void 0,void 0,function*(){return toPromise(new Parser(this).parseFile(file2,!1,lookupType))})}parseFileSync(file2,lookupType){return toValueSync(new Parser(this).parseFile(file2,!0,lookupType))}*_renderFile(file2,ctx,renderFileOptions){let templates=yield this._parseFile(file2,renderFileOptions.sync,renderFileOptions.lookupType);return yield this._render(templates,ctx,renderFileOptions)}renderFile(file2,ctx,renderFileOptions){return __awaiter(this,void 0,void 0,function*(){return toPromise(this._renderFile(file2,ctx,Object.assign(Object.assign({},renderFileOptions),{sync:!1})))})}renderFileSync(file2,ctx,renderFileOptions){return toValueSync(this._renderFile(file2,ctx,Object.assign(Object.assign({},renderFileOptions),{sync:!0})))}renderFileToNodeStream(file2,scope,renderOptions){return __awaiter(this,void 0,void 0,function*(){let templates=yield this.parseFile(file2);return this.renderToNodeStream(templates,scope,renderOptions)})}_evalValue(str,scope){let value=new Value(str,this),ctx=scope instanceof Context?scope:new Context(scope,this.options);return value.value(ctx)}evalValue(str,scope){return __awaiter(this,void 0,void 0,function*(){return toPromise(this._evalValue(str,scope))})}evalValueSync(str,scope){return toValueSync(this._evalValue(str,scope))}registerFilter(name,filter3){this.filters[name]=filter3}registerTag(name,tag){this.tags[name]=isFunction(tag)?tag:createTagClass(tag)}plugin(plugin){return plugin.call(this,_Liquid)}express(){let self=this,firstCall=!0;return function(filePath,ctx,callback){if(firstCall){firstCall=!1;let dirs=normalizeDirectoryList(this.root);self.options.root.unshift(...dirs),self.options.layouts.unshift(...dirs),self.options.partials.unshift(...dirs)}self.renderFile(filePath,ctx).then(html=>callback(null,html),callback)}}analyze(template,options2={}){return __awaiter(this,void 0,void 0,function*(){return analyze(template,options2)})}analyzeSync(template,options2={}){return analyzeSync(template,options2)}parseAndAnalyze(html,filename,options2={}){return __awaiter(this,void 0,void 0,function*(){return analyze(this.parse(html,filename),options2)})}parseAndAnalyzeSync(html,filename,options2={}){return analyzeSync(this.parse(html,filename),options2)}variables(template,options2={}){return __awaiter(this,void 0,void 0,function*(){let analysis=yield analyze(isString(template)?this.parse(template):template,options2);return Object.keys(analysis.variables)})}variablesSync(template,options2={}){let analysis=analyzeSync(isString(template)?this.parse(template):template,options2);return Object.keys(analysis.variables)}fullVariables(template,options2={}){return __awaiter(this,void 0,void 0,function*(){let analysis=yield analyze(isString(template)?this.parse(template):template,options2);return Array.from(new Set(Object.values(analysis.variables).flatMap(a=>a.map(v2=>String(v2)))))})}fullVariablesSync(template,options2={}){let analysis=analyzeSync(isString(template)?this.parse(template):template,options2);return Array.from(new Set(Object.values(analysis.variables).flatMap(a=>a.map(v2=>String(v2)))))}variableSegments(template,options2={}){return __awaiter(this,void 0,void 0,function*(){let analysis=yield analyze(isString(template)?this.parse(template):template,options2);return Array.from(strictUniq(Object.values(analysis.variables).flatMap(a=>a.map(v2=>v2.toArray()))))})}variableSegmentsSync(template,options2={}){let analysis=analyzeSync(isString(template)?this.parse(template):template,options2);return Array.from(strictUniq(Object.values(analysis.variables).flatMap(a=>a.map(v2=>v2.toArray()))))}globalVariables(template,options2={}){return __awaiter(this,void 0,void 0,function*(){let analysis=yield analyze(isString(template)?this.parse(template):template,options2);return Object.keys(analysis.globals)})}globalVariablesSync(template,options2={}){let analysis=analyzeSync(isString(template)?this.parse(template):template,options2);return Object.keys(analysis.globals)}globalFullVariables(template,options2={}){return __awaiter(this,void 0,void 0,function*(){let analysis=yield analyze(isString(template)?this.parse(template):template,options2);return Array.from(new Set(Object.values(analysis.globals).flatMap(a=>a.map(v2=>String(v2)))))})}globalFullVariablesSync(template,options2={}){let analysis=analyzeSync(isString(template)?this.parse(template):template,options2);return Array.from(new Set(Object.values(analysis.globals).flatMap(a=>a.map(v2=>String(v2)))))}globalVariableSegments(template,options2={}){return __awaiter(this,void 0,void 0,function*(){let analysis=yield analyze(isString(template)?this.parse(template):template,options2);return Array.from(strictUniq(Object.values(analysis.globals).flatMap(a=>a.map(v2=>v2.toArray()))))})}globalVariableSegmentsSync(template,options2={}){let analysis=analyzeSync(isString(template)?this.parse(template):template,options2);return Array.from(strictUniq(Object.values(analysis.globals).flatMap(a=>a.map(v2=>v2.toArray()))))}};import{NotFoundError as NotFoundError3,PluginError as PluginError6}from"@sous-io/sous-plugin-api";var DEFAULT_PURPOSE="template",CONFIG_EXPRESSION_PURPOSE="config-expression";function tagAllowed(tag,purpose){return tag.purposes?tag.purposes.includes(purpose):purpose!==CONFIG_EXPRESSION_PURPOSE}function filterAllowed(filter3,purpose){return filter3.purposes?filter3.purposes.includes(purpose):!0}function createLiquidEngines(deps){return{create:(options2={})=>buildEngine(deps,options2),available(purpose=DEFAULT_PURPOSE){return{tags:deps.entities.list("liquid-tag").filter(tag=>tagAllowed(tag,purpose)).map(tag=>tag.id),filters:deps.entities.list("liquid-filter").filter(filter3=>filterAllowed(filter3,purpose)).map(filter3=>filter3.id)}}}}function buildEngine(deps,options2){let purpose=options2.purpose??DEFAULT_PURPOSE,root=rootOf(options2.root,deps.project),liquidOptions={extname:"",strictVariables:!1,strictFilters:!1,...options2.liquid,...root===void 0?{}:{root},...options2.fs===void 0?{}:{fs:options2.fs}},engine=withBooleans(new Liquid(liquidOptions),options2.booleanNames??declaredBooleans2(deps.services)),ctx=Object.freeze({project:deps.project,env:deps.env,services:deps.services,entities:deps.entities,purpose,secretNames:new Set(options2.secretNames??declaredSecrets(deps.services)),data:Object.freeze({...options2.data})}),filters2=pick(deps.entities.describe("liquid-filter"),options2.only?.filters,entry=>filterAllowed(entry,purpose),"Liquid filter");for(let record2 of filters2)engine.registerFilter(record2.id,make(record2,"filter",()=>record2.entry.filter(ctx)));let tags2=pick(deps.entities.describe("liquid-tag"),options2.only?.tags,entry=>tagAllowed(entry,purpose),"Liquid tag");for(let record2 of tags2)engine.registerTag(record2.id,make(record2,"tag",()=>record2.entry.tag(ctx)));return engine}function rootOf(root,project){return root!==void 0?typeof root=="string"?root:[...root]:project?[project.root]:void 0}function liquidValues(scope,booleanNames2){let out;for(let name of booleanNames2){let value=scope[name];(value==="true"||value==="false")&&(out??={...scope},out[name]=value==="true")}return out??scope}function withBooleans(engine,names2){let booleanNames2=new Set(names2);if(booleanNames2.size===0)return engine;let convert=scope=>scope!==null&&typeof scope=="object"&&Object.getPrototypeOf(scope)===Object.prototype?liquidValues(scope,booleanNames2):scope,internal=engine;for(let method of["_render","_renderFile","_evalValue"]){let original=internal[method].bind(engine);internal[method]=(first2,scope,...rest)=>original(first2,convert(scope),...rest)}return engine}function declaredBooleans2(services){try{return services.has("variables.booleans")?services.get("variables.booleans").declared():[]}catch{return[]}}function declaredSecrets(services){return services.has("variables.secrets")?services.get("variables.secrets").declared():[]}function pick(records,only,allowed,thing){return only===void 0?records.filter(record2=>allowed(record2.entry)):only.map(id=>{let record2=records.find(candidate=>candidate.id===id);if(!record2)throw new NotFoundError3(thing,id);return record2})}function make(record2,what,factory2){try{return factory2()}catch(error51){throw new PluginError6(record2.plugin,`The Liquid ${what} "${record2.id}" from ${record2.plugin} could not be made.`,{cause:error51,details:[error51 instanceof Error?error51.message:String(error51)]})}}import{jsonSchema as jsonSchema8}from"@sous-io/sous-plugin-api";var PURPOSES={type:"array",items:{type:"string"}};function extensionSchema(factory2){let base=jsonSchema8({type:"object",properties:{id:{type:"string"},description:{type:"string"},purposes:PURPOSES,[factory2]:{}},required:["id",factory2]});return{"~standard":{...base["~standard"],validate(value){let result=base["~standard"].validate(value);return result instanceof Promise||result.issues?result:typeof result.value[factory2]!="function"?{issues:[{message:"Expected a function.",path:[factory2]}]}:result}}}}var liquidTagSchema=extensionSchema("tag"),liquidFilterSchema=extensionSchema("filter");var package_default7={name:"@sous-io/sous-plugin-liquid",version:"1.1.4",description:"A configured LiquidJS engine, and the Liquid tags and filters plugins add.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-host":"workspace:*",liquidjs:"^10.25.0"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME6="@sous-io/sous-plugin-liquid",liquidPlugin=definePlugin7({name:PLUGIN_NAME6,version:package_default7.version,description:"A configured LiquidJS engine, and the Liquid tags and filters plugins add.",dependsOn:{"@sous-io/sous-plugin-host":`^${package_default7.version}`},register(sous){sous.entities.define("liquid-tag",liquidTagSchema,{description:"A Liquid tag, as written in {% name %}."}),sous.entities.define("liquid-filter",liquidFilterSchema,{description:"A Liquid filter, as written after |. Config expressions see it too."}),sous.services.add("liquid.engine",(_config,ctx)=>createLiquidEngines(ctx),{lifetime:"factory"})}});init_src5();import{definePlugin as definePlugin9,jsonSchema as jsonSchema9}from"@sous-io/sous-plugin-api";import fs16 from"node:fs";import nodePath from"node:path";import{ConfigError as ConfigError21,formatIssuePath as formatIssuePath2}from"@sous-io/sous-plugin-api";function formatPath2(path122){return path122.length===0?"(root)":formatIssuePath2(path122)}var ExpressionError=class extends ConfigError21{file;path;constructor(file2,path122,problem,options2={}){let printed=typeof path122=="string"?path122:formatPath2(path122);super(`${printed} ${problem}`,{...options2,details:[`in ${file2}`,...options2.details??[]]}),this.file=file2,this.path=printed}};var QUALIFIED=/^\$(expr|if|elseif)(?::(.*))?$/s,FILE_KEY="$file";function parseReservedKey(key){if(key==="$else")return{kind:"else",key};if(key===FILE_KEY)return{kind:"file",key};let match2=QUALIFIED.exec(key);if(!match2)return;let kind=match2[1],qualifier=match2[2];return kind==="expr"?{kind,key,language:qualifier}:{kind,key,name:qualifier}}function isReservedKey(key){return parseReservedKey(key)!==void 0}function isPlainObject3(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isExpressionObject(value){return isPlainObject3(value)&&Object.keys(value).some(isReservedKey)}function hasExpressions(value){return Array.isArray(value)?value.some(hasExpressions):isPlainObject3(value)?isExpressionObject(value)||Object.values(value).some(hasExpressions):!1}function compareBytes(a,b){return Buffer.compare(Buffer.from(a,"utf8"),Buffer.from(b,"utf8"))}function chainOrder(keys){return[...keys].sort((a,b)=>a.name===void 0||b.name===void 0?a.name===b.name?0:a.name===void 0?-1:1:compareBytes(a.name,b.name))}import{ConfigError as ConfigError22}from"@sous-io/sous-plugin-api";var LIQUID_LANGUAGE="liquid",LEFT="\0<",RIGHT=">\0",analyzerEngine;function analyzer(){return analyzerEngine??=new Liquid({outputDelimiterLeft:LEFT,outputDelimiterRight:RIGHT}),analyzerEngine}function createLiquidLanguage(){return{id:LIQUID_LANGUAGE,description:"Liquid expressions, as in a {% if %} condition (the default).",runsCode:!1,variables(expression,ctx){return guard(expression,ctx,()=>analyzer().globalVariablesSync(analyzer().parse(`${LEFT}${expression}${RIGHT}`)))},evaluate(expression,scope,ctx){return evaluateLiquid(expression,scope,ctx)}}}function evaluateLiquid(expression,scope,ctx){let engine=engineFor(ctx),used=guard(expression,ctx,()=>new Tokenizer(expression).readFilteredValue().filters.map(filter3=>filter3.name)),missing=[...new Set(used.filter(name=>!(name in engine.filters)))];if(missing.length>0)return{unknown:{variables:[],filters:missing}};let value=guard(expression,ctx,()=>engine.evalValueSync(expression,{...scope.vars,host:scope.host,harness:scope.harness,env:scope.env}));return{value:toValue(value)}}function renderLiquidTemplate(text,scope,ctx){let engine=engineFor(ctx);try{return engine.parseAndRenderSync(text,{...scope})}catch(error51){if(error51 instanceof ConfigError22)throw error51;let reason=error51 instanceof Error?error51.message:String(error51);throw new ExpressionError(ctx.file,ctx.path,`reads a template that failed to render: ${reason}`,{cause:error51})}}function engineFor(ctx){let entities=ctx.entities??emptyEntities,cached2=engines.get(entities);if(cached2)return cached2;let engine=makeEngine(ctx,entities);return engines.set(entities,engine),engine}var engines=new WeakMap;function makeEngine(ctx,entities){let services=ctx.services??noServices;return createLiquidEngines({project:ctx.project,env:ctx.env??{},services,entities}).create({purpose:CONFIG_EXPRESSION_PURPOSE,secretNames:[],liquid:{strictFilters:!0}})}function guard(expression,ctx,run){try{return run()}catch(error51){if(error51 instanceof ConfigError22)throw error51;let reason=error51 instanceof Error?error51.message:String(error51);throw new ExpressionError(ctx.file,ctx.path,`holds the Liquid expression ${JSON.stringify(expression)}, which failed: ${reason}`,{cause:error51})}}var emptyEntities={get:()=>{},list:()=>[],has:()=>!1,describe:()=>[],kinds:()=>[]},noServices={get(name){throw new ConfigError22(`The service "${name}" is not available to config expressions.`)},has:()=>!1};function parseExpressionObject(object3,path122,file2){if(Object.hasOwn(object3,FILE_KEY))return parseFileObject(object3,path122,file2);let exprKeys=[],ifs=[],elseifs=[],hasElse=!1,stray=[];for(let key of Object.keys(object3)){let reserved=parseReservedKey(key);reserved?reserved.kind==="expr"?exprKeys.push(reserved):reserved.kind==="else"?hasElse=!0:reserved.kind==="file"||(reserved.kind==="if"?ifs:elseifs).push(reserved):stray.push(key)}let reservedKeys=Object.keys(object3).filter(key=>!stray.includes(key));if(stray.length>0)throw new ExpressionError(file2,path122,`mixes the expression key ${quote(reservedKeys[0])} with ${list(stray)}, which ${stray.length===1?"is":"are"} not one.`,{details:["An expression object holds only $expr, $if, $elseif and $else keys (with their qualifiers)."]});for(let key of[...ifs,...elseifs])if(key.name==="")throw new ExpressionError(file2,[...path122,key.key],"has an empty qualifier. Write a name after the colon, or leave the colon out.");if(exprKeys.length>0){if(exprKeys.length>1)throw new ExpressionError(file2,path122,`holds ${list(exprKeys.map(key2=>key2.key))}; write one.`);if(ifs.length>0||elseifs.length>0||hasElse)throw new ExpressionError(file2,path122,`holds ${quote(exprKeys[0].key)} together with ${list(reservedKeys.filter(key2=>key2!==exprKeys[0].key))}.`,{details:["$expr computes one value; $if, $elseif and $else choose between values. Use one or the other."]});let key=exprKeys[0];return{kind:"value",expression:expressionAt(object3[key.key],key.language,[...path122,key.key],file2)}}let keys=[...chainOrder(ifs),...chainOrder(elseifs)],branches=[];return keys.forEach((key,index)=>{let last2=index===keys.length-1;branches.push(...parseBranches(object3[key.key],[...path122,key.key],{last:last2,hasElse},file2))}),{kind:"chain",branches,otherwise:hasElse?{value:object3.$else,path:[...path122,"$else"]}:void 0}}function parseFileObject(object3,path122,file2){let others=Object.keys(object3).filter(key=>key!==FILE_KEY);if(others.length>0)throw new ExpressionError(file2,path122,`mixes "$file" with ${list(others)}.`,{details:["An object holding $file stands in for the file's value, so it holds no other key. Wrap it in $if to choose it conditionally."]});let value=object3[FILE_KEY];if(typeof value!="string"||value.trim()==="")throw new ExpressionError(file2,[...path122,FILE_KEY],`is ${describe3(value??null)}. $file takes the path of a file, as a string.`);return{kind:"file",file:value,path:[...path122,FILE_KEY]}}function parseBranches(value,path122,place,file2){if(typeof value=="string")return[{condition:expressionAt(value,void 0,path122,file2),then:void 0}];if(Array.isArray(value))return value.map((item,index)=>{let itemPath=[...path122,index],branch2=typeof item=="string"?{condition:expressionAt(item,void 0,itemPath,file2),then:void 0}:parseBlock(item,itemPath,file2);return branch2.condition===void 0&&checkFallback(itemPath,index===value.length-1,place,file2),branch2});let branch=parseBlock(value,path122,file2);if(branch.condition===void 0)throw new ExpressionError(file2,path122,"has no expr. A branch block needs one; only an array item may leave it out, as a fallback.");return[branch]}function checkFallback(path122,lastItem,place,file2){if(place.hasElse)throw new ExpressionError(file2,path122,"is a fallback (an item with no expr), and the chain also has an $else. Keep one of them.");if(!lastItem||!place.last)throw new ExpressionError(file2,path122,"is a fallback (an item with no expr), which is only allowed as the last item of the last key in the chain.")}function parseBlock(value,path122,file2){if(!isPlainObject3(value))throw new ExpressionError(file2,path122,`is ${describe3(value)}. A branch is a string, a block with expr and then, or an array of those.`);let exprKeys=[],thenKeys=[],unknown2=[];for(let key of Object.keys(value))/^\$?expr(:.*)?$/s.test(key)?exprKeys.push(key):key==="then"||key==="$then"?thenKeys.push(key):unknown2.push(key);if(unknown2.length>0)throw new ExpressionError(file2,path122,`holds ${list(unknown2)}. A branch block holds only expr (or $expr) and then (or $then).`);if(exprKeys.length>1)throw new ExpressionError(file2,path122,`holds both ${list(exprKeys,"and")}. Write one.`);if(thenKeys.length>1)throw new ExpressionError(file2,path122,'holds both "then" and "$then". Write one.');if(exprKeys.length===0&&thenKeys.length===0)throw new ExpressionError(file2,path122,"is an empty branch block. Give it an expr, a then, or both.");let exprKey=exprKeys[0],thenKey=thenKeys[0],language=exprKey===void 0?void 0:qualifierOf(exprKey);return{condition:exprKey===void 0?void 0:expressionAt(value[exprKey],language,[...path122,exprKey],file2),then:thenKey===void 0?void 0:{value:value[thenKey],path:[...path122,thenKey]}}}function qualifierOf(key){let colon=key.indexOf(":");return colon===-1?void 0:key.slice(colon+1)}function expressionAt(value,language,path122,file2){if(language==="")throw new ExpressionError(file2,path122,"has an empty language qualifier. Name the language after the colon, or leave the colon out.");if(typeof value!="string")throw new ExpressionError(file2,path122,`is ${describe3(value)}. An expression is a string.`);return{language,source:value,path:path122}}function describe3(value){return value===null?"null":Array.isArray(value)?"an array":typeof value=="object"?"an object":`a ${typeof value} (${JSON.stringify(value)})`}function quote(key){return JSON.stringify(key)}function list(keys,join4="and"){let quoted=keys.map(quote);return quoted.length<=1?quoted.join(""):`${quoted.slice(0,-1).join(", ")} ${join4} ${quoted.at(-1)}`}var BUILT_IN_NAMES=new Set(["host","harness","env"]);function createEvaluator(deps){let byFile=new Map,stale=!1;return{evaluateLayer(data,options2){stale&&(byFile.clear(),stale=!1);let run=new LayerRun(data,options2,deps),value=run.evaluate(),harness=harnessOf(options2.config);return byFile.set(`${harness}\0${options2.file}`,{harness,expressions:run.expressions,unsettled:run.unsettled,files:[...run.files]}),{value,expressions:run.expressions,pending:run.unsettled.length>0}},isExpressionObject,hasExpressions,evaluations(file2,harness=""){return file2!==void 0?[...byFile.get(`${harness}\0${file2}`)?.expressions??[]]:[...byFile.values()].filter(entry=>entry.harness===harness).flatMap(entry=>entry.expressions)},unsettled(){return[...byFile.values()].flatMap(entry=>entry.unsettled)},files(){return[...new Set([...byFile.values()].flatMap(entry=>entry.files))]},languages(){return deps.entities.list("expression-language").map(language=>language.id)},settle(){let open2=this.unsettled();if(stale=!0,open2.length>0)throw unsettledError(open2)}}}function unsettledError(open2){let[first2,...rest]=open2;return new ExpressionError(first2.file,first2.path,`${describeUnknown(first2.unknown)}.`,{details:[...first2.harness===""?[]:[`This is in the config build for the harness "${first2.harness}".`],...rest.map(entry=>`${entry.path} ${describeUnknown(entry.unknown)} (in ${entry.file}${entry.harness===""?"":`, in the build for the harness "${entry.harness}"`})`)]})}function describeUnknown(unknown2){let parts=[];if(unknown2.variables.length>0){let one=unknown2.variables.length===1;parts.push(`reads ${names(unknown2.variables)}, which ${one?"is":"are"} not set anywhere in the config`)}if(unknown2.filters.length>0){let one=unknown2.filters.length===1;parts.push(`uses the Liquid filter${one?"":"s"} ${names(unknown2.filters)}, which no plugin adds`)}return parts.join(", and ")}function names(list2){return list2.join(", ")}function harnessOf(config2){return config2.harness?.id??""}function isTruthy2(value){return value!==!1&&value!==void 0&&value!==null}var LayerRun=class{constructor(data,options2,deps){this.data=data;this.options=options2;this.deps=deps;this.config=options2.config,this.file=options2.file,this.entities=builderEntities(options2.config),this.lookup={get:path122=>options2.config.atPath(path122).get()}}expressions=[];unsettled=[];files=new Set;reading=[];config;file;entities;lookup;reads;unknown;evaluate(){return this.walk(this.data,[],{})}walk(value,path122,levelVars){if(Array.isArray(value)){let out2=[];return value.forEach((item,index)=>{let result=this.walk(item,[...path122,index],levelVars);result!==void 0&&out2.push(result)}),out2}if(!isPlainObject3(value))return value;if(isExpressionObject(value))return this.expressionObject(value,path122,levelVars);let inner=isScopeLevel(path122)?{...levelVars,...this.ownVarsOf(value,path122)}:levelVars,out={};for(let[key,child2]of Object.entries(value)){let result=this.walk(child2,[...path122,key],inner);result!==void 0&&(out[key]=result)}return out}ownVarsOf(object3,path122){if(path122.length===0&&this.options.ownVars)return this.options.ownVars;let block=object3._vars;return isPlainObject3(block)?Object.fromEntries(Object.entries(block).filter(entry=>typeof entry[1]=="string")):{}}expressionObject(object3,path122,levelVars){let outermost=this.reads===void 0;outermost&&(this.reads={},this.unknown=void 0);try{let plan2=parseExpressionObject(object3,path122,this.file),value=this.evaluatePlan(plan2,path122,levelVars);return outermost&&this.expressions.push({path:formatPath2(path122),written:object3,value,reads:this.reads,...this.unknown?{unknown:this.unknown}:{}}),value}finally{outermost&&(this.reads=void 0,this.unknown=void 0)}}evaluatePlan(plan2,path122,levelVars){if(plan2.kind==="file")return this.fileValue(plan2,path122,levelVars);if(plan2.kind==="value"){let outcome=this.run(plan2.expression,path122,levelVars);return"unknown"in outcome?this.pending(path122,outcome.unknown):toJson(outcome.value)}for(let branch of plan2.branches){if(branch.condition===void 0)return this.chosen(branch.then,path122,levelVars);let outcome=this.run(branch.condition,path122,levelVars);if("unknown"in outcome)return this.pending(path122,outcome.unknown);if(isTruthy2(outcome.value))return branch.then?this.chosen(branch.then,path122,levelVars):!0}return plan2.otherwise?this.chosen(plan2.otherwise,path122,levelVars):void 0}chosen(written,path122,levelVars){return this.walk(written.value,path122,levelVars)}pending(path122,unknown2){this.unknown=unknown2,this.unsettled.push({file:this.file,harness:harnessOf(this.config),path:formatPath2(path122),unknown:unknown2})}run(expression,path122,levelVars){let language=this.language(expression),ctx={project:this.deps.project,file:this.file,path:formatPath2(expression.path),env:this.config.env,entities:this.entities,services:this.deps.services},variables=[...new Set(language.variables(expression.source,ctx))].filter(name=>!BUILT_IN_NAMES.has(name));this.checkForbidden(variables,path122);let vars=variables.length>0?this.scope(path122,levelVars):levelVars,missing=[];for(let name of variables){let known=Object.hasOwn(vars,name);this.reads[name]=known?vars[name]:void 0,known||missing.push(name)}return missing.length>0?{unknown:{variables:missing,filters:[]}}:language.evaluate(expression.source,{...this.builtIns(),vars:this.typed(vars)},ctx)}typed(vars){let names2=new Set(this.config.entities("variable-source").flatMap(source=>source.booleans?.({project:this.deps.project,env:this.config.env,config:this.lookup})??[]));return names2.size===0?vars:liquidValues(vars,names2)}builtIns(){return{host:{platform:this.deps.platform??process.platform},env:this.config.env,harness:{id:harnessOf(this.config)}}}fileValue(plan2,path122,levelVars){let written=plan2.file,vars;if(written.includes("${")){if(!this.deps.services.has("variables.resolver"))throw new ExpressionError(this.file,plan2.path,`holds the path ${JSON.stringify(written)}, whose variables cannot be filled in without sous-plugin-variables.`);let resolver=this.deps.services.get("variables.resolver");vars=this.scope(path122,levelVars);let missing=resolver.unresolved(written,vars);for(let name2 of resolver.references(written))this.reads[name2]=vars[name2];if(missing.length>0)return this.pending(path122,{variables:missing,filters:[]});written=resolver.substitute(written,vars)}let absolute=nodePath.resolve(this.baseDir(),written);if(this.reading.includes(absolute))throw new ExpressionError(this.file,plan2.path,`reads ${absolute}, which is already being read: a $file cannot read itself.`);this.files.add(absolute);let text;try{text=fs16.readFileSync(absolute,"utf8")}catch(error51){throw new ExpressionError(this.file,plan2.path,`names the file ${absolute}, which could not be read: ${error51.message}`,{cause:error51})}let name=nodePath.basename(absolute);this.reading.push(absolute);try{name.includes(".tpl.")&&(text=renderLiquidTemplate(text,{...this.typed(vars??this.scope(path122,levelVars)),...this.builtIns()},{project:this.deps.project,file:this.file,path:formatPath2(plan2.path),env:this.config.env,entities:this.entities,services:this.deps.services}));let value=parseByExtension(text,name,this.deps.services,reason=>new ExpressionError(this.file,plan2.path,`names the file ${absolute}, which ${reason}`));return escapeVariables(value)}finally{this.reading.pop()}}baseDir(){return this.options.baseDir??this.deps.project?.root??process.cwd()}language(expression){let id=expression.language??LIQUID_LANGUAGE,languages=this.config.entities("expression-language"),language=languages.find(entry=>entry.id===id);if(!language){let known=languages.map(entry=>entry.id).join(", ")||"none";throw new ExpressionError(this.file,expression.path,`uses the expression language "${id}", which sous does not know. Known languages: ${known}.`)}if(this.options.fromRecipe&&language.runsCode){let allowed=languages.filter(entry=>!entry.runsCode).map(entry=>entry.id).join(", ")||"none";throw new ExpressionError(this.file,expression.path,`uses the expression language "${id}", which runs code. A recipe's config file may only use languages that do not (${allowed}).`)}return language}scope(path122,levelVars){if(!this.deps.services.has("variables.resolver"))return levelVars;let resolver=this.deps.services.get("variables.resolver"),level=path122[0]==="compilation"?"compilation":"root";return resolver.scopeIn(this.config,{level,extra:levelVars,...this.options.scopeKey===void 0?{}:{scopeKey:this.options.scopeKey}})}checkForbidden(variables,path122){let top=path122[0];if(!(variables.length===0||typeof top!="string"))for(let source of this.config.entities("variable-source")){if(!source.forbiddenUnder?.includes(top))continue;let given=source.variables({project:this.deps.project,env:this.config.env,config:this.lookup}),read=variables.find(name=>Object.hasOwn(given,name));if(read!==void 0)throw new ExpressionError(this.file,path122,forbiddenProblem(read,source))}}};function forbiddenProblem(name,source){let under=source.forbiddenUnder.map(key=>`"${key}"`).join(" or ");return source.description==="recipe answers"?`reads ${name}, which is an answer to a recipe. An expression that decides which recipes are subscribed or pinned (anything under ${under}) cannot read recipe answers.`:`reads ${name}, which comes from ${source.description}. An expression under ${under} cannot read ${source.description}.`}function parseByExtension(text,name,services,fail){let extension=nodePath.extname(name).toLowerCase();if(![".json",".jsonc",".yaml",".yml"].includes(extension))return text;try{if(services.has("formats.manifests"))return toJson(services.get("formats.manifests").parseText(text,name))??null;if(extension===".json")return toJson(JSON.parse(text))??null}catch(error51){throw fail(`could not be parsed: ${error51.message}`)}throw fail("is YAML or JSONC, which needs sous-plugin-formats to read.")}function escapeVariables(value){return typeof value=="string"?value.split("${").join("$${"):Array.isArray(value)?value.map(escapeVariables):isPlainObject3(value)?Object.fromEntries(Object.entries(value).map(([key,item])=>[key,escapeVariables(item)])):value}function isScopeLevel(path122){return path122.length===0?!0:path122[0]!=="compilation"?!1:path122.length===1||path122.length===3&&path122[1]==="targets"&&typeof path122[2]=="number"||path122.length===5&&path122[1]==="targets"&&typeof path122[2]=="number"&&path122[3]==="outputs"&&typeof path122[4]=="number"}function toJson(value){if(value==null||typeof value=="string"||typeof value=="boolean")return value;if(typeof value=="number")return Number.isFinite(value)?value:null;if(Array.isArray(value))return value.map(toJson).filter(item=>item!==void 0);if(isPlainObject3(value)&&Object.getPrototypeOf(value)===Object.prototype){let out={};for(let[key,item]of Object.entries(value)){let json3=toJson(item);json3!==void 0&&(out[key]=json3)}return out}if(!(typeof value=="function"||typeof value=="symbol"))return String(value)}function builderEntities(config2){return{get:(kind,id)=>config2.entity(kind,id),list:kind=>config2.entities(kind),has:(kind,id)=>config2.entity(kind,id)!==void 0,describe:kind=>config2.entities(kind).map(entry=>({kind,id:entry.id,entry,plugin:"a plugin"})),kinds:()=>[]}}var package_default9={name:"@sous-io/sous-plugin-expressions",version:"1.1.4",description:"Config expressions (S5) and the expression languages plugins add.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-liquid":"workspace:*","@sous-io/sous-plugin-variables":"workspace:*",liquidjs:"^10.25.0"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*","@sous-io/sous-plugin-host":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME8="@sous-io/sous-plugin-expressions",expressionsPlugin=definePlugin9({name:PLUGIN_NAME8,version:package_default9.version,description:"Config expressions and the expression languages plugins add.",dependsOn:{"@sous-io/sous-plugin-liquid":`^${package_default9.version}`,"@sous-io/sous-plugin-variables":`^${package_default9.version}`},register(sous){sous.entities.define("expression-language",jsonSchema9({type:"object",properties:{id:{type:"string"},description:{type:"string"},runsCode:{type:"boolean"}},required:["id","variables","evaluate"]}),{description:"A language config expressions are written in, named after $expr: or expr:."}),sous.entities.add("expression-language",createLiquidLanguage());let evaluator=createEvaluator({services:sous.services,entities:sous.entities,get project(){return sous.project}});sous.services.add("expressions.evaluator",()=>evaluator,{lifetime:"singleton"}),sous.on("config.built",()=>evaluator.settle())}});import fs19 from"node:fs";import{ConfigError as ConfigError24,definePlugin as definePlugin10}from"@sous-io/sous-plugin-api";import fs17 from"node:fs";import path22 from"node:path";var CONTRIBUTOR_PREFIX="confd/",MANAGED_NAME=/^5\d\d-/;function isManagedName(name){return MANAGED_NAME.test(name)}function contributorId(name){return`${CONTRIBUTOR_PREFIX}${name}`}function listConfdFiles(confDir,loader,compare){if(confDir===void 0)return[];let names2;try{names2=fs17.readdirSync(confDir)}catch{return[]}let files=[];for(let name of[...names2].sort(compare)){let format3=loader.formatOf(name),full=path22.join(confDir,name);format3===void 0||!isFile4(full)||files.push({name,path:full,format:format3,contributor:contributorId(name),managed:isManagedName(name)})}return files}function duplicateBaseNames(names2){let byBase=new Map;for(let name of names2){let dot=name.lastIndexOf("."),base=dot<=0?name:name.slice(0,dot);byBase.set(base,[...byBase.get(base)??[],name])}return[...byBase.values()].filter(group=>group.length>1)}var ConfdFilesImpl=class{constructor(confDir,loader,compare){this.confDir=confDir;this.loader=loader;this.compare=compare}directory(){return this.confDir}list(){return listConfdFiles(this.confDir,this.loader,this.compare)}};function isFile4(file2){try{return fs17.statSync(file2).isFile()}catch{return!1}}init_src();import fs18 from"node:fs";import path23 from"node:path";import{ConfigError as ConfigError23}from"@sous-io/sous-plugin-api";var MANAGED_FILE_COMMENT="This file is managed by sous. Sous edits these files by key; you may edit them too, and your comments, key order and formatting are kept.",FORMAT_NOTE=["It is JSON with comments (.jsonc): line comments, block comments and trailing","commas are all allowed here."],DESCRIPTIONS={"500-repos.jsonc":["It records the repositories this project trusts. The 'sous repo add' and","'sous repo remove' commands write the entries under 'repos'."],"510-subscriptions.jsonc":["It records what this project subscribes to. The 'sous subscription add' and","'sous subscription remove' commands write the entries under 'subscriptions'."]};function wrap2(text,width=78){let lines3=[],current="";for(let word of text.split(/\s+/))current.length===0?current=word:`${current} ${word}`.length+3<=width?current=`${current} ${word}`:(lines3.push(current),current=word);return current.length>0&&lines3.push(current),lines3}function managedHeader(name,description){let what=description.length>0?description:DESCRIPTIONS[name]??[];return`${[wrap2(MANAGED_FILE_COMMENT),what,FORMAT_NOTE].filter(block=>block.length>0).map(block=>block.map(line=>`// ${line}`.trimEnd()).join(`
1088
+ `," ",outputDelimiterLeft],htmlStopStringSet=new Set(htmlStopStrings);for(;this.p<this.N&&!htmlStopStringSet.has(this.peek());)yield this.match(outputDelimiterLeft)?this.readOutputToken(options2):this.readHTMLToken(htmlStopStrings)}match(word){for(let i=0;i<word.length;i++)if(word[i]!==this.input[this.p+i])return!1;return!0}rmatch(pattern){for(let i=0;i<pattern.length;i++)if(pattern[pattern.length-1-i]!==this.input[this.p-1-i])return!1;return!0}peekType(n7=0){return this.p+n7>=this.N?0:TYPES[this.input.charCodeAt(this.p+n7)]}peek(n7=0){return this.p+n7>=this.N?"":this.input[this.p+n7]}skipBlank(){for(;this.peekType()&BLANK2;)++this.p}},ParseStream=class{constructor(tokens,parseToken){this.handlers={},this.stopRequested=!1,this.tokens=tokens,this.parseToken=parseToken}on(name,cb){return this.handlers[name]=cb,this}trigger(event,arg){let h=this.handlers[event];return h?(h.call(this,arg),!0):!1}start(){this.trigger("start");let token;for(;!this.stopRequested&&(token=this.tokens.shift());){if(this.trigger("token",token)||isTagToken(token)&&this.trigger(`tag:${token.name}`,token))continue;let template=this.parseToken(token,this.tokens);this.trigger("template",template)}return this.stopRequested||this.trigger("end"),this}stop(){return this.stopRequested=!0,this}},TemplateImpl=class{constructor(token){this.token=token}},Tag=class extends TemplateImpl{constructor(token,remainTokens,liquid){super(token),this.name=token.name,this.liquid=liquid,this.tokenizer=token.tokenizer}},Hash=class{constructor(input,jekyllStyle){this.hash={};let tokenizer=input instanceof Tokenizer?input:new Tokenizer(input,{});for(let hash2 of tokenizer.readHashes(jekyllStyle))this.hash[hash2.name.content]=hash2.value}*render(ctx){let hash2={};for(let key of Object.keys(this.hash))hash2[key]=this.hash[key]===void 0?!0:yield evalToken(this.hash[key],ctx);return hash2}};function createTagClass(options2){return class extends Tag{constructor(token,tokens,liquid){super(token,tokens,liquid),isFunction(options2.parse)&&options2.parse.call(this,token,tokens)}*render(ctx,emitter){let hash2=yield new Hash(this.token.args,ctx.opts.keyValueSeparator).render(ctx);return yield options2.render.call(this,ctx,emitter,hash2)}}}function isKeyValuePair(arr){return isArray(arr)}var Filter=class{constructor(token,options2,liquid){this.token=token,this.name=token.name,this.handler=isFunction(options2)?options2:isFunction(options2?.handler)?options2.handler:identify,this.raw=!isFunction(options2)&&!!options2?.raw,this.args=token.args,this.liquid=liquid}*render(value,context){let argv2=[];for(let arg of this.args)isKeyValuePair(arg)?argv2.push([arg[0],yield evalToken(arg[1],context)]):argv2.push(yield evalToken(arg,context));return yield this.handler.apply({context,token:this.token,liquid:this.liquid},[value,...argv2])}},Value=class{constructor(input,liquid){this.filters=[];let token=typeof input=="string"?new Tokenizer(input,liquid.options.operators).readFilteredValue():input;this.initial=token.initial,this.filters=token.filters.map(token2=>new Filter(token2,this.getFilter(liquid,token2.name),liquid))}*value(ctx,lenient){lenient=lenient||ctx.opts.lenientIf&&this.filters.length>0&&this.filters[0].name==="default";let val=yield this.initial.evaluate(ctx,lenient);for(let filter3 of this.filters)val=yield filter3.render(val,ctx);return val}getFilter(liquid,name){let impl=liquid.filters[name];return assert(impl||!liquid.options.strictFilters,()=>`undefined filter: ${name}`),impl}},Output=class extends TemplateImpl{constructor(token,liquid){var _a4;super(token);let tokenizer=new Tokenizer(token.input,liquid.options.operators,token.file,token.contentRange);this.value=new Value(tokenizer.readFilteredValue(),liquid);let filters2=this.value.filters,outputEscape=liquid.options.outputEscape;if(!(!((_a4=filters2[filters2.length-1])===null||_a4===void 0)&&_a4.raw)&&outputEscape){let token2=new FilterToken(toString.call(outputEscape),[],"",0,0);filters2.push(new Filter(token2,outputEscape,liquid))}}*render(ctx,emitter){let val=yield this.value.value(ctx,!1);emitter.write(val)}*arguments(){yield this.value}},HTML=class extends TemplateImpl{constructor(token){super(token),this.str=token.getContent()}*render(ctx,emitter){emitter.write(this.str)}},Variable=class _Variable{constructor(segments,location){this.segments=segments,this.location=location}toString(){return segmentsString(this.segments,!0)}toArray(){function*_visit(...segments){for(let segment of segments)segment instanceof _Variable?yield Array.from(_visit(...segment.segments)):yield segment}return Array.from(_visit(...this.segments))}},VariableMap=class{constructor(){this.map=new Map}get(key){let k2=segmentsString([key.segments[0]]);return this.map.has(k2)||this.map.set(k2,[]),this.map.get(k2)}has(key){return this.map.has(segmentsString([key.segments[0]]))}push(variable){this.get(variable).push(variable)}asObject(){return Object.fromEntries(this.map)}},defaultStaticAnalysisOptions={partials:!0};function*_analyze(templates,partials,sync){let variables=new VariableMap,globals=new VariableMap,locals=new VariableMap,rootScope=new DummyScope(new Set),seen=new Set;function updateVariables(variable,scope){variables.push(variable);let aliased=scope.alias(variable);if(aliased!==void 0){let root=aliased.segments[0];isString(root)&&!rootScope.has(root)&&globals.push(aliased)}else{let root=variable.segments[0];isString(root)&&!scope.has(root)&&globals.push(variable)}for(let segment of variable.segments)segment instanceof Variable&&updateVariables(segment,scope)}function*visit3(template,scope){if(template.arguments)for(let arg of template.arguments())for(let variable of extractVariables(arg))updateVariables(variable,scope);if(template.localScope)for(let ident of template.localScope()){scope.add(ident.content),scope.deleteAlias(ident.content);let[row,col]=ident.getPosition();locals.push(new Variable([ident.content],{row,col,file:ident.file}))}if(template.children)if(template.partialScope){let partial2=template.partialScope();if(partial2===void 0){for(let child2 of yield template.children(partials,sync))yield visit3(child2,scope);return}if(seen.has(partial2.name))return;let partialScopeNames=new Set,partialScope=partial2.isolated?new DummyScope(partialScopeNames):scope.push(partialScopeNames);for(let name of partial2.scope)if(isString(name))partialScopeNames.add(name);else{let[alias2,argument]=name;partialScopeNames.add(alias2);let variables2=Array.from(extractVariables(argument));variables2.length&&partialScope.setAlias(alias2,variables2[0].segments)}for(let child2 of yield template.children(partials,sync))yield visit3(child2,partialScope),seen.add(partial2.name);partialScope.pop()}else{template.blockScope&&scope.push(new Set(template.blockScope()));for(let child2 of yield template.children(partials,sync))yield visit3(child2,scope);template.blockScope&&scope.pop()}}for(let template of templates)yield visit3(template,rootScope);return{variables:variables.asObject(),globals:globals.asObject(),locals:locals.asObject()}}function analyze(template,options2={}){let opts=Object.assign(Object.assign({},defaultStaticAnalysisOptions),options2);return toPromise(_analyze(template,opts.partials,!1))}function analyzeSync(template,options2={}){let opts=Object.assign(Object.assign({},defaultStaticAnalysisOptions),options2);return toValueSync(_analyze(template,opts.partials,!0))}var DummyScope=class{constructor(globals){this.stack=[{names:globals,aliases:new Map}]}has(name){for(let scope of this.stack)if(scope.names.has(name))return!0;return!1}push(scope){return this.stack.push({names:scope,aliases:new Map}),this}pop(){var _a4;return(_a4=this.stack.pop())===null||_a4===void 0?void 0:_a4.names}add(name){this.stack[0].names.add(name)}alias(variable){let root=variable.segments[0];if(!isString(root))return;let alias2=this.getAlias(root);if(alias2!==void 0)return new Variable([...alias2,...variable.segments.slice(1)],variable.location)}setAlias(from,to){this.stack[this.stack.length-1].aliases.set(from,to)}deleteAlias(name){this.stack[this.stack.length-1].aliases.delete(name)}getAlias(name){for(let scope of this.stack){if(scope.aliases.has(name))return scope.aliases.get(name);if(scope.names.has(name))return}}};function*extractVariables(value){isValueToken(value)?yield*extractValueTokenVariables(value):value instanceof Value&&(yield*extractFilteredValueVariables(value))}function*extractFilteredValueVariables(value){for(let token of value.initial.postfix)isValueToken(token)&&(yield*extractValueTokenVariables(token));for(let filter3 of value.filters)for(let arg of filter3.args)isKeyValuePair(arg)&&arg[1]?yield*extractValueTokenVariables(arg[1]):isValueToken(arg)&&(yield*extractValueTokenVariables(arg))}function*extractValueTokenVariables(token){isRangeToken(token)?(yield*extractValueTokenVariables(token.lhs),yield*extractValueTokenVariables(token.rhs)):isPropertyAccessToken(token)&&(yield extractPropertyAccessVariable(token))}function extractPropertyAccessVariable(token){let segments=[],file2=token.file,root=token.props[0];file2=file2||root.file,isQuotedToken(root)||isNumberToken(root)||isWordToken(root)?segments.push(root.content):isPropertyAccessToken(root)&&segments.push(...extractPropertyAccessVariable(root).segments);for(let prop of token.props.slice(1))file2=file2||prop.file,isQuotedToken(prop)||isNumberToken(prop)||isWordToken(prop)?segments.push(prop.content):isPropertyAccessToken(prop)&&segments.push(extractPropertyAccessVariable(prop));let[row,col]=token.getPosition();return new Variable(segments,{row,col,file:file2})}var RE_PROPERTY=/^[\u0080-\uFFFFa-zA-Z_][\u0080-\uFFFFa-zA-Z0-9_-]*$/;function segmentsString(segments,bracketedRoot=!1){let buf=[],root=segments[0];isString(root)&&(!bracketedRoot||root.match(RE_PROPERTY)?buf.push(`${root}`):buf.push(`['${root}']`));for(let segment of segments.slice(1))segment instanceof Variable?buf.push(`[${segmentsString(segment.segments)}]`):isString(segment)?segment.match(RE_PROPERTY)?buf.push(`.${segment}`):buf.push(`['${segment}']`):buf.push(`[${segment}]`);return buf.join("")}var LookupType;(function(LookupType2){LookupType2.Partials="partials",LookupType2.Layouts="layouts",LookupType2.Root="root"})(LookupType||(LookupType={}));var Loader=class{constructor(options2){if(this.options=options2,options2.relativeReference){let sep3=options2.fs.sep;assert(sep3,"`fs.sep` is required for relative reference");let rRelativePath=new RegExp(["."+sep3,".."+sep3,"./","../"].map(prefix=>escapeRegex(prefix)).join("|"));this.shouldLoadRelative=referencedFile=>rRelativePath.test(referencedFile)}else this.shouldLoadRelative=_referencedFile=>!1;this.contains=this.options.fs.contains||(()=>!0)}*lookup(file2,type,sync,currentFile){let{fs:fs88}=this.options,dirs=this.options[type];for(let filepath of this.candidates(file2,dirs,currentFile,type!==LookupType.Root))if(sync?fs88.existsSync(filepath):yield fs88.exists(filepath))return filepath;throw this.lookupError(file2,dirs)}*candidates(file2,dirs,currentFile,enforceRoot){let{fs:fs88,extname:extname3}=this.options,isAllowed=filepath=>{if(!enforceRoot)return!0;for(let dir of dirs)if(this.contains(dir,filepath))return!0;return!1};if(this.shouldLoadRelative(file2)&&currentFile){let referenced=fs88.resolve(this.dirname(currentFile),file2,extname3);isAllowed(referenced)&&(yield referenced)}for(let dir of dirs){let referenced=fs88.resolve(dir,file2,extname3);isAllowed(referenced)&&(yield referenced)}if(fs88.fallback!==void 0){let filepath=fs88.fallback(file2);filepath!==void 0&&isAllowed(filepath)&&(yield filepath)}}dirname(path122){let fs88=this.options.fs;return assert(fs88.dirname,"`fs.dirname` is required for relative reference"),fs88.dirname(path122)}lookupError(file2,roots){let err=new Error("ENOENT");return err.message=`ENOENT: Failed to lookup "${file2}" in "${roots}"`,err.code="ENOENT",err}},Parser=class{constructor(liquid){this.liquid=liquid,this.cache=this.liquid.options.cache,this.fs=this.liquid.options.fs,this.parseFile=this.cache?this._parseFileCached:this._parseFile,this.loader=new Loader(this.liquid.options),this.parseLimit=new Limiter("parse length",liquid.options.parseLimit)}parse(html,filepath){html=String(html),this.parseLimit.use(html.length);let tokens=new Tokenizer(html,this.liquid.options.operators,filepath).readTopLevelTokens(this.liquid.options);return this.parseTokens(tokens)}parseTokens(tokens){let token,templates=[],errors=[];for(;token=tokens.shift();)try{templates.push(this.parseToken(token,tokens))}catch(err){if(this.liquid.options.catchAllErrors)errors.push(err);else throw err}if(errors.length)throw new LiquidErrors(errors);return templates}parseToken(token,remainTokens){try{if(isTagToken(token)){let TagClass=this.liquid.tags[token.name];return assert(TagClass,`tag "${token.name}" not found`),new TagClass(token,remainTokens,this.liquid,this)}return isOutputToken(token)?new Output(token,this.liquid):new HTML(token)}catch(e){throw LiquidError.is(e)?e:new ParseError(e,token)}}parseStream(tokens){return new ParseStream(tokens,(token,tokens2)=>this.parseToken(token,tokens2))}*_parseFileCached(file2,sync,type=LookupType.Root,currentFile){let cache2=this.cache,key=this.loader.shouldLoadRelative(file2)?currentFile+","+file2:type+":"+file2,tpls=yield cache2.read(key);if(tpls)return tpls;let task=this._parseFile(file2,sync,type,currentFile),taskOrTpl=sync?yield task:toPromise(task);cache2.write(key,taskOrTpl);try{return yield taskOrTpl}catch(err){throw cache2.remove(key),err}}*_parseFile(file2,sync,type=LookupType.Root,currentFile){let filepath=yield this.loader.lookup(file2,type,sync,currentFile);return this.parse(sync?this.fs.readFileSync(filepath):yield this.fs.readFile(filepath),filepath)}},TokenKind;(function(TokenKind2){TokenKind2[TokenKind2.Number=1]="Number",TokenKind2[TokenKind2.Literal=2]="Literal",TokenKind2[TokenKind2.Tag=4]="Tag",TokenKind2[TokenKind2.Output=8]="Output",TokenKind2[TokenKind2.HTML=16]="HTML",TokenKind2[TokenKind2.Filter=32]="Filter",TokenKind2[TokenKind2.Hash=64]="Hash",TokenKind2[TokenKind2.PropertyAccess=128]="PropertyAccess",TokenKind2[TokenKind2.Word=256]="Word",TokenKind2[TokenKind2.Range=512]="Range",TokenKind2[TokenKind2.Quoted=1024]="Quoted",TokenKind2[TokenKind2.Operator=2048]="Operator",TokenKind2[TokenKind2.FilteredValue=4096]="FilteredValue",TokenKind2[TokenKind2.Delimited=12]="Delimited"})(TokenKind||(TokenKind={}));function isDelimitedToken(val){return!!(getKind(val)&TokenKind.Delimited)}function isOperatorToken(val){return getKind(val)===TokenKind.Operator}function isHTMLToken(val){return getKind(val)===TokenKind.HTML}function isOutputToken(val){return getKind(val)===TokenKind.Output}function isTagToken(val){return getKind(val)===TokenKind.Tag}function isQuotedToken(val){return getKind(val)===TokenKind.Quoted}function isNumberToken(val){return getKind(val)===TokenKind.Number}function isPropertyAccessToken(val){return getKind(val)===TokenKind.PropertyAccess}function isWordToken(val){return getKind(val)===TokenKind.Word}function isRangeToken(val){return getKind(val)===TokenKind.Range}function isValueToken(val){return(getKind(val)&1667)>0}function getKind(val){return val?val.kind:-1}var Context=class _Context{constructor(env={},opts=defaultOptions,renderOptions={},{memoryLimit,renderLimit}={}){var _a4,_b,_c,_d,_e2;this.scopes=[{}],this.registers={},this.breakCalled=!1,this.continueCalled=!1,this.sync=!!renderOptions.sync,this.opts=opts,this.globals=(_a4=renderOptions.globals)!==null&&_a4!==void 0?_a4:opts.globals,this.environments=isObject2(env)?env:Object(env),this.strictVariables=(_b=renderOptions.strictVariables)!==null&&_b!==void 0?_b:this.opts.strictVariables,this.ownPropertyOnly=(_c=renderOptions.ownPropertyOnly)!==null&&_c!==void 0?_c:opts.ownPropertyOnly,this.memoryLimit=memoryLimit??new Limiter("memory alloc",(_d=renderOptions.memoryLimit)!==null&&_d!==void 0?_d:opts.memoryLimit),this.renderLimit=renderLimit??new Limiter("template render",getPerformance().now()+((_e2=renderOptions.renderLimit)!==null&&_e2!==void 0?_e2:opts.renderLimit))}getRegister(key){return this.registers[key]=this.registers[key]||{}}setRegister(key,value){return this.registers[key]=value}saveRegister(...keys){return keys.map(key=>[key,this.getRegister(key)])}restoreRegister(keyValues){return keyValues.forEach(([key,value])=>this.setRegister(key,value))}getAll(){return[this.globals,this.environments,...this.scopes].reduce((ctx,val)=>__assign(ctx,val),{})}get(paths){return this.getSync(paths)}getSync(paths){return toValueSync(this._get(paths))}*_get(paths){let scope=this.findScope(paths[0]);return yield this._getFromScope(scope,paths)}getFromScope(scope,paths){return toValueSync(this._getFromScope(scope,paths))}*_getFromScope(scope,paths,strictVariables=this.strictVariables){isString(paths)&&(paths=paths.split("."));for(let i=0;i<paths.length;i++)if(scope=yield this.readProperty(scope,paths[i]),strictVariables&&isUndefined(scope))throw new InternalUndefinedVariableError(paths.slice(0,i+1).join("."));return scope}push(ctx){return this.scopes.push(ctx)}pop(){return this.scopes.pop()}bottom(){return this.scopes[0]}spawn(scope={}){return new _Context(scope,this.opts,{sync:this.sync,globals:this.globals,strictVariables:this.strictVariables},{renderLimit:this.renderLimit,memoryLimit:this.memoryLimit})}findScope(key){for(let i=this.scopes.length-1;i>=0;i--){let candidate=this.scopes[i];if(key in candidate)return candidate}return key in this.environments?this.environments:this.globals}readProperty(obj,key){if(obj=toLiquid(obj),key=toValue(key),isNil(obj))return obj;if(isArray(obj)&&key<0)return obj[obj.length+ +key];let value=readJSProperty(obj,key,this.ownPropertyOnly);return value===void 0&&obj instanceof Drop?obj.liquidMethodMissing(key,this):isFunction(value)?value.call(obj):key==="size"?readSize(obj):key==="first"?readFirst(obj):key==="last"?readLast(obj):value}};function readJSProperty(obj,key,ownPropertyOnly){if(!(ownPropertyOnly&&!hasOwnProperty.call(obj,key)&&!(obj instanceof Drop)))return obj[key]}function readFirst(obj){return isArray(obj)?obj[0]:obj.first}function readLast(obj){return isArray(obj)?obj[obj.length-1]:obj.last}function readSize(obj){if(hasOwnProperty.call(obj,"size")||obj.size!==void 0)return obj.size;if(isArray(obj)||isString(obj))return obj.length;if(typeof obj=="object")return Object.keys(obj).length}var BlockMode;(function(BlockMode2){BlockMode2[BlockMode2.OUTPUT=0]="OUTPUT",BlockMode2[BlockMode2.STORE=1]="STORE"})(BlockMode||(BlockMode={}));var abs=argumentsToNumber(Math.abs),at_least=argumentsToNumber(Math.max),at_most=argumentsToNumber(Math.min),ceil=argumentsToNumber(Math.ceil),divided_by=argumentsToNumber((dividend,divisor,integerArithmetic=!1)=>integerArithmetic?Math.floor(dividend/divisor):dividend/divisor),floor=argumentsToNumber(Math.floor),minus=argumentsToNumber((v2,arg)=>v2-arg),plus=argumentsToNumber((lhs,rhs)=>lhs+rhs),modulo=argumentsToNumber((v2,arg)=>v2%arg),times=argumentsToNumber((v2,arg)=>v2*arg);function round(v2,arg=0){v2=toNumber(v2),arg=toNumber(arg);let amp=Math.pow(10,arg);return Math.round(v2*amp)/amp}var mathFilters=Object.freeze({__proto__:null,abs,at_least,at_most,ceil,divided_by,floor,minus,plus,modulo,times,round}),url_decode=x2=>decodeURIComponent(stringify2(x2)).replace(/\+/g," "),url_encode=x2=>encodeURIComponent(stringify2(x2)).replace(/%20/g,"+"),cgi_escape=x2=>encodeURIComponent(stringify2(x2)).replace(/%20/g,"+").replace(/[!'()*]/g,c=>"%"+c.charCodeAt(0).toString(16).toUpperCase()),uri_escape=x2=>encodeURI(stringify2(x2)).replace(/%5B/g,"[").replace(/%5D/g,"]"),rSlugifyDefault=/[^\p{M}\p{L}\p{Nd}]+/ug,rSlugifyReplacers={raw:/\s+/g,default:rSlugifyDefault,pretty:/[^\p{M}\p{L}\p{Nd}._~!$&'()+,;=@]+/ug,ascii:/[^A-Za-z0-9]+/g,latin:rSlugifyDefault,none:null};function slugify(str,mode="default",cased=!1){str=stringify2(str);let replacer=rSlugifyReplacers[mode];return replacer&&(mode==="latin"&&(str=removeAccents(str)),str=str.replace(replacer,"-").replace(/^-|-$/g,"")),cased?str:str.toLowerCase()}function removeAccents(str){return str.replace(/[àáâãäå]/g,"a").replace(/[æ]/g,"ae").replace(/[ç]/g,"c").replace(/[èéêë]/g,"e").replace(/[ìíîï]/g,"i").replace(/[ð]/g,"d").replace(/[ñ]/g,"n").replace(/[òóôõöø]/g,"o").replace(/[ùúûü]/g,"u").replace(/[ýÿ]/g,"y").replace(/[ß]/g,"ss").replace(/[œ]/g,"oe").replace(/[þ]/g,"th").replace(/[ẞ]/g,"SS").replace(/[Œ]/g,"OE").replace(/[Þ]/g,"TH")}var urlFilters=Object.freeze({__proto__:null,url_decode,url_encode,cgi_escape,uri_escape,slugify}),join=argumentsToValue(function(v2,arg){let array2=toArray(v2),sep3=isNil(arg)?" ":stringify2(arg),complexity=array2.length*(1+sep3.length);return this.context.memoryLimit.use(complexity),array2.join(sep3)}),last$1=argumentsToValue(v2=>isArrayLike(v2)?last(v2):""),first=argumentsToValue(v2=>isArrayLike(v2)?v2[0]:""),reverse=argumentsToValue(function(v2){let array2=toArray(v2);return this.context.memoryLimit.use(array2.length),[...array2].reverse()});function*sort(arr,property){let values=[],array2=toArray(arr);this.context.memoryLimit.use(array2.length);for(let item of array2)values.push([item,property?yield this.context._getFromScope(item,stringify2(property).split("."),!1):item]);return values.sort((lhs,rhs)=>{let lvalue=lhs[1],rvalue=rhs[1];return lvalue<rvalue?-1:lvalue>rvalue?1:0}).map(tuple2=>tuple2[0])}function sort_natural(input,property){let propertyString=stringify2(property),compare=property===void 0?caseInsensitiveCompare:(lhs,rhs)=>caseInsensitiveCompare(lhs[propertyString],rhs[propertyString]),array2=toArray(input);return this.context.memoryLimit.use(array2.length),[...array2].sort(compare)}var size=v2=>v2&&v2.length||0;function*map(arr,property){let results=[],array2=toArray(arr);this.context.memoryLimit.use(array2.length);for(let item of array2)results.push(yield this.context._getFromScope(item,stringify2(property),!1));return results}function*sum2(arr,property){let sum3=0,array2=toArray(arr);for(let item of array2){let data=Number(property?yield this.context._getFromScope(item,stringify2(property),!1):item);sum3+=Number.isNaN(data)?0:data}return sum3}function compact(arr){let array2=toArray(arr);return this.context.memoryLimit.use(array2.length),array2.filter(x2=>!isNil(toValue(x2)))}function concat(v2,arg=[]){let lhs=toArray(v2),rhs=toArray(arg);return this.context.memoryLimit.use(lhs.length+rhs.length),lhs.concat(rhs)}function push(v2,arg){return concat.call(this,v2,[arg])}function unshift(v2,arg){let array2=toArray(v2);this.context.memoryLimit.use(array2.length);let clone2=[...array2];return clone2.unshift(arg),clone2}function pop(v2){let clone2=[...toArray(v2)];return clone2.pop(),clone2}function shift(v2){let array2=toArray(v2);this.context.memoryLimit.use(array2.length);let clone2=[...array2];return clone2.shift(),clone2}function slice(v2,begin,length=1){return v2=toValue(v2),isNil(v2)?[]:(isArray(v2)||(v2=stringify2(v2)),begin=begin<0?v2.length+begin:begin,this.context.memoryLimit.use(length),v2.slice(begin,begin+length))}function expectedMatcher(expected){return this.context.opts.jekyllWhere?v2=>EmptyDrop.is(expected)?equals(v2,expected):isArray(v2)?arrayIncludes(v2,expected):equals(v2,expected):expected===void 0?v2=>isTruthy(v2,this.context):v2=>equals(v2,expected)}function*filter2(include,arr,property,expected){let values=[];arr=toArray(arr),this.context.memoryLimit.use(arr.length);let token=new Tokenizer(stringify2(property)).readScopeValue();for(let item of arr)values.push(yield evalToken(token,this.context.spawn(item)));let matcher2=expectedMatcher.call(this,expected);return arr.filter((_2,i)=>matcher2(values[i])===include)}function*filter_exp(include,arr,itemName,exp){let filtered=[],keyTemplate=new Value(stringify2(exp),this.liquid),array2=toArray(arr);this.context.memoryLimit.use(array2.length);for(let item of array2){this.context.push({[itemName]:item});let value=yield keyTemplate.value(this.context);this.context.pop(),value===include&&filtered.push(item)}return filtered}function*where2(arr,property,expected){return yield*filter2.call(this,!0,arr,property,expected)}function*reject(arr,property,expected){return yield*filter2.call(this,!1,arr,property,expected)}function*where_exp(arr,itemName,exp){return yield*filter_exp.call(this,!0,arr,itemName,exp)}function*reject_exp(arr,itemName,exp){return yield*filter_exp.call(this,!1,arr,itemName,exp)}function*group_by(arr,property){let map3=new Map;arr=toEnumerable(arr);let token=new Tokenizer(stringify2(property)).readScopeValue();this.context.memoryLimit.use(arr.length);for(let item of arr){let key=yield evalToken(token,this.context.spawn(item));map3.has(key)||map3.set(key,[]),map3.get(key).push(item)}return[...map3.entries()].map(([name,items2])=>({name,items:items2}))}function*group_by_exp(arr,itemName,exp){let map3=new Map,keyTemplate=new Value(stringify2(exp),this.liquid);arr=toEnumerable(arr),this.context.memoryLimit.use(arr.length);for(let item of arr){this.context.push({[itemName]:item});let key=yield keyTemplate.value(this.context);this.context.pop(),map3.has(key)||map3.set(key,[]),map3.get(key).push(item)}return[...map3.entries()].map(([name,items2])=>({name,items:items2}))}function*search(arr,property,expected){let token=new Tokenizer(stringify2(property)).readScopeValue(),array2=toArray(arr),matcher2=expectedMatcher.call(this,expected);for(let index=0;index<array2.length;index++){let value=yield evalToken(token,this.context.spawn(array2[index]));if(matcher2(value))return[index,array2[index]]}}function*search_exp(arr,itemName,exp){let predicate=new Value(stringify2(exp),this.liquid),array2=toArray(arr);for(let index=0;index<array2.length;index++){this.context.push({[itemName]:array2[index]});let value=yield predicate.value(this.context);if(this.context.pop(),value)return[index,array2[index]]}}function*has(arr,property,expected){return!!(yield*search.call(this,arr,property,expected))}function*has_exp(arr,itemName,exp){return!!(yield*search_exp.call(this,arr,itemName,exp))}function*find_index(arr,property,expected){let result=yield*search.call(this,arr,property,expected);return result?result[0]:void 0}function*find_index_exp(arr,itemName,exp){let result=yield*search_exp.call(this,arr,itemName,exp);return result?result[0]:void 0}function*find(arr,property,expected){let result=yield*search.call(this,arr,property,expected);return result?result[1]:void 0}function*find_exp(arr,itemName,exp){let result=yield*search_exp.call(this,arr,itemName,exp);return result?result[1]:void 0}function uniq(arr){return arr=toArray(arr),this.context.memoryLimit.use(arr.length),[...new Set(arr)]}function sample(v2,count2=1){if(v2=toValue(v2),isNil(v2))return[];isArray(v2)||(v2=stringify2(v2)),this.context.memoryLimit.use(count2);let shuffled=[...v2].sort(()=>Math.random()-.5);return count2===1?shuffled[0]:shuffled.slice(0,count2)}var arrayFilters=Object.freeze({__proto__:null,join,last:last$1,first,reverse,sort,sort_natural,size,map,sum:sum2,compact,concat,push,unshift,pop,shift,slice,where:where2,reject,where_exp,reject_exp,group_by,group_by_exp,has,has_exp,find_index,find_index_exp,find,find_exp,uniq,sample});function date(v2,format3,timezoneOffset){var _a4,_b,_c;let size2=((_a4=v2?.length)!==null&&_a4!==void 0?_a4:0)+((_b=format3?.length)!==null&&_b!==void 0?_b:0)+((_c=timezoneOffset?.length)!==null&&_c!==void 0?_c:0);this.context.memoryLimit.use(size2);let date6=parseDate(v2,this.context.opts,timezoneOffset);return date6?(format3=toValue(format3),format3=isNil(format3)?this.context.opts.dateFormat:stringify2(format3),strftime(date6,format3)):v2}function date_to_xmlschema(v2){return date.call(this,v2,"%Y-%m-%dT%H:%M:%S%:z")}function date_to_rfc822(v2){return date.call(this,v2,"%a, %d %b %Y %H:%M:%S %z")}function date_to_string(v2,type,style){return stringify_date.call(this,v2,"%b",type,style)}function date_to_long_string(v2,type,style){return stringify_date.call(this,v2,"%B",type,style)}function stringify_date(v2,month_type,type,style){let date6=parseDate(v2,this.context.opts);if(!date6)return v2;if(type==="ordinal"){let d=date6.getDate();return style==="US"?strftime(date6,`${month_type} ${d}%q, %Y`):strftime(date6,`${d}%q ${month_type} %Y`)}return strftime(date6,`%d ${month_type} %Y`)}function parseDate(v2,opts,timezoneOffset){let date6,defaultTimezoneOffset=timezoneOffset??opts.timezoneOffset,locale=opts.locale;return v2=toValue(v2),v2==="now"||v2==="today"?date6=new LiquidDate(Date.now(),locale,defaultTimezoneOffset):isNumber(v2)?date6=new LiquidDate(v2*1e3,locale,defaultTimezoneOffset):isString(v2)?/^\d+$/.test(v2)?date6=new LiquidDate(+v2*1e3,locale,defaultTimezoneOffset):opts.preserveTimezones&&timezoneOffset===void 0?date6=LiquidDate.createDateFixedToTimezone(v2,locale):date6=new LiquidDate(v2,locale,defaultTimezoneOffset):date6=new LiquidDate(v2,locale,defaultTimezoneOffset),date6.valid()?date6:void 0}var dateFilters=Object.freeze({__proto__:null,date,date_to_xmlschema,date_to_rfc822,date_to_string,date_to_long_string}),rCJKWord=/[\u4E00-\u9FFF\uF900-\uFAFF\u3400-\u4DBF\u3040-\u309F\u30A0-\u30FF\uAC00-\uD7AF]/gu,rNonCJKWord=/[^\u4E00-\u9FFF\uF900-\uFAFF\u3400-\u4DBF\u3040-\u309F\u30A0-\u30FF\uAC00-\uD7AF\s]+/gu;function append(v2,arg){assert(arguments.length===2,"append expect 2 arguments");let lhs=stringify2(v2),rhs=stringify2(arg);return this.context.memoryLimit.use(lhs.length+rhs.length),lhs+rhs}function prepend(v2,arg){assert(arguments.length===2,"prepend expect 2 arguments");let lhs=stringify2(v2),rhs=stringify2(arg);return this.context.memoryLimit.use(lhs.length+rhs.length),rhs+lhs}function lstrip(v2,chars){let str=stringify2(v2);return this.context.memoryLimit.use(str.length),chars?(chars=escapeRegExp2(stringify2(chars)),str.replace(new RegExp(`^[${chars}]+`,"g"),"")):str.replace(/^\s+/,"")}function downcase(v2){let str=stringify2(v2);return this.context.memoryLimit.use(str.length),str.toLowerCase()}function upcase(v2){let str=stringify2(v2);return this.context.memoryLimit.use(str.length),stringify2(str).toUpperCase()}function remove(v2,arg){let str=stringify2(v2);return this.context.memoryLimit.use(str.length),str.split(stringify2(arg)).join("")}function remove_first(v2,l){let str=stringify2(v2);return this.context.memoryLimit.use(str.length),str.replace(stringify2(l),"")}function remove_last(v2,l){let str=stringify2(v2);this.context.memoryLimit.use(str.length);let pattern=stringify2(l),index=str.lastIndexOf(pattern);return index===-1?str:str.substring(0,index)+str.substring(index+pattern.length)}function rstrip(str,chars){return str=stringify2(str),this.context.memoryLimit.use(str.length),chars?(chars=escapeRegExp2(stringify2(chars)),str.replace(new RegExp(`[${chars}]+$`,"g"),"")):str.replace(/\s+$/,"")}function split2(v2,arg){let str=stringify2(v2);this.context.memoryLimit.use(str.length);let arr=str.split(stringify2(arg));for(;arr.length&&arr[arr.length-1]==="";)arr.pop();return arr}function strip(v2,chars){let str=stringify2(v2);return this.context.memoryLimit.use(str.length),chars?(chars=escapeRegExp2(stringify2(chars)),str.replace(new RegExp(`^[${chars}]+`,"g"),"").replace(new RegExp(`[${chars}]+$`,"g"),"")):str.trim()}function strip_newlines(v2){let str=stringify2(v2);return this.context.memoryLimit.use(str.length),str.replace(/\r?\n/gm,"")}function capitalize(str){return str=stringify2(str),this.context.memoryLimit.use(str.length),str.charAt(0).toUpperCase()+str.slice(1).toLowerCase()}function replace2(v2,pattern,replacement){let str=stringify2(v2);return this.context.memoryLimit.use(str.length),str.split(stringify2(pattern)).join(replacement)}function replace_first(v2,arg1,arg2){let str=stringify2(v2);return this.context.memoryLimit.use(str.length),str.replace(stringify2(arg1),arg2)}function replace_last(v2,arg1,arg2){let str=stringify2(v2);this.context.memoryLimit.use(str.length);let pattern=stringify2(arg1),index=str.lastIndexOf(pattern);if(index===-1)return str;let replacement=stringify2(arg2);return str.substring(0,index)+replacement+str.substring(index+pattern.length)}function truncate(v2,l=50,o="..."){let str=stringify2(v2);return this.context.memoryLimit.use(str.length),str.length<=l?v2:str.substring(0,l-o.length)+o}function truncatewords(v2,words2=15,o="..."){let str=stringify2(v2);this.context.memoryLimit.use(str.length);let arr=str.split(/\s+/);words2<=0&&(words2=1);let ret=arr.slice(0,words2).join(" ");return arr.length>=words2&&(ret+=o),ret}function normalize_whitespace(v2){let str=stringify2(v2);return this.context.memoryLimit.use(str.length),str.replace(/\s+/g," ")}function number_of_words(input,mode){let str=stringify2(input);if(this.context.memoryLimit.use(str.length),input=str.trim(),!input)return 0;switch(mode){case"cjk":return(input.match(rCJKWord)||[]).length+(input.match(rNonCJKWord)||[]).length;case"auto":return rCJKWord.test(input)?input.match(rCJKWord).length+(input.match(rNonCJKWord)||[]).length:input.split(/\s+/).length;default:return input.split(/\s+/).length}}function array_to_sentence_string(array2,connector="and"){switch(this.context.memoryLimit.use(array2.length),array2.length){case 0:return"";case 1:return array2[0];case 2:return`${array2[0]} ${connector} ${array2[1]}`;default:return`${array2.slice(0,-1).join(", ")}, ${connector} ${array2[array2.length-1]}`}}var stringFilters=Object.freeze({__proto__:null,append,prepend,lstrip,downcase,upcase,remove,remove_first,remove_last,rstrip,split:split2,strip,strip_newlines,capitalize,replace:replace2,replace_first,replace_last,truncate,truncatewords,normalize_whitespace,number_of_words,array_to_sentence_string});function base64Encode(str){return Buffer.from(str,"utf8").toString("base64")}function base64Decode(str){return Buffer.from(str,"base64").toString("utf8")}function base64_encode(value){let str=stringify2(value);return this.context.memoryLimit.use(str.length),base64Encode(str)}function base64_decode(value){let str=stringify2(value);return this.context.memoryLimit.use(str.length),base64Decode(str)}var base64Filters=Object.freeze({__proto__:null,base64_encode,base64_decode}),filters=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},htmlFilters),mathFilters),urlFilters),arrayFilters),dateFilters),stringFilters),base64Filters),misc),AssignTag=class extends Tag{constructor(token,remainTokens,liquid){super(token,remainTokens,liquid),this.identifier=this.tokenizer.readIdentifier(),this.key=this.identifier.content,this.tokenizer.assert(this.key,"expected variable name"),this.tokenizer.skipBlank(),this.tokenizer.assert(this.tokenizer.peek()==="=",'expected "="'),this.tokenizer.advance(),this.value=new Value(this.tokenizer.readFilteredValue(),this.liquid)}*render(ctx){ctx.bottom()[this.key]=yield this.value.value(ctx,this.liquid.options.lenientIf)}*arguments(){yield this.value}*localScope(){yield this.identifier}},MODIFIERS=["offset","limit","reversed"],ForTag=class extends Tag{constructor(token,remainTokens,liquid,parser){super(token,remainTokens,liquid);let variable=this.tokenizer.readIdentifier(),inStr=this.tokenizer.readIdentifier(),collection=this.tokenizer.readValue();if(!variable.size()||inStr.content!=="in"||!collection)throw new Error(`illegal tag: ${token.getText()}`);this.variable=variable.content,this.collection=collection,this.hash=new Hash(this.tokenizer,liquid.options.keyValueSeparator),this.templates=[],this.elseTemplates=[];let p,stream=parser.parseStream(remainTokens).on("start",()=>p=this.templates).on("tag:else",tag=>{assertEmpty(tag.args),p=this.elseTemplates}).on("tag:endfor",tag=>{assertEmpty(tag.args),stream.stop()}).on("template",tpl=>p.push(tpl)).on("end",()=>{throw new Error(`tag ${token.getText()} not closed`)});stream.start()}*render(ctx,emitter){let r=this.liquid.renderer,collection=toEnumerable(yield evalToken(this.collection,ctx));if(!collection.length){yield r.renderTemplates(this.elseTemplates,ctx,emitter);return}let continueKey="continue-"+this.variable+"-"+this.collection.getText();ctx.push({continue:ctx.getRegister(continueKey)});let hash2=yield this.hash.render(ctx);ctx.pop(),collection=(this.liquid.options.orderedFilterParameters?Object.keys(hash2).filter(x2=>MODIFIERS.includes(x2)):MODIFIERS.filter(x2=>hash2[x2]!==void 0)).reduce((collection2,modifier)=>modifier==="offset"?offset(collection2,hash2.offset):modifier==="limit"?limit(collection2,hash2.limit):reversed(collection2),collection),ctx.setRegister(continueKey,(hash2.offset||0)+collection.length);let scope={forloop:new ForloopDrop(collection.length,this.collection.getText(),this.variable)};ctx.push(scope);for(let item of collection){if(scope[this.variable]=item,ctx.continueCalled=ctx.breakCalled=!1,yield r.renderTemplates(this.templates,ctx,emitter),ctx.breakCalled)break;scope.forloop.next()}ctx.continueCalled=ctx.breakCalled=!1,ctx.pop()}*children(){let templates=this.templates.slice();return this.elseTemplates&&templates.push(...this.elseTemplates),templates}*arguments(){yield this.collection;for(let v2 of Object.values(this.hash.hash))isValueToken(v2)&&(yield v2)}blockScope(){return[this.variable,"forloop"]}};function reversed(arr){return[...arr].reverse()}function offset(arr,count2){return arr.slice(count2)}function limit(arr,count2){return arr.slice(0,count2)}var CaptureTag=class extends Tag{constructor(tagToken,remainTokens,liquid,parser){for(super(tagToken,remainTokens,liquid),this.templates=[],this.identifier=this.readVariable(),this.variable=this.identifier.content;remainTokens.length;){let token=remainTokens.shift();if(isTagToken(token)&&token.name==="endcapture")return;this.templates.push(parser.parseToken(token,remainTokens))}throw new Error(`tag ${tagToken.getText()} not closed`)}readVariable(){let ident=this.tokenizer.readIdentifier();if(ident.content||(ident=this.tokenizer.readQuoted(),ident))return ident;throw this.tokenizer.error("invalid capture name")}*render(ctx){let html=yield this.liquid.renderer.renderTemplates(this.templates,ctx);ctx.bottom()[this.variable]=html}*children(){return this.templates}*localScope(){yield this.identifier}},CaseTag=class extends Tag{constructor(tagToken,remainTokens,liquid,parser){super(tagToken,remainTokens,liquid),this.branches=[],this.elseTemplates=[],this.value=new Value(this.tokenizer.readFilteredValue(),this.liquid),this.elseTemplates=[];let p=[],elseCount=0,stream=parser.parseStream(remainTokens).on("tag:when",token=>{if(elseCount>0)return;p=[];let values=[];for(;!token.tokenizer.end();)values.push(token.tokenizer.readValueOrThrow()),token.tokenizer.skipBlank(),token.tokenizer.peek()===","?token.tokenizer.readTo(","):token.tokenizer.readTo("or");this.branches.push({values,templates:p})}).on("tag:else",()=>{elseCount++,p=this.elseTemplates}).on("tag:endcase",()=>stream.stop()).on("template",tpl=>{(p!==this.elseTemplates||elseCount===1)&&p.push(tpl)}).on("end",()=>{throw new Error(`tag ${tagToken.getText()} not closed`)});stream.start()}*render(ctx,emitter){let r=this.liquid.renderer,target=toValue(yield this.value.value(ctx,ctx.opts.lenientIf)),branchHit=!1;for(let branch of this.branches)for(let valueToken of branch.values){let value=yield evalToken(valueToken,ctx,ctx.opts.lenientIf);if(equals(target,value)){yield r.renderTemplates(branch.templates,ctx,emitter),branchHit=!0;break}}branchHit||(yield r.renderTemplates(this.elseTemplates,ctx,emitter))}*arguments(){yield this.value,yield*this.branches.flatMap(b=>b.values)}*children(){let templates=this.branches.flatMap(b=>b.templates);return this.elseTemplates&&templates.push(...this.elseTemplates),templates}},CommentTag=class extends Tag{constructor(tagToken,remainTokens,liquid){for(super(tagToken,remainTokens,liquid);remainTokens.length;){let token=remainTokens.shift();if(isTagToken(token)&&token.name==="endcomment")return}throw new Error(`tag ${tagToken.getText()} not closed`)}render(){}},RenderTag=class extends Tag{constructor(token,remainTokens,liquid,parser){super(token,remainTokens,liquid);let tokenizer=this.tokenizer;for(this.file=parseFilePath(tokenizer,this.liquid,parser),this.currentFile=token.file;!tokenizer.end();){tokenizer.skipBlank();let begin=tokenizer.p,keyword=tokenizer.readIdentifier();if((keyword.content==="with"||keyword.content==="for")&&(tokenizer.skipBlank(),tokenizer.peek()!==":")){let value=tokenizer.readValue();if(value){let beforeAs=tokenizer.p,asStr=tokenizer.readIdentifier(),alias2;asStr.content==="as"?alias2=tokenizer.readIdentifier():tokenizer.p=beforeAs,this[keyword.content]={value,alias:alias2&&alias2.content},tokenizer.skipBlank(),tokenizer.peek()===","&&tokenizer.advance();continue}}tokenizer.p=begin;break}this.hash=new Hash(tokenizer,liquid.options.keyValueSeparator)}*render(ctx,emitter){let{liquid,hash:hash2}=this,filepath=yield renderFilePath(this.file,ctx,liquid);assert(filepath,()=>`illegal file path "${filepath}"`);let childCtx=ctx.spawn(),scope=childCtx.bottom();if(__assign(scope,yield hash2.render(ctx)),this.with){let{value,alias:alias2}=this.with;scope[alias2||filepath]=yield evalToken(value,ctx)}if(this.for){let{value,alias:alias2}=this.for,collection=toEnumerable(yield evalToken(value,ctx));scope.forloop=new ForloopDrop(collection.length,value.getText(),alias2);for(let item of collection){scope[alias2]=item;let templates=yield liquid._parsePartialFile(filepath,childCtx.sync,this.currentFile);yield liquid.renderer.renderTemplates(templates,childCtx,emitter),scope.forloop.next()}}else{let templates=yield liquid._parsePartialFile(filepath,childCtx.sync,this.currentFile);yield liquid.renderer.renderTemplates(templates,childCtx,emitter)}}*children(partials,sync){return partials&&isString(this.file)?yield this.liquid._parsePartialFile(this.file,sync,this.currentFile):[]}partialScope(){if(isString(this.file)){let names2=Object.keys(this.hash.hash);if(this.with){let{value,alias:alias2}=this.with;isString(alias2)?names2.push([alias2,value]):isString(this.file)&&names2.push([this.file,value])}if(this.for){let{value,alias:alias2}=this.for;isString(alias2)?names2.push([alias2,value]):isString(this.file)&&names2.push([this.file,value])}return{name:this.file,isolated:!0,scope:names2}}}*arguments(){for(let v2 of Object.values(this.hash.hash))isValueToken(v2)&&(yield v2);if(this.with){let{value}=this.with;isValueToken(value)&&(yield value)}if(this.for){let{value}=this.for;isValueToken(value)&&(yield value)}}};function parseFilePath(tokenizer,liquid,parser){if(liquid.options.dynamicPartials){let file2=tokenizer.readValue();if(tokenizer.assert(file2,"illegal file path"),file2.getText()==="none")return;if(isQuotedToken(file2)){let templates2=parser.parse(evalQuotedToken(file2));return optimize(templates2)}return file2}let tokens=[...tokenizer.readFileNameTemplate(liquid.options)],templates=optimize(parser.parseTokens(tokens));return templates==="none"?void 0:templates}function optimize(templates){return templates.length===1&&isHTMLToken(templates[0].token)?templates[0].token.getContent():templates}function*renderFilePath(file2,ctx,liquid){return typeof file2=="string"?file2:Array.isArray(file2)?liquid.renderer.renderTemplates(file2,ctx):yield evalToken(file2,ctx)}var IncludeTag=class extends Tag{constructor(token,remainTokens,liquid,parser){super(token,remainTokens,liquid);let{tokenizer}=token;this.file=parseFilePath(tokenizer,this.liquid,parser),this.currentFile=token.file;let begin=tokenizer.p;tokenizer.readIdentifier().content==="with"?(tokenizer.skipBlank(),tokenizer.peek()!==":"?this.withVar=tokenizer.readValue():tokenizer.p=begin):tokenizer.p=begin,this.hash=new Hash(tokenizer,liquid.options.jekyllInclude||liquid.options.keyValueSeparator)}*render(ctx,emitter){let{liquid,hash:hash2,withVar}=this,{renderer}=liquid,filepath=yield renderFilePath(this.file,ctx,liquid);assert(filepath,()=>`illegal file path "${filepath}"`);let saved=ctx.saveRegister("blocks","blockMode");ctx.setRegister("blocks",{}),ctx.setRegister("blockMode",BlockMode.OUTPUT);let scope=yield hash2.render(ctx);withVar&&(scope[filepath]=yield evalToken(withVar,ctx));let templates=yield liquid._parsePartialFile(filepath,ctx.sync,this.currentFile);ctx.push(ctx.opts.jekyllInclude?{include:scope}:scope),yield renderer.renderTemplates(templates,ctx,emitter),ctx.pop(),ctx.restoreRegister(saved)}*children(partials,sync){return partials&&isString(this.file)?yield this.liquid._parsePartialFile(this.file,sync,this.currentFile):[]}partialScope(){if(isString(this.file)){let names2;return this.liquid.options.jekyllInclude?names2=["include"]:(names2=Object.keys(this.hash.hash),this.withVar&&names2.push([this.file,this.withVar])),{name:this.file,isolated:!1,scope:names2}}}*arguments(){yield*Object.values(this.hash.hash).filter(isValueToken),isValueToken(this.file)&&(yield this.file),isValueToken(this.withVar)&&(yield this.withVar)}},DecrementTag=class extends Tag{constructor(token,remainTokens,liquid){super(token,remainTokens,liquid),this.identifier=this.tokenizer.readIdentifier(),this.variable=this.identifier.content}render(context,emitter){let scope=context.environments;isNumber(scope[this.variable])||(scope[this.variable]=0),emitter.write(stringify2(--scope[this.variable]))}*localScope(){yield this.identifier}},CycleTag=class extends Tag{constructor(token,remainTokens,liquid){super(token,remainTokens,liquid),this.candidates=[];let group=this.tokenizer.readValue();for(this.tokenizer.skipBlank(),group&&(this.tokenizer.peek()===":"?(this.group=group,this.tokenizer.advance()):this.candidates.push(group));!this.tokenizer.end();){let value=this.tokenizer.readValue();value&&this.candidates.push(value),this.tokenizer.readTo(",")}this.tokenizer.assert(this.candidates.length,()=>`empty candidates: "${token.getText()}"`)}*render(ctx,emitter){let fingerprint2=`cycle:${yield evalToken(this.group,ctx)}:`+this.candidates.join(","),groups=ctx.getRegister("cycle"),idx=groups[fingerprint2];idx===void 0&&(idx=groups[fingerprint2]=0);let candidate=this.candidates[idx];return idx=(idx+1)%this.candidates.length,groups[fingerprint2]=idx,yield evalToken(candidate,ctx)}*arguments(){yield*this.candidates,this.group&&(yield this.group)}},IfTag=class extends Tag{constructor(tagToken,remainTokens,liquid,parser){super(tagToken,remainTokens,liquid),this.branches=[];let p=[];parser.parseStream(remainTokens).on("start",()=>this.branches.push({value:new Value(tagToken.tokenizer.readFilteredValue(),this.liquid),templates:p=[]})).on("tag:elsif",token=>{assert(!this.elseTemplates,"unexpected elsif after else"),this.branches.push({value:new Value(token.tokenizer.readFilteredValue(),this.liquid),templates:p=[]})}).on("tag:else",tag=>{assertEmpty(tag.args),assert(!this.elseTemplates,"duplicated else"),p=this.elseTemplates=[]}).on("tag:endif",function(tag){assertEmpty(tag.args),this.stop()}).on("template",tpl=>p.push(tpl)).on("end",()=>{throw new Error(`tag ${tagToken.getText()} not closed`)}).start()}*render(ctx,emitter){let r=this.liquid.renderer;for(let{value,templates}of this.branches){let v2=yield value.value(ctx,ctx.opts.lenientIf);if(isTruthy(v2,ctx)){yield r.renderTemplates(templates,ctx,emitter);return}}yield r.renderTemplates(this.elseTemplates||[],ctx,emitter)}*children(){let templates=this.branches.flatMap(b=>b.templates);return this.elseTemplates&&templates.push(...this.elseTemplates),templates}arguments(){return this.branches.map(b=>b.value)}},IncrementTag=class extends Tag{constructor(token,remainTokens,liquid){super(token,remainTokens,liquid),this.identifier=this.tokenizer.readIdentifier(),this.variable=this.identifier.content}render(context,emitter){let scope=context.environments;isNumber(scope[this.variable])||(scope[this.variable]=0);let val=scope[this.variable];scope[this.variable]++,emitter.write(stringify2(val))}*localScope(){yield this.identifier}},LayoutTag=class extends Tag{constructor(token,remainTokens,liquid,parser){super(token,remainTokens,liquid),this.file=parseFilePath(this.tokenizer,this.liquid,parser),this.currentFile=token.file,this.args=new Hash(this.tokenizer,liquid.options.keyValueSeparator),this.templates=parser.parseTokens(remainTokens)}*render(ctx,emitter){let{liquid,args,file:file2}=this,{renderer}=liquid;if(file2===void 0){ctx.setRegister("blockMode",BlockMode.OUTPUT),yield renderer.renderTemplates(this.templates,ctx,emitter);return}let filepath=yield renderFilePath(this.file,ctx,liquid);assert(filepath,()=>`illegal file path "${filepath}"`);let templates=yield liquid._parseLayoutFile(filepath,ctx.sync,this.currentFile);ctx.setRegister("blockMode",BlockMode.STORE);let html=yield renderer.renderTemplates(this.templates,ctx),blocks=ctx.getRegister("blocks");blocks[""]===void 0&&(blocks[""]=(parent,emitter2)=>emitter2.write(html)),ctx.setRegister("blockMode",BlockMode.OUTPUT),ctx.push(yield args.render(ctx)),yield renderer.renderTemplates(templates,ctx,emitter),ctx.pop()}*children(partials){let templates=this.templates.slice();return partials&&isString(this.file)&&templates.push(...yield this.liquid._parsePartialFile(this.file,!0,this.currentFile)),templates}*arguments(){for(let v2 of Object.values(this.args.hash))isValueToken(v2)&&(yield v2);isValueToken(this.file)&&(yield this.file)}partialScope(){if(isString(this.file))return{name:this.file,isolated:!1,scope:Object.keys(this.args.hash)}}},BlockTag=class extends Tag{constructor(token,remainTokens,liquid,parser){super(token,remainTokens,liquid),this.templates=[];let match2=/\w+/.exec(token.args);for(this.block=match2?match2[0]:"";remainTokens.length;){let token2=remainTokens.shift();if(isTagToken(token2)&&token2.name==="endblock")return;let template=parser.parseToken(token2,remainTokens);this.templates.push(template)}throw new Error(`tag ${token.getText()} not closed`)}*render(ctx,emitter){let blockRender=this.getBlockRender(ctx);ctx.getRegister("blockMode")===BlockMode.STORE?ctx.getRegister("blocks")[this.block]=blockRender:yield blockRender(new BlockDrop,emitter)}getBlockRender(ctx){let{liquid,templates}=this,renderChild=ctx.getRegister("blocks")[this.block],renderCurrent=function*(superBlock,emitter){ctx.push({block:superBlock}),yield liquid.renderer.renderTemplates(templates,ctx,emitter),ctx.pop()};return renderChild?(superBlock,emitter)=>renderChild(new BlockDrop(emitter2=>renderCurrent(superBlock,emitter2)),emitter):renderCurrent}*children(){return this.templates}blockScope(){return["block"]}},RawTag=class extends Tag{constructor(tagToken,remainTokens,liquid){for(super(tagToken,remainTokens,liquid),this.tokens=[];remainTokens.length;){let token=remainTokens.shift();if(isTagToken(token)&&token.name==="endraw")return;this.tokens.push(token)}throw new Error(`tag ${tagToken.getText()} not closed`)}render(){return this.tokens.map(token=>token.getText()).join("")}},TablerowloopDrop=class extends ForloopDrop{constructor(length,cols,collection,variable){super(length,collection,variable),this.length=length,this.cols=cols}row(){return Math.floor(this.i/this.cols)+1}col0(){return this.i%this.cols}col(){return this.col0()+1}col_first(){return this.col0()===0}col_last(){return this.col()===this.cols}},TablerowTag=class extends Tag{constructor(tagToken,remainTokens,liquid,parser){super(tagToken,remainTokens,liquid);let variable=this.tokenizer.readIdentifier();this.tokenizer.skipBlank();let predicate=this.tokenizer.readIdentifier(),collectionToken=this.tokenizer.readValue();if(predicate.content!=="in"||!collectionToken)throw new Error(`illegal tag: ${tagToken.getText()}`);this.variable=variable.content,this.collection=collectionToken,this.args=new Hash(this.tokenizer,liquid.options.keyValueSeparator),this.templates=[];let p,stream=parser.parseStream(remainTokens).on("start",()=>p=this.templates).on("tag:endtablerow",()=>stream.stop()).on("template",tpl=>p.push(tpl)).on("end",()=>{throw new Error(`tag ${tagToken.getText()} not closed`)});stream.start()}*render(ctx,emitter){let collection=toEnumerable(yield evalToken(this.collection,ctx)),args=yield this.args.render(ctx),offset2=args.offset||0,limit2=args.limit===void 0?collection.length:args.limit;collection=collection.slice(offset2,offset2+limit2);let cols=args.cols||collection.length,r=this.liquid.renderer,tablerowloop=new TablerowloopDrop(collection.length,cols,this.collection.getText(),this.variable),scope={tablerowloop};ctx.push(scope);for(let idx=0;idx<collection.length;idx++,tablerowloop.next())scope[this.variable]=collection[idx],tablerowloop.col0()===0&&(tablerowloop.row()!==1&&emitter.write("</tr>"),emitter.write(`<tr class="row${tablerowloop.row()}">`)),emitter.write(`<td class="col${tablerowloop.col()}">`),yield r.renderTemplates(this.templates,ctx,emitter),emitter.write("</td>");collection.length&&emitter.write("</tr>"),ctx.pop()}*children(){return this.templates}*arguments(){yield this.collection;for(let v2 of Object.values(this.args.hash))isValueToken(v2)&&(yield v2)}blockScope(){return[this.variable,"tablerowloop"]}},UnlessTag=class extends Tag{constructor(tagToken,remainTokens,liquid,parser){super(tagToken,remainTokens,liquid),this.branches=[],this.elseTemplates=[];let p=[],elseCount=0;parser.parseStream(remainTokens).on("start",()=>this.branches.push({value:new Value(tagToken.tokenizer.readFilteredValue(),this.liquid),test:isFalsy,templates:p=[]})).on("tag:elsif",token=>{if(elseCount>0){p=[];return}this.branches.push({value:new Value(token.tokenizer.readFilteredValue(),this.liquid),test:isTruthy,templates:p=[]})}).on("tag:else",()=>{elseCount++,p=this.elseTemplates}).on("tag:endunless",function(){this.stop()}).on("template",tpl=>{(p!==this.elseTemplates||elseCount===1)&&p.push(tpl)}).on("end",()=>{throw new Error(`tag ${tagToken.getText()} not closed`)}).start()}*render(ctx,emitter){let r=this.liquid.renderer;for(let{value,test,templates}of this.branches){let v2=yield value.value(ctx,ctx.opts.lenientIf);if(test(v2,ctx)){yield r.renderTemplates(templates,ctx,emitter);return}}yield r.renderTemplates(this.elseTemplates,ctx,emitter)}*children(){let children=this.branches.flatMap(b=>b.templates);return this.elseTemplates&&children.push(...this.elseTemplates),children}arguments(){return this.branches.map(b=>b.value)}},BreakTag=class extends Tag{render(ctx,_emitter){ctx.breakCalled=!0}},ContinueTag=class extends Tag{render(ctx,_emitter){ctx.continueCalled=!0}},EchoTag=class extends Tag{constructor(token,remainTokens,liquid){super(token,remainTokens,liquid),this.tokenizer.skipBlank(),this.tokenizer.end()||(this.value=new Value(this.tokenizer.readFilteredValue(),this.liquid))}*render(ctx,emitter){if(!this.value)return;let val=yield this.value.value(ctx,!1);emitter.write(val)}*arguments(){this.value&&(yield this.value)}},LiquidTag=class extends Tag{constructor(token,remainTokens,liquid,parser){super(token,remainTokens,liquid);let tokens=this.tokenizer.readLiquidTagTokens(this.liquid.options);this.templates=parser.parseTokens(tokens)}*render(ctx,emitter){yield this.liquid.renderer.renderTemplates(this.templates,ctx,emitter)}*children(){return this.templates}},InlineCommentTag=class extends Tag{constructor(tagToken,remainTokens,liquid){if(super(tagToken,remainTokens,liquid),tagToken.args.search(/\n\s*[^#\s]/g)!==-1)throw new Error("every line of an inline comment must start with a '#' character")}render(){}},tags={assign:AssignTag,for:ForTag,capture:CaptureTag,case:CaseTag,comment:CommentTag,include:IncludeTag,render:RenderTag,decrement:DecrementTag,increment:IncrementTag,cycle:CycleTag,if:IfTag,layout:LayoutTag,block:BlockTag,raw:RawTag,tablerow:TablerowTag,unless:UnlessTag,break:BreakTag,continue:ContinueTag,echo:EchoTag,liquid:LiquidTag,"#":InlineCommentTag},Liquid=class _Liquid{constructor(opts={}){this.renderer=new Render,this.filters={},this.tags={},this.options=normalize2(opts),this.parser=new Parser(this),forOwn(tags,(conf,name)=>this.registerTag(name,conf)),forOwn(filters,(handler,name)=>this.registerFilter(name,handler))}parse(html,filepath){return new Parser(this).parse(html,filepath)}_render(tpl,scope,renderOptions){let ctx=scope instanceof Context?scope:new Context(scope,this.options,renderOptions);return this.renderer.renderTemplates(tpl,ctx)}render(tpl,scope,renderOptions){return __awaiter(this,void 0,void 0,function*(){return toPromise(this._render(tpl,scope,Object.assign(Object.assign({},renderOptions),{sync:!1})))})}renderSync(tpl,scope,renderOptions){return toValueSync(this._render(tpl,scope,Object.assign(Object.assign({},renderOptions),{sync:!0})))}renderToNodeStream(tpl,scope,renderOptions={}){let ctx=new Context(scope,this.options,renderOptions);return this.renderer.renderTemplatesToNodeStream(tpl,ctx)}_parseAndRender(html,scope,renderOptions){let tpl=this.parse(html);return this._render(tpl,scope,renderOptions)}parseAndRender(html,scope,renderOptions){return __awaiter(this,void 0,void 0,function*(){return toPromise(this._parseAndRender(html,scope,Object.assign(Object.assign({},renderOptions),{sync:!1})))})}parseAndRenderSync(html,scope,renderOptions){return toValueSync(this._parseAndRender(html,scope,Object.assign(Object.assign({},renderOptions),{sync:!0})))}_parsePartialFile(file2,sync,currentFile){return new Parser(this).parseFile(file2,sync,LookupType.Partials,currentFile)}_parseLayoutFile(file2,sync,currentFile){return new Parser(this).parseFile(file2,sync,LookupType.Layouts,currentFile)}_parseFile(file2,sync,lookupType,currentFile){return new Parser(this).parseFile(file2,sync,lookupType,currentFile)}parseFile(file2,lookupType){return __awaiter(this,void 0,void 0,function*(){return toPromise(new Parser(this).parseFile(file2,!1,lookupType))})}parseFileSync(file2,lookupType){return toValueSync(new Parser(this).parseFile(file2,!0,lookupType))}*_renderFile(file2,ctx,renderFileOptions){let templates=yield this._parseFile(file2,renderFileOptions.sync,renderFileOptions.lookupType);return yield this._render(templates,ctx,renderFileOptions)}renderFile(file2,ctx,renderFileOptions){return __awaiter(this,void 0,void 0,function*(){return toPromise(this._renderFile(file2,ctx,Object.assign(Object.assign({},renderFileOptions),{sync:!1})))})}renderFileSync(file2,ctx,renderFileOptions){return toValueSync(this._renderFile(file2,ctx,Object.assign(Object.assign({},renderFileOptions),{sync:!0})))}renderFileToNodeStream(file2,scope,renderOptions){return __awaiter(this,void 0,void 0,function*(){let templates=yield this.parseFile(file2);return this.renderToNodeStream(templates,scope,renderOptions)})}_evalValue(str,scope){let value=new Value(str,this),ctx=scope instanceof Context?scope:new Context(scope,this.options);return value.value(ctx)}evalValue(str,scope){return __awaiter(this,void 0,void 0,function*(){return toPromise(this._evalValue(str,scope))})}evalValueSync(str,scope){return toValueSync(this._evalValue(str,scope))}registerFilter(name,filter3){this.filters[name]=filter3}registerTag(name,tag){this.tags[name]=isFunction(tag)?tag:createTagClass(tag)}plugin(plugin){return plugin.call(this,_Liquid)}express(){let self=this,firstCall=!0;return function(filePath,ctx,callback){if(firstCall){firstCall=!1;let dirs=normalizeDirectoryList(this.root);self.options.root.unshift(...dirs),self.options.layouts.unshift(...dirs),self.options.partials.unshift(...dirs)}self.renderFile(filePath,ctx).then(html=>callback(null,html),callback)}}analyze(template,options2={}){return __awaiter(this,void 0,void 0,function*(){return analyze(template,options2)})}analyzeSync(template,options2={}){return analyzeSync(template,options2)}parseAndAnalyze(html,filename,options2={}){return __awaiter(this,void 0,void 0,function*(){return analyze(this.parse(html,filename),options2)})}parseAndAnalyzeSync(html,filename,options2={}){return analyzeSync(this.parse(html,filename),options2)}variables(template,options2={}){return __awaiter(this,void 0,void 0,function*(){let analysis=yield analyze(isString(template)?this.parse(template):template,options2);return Object.keys(analysis.variables)})}variablesSync(template,options2={}){let analysis=analyzeSync(isString(template)?this.parse(template):template,options2);return Object.keys(analysis.variables)}fullVariables(template,options2={}){return __awaiter(this,void 0,void 0,function*(){let analysis=yield analyze(isString(template)?this.parse(template):template,options2);return Array.from(new Set(Object.values(analysis.variables).flatMap(a=>a.map(v2=>String(v2)))))})}fullVariablesSync(template,options2={}){let analysis=analyzeSync(isString(template)?this.parse(template):template,options2);return Array.from(new Set(Object.values(analysis.variables).flatMap(a=>a.map(v2=>String(v2)))))}variableSegments(template,options2={}){return __awaiter(this,void 0,void 0,function*(){let analysis=yield analyze(isString(template)?this.parse(template):template,options2);return Array.from(strictUniq(Object.values(analysis.variables).flatMap(a=>a.map(v2=>v2.toArray()))))})}variableSegmentsSync(template,options2={}){let analysis=analyzeSync(isString(template)?this.parse(template):template,options2);return Array.from(strictUniq(Object.values(analysis.variables).flatMap(a=>a.map(v2=>v2.toArray()))))}globalVariables(template,options2={}){return __awaiter(this,void 0,void 0,function*(){let analysis=yield analyze(isString(template)?this.parse(template):template,options2);return Object.keys(analysis.globals)})}globalVariablesSync(template,options2={}){let analysis=analyzeSync(isString(template)?this.parse(template):template,options2);return Object.keys(analysis.globals)}globalFullVariables(template,options2={}){return __awaiter(this,void 0,void 0,function*(){let analysis=yield analyze(isString(template)?this.parse(template):template,options2);return Array.from(new Set(Object.values(analysis.globals).flatMap(a=>a.map(v2=>String(v2)))))})}globalFullVariablesSync(template,options2={}){let analysis=analyzeSync(isString(template)?this.parse(template):template,options2);return Array.from(new Set(Object.values(analysis.globals).flatMap(a=>a.map(v2=>String(v2)))))}globalVariableSegments(template,options2={}){return __awaiter(this,void 0,void 0,function*(){let analysis=yield analyze(isString(template)?this.parse(template):template,options2);return Array.from(strictUniq(Object.values(analysis.globals).flatMap(a=>a.map(v2=>v2.toArray()))))})}globalVariableSegmentsSync(template,options2={}){let analysis=analyzeSync(isString(template)?this.parse(template):template,options2);return Array.from(strictUniq(Object.values(analysis.globals).flatMap(a=>a.map(v2=>v2.toArray()))))}};import{NotFoundError as NotFoundError3,PluginError as PluginError6}from"@sous-io/sous-plugin-api";var DEFAULT_PURPOSE="template",CONFIG_EXPRESSION_PURPOSE="config-expression";function tagAllowed(tag,purpose){return tag.purposes?tag.purposes.includes(purpose):purpose!==CONFIG_EXPRESSION_PURPOSE}function filterAllowed(filter3,purpose){return filter3.purposes?filter3.purposes.includes(purpose):!0}function createLiquidEngines(deps){return{create:(options2={})=>buildEngine(deps,options2),available(purpose=DEFAULT_PURPOSE){return{tags:deps.entities.list("liquid-tag").filter(tag=>tagAllowed(tag,purpose)).map(tag=>tag.id),filters:deps.entities.list("liquid-filter").filter(filter3=>filterAllowed(filter3,purpose)).map(filter3=>filter3.id)}}}}function buildEngine(deps,options2){let purpose=options2.purpose??DEFAULT_PURPOSE,root=rootOf(options2.root,deps.project),liquidOptions={extname:"",strictVariables:!1,strictFilters:!1,...options2.liquid,...root===void 0?{}:{root},...options2.fs===void 0?{}:{fs:options2.fs}},engine=withBooleans(new Liquid(liquidOptions),options2.booleanNames??declaredBooleans2(deps.services)),ctx=Object.freeze({project:deps.project,env:deps.env,services:deps.services,entities:deps.entities,purpose,secretNames:new Set(options2.secretNames??declaredSecrets(deps.services)),data:Object.freeze({...options2.data})}),filters2=pick(deps.entities.describe("liquid-filter"),options2.only?.filters,entry=>filterAllowed(entry,purpose),"Liquid filter");for(let record2 of filters2)engine.registerFilter(record2.id,make(record2,"filter",()=>record2.entry.filter(ctx)));let tags2=pick(deps.entities.describe("liquid-tag"),options2.only?.tags,entry=>tagAllowed(entry,purpose),"Liquid tag");for(let record2 of tags2)engine.registerTag(record2.id,make(record2,"tag",()=>record2.entry.tag(ctx)));return engine}function rootOf(root,project){return root!==void 0?typeof root=="string"?root:[...root]:project?[project.root]:void 0}function liquidValues(scope,booleanNames2){let out;for(let name of booleanNames2){let value=scope[name];(value==="true"||value==="false")&&(out??={...scope},out[name]=value==="true")}return out??scope}function withBooleans(engine,names2){let booleanNames2=new Set(names2);if(booleanNames2.size===0)return engine;let convert=scope=>scope!==null&&typeof scope=="object"&&Object.getPrototypeOf(scope)===Object.prototype?liquidValues(scope,booleanNames2):scope,internal=engine;for(let method of["_render","_renderFile","_evalValue"]){let original=internal[method].bind(engine);internal[method]=(first2,scope,...rest)=>original(first2,convert(scope),...rest)}return engine}function declaredBooleans2(services){try{return services.has("variables.booleans")?services.get("variables.booleans").declared():[]}catch{return[]}}function declaredSecrets(services){return services.has("variables.secrets")?services.get("variables.secrets").declared():[]}function pick(records,only,allowed,thing){return only===void 0?records.filter(record2=>allowed(record2.entry)):only.map(id=>{let record2=records.find(candidate=>candidate.id===id);if(!record2)throw new NotFoundError3(thing,id);return record2})}function make(record2,what,factory2){try{return factory2()}catch(error51){throw new PluginError6(record2.plugin,`The Liquid ${what} "${record2.id}" from ${record2.plugin} could not be made.`,{cause:error51,details:[error51 instanceof Error?error51.message:String(error51)]})}}import{jsonSchema as jsonSchema8}from"@sous-io/sous-plugin-api";var PURPOSES={type:"array",items:{type:"string"}};function extensionSchema(factory2){let base=jsonSchema8({type:"object",properties:{id:{type:"string"},description:{type:"string"},purposes:PURPOSES,[factory2]:{}},required:["id",factory2]});return{"~standard":{...base["~standard"],validate(value){let result=base["~standard"].validate(value);return result instanceof Promise||result.issues?result:typeof result.value[factory2]!="function"?{issues:[{message:"Expected a function.",path:[factory2]}]}:result}}}}var liquidTagSchema=extensionSchema("tag"),liquidFilterSchema=extensionSchema("filter");var package_default7={name:"@sous-io/sous-plugin-liquid",version:"1.1.6",description:"A configured LiquidJS engine, and the Liquid tags and filters plugins add.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-host":"workspace:*",liquidjs:"^10.25.0"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME6="@sous-io/sous-plugin-liquid",liquidPlugin=definePlugin7({name:PLUGIN_NAME6,version:package_default7.version,description:"A configured LiquidJS engine, and the Liquid tags and filters plugins add.",dependsOn:{"@sous-io/sous-plugin-host":`^${package_default7.version}`},register(sous){sous.entities.define("liquid-tag",liquidTagSchema,{description:"A Liquid tag, as written in {% name %}."}),sous.entities.define("liquid-filter",liquidFilterSchema,{description:"A Liquid filter, as written after |. Config expressions see it too."}),sous.services.add("liquid.engine",(_config,ctx)=>createLiquidEngines(ctx),{lifetime:"factory"})}});init_src5();import{definePlugin as definePlugin9,jsonSchema as jsonSchema9}from"@sous-io/sous-plugin-api";import fs16 from"node:fs";import nodePath from"node:path";import{ConfigError as ConfigError21,formatIssuePath as formatIssuePath2}from"@sous-io/sous-plugin-api";function formatPath2(path122){return path122.length===0?"(root)":formatIssuePath2(path122)}var ExpressionError=class extends ConfigError21{file;path;constructor(file2,path122,problem,options2={}){let printed=typeof path122=="string"?path122:formatPath2(path122);super(`${printed} ${problem}`,{...options2,details:[`in ${file2}`,...options2.details??[]]}),this.file=file2,this.path=printed}};var QUALIFIED=/^\$(expr|if|elseif)(?::(.*))?$/s,FILE_KEY="$file";function parseReservedKey(key){if(key==="$else")return{kind:"else",key};if(key===FILE_KEY)return{kind:"file",key};let match2=QUALIFIED.exec(key);if(!match2)return;let kind=match2[1],qualifier=match2[2];return kind==="expr"?{kind,key,language:qualifier}:{kind,key,name:qualifier}}function isReservedKey(key){return parseReservedKey(key)!==void 0}function isPlainObject3(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isExpressionObject(value){return isPlainObject3(value)&&Object.keys(value).some(isReservedKey)}function hasExpressions(value){return Array.isArray(value)?value.some(hasExpressions):isPlainObject3(value)?isExpressionObject(value)||Object.values(value).some(hasExpressions):!1}function compareBytes(a,b){return Buffer.compare(Buffer.from(a,"utf8"),Buffer.from(b,"utf8"))}function chainOrder(keys){return[...keys].sort((a,b)=>a.name===void 0||b.name===void 0?a.name===b.name?0:a.name===void 0?-1:1:compareBytes(a.name,b.name))}import{ConfigError as ConfigError22}from"@sous-io/sous-plugin-api";var LIQUID_LANGUAGE="liquid",LEFT="\0<",RIGHT=">\0",analyzerEngine;function analyzer(){return analyzerEngine??=new Liquid({outputDelimiterLeft:LEFT,outputDelimiterRight:RIGHT}),analyzerEngine}function createLiquidLanguage(){return{id:LIQUID_LANGUAGE,description:"Liquid expressions, as in a {% if %} condition (the default).",runsCode:!1,variables(expression,ctx){return guard(expression,ctx,()=>analyzer().globalVariablesSync(analyzer().parse(`${LEFT}${expression}${RIGHT}`)))},evaluate(expression,scope,ctx){return evaluateLiquid(expression,scope,ctx)}}}function evaluateLiquid(expression,scope,ctx){let engine=engineFor(ctx),used=guard(expression,ctx,()=>new Tokenizer(expression).readFilteredValue().filters.map(filter3=>filter3.name)),missing=[...new Set(used.filter(name=>!(name in engine.filters)))];if(missing.length>0)return{unknown:{variables:[],filters:missing}};let value=guard(expression,ctx,()=>engine.evalValueSync(expression,{...scope.vars,host:scope.host,harness:scope.harness,env:scope.env}));return{value:toValue(value)}}function renderLiquidTemplate(text,scope,ctx){let engine=engineFor(ctx);try{return engine.parseAndRenderSync(text,{...scope})}catch(error51){if(error51 instanceof ConfigError22)throw error51;let reason=error51 instanceof Error?error51.message:String(error51);throw new ExpressionError(ctx.file,ctx.path,`reads a template that failed to render: ${reason}`,{cause:error51})}}function engineFor(ctx){let entities=ctx.entities??emptyEntities,cached2=engines.get(entities);if(cached2)return cached2;let engine=makeEngine(ctx,entities);return engines.set(entities,engine),engine}var engines=new WeakMap;function makeEngine(ctx,entities){let services=ctx.services??noServices;return createLiquidEngines({project:ctx.project,env:ctx.env??{},services,entities}).create({purpose:CONFIG_EXPRESSION_PURPOSE,secretNames:[],liquid:{strictFilters:!0}})}function guard(expression,ctx,run){try{return run()}catch(error51){if(error51 instanceof ConfigError22)throw error51;let reason=error51 instanceof Error?error51.message:String(error51);throw new ExpressionError(ctx.file,ctx.path,`holds the Liquid expression ${JSON.stringify(expression)}, which failed: ${reason}`,{cause:error51})}}var emptyEntities={get:()=>{},list:()=>[],has:()=>!1,describe:()=>[],kinds:()=>[]},noServices={get(name){throw new ConfigError22(`The service "${name}" is not available to config expressions.`)},has:()=>!1};function parseExpressionObject(object3,path122,file2){if(Object.hasOwn(object3,FILE_KEY))return parseFileObject(object3,path122,file2);let exprKeys=[],ifs=[],elseifs=[],hasElse=!1,stray=[];for(let key of Object.keys(object3)){let reserved=parseReservedKey(key);reserved?reserved.kind==="expr"?exprKeys.push(reserved):reserved.kind==="else"?hasElse=!0:reserved.kind==="file"||(reserved.kind==="if"?ifs:elseifs).push(reserved):stray.push(key)}let reservedKeys=Object.keys(object3).filter(key=>!stray.includes(key));if(stray.length>0)throw new ExpressionError(file2,path122,`mixes the expression key ${quote(reservedKeys[0])} with ${list(stray)}, which ${stray.length===1?"is":"are"} not one.`,{details:["An expression object holds only $expr, $if, $elseif and $else keys (with their qualifiers)."]});for(let key of[...ifs,...elseifs])if(key.name==="")throw new ExpressionError(file2,[...path122,key.key],"has an empty qualifier. Write a name after the colon, or leave the colon out.");if(exprKeys.length>0){if(exprKeys.length>1)throw new ExpressionError(file2,path122,`holds ${list(exprKeys.map(key2=>key2.key))}; write one.`);if(ifs.length>0||elseifs.length>0||hasElse)throw new ExpressionError(file2,path122,`holds ${quote(exprKeys[0].key)} together with ${list(reservedKeys.filter(key2=>key2!==exprKeys[0].key))}.`,{details:["$expr computes one value; $if, $elseif and $else choose between values. Use one or the other."]});let key=exprKeys[0];return{kind:"value",expression:expressionAt(object3[key.key],key.language,[...path122,key.key],file2)}}let keys=[...chainOrder(ifs),...chainOrder(elseifs)],branches=[];return keys.forEach((key,index)=>{let last2=index===keys.length-1;branches.push(...parseBranches(object3[key.key],[...path122,key.key],{last:last2,hasElse},file2))}),{kind:"chain",branches,otherwise:hasElse?{value:object3.$else,path:[...path122,"$else"]}:void 0}}function parseFileObject(object3,path122,file2){let others=Object.keys(object3).filter(key=>key!==FILE_KEY);if(others.length>0)throw new ExpressionError(file2,path122,`mixes "$file" with ${list(others)}.`,{details:["An object holding $file stands in for the file's value, so it holds no other key. Wrap it in $if to choose it conditionally."]});let value=object3[FILE_KEY];if(typeof value!="string"||value.trim()==="")throw new ExpressionError(file2,[...path122,FILE_KEY],`is ${describe3(value??null)}. $file takes the path of a file, as a string.`);return{kind:"file",file:value,path:[...path122,FILE_KEY]}}function parseBranches(value,path122,place,file2){if(typeof value=="string")return[{condition:expressionAt(value,void 0,path122,file2),then:void 0}];if(Array.isArray(value))return value.map((item,index)=>{let itemPath=[...path122,index],branch2=typeof item=="string"?{condition:expressionAt(item,void 0,itemPath,file2),then:void 0}:parseBlock(item,itemPath,file2);return branch2.condition===void 0&&checkFallback(itemPath,index===value.length-1,place,file2),branch2});let branch=parseBlock(value,path122,file2);if(branch.condition===void 0)throw new ExpressionError(file2,path122,"has no expr. A branch block needs one; only an array item may leave it out, as a fallback.");return[branch]}function checkFallback(path122,lastItem,place,file2){if(place.hasElse)throw new ExpressionError(file2,path122,"is a fallback (an item with no expr), and the chain also has an $else. Keep one of them.");if(!lastItem||!place.last)throw new ExpressionError(file2,path122,"is a fallback (an item with no expr), which is only allowed as the last item of the last key in the chain.")}function parseBlock(value,path122,file2){if(!isPlainObject3(value))throw new ExpressionError(file2,path122,`is ${describe3(value)}. A branch is a string, a block with expr and then, or an array of those.`);let exprKeys=[],thenKeys=[],unknown2=[];for(let key of Object.keys(value))/^\$?expr(:.*)?$/s.test(key)?exprKeys.push(key):key==="then"||key==="$then"?thenKeys.push(key):unknown2.push(key);if(unknown2.length>0)throw new ExpressionError(file2,path122,`holds ${list(unknown2)}. A branch block holds only expr (or $expr) and then (or $then).`);if(exprKeys.length>1)throw new ExpressionError(file2,path122,`holds both ${list(exprKeys,"and")}. Write one.`);if(thenKeys.length>1)throw new ExpressionError(file2,path122,'holds both "then" and "$then". Write one.');if(exprKeys.length===0&&thenKeys.length===0)throw new ExpressionError(file2,path122,"is an empty branch block. Give it an expr, a then, or both.");let exprKey=exprKeys[0],thenKey=thenKeys[0],language=exprKey===void 0?void 0:qualifierOf(exprKey);return{condition:exprKey===void 0?void 0:expressionAt(value[exprKey],language,[...path122,exprKey],file2),then:thenKey===void 0?void 0:{value:value[thenKey],path:[...path122,thenKey]}}}function qualifierOf(key){let colon=key.indexOf(":");return colon===-1?void 0:key.slice(colon+1)}function expressionAt(value,language,path122,file2){if(language==="")throw new ExpressionError(file2,path122,"has an empty language qualifier. Name the language after the colon, or leave the colon out.");if(typeof value!="string")throw new ExpressionError(file2,path122,`is ${describe3(value)}. An expression is a string.`);return{language,source:value,path:path122}}function describe3(value){return value===null?"null":Array.isArray(value)?"an array":typeof value=="object"?"an object":`a ${typeof value} (${JSON.stringify(value)})`}function quote(key){return JSON.stringify(key)}function list(keys,join4="and"){let quoted=keys.map(quote);return quoted.length<=1?quoted.join(""):`${quoted.slice(0,-1).join(", ")} ${join4} ${quoted.at(-1)}`}var BUILT_IN_NAMES=new Set(["host","harness","env"]);function createEvaluator(deps){let byFile=new Map,stale=!1;return{evaluateLayer(data,options2){stale&&(byFile.clear(),stale=!1);let run=new LayerRun(data,options2,deps),value=run.evaluate(),harness=harnessOf(options2.config);return byFile.set(`${harness}\0${options2.file}`,{harness,expressions:run.expressions,unsettled:run.unsettled,files:[...run.files]}),{value,expressions:run.expressions,pending:run.unsettled.length>0}},isExpressionObject,hasExpressions,evaluations(file2,harness=""){return file2!==void 0?[...byFile.get(`${harness}\0${file2}`)?.expressions??[]]:[...byFile.values()].filter(entry=>entry.harness===harness).flatMap(entry=>entry.expressions)},unsettled(){return[...byFile.values()].flatMap(entry=>entry.unsettled)},files(){return[...new Set([...byFile.values()].flatMap(entry=>entry.files))]},languages(){return deps.entities.list("expression-language").map(language=>language.id)},settle(){let open2=this.unsettled();if(stale=!0,open2.length>0)throw unsettledError(open2)}}}function unsettledError(open2){let[first2,...rest]=open2;return new ExpressionError(first2.file,first2.path,`${describeUnknown(first2.unknown)}.`,{details:[...first2.harness===""?[]:[`This is in the config build for the harness "${first2.harness}".`],...rest.map(entry=>`${entry.path} ${describeUnknown(entry.unknown)} (in ${entry.file}${entry.harness===""?"":`, in the build for the harness "${entry.harness}"`})`)]})}function describeUnknown(unknown2){let parts=[];if(unknown2.variables.length>0){let one=unknown2.variables.length===1;parts.push(`reads ${names(unknown2.variables)}, which ${one?"is":"are"} not set anywhere in the config`)}if(unknown2.filters.length>0){let one=unknown2.filters.length===1;parts.push(`uses the Liquid filter${one?"":"s"} ${names(unknown2.filters)}, which no plugin adds`)}return parts.join(", and ")}function names(list2){return list2.join(", ")}function harnessOf(config2){return config2.harness?.id??""}function isTruthy2(value){return value!==!1&&value!==void 0&&value!==null}var LayerRun=class{constructor(data,options2,deps){this.data=data;this.options=options2;this.deps=deps;this.config=options2.config,this.file=options2.file,this.entities=builderEntities(options2.config),this.lookup={get:path122=>options2.config.atPath(path122).get()}}expressions=[];unsettled=[];files=new Set;reading=[];config;file;entities;lookup;reads;unknown;evaluate(){return this.walk(this.data,[],{})}walk(value,path122,levelVars){if(Array.isArray(value)){let out2=[];return value.forEach((item,index)=>{let result=this.walk(item,[...path122,index],levelVars);result!==void 0&&out2.push(result)}),out2}if(!isPlainObject3(value))return value;if(isExpressionObject(value))return this.expressionObject(value,path122,levelVars);let inner=isScopeLevel(path122)?{...levelVars,...this.ownVarsOf(value,path122)}:levelVars,out={};for(let[key,child2]of Object.entries(value)){let result=this.walk(child2,[...path122,key],inner);result!==void 0&&(out[key]=result)}return out}ownVarsOf(object3,path122){if(path122.length===0&&this.options.ownVars)return this.options.ownVars;let block=object3._vars;return isPlainObject3(block)?Object.fromEntries(Object.entries(block).filter(entry=>typeof entry[1]=="string")):{}}expressionObject(object3,path122,levelVars){let outermost=this.reads===void 0;outermost&&(this.reads={},this.unknown=void 0);try{let plan2=parseExpressionObject(object3,path122,this.file),value=this.evaluatePlan(plan2,path122,levelVars);return outermost&&this.expressions.push({path:formatPath2(path122),written:object3,value,reads:this.reads,...this.unknown?{unknown:this.unknown}:{}}),value}finally{outermost&&(this.reads=void 0,this.unknown=void 0)}}evaluatePlan(plan2,path122,levelVars){if(plan2.kind==="file")return this.fileValue(plan2,path122,levelVars);if(plan2.kind==="value"){let outcome=this.run(plan2.expression,path122,levelVars);return"unknown"in outcome?this.pending(path122,outcome.unknown):toJson(outcome.value)}for(let branch of plan2.branches){if(branch.condition===void 0)return this.chosen(branch.then,path122,levelVars);let outcome=this.run(branch.condition,path122,levelVars);if("unknown"in outcome)return this.pending(path122,outcome.unknown);if(isTruthy2(outcome.value))return branch.then?this.chosen(branch.then,path122,levelVars):!0}return plan2.otherwise?this.chosen(plan2.otherwise,path122,levelVars):void 0}chosen(written,path122,levelVars){return this.walk(written.value,path122,levelVars)}pending(path122,unknown2){this.unknown=unknown2,this.unsettled.push({file:this.file,harness:harnessOf(this.config),path:formatPath2(path122),unknown:unknown2})}run(expression,path122,levelVars){let language=this.language(expression),ctx={project:this.deps.project,file:this.file,path:formatPath2(expression.path),env:this.config.env,entities:this.entities,services:this.deps.services},variables=[...new Set(language.variables(expression.source,ctx))].filter(name=>!BUILT_IN_NAMES.has(name));this.checkForbidden(variables,path122);let vars=variables.length>0?this.scope(path122,levelVars):levelVars,missing=[];for(let name of variables){let known=Object.hasOwn(vars,name);this.reads[name]=known?vars[name]:void 0,known||missing.push(name)}return missing.length>0?{unknown:{variables:missing,filters:[]}}:language.evaluate(expression.source,{...this.builtIns(),vars:this.typed(vars)},ctx)}typed(vars){let names2=new Set(this.config.entities("variable-source").flatMap(source=>source.booleans?.({project:this.deps.project,env:this.config.env,config:this.lookup})??[]));return names2.size===0?vars:liquidValues(vars,names2)}builtIns(){return{host:{platform:this.deps.platform??process.platform},env:this.config.env,harness:{id:harnessOf(this.config)}}}fileValue(plan2,path122,levelVars){let written=plan2.file,vars;if(written.includes("${")){if(!this.deps.services.has("variables.resolver"))throw new ExpressionError(this.file,plan2.path,`holds the path ${JSON.stringify(written)}, whose variables cannot be filled in without sous-plugin-variables.`);let resolver=this.deps.services.get("variables.resolver");vars=this.scope(path122,levelVars);let missing=resolver.unresolved(written,vars);for(let name2 of resolver.references(written))this.reads[name2]=vars[name2];if(missing.length>0)return this.pending(path122,{variables:missing,filters:[]});written=resolver.substitute(written,vars)}let absolute=nodePath.resolve(this.baseDir(),written);if(this.reading.includes(absolute))throw new ExpressionError(this.file,plan2.path,`reads ${absolute}, which is already being read: a $file cannot read itself.`);this.files.add(absolute);let text;try{text=fs16.readFileSync(absolute,"utf8")}catch(error51){throw new ExpressionError(this.file,plan2.path,`names the file ${absolute}, which could not be read: ${error51.message}`,{cause:error51})}let name=nodePath.basename(absolute);this.reading.push(absolute);try{name.includes(".tpl.")&&(text=renderLiquidTemplate(text,{...this.typed(vars??this.scope(path122,levelVars)),...this.builtIns()},{project:this.deps.project,file:this.file,path:formatPath2(plan2.path),env:this.config.env,entities:this.entities,services:this.deps.services}));let value=parseByExtension(text,name,this.deps.services,reason=>new ExpressionError(this.file,plan2.path,`names the file ${absolute}, which ${reason}`));return escapeVariables(value)}finally{this.reading.pop()}}baseDir(){return this.options.baseDir??this.deps.project?.root??process.cwd()}language(expression){let id=expression.language??LIQUID_LANGUAGE,languages=this.config.entities("expression-language"),language=languages.find(entry=>entry.id===id);if(!language){let known=languages.map(entry=>entry.id).join(", ")||"none";throw new ExpressionError(this.file,expression.path,`uses the expression language "${id}", which sous does not know. Known languages: ${known}.`)}if(this.options.fromRecipe&&language.runsCode){let allowed=languages.filter(entry=>!entry.runsCode).map(entry=>entry.id).join(", ")||"none";throw new ExpressionError(this.file,expression.path,`uses the expression language "${id}", which runs code. A recipe's config file may only use languages that do not (${allowed}).`)}return language}scope(path122,levelVars){if(!this.deps.services.has("variables.resolver"))return levelVars;let resolver=this.deps.services.get("variables.resolver"),level=path122[0]==="compilation"?"compilation":"root";return resolver.scopeIn(this.config,{level,extra:levelVars,...this.options.scopeKey===void 0?{}:{scopeKey:this.options.scopeKey}})}checkForbidden(variables,path122){let top=path122[0];if(!(variables.length===0||typeof top!="string"))for(let source of this.config.entities("variable-source")){if(!source.forbiddenUnder?.includes(top))continue;let given=source.variables({project:this.deps.project,env:this.config.env,config:this.lookup}),read=variables.find(name=>Object.hasOwn(given,name));if(read!==void 0)throw new ExpressionError(this.file,path122,forbiddenProblem(read,source))}}};function forbiddenProblem(name,source){let under=source.forbiddenUnder.map(key=>`"${key}"`).join(" or ");return source.description==="recipe answers"?`reads ${name}, which is an answer to a recipe. An expression that decides which recipes are subscribed or pinned (anything under ${under}) cannot read recipe answers.`:`reads ${name}, which comes from ${source.description}. An expression under ${under} cannot read ${source.description}.`}function parseByExtension(text,name,services,fail){let extension=nodePath.extname(name).toLowerCase();if(![".json",".jsonc",".yaml",".yml"].includes(extension))return text;try{if(services.has("formats.manifests"))return toJson(services.get("formats.manifests").parseText(text,name))??null;if(extension===".json")return toJson(JSON.parse(text))??null}catch(error51){throw fail(`could not be parsed: ${error51.message}`)}throw fail("is YAML or JSONC, which needs sous-plugin-formats to read.")}function escapeVariables(value){return typeof value=="string"?value.split("${").join("$${"):Array.isArray(value)?value.map(escapeVariables):isPlainObject3(value)?Object.fromEntries(Object.entries(value).map(([key,item])=>[key,escapeVariables(item)])):value}function isScopeLevel(path122){return path122.length===0?!0:path122[0]!=="compilation"?!1:path122.length===1||path122.length===3&&path122[1]==="targets"&&typeof path122[2]=="number"||path122.length===5&&path122[1]==="targets"&&typeof path122[2]=="number"&&path122[3]==="outputs"&&typeof path122[4]=="number"}function toJson(value){if(value==null||typeof value=="string"||typeof value=="boolean")return value;if(typeof value=="number")return Number.isFinite(value)?value:null;if(Array.isArray(value))return value.map(toJson).filter(item=>item!==void 0);if(isPlainObject3(value)&&Object.getPrototypeOf(value)===Object.prototype){let out={};for(let[key,item]of Object.entries(value)){let json3=toJson(item);json3!==void 0&&(out[key]=json3)}return out}if(!(typeof value=="function"||typeof value=="symbol"))return String(value)}function builderEntities(config2){return{get:(kind,id)=>config2.entity(kind,id),list:kind=>config2.entities(kind),has:(kind,id)=>config2.entity(kind,id)!==void 0,describe:kind=>config2.entities(kind).map(entry=>({kind,id:entry.id,entry,plugin:"a plugin"})),kinds:()=>[]}}var package_default9={name:"@sous-io/sous-plugin-expressions",version:"1.1.6",description:"Config expressions (S5) and the expression languages plugins add.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-liquid":"workspace:*","@sous-io/sous-plugin-variables":"workspace:*",liquidjs:"^10.25.0"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*","@sous-io/sous-plugin-host":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME8="@sous-io/sous-plugin-expressions",expressionsPlugin=definePlugin9({name:PLUGIN_NAME8,version:package_default9.version,description:"Config expressions and the expression languages plugins add.",dependsOn:{"@sous-io/sous-plugin-liquid":`^${package_default9.version}`,"@sous-io/sous-plugin-variables":`^${package_default9.version}`},register(sous){sous.entities.define("expression-language",jsonSchema9({type:"object",properties:{id:{type:"string"},description:{type:"string"},runsCode:{type:"boolean"}},required:["id","variables","evaluate"]}),{description:"A language config expressions are written in, named after $expr: or expr:."}),sous.entities.add("expression-language",createLiquidLanguage());let evaluator=createEvaluator({services:sous.services,entities:sous.entities,get project(){return sous.project}});sous.services.add("expressions.evaluator",()=>evaluator,{lifetime:"singleton"}),sous.on("config.built",()=>evaluator.settle())}});import fs19 from"node:fs";import{ConfigError as ConfigError24,definePlugin as definePlugin10}from"@sous-io/sous-plugin-api";import fs17 from"node:fs";import path22 from"node:path";var CONTRIBUTOR_PREFIX="confd/",MANAGED_NAME=/^5\d\d-/;function isManagedName(name){return MANAGED_NAME.test(name)}function contributorId(name){return`${CONTRIBUTOR_PREFIX}${name}`}function listConfdFiles(confDir,loader,compare){if(confDir===void 0)return[];let names2;try{names2=fs17.readdirSync(confDir)}catch{return[]}let files=[];for(let name of[...names2].sort(compare)){let format3=loader.formatOf(name),full=path22.join(confDir,name);format3===void 0||!isFile4(full)||files.push({name,path:full,format:format3,contributor:contributorId(name),managed:isManagedName(name)})}return files}function duplicateBaseNames(names2){let byBase=new Map;for(let name of names2){let dot=name.lastIndexOf("."),base=dot<=0?name:name.slice(0,dot);byBase.set(base,[...byBase.get(base)??[],name])}return[...byBase.values()].filter(group=>group.length>1)}var ConfdFilesImpl=class{constructor(confDir,loader,compare){this.confDir=confDir;this.loader=loader;this.compare=compare}directory(){return this.confDir}list(){return listConfdFiles(this.confDir,this.loader,this.compare)}};function isFile4(file2){try{return fs17.statSync(file2).isFile()}catch{return!1}}init_src();import fs18 from"node:fs";import path23 from"node:path";import{ConfigError as ConfigError23}from"@sous-io/sous-plugin-api";var MANAGED_FILE_COMMENT="This file is managed by sous. Sous edits these files by key; you may edit them too, and your comments, key order and formatting are kept.",FORMAT_NOTE=["It is JSON with comments (.jsonc): line comments, block comments and trailing","commas are all allowed here."],DESCRIPTIONS={"500-repos.jsonc":["It records the repositories this project trusts. The 'sous repo add' and","'sous repo remove' commands write the entries under 'repos'."],"510-subscriptions.jsonc":["It records what this project subscribes to. The 'sous subscription add' and","'sous subscription remove' commands write the entries under 'subscriptions'."]};function wrap2(text,width=78){let lines3=[],current="";for(let word of text.split(/\s+/))current.length===0?current=word:`${current} ${word}`.length+3<=width?current=`${current} ${word}`:(lines3.push(current),current=word);return current.length>0&&lines3.push(current),lines3}function managedHeader(name,description){let what=description.length>0?description:DESCRIPTIONS[name]??[];return`${[wrap2(MANAGED_FILE_COMMENT),what,FORMAT_NOTE].filter(block=>block.length>0).map(block=>block.map(line=>`// ${line}`.trimEnd()).join(`
1088
1089
  `)).join(`
1089
1090
  //
1090
1091
  `)}
1091
1092
  `}var ConfdManagedImpl=class{constructor(host){this.host=host}path(name){if(this.host.confDir===void 0)throw new ConfigError23(`There is no sous project here, so there is no ${name} to edit.`,{details:["Run sous init in the project root first."]});return path23.join(this.host.confDir,name)}header(name,description){return managedHeader(name,description)}async read(name){let existing=this.existing(name);if(existing!==void 0)return objectOf(parse5(readText(existing),existing).value(),existing)}async edit(name,edit,options2={}){return this.change(name,`edit ${name}`,edit,options2)}async set(name,keyPath,value,options2={}){let segments=parsePath(keyPath);return this.change(name,`set ${keyPath}`,root=>root.atPath(segments).set(value),options2)}async delete(name,keyPath,options2={}){let segments=parsePath(keyPath);return this.change(name,`delete ${keyPath}`,root=>{let node=root.atPath(segments);node.exists()&&node.delete()},options2)}existing(name){let current=this.path(name);if(isFile5(current))return current;let legacy=legacyPath(current);return legacy!==void 0&&isFile5(legacy)?legacy:void 0}async change(name,label,edit,options2){let file2=this.path(name),existing=this.existing(name),original=existing===void 0?`${managedHeader(name,options2.description??[])}{}
1092
1093
  `:readText(existing),document=parse5(original,existing??file2);objectOf(document.value(),existing??file2),edit(document.root());let text=document.toString();text.endsWith(`
1093
1094
  `)||(text+=`
1094
- `);let patches={name:label,patches:document.patches().patches},migrating=existing!==void 0&&existing!==file2,created=existing===void 0,changed2=created?patches.patches.length>0:text!==original||migrating;return changed2&&options2.dryRun!==!0&&(await this.write(file2,text),migrating&&fs18.rmSync(existing,{force:!0})),{file:file2,created:created&&changed2,changed:changed2,patches,text}}async write(file2,text){let directory=path23.dirname(file2);await this.host.ensureDirectory(directory);let temporary=path23.join(directory,`.${path23.basename(file2)}.tmp-${process.pid}`);try{fs18.writeFileSync(temporary,text,"utf8"),fs18.renameSync(temporary,file2)}catch(error51){throw fs18.rmSync(temporary,{force:!0}),new ConfigError23(`Sous could not write its config file at ${file2}.`,{cause:error51,details:[error51.message]})}}};function legacyPath(file2){return file2.endsWith(".jsonc")?file2.slice(0,-1):void 0}function readText(file2){try{return fs18.readFileSync(file2,"utf8")}catch(error51){throw new ConfigError23(`Sous could not read its own config file at ${file2}.`,{cause:error51,details:[error51.message]})}}function parse5(text,file2){try{return parseDocument2(text,"jsonc")}catch(error51){throw new ConfigError23(`Sous could not read its own config file at ${file2}.`,{cause:error51,details:["The file is not valid JSON with comments.","Sous writes this file itself. Restoring it from version control, or deleting it and adding the entries again, both fix this."]})}}function objectOf(value,file2){if(!isJsonObject(value))throw new ConfigError23(`The config file at ${file2} is not a JSON object.`,{details:["Sous writes this file itself; it always holds one object."]});return value}function isFile5(file2){try{return fs18.statSync(file2).isFile()}catch{return!1}}var package_default10={name:"@sous-io/sous-plugin-confd",version:"1.1.4",description:"The conf.d files, one contributor per file, and surgical edits to the managed conf.d/5xx files.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-lib-documents":"workspace:*","@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-config-files":"workspace:*","@sous-io/sous-plugin-expressions":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@sous-io/sous-plugin-variables":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME9="@sous-io/sous-plugin-confd",USER_FILES_APPLY_ORDER=9e4,MAX_FILE_NUMBER=9999,UNNUMBERED_APPLY_ORDER=90500,SCAN_CONTRIBUTOR="confd.files",confdPlugin=definePlugin10({name:PLUGIN_NAME9,version:package_default10.version,description:"The conf.d files, one contributor per file, and surgical edits to the managed conf.d/5xx files.",dependsOn:{"@sous-io/sous-plugin-config-files":`^${package_default10.version}`,"@sous-io/sous-plugin-expressions":`^${package_default10.version}`,"@sous-io/sous-plugin-variables":`^${package_default10.version}`,"@sous-io/sous-plugin-host":`^${package_default10.version}`},register(sous){let confDir=()=>sous.project?.confDir,compare=(left,right)=>sous.services.get("host.globs").compareBytewise(left,right),loader=()=>sous.services.get("config-files.loader"),added=new Set,addContributors=files=>{for(let file2 of files)added.has(file2.contributor)||(added.add(file2.contributor),sous.config.contribute(fileContributor2(sous,file2)))};addContributors(listConfdFiles(confDir(),loader(),compare)),sous.config.contribute({id:SCAN_CONTRIBUTOR,applyOrder:USER_FILES_APPLY_ORDER,contribute(config2){let files=listConfdFiles(confDir(),loader(),compare),duplicate=duplicateBaseNames(files.map(file2=>file2.name))[0];if(duplicate!==void 0)throw duplicateBaseNameError(duplicate,files);addContributors(files)}}),sous.services.add("confd.files",()=>new ConfdFilesImpl(confDir(),loader(),compare),{lifetime:"config"}),sous.services.add("confd.managed",(_config,ctx)=>new ConfdManagedImpl({confDir:confDir(),ensureDirectory:async directory=>{ctx.services.has("host.directories")?await ctx.services.get("host.directories").ensureKnown("confd",directory):fs19.mkdirSync(directory,{recursive:!0})}}),{lifetime:"config"})}});function leadingFileNumber(name){let leading=/^\d+/.exec(name)?.[0];return leading===void 0?void 0:{read:Number(leading),used:Math.min(MAX_FILE_NUMBER,Number(leading))}}function confdApplyOrder(name){let number4=leadingFileNumber(name);return number4===void 0?UNNUMBERED_APPLY_ORDER:USER_FILES_APPLY_ORDER+number4.used}function fileContributor2(sous,file2){let isPatch2=file2.format==="patch-json"||file2.format==="patch-jsonl";return{id:contributorId(file2.name),source:file2.path,applyOrder:confdApplyOrder(file2.name),...isPatch2?{monitors:[""]}:{},async contribute(config2){let loader=sous.services.get("config-files.loader");if(config2.contributor.run===1){loader.forget(file2.path);let number4=leadingFileNumber(file2.name);number4!==void 0&&number4.read>number4.used&&config2.debug(`The conf.d file ${file2.name} starts with the number ${number4.read}, which is more than ${MAX_FILE_NUMBER}; it is applied as number ${number4.used} (apply order ${confdApplyOrder(file2.name)}).`)}isFile6(file2.path)&&await loader.contribute(await loader.load(file2.path),config2)}}}function duplicateBaseNameError(names2,files){let dot=names2[0].lastIndexOf("."),base=dot<=0?names2[0]:names2[0].slice(0,dot),paths=names2.map(name=>files.find(file2=>file2.name===name)?.path??name);return new ConfigError24(`Duplicate config layer baseName '${base}':`,{details:[...paths.map(file2=>` ${file2}`),"Two config files in one directory must not share a name once the final extension is removed. Delete or rename one of them."]})}function isFile6(file2){try{return fs19.statSync(file2).isFile()}catch{return!1}}import{definePlugin as definePlugin11,jsonSchema as jsonSchema10}from"@sous-io/sous-plugin-api";import path25 from"node:path";import os5 from"node:os";import path24 from"node:path";var IMPORT_TOKEN_PATTERN=/(?:^|\s)@((?:[^\s\\]|\\ )+)/g;function importPath(run){let hash2=run.indexOf("#"),cut=(hash2===-1?run:run.slice(0,hash2)).replaceAll("\\ "," ");if(cut!=="")return cut.startsWith("./")||cut.startsWith("~/")||cut.startsWith("/")&&cut!=="/"||/^[a-zA-Z0-9._-]/.test(cut)?cut:void 0}var IMPORTABLE_EXTENSIONS=new Set([".md",".txt",".text",".json",".yaml",".yml",".toml",".xml",".csv",".html",".htm",".css",".scss",".sass",".less",".js",".ts",".tsx",".jsx",".mjs",".cjs",".mts",".cts",".py",".pyi",".pyw",".rb",".erb",".rake",".go",".rs",".java",".kt",".kts",".scala",".c",".cpp",".cc",".cxx",".h",".hpp",".hxx",".cs",".swift",".sh",".bash",".zsh",".fish",".ps1",".bat",".cmd",".env",".ini",".cfg",".conf",".config",".properties",".sql",".graphql",".gql",".proto",".vue",".svelte",".astro",".ejs",".hbs",".pug",".jade",".php",".pl",".pm",".lua",".r",".dart",".ex",".exs",".erl",".hrl",".clj",".cljs",".cljc",".edn",".hs",".lhs",".elm",".ml",".mli",".f",".f90",".f95",".for",".cmake",".make",".makefile",".gradle",".sbt",".rst",".adoc",".asciidoc",".org",".tex",".latex",".lock",".log",".diff",".patch"]);function isIncludableFile(file2){let extension=path24.extname(file2).toLowerCase();return extension===""||IMPORTABLE_EXTENSIONS.has(extension)}var GLOB_CHARS2=/[*?[\]{}]/;function isSousIncludeForm(word){let{path:bare,query}=splitIncludeQuery(word);return/^~[^/]/.test(word)||word.startsWith("#")||word.includes("${")||GLOB_CHARS2.test(bare)||query!==""}function isIncludeLine(line){let match2=/^@(\S+)$/.exec(line.trimEnd());return match2!==null&&(isSousIncludeForm(match2[1])||importPath(match2[1])!==void 0)}var TEMPLATE_MARKER=".tpl";function templateTwin(filePath){let dir=path24.dirname(filePath),base=path24.basename(filePath),ext2=path24.extname(base);if(ext2===""||ext2===base)return;let stem=base.slice(0,-ext2.length),twin=stem.endsWith(TEMPLATE_MARKER)?`${stem.slice(0,-TEMPLATE_MARKER.length)}${ext2}`:`${stem}${TEMPLATE_MARKER}${ext2}`;return path24.join(dir,twin)}function withTemplateTwins(candidates){let out=[];for(let candidate of candidates){out.push(candidate);let twin=templateTwin(candidate);twin!==void 0&&out.push(twin)}return[...new Set(out)]}function splitAliasKey(value){let match2=value.match(/^([^/:]+)[/:]([\s\S]*)$/);return match2?{key:match2[1],rest:match2[2]}:{key:value,rest:""}}var QUERY_SUFFIX=/^(.*\.md)(\?[^?\s]*=\S*)$/;function splitIncludeQuery(raw2){let match2=QUERY_SUFFIX.exec(raw2);return match2===null?{path:raw2,query:""}:{path:match2[1],query:match2[2]}}function expandHome2(value,home=os5.homedir()){return value==="~"?home:value.startsWith("~/")?path24.join(home,value.slice(2)):value}function resolveOutputPath(unit,output){if(output.destinationFile)return output.destinationFile;if(!output.destinationDir)return;let sourceRelative=unit.globBase?path24.relative(unit.globBase,unit.source):path24.basename(unit.source);return path24.join(output.destinationDir,sourceRelative.replace(/\.tpl\./,"."))}function stableVarsFingerprint(vars){return JSON.stringify(Object.keys(vars).sort().map(key=>[key,vars[key]]))}function isReservedAliasName(name){return name.startsWith("~")||name.startsWith("#")}function buildAliasMap(options2){let substitute3=options2.substitute??(text=>text),out={};for(let[name,bases]of Object.entries(options2.builtIns??{}))out[name]=[...bases];for(let block of options2.userAliases??[])if(block)for(let[name,value]of Object.entries(block)){if(isReservedAliasName(name)){options2.onError?.(`Alias "${name}" is invalid: names beginning with "~" or "#" are reserved ("~" for the home directory and recipe namespaces, "#" for built-in names).`);continue}let bases=(typeof value=="string"?[value]:[...value]).map(entry=>substitute3(entry));out[name]=[...bases,...out[name]??[]]}return out}function resolveAliasPrefix(value,aliases2){if(path25.isAbsolute(value))return[value];let{key,rest}=splitAliasKey(value);return!key||!Object.prototype.hasOwnProperty.call(aliases2,key)?[value]:aliases2[key].map(base=>path25.resolve(base,rest))}var AliasService=class{constructor(map3){this.map=map3}all(){return Object.fromEntries(Object.entries(this.map).map(([name,bases])=>[name,[...bases]]))}get(name){return Object.prototype.hasOwnProperty.call(this.map,name)?[...this.map[name]]:void 0}split(value){let{key,rest}=splitAliasKey(value);return Object.prototype.hasOwnProperty.call(this.map,key)?{alias:key,rest}:void 0}};import fs21 from"node:fs";import path27 from"node:path";import fs20 from"node:fs";import path26 from"node:path";function compareIncludeOrder(left,right){let a=left.split(/[\\/]/),b=right.split(/[\\/]/);for(let index=0;index<Math.min(a.length,b.length);index+=1){let leftIsFile=index===a.length-1,rightIsFile=index===b.length-1;if(leftIsFile!==rightIsFile)return leftIsFile?-1:1;let order=compareIncludeNames(a[index],b[index]);if(order!==0)return order}return a.length-b.length}function compareIncludeNames(left,right){let length=Math.min(left.length,right.length);for(let index=0;index<length;index+=1){let order=includeCharRank(left[index])-includeCharRank(right[index]);if(order!==0)return order}return left.length!==right.length?left.length-right.length:left<right?-1:left>right?1:0}function includeCharRank(char){return char==="_"?-1:char.toLowerCase().charCodeAt(0)}function expandPattern(globs,pattern,options2={}){if(!globs.hasGlob(pattern))return isFile7(pattern)?[path26.resolve(pattern)]:[];let normalized=pattern.split(path26.sep).join("/"),base=globs.staticBase(normalized),relative4=base==="/"?normalized.replace(/^\/+/,""):normalized.slice(base.length).replace(/^\/+/,"");if(relative4==="")return[];try{let matches=globs.matchSync(relative4,{cwd:base,absolute:!0,dot:options2.dot??!0,onlyFiles:!0});return[...new Set(matches.map(file2=>path26.resolve(file2)))].sort(compareIncludeOrder)}catch{return[]}}function isFile7(file2){try{return fs20.statSync(file2).isFile()}catch{return!1}}var FILES_CONTRIBUTOR="compiler.files",LISTING_STAGE=1;function targetName(target,index){return target.id??String(index)}function listFiles(targets,env){let files=[],problems=[];return targets.forEach((target,index)=>{try{files.push(...listTarget(target,index,env,problems))}catch(error51){problems.push({level:"error",message:error51 instanceof Error?error51.message:String(error51),target:targetName(target,index),targetIndex:index})}}),{files,listing:{targets:targets.length,problems}}}function listTarget(target,index,env,problems){let where3=`compilation.targets[${index}]`,name=targetName(target,index),scopeKey=target.origin?.recipe,keyed=scopeKey===void 0?{}:{scopeKey},scope=env.scope({level:"target",target:index,...keyed}),toPath=(value,context,inScope=scope)=>path27.resolve(env.projectRoot,env.resolver.normalizePath(env.resolver.substituteStrict(value,inScope,context)));if([target.entryPoint,target.entryGlob,target.content].filter(source=>source!==void 0).length!==1||target.content!==void 0&&target.id===void 0||!Array.isArray(target.outputs))return[];let outputs=target.outputs.map((output,outputIndex)=>{let vars=output._vars!==void 0&&Object.keys(output._vars).length>0?env.scope({level:"output",target:index,output:outputIndex,...keyed}):scope,at2=`${where3}.outputs[${outputIndex}]`;return{outputIndex,harness:output.harness,...output.destinationFile===void 0?{}:{destinationFile:toPath(output.destinationFile,`${at2}.destinationFile`,vars)},...output.destinationDir===void 0?{}:{destinationDir:toPath(output.destinationDir,`${at2}.destinationDir`,vars)}}}),entriesFor=(source,globBase2)=>outputs.flatMap(output=>{let destination=resolveOutputPath({source,...globBase2===void 0?{}:{globBase:globBase2}},output);return destination===void 0?[]:[{target:name,targetIndex:index,source,output:output.outputIndex,destination,...output.harness===void 0?{}:{harness:output.harness}}]});if(target.content!==void 0)return entriesFor(path27.join(env.projectRoot,target.id),env.projectRoot);if(target.entryPoint!==void 0){let source=toPath(target.entryPoint,`${where3}.entryPoint`),globBase2=target.globBase===void 0?void 0:toPath(target.globBase,`${where3}.globBase`);return entriesFor(source,globBase2)}let rawPattern=env.resolver.normalizePath(env.resolver.substituteStrict(target.entryGlob,scope,`${where3}.entryGlob`)),candidates=resolveAliasPrefix(rawPattern,aliasesFor(rawPattern,env)).map(candidate=>path27.resolve(env.projectRoot,candidate)),pattern=candidates[0],matched=[];for(let candidate of candidates){let found=expandPattern(env.globs,candidate,{dot:!1});if(found.length>0){pattern=candidate,matched=found;break}}let globBase=target.globBase===void 0?path27.resolve(env.globs.staticBase(pattern.split(path27.sep).join("/"))):toPath(target.globBase,`${where3}.globBase`);return matched.length===0&&fs21.existsSync(globBase)&&problems.push({level:"warning",message:`Glob pattern matched no files:
1095
+ `);let patches={name:label,patches:document.patches().patches},migrating=existing!==void 0&&existing!==file2,created=existing===void 0,changed2=created?patches.patches.length>0:text!==original||migrating;return changed2&&options2.dryRun!==!0&&(await this.write(file2,text),migrating&&fs18.rmSync(existing,{force:!0})),{file:file2,created:created&&changed2,changed:changed2,patches,text}}async write(file2,text){let directory=path23.dirname(file2);await this.host.ensureDirectory(directory);let temporary=path23.join(directory,`.${path23.basename(file2)}.tmp-${process.pid}`);try{fs18.writeFileSync(temporary,text,"utf8"),fs18.renameSync(temporary,file2)}catch(error51){throw fs18.rmSync(temporary,{force:!0}),new ConfigError23(`Sous could not write its config file at ${file2}.`,{cause:error51,details:[error51.message]})}}};function legacyPath(file2){return file2.endsWith(".jsonc")?file2.slice(0,-1):void 0}function readText(file2){try{return fs18.readFileSync(file2,"utf8")}catch(error51){throw new ConfigError23(`Sous could not read its own config file at ${file2}.`,{cause:error51,details:[error51.message]})}}function parse5(text,file2){try{return parseDocument2(text,"jsonc")}catch(error51){throw new ConfigError23(`Sous could not read its own config file at ${file2}.`,{cause:error51,details:["The file is not valid JSON with comments.","Sous writes this file itself. Restoring it from version control, or deleting it and adding the entries again, both fix this."]})}}function objectOf(value,file2){if(!isJsonObject(value))throw new ConfigError23(`The config file at ${file2} is not a JSON object.`,{details:["Sous writes this file itself; it always holds one object."]});return value}function isFile5(file2){try{return fs18.statSync(file2).isFile()}catch{return!1}}var package_default10={name:"@sous-io/sous-plugin-confd",version:"1.1.6",description:"The conf.d files, one contributor per file, and surgical edits to the managed conf.d/5xx files.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-lib-documents":"workspace:*","@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-config-files":"workspace:*","@sous-io/sous-plugin-expressions":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@sous-io/sous-plugin-variables":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME9="@sous-io/sous-plugin-confd",USER_FILES_APPLY_ORDER=9e4,MAX_FILE_NUMBER=9999,UNNUMBERED_APPLY_ORDER=90500,SCAN_CONTRIBUTOR="confd.files",confdPlugin=definePlugin10({name:PLUGIN_NAME9,version:package_default10.version,description:"The conf.d files, one contributor per file, and surgical edits to the managed conf.d/5xx files.",dependsOn:{"@sous-io/sous-plugin-config-files":`^${package_default10.version}`,"@sous-io/sous-plugin-expressions":`^${package_default10.version}`,"@sous-io/sous-plugin-variables":`^${package_default10.version}`,"@sous-io/sous-plugin-host":`^${package_default10.version}`},register(sous){let confDir=()=>sous.project?.confDir,compare=(left,right)=>sous.services.get("host.globs").compareBytewise(left,right),loader=()=>sous.services.get("config-files.loader"),added=new Set,addContributors=files=>{for(let file2 of files)added.has(file2.contributor)||(added.add(file2.contributor),sous.config.contribute(fileContributor2(sous,file2)))};addContributors(listConfdFiles(confDir(),loader(),compare)),sous.config.contribute({id:SCAN_CONTRIBUTOR,applyOrder:USER_FILES_APPLY_ORDER,contribute(config2){let files=listConfdFiles(confDir(),loader(),compare),duplicate=duplicateBaseNames(files.map(file2=>file2.name))[0];if(duplicate!==void 0)throw duplicateBaseNameError(duplicate,files);addContributors(files)}}),sous.services.add("confd.files",()=>new ConfdFilesImpl(confDir(),loader(),compare),{lifetime:"config"}),sous.services.add("confd.managed",(_config,ctx)=>new ConfdManagedImpl({confDir:confDir(),ensureDirectory:async directory=>{ctx.services.has("host.directories")?await ctx.services.get("host.directories").ensureKnown("confd",directory):fs19.mkdirSync(directory,{recursive:!0})}}),{lifetime:"config"})}});function leadingFileNumber(name){let leading=/^\d+/.exec(name)?.[0];return leading===void 0?void 0:{read:Number(leading),used:Math.min(MAX_FILE_NUMBER,Number(leading))}}function confdApplyOrder(name){let number4=leadingFileNumber(name);return number4===void 0?UNNUMBERED_APPLY_ORDER:USER_FILES_APPLY_ORDER+number4.used}function fileContributor2(sous,file2){let isPatch2=file2.format==="patch-json"||file2.format==="patch-jsonl";return{id:contributorId(file2.name),source:file2.path,applyOrder:confdApplyOrder(file2.name),...isPatch2?{monitors:[""]}:{},async contribute(config2){let loader=sous.services.get("config-files.loader");if(config2.contributor.run===1){loader.forget(file2.path);let number4=leadingFileNumber(file2.name);number4!==void 0&&number4.read>number4.used&&config2.debug(`The conf.d file ${file2.name} starts with the number ${number4.read}, which is more than ${MAX_FILE_NUMBER}; it is applied as number ${number4.used} (apply order ${confdApplyOrder(file2.name)}).`)}isFile6(file2.path)&&await loader.contribute(await loader.load(file2.path),config2)}}}function duplicateBaseNameError(names2,files){let dot=names2[0].lastIndexOf("."),base=dot<=0?names2[0]:names2[0].slice(0,dot),paths=names2.map(name=>files.find(file2=>file2.name===name)?.path??name);return new ConfigError24(`Duplicate config layer baseName '${base}':`,{details:[...paths.map(file2=>` ${file2}`),"Two config files in one directory must not share a name once the final extension is removed. Delete or rename one of them."]})}function isFile6(file2){try{return fs19.statSync(file2).isFile()}catch{return!1}}import{definePlugin as definePlugin11,jsonSchema as jsonSchema10}from"@sous-io/sous-plugin-api";import path25 from"node:path";import os5 from"node:os";import path24 from"node:path";var IMPORT_TOKEN_PATTERN=/(?:^|\s)@((?:[^\s\\]|\\ )+)/g;function importPath(run){let hash2=run.indexOf("#"),cut=(hash2===-1?run:run.slice(0,hash2)).replaceAll("\\ "," ");if(cut!=="")return cut.startsWith("./")||cut.startsWith("~/")||cut.startsWith("/")&&cut!=="/"||/^[a-zA-Z0-9._-]/.test(cut)?cut:void 0}var IMPORTABLE_EXTENSIONS=new Set([".md",".txt",".text",".json",".yaml",".yml",".toml",".xml",".csv",".html",".htm",".css",".scss",".sass",".less",".js",".ts",".tsx",".jsx",".mjs",".cjs",".mts",".cts",".py",".pyi",".pyw",".rb",".erb",".rake",".go",".rs",".java",".kt",".kts",".scala",".c",".cpp",".cc",".cxx",".h",".hpp",".hxx",".cs",".swift",".sh",".bash",".zsh",".fish",".ps1",".bat",".cmd",".env",".ini",".cfg",".conf",".config",".properties",".sql",".graphql",".gql",".proto",".vue",".svelte",".astro",".ejs",".hbs",".pug",".jade",".php",".pl",".pm",".lua",".r",".dart",".ex",".exs",".erl",".hrl",".clj",".cljs",".cljc",".edn",".hs",".lhs",".elm",".ml",".mli",".f",".f90",".f95",".for",".cmake",".make",".makefile",".gradle",".sbt",".rst",".adoc",".asciidoc",".org",".tex",".latex",".lock",".log",".diff",".patch"]);function isIncludableFile(file2){let extension=path24.extname(file2).toLowerCase();return extension===""||IMPORTABLE_EXTENSIONS.has(extension)}var GLOB_CHARS2=/[*?[\]{}]/;function isSousIncludeForm(word){let{path:bare,query}=splitIncludeQuery(word);return/^~[^/]/.test(word)||word.startsWith("#")||word.includes("${")||GLOB_CHARS2.test(bare)||query!==""}function isIncludeLine(line){let match2=/^@(\S+)$/.exec(line.trimEnd());return match2!==null&&(isSousIncludeForm(match2[1])||importPath(match2[1])!==void 0)}var TEMPLATE_MARKER=".tpl";function templateTwin(filePath){let dir=path24.dirname(filePath),base=path24.basename(filePath),ext2=path24.extname(base);if(ext2===""||ext2===base)return;let stem=base.slice(0,-ext2.length),twin=stem.endsWith(TEMPLATE_MARKER)?`${stem.slice(0,-TEMPLATE_MARKER.length)}${ext2}`:`${stem}${TEMPLATE_MARKER}${ext2}`;return path24.join(dir,twin)}function withTemplateTwins(candidates){let out=[];for(let candidate of candidates){out.push(candidate);let twin=templateTwin(candidate);twin!==void 0&&out.push(twin)}return[...new Set(out)]}function splitAliasKey(value){let match2=value.match(/^([^/:]+)[/:]([\s\S]*)$/);return match2?{key:match2[1],rest:match2[2]}:{key:value,rest:""}}var QUERY_SUFFIX=/^(.*\.md)(\?[^?\s]*=\S*)$/;function splitIncludeQuery(raw2){let match2=QUERY_SUFFIX.exec(raw2);return match2===null?{path:raw2,query:""}:{path:match2[1],query:match2[2]}}function expandHome2(value,home=os5.homedir()){return value==="~"?home:value.startsWith("~/")?path24.join(home,value.slice(2)):value}function resolveOutputPath(unit,output){if(output.destinationFile)return output.destinationFile;if(!output.destinationDir)return;let sourceRelative=unit.globBase?path24.relative(unit.globBase,unit.source):path24.basename(unit.source);return path24.join(output.destinationDir,sourceRelative.replace(/\.tpl\./,"."))}function stableVarsFingerprint(vars){return JSON.stringify(Object.keys(vars).sort().map(key=>[key,vars[key]]))}function isReservedAliasName(name){return name.startsWith("~")||name.startsWith("#")}function buildAliasMap(options2){let substitute3=options2.substitute??(text=>text),out={};for(let[name,bases]of Object.entries(options2.builtIns??{}))out[name]=[...bases];for(let block of options2.userAliases??[])if(block)for(let[name,value]of Object.entries(block)){if(isReservedAliasName(name)){options2.onError?.(`Alias "${name}" is invalid: names beginning with "~" or "#" are reserved ("~" for the home directory and recipe namespaces, "#" for built-in names).`);continue}let bases=(typeof value=="string"?[value]:[...value]).map(entry=>substitute3(entry));out[name]=[...bases,...out[name]??[]]}return out}function resolveAliasPrefix(value,aliases2){if(path25.isAbsolute(value))return[value];let{key,rest}=splitAliasKey(value);return!key||!Object.prototype.hasOwnProperty.call(aliases2,key)?[value]:aliases2[key].map(base=>path25.resolve(base,rest))}var AliasService=class{constructor(map3){this.map=map3}all(){return Object.fromEntries(Object.entries(this.map).map(([name,bases])=>[name,[...bases]]))}get(name){return Object.prototype.hasOwnProperty.call(this.map,name)?[...this.map[name]]:void 0}split(value){let{key,rest}=splitAliasKey(value);return Object.prototype.hasOwnProperty.call(this.map,key)?{alias:key,rest}:void 0}};import fs21 from"node:fs";import path27 from"node:path";import fs20 from"node:fs";import path26 from"node:path";function compareIncludeOrder(left,right){let a=left.split(/[\\/]/),b=right.split(/[\\/]/);for(let index=0;index<Math.min(a.length,b.length);index+=1){let leftIsFile=index===a.length-1,rightIsFile=index===b.length-1;if(leftIsFile!==rightIsFile)return leftIsFile?-1:1;let order=compareIncludeNames(a[index],b[index]);if(order!==0)return order}return a.length-b.length}function compareIncludeNames(left,right){let length=Math.min(left.length,right.length);for(let index=0;index<length;index+=1){let order=includeCharRank(left[index])-includeCharRank(right[index]);if(order!==0)return order}return left.length!==right.length?left.length-right.length:left<right?-1:left>right?1:0}function includeCharRank(char){return char==="_"?-1:char.toLowerCase().charCodeAt(0)}function expandPattern(globs,pattern,options2={}){if(!globs.hasGlob(pattern))return isFile7(pattern)?[path26.resolve(pattern)]:[];let normalized=pattern.split(path26.sep).join("/"),base=globs.staticBase(normalized),relative4=base==="/"?normalized.replace(/^\/+/,""):normalized.slice(base.length).replace(/^\/+/,"");if(relative4==="")return[];try{let matches=globs.matchSync(relative4,{cwd:base,absolute:!0,dot:options2.dot??!0,onlyFiles:!0});return[...new Set(matches.map(file2=>path26.resolve(file2)))].sort(compareIncludeOrder)}catch{return[]}}function isFile7(file2){try{return fs20.statSync(file2).isFile()}catch{return!1}}var FILES_CONTRIBUTOR="compiler.files",LISTING_STAGE=1;function targetName(target,index){return target.id??String(index)}function listFiles(targets,env){let files=[],problems=[];return targets.forEach((target,index)=>{try{files.push(...listTarget(target,index,env,problems))}catch(error51){problems.push({level:"error",message:error51 instanceof Error?error51.message:String(error51),target:targetName(target,index),targetIndex:index})}}),{files,listing:{targets:targets.length,problems}}}function listTarget(target,index,env,problems){let where3=`compilation.targets[${index}]`,name=targetName(target,index),scopeKey=target.origin?.recipe,keyed=scopeKey===void 0?{}:{scopeKey},scope=env.scope({level:"target",target:index,...keyed}),toPath=(value,context,inScope=scope)=>path27.resolve(env.projectRoot,env.resolver.normalizePath(env.resolver.substituteStrict(value,inScope,context)));if([target.entryPoint,target.entryGlob,target.content].filter(source=>source!==void 0).length!==1||target.content!==void 0&&target.id===void 0||!Array.isArray(target.outputs))return[];let outputs=target.outputs.map((output,outputIndex)=>{let vars=output._vars!==void 0&&Object.keys(output._vars).length>0?env.scope({level:"output",target:index,output:outputIndex,...keyed}):scope,at2=`${where3}.outputs[${outputIndex}]`;return{outputIndex,harness:output.harness,...output.destinationFile===void 0?{}:{destinationFile:toPath(output.destinationFile,`${at2}.destinationFile`,vars)},...output.destinationDir===void 0?{}:{destinationDir:toPath(output.destinationDir,`${at2}.destinationDir`,vars)}}}),entriesFor=(source,globBase2)=>outputs.flatMap(output=>{let destination=resolveOutputPath({source,...globBase2===void 0?{}:{globBase:globBase2}},output);return destination===void 0?[]:[{target:name,targetIndex:index,source,output:output.outputIndex,destination,...output.harness===void 0?{}:{harness:output.harness}}]});if(target.content!==void 0)return entriesFor(path27.join(env.projectRoot,target.id),env.projectRoot);if(target.entryPoint!==void 0){let source=toPath(target.entryPoint,`${where3}.entryPoint`),globBase2=target.globBase===void 0?void 0:toPath(target.globBase,`${where3}.globBase`);return entriesFor(source,globBase2)}let rawPattern=env.resolver.normalizePath(env.resolver.substituteStrict(target.entryGlob,scope,`${where3}.entryGlob`)),candidates=resolveAliasPrefix(rawPattern,aliasesFor(rawPattern,env)).map(candidate=>path27.resolve(env.projectRoot,candidate)),pattern=candidates[0],matched=[];for(let candidate of candidates){let found=expandPattern(env.globs,candidate,{dot:!1});if(found.length>0){pattern=candidate,matched=found;break}}let globBase=target.globBase===void 0?path27.resolve(env.globs.staticBase(pattern.split(path27.sep).join("/"))):toPath(target.globBase,`${where3}.globBase`);return matched.length===0&&fs21.existsSync(globBase)&&problems.push({level:"warning",message:`Glob pattern matched no files:
1095
1096
  ${candidates.join(`
1096
1097
  `)}`,target:name,targetIndex:index}),matched.flatMap(source=>entriesFor(source,globBase))}function aliasesFor(pattern,env){return path27.isAbsolute(pattern)?{}:env.aliases()}function filesContributor(options2){return{id:FILES_CONTRIBUTOR,stage:LISTING_STAGE,after:["*"],contribute(config2){let targets=config2.atPath(["compilation","targets"]).get(),list2=Array.isArray(targets)?targets:[],resolver=options2.services.get("variables.resolver"),globs=options2.services.get("host.globs"),projectRoot=config2.project?.root??path27.resolve("/"),{files,listing}=listFiles(list2,{scope:cachedScopes(config2,resolver),resolver,aliases:once(()=>builderAliases(config2,options2.plugin,options2.services,resolver,projectRoot)),globs,projectRoot});config2.atPath(["compilation","files"]).set(files),config2.atPath(["compilation","listing"]).set(listing)}}}function cachedScopes(config2,resolver){let cache2=new Map,targets=config2.atPath(["compilation","targets"]),cached2=request=>{let key=JSON.stringify([request.level,request.target,request.output,request.scopeKey]),scope=cache2.get(key);return scope===void 0&&(scope=resolver.scopeIn(config2,request),cache2.set(key,scope)),scope},keyed=scopeKey=>scopeKey===void 0?{}:{scopeKey},scopeAt=request=>request.level==="output"&&targets.atPath([request.target,"outputs",request.output,"_vars"]).get()===void 0?scopeAt({level:"target",target:request.target,...keyed(request.scopeKey)}):request.level==="target"&&targets.atPath([request.target,"_vars"]).get()===void 0?cached2({level:"compilation",...keyed(request.scopeKey)}):cached2(request);return scopeAt}function once(make2){let value;return()=>(value??={v:make2()},value.v)}function builderAliases(config2,plugin,services,resolver,projectRoot){let scope=resolver.scopeIn(config2,{}),context={plugin,config:{get:at2=>config2.atPath(at2).get(),has:at2=>config2.atPath(at2).exists(),value:()=>config2.root().get()},services,entities:{get:(kind,id)=>config2.entity(kind,id),list:kind=>config2.entities(kind),has:(kind,id)=>config2.entity(kind,id)!==void 0,describe:()=>[],kinds:()=>[]},project:config2.project,env:config2.env,scope},builtIns={};for(let entity of config2.entities("hash-name"))entity.view||(builtIns[`#${entity.id}`]=(entity.bases?.(context)??[]).map(base=>path27.resolve(projectRoot,base)));return buildAliasMap({builtIns,userAliases:[config2.atPath("_aliases").get()],substitute:text=>path27.resolve(projectRoot,resolver.normalizePath(resolver.substitute(text,scope)))})}init_src();import fs22 from"node:fs";import path28 from"node:path";var IF_MIGRATION_VERSION="1.1.0",SHADOWED=new Set(["env","host"]),DATA_ENDINGS=[[".jsonc","jsonc"],[".json","json"],[".yaml","yaml"],[".yml","yaml"]],CODE_ENDINGS=[".js",".mjs",".cjs",".ts",".mts",".cts"];function ifExpression(conditions){return(conditions!==null&&typeof conditions=="object"?Object.entries(conditions).map(([name,condition])=>{let value=condition?.eq;return`${name} == '${String(value).replace(/'/g,"\\'")}'`}):[]).join(" and ")||"true"}function ifReplacementValue(output){let{_if:conditions,...rest}=output;return{$if:{expr:ifExpression(conditions),then:rest}}}function shadowedNames(conditions){return conditions!==null&&typeof conditions=="object"?Object.keys(conditions).filter(name=>SHADOWED.has(name)):[]}function configFiles(sousDir,confDir){let main2=fs22.existsSync(sousDir)?fs22.readdirSync(sousDir).filter(name=>name.startsWith("sous.config.")).map(name=>path28.join(sousDir,name)):[],layers=fs22.existsSync(confDir)?fs22.readdirSync(confDir).filter(name=>!name.startsWith(".")&&!name.includes(".patch.")).map(name=>path28.join(confDir,name)):[];return[...main2,...layers].filter(file2=>fs22.statSync(file2).isFile()).sort()}function outputsWithIf(node,value,inOutputs=!1,found=[]){if(Array.isArray(value))value.forEach((item,index)=>{outputsWithIf(node.atIndex(index),item,!1,found)}),inOutputs&&value.forEach((item,index)=>{isJsonObject(item)&&"_if"in item&&found.push(node.atIndex(index))});else if(isJsonObject(value))for(let[key,child2]of Object.entries(value))outputsWithIf(node.atPath([key]),child2,key==="outputs",found);return found}function migrateDataFile(file2,format3,dryRun4=!1){let text=fs22.readFileSync(file2,"utf8"),result={converted:[],leftAlone:[]};if(!text.includes("_if"))return result;let doc=parseDocument2(text,format3);for(let node of outputsWithIf(doc.root(),doc.value())){let output=node.get(),shadowed=shadowedNames(output._if);if(shadowed.length>0){result.leftAlone.push(`${node.pathString}: names ${shadowed.map(name=>`'${name}'`).join(" and ")}, which an expression reads as Sous's own value; rename the variable, then write ${JSON.stringify(ifReplacementValue(output))}.`);continue}node.set(ifReplacementValue(output)),result.converted.push(node.pathString)}return result.converted.length>0&&!dryRun4&&fs22.writeFileSync(file2,doc.toString(),"utf8"),result}function reportCodeFile(file2){let lines3=fs22.readFileSync(file2,"utf8").split(/\r?\n/),found=[];return lines3.forEach((line,index)=>{if(!/(^|[\s{,'"])_if['"]?\s*:/.test(line))return;let conditions={};for(let match2 of line.matchAll(/['"]?([A-Za-z_][\w-]*)['"]?\s*:\s*\{\s*eq\s*:\s*(['"])(.*?)\2\s*\}/g))conditions[match2[1]]={eq:match2[3]};let expr=Object.keys(conditions).length>0?ifExpression(conditions):"<variable> == '<value>'";found.push(`${file2}:${index+1}: write the output as { $if: { expr: ${JSON.stringify(expr)}, then: { ...the output without _if... } } }`)}),found}function migrateIfConditions(sousDir,confDir,dryRun4=!1){let converted=[],reported=[];for(let file2 of configFiles(sousDir,confDir)){let name=file2.toLowerCase(),data=DATA_ENDINGS.find(([ending])=>name.endsWith(ending));if(data!==void 0){let result=migrateDataFile(file2,data[1],dryRun4);converted.push(...result.converted.map(at2=>`${file2}: ${at2}`)),reported.push(...result.leftAlone.map(line=>`${file2}: ${line}`))}else CODE_ENDINGS.some(ending=>name.endsWith(ending))&&reported.push(...reportCodeFile(file2))}return converted.length===0&&reported.length===0?{summary:"No output in the config uses '_if'."}:{summary:`${[...converted.length>0?[`${converted.length===1?"One output's '_if' was":`${converted.length} outputs' '_if' were`} rewritten as a config expression ($if)`]:[],...reported.length>0?[`${reported.length===1?"one '_if' needs":`${reported.length} '_if' need`} changing by hand, as listed`]:[]].join("; ")}.`,details:[...converted,...reported]}}var ifMigration={version:IF_MIGRATION_VERSION,id:"compiler/if-to-expression",description:"Rewrite each compilation output's removed '_if' as the config expression ($if) that replaces it",up(ctx){let project=ctx.project;return project===void 0?{summary:"There is no project here."}:migrateIfConditions(project.sousDir,project.confDir)}};init_src2();import path29 from"node:path";var VAR_OVERRIDES_CONTRIBUTOR="compiler.var-overrides";function listOf(value){return value===void 0?[]:typeof value=="string"?[value]:[...value]}function posix(file2){return file2.split(path29.sep).join("/")}function compileRule(rule,index,env){let where3=`compilation.varOverrides[${index}]`,prepare2=(entries,key)=>entries.map((entry,at2)=>{if(entry.length>=3&&entry.startsWith("/")&&entry.endsWith("/"))return entry;let substituted=env.resolver.normalizePath(env.resolver.substituteStrict(entry,env.scope,`${where3}.${key}[${at2}]`));return posix(path29.isAbsolute(substituted)?substituted:path29.join(env.projectRoot,substituted))}),match2=compilePatternList(prepare2(listOf(rule.match),"match"),`${where3}.match`,env.isMatch),exclude=compilePatternList(prepare2(listOf(rule.exclude),"exclude"),`${where3}.exclude`,env.isMatch);return{matches:file2=>match2(file2)&&!exclude(file2),vars:rule._vars??{}}}function applyOverrides(rules,files,env){let problems=[],compiled=rules.flatMap((rule,index)=>{try{return[compileRule(rule,index,env)]}catch(error51){return problems.push({level:"error",message:`compilation.varOverrides[${index}] is not applied: ${error51 instanceof Error?error51.message:String(error51)}`}),[]}}),vars=new Map;return compiled.length===0?{vars,problems}:(files.forEach((file2,index)=>{let destination=posix(file2.destination),merged;for(let rule of compiled)rule.matches(destination)&&(merged={...merged,...rule.vars});merged!==void 0&&vars.set(index,merged)}),{vars,problems})}function varOverridesContributor(options2){return{id:VAR_OVERRIDES_CONTRIBUTOR,stage:LISTING_STAGE,after:["*",FILES_CONTRIBUTOR],contribute(config2){let rules=config2.atPath(["compilation","varOverrides"]).get();if(!Array.isArray(rules)||rules.length===0)return;let files=config2.atPath(["compilation","files"]).get()??[],resolver=options2.services.get("variables.resolver"),globs=options2.services.get("host.globs"),{vars,problems}=applyOverrides(rules,files,{resolver,scope:resolver.scopeIn(config2,{level:"compilation"}),isMatch:(file2,pattern)=>globs.isMatch(file2,pattern,{dot:!0}),projectRoot:config2.project?.root??path29.resolve("/")});for(let[index,values]of vars)config2.atPath(["compilation","files",index,"_vars"]).set(values);for(let problem of problems)config2.atPath(["compilation","listing","problems"]).append(problem)}}}import fs23 from"node:fs";import path30 from"node:path";function literalGroups(candidate,root){return withTemplateTwins([candidate]).map(entry=>({paths:[entry],glob:!1,...root===void 0?{}:{roots:[root]}}))}function planInclude(rawPath,context,env){let baseDir=context.baseDir??path30.dirname(context.fromFile),withQuery=expandHome2(env.substitute(rawPath,context.scope),env.home),substituted=splitIncludeQuery(withQuery).path,glob=env.globs.hasGlob(substituted),finish4=(groups2,extra={})=>({groups:groups2,candidates:[...new Set(groups2.flatMap(group=>group.paths))],glob,view:extra.view??!1,...extra.namespaceProblem===void 0?{}:{namespaceProblem:extra.namespaceProblem},...extra.hashProblem===void 0?{}:{hashProblem:extra.hashProblem}}),single=candidate=>glob?[{paths:[candidate],glob:!0}]:literalGroups(candidate);if(path30.isAbsolute(substituted))return finish4(single(path30.normalize(substituted)));let{key,rest}=splitAliasKey(substituted);if(key.startsWith("#")&&Object.prototype.hasOwnProperty.call(env.views,key))return planView(key,rest,glob,context,env,finish4);let groups=[],namespaceProblem,hashProblem;if(key&&Object.prototype.hasOwnProperty.call(env.aliases,key))for(let base of env.aliases[key])groups.push(...single(path30.resolve(base,rest)));else if(key.startsWith("#")&&rest.length>0){let known=[...Object.keys(env.aliases),...Object.keys(env.views)].filter(name=>name.startsWith("#"));hashProblem=`There is no built-in name "${key}" available here.
1097
1098
  `+(known.length>0?`Available names: ${known.sort().join(", ")}.`:"No '#' names are available in this project.")}if(env.namespaceResolver&&substituted.startsWith("~")&&substituted.length>1&&substituted.includes("/")){let reference=withQuery.slice(1),resolution=env.namespaceResolver.resolve({reference,fromFile:context.fromFile});resolution.kind==="candidates"&&resolution.glob===!0?groups.push({paths:[...resolution.candidates],glob:!0,...resolution.roots===void 0?{}:{roots:resolution.roots}}):resolution.kind==="candidates"&&resolution.candidates.length>0?resolution.candidates.forEach((candidate,index)=>{groups.push(...literalGroups(path30.normalize(candidate),resolution.roots?.[index]))}):resolution.kind!=="candidates"&&(namespaceProblem={reference,fromFile:context.fromFile,resolution})}return groups.push(...single(path30.resolve(baseDir,substituted))),finish4(groups,{...namespaceProblem===void 0?{}:{namespaceProblem},...hashProblem===void 0?{}:{hashProblem}})}function planView(key,wanted,glob,context,env,finish4){let includingRecipe=env.namespaceResolver?.includingRecipe?.(context.fromFile)??null;if(includingRecipe!==null)return finish4([],{view:!0,hashProblem:`The recipe "${includingRecipe}" may not include "${key}", because a view lists other recipes' files.
@@ -1130,7 +1131,7 @@ ${result.candidates.map(candidate=>` - ${candidate}`).join(`
1130
1131
  ${messageOf4(counterError)}`;ctx.reporter.problem(message2,{},LogLevel5.Warning),problems.push({level:"warning",message:message2})}let run=new CompileRun(deps,{strict,...input.rebuild?{rebuild:!0}:{},dryRun:dryRun4,...ctx.chain===void 0?{}:{run:ctx.chain.id}}),units=expanded.units;if(input.changedFiles!==void 0){let changed2=new Set(input.changedFiles.map(file2=>path35.resolve(runtime.projectRoot(),file2)));units=units.filter(unit=>run.reads(unit,changed2)),units.length===0&&ctx.reporter.detail(`No targets affected by change to ${input.changedFiles.join(", ")}; nothing compiled`)}try{let result=await run.run(units),allProblems=[...problems,...result.problems],errors=allProblems.filter(problem=>problem.level==="error").length;return await ctx.services.get("compiler.writer").commit({dryRun:dryRun4}),input.targets===void 0&&input.changedFiles===void 0&&(runtime.produced=result.produced),input.reportEnd!==!1&&ctx.reporter.operationEnd(errors>0?`Done with ${errors} error(s).`:"Done.",errors===0),await ctx.emit("compiler.wrote",{files:result.outputs,dryRun:dryRun4}),{ok:errors===0&&(!strict||allProblems.every(problem=>problem.level!=="warning")),outputs:result.outputs,problems:allProblems,notWritten:[...result.notWritten],included:[...result.included],durationMs:performance.now()-started}}finally{counter?.free()}}async function producedNow(runtime,ctx){if(runtime.produced)return runtime.produced;let expanded=unitsOf(runtime.settings(),{resolver:runtime.resolver(),projectRoot:runtime.projectRoot()}),{deps}=await runDependencies(runtime,ctx,nullReporter2,!1);return(await new CompileRun(deps,{dryRun:!0}).run(expanded.units)).produced}function isDirectWrite(entry){return entry.target===void 0&&entry.origin?.plugin!==void 0}async function prune(input,ctx,runtime){return IntentOutputs8.of(await pruneOutputs(input,ctx,runtime))}async function pruneOutputs(input,ctx,runtime){let dryRun4=input.dryRun??!1,store2=runtime.store();store2.refresh();let entries=ctx.services.get("compiler.state").entries(),protectedRoots=runtime.protectedRoots(),keep=input.all?new Set:await producedNow(runtime,ctx),candidates=entries.filter(entry=>input.all||!isDirectWrite(entry)).map(entry=>path35.resolve(entry.dest)).filter(dest=>!keep.has(dest)&&!isProtectedPath(dest,protectedRoots)),writer=ctx.services.get("compiler.writer"),{removed,dirsRemoved,backedUp}=await writer.remove(candidates,{dryRun:dryRun4,...ctx.chain===void 0?{}:{run:ctx.chain.id}}),backups=new Map((backedUp??[]).map(entry=>[entry.file,entry.backup]));if(input.report!==!1&&removed.length>0){ctx.reporter.stepStart(dryRun4?"Outputs that would be removed":"Removed outputs");for(let file2 of removed){let backup=backups.get(file2);backup!==void 0&&reportBackup(ctx.reporter,file2,backup,dryRun4),ctx.reporter.operation(dryRun4?"would-remove":"removed",file2)}}else for(let[file2,backup]of backups)reportBackup(ctx.reporter,file2,backup,dryRun4);return dryRun4||(input.all?store2.delete():await writer.commit()),await ctx.emit("compiler.pruned",{removed,dryRun:dryRun4}),{removed,dirsRemoved,...backedUp===void 0?{}:{backedUp},dryRun:dryRun4}}function messageOf4(error51){return error51 instanceof Error?error51.message:String(error51)}import path36 from"node:path";async function globFiles(globs,options2){let include=options2.include?.length?options2.include:["**/*"],matches=await globs.match(include,{cwd:options2.root,ignore:options2.exclude??[],onlyFiles:!0,dot:!0});return[...new Set(matches.map(match2=>match2.split(path36.sep).join("/")))].sort((a,b)=>a.localeCompare(b)).map(relPath=>{let absPath=path36.resolve(options2.root,relPath);return{path:absPath,dir:path36.dirname(absPath),relPath,name:path36.basename(absPath)}})}function parseGlobList(value){return value?value.split(",").map(pattern=>pattern.trim()).filter(pattern=>pattern.length>0):[]}import{pathToFileURL as pathToFileURL4}from"node:url";async function importNamedExport(absPath,exportName,onError){try{return(await import(pathToFileURL4(absPath).href))[exportName]}catch(error51){onError?.(absPath,error51);return}}var FALLBACK_HIDDEN="(hidden)";function secretCheck(ctx){let secrets=ctx.services.has("variables.secrets")?ctx.services.get("variables.secrets"):void 0;return secrets?{hiddenValue:secrets.hiddenValue,isSecret:(name,value)=>secrets.isSecret(name,value,ctx.secretNames)}:{hiddenValue:FALLBACK_HIDDEN,isSecret:(name,value)=>typeof value=="string"&&value.length>0&&ctx.secretNames.has(name)}}function sortObjectKeys(value){return Object.keys(value).sort().reduce((acc,key)=>(acc[key]=value[key],acc),{})}function splitPositionalName(args){let lead=args.match(/^\s*([a-zA-Z_][\w]*)(\s*=)?/);return lead&&!lead[2]?{name:lead[1],rest:args.slice(lead[0].length).trim()}:{name:null,rest:args.trim()}}function globsOf(ctx){return ctx.services.get("host.globs")}function isScalar2(value){return typeof value=="string"||typeof value=="boolean"||typeof value=="number"&&Number.isFinite(value)}var showVarsTag={id:"showVars",description:"Dumps every variable in scope as a fenced JSON block, secrets hidden.",tag(ctx){let secrets=secretCheck(ctx);return{parse(){},render(liquidCtx){let seen=new WeakSet,scope=sortObjectKeys(liquidCtx.getAll());return"# Sous Debug: Variable Dump\n```json\n"+JSON.stringify(scope,(key,value)=>{if(typeof value=="object"&&value!==null){if(seen.has(value))return"[Circular]";seen.add(value)}return key!==""&&secrets.isSecret(key,value)?secrets.hiddenValue:value},2)+"\n```"}}}},exportScalarVarsJsTag={id:"exportScalarVarsJs",description:"Writes every scalar variable in scope as an ES module default export, secrets left out.",tag(ctx){let secrets=secretCheck(ctx);return{parse(){},render(liquidCtx){let scalars={};for(let[key,value]of Object.entries(liquidCtx.getAll()))isScalar2(value)&&!secrets.isSecret(key,value)&&(scalars[key]=value);return`export default ${JSON.stringify(sortObjectKeys(scalars),null,2)};
1131
1132
  `}}}};async function resolveFiles(tag,ctx,hash2){let root=hash2.root!=null?String(hash2.root):"";if(!root)throw new Error(`${tag}: a "root" attribute is required`);return globFiles(globsOf(ctx),{root,include:parseGlobList(hash2.include!=null?String(hash2.include):void 0),exclude:parseGlobList(hash2.exclude!=null?String(hash2.exclude):void 0)})}async function attachImports(files,importName){return(await Promise.all(files.map(async file2=>{let value=await importNamedExport(file2.path,importName);return value===void 0?null:{...file2,[importName]:value}}))).filter(file2=>file2!==null)}var getFilesTag={id:"getFiles",description:"Finds files under a root and assigns them to a variable, optionally with an export of each.",tag(ctx){return{parse(token){let{name,rest}=splitPositionalName(token.args);this.varName=name,this.hash=new Hash(rest,!0)},*render(liquidCtx){let hash2=yield this.hash.render(liquidCtx),files=yield resolveFiles("getFiles",ctx,hash2),importName=hash2.import!=null?String(hash2.import).trim():"";return importName&&(files=yield attachImports(files,importName)),this.varName&&(liquidCtx.bottom()[this.varName]=files),""}}}},listFilesTag={id:"listFiles",description:"Renders the files under a root as a bullet list.",tag(ctx){return{parse(token){this.hash=new Hash(token.args,!0)},*render(liquidCtx){let hash2=yield this.hash.render(liquidCtx),files=yield resolveFiles("listFiles",ctx,hash2),relative4=String(hash2.relative??"")==="true";return files.map(file2=>`- ${relative4?file2.relPath:file2.name}`).join(`
1132
1133
  `)}}}},bulletListFilter={id:"bulletList",description:"Turns an array into a Markdown bullet list.",filter(){return items2=>Array.isArray(items2)?items2.map(item=>`- ${String(item)}`).join(`
1133
- `):String(items2)}},BUILT_IN_TAGS=[showVarsTag,exportScalarVarsJsTag,getFilesTag,listFilesTag],BUILT_IN_FILTERS=[bulletListFilter];import path37 from"node:path";import{isDeepStrictEqual}from"node:util";function soleHarness2(target){let marks=new Set((target.outputs??[]).map(output=>output.harness)),[mark]=marks;return marks.size===1&&typeof mark=="string"?mark:void 0}function withHarnessFiles(settings,config2){let listing=settings.listing;if(listing===void 0||typeof config2.forHarness!="function"||(config2.harnesses??[]).length===0)return settings;let files=[],problems=[],fromHarness=[];return settings.targets.forEach((target,index)=>{let harness=soleHarness2(target);if(index<listing.targets||target.id===void 0||harness===void 0)return;let own=config2.forHarness(harness)?.get("compilation"),ownTargets=own?.targets??[],ownIndex=ownTargets.findIndex(candidate=>candidate.id===target.id);if(ownIndex===-1||own?.listing===void 0||ownIndex>=own.listing.targets)return;let ownOutputs=ownTargets[ownIndex].outputs??[],place=output=>target.outputs.findIndex(kept=>isDeepStrictEqual(kept,ownOutputs[output]));for(let file2 of own.files??[]){let output=file2.targetIndex===ownIndex?place(file2.output):-1;output!==-1&&files.push({...file2,targetIndex:index,output})}for(let problem of own.listing.problems)problem.targetIndex===ownIndex&&problems.push({...problem,targetIndex:index});fromHarness.push(index)}),fromHarness.length===0?settings:{...settings,files:[...settings.files??[],...files],listing:{...listing,problems:[...listing.problems,...problems],fromHarness}}}init_zod();init_src2();var DEFAULT_STATE_FILE="${sousDir}/sous.state.json",varsSchema=external_exports.record(external_exports.string(),external_exports.string());function ifReplacement(output){let{_if:conditions,...rest}=output;return`{ "$if": { "expr": ${JSON.stringify(ifExpression(conditions))}, "then": ${JSON.stringify(rest)} } }`}var outputSchema=external_exports.object({_if:external_exports.unknown().optional().describe('Removed. Write the condition as a config expression on the output: { "$if": { "expr": "...", "then": { ...the output... } } }.'),_vars:varsSchema.optional(),destinationFile:external_exports.string().optional(),destinationDir:external_exports.string().optional(),transforms:external_exports.array(external_exports.string()).optional(),harness:external_exports.string().min(1).optional().describe("The harness this output belongs to (claude-code, codex). Templates read it as harness.id."),backupExisting:external_exports.boolean().optional().describe("When true, a file sous did not write at the destination is backed up, a warning is given, and it is overwritten, whatever compilation.overwriteUntracked says.")}).strict().superRefine((output,ctx)=>{if(output._if===void 0)return;let shadowed=(output._if!==null&&typeof output._if=="object"?Object.keys(output._if):[]).filter(name=>name==="env"||name==="host");ctx.addIssue({code:"custom",path:["_if"],message:`'_if' was removed; a config expression on the output replaces it. Write the output as ${ifReplacement(output)}. The expression reads variables by their bare name, as every config expression does.`+(shadowed.length>0?` An expression reads ${shadowed.map(name=>`'${name}'`).join(" and ")} as sous's own value (the environment, the machine), so rename that variable first.`:"")})}),originSchema=external_exports.object({plugin:external_exports.string().optional(),recipe:external_exports.string().optional(),repository:external_exports.string().optional()}).strict(),targetSchema=external_exports.object({id:external_exports.string().min(1).optional(),_vars:varsSchema.optional(),entryPoint:external_exports.string().optional(),entryGlob:external_exports.string().optional(),content:external_exports.string().optional(),globBase:external_exports.string().optional(),includeSourceComments:external_exports.boolean().optional(),generateRuntimeContext:external_exports.boolean().optional(),transforms:external_exports.array(external_exports.string()).optional(),origin:originSchema.optional(),outputs:external_exports.array(outputSchema)}).strict().superRefine((target,ctx)=>{[target.entryPoint,target.entryGlob,target.content].filter(source=>source!==void 0).length!==1&&ctx.addIssue({code:"custom",message:"a target must have exactly one of 'entryPoint', 'entryGlob' or 'content'"}),target.content!==void 0&&target.id===void 0&&ctx.addIssue({code:"custom",path:["id"],message:"a target whose source is 'content' needs an 'id', which names it in errors"})}),fileSchema=external_exports.object({target:external_exports.string(),targetIndex:external_exports.number().int().min(0),source:external_exports.string(),output:external_exports.number().int().min(0),destination:external_exports.string(),harness:external_exports.string().optional(),_vars:varsSchema.optional()}).strict(),listingSchema=external_exports.object({targets:external_exports.number().int().min(0),problems:external_exports.array(external_exports.object({level:external_exports.enum(["error","warning"]),message:external_exports.string(),target:external_exports.string().optional(),file:external_exports.string().optional(),line:external_exports.number().optional(),targetIndex:external_exports.number().int().min(0).optional()}).strict())}).strict(),patternsSchema=external_exports.union([external_exports.string().min(1),external_exports.array(external_exports.string().min(1)).min(1)]),varOverrideSchema=external_exports.object({match:patternsSchema.describe("The output paths the rule applies to: a glob, or a regular expression written /.../, or a list of them."),exclude:patternsSchema.optional().describe("Output paths the rule leaves out, though match takes them."),_vars:varsSchema.describe("The variables to set. They win over the output's own _vars; a later rule wins over an earlier one.")}).strict().superRefine((rule,ctx)=>{for(let key of["match","exclude"]){let value=rule[key];(value===void 0?[]:typeof value=="string"?[value]:value).forEach((entry,index)=>{try{compilePatternList([entry],typeof value=="string"?key:`${key}[${index}]`,()=>!1)}catch(error51){ctx.addIssue({code:"custom",path:typeof value=="string"?[key]:[key,index],message:error51 instanceof Error?error51.message:String(error51)})}})}}),compilationSchema=external_exports.object({_vars:varsSchema.optional(),varOverrides:external_exports.array(varOverrideSchema).default([]).describe("Variables for every output whose path matches a pattern, outputs a plugin or a recipe added included. A rule wins over the output's own _vars."),files:external_exports.array(fileSchema).optional().describe("Every file a build writes, listed while the config is built. Set by sous; anything written here is replaced."),listing:listingSchema.optional().describe("What listing compilation.files found. Set by sous."),includeSourceComments:external_exports.boolean().default(!1),overwriteUntracked:external_exports.boolean().default(!0).describe("Overwrite an output file sous did not write, and take it over. Sous copies the file to <sousDir>/backups/ first. With false, the file is left alone and the build warns."),stateFile:external_exports.string().default(DEFAULT_STATE_FILE).describe("Where sous records every file it wrote and the hash of what it wrote, which tells prune and clear what is theirs to remove and which outputs were edited by hand."),targets:external_exports.array(targetSchema).default([])}).strict(),aliasesSchema=external_exports.record(external_exports.string(),external_exports.union([external_exports.string(),external_exports.array(external_exports.string())])).superRefine((aliases2,ctx)=>{for(let name of Object.keys(aliases2))isReservedAliasName(name)&&ctx.addIssue({code:"custom",path:[name],message:`Alias "${name}" is invalid: names beginning with "~" or "#" are reserved ("~" for the home directory and recipe namespaces, "#" for built-in names).`})}),CONFIG_KEYS2=[{id:"compilation",schema:compilationSchema,description:"What to compile: targets, their outputs, source comments, the state file, overwriting files sous did not write. Content sous did not produce is backed up to <sousDir>/backups/ before it is overwritten or removed."},{id:"_aliases",schema:aliasesSchema.optional(),description:"Include aliases: a name to one base directory or several, tried in order."}];function compilationSettings(config2){let value=config2.get("compilation")??{};return{...value,includeSourceComments:value.includeSourceComments??!1,overwriteUntracked:value.overwriteUntracked??!0,stateFile:value.stateFile??DEFAULT_STATE_FILE,targets:value.targets??[]}}var CompilerRuntime=class{constructor(source,stores,clock=new BackupClock){this.source=source;this.stores=stores;this.clock=clock}cachedScope;cachedNames;produced;get serviceContext(){let{plugin,config:config2,services,entities,project,env}=this.source;return{plugin,config:config2,services,entities,project,env}}settings(){return withHarnessFiles(compilationSettings(this.source.config),this.source.config)}resolver(){let resolver=this.source.services.get("variables.resolver"),config2=this.source.config;return new Proxy(resolver,{get(target,key){if(key==="scope")return request=>target.scopeIn(config2,request);let value=Reflect.get(target,key,target);return typeof value=="function"?value.bind(target):value}})}globs(){return this.source.services.get("host.globs")}projectRoot(){return this.source.project?.root??path37.resolve("/")}rootScope(){return this.cachedScope??=this.resolver().scope(),this.cachedScope}namespaceResolver(){return this.source.services.has("compiler.namespace-resolver")?this.source.services.get("compiler.namespace-resolver"):void 0}hashNames(){if(this.cachedNames)return this.cachedNames;let context={...this.serviceContext,scope:this.rootScope()},aliases2={},views={};for(let entity of this.source.entities.list("hash-name")){let name=`#${entity.id}`;entity.view?views[name]=entity.view(context):aliases2[name]=(entity.bases?.(context)??[]).map(base=>path37.resolve(this.projectRoot(),base))}return this.cachedNames={aliases:aliases2,views},this.cachedNames}aliases(){let resolver=this.resolver(),scope=this.rootScope(),user=this.source.config.get("_aliases");return buildAliasMap({builtIns:this.hashNames().aliases,userAliases:[user],substitute:text=>path37.resolve(this.projectRoot(),resolver.normalizePath(resolver.substitute(text,scope)))})}views(){return this.hashNames().views}includeEnvironment(){let resolver=this.resolver(),home=this.source.env.HOME;return{aliases:this.aliases(),views:this.views(),globs:this.globs(),namespaceResolver:this.namespaceResolver(),substitute:(text,scope)=>resolver.substitute(text,scope),...home?{home}:{}}}stateFile(){let scope=this.rootScope(),resolver=this.resolver(),written=scope.stateFilePath??this.settings().stateFile??DEFAULT_STATE_FILE;return path37.resolve(this.projectRoot(),resolver.normalizePath(resolver.substitute(written,scope)))}store(){let file2=this.stateFile(),store2=this.stores.get(file2);return store2||(store2=new StateStore(file2,this.projectRoot()),this.stores.set(file2,store2)),store2}backups(){let dir=this.source.project?path37.join(this.source.project.sousDir,"backups"):path37.join(path37.dirname(this.stateFile()),"backups");return new Backups(dir,this.source.project?.root,this.clock)}protectedRoots(){let roots=[];if(this.source.project&&roots.push(path37.join(this.source.project.sousDir,"repos")),this.source.services.has("host.sous-home")){let home=this.source.services.get("host.sous-home").paths(this.source.env);roots.push(home.repos,home.store)}return roots}},RuntimeCache=class{runtimes=new WeakMap;stores=new Map;clock=new BackupClock;for(source){let runtime=this.runtimes.get(source.config);return runtime||(runtime=new CompilerRuntime(source,this.stores,this.clock),this.runtimes.set(source.config,runtime)),runtime}};import fs28 from"node:fs";import path38 from"node:path";var WriterService=class{constructor(store2,settings){this.store=store2;this.settings=settings;this.backups=settings.backups??new Backups(path38.join(path38.dirname(store2.file),"backups"),store2.projectRoot)}backups;async write(file2,content,options2){let dest=path38.resolve(file2),data=typeof content=="string"?Buffer.from(content,"utf8"):Buffer.from(content.buffer,content.byteOffset,content.byteLength),bytes=data.byteLength,tracked=this.store.entry(dest),exists3=fs28.existsSync(dest),base={file:dest,bytes,...options2.target===void 0?{}:{target:options2.target},...options2.origin===void 0?{}:{origin:options2.origin}},current=exists3?readBytes2(dest):void 0,sameContent=current!==void 0&&current.equals(data);if(exists3&&tracked===void 0&&!(options2.overwriteUntracked??this.settings.overwriteUntracked))return{...base,action:"skipped-untracked"};let backUp=current!==void 0&&!sameContent&&!isOwnContent(current,tracked);if(options2.dryRun){let action=exists3?sameContent&&!options2.force?"unchanged":"would-update":"would-create";return{...base,action,...backUp?{backup:this.backups.plan(dest,options2.run)}:{}}}let entry={dest,srcHash:options2.sourceHash??hashContent(options2.source),destHash:hashContent(data),size:bytes,builtAt:new Date().toISOString(),...options2.target===void 0?{}:{target:options2.target},...options2.origin===void 0?{}:{origin:options2.origin}};if(sameContent&&!options2.force)return this.store.record(tracked===void 0?entry:{...entry,builtAt:tracked.builtAt}),this.applyMode(dest,options2.mode),{...base,action:"unchanged"};let backup=backUp?this.backups.copy(dest,options2.run):void 0;return this.ensureDir(path38.dirname(dest)),fs28.writeFileSync(dest,data),options2.mode!==void 0?this.applyMode(dest,options2.mode):dest.endsWith(".sh")&&fs28.chmodSync(dest,493),this.store.record(entry),{...base,action:exists3?"updated":"created",...backup===void 0?{}:{backup}}}applyMode(dest,mode){if(mode!==void 0)try{(fs28.statSync(dest).mode&4095)!==(mode&4095)&&fs28.chmodSync(dest,mode&4095)}catch{}}async remove(files,options2={}){let removed=[],backedUp=[];for(let file2 of files){let dest=path38.resolve(file2),tracked=this.store.entry(dest);if(isProtectedPath(dest,this.settings.protectedRoots)||tracked===void 0)continue;removed.push(dest);let current=fs28.existsSync(dest)?readBytes2(dest):void 0,backUp=current!==void 0&&!isOwnContent(current,tracked);if(options2.dryRun){backUp&&backedUp.push({file:dest,backup:this.backups.plan(dest,options2.run)});continue}backUp&&backedUp.push({file:dest,backup:this.backups.copy(dest,options2.run)}),fs28.existsSync(dest)&&fs28.rmSync(dest),this.store.forget(dest)}let dirsRemoved=options2.dryRun?[]:this.removeEmptyDirs();return{removed,dirsRemoved,...backedUp.length===0?{}:{backedUp}}}async commit(options2={}){this.store.commit(options2)}ensureDir(dir){let missing=[],walk3=dir;for(;!fs28.existsSync(walk3);){missing.unshift(walk3);let parent=path38.dirname(walk3);if(parent===walk3)break;walk3=parent}if(missing.length!==0){fs28.mkdirSync(dir,{recursive:!0});for(let created of missing)this.store.recordDir(created)}}removeEmptyDirs(){let dirs=[...this.store.current().dirs].sort((a,b)=>b.split(path38.sep).length-a.split(path38.sep).length),removed=[];for(let dir of dirs)if(!isProtectedPath(dir,this.settings.protectedRoots))try{fs28.existsSync(dir)&&fs28.readdirSync(dir).length===0&&(fs28.rmdirSync(dir),removed.push(dir))}catch{}return removed}};function isOwnContent(current,tracked){return tracked!==void 0&&hashContent(current)===tracked.destHash}function readBytes2(file2){try{return fs28.readFileSync(file2)}catch{return}}var package_default11={name:"@sous-io/sous-plugin-compiler",version:"1.1.4",description:"Compiling templates, includes, aliases, compilation settings, the built-in tags and filters, the state file, writing outputs, pruning.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-lib-documents":"workspace:*","@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@sous-io/sous-plugin-liquid":"workspace:*","@sous-io/sous-plugin-refs":"workspace:*","@sous-io/sous-plugin-variables":"workspace:*","@sous-io/sous-plugin-migrations":"workspace:*",liquidjs:"^10.25.0",tiktoken:"^1.0.22",zod:"^4.4.3"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*",glob:"^13.0.6",minimatch:"^10.2.4"},engines:{node:">=22"}};var PLUGIN_NAME10="@sous-io/sous-plugin-compiler",transformSchema={"~standard":{version:1,vendor:"sous",validate:value=>{let entry=value;return typeof entry?.id=="string"&&typeof entry.transform=="function"?{value}:{issues:[{message:"A compilation-transform entity needs an id and a transform function."}]}}}},compileInput=jsonSchema10({type:"object",properties:{targets:{type:"array",items:{anyOf:[{type:"string"},{type:"integer"}]},description:"Only these targets, by id or index."},changedFiles:{type:"array",items:{type:"string"},description:"Only the targets whose sources include one of these files."},strict:{type:"boolean",description:"Warnings fail the compile."},rebuild:{type:"boolean",description:"Writes every output, changed or not."},dryRun:{type:"boolean",description:"Writes nothing."},reportEnd:{type:"boolean",description:"Ends the report with 'Done.'. Default: true."}},additionalProperties:!1}),pruneInput=jsonSchema10({type:"object",properties:{all:{type:"boolean",description:"Removes every file the compiler wrote, not only those no target produces."},dryRun:{type:"boolean",description:"Removes nothing."},report:{type:"boolean",description:"Reports each removed file as progress. Default: true."}},additionalProperties:!1}),compilerPlugin=definePlugin11({name:PLUGIN_NAME10,version:package_default11.version,description:"Compiling templates, includes, aliases, compilation settings, the built-in tags and filters, the state file, writing outputs, pruning.",implementable:["compiler.namespace-resolver"],dependsOn:{"@sous-io/sous-plugin-liquid":`^${package_default11.version}`,"@sous-io/sous-plugin-refs":`^${package_default11.version}`,"@sous-io/sous-plugin-variables":`^${package_default11.version}`,"@sous-io/sous-plugin-host":`^${package_default11.version}`},register(sous){let runtimes=new RuntimeCache;sous.entities.define("compilation-transform",transformSchema,{description:"A change to an output's path or contents before it is written."});for(let key of CONFIG_KEYS2)sous.entities.add("config-key",key);for(let tag of BUILT_IN_TAGS)sous.entities.add("liquid-tag",tag);for(let filter3 of BUILT_IN_FILTERS)sous.entities.add("liquid-filter",filter3);sous.migrations?.add(ifMigration),sous.config.contribute(filesContributor({plugin:PLUGIN_NAME10,services:sous.services})),sous.config.contribute(varOverridesContributor({services:sous.services})),sous.services.add("compiler.aliases",(_config,ctx)=>new AliasService(runtimes.for(ctx).aliases()),{lifetime:"config"}),sous.services.add("compiler.includes",(_config,ctx)=>new IncludeService(runtimes.for(ctx).includeEnvironment()),{lifetime:"config"}),sous.services.add("compiler.state",(_config,ctx)=>new StateService(runtimes.for(ctx).store()),{lifetime:"config"}),sous.services.add("compiler.writer",(_config,ctx)=>{let runtime=runtimes.for(ctx);return new WriterService(runtime.store(),{overwriteUntracked:runtime.settings().overwriteUntracked,protectedRoots:runtime.protectedRoots(),backups:runtime.backups()})},{lifetime:"config"}),sous.intents.add({intent:"compiler.compile",needsRecipeFiles:!0,summary:"Compile every compilation target into its outputs",internal:!0,input:compileInput,handle:(input,ctx)=>compile(input,ctx,runtimes.for(ctx))}),sous.intents.add({intent:"compiler.prune",needsRecipeFiles:!0,summary:"Remove outputs no compilation target produces any more",internal:!0,input:pruneInput,handle:(input,ctx)=>prune(input,ctx,runtimes.for(ctx))})}});init_src6();import{definePlugin as definePlugin13,jsonSchema as jsonSchema17}from"@sous-io/sous-plugin-api";import path61 from"node:path";import{ConfigError as ConfigError41}from"@sous-io/sous-plugin-api";import{Worker}from"node:worker_threads";var DEFAULT_PATTERN_BUDGET_MS=100,STARTUP_GRACE_MS=5e3,STATUS=0,STARTED=1,PENDING=0,MATCHED=1,DID_NOT_MATCH=2,FAILED=3,WORKER_SOURCE=`
1134
+ `):String(items2)}},BUILT_IN_TAGS=[showVarsTag,exportScalarVarsJsTag,getFilesTag,listFilesTag],BUILT_IN_FILTERS=[bulletListFilter];import path37 from"node:path";import{isDeepStrictEqual}from"node:util";function soleHarness2(target){let marks=new Set((target.outputs??[]).map(output=>output.harness)),[mark]=marks;return marks.size===1&&typeof mark=="string"?mark:void 0}function withHarnessFiles(settings,config2){let listing=settings.listing;if(listing===void 0||typeof config2.forHarness!="function"||(config2.harnesses??[]).length===0)return settings;let files=[],problems=[],fromHarness=[];return settings.targets.forEach((target,index)=>{let harness=soleHarness2(target);if(index<listing.targets||target.id===void 0||harness===void 0)return;let own=config2.forHarness(harness)?.get("compilation"),ownTargets=own?.targets??[],ownIndex=ownTargets.findIndex(candidate=>candidate.id===target.id);if(ownIndex===-1||own?.listing===void 0||ownIndex>=own.listing.targets)return;let ownOutputs=ownTargets[ownIndex].outputs??[],place=output=>target.outputs.findIndex(kept=>isDeepStrictEqual(kept,ownOutputs[output]));for(let file2 of own.files??[]){let output=file2.targetIndex===ownIndex?place(file2.output):-1;output!==-1&&files.push({...file2,targetIndex:index,output})}for(let problem of own.listing.problems)problem.targetIndex===ownIndex&&problems.push({...problem,targetIndex:index});fromHarness.push(index)}),fromHarness.length===0?settings:{...settings,files:[...settings.files??[],...files],listing:{...listing,problems:[...listing.problems,...problems],fromHarness}}}init_zod();init_src2();var DEFAULT_STATE_FILE="${sousDir}/sous.state.json",varsSchema=external_exports.record(external_exports.string(),external_exports.string());function ifReplacement(output){let{_if:conditions,...rest}=output;return`{ "$if": { "expr": ${JSON.stringify(ifExpression(conditions))}, "then": ${JSON.stringify(rest)} } }`}var outputSchema=external_exports.object({_if:external_exports.unknown().optional().describe('Removed. Write the condition as a config expression on the output: { "$if": { "expr": "...", "then": { ...the output... } } }.'),_vars:varsSchema.optional(),destinationFile:external_exports.string().optional(),destinationDir:external_exports.string().optional(),transforms:external_exports.array(external_exports.string()).optional(),harness:external_exports.string().min(1).optional().describe("The harness this output belongs to (claude-code, codex). Templates read it as harness.id."),backupExisting:external_exports.boolean().optional().describe("When true, a file sous did not write at the destination is backed up, a warning is given, and it is overwritten, whatever compilation.overwriteUntracked says.")}).strict().superRefine((output,ctx)=>{if(output._if===void 0)return;let shadowed=(output._if!==null&&typeof output._if=="object"?Object.keys(output._if):[]).filter(name=>name==="env"||name==="host");ctx.addIssue({code:"custom",path:["_if"],message:`'_if' was removed; a config expression on the output replaces it. Write the output as ${ifReplacement(output)}. The expression reads variables by their bare name, as every config expression does.`+(shadowed.length>0?` An expression reads ${shadowed.map(name=>`'${name}'`).join(" and ")} as sous's own value (the environment, the machine), so rename that variable first.`:"")})}),originSchema=external_exports.object({plugin:external_exports.string().optional(),recipe:external_exports.string().optional(),repository:external_exports.string().optional()}).strict(),targetSchema=external_exports.object({id:external_exports.string().min(1).optional(),_vars:varsSchema.optional(),entryPoint:external_exports.string().optional(),entryGlob:external_exports.string().optional(),content:external_exports.string().optional(),globBase:external_exports.string().optional(),includeSourceComments:external_exports.boolean().optional(),generateRuntimeContext:external_exports.boolean().optional(),transforms:external_exports.array(external_exports.string()).optional(),origin:originSchema.optional(),outputs:external_exports.array(outputSchema)}).strict().superRefine((target,ctx)=>{[target.entryPoint,target.entryGlob,target.content].filter(source=>source!==void 0).length!==1&&ctx.addIssue({code:"custom",message:"a target must have exactly one of 'entryPoint', 'entryGlob' or 'content'"}),target.content!==void 0&&target.id===void 0&&ctx.addIssue({code:"custom",path:["id"],message:"a target whose source is 'content' needs an 'id', which names it in errors"})}),fileSchema=external_exports.object({target:external_exports.string(),targetIndex:external_exports.number().int().min(0),source:external_exports.string(),output:external_exports.number().int().min(0),destination:external_exports.string(),harness:external_exports.string().optional(),_vars:varsSchema.optional()}).strict(),listingSchema=external_exports.object({targets:external_exports.number().int().min(0),problems:external_exports.array(external_exports.object({level:external_exports.enum(["error","warning"]),message:external_exports.string(),target:external_exports.string().optional(),file:external_exports.string().optional(),line:external_exports.number().optional(),targetIndex:external_exports.number().int().min(0).optional()}).strict())}).strict(),patternsSchema=external_exports.union([external_exports.string().min(1),external_exports.array(external_exports.string().min(1)).min(1)]),varOverrideSchema=external_exports.object({match:patternsSchema.describe("The output paths the rule applies to: a glob, or a regular expression written /.../, or a list of them."),exclude:patternsSchema.optional().describe("Output paths the rule leaves out, though match takes them."),_vars:varsSchema.describe("The variables to set. They win over the output's own _vars; a later rule wins over an earlier one.")}).strict().superRefine((rule,ctx)=>{for(let key of["match","exclude"]){let value=rule[key];(value===void 0?[]:typeof value=="string"?[value]:value).forEach((entry,index)=>{try{compilePatternList([entry],typeof value=="string"?key:`${key}[${index}]`,()=>!1)}catch(error51){ctx.addIssue({code:"custom",path:typeof value=="string"?[key]:[key,index],message:error51 instanceof Error?error51.message:String(error51)})}})}}),compilationSchema=external_exports.object({_vars:varsSchema.optional(),varOverrides:external_exports.array(varOverrideSchema).default([]).describe("Variables for every output whose path matches a pattern, outputs a plugin or a recipe added included. A rule wins over the output's own _vars."),files:external_exports.array(fileSchema).optional().describe("Every file a build writes, listed while the config is built. Set by sous; anything written here is replaced."),listing:listingSchema.optional().describe("What listing compilation.files found. Set by sous."),includeSourceComments:external_exports.boolean().default(!1),overwriteUntracked:external_exports.boolean().default(!0).describe("Overwrite an output file sous did not write, and take it over. Sous copies the file to <sousDir>/backups/ first. With false, the file is left alone and the build warns."),stateFile:external_exports.string().default(DEFAULT_STATE_FILE).describe("Where sous records every file it wrote and the hash of what it wrote, which tells prune and clear what is theirs to remove and which outputs were edited by hand."),targets:external_exports.array(targetSchema).default([])}).strict(),aliasesSchema=external_exports.record(external_exports.string(),external_exports.union([external_exports.string(),external_exports.array(external_exports.string())])).superRefine((aliases2,ctx)=>{for(let name of Object.keys(aliases2))isReservedAliasName(name)&&ctx.addIssue({code:"custom",path:[name],message:`Alias "${name}" is invalid: names beginning with "~" or "#" are reserved ("~" for the home directory and recipe namespaces, "#" for built-in names).`})}),CONFIG_KEYS2=[{id:"compilation",schema:compilationSchema,description:"What to compile: targets, their outputs, source comments, the state file, overwriting files sous did not write. Content sous did not produce is backed up to <sousDir>/backups/ before it is overwritten or removed."},{id:"_aliases",schema:aliasesSchema.optional(),description:"Include aliases: a name to one base directory or several, tried in order."}];function compilationSettings(config2){let value=config2.get("compilation")??{};return{...value,includeSourceComments:value.includeSourceComments??!1,overwriteUntracked:value.overwriteUntracked??!0,stateFile:value.stateFile??DEFAULT_STATE_FILE,targets:value.targets??[]}}var CompilerRuntime=class{constructor(source,stores,clock=new BackupClock){this.source=source;this.stores=stores;this.clock=clock}cachedScope;cachedNames;produced;get serviceContext(){let{plugin,config:config2,services,entities,project,env}=this.source;return{plugin,config:config2,services,entities,project,env}}settings(){return withHarnessFiles(compilationSettings(this.source.config),this.source.config)}resolver(){let resolver=this.source.services.get("variables.resolver"),config2=this.source.config;return new Proxy(resolver,{get(target,key){if(key==="scope")return request=>target.scopeIn(config2,request);let value=Reflect.get(target,key,target);return typeof value=="function"?value.bind(target):value}})}globs(){return this.source.services.get("host.globs")}projectRoot(){return this.source.project?.root??path37.resolve("/")}rootScope(){return this.cachedScope??=this.resolver().scope(),this.cachedScope}namespaceResolver(){return this.source.services.has("compiler.namespace-resolver")?this.source.services.get("compiler.namespace-resolver"):void 0}hashNames(){if(this.cachedNames)return this.cachedNames;let context={...this.serviceContext,scope:this.rootScope()},aliases2={},views={};for(let entity of this.source.entities.list("hash-name")){let name=`#${entity.id}`;entity.view?views[name]=entity.view(context):aliases2[name]=(entity.bases?.(context)??[]).map(base=>path37.resolve(this.projectRoot(),base))}return this.cachedNames={aliases:aliases2,views},this.cachedNames}aliases(){let resolver=this.resolver(),scope=this.rootScope(),user=this.source.config.get("_aliases");return buildAliasMap({builtIns:this.hashNames().aliases,userAliases:[user],substitute:text=>path37.resolve(this.projectRoot(),resolver.normalizePath(resolver.substitute(text,scope)))})}views(){return this.hashNames().views}includeEnvironment(){let resolver=this.resolver(),home=this.source.env.HOME;return{aliases:this.aliases(),views:this.views(),globs:this.globs(),namespaceResolver:this.namespaceResolver(),substitute:(text,scope)=>resolver.substitute(text,scope),...home?{home}:{}}}stateFile(){let scope=this.rootScope(),resolver=this.resolver(),written=scope.stateFilePath??this.settings().stateFile??DEFAULT_STATE_FILE;return path37.resolve(this.projectRoot(),resolver.normalizePath(resolver.substitute(written,scope)))}store(){let file2=this.stateFile(),store2=this.stores.get(file2);return store2||(store2=new StateStore(file2,this.projectRoot()),this.stores.set(file2,store2)),store2}backups(){let dir=this.source.project?path37.join(this.source.project.sousDir,"backups"):path37.join(path37.dirname(this.stateFile()),"backups");return new Backups(dir,this.source.project?.root,this.clock)}protectedRoots(){let roots=[];if(this.source.project&&roots.push(path37.join(this.source.project.sousDir,"repos")),this.source.services.has("host.sous-home")){let home=this.source.services.get("host.sous-home").paths(this.source.env);roots.push(home.repos,home.store)}return roots}},RuntimeCache=class{runtimes=new WeakMap;stores=new Map;clock=new BackupClock;for(source){let runtime=this.runtimes.get(source.config);return runtime||(runtime=new CompilerRuntime(source,this.stores,this.clock),this.runtimes.set(source.config,runtime)),runtime}};import fs28 from"node:fs";import path38 from"node:path";var WriterService=class{constructor(store2,settings){this.store=store2;this.settings=settings;this.backups=settings.backups??new Backups(path38.join(path38.dirname(store2.file),"backups"),store2.projectRoot)}backups;async write(file2,content,options2){let dest=path38.resolve(file2),data=typeof content=="string"?Buffer.from(content,"utf8"):Buffer.from(content.buffer,content.byteOffset,content.byteLength),bytes=data.byteLength,tracked=this.store.entry(dest),exists3=fs28.existsSync(dest),base={file:dest,bytes,...options2.target===void 0?{}:{target:options2.target},...options2.origin===void 0?{}:{origin:options2.origin}},current=exists3?readBytes2(dest):void 0,sameContent=current!==void 0&&current.equals(data);if(exists3&&tracked===void 0&&!(options2.overwriteUntracked??this.settings.overwriteUntracked))return{...base,action:"skipped-untracked"};let backUp=current!==void 0&&!sameContent&&!isOwnContent(current,tracked);if(options2.dryRun){let action=exists3?sameContent&&!options2.force?"unchanged":"would-update":"would-create";return{...base,action,...backUp?{backup:this.backups.plan(dest,options2.run)}:{}}}let entry={dest,srcHash:options2.sourceHash??hashContent(options2.source),destHash:hashContent(data),size:bytes,builtAt:new Date().toISOString(),...options2.target===void 0?{}:{target:options2.target},...options2.origin===void 0?{}:{origin:options2.origin}};if(sameContent&&!options2.force)return this.store.record(tracked===void 0?entry:{...entry,builtAt:tracked.builtAt}),this.applyMode(dest,options2.mode),{...base,action:"unchanged"};let backup=backUp?this.backups.copy(dest,options2.run):void 0;return this.ensureDir(path38.dirname(dest)),fs28.writeFileSync(dest,data),options2.mode!==void 0?this.applyMode(dest,options2.mode):dest.endsWith(".sh")&&fs28.chmodSync(dest,493),this.store.record(entry),{...base,action:exists3?"updated":"created",...backup===void 0?{}:{backup}}}applyMode(dest,mode){if(mode!==void 0)try{(fs28.statSync(dest).mode&4095)!==(mode&4095)&&fs28.chmodSync(dest,mode&4095)}catch{}}async remove(files,options2={}){let removed=[],backedUp=[];for(let file2 of files){let dest=path38.resolve(file2),tracked=this.store.entry(dest);if(isProtectedPath(dest,this.settings.protectedRoots)||tracked===void 0)continue;removed.push(dest);let current=fs28.existsSync(dest)?readBytes2(dest):void 0,backUp=current!==void 0&&!isOwnContent(current,tracked);if(options2.dryRun){backUp&&backedUp.push({file:dest,backup:this.backups.plan(dest,options2.run)});continue}backUp&&backedUp.push({file:dest,backup:this.backups.copy(dest,options2.run)}),fs28.existsSync(dest)&&fs28.rmSync(dest),this.store.forget(dest)}let dirsRemoved=options2.dryRun?[]:this.removeEmptyDirs();return{removed,dirsRemoved,...backedUp.length===0?{}:{backedUp}}}async commit(options2={}){this.store.commit(options2)}ensureDir(dir){let missing=[],walk3=dir;for(;!fs28.existsSync(walk3);){missing.unshift(walk3);let parent=path38.dirname(walk3);if(parent===walk3)break;walk3=parent}if(missing.length!==0){fs28.mkdirSync(dir,{recursive:!0});for(let created of missing)this.store.recordDir(created)}}removeEmptyDirs(){let dirs=[...this.store.current().dirs].sort((a,b)=>b.split(path38.sep).length-a.split(path38.sep).length),removed=[];for(let dir of dirs)if(!isProtectedPath(dir,this.settings.protectedRoots))try{fs28.existsSync(dir)&&fs28.readdirSync(dir).length===0&&(fs28.rmdirSync(dir),removed.push(dir))}catch{}return removed}};function isOwnContent(current,tracked){return tracked!==void 0&&hashContent(current)===tracked.destHash}function readBytes2(file2){try{return fs28.readFileSync(file2)}catch{return}}var package_default11={name:"@sous-io/sous-plugin-compiler",version:"1.1.6",description:"Compiling templates, includes, aliases, compilation settings, the built-in tags and filters, the state file, writing outputs, pruning.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-lib-documents":"workspace:*","@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@sous-io/sous-plugin-liquid":"workspace:*","@sous-io/sous-plugin-refs":"workspace:*","@sous-io/sous-plugin-variables":"workspace:*","@sous-io/sous-plugin-migrations":"workspace:*",liquidjs:"^10.25.0",tiktoken:"^1.0.22",zod:"^4.4.3"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*",glob:"^13.0.6",minimatch:"^10.2.4"},engines:{node:">=22"}};var PLUGIN_NAME10="@sous-io/sous-plugin-compiler",transformSchema={"~standard":{version:1,vendor:"sous",validate:value=>{let entry=value;return typeof entry?.id=="string"&&typeof entry.transform=="function"?{value}:{issues:[{message:"A compilation-transform entity needs an id and a transform function."}]}}}},compileInput=jsonSchema10({type:"object",properties:{targets:{type:"array",items:{anyOf:[{type:"string"},{type:"integer"}]},description:"Only these targets, by id or index."},changedFiles:{type:"array",items:{type:"string"},description:"Only the targets whose sources include one of these files."},strict:{type:"boolean",description:"Warnings fail the compile."},rebuild:{type:"boolean",description:"Writes every output, changed or not."},dryRun:{type:"boolean",description:"Writes nothing."},reportEnd:{type:"boolean",description:"Ends the report with 'Done.'. Default: true."}},additionalProperties:!1}),pruneInput=jsonSchema10({type:"object",properties:{all:{type:"boolean",description:"Removes every file the compiler wrote, not only those no target produces."},dryRun:{type:"boolean",description:"Removes nothing."},report:{type:"boolean",description:"Reports each removed file as progress. Default: true."}},additionalProperties:!1}),compilerPlugin=definePlugin11({name:PLUGIN_NAME10,version:package_default11.version,description:"Compiling templates, includes, aliases, compilation settings, the built-in tags and filters, the state file, writing outputs, pruning.",implementable:["compiler.namespace-resolver"],dependsOn:{"@sous-io/sous-plugin-liquid":`^${package_default11.version}`,"@sous-io/sous-plugin-refs":`^${package_default11.version}`,"@sous-io/sous-plugin-variables":`^${package_default11.version}`,"@sous-io/sous-plugin-host":`^${package_default11.version}`},register(sous){let runtimes=new RuntimeCache;sous.entities.define("compilation-transform",transformSchema,{description:"A change to an output's path or contents before it is written."});for(let key of CONFIG_KEYS2)sous.entities.add("config-key",key);for(let tag of BUILT_IN_TAGS)sous.entities.add("liquid-tag",tag);for(let filter3 of BUILT_IN_FILTERS)sous.entities.add("liquid-filter",filter3);sous.migrations?.add(ifMigration),sous.config.contribute(filesContributor({plugin:PLUGIN_NAME10,services:sous.services})),sous.config.contribute(varOverridesContributor({services:sous.services})),sous.services.add("compiler.aliases",(_config,ctx)=>new AliasService(runtimes.for(ctx).aliases()),{lifetime:"config"}),sous.services.add("compiler.includes",(_config,ctx)=>new IncludeService(runtimes.for(ctx).includeEnvironment()),{lifetime:"config"}),sous.services.add("compiler.state",(_config,ctx)=>new StateService(runtimes.for(ctx).store()),{lifetime:"config"}),sous.services.add("compiler.writer",(_config,ctx)=>{let runtime=runtimes.for(ctx);return new WriterService(runtime.store(),{overwriteUntracked:runtime.settings().overwriteUntracked,protectedRoots:runtime.protectedRoots(),backups:runtime.backups()})},{lifetime:"config"}),sous.intents.add({intent:"compiler.compile",needsRecipeFiles:!0,summary:"Compile every compilation target into its outputs",internal:!0,input:compileInput,handle:(input,ctx)=>compile(input,ctx,runtimes.for(ctx))}),sous.intents.add({intent:"compiler.prune",needsRecipeFiles:!0,summary:"Remove outputs no compilation target produces any more",internal:!0,input:pruneInput,handle:(input,ctx)=>prune(input,ctx,runtimes.for(ctx))})}});init_src6();import{definePlugin as definePlugin13,jsonSchema as jsonSchema17}from"@sous-io/sous-plugin-api";import path61 from"node:path";import{ConfigError as ConfigError41}from"@sous-io/sous-plugin-api";import{Worker}from"node:worker_threads";var DEFAULT_PATTERN_BUDGET_MS=100,STARTUP_GRACE_MS=5e3,STATUS=0,STARTED=1,PENDING=0,MATCHED=1,DID_NOT_MATCH=2,FAILED=3,WORKER_SOURCE=`
1134
1135
  const { parentPort } = require("node:worker_threads");
1135
1136
  parentPort.on("message", (task) => {
1136
1137
  const slots = new Int32Array(task.shared);
@@ -1145,11 +1146,11 @@ parentPort.on("message", (task) => {
1145
1146
  Atomics.store(slots, ${STATUS}, code);
1146
1147
  Atomics.notify(slots, ${STATUS});
1147
1148
  });
1148
- `,defaultFactory=()=>{let worker2=new Worker(WORKER_SOURCE,{eval:!0});return worker2.unref(),worker2},factory=defaultFactory,worker,workersUnavailable=!1;function disposeMatcherWorker(){let running=worker;if(worker=void 0,running!==void 0)try{running.terminate()}catch{}}function matcher(){if(!workersUnavailable){if(worker!==void 0)return worker;try{worker=factory()}catch{worker=void 0}return worker===void 0&&(workersUnavailable=!0),worker}}function matchWithBudget(pattern,input,budgetMs=DEFAULT_PATTERN_BUDGET_MS){let running=matcher();if(running===void 0)return inProcessMatch(pattern,input);let shared=new SharedArrayBuffer(2*Int32Array.BYTES_PER_ELEMENT),slots=new Int32Array(shared);try{running.postMessage({pattern,input,shared})}catch{return disposeMatcherWorker(),inProcessMatch(pattern,input)}if(!waitForStart(slots))return disposeMatcherWorker(),workersUnavailable=!0,inProcessMatch(pattern,input);switch(Atomics.load(slots,STATUS)===PENDING&&Atomics.wait(slots,STATUS,PENDING,budgetMs),Atomics.load(slots,STATUS)){case MATCHED:return"match";case DID_NOT_MATCH:return"no-match";case FAILED:return inProcessMatch(pattern,input);default:return disposeMatcherWorker(),"timeout"}}function waitForStart(slots){let deadline=Date.now()+STARTUP_GRACE_MS;for(;Atomics.load(slots,STARTED)===0&&Atomics.load(slots,STATUS)===PENDING;){let remaining=deadline-Date.now();if(remaining<=0)return!1;Atomics.wait(slots,STARTED,0,remaining)}return!0}function inProcessMatch(pattern,input){return new RegExp(pattern).test(input)?"match":"no-match"}var TRUE_WORDS=new Set(["true","yes","y","on","1"]),FALSE_WORDS=new Set(["false","no","n","off","0"]);function canonicalBoolean(value){if(typeof value=="boolean")return value?"true":"false";let word=value.trim().toLowerCase();return TRUE_WORDS.has(word)?"true":FALSE_WORDS.has(word)?"false":void 0}function patternsOf(definition2){return definition2.patterns??(definition2.validate?.pattern===void 0?[]:[definition2.validate.pattern])}function validateAnswer(definition2,raw2,context={}){let trimmed=typeof raw2=="string"?raw2.trim():"";if(trimmed.length===0&&!definition2.required)return{ok:!0,value:""};let rules=definition2.validate,fail=reason=>({ok:!1,message:`${definition2.name} ${reason}.`});switch(definition2.type){case"number":{if(trimmed.length===0||!Number.isFinite(Number(trimmed)))return fail("must be a number");let value=Number(trimmed);return rules?.min!==void 0&&value<rules.min?fail(`must be at least ${rules.min}`):rules?.max!==void 0&&value>rules.max?fail(`must be at most ${rules.max}`):{ok:!0,value}}case"boolean":{let word=trimmed.toLowerCase();return!TRUE_WORDS.has(word)&&!FALSE_WORDS.has(word)?fail("must be 'true' or 'false'"):{ok:!0,value:TRUE_WORDS.has(word)}}case"enum":{let options2=rules?.enum??[];return runString(trimmed,[value=>options2.includes(value)?void 0:`must be one of: ${options2.join(", ")}`,...stringChecks()])}case"url":return runString(trimmed,[value=>isUrl(value)?void 0:"must be a URL, including its scheme (for example 'https://example.com')",...stringChecks()]);case"path":return runString(trimmed,[value=>value.includes("\0")?"must be a filesystem path, with no null characters in it":void 0,...stringChecks()]);default:return runString(trimmed,stringChecks())}function runString(value,checks){for(let check3 of checks){let reason=check3(value);if(reason!==void 0)return fail(reason)}return{ok:!0,value}}function stringChecks(){let checks=[];if(definition2.required&&checks.push(value=>value.length>0?void 0:"must not be empty"),rules?.minLength!==void 0){let min=rules.minLength;checks.push(value=>value.length>=min?void 0:`must be at least ${min} characters long`)}if(rules?.maxLength!==void 0){let max=rules.maxLength;checks.push(value=>value.length<=max?void 0:`must be at most ${max} characters long`)}let budget=context.patternBudgetMs??DEFAULT_PATTERN_BUDGET_MS;for(let pattern of patternsOf(definition2))checks.push(value=>{let outcome=matchWithBudget(pattern,value,budget);if(outcome!=="match")return outcome==="timeout"?patternTooSlowMessage(pattern,budget,context.recipe):`must match the pattern ${pattern}`});return checks}}function isUrl(value){try{return new URL(value).protocol.length>1}catch{return!1}}function patternTooSlowMessage(pattern,budgetMs,recipe){let publisher=recipe===void 0?"the recipe that defines it":`the recipe ${recipe}`;return`could not be checked: the pattern ${pattern}, published by ${publisher}, took longer than ${budgetMs} milliseconds to run, so sous stopped waiting for it. The pattern is too slow to run, and the answer was not the problem; this needs to be reported to whoever publishes the recipe`}function characters(count2){return count2===1?"1 character":`${count2} characters`}function constraintBullets(definition2){let rules=definition2.validate,options2=rules?.enum,bullets=definition2.type==="enum"&&options2!==void 0?[`must be one of: ${options2.join(", ")} (type: enum)`]:[`must be a value of the type ${definition2.type} (type: ${definition2.type})`];options2!==void 0&&definition2.type!=="enum"&&bullets.push(`must be one of: ${options2.join(", ")} (enum: ${options2.join(", ")})`),rules?.minLength!==void 0&&bullets.push(`must be at least ${characters(rules.minLength)} long (minLength: ${rules.minLength})`),rules?.maxLength!==void 0&&bullets.push(`must be at most ${characters(rules.maxLength)} long (maxLength: ${rules.maxLength})`),rules?.min!==void 0&&bullets.push(`must be no less than ${rules.min} (min: ${rules.min})`),rules?.max!==void 0&&bullets.push(`must be no more than ${rules.max} (max: ${rules.max})`);for(let pattern of patternsOf(definition2))bullets.push(`must match the pattern /${pattern}/ (pattern: ${pattern})`);return definition2.required||bullets.push("an answer is optional"),bullets}var validator={validate:(definition2,answer2,options2)=>validateAnswer(definition2,answer2,options2)};function tightest(definers,field){let lower=field==="min"||field==="minLength",best;for(let{definition:definition2,label}of definers){let value=definition2.validate?.[field];value!==void 0&&(best===void 0||(lower?value>best.value:value<best.value))&&(best={value,label})}return best}function combineDefinitions(definers){let[first2]=definers;if(first2===void 0)throw new Error("combineDefinitions needs at least one definition.");if(definers.length===1)return{ok:!0,definition:first2.definition};let name=first2.definition.name,otherType=definers.find(entry=>entry.definition.type!==first2.definition.type);if(otherType!==void 0)return{ok:!1,reason:`${first2.label} defines ${name} as ${article2(first2.definition.type)}, and ${otherType.label} defines it as ${article2(otherType.definition.type)}, so no answer fits both.`};let listing=definers.filter(entry=>entry.definition.validate?.enum!==void 0),options2;for(let entry of listing){let own=entry.definition.validate.enum;options2=options2===void 0?[...own]:options2.filter(option=>own.includes(option))}if(options2!==void 0&&options2.length===0){let lists=listing.map(entry=>`${entry.label} accepts ${entry.definition.validate.enum.join(", ")}`);return{ok:!1,reason:`No value of ${name} is accepted by every definition (${lists.join("; ")}).`}}let min=tightest(definers,"min"),max=tightest(definers,"max");if(min!==void 0&&max!==void 0&&min.value>max.value)return{ok:!1,reason:`${min.label} requires ${name} to be at least ${min.value}, and ${max.label} requires it to be at most ${max.value}, so no answer fits both.`};let minLength=tightest(definers,"minLength"),maxLength=tightest(definers,"maxLength");if(minLength!==void 0&&maxLength!==void 0&&minLength.value>maxLength.value)return{ok:!1,reason:`${minLength.label} requires ${name} to be at least ${minLength.value} characters long, and ${maxLength.label} requires it to be at most ${maxLength.value} characters long, so no answer fits both.`};let patterns=[...new Set(definers.flatMap(entry=>entry.definition.validate?.pattern===void 0?[]:[entry.definition.validate.pattern]))],validate={...first2.definition.validate??{},...options2===void 0?{}:{enum:options2},...min===void 0?{}:{min:min.value},...max===void 0?{}:{max:max.value},...minLength===void 0?{}:{minLength:minLength.value},...maxLength===void 0?{}:{maxLength:maxLength.value},...patterns[0]===void 0?{}:{pattern:patterns[0]}},envs=new Set(definers.map(entry=>entry.definition.env)),rest={...first2.definition};delete rest.default,delete rest.env;let combined={...rest,...envs.size===1&&first2.definition.env!==void 0?{env:first2.definition.env}:{},secret:definers.some(entry=>entry.definition.secret),scope:definers.some(entry=>entry.definition.scope==="local")?"local":"shared",required:definers.some(entry=>entry.definition.required),...Object.keys(validate).length===0?{}:{validate},...patterns.length>1?{patterns}:{}},fallback2=definers.map(entry=>entry.definition.default).find(value=>value!==void 0&&validateAnswer(combined,String(value)).ok);return{ok:!0,definition:fallback2===void 0?combined:{...combined,default:fallback2}}}function article2(type){return/^[aeiou]/.test(type)?`an ${type}`:`a ${type}`}import path60 from"node:path";function resolveUserPath(file2,base){if(path60.isAbsolute(file2))return file2;let from=base.cwd??base.project?.root;return from===void 0?file2:path60.resolve(from,file2)}var LOCAL_FILE_REPO="local",LOCAL_FILE_NAMESPACE="local";function recipeKey(recipe){return`${recipe.namespace}/${recipe.name}`}function variableKey(recipe,variable){return`${recipeKey(recipe)}.${variable}`}function qualifiedKey(defined){return`${defined.recipe.repo}:${defined.key}`}function variableRefOf(recipe,definition2){return{kind:"variable",name:definition2.name,description:definition2.prompt,recipe:{kind:"recipe",name:recipe.name,namespace:{kind:"namespace",name:recipe.namespace,repo:{kind:"repo",name:recipe.repo}}}}}function defineVariable(recipe,definition2,shared={}){let{requiredBy,combined,separate,unanswerable}=shared;return{definition:combined??definition2,recipe,ref:variableRefOf(recipe,definition2),key:variableKey(recipe,definition2.name),...requiredBy===void 0||requiredBy.length===0?{}:{requiredBy},...combined===void 0||combined===definition2?{}:{published:definition2},...separate===void 0?{}:{separate},...unanswerable===void 0?{}:{unanswerable}}}function definersOf(group){let keys=group.map(entry=>recipeKey(entry.recipe));return group.map((entry,index)=>{let key=keys[index];return{definition:entry.published??entry.definition,label:keys.indexOf(key)===keys.lastIndexOf(key)?key:`${key} ${entry.recipe.version}`}})}function holderList(holders){let named=holders.map(holder=>holder==="project"?"this project":holder);return named.length<2?named[0]??"":`${named.slice(0,-1).join(", ")} and ${named.at(-1)}`}function versionConflictWarning(name,skipped,asked,reason){let key=recipeKey(skipped),skippedAt=`${key} ${skipped.version}`,askedAt=`${key} ${asked.version}`,users=[...skipped.holders===void 0||skipped.holders.length===0?[]:[`${skippedAt} is used by ${holderList(skipped.holders)}`],...asked.holders===void 0||asked.holders.length===0?[]:[`${askedAt} by ${holderList(asked.holders)}`]],used=users.length===0?"":` ${users.join(", and ")}.`;return`The variable ${name} of ${skippedAt} cannot be answered alongside ${askedAt}, so it is not asked and gets no answer: where ${skippedAt} is used, ${name} renders empty.${used} ${reason}`}function settleConflict(group,settled){let name=group[0].definition.name,byRecipe=new Map;for(let entry of group)byRecipe.set(recipeKey(entry.recipe),[...byRecipe.get(recipeKey(entry.recipe))??[],entry]);let ownCombination=new Map;for(let versions of byRecipe.values()){let asked=versions.find(entry=>entry.recipe.pinned!==!0)??versions[0],kept=[asked];for(let other of versions){if(other===asked)continue;let combination2=combineDefinitions(definersOf([...kept,other]));combination2.ok?kept.push(other):settled.set(other,{unanswerable:versionConflictWarning(name,other.recipe,asked.recipe,combination2.reason)})}let own=combineDefinitions(definersOf(kept));for(let entry of kept)ownCombination.set(entry,own.ok?own.definition:entry.published??entry.definition)}let remaining=group.filter(entry=>!settled.has(entry));if(remaining.length<2)return;let combination=combineDefinitions(definersOf(remaining));for(let entry of remaining)settled.set(entry,combination.ok?{combined:combination.definition}:{combined:ownCombination.get(entry),separate:combination.reason})}function combineSharedNames(variables){let byName=new Map;for(let entry of variables){let group=byName.get(entry.definition.name)??[];group.push(entry),byName.set(entry.definition.name,group)}let settled=new Map;for(let group of byName.values()){if(group.length<2)continue;let combination=combineDefinitions(definersOf(group));if(combination.ok)for(let entry of group)settled.set(entry,{combined:combination.definition});else settleConflict(group,settled)}return variables.map(entry=>{let outcome=settled.get(entry),group=byName.get(entry.definition.name)??[];if(group.length<2)return entry;let others=group.filter(other=>other!==entry&&(outcome?.unanswerable!==void 0||settled.get(other)?.unanswerable===void 0)).map(other=>other.recipe);return defineVariable(entry.recipe,entry.published??entry.definition,{requiredBy:others,...outcome??{}})})}function definitionsFromRecipes(recipes,repos={}){let defined=[];for(let active of recipes){let url2=repos[active.repo]?.url,recipe={repo:active.repo,namespace:active.namespace,name:active.name,version:active.version,dir:active.dir,identity:active.identity,direct:active.requestedBy.includes("project"),...url2===void 0?{}:{url:url2}},pinnedFor=new Map;for(let pin of active.pins??[]){let same=pinnedFor.get(pin.version);same===void 0?pinnedFor.set(pin.version,{version:pin.version,dir:pin.dir,manifest:pin.manifest,holders:[pin.holder]}):same.holders.push(pin.holder)}let pinnedHolders=new Set((active.pins??[]).map(pin=>pin.holder)),shared={...recipe,holders:active.requestedBy.filter(holder=>!pinnedHolders.has(holder))};for(let definition2 of active.manifest.variables??[])defined.push(defineVariable(pinnedFor.size===0?recipe:shared,definition2));for(let pin of pinnedFor.values()){let pinned={...recipe,version:pin.version,dir:pin.dir,direct:!1,holders:pin.holders,pinned:!0};for(let definition2 of pin.manifest.variables??[])defined.push(defineVariable(pinned,definition2))}}return combineSharedNames(defined)}function pseudoRecipeName(filePath){let slug=path61.basename(filePath).replace(/\.[^.]+$/,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return slug.length===0||!/^[a-z]/.test(slug)?`file-${slug}`:slug}async function loadDefinitionsFile(filePath,reader){let raw2=await reader.readFile(filePath),variables=raw2?.variables;if(raw2===null||typeof raw2!="object"||Array.isArray(raw2)||!Array.isArray(variables)||variables.length===0)throw new ConfigError41(`The variable definitions file at ${filePath} is not valid.`,{details:["variables: must list at least one variable, in the form a recipe manifest uses."]});let recipe={repo:LOCAL_FILE_REPO,namespace:LOCAL_FILE_NAMESPACE,name:pseudoRecipeName(filePath),version:"0.0.0",dir:filePath,direct:!0},problems=[],defined=[];for(let[index,value]of variables.entries()){let checked3=reader.definition.check(value,`${filePath}, variables[${index}]`);if(checked3.issues===void 0)defined.push(defineVariable(recipe,checked3.value));else{let issues=checked3.issues.filter(issue2=>!/^Invalid .*:$/.test(issue2));problems.push(...issues.map(issue2=>placeIssue(issue2,index)))}}if(problems.length>0)throw new ConfigError41(`Invalid variable definitions file at ${filePath}:`,{details:problems});return combineSharedNames(defined)}function placeIssue(issue2,index){let text=issue2.replace(/^\s*-\s*/,"");return/^([\w.[\]]+): /.exec(text)===null?`- variables[${index}]: ${text}`:`- variables[${index}].${text}`}function namesVariable(defined,name){return defined.definition.name===name||defined.key===name||qualifiedKey(defined)===name}var DefinitionsService=class{constructor(ctx){this.ctx=ctx}listSync(){let recipes=this.ctx.entities.kinds().includes("active-recipe")?this.ctx.entities.list("active-recipe"):[];return definitionsFromRecipes(recipes,this.ctx.config.get("repos")??{})}async list(options2={}){return options2.file===void 0?this.listSync():loadDefinitionsFile(resolveUserPath(options2.file,this.ctx),{readFile:file2=>this.ctx.services.get("formats.manifests").readFile(file2),definition:this.ctx.services.get("formats.variable-definition")})}async find(nameOrRef,options2={}){return(await this.list(options2)).filter(entry=>namesVariable(entry,nameOrRef))}combine(variables){return combineSharedNames(variables)}};function answerFor(variable,ladder){if(variable.unanswerable!==void 0)return;let resolved=ladder.resolve(variable),fallback2=variable.definition.default,value=resolved!==void 0?resolved.value:fallback2===void 0?void 0:String(fallback2);return value===void 0||variable.definition.type!=="boolean"?value:canonicalBoolean(value)??value}function booleanNames(variables){return[...new Set(variables.filter(variable=>variable.definition.type==="boolean").map(variable=>variable.definition.name))]}function computeAnswers(variables,ladder){let merged={},byRecipe={},unanswered=[],unanswerable=[],secrets=new Set;for(let variable of variables){let name=variable.definition.name,value=answerFor(variable,ladder);if(variable.definition.secret&&secrets.add(name),variable.unanswerable!==void 0){unanswerable.push(variable);continue}if(value===void 0){variable.definition.required&&unanswered.push(variable);continue}name in merged||(merged[name]=value);let key=recipeKey(variable.recipe);byRecipe[key]={...byRecipe[key]??{},[name]:value}}for(let variable of unanswerable){let name=variable.definition.name;for(let holder of variable.recipe.holders??[])variables.some(other=>other.definition.name===name&&recipeKey(other.recipe)===holder)||(byRecipe[holder]={...byRecipe[holder]??{},[name]:""})}return{merged,byRecipe,unanswered,unanswerable,secrets}}function answersForRecipe(answers,key){return{...answers.merged,...answers.byRecipe[key]??{}}}var AnswersService=class{constructor(compute){this.compute=compute}cached;get(){return this.cached??=this.compute(),this.cached}forRecipe(key){return answersForRecipe(this.get(),key)}};import{commandVariables as commandVariables2,ConfigError as ConfigError44,InputError as InputError5,IntentOutput as IntentOutput9,IntentOutputs as IntentOutputs10,jsonSchema as jsonSchema16,ReportEntryStyle as ReportEntryStyle5,TextBlock as TextBlock6}from"@sous-io/sous-plugin-api";import{LogLevel as LogLevel11,NonInteractiveError as NonInteractiveError4}from"@sous-io/sous-plugin-api";import{ConfigError as ConfigError42,InputError as InputError3}from"@sous-io/sous-plugin-api";var VAR_MAPPINGS_FILE="520-var-mappings.jsonc",VAR_MAPPINGS_DESCRIPTION=["Each entry under 'varMappings' binds an environment variable to one recipe","variable, so an answer can be stored under a name of your choosing when the","usual names are taken. The 'sous vars ask' and 'sous vars map' commands write","them; run 'sous vars' to see which name answered what."],TARGET_HELP="A mapping target is written as 'namespace/recipe/variableName', optionally qualified with a repository as 'repo:namespace/recipe/variableName'.",STORED_NAME=/^[a-z][a-z0-9-]*$/,VARIABLE_NAME2=/^[a-z][a-zA-Z0-9]*$/;function parseMappingTarget(input){let fail=problem=>{throw new ConfigError42(`Invalid variable mapping target '${input}': ${problem}`,{details:[TARGET_HELP]})},trimmed=typeof input=="string"?input.trim():"";trimmed.length===0&&fail("a target must not be empty.");let colon=trimmed.indexOf(":"),repo=colon===-1?void 0:trimmed.slice(0,colon),parts=trimmed.slice(colon+1).split("/");(parts.length!==3||parts.some(part=>part.length===0))&&fail("a target names a namespace, a recipe and a variable, joined by slashes.");let[namespace,recipe,variable]=parts,named=[...repo===void 0?[]:[repo],namespace,recipe];for(let name of named)STORED_NAME.test(name)||fail(name.toLowerCase()!==name&&STORED_NAME.test(name.toLowerCase())?`the repository, namespace and recipe in '${trimmed.slice(0,trimmed.lastIndexOf("/"))}' must be lowercase.`:`'${name}' is not a repository, namespace or recipe name: a lowercase letter, then lowercase letters, digits or dashes.`);return VARIABLE_NAME2.test(variable)||fail(`the variable name '${variable}' must be camelCase: a lowercase letter, then letters or digits.`),{...repo===void 0?{}:{repo},namespace,recipe,variable}}function formatMappingTarget(target){return`${target.repo===void 0?"":`${target.repo}:`}${target.namespace}/${target.recipe}/${target.variable}`}function mappingTargetFor(defined){return{repo:defined.recipe.repo,namespace:defined.recipe.namespace,recipe:defined.recipe.name,variable:defined.definition.name}}function mappingMatches(target,defined){return target.repo!==void 0&&target.repo!==defined.recipe.repo?!1:target.namespace===defined.recipe.namespace&&target.recipe===defined.recipe.name&&target.variable===defined.definition.name}function mappedNamesFor(mappings,defined){let names2=[];for(let[envName,target]of Object.entries(mappings))mappingMatches(parseMappingTarget(target),defined)&&names2.push(envName);return names2.sort()}var MappingsService=class{constructor(ctx){this.ctx=ctx}list(){let records=this.ctx.config.get("varMappings")??{},parsed={};for(let[envName,target]of Object.entries(records))parsed[envName]=parseMappingTarget(target);return parsed}parseTarget(text){return parseMappingTarget(text)}formatTarget(target){return formatMappingTarget(target)}async set(envName,target,options2={}){this.checkEnvName(envName);let written=formatMappingTarget(parseMappingTarget(formatMappingTarget(target))),result=await this.ctx.services.get("confd.managed").set(VAR_MAPPINGS_FILE,`varMappings.${envName}`,written,{description:VAR_MAPPINGS_DESCRIPTION,...options2.dryRun===void 0?{}:{dryRun:options2.dryRun}});return{file:result.file,changed:result.changed}}async remove(envName,options2={}){this.checkEnvName(envName);let result=await this.ctx.services.get("confd.managed").delete(VAR_MAPPINGS_FILE,`varMappings.${envName}`,{description:VAR_MAPPINGS_DESCRIPTION,...options2.dryRun===void 0?{}:{dryRun:options2.dryRun}});return{file:result.file,changed:result.changed}}checkEnvName(envName){if(!this.ctx.services.get("variables.names").isEnvName(envName))throw new InputError3("vars.map",[{path:"envName",message:`'${envName}' is not an environment variable name: a letter or underscore, then letters, digits or underscores.`}])}};var RUNG_LABELS2={mapping:"mapping record",recipe:"recipe scope",namespace:"namespace scope",shared:"shared scope",bare:"declared name"},SOURCE_LABELS2={shell:"the shell environment",local:"the .env.local file",shared:"the .env file"},ENV_FILE_NAMES={shared:".env",local:".env.local"};function layersFrom(files,env){let local2={...files?.local??{}},shared={...files?.shared??{}},shell={};for(let[name,value]of Object.entries(env))value===void 0||local2[name]===value||shared[name]===value||(shell[name]=value);return{shell,local:local2,shared}}var Ladder=class{constructor(names2,layers,mappings={}){this.names=names2;this.layers={shell:{...layers.shell},local:{...layers.local},shared:{...layers.shared}},this.mappingRecords={...mappings}}layers;mappingRecords;get mappings(){return this.mappingRecords}namesInFiles(){return new Set([...Object.keys(this.layers.local),...Object.keys(this.layers.shared)])}candidates(variable){let{namespace,name:recipe}=variable.recipe,name=variable.definition.name,ordered2=[...mappedNamesFor(this.mappingRecords,variable).map(envName=>({rung:"mapping",envName})),{rung:"recipe",envName:this.names.recipeScopedName(namespace,recipe,name)},{rung:"namespace",envName:this.names.namespaceScopedName(namespace,name)},{rung:"shared",envName:this.names.sharedName(name)},{rung:"bare",envName:this.names.bareName(variable.published??variable.definition)}],seen=new Set;return ordered2.filter(candidate=>seen.has(candidate.envName)?!1:(seen.add(candidate.envName),!0))}bareName(variable){return variable.separate===void 0?this.names.bareName(variable.definition):this.recipeScopedName(variable)}recipeScopedName(variable){return this.names.recipeScopedName(variable.recipe.namespace,variable.recipe.name,variable.definition.name)}lookupIn(file2,envName){return this.layers[file2][envName]}lookup(envName){for(let file2 of["shell","local","shared"]){let value=this.layers[file2][envName];if(value!==void 0)return{value,file:file2}}}resolve(variable){return this.diagnose(variable).resolved}diagnose(variable){let candidates=this.candidates(variable);if(variable.unanswerable!==void 0)return{candidates};for(let candidate of candidates){let hit=this.lookup(candidate.envName);if(hit!==void 0)return{resolved:{value:hit.value,source:{...candidate,file:hit.file}},candidates}}return{candidates}}record(file2,envName,value){this.layers[file2][envName]=value}addMapping(envName,target){this.mappingRecords={...this.mappingRecords,[envName]:target}}};function describeSource2(source){let label=RUNG_LABELS2[source.rung];return`the ${label.endsWith(" name")?label:`${label} name`} ${source.envName}, from ${SOURCE_LABELS2[source.file]??source.file}`}function buildLadder(inputs){let files=inputs.services.has("config-files.env")?inputs.services.get("config-files.env").readSync():void 0;return new Ladder(inputs.services.get("variables.names"),layersFrom(files,inputs.env),inputs.config.get("varMappings")??{})}function answerFileFor(definition2){return definition2.secret||definition2.scope==="local"?"local":"shared"}var UNANSWERED_VALUE="(unanswered)";function displayValue(value,secret,hidden){return value===void 0?UNANSWERED_VALUE:secret?hidden:value}function hiddenValue(services){return services.has("variables.secrets")?services.get("variables.secrets").hiddenValue:"(hidden)"}var OPTIONAL_REASON="no answer yet, and this variable is optional",OPTIONAL_HINT="To answer an optional variable, run 'sous vars ask <name>'. 'sous vars ask --all' asks every variable, including the ones already answered.",TRUE_WORDS2=["true","yes","y","on","1"];function answerCount(count2){return count2===1?"1 answer":`${count2} answers`}function answeredBy(variable){return`--answer ${variable.definition.name}=<value>`}function askLeadIn(groups){if(groups.length<2)return;let parts=groups.map((group,index)=>{let relation=index===0||group.direct?"":", which it depends on,",needs=index===0?answerCount(group.count):String(group.count);return`${group.key}${relation} needs ${needs}`}),last2=parts.pop();return`${[...parts,`and ${last2}`].join(", ")}.`}function recipeOpeningLine(key,count2){return`${key} needs ${answerCount(count2)} before it can be used.`}function answerComment(variable){return`Set by sous for ${recipeKey(variable.recipe)}: ${variable.definition.prompt}`}function nonInteractiveError(pending){let details=["Set one of the environment variables listed under each variable, pass --answer <name>=<value>, or run 'sous vars ask' from a terminal."];for(let entry of pending){details.push("",`${entry.variable.definition.name} (${recipeKey(entry.variable.recipe)}): ${entry.variable.definition.prompt}`),entry.current!==void 0&&details.push(` The value currently in scope does not fit this variable: ${entry.current}`),entry.variable.separate!==void 0&&details.push(` ${entry.variable.separate} Each recipe needs its own answer.`);for(let candidate of entry.candidates)details.push(` ${candidate.envName} (${RUNG_LABELS2[candidate.rung]})`)}let first2=pending[0],question=pending.length===1?first2.variable.definition.prompt:`${pending.length} questions about recipe variables`,error51=new NonInteractiveError4(question,pending.length===1?answeredBy(first2.variable):"--answer <name>=<value>",{details,exitCode:1});return error51.message=pending.length===1?"One variable still needs an answer, and there is no terminal to ask on.":`${pending.length} variables still need answers, and there is no terminal to ask on.`,error51}function askedFor(variable){let others=variable.separate===void 0?variable.requiredBy??[]:[];return others.length===0?recipeKey(variable.recipe):`${recipeKey(variable.recipe)}, also used by ${others.map(recipeKey).join(", ")}`}function separateNote(variable){return variable.separate===void 0?void 0:`${variable.separate} Each recipe is asked for its own answer, stored under its recipe-scoped name.`}function unanswerableReason(variable){let key=recipeKey(variable.recipe);return`not asked for ${key} ${variable.recipe.version}, which cannot share an answer with another version of ${key}`}function committedFileWarning(variable,file2){let what=variable.definition.secret?"a secret":"machine-specific";return`${variable.published===void 0||variable.requiredBy===void 0?`${recipeKey(variable.recipe)} declared this variable ${what}`:`${recipeKey(variable.recipe)} shares this variable with ${variable.requiredBy.map(recipeKey).join(", ")}, and one of their definitions declares it ${what}`}, and ${file2} is committed to git. An answer stored there enters your project's git history, is pushed with every clone, and is visible to everyone who can read the repository.`}async function allowedFile(variable,file2,run){if(file2!=="shared"||run.envFile!=="shared"||answerFileFor(variable.definition)!=="local"||run.yes===!0)return!0;let name=ENV_FILE_NAMES.shared;return run.reporter.warning(committedFileWarning(variable,`.sous/${name}`)),run.prompter.confirm({message:`Store this answer in .sous/${name} anyway?`,answeredBy:"--yes",default:!1})}function check2(variable,value){return validateAnswer(variable.definition,value,{recipe:recipeKey(variable.recipe)})}async function storeGivenAnswers(applicable,ladder,run){let stored=[],keys=new Set,written=new Set;for(let entry of applicable){keys.add(entry.target.key);let existing=ladder.resolve(entry.target),fallback2={file:run.envFile??answerFileFor(entry.target.definition),envName:ladder.bareName(entry.target)},plan2=run.envFile===void 0&&existing!==void 0&&existing.source.file!=="shell"?{file:existing.source.file,envName:existing.source.envName}:fallback2,slot=`${plan2.file}:${plan2.envName}`;if(written.has(slot)||(written.add(slot),!await allowedFile(entry.target,plan2.file,run)))continue;let outcome=run.dryRun?"not written":ladder.lookupIn(plan2.file,plan2.envName)===void 0?"appended":"updated";run.dryRun||await run.store.writeAnswer(plan2.file,plan2.envName,entry.value,answerComment(entry.target)),ladder.record(plan2.file,plan2.envName,entry.value),stored.push({variable:entry.target,envName:plan2.envName,file:plan2.file,filePath:run.store.envPath(plan2.file),value:displayValue(entry.value,entry.target.definition.secret,run.hidden),outcome,...existing===void 0||existing.value===entry.value?{}:{replaced:displayValue(existing.value,entry.target.definition.secret,run.hidden)},...existing?.source.file==="shell"?{shadowedBy:existing.source.envName}:{}})}return{stored,keys}}async function askForMissing(variables,ladder,options2,run){let report={answered:[],inherited:[],skipped:[],wouldAsk:[]},announced=!1,announce=()=>{announced||(announced=!0,run.beforeReporting?.())},pending=[],questions=[],deferred=[],plannedNames=new Set,named=options2.only!==void 0;for(let variable of variables){if(options2.only!==void 0&&!options2.only.has(variable.key)||options2.within!==void 0&&!options2.within.has(recipeKey(variable.recipe)))continue;if(variable.unanswerable!==void 0){announce(),run.reporter.warning(variable.unanswerable),report.skipped.push({variable,reason:unanswerableReason(variable)});continue}if(options2.skip?.has(variable.key)===!0)continue;let{definition:definition2}=variable,diagnosis=ladder.diagnose(variable),existing=diagnosis.resolved,validity=existing===void 0?void 0:check2(variable,existing.value);if(existing!==void 0&&validity?.ok===!0&&options2.reask!==!0&&!named){report.inherited.push({variable,resolved:existing});continue}if((existing===void 0||validity?.ok===!1)&&options2.reask!==!0&&!named&&diagnosis.candidates.some(candidate=>plannedNames.has(candidate.envName))){deferred.push(variable);continue}if(!(existing!==void 0&&validity?.ok===!1||existing===void 0&&definition2.required||options2.reask===!0||named)){report.skipped.push({variable,reason:OPTIONAL_REASON});continue}if(!run.prompter.interactive&&existing===void 0&&!named&&options2.reask!==!0&&definition2.default!==void 0&&check2(variable,String(definition2.default)).ok){report.skipped.push({variable,reason:definition2.secret?"no answer yet, so its default is used":`no answer yet, so its default is used: ${String(definition2.default)}`});continue}if(!run.prompter.interactive&&run.dryRun){report.wouldAsk.push({variable,...validity?.ok===!1?{current:validity.message}:{}});continue}if(!run.prompter.interactive){pending.push({variable,candidates:diagnosis.candidates,...validity?.ok===!1?{current:validity.message}:{}});continue}let suggestion=existing!==void 0&&validity?.ok===!0?existing.value:definition2.default!==void 0?String(definition2.default):void 0;plannedNames.add(ladder.bareName(variable)),questions.push({variable,...suggestion===void 0?{}:{suggestion}})}if(pending.length>0)throw nonInteractiveError(pending);questions.length>0&&announce();for(let note of new Set(questions.map(question=>separateNote(question.variable))))note!==void 0&&run.reporter.note(note);let groups=groupQuestions(questions),leadIn=askLeadIn(groups.map(group=>({key:group.key,count:group.questions.length,direct:group.direct})));leadIn!==void 0&&run.reporter.note(leadIn);for(let group of groups){run.reporter.note(recipeOpeningLine(group.key,group.questions.length));for(let[position,question]of group.questions.entries())await runQuestion(question,{index:position+1,total:group.questions.length},ladder,run,report)}for(let variable of deferred){let resolved=ladder.resolve(variable);if(resolved!==void 0&&check2(variable,resolved.value).ok){report.inherited.push({variable,resolved});continue}announce(),run.reporter.note(recipeOpeningLine(recipeKey(variable.recipe),1)),await runQuestion({variable},{index:1,total:1},ladder,run,report)}return report}function groupQuestions(questions){let groups=new Map;for(let question of questions){let key=recipeKey(question.variable.recipe),group=groups.get(key);group===void 0?groups.set(key,{key,direct:question.variable.recipe.direct!==!1,questions:[question]}):group.questions.push(question)}return[...groups.values()]}async function askByType(definition2,variable,suggestion,prompter){let by2=answeredBy(variable);if(definition2.type==="enum"){let options2=definition2.validate?.enum??[],index=suggestion===void 0?-1:options2.indexOf(suggestion);return prompter.askChoice({message:definition2.prompt,answeredBy:by2,choices:options2.map(option=>({label:option,value:option})),...index===-1?{}:{defaultIndex:index}})}if(definition2.type==="boolean"){let current=suggestion??String(definition2.default??"");return String(await prompter.confirm({message:definition2.prompt,answeredBy:by2,default:TRUE_WORDS2.includes(current.toLowerCase())}))}return prompter.askValue({message:definition2.prompt,answeredBy:by2,validate:value=>{let result=check2(variable,value);return result.ok?void 0:result.message},...suggestion===void 0?{}:{default:suggestion},...definition2.secret?{secret:!0}:{}})}async function runQuestion(question,place,ladder,run,report){let{variable}=question,{definition:definition2}=variable,plan2={file:run.envFile??answerFileFor(definition2),envName:ladder.bareName(variable)};if(!await allowedFile(variable,plan2.file,run)){report.skipped.push({variable,reason:`not stored in .sous/${ENV_FILE_NAMES.shared}, which is committed to git`});return}run.reporter.question({index:place.index,total:place.total,name:definition2.name,...definition2.description===void 0?{}:{description:definition2.description},...definition2.example===void 0?{}:{example:String(definition2.example)},recipe:askedFor(variable),storedIn:run.store.envPath(plan2.file),storedAs:plan2.envName});let answer2=await askByType(definition2,variable,question.suggestion,run.prompter),checked3=check2(variable,answer2);if(!checked3.ok){report.skipped.push({variable,reason:checked3.message});return}let stored=await storeAnswer(variable,String(checked3.value),plan2,ladder,run);report.answered.push(stored),run.reporter.variables([{label:"Answer",value:`${stored.envName}=${stored.value}`},{label:run.dryRun?"Would be saved to":"Saved to",value:stored.filePath}],void 0,LogLevel11.Notice)}async function storeAnswer(variable,value,plan2,ladder,run){let envName=plan2.envName,mapping,occupant=ladder.lookup(envName);if(occupant!==void 0&&!check2(variable,occupant.value).ok){let scoped=ladder.recipeScopedName(variable),target=formatMappingTarget(mappingTargetFor(variable));(!run.prompter.interactive||await run.prompter.askChoice({message:`${envName} already holds a value that does not fit ${variable.definition.name}. Where should this answer go?`,choices:[{label:`${scoped}, with a mapping record (recommended)`,value:!0},{label:`${envName}, replacing what is there`,value:!1}]}))&&(envName=scoped,mapping={envName:scoped,target,filePath:run.dryRun?run.store.mappingPath():await run.store.writeMapping(scoped,target)},ladder.addMapping(scoped,target))}let outcome=run.dryRun?"not written":ladder.lookupIn(plan2.file,envName)===void 0?"appended":"updated";run.dryRun||(await run.store.writeAnswer(plan2.file,envName,value,answerComment(variable)),ladder.record(plan2.file,envName,value));let winner=ladder.resolve(variable),shadowedBy=winner?.source.file==="shell"&&(winner.source.envName!==envName||winner.value!==value)?winner.source.envName:void 0;return{variable,envName,file:plan2.file,filePath:run.store.envPath(plan2.file),value:displayValue(value,variable.definition.secret,run.hidden),outcome,...mapping===void 0?{}:{mapping},...shadowedBy===void 0?{}:{shadowedBy}}}function reportedOnce(entries,sameness){let lines3=new Map,linesPerName=new Map;for(let entry of entries){let name=entry.variable.definition.name,key=JSON.stringify([name,sameness(entry)]),recipe=recipeKey(entry.variable.recipe),line=lines3.get(key);line===void 0?(lines3.set(key,{entry,recipes:[recipe]}),linesPerName.set(name,(linesPerName.get(name)??0)+1)):line.recipes.includes(recipe)||line.recipes.push(recipe)}return[...lines3.values()].map(({entry,recipes})=>({entry,recipes,named:recipes.length>1||(linesPerName.get(entry.variable.definition.name)??0)>1}))}function inheritedSameness(entry){return JSON.stringify([entry.resolved.source.envName,entry.resolved.source.file,entry.resolved.value])}import path62 from"node:path";import{IntentOutput as IntentOutput8,Table as Table3,VariableSet as VariableSet4}from"@sous-io/sous-plugin-api";function rungLabel(rung){return RUNG_LABELS2[rung]??rung}function sourceLabel(file2){return SOURCE_LABELS2[file2]??file2}function envFileName(file2){return ENV_FILE_NAMES[file2]??file2}function variableKeyOf(variable){return`${recipeKey(variable.recipe)}.${variable.definition.name}`}function isHostedUrl(location){return/^[a-z][a-z0-9+.-]*:\/\//i.test(location)||location.startsWith("git@")}function recipeLocation(recipe){let{url:url2,path:folder,dir}=recipe;if(url2!==void 0&&isHostedUrl(url2)){let base=url2.replace(/\/+$/,"");return folder===void 0?base:`${base}/${folder}`}return url2!==void 0?folder===void 0?url2:`${url2.replace(/\/+$/,"")}/${folder}`:dir}function recipeLink(recipe,label){let location=recipeLocation(recipe);return location===void 0?{label,value:recipeKey(recipe)}:{label,value:recipeKey(recipe),detail:location}}function variableFacts(detail){let{variable}=detail,{definition:definition2}=variable,entries=[];definition2.default!==void 0&&entries.push({label:"default",value:String(definition2.default)}),entries.push({label:"example",value:String(definition2.example)});let chain=variable.requiredBy!==void 0&&variable.requiredBy.length>0?variable.requiredBy:[variable.recipe];return entries.push(recipeLink(chain[0]??variable.recipe,"required-by")),chain.length>1&&entries.push({label:"",value:`pulled in through ${chain.map(recipeKey).join(" then ")}`}),entries.push(recipeLink(variable.recipe,"defined-by")),variable.unanswerable!==void 0?entries.push({label:"not-answerable",value:variable.unanswerable}):variable.separate!==void 0?entries.push({label:"asked-separately",value:variable.separate}):variable.requiredBy!==void 0&&variable.requiredBy.length>0&&entries.push({label:"combined-with",value:variable.requiredBy.map(recipeKey).join(", ")}),entries.push({label:"stored-as",value:detail.storedAs}),detail.constraints.forEach((line,index)=>entries.push({label:index===0?"constraints":"",value:line})),entries}var LIST_COLUMNS=[{key:"name",header:"Variable",overflow:"truncate",minWidth:8},{key:"recipe",header:"Recipe",kind:"path",overflow:"truncate",priority:"medium",minWidth:8},{key:"envName",header:"Answered by",overflow:"truncate",truncate:"start",priority:"medium",minWidth:11},{key:"value",header:"Value",overflow:"truncate",truncate:"end",flex:1,minWidth:10},{key:"source",header:"Source",priority:"low"}],LADDER_COLUMNS=[{key:"envName",header:"Environment variable",overflow:"truncate",truncate:"start"},{key:"rung",header:"Rung",priority:"medium"},{key:"status",header:"Status",flex:1,priority:"medium"}];function variableListOutput(listings,hidden){let rows=[...listings].sort((left,right)=>variableKeyOf(left.variable).localeCompare(variableKeyOf(right.variable))).map(listing=>({name:listing.variable.definition.name,recipe:recipeKey(listing.variable.recipe),envName:listing.source?.envName??"",value:displayValue(listing.answered||listing.usesDefault===!0?listing.value??"":void 0,listing.variable.definition.secret,hidden),source:listing.variable.unanswerable!==void 0?"not answerable alongside another version of this recipe":listing.usesDefault===!0?"its default; no answer is stored":listing.source===void 0?"nothing yet":`${rungLabel(listing.source.rung)}, ${sourceLabel(listing.source.file)}`}));return new IntentOutput8({title:"Variables in play",result:new Table3(LIST_COLUMNS,rows,{empty:"No recipe in this project defines any variables yet. Subscribe to a recipe that publishes some, or read a definitions file with --file."})})}function envFileShown(file2,sousDir){return sousDir===void 0?envFileName(file2):path62.join(sousDir,envFileName(file2))}function variableDetailOutputs(detail,hidden,sousDir){let{variable}=detail,{definition:definition2}=variable,resolved=detail.diagnosis.resolved,key=recipeKey(variable.recipe),rows=detail.diagnosis.candidates.map(candidate=>({envName:candidate.envName,rung:rungLabel(candidate.rung),status:candidate.envName===resolved?.source.envName?`answered it, from ${sourceLabel(resolved.source.file)}`:"not set"}));return withOneLabelWidth([new IntentOutput8({title:`${definition2.name} (${key})`,result:new VariableSet4({Question:definition2.prompt,About:definition2.description,"For example":String(definition2.example),Recipe:`${key} version ${variable.recipe.version} from ${variable.recipe.repo}`,"Stored in":resolved===void 0?"nowhere yet":resolved.source.file==="shell"?sourceLabel("shell"):envFileShown(resolved.source.file,sousDir),"Saved to":`${envFileShown(detail.storeIn,sousDir)} (where new answers go)`,Value:detail.usesDefault===!0?`${displayValue(detail.value,definition2.secret,hidden)} (default)`:displayValue(resolved===void 0?void 0:resolved.value,definition2.secret,hidden),Answer:variable.unanswerable!==void 0?`none: this version of ${key} is not asked this variable, because another version of ${key} is`:detail.usesDefault===!0?"nothing in scope answers this variable, so its default is used":resolved===void 0?"nothing in scope answers this variable yet":detail.problem===void 0?"the value in scope fits this definition":`the value in scope does not fit: ${detail.problem}`})}),new IntentOutput8({result:new VariableSet4(variableFacts(detail))}),new IntentOutput8({result:new Table3(LADDER_COLUMNS,rows,{title:"Environment variables sous looks at, most specific first"})})])}function withOneLabelWidth(outputs){let sets=outputs.map(output=>output.result).filter(result=>result instanceof VariableSet4),labelWidth=Math.max(0,...sets.flatMap(set2=>set2.entries.map(entry=>entry.label.length)));return outputs.map(output=>output.result instanceof VariableSet4?new IntentOutput8({...output.title===void 0?{}:{title:output.title},...output.summary===void 0?{}:{summary:output.summary},...output.data===void 0?{}:{data:output.data},...output.style===void 0?{}:{style:output.style},result:new VariableSet4(output.result.entries,{...output.result.title===void 0?{}:{title:output.result.title},labelWidth})}):output)}function answeredEntries(entry,dryRun4,hidden){let secret=entry.variable.definition.secret,note=text=>({label:"",value:text}),entries=[{label:entry.variable.definition.name,value:displayValue(entry.value,secret,hidden),detail:`${entry.envName} in ${envFileName(entry.file)}`}];return entry.mapping!==void 0&&entries.push(note(`mapped to ${entry.mapping.target} in the conf.d layer`)),entry.replaced!==void 0&&entries.push(note(`${dryRun4?"replacing":"replaced"} the answer already there: ${displayValue(entry.replaced,secret,hidden)}`)),entry.shadowedBy!==void 0&&entries.push(note(`${entry.shadowedBy} is set in your shell environment and answers this variable first; unset it for the stored answer to take effect`)),entries}function askReportOutputs(report,hidden){let outputs=[];return report.inherited.length>0&&outputs.push(new IntentOutput8({title:"Answers already in scope",result:new VariableSet4(reportedOnce(report.inherited,inheritedSameness).map(({entry,recipes,named})=>({label:entry.variable.definition.name,value:displayValue(entry.resolved.value,entry.variable.definition.secret,hidden),detail:`from ${describeSource2(entry.resolved.source)}${named?`; used by ${recipes.join(", ")}`:""}`})))})),report.answered.length>0&&outputs.push(new IntentOutput8({title:report.dryRun?"Answers that would be stored":"Answers stored",result:new VariableSet4(report.answered.flatMap(entry=>answeredEntries(entry,report.dryRun,hidden)))})),report.skipped.length>0&&(outputs.push(new IntentOutput8({title:"Left unanswered",result:new VariableSet4(reportedOnce(report.skipped,entry=>entry.reason).map(({entry,recipes,named})=>({label:entry.variable.definition.name,value:named?`${entry.reason} (used by ${recipes.join(", ")})`:entry.reason})))})),report.skipped.some(entry=>entry.reason===OPTIONAL_REASON)&&outputs.push(new IntentOutput8({summary:OPTIONAL_HINT}))),report.wouldAsk!==void 0&&report.wouldAsk.length>0&&outputs.push(new IntentOutput8({title:"Questions that would be asked",result:new VariableSet4(report.wouldAsk.flatMap(entry=>[{label:entry.variable.definition.name,value:entry.variable.definition.prompt,detail:recipeKey(entry.variable.recipe)},...entry.current===void 0?[]:[{label:"",value:`the value in scope does not fit: ${entry.current}`}],{label:"",value:`answer it ahead of time with ${answeredBy(entry.variable)}`}]))})),outputs.length===0&&outputs.push(new IntentOutput8({summary:"Every variable in play already has an answer that fits its definition."})),outputs}import{readFile as readFile2}from"node:fs/promises";import path63 from"node:path";import{InputError as InputError4}from"@sous-io/sous-plugin-api";var ANSWER_FLAG_FORM="--answer <name>=<value>",ANSWER_NAME_HELP="A name is spelled exactly as the recipe declares it, in camelCase; the full 'namespace/recipe.name' key works too.",INTENT="vars.ask";function answerError(field,lines3){return new InputError4(INTENT,[{path:field,message:lines3[0]??""}],{details:lines3})}function parseAnswerPair(entry,from="--answer"){let at2=entry.indexOf("="),name=at2===-1?"":entry.slice(0,at2).trim();if(at2===-1||name.length===0)throw answerError("answer",[`'${entry}' is not an answer sous can read.`,`Write one as '${ANSWER_FLAG_FORM}', for example '--answer apiUrl=https://api.example.com'.`,"Everything after the first '=' is the answer, so a value may contain more of them."]);return{name,value:entry.slice(at2+1),from}}function isEnvFile(filePath){let base=path63.basename(filePath);return base===".env"||base.startsWith(".env.")||base.endsWith(".env")}function answersFromData(raw2,filePath){if(typeof raw2!="object"||raw2===null||Array.isArray(raw2))throw answerError("answersFile",[`The answers file at ${filePath} is not a map of answers.`,"It holds one entry per variable, written as 'name: value'."]);let answers=[];for(let[name,value]of Object.entries(raw2)){if(typeof value=="object"&&value!==null)throw answerError("answersFile",[`The answer for '${name}' in ${filePath} is a list or a map, and an answer is a single value.`,"Answers are stored in environment files, which hold text; write the answer as a string, a number or a boolean."]);if(value==null)throw answerError("answersFile",[`The answer for '${name}' in ${filePath} is empty.`,"Write the value the variable should be given, or leave the entry out entirely so sous asks for it."]);answers.push({name:name.trim(),value:String(value),from:filePath})}return answers}function collectAnswers(fromFile,flags){let collected=new Map;for(let answer2 of fromFile)collected.set(answer2.name,answer2);for(let entry of flags){let answer2=parseAnswerPair(entry);collected.set(answer2.name,answer2)}return[...collected.values()]}function unknownAnswerError(answer2,variables){let lines3=[`Nothing in this project defines a variable called '${answer2.name}', so the answer given with ${answer2.from} cannot be stored.`];if(variables.length===0)return lines3.push("No recipe this project subscribes to defines any variables yet, so there is nothing to answer."),answerError(answer2.from==="--answer"?"answer":"answersFile",lines3);let groups=new Map;for(let entry of variables){let key=recipeKey(entry.recipe),names2=groups.get(key)??[];names2.includes(entry.definition.name)||names2.push(entry.definition.name),groups.set(key,names2)}lines3.push("","These are the variables in play, and the recipes that declare them:","");for(let[key,names2]of groups)lines3.push(` ${key}`,...names2.map(name=>` ${name}`));return lines3.push("",ANSWER_NAME_HELP),answerError(answer2.from==="--answer"?"answer":"answersFile",lines3)}function invalidAnswerError(answer2,variable,message2,hidden){let shown=variable.definition.secret?hidden:answer2.value;return answerError(answer2.from==="--answer"?"answer":"answersFile",[`The answer given for '${answer2.name}' does not fit the definition ${recipeKey(variable.recipe)} publishes.`,message2,`For example: ${String(variable.definition.example)}`,`The answer given with ${answer2.from} was: ${shown}`,"Nothing was written; fix the answer and run the command again."])}function matchAnswers(answers,variables,hidden="(hidden)"){let applicable=[];for(let answer2 of answers){let targets=variables.filter(entry=>namesVariable(entry,answer2.name));if(targets.length===0)throw unknownAnswerError(answer2,variables);for(let target of targets){if(target.unanswerable!==void 0)continue;let checked3=validateAnswer(target.definition,answer2.value,{recipe:recipeKey(target.recipe)});if(!checked3.ok)throw invalidAnswerError(answer2,target,checked3.message,hidden);applicable.push({answer:answer2,target,value:String(checked3.value)})}}return applicable}var PreanswersService=class{constructor(ctx){this.ctx=ctx}async read(inputs){let fromFile=inputs.answersFile===void 0?[]:await this.readFile(resolveUserPath(inputs.answersFile,this.ctx));return collectAnswers(fromFile,inputs.answer??[])}match(answers,variables){let secrets=this.ctx.services.has("variables.secrets")?this.ctx.services.get("variables.secrets"):void 0;return matchAnswers(answers,variables,secrets?.hiddenValue)}async readFile(filePath){if(isEnvFile(filePath)){let text;try{text=await readFile2(filePath,"utf8")}catch(error51){throw answerError("answersFile",[`Could not read the answers file at ${filePath}: ${error51.message}`])}return answersFromData(this.ctx.services.get("config-files.env").parse(text),filePath)}return answersFromData(await this.ctx.services.get("formats.manifests").readFile(filePath),filePath)}};import{ConfigError as ConfigError43,isSousErrorOfKind as isSousErrorOfKind4,NonInteractiveError as NonInteractiveError5}from"@sous-io/sous-plugin-api";var GLOB_CHARS3=/[*?[\]{}]/;function globToRegExp(pattern,ignoreCase){let source="",braces=0;for(let index=0;index<pattern.length;index+=1){let character=pattern[index];if(character==="*")source+=".*";else if(character==="?")source+=".";else if(character==="["){let end=pattern.indexOf("]",index+1);if(end===-1)source+="\\[";else{let body2=pattern.slice(index+1,end).replace(/^!/,"^").replace(/\\/g,"\\\\");source+=`[${body2}]`,index=end}}else character==="{"?(braces+=1,source+="(?:"):character==="}"&&braces>0?(braces-=1,source+=")"):character===","&&braces>0?source+="|":source+=character.replace(/[.+^$()|\\]/g,"\\$&")}return new RegExp(`^${source}$`,ignoreCase?"i":"")}function matchName(written,known){return GLOB_CHARS3.test(written)?globToRegExp(written,!1).test(known)?"exact":globToRegExp(written,!0).test(known)?"folded":void 0:written===known?"exact":written.toLowerCase()===known.toLowerCase()?"folded":void 0}function both2(left,right){if(!(left===void 0||right===void 0))return left==="folded"||right==="folded"?"folded":"exact"}function qualifies2(qualifier,variable){if(qualifier===void 0)return"exact";let result="exact";if(qualifier.name!==void 0&&(result=matchName(qualifier.name,variable.recipe.repo)),!(qualifier.location!==void 0&&qualifier.location.identity!==variable.recipe.identity))return result}function repoRef(variable){return{kind:"repo",name:variable.recipe.repo}}function namespaceRef2(variable){return{kind:"namespace",name:variable.recipe.namespace,repo:repoRef(variable)}}function recipeRef2(variable){return{kind:"recipe",name:variable.recipe.name,namespace:namespaceRef2(variable)}}function keyOf(ref){switch(ref.kind){case"repo":return`repo ${ref.name??""}`;case"namespace":return`namespace ${ref.repo?.name??""}:${ref.name}`;case"recipe":return`recipe ${ref.namespace?.repo?.name??""}:${ref.namespace?.name??""}/${ref.name}`;case"variable":return`variable ${ref.recipe?.namespace?.repo?.name??""}:${ref.recipe?.namespace?.name??""}/${ref.recipe?.name??""}.${ref.name}`;default:return`${ref.kind} ${"name"in ref?String(ref.name):""}`}}function carry2(candidate,known){return candidate.vars===void 0?known:{...known,vars:candidate.vars}}function envNamesOf(variable,ladder){let inUse=ladder.namesInFiles(),names2=new Set([ladder.bareName(variable)]);for(let candidate of ladder.candidates(variable))inUse.has(candidate.envName)&&names2.add(candidate.envName);return names2}function matchVariables(pool,candidate,ladder){let found=new Map,add=(ref,spelling)=>{if(spelling===void 0)return;let key=keyOf(ref),known=found.get(key);(known===void 0||!known.exactSpelling&&spelling==="exact")&&found.set(key,{ref,exactSpelling:spelling==="exact"})};if(candidate.kind==="envVar"){if(ladder===void 0)return[];let variables=pool.filter(entry=>envNamesOf(entry,ladder).has(candidate.name)).map(entry=>entry.ref);return variables.length===0?[]:[{ref:carry2(candidate,{kind:"envVar",name:candidate.name,variables}),exactSpelling:!0}]}for(let variable of pool)switch(candidate.kind){case"repo":(candidate.name!==void 0||candidate.location!==void 0)&&add(carry2(candidate,repoRef(variable)),qualifies2(candidate,variable));break;case"namespace":add(carry2(candidate,namespaceRef2(variable)),both2(qualifies2(candidate.repo,variable),matchName(candidate.name,variable.recipe.namespace)));break;case"recipe":{let inNamespace=candidate.namespace===void 0?"exact":matchName(candidate.namespace.name,variable.recipe.namespace),spelling=both2(both2(qualifies2(candidate.namespace?.repo??candidate.repo,variable),inNamespace),matchName(candidate.name,variable.recipe.name));add(carry2(candidate,{...recipeRef2(variable),...candidate.range===void 0?{}:{range:candidate.range}}),spelling);break}case"variable":{let spelling=qualifies2(candidate.recipe?.namespace?.repo??candidate.recipe?.repo??candidate.repo,variable);candidate.recipe!==void 0&&(spelling=both2(spelling,matchName(candidate.recipe.name,variable.recipe.name)),candidate.recipe.namespace!==void 0&&(spelling=both2(spelling,matchName(candidate.recipe.namespace.name,variable.recipe.namespace)))),add(carry2(candidate,variable.ref),both2(spelling,matchName(candidate.name,variable.definition.name)));break}default:break}return[...found.values()].sort((left,right)=>keyOf(left.ref)<keyOf(right.ref)?-1:keyOf(left.ref)>keyOf(right.ref)?1:0)}function partsOf(ref){switch(ref.kind){case"repo":return{...ref.name===void 0?{}:{repo:ref.name}};case"namespace":return{...ref.repo?.name===void 0?{}:{repo:ref.repo.name},namespace:ref.name};case"recipe":{let repo=ref.namespace?.repo?.name??ref.repo?.name;return{...repo===void 0?{}:{repo},...ref.namespace===void 0?{}:{namespace:ref.namespace.name},recipe:ref.name}}case"variable":return ref.recipe===void 0?{...ref.repo?.name===void 0?{}:{repo:ref.repo.name}}:partsOf(ref.recipe);default:return{}}}function narrowTo(pool,match2){let target=match2.kind==="envVar"?match2.variables?.[0]:match2;if(target===void 0||target.kind==="recipeFile")return[];let{repo,namespace,recipe}=partsOf(target);return pool.filter(entry=>repo!==void 0&&entry.recipe.repo!==repo?!1:target.kind==="repo"?!0:namespace!==void 0&&entry.recipe.namespace!==namespace?!1:target.kind==="namespace"?!0:recipe!==void 0&&entry.recipe.name!==recipe?!1:target.kind==="recipe"?!0:entry.definition.name===target.name)}var SEE_ALL="Run 'sous vars' to see every variable this project's recipes define.";function describeSelection(input){let parts=[];input.repo!==void 0&&parts.push(`the repository '${input.repo}'`),input.namespace!==void 0&&parts.push(`the namespace '${input.namespace}'`),input.recipe!==void 0&&parts.push(`the recipe '${input.recipe}'`),input.name!==void 0&&parts.push(`'${input.name}'`);for(let wanted of input.var??[])parts.push(`the variable '${wanted}'`);return parts.length===0?input.all===!0?"every variable":"everything unanswered":parts.join(", ")}async function resolveSelection(pool,ladder,input,io){let{name,repo,namespace,recipe}=input,vars=input.var;if(name===void 0&&repo===void 0&&namespace===void 0&&recipe===void 0&&vars===void 0)return;let left=[...pool],pick3=(search2,kinds)=>pickOne(search2,left,ladder,kinds,input.acceptFirst===!0,io);if(repo!==void 0&&(left=narrowTo(left,await pick3(repo,["repo"]))),namespace!==void 0&&(left=narrowTo(left,await pick3(namespace,["namespace"]))),recipe!==void 0){let exact=left.filter(entry=>recipeKey(entry.recipe)===recipe);left=exact.length>0?exact:narrowTo(left,await pick3(recipe,["recipe"]))}if(name!==void 0&&(left=narrowTo(left,await pick3(name))),vars!==void 0){let chosen=[];for(let wanted of vars)chosen.push(...narrowTo(left,await pick3(wanted,["variable","envVar"])));left=chosen}if(left.length===0)throw new ConfigError43(`Nothing is left to ask: ${describeSelection({...input,all:!1})} names no variable this project holds.`,{details:[SEE_ALL]});return new Set(left.map(entry=>entry.key))}function candidatesFor(search2,pool,ladder,kinds,services){let readings;try{readings=services.get("refs.resolver").parse(search2,"commandLine").refs}catch{readings=[]}let found=new Map;for(let reading of readings)if(!(kinds!==void 0&&!kinds.includes(reading.kind)))for(let match2 of matchVariables(pool,reading,ladder)){let key=`${match2.ref.kind} ${JSON.stringify(match2.ref)}`;found.has(key)||found.set(key,{ref:match2.ref,exact:match2.exactSpelling})}let all=[...found.values()];return(all.some(entry=>entry.exact)?all.filter(entry=>entry.exact):all).flatMap(({ref})=>ref.kind==="envVar"&&(ref.variables?.length??0)>1?ref.variables.map(variable=>({...ref,variables:[variable]})):[ref])}async function pickOne(search2,pool,ladder,kinds,acceptFirst2,io){let candidates=candidatesFor(search2,pool,ladder,kinds,io.services);if(candidates.length===0)throw new ConfigError43(`Nothing called '${search2}' was found.`,{details:[SEE_ALL]});if(candidates.length===1)return candidates[0];try{return await io.services.get("refs.picker").pick(candidates,{search:search2,acceptFirst:acceptFirst2,announce:!1,details:[SEE_ALL]},io)}catch(error51){throw isSousErrorOfKind4(error51,"non-interactive")?ambiguityError(search2,error51):error51}}function ambiguityError(search2,cause){let error51=new NonInteractiveError5(cause.question,cause.answeredBy,{cause,details:cause.details,exitCode:1});return error51.message=`Sous has to ask which '${search2}' you meant, and it is not running where it can ask.`,error51}var FILE_FIELD={type:"string",description:"Read the variable definitions from a standalone definitions file instead of the project's recipes"};function definitionsLabel(file2){return file2??"the project's subscribed recipes"}function ladderFor(ctx){return buildLadder({services:ctx.services,env:ctx.env,config:ctx.config})}function listingOf(variable,ladder,hidden){let resolved=ladder.resolve(variable),fallback2=resolved===void 0&&variable.unanswerable===void 0?variable.definition.default:void 0;return{variable,answered:resolved!==void 0,...resolved===void 0?{}:{value:displayValue(resolved.value,variable.definition.secret,hidden),source:resolved.source},...fallback2===void 0?{}:{value:displayValue(String(fallback2),variable.definition.secret,hidden),usesDefault:!0},storedAs:resolved?.source.envName??ladder.bareName(variable),storeIn:answerFileFor(variable.definition)}}function detailOf(variable,ladder,hidden){let diagnosis=ladder.diagnose(variable),checked3=diagnosis.resolved===void 0?void 0:validateAnswer(variable.definition,diagnosis.resolved.value,{recipe:recipeKey(variable.recipe)}),mapping=diagnosis.resolved?.source.rung==="mapping"?diagnosis.resolved.source.envName:void 0,shownDiagnosis=diagnosis.resolved===void 0||!variable.definition.secret?diagnosis:{...diagnosis,resolved:{...diagnosis.resolved,value:hidden}};return{...listingOf(variable,ladder,hidden),diagnosis:shownDiagnosis,constraints:constraintBullets(variable.definition),...checked3?.ok===!1?{problem:checked3.message}:{},...mapping===void 0?{}:{mapping:{envName:mapping,target:ladder.mappings[mapping]??""}}}}function variablesNamed(variables,name,ladder){let byName=variables.filter(entry=>namesVariable(entry,name)),matches=byName.length>0?byName:variables.filter(entry=>ladder.candidates(entry).some(candidate=>candidate.envName===name));if(matches.length===0)throw new ConfigError44(`No variable named '${name}' is in play.`,{details:["Run 'sous vars list' to see every variable this project's recipes define."]});return matches}function storeFor(ctx){let env=ctx.services.get("config-files.env");return{envPath:file2=>env.paths()?.[file2]??(file2==="local"?".sous/.env.local":".sous/.env"),mappingPath:()=>ctx.services.get("confd.managed").path(VAR_MAPPINGS_FILE),writeAnswer:async(file2,envName,value,comment)=>{await env.write(file2,{[envName]:value},{comment})},writeMapping:async(envName,target)=>{let mappings=ctx.services.get("recipe-answers.mappings");return(await mappings.set(envName,mappings.parseTarget(target))).file}}}function chosenEnvFile(input){if(input.saveLocally===!0&&input.saveShared===!0)throw new ConfigError44("--save-locally and --save-shared cannot be used together: each names a different file for every answer of the run.");return input.saveLocally===!0?"local":input.saveShared===!0?"shared":void 0}function holdingStore(real3){let writes=[];return{envPath:file2=>real3.envPath(file2),mappingPath:()=>real3.mappingPath(),writeAnswer:async(file2,envName,value,comment)=>{writes.push(()=>real3.writeAnswer(file2,envName,value,comment))},writeMapping:async(envName,target)=>(writes.push(()=>real3.writeMapping(envName,target)),real3.mappingPath()),get held(){return writes.length},write:async()=>{for(let one of writes.splice(0))await one()}}}async function handleAsk(input,ctx){return(await askOnce(input,ctx,storeFor(ctx))).outputs}var asking={async hold(variables,input,ctx){let store2=holdingStore(storeFor(ctx));return{outputs:(await askOnce({within:[...input.within],...input.answer===void 0?{}:{answer:[...input.answer]},...input.answersFile===void 0?{}:{answersFile:input.answersFile},...input.yes===!0?{yes:!0}:{}},ctx,store2,variables)).outputs,empty:store2.held===0,write:()=>store2.write()}}};async function askOnce(input,ctx,store2,defined){let dryRun4=input.dryRun===!0,hidden=hiddenValue(ctx.services),envFile=chosenEnvFile(input),reportSettings=()=>ctx.reporter.variables([{label:"Definitions",value:definitionsLabel(input.file)},{label:"Asking",value:describeSelection(input)},...envFile===void 0?[]:[{label:"Env file",value:store2.envPath(envFile)}]]),deferSettings=input.within!==void 0;deferSettings||reportSettings(),dryRun4&&ctx.reporter.dryRun("No answers will be written.");let preanswers=ctx.services.get("recipe-answers.preanswers"),provided=await preanswers.read(input.answersFile===void 0?input:{...input,answersFile:resolveUserPath(input.answersFile,ctx)}),variables=defined===void 0?await ctx.services.get("recipe-answers.definitions").list(input.file===void 0?{}:{file:resolveUserPath(input.file,ctx)}):[...defined];if(variables.length===0){if(provided[0]!==void 0)throw unknownAnswerError(provided[0],variables);let empty={answered:[],inherited:[],skipped:[],dryRun:dryRun4};return{outputs:new IntentOutputs10([new IntentOutput9({title:"Answering variables"}),new IntentOutput9({result:new TextBlock6("No recipe in this project defines any variables yet, so there is nothing to ask. Subscribe to a recipe that publishes some, or read a definitions file with --file."),style:ReportEntryStyle5.Note})]).withData(empty)}}let ladder=ladderFor(ctx),only=await resolveSelection(variables,ladder,input,ctx),run={prompter:ctx.prompter,reporter:ctx.reporter,store:store2,hidden,dryRun:dryRun4,...envFile===void 0?{}:{envFile},yes:input.yes===!0,...deferSettings?{beforeReporting:reportSettings}:{}},given=await storeGivenAnswers(preanswers.match(provided,variables),ladder,run),report=await askForMissing(variables,ladder,{...only===void 0?{}:{only},...input.within===void 0?{}:{within:new Set(input.within)},skip:given.keys,reask:input.all===!0},run),result={answered:[...given.stored,...report.answered],inherited:report.inherited.map(({variable,resolved})=>({variable,resolved:variable.definition.secret?{...resolved,value:hidden}:resolved})),skipped:report.skipped,...report.wouldAsk.length===0?{}:{wouldAsk:report.wouldAsk},dryRun:dryRun4};!dryRun4&&result.answered.some(entry=>entry.outcome!=="not written")&&ctx.configChanged();let entries=result.answered.length>0||result.inherited.length>0||result.skipped.length>0||report.wouldAsk.length>0?askReportOutputs(result,hidden):[];return{outputs:new IntentOutputs10([new IntentOutput9({title:"Answering variables"}),...entries]).withData(result)}}async function handleList(input,ctx){let variables=await ctx.services.get("recipe-answers.definitions").list(input.file===void 0?{}:{file:resolveUserPath(input.file,ctx)}),ladder=ladderFor(ctx),hidden=hiddenValue(ctx.services),opening=commandVariables2(ctx,{Definitions:definitionsLabel(input.file)});if(input.name!==void 0){let details=variablesNamed(variables,input.name,ladder).map(variable=>detailOf(variable,ladder,hidden)),shown=details.flatMap(detail=>variableDetailOutputs(detail,hidden,ctx.project?.sousDir));return new IntentOutputs10([opening,...shown]).withData({variables:details})}let listings=variables.map(variable=>listingOf(variable,ladder,hidden));return new IntentOutputs10([opening,variableListOutput(listings,hidden)]).withData({variables:listings})}async function handleShow(input,ctx){let variables=await ctx.services.get("recipe-answers.definitions").list(input.file===void 0?{}:{file:resolveUserPath(input.file,ctx)}),ladder=ladderFor(ctx),matches=variablesNamed(variables,input.name,ladder),hidden=hiddenValue(ctx.services),opening=commandVariables2(ctx,{Definitions:definitionsLabel(input.file)}),outputsOf2=variable=>{let detail=detailOf(variable,ladder,hidden);return new IntentOutputs10([opening,...variableDetailOutputs(detail,hidden,ctx.project?.sousDir)]).withData(detail)};if(matches.length===1)return outputsOf2(matches[0]);let picked=await ctx.services.get("refs.picker").pick(matches.map(entry=>entry.ref),{search:input.name,acceptFirst:input.acceptFirst===!0,announce:!1,details:[SEE_ALL]},ctx),chosen=matches.find(entry=>entry.ref===picked)??matches.find(entry=>JSON.stringify(entry.ref)===JSON.stringify(picked))??matches[0];return outputsOf2(chosen)}async function handleMap(input,ctx){let mappings=ctx.services.get("recipe-answers.mappings"),dryRun4=input.dryRun===!0;if(input.remove===!0){let{file:file3,changed:changed3}=await mappings.remove(input.envName,{dryRun:dryRun4});changed3&&!dryRun4&&ctx.configChanged();let removal=changed3?`${dryRun4?"Would remove":"Removed"} the mapping of ${input.envName} in ${file3}.`:`${input.envName} has no mapping in ${file3}.`;return IntentOutputs10.of({envName:input.envName,file:file3,changed:changed3,dryRun:dryRun4},{summary:removal})}if(input.target===void 0)throw new InputError5("vars.map",[{path:"target",message:"Name the variable to bind, as 'namespace/recipe/variableName', or pass --remove."}]);let target=mappings.formatTarget(mappings.parseTarget(input.target)),{file:file2,changed:changed2}=await mappings.set(input.envName,mappings.parseTarget(target),{dryRun:dryRun4});return changed2&&!dryRun4&&ctx.configChanged(),IntentOutputs10.of({envName:input.envName,target,file:file2,changed:changed2,dryRun:dryRun4},{summary:changed2?`${dryRun4?"Would map":"Mapped"} ${input.envName} to ${target} in ${file2}.`:`${input.envName} is already mapped to ${target}.`})}var varsIntents=[{intent:"vars.ask",needsRecipeFiles:!0,summary:"Answer the variables this project's recipes define, storing the answers in the .sous env files",description:"Asks only what is unanswered or no longer fits; --all asks everything again. The name may be a variable, an environment variable name, a recipe, a namespace or a repository. Every question can be answered ahead of time with --answer <name>=<value> or --answers-file.",input:jsonSchema16({type:"object",properties:{name:{type:"string",description:"What to ask about: a variable, an environment variable name, a recipe, a namespace or a repository"},all:{type:"boolean",default:!1,description:"Ask every variable again, including the ones already answered"},repo:{type:"string",description:"Ask only the variables published by this repository"},namespace:{type:"string",description:"Ask only the variables published in this namespace"},recipe:{type:"string",description:"Ask only the variables published by this recipe (namespace/recipe)"},var:{type:"array",items:{type:"string"},description:"Ask only this variable"},within:{type:"array",items:{type:"string"},description:"Ask only what the recipes named here (namespace/recipe) still need"},acceptFirst:{type:"boolean",default:!1,description:"When a name matches several things, take the first one listed"},file:FILE_FIELD,dryRun:{type:"boolean",default:!1,description:"Report what would be asked and written, without writing anything"},answer:{type:"array",items:{type:"string"},description:"Answer a variable ahead of its question, as <name>=<value>"},answersFile:{type:"string",description:"Read answers from a YAML, JSON or .env file of name: value pairs"},saveLocally:{type:"boolean",default:!1,description:"Store every answer of this run in .sous/.env.local, which is gitignored and stays on this machine"},saveShared:{type:"boolean",default:!1,description:"Store every answer of this run in .sous/.env, which is committed and shared with everyone on the project"},yes:{type:"boolean",default:!1,description:"Answer yes to storing a secret or machine-specific answer in the committed .sous/.env"}},additionalProperties:!1}),cli:{command:["vars","ask"],positional:["name"],examples:["sous vars ask","sous vars ask apiUrl","sous vars ask SOUS_VAR_API_URL","sous vars ask workflow/task-files","sous vars ask workflow --accept-first","sous vars ask --namespace workflow --var apiUrl","sous vars ask --all","sous vars ask --file ./questions.yaml","sous vars ask --answer apiUrl=https://api.example.com","sous vars ask --answers-file ./answers.yaml","sous vars ask --save-locally"],flags:{within:{hidden:!0},yes:{short:"y",aliases:["force"]}}},agent:{usage:"Pass every answer with `answer` (name=value pairs) or `answersFile`; questions cannot be asked through MCP unless the client supports elicitation."},requiresProject:!0,handle:handleAsk},{intent:"vars.list",needsRecipeFiles:!0,summary:"List every variable this project's recipes define, with its answer",input:jsonSchema16({type:"object",properties:{name:{type:"string",description:"A variable's name, its namespace/recipe.name key, or an environment variable name that answers it, to show in full"},file:FILE_FIELD},additionalProperties:!1}),parallel:!0,cli:{command:["vars","list"],aliases:[["vars","ls"],["vars"]],positional:["name"],examples:["sous vars","sous vars apiUrl","sous vars list","sous vars list --file ./questions.yaml"]},requiresProject:!0,handle:handleList},{intent:"vars.show",needsRecipeFiles:!0,summary:"Show everything about one variable, including how it was answered",input:jsonSchema16({type:"object",properties:{name:{type:"string",description:"A variable's name, its namespace/recipe.name key, or an environment variable name that answers it"},file:FILE_FIELD,acceptFirst:{type:"boolean",default:!1,description:"When the name matches several variables, take the first one listed"}},required:["name"],additionalProperties:!1}),parallel:!0,cli:{command:["vars","show"],positional:["name"],examples:["sous vars show apiUrl","sous vars show workflow/task-files.apiUrl","sous vars show SOUS_VAR_API_URL"]},requiresProject:!0,handle:handleShow},{intent:"vars.map",needsRecipeFiles:!0,summary:"Bind an environment variable to one recipe variable, in conf.d/520-var-mappings.jsonc",input:jsonSchema16({type:"object",properties:{envName:{type:"string",description:"The environment variable name, in upper snake case"},target:{type:"string",description:"The variable it answers: namespace/recipe/variableName, optionally repo:-qualified"},remove:{type:"boolean",default:!1,description:"Remove the mapping instead"},dryRun:{type:"boolean",default:!1,description:"Report what would change, without writing anything"}},required:["envName"],additionalProperties:!1}),changesConfig:!0,cli:{command:["vars","map"],positional:["envName","target"],examples:["sous vars map TEAM_API_URL sous-recipes:misc/stuff/apiUrl","sous vars map TEAM_API_URL --remove"]},requiresProject:!0,handle:handleMap}];var VARIABLES_TAG="variables",variableLookup={id:"recipe-answers.variables",description:"the variables the active recipes define",kinds:["repo","namespace","recipe","variable"],tags:[VARIABLES_TAG],optIn:!0,find:async(candidate,ctx)=>variableLookup.findSync(candidate,ctx),findSync:(candidate,ctx)=>matchVariables(ctx.services.get("recipe-answers.definitions").listSync(),candidate)},envVarLookup={id:"recipe-answers.env-vars",description:"the environment variable names that answer recipe variables",kinds:["envVar"],tags:[VARIABLES_TAG],optIn:!0,find:async(candidate,ctx)=>envVarLookup.findSync(candidate,ctx),findSync:(candidate,ctx)=>matchVariables(ctx.services.get("recipe-answers.definitions").listSync(),candidate,buildLadder({services:ctx.services,env:ctx.env,config:ctx.config}))};var VARIABLE_SOURCE_ID="recipe-answers",FORBIDDEN_UNDER=["subscriptions","repos"];function recipeAnswersSource(variables,services){let answers=ctx=>computeAnswers(variables,buildLadder({services,env:ctx.env,config:ctx.config})),scopeKeys=new Set([...variables.map(entry=>`${entry.recipe.namespace}/${entry.recipe.name}`),...variables.flatMap(entry=>entry.unanswerable===void 0?[]:entry.recipe.holders??[])]);return{id:VARIABLE_SOURCE_ID,description:"recipe answers",definitions:variables,variables:ctx=>variables.length===0?{}:answers(ctx).merged,scoped:(scopeKey,ctx)=>{if(scopeKeys.has(scopeKey))return answersForRecipe(answers(ctx),scopeKey)},secrets:()=>variables.filter(entry=>entry.definition.secret).map(entry=>entry.definition.name),booleans:()=>booleanNames(variables),forbiddenUnder:FORBIDDEN_UNDER}}function variableSourceContributor(services){return{id:"recipe-answers.variable-source",after:["@sous-io/sous-plugin-recipes"],contribute(config2){let variables=definitionsFromRecipes(config2.entities("active-recipe"));config2.addEntity("variable-source",recipeAnswersSource(variables,services))}}}var package_default13={name:"@sous-io/sous-plugin-recipe-answers",version:"1.1.4",description:"Recipe variable definitions, the answer ladder, asking for answers, answer files and variable mappings.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-recipes":"workspace:*","@sous-io/sous-plugin-confd":"workspace:*","@sous-io/sous-plugin-config-files":"workspace:*","@sous-io/sous-plugin-formats":"workspace:*","@sous-io/sous-plugin-refs":"workspace:*","@sous-io/sous-plugin-variables":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME12="@sous-io/sous-plugin-recipe-answers",recipeAnswersPlugin=definePlugin13({name:PLUGIN_NAME12,version:package_default13.version,description:"Recipe variable definitions, the answer ladder, asking for answers, answer files and variable mappings.",dependsOn:{"@sous-io/sous-plugin-recipes":`^${package_default13.version}`,"@sous-io/sous-plugin-confd":`^${package_default13.version}`,"@sous-io/sous-plugin-config-files":`^${package_default13.version}`,"@sous-io/sous-plugin-formats":`^${package_default13.version}`,"@sous-io/sous-plugin-refs":`^${package_default13.version}`,"@sous-io/sous-plugin-variables":`^${package_default13.version}`},register(sous){sous.services.add("recipe-answers.definitions",(_config,ctx)=>new DefinitionsService(ctx),{lifetime:"config"}),sous.services.add("recipe-answers.ladder",(config2,ctx)=>buildLadder({services:ctx.services,env:ctx.env,config:config2}),{lifetime:"config"}),sous.services.add("recipe-answers.answers",(_config,ctx)=>new AnswersService(()=>computeAnswers(ctx.services.get("recipe-answers.definitions").listSync(),ctx.services.get("recipe-answers.ladder"))),{lifetime:"config"}),sous.services.add("recipe-answers.preanswers",(_config,ctx)=>new PreanswersService(ctx),{lifetime:"factory"}),sous.services.add("recipe-answers.mappings",(_config,ctx)=>new MappingsService(ctx),{lifetime:"config"}),sous.services.add("recipe-answers.validator",()=>validator,{lifetime:"singleton"}),sous.services.add("recipe-answers.asking",()=>asking,{lifetime:"singleton"}),sous.entities.add("config-key",{id:"varMappings",description:"Environment variable names bound to recipe variables (conf.d/520-var-mappings.jsonc).",schema:jsonSchema17({type:"object",additionalProperties:{type:"string"},default:{}})}),sous.entities.add("ref-lookup",variableLookup),sous.entities.add("ref-lookup",envVarLookup),sous.config.contribute(variableSourceContributor(sous.services));for(let intent of varsIntents)sous.intents.add(intent)}});import{definePlugin as definePlugin14}from"@sous-io/sous-plugin-api";import path64 from"node:path";function transformIdFor(targetId){return`skills/${targetId}`}function outputDir(directory){let trimmed=directory.trim();if(path64.isAbsolute(trimmed))return stripTrailingSlash(path64.normalize(trimmed));if(trimmed.startsWith("${"))return stripTrailingSlash(trimmed);let relative4=path64.posix.normalize(trimmed.split(path64.sep).join("/"));return relative4==="."?"${projectRoot}":`\${projectRoot}/${stripTrailingSlash(relative4.replace(/^\.\//,""))}`}function skillDestinations(outputs,targets){let destinations=[],seen=new Set;for(let target of targets){if(typeof target.directory!="string"||target.directory.trim()==="")continue;let dir=outputDir(target.directory);seen.has(dir)||(seen.add(dir),destinations.push({dir,target:target.id,...typeof target.transform=="function"?{transform:transformIdFor(target.id)}:{},...typeof target.harness=="string"&&target.harness!==""?{harness:target.harness}:{}}))}for(let output of outputs){let dir=outputDir(output);seen.has(dir)||(seen.add(dir),destinations.push({dir}))}return destinations}function stripTrailingSlash(value){return value.length>1&&value.endsWith("/")?value.slice(0,-1):value}import{jsonSchema as jsonSchema18}from"@sous-io/sous-plugin-api";var SKILLS_KEY="recipes.skills",stringList2={type:"array",items:{type:"string"},default:[]},skillsConfigKey={id:SKILLS_KEY,description:"Where skills go (outputs, `${var}` allowed) and directories of your own skills (include).",schema:jsonSchema18({type:"object",properties:{outputs:{...stringList2,description:"Directories skills are also written to."},include:{...stringList2,description:"Directories of your own skills, compiled like a recipe's."}},additionalProperties:!1,default:{}})};function stringsOf(value){return Array.isArray(value)?value.filter(item=>typeof item=="string"&&item.trim()!==""):[]}function describeNowhere(sources){let recipes=new Set(sources.flatMap(source=>source.recipe===void 0?[]:[source.recipe])).size,own=sources.filter(source=>source.origin==="project").length,parts=[];if(recipes>0&&parts.push(`the skills of ${recipes} ${recipes===1?"recipe":"recipes"}`),own>0&&parts.push(`${own} ${own===1?"skill":"skills"} of your own`),parts.length!==0)return{summary:`Skipped ${parts.join(" and ")}: nothing says where skills go.`,hint:"Set recipes.skills.outputs in the config, or enable an agent plugin (such as @sous-io/sous-plugin-claude-code)."}}function skillWarnings(ctx){if(!ctx.services.has("skills.sources"))return[];let sources=ctx.services.get("skills.sources"),warnings=(sources.problems?.()??[]).map(summary2=>({summary:summary2}));if(skillDestinations(stringsOf(ctx.config.get("recipes.skills.outputs")),ctx.entities.list("skill-target")).length===0){let nowhere=describeNowhere(sources.list());nowhere&&warnings.push(nowhere)}return warnings}init_index_min();import fs49 from"node:fs";import path65 from"node:path";function bytewise(a,b){return a<b?-1:a>b?1:0}function findSkills(input){let skills=[],problems=[],repositories=new Map(input.recipes.map(recipe=>[recipe.id,recipe.repo]));for(let content of input.contents)skills.push(...recipeSkills(content,repositories.get(content.recipe)));return input.include.forEach((entry,index)=>{let setting=`recipes.skills.include[${index}]`,dir=resolveProjectDir(entry,input.project);if(typeof dir!="string"){problems.push({setting,message:`${setting} is "${entry}": ${dir.reason}`});return}if(!isDirectory2(dir)){problems.push({setting,message:`${setting} is "${entry}", which is not a directory, so it was skipped.`});return}skills.push(...groupSkills({origin:"project"},[{base:dir,files:listFiles2(dir,"**/*",[])}]))}),{skills,problems}}function recipeSkills(content,repository){let byBase=new Map,inline=new Map;for(let{base,file:file2,content:text}of content.files)byBase.set(base,[...byBase.get(base)??[],file2]),text!==void 0&&inline.set(file2,text);let skills=groupSkills({origin:"recipe",recipe:content.recipe,...repository===void 0?{}:{repository}},[...byBase].map(([base,files])=>({base,files})));return inline.size===0?skills:skills.map(skill=>{let own=new Map([...inline].filter(([file2])=>skill.files.some(relative4=>path65.join(skill.dir,relative4)===file2)));return own.size===0?skill:{...skill,inline:own}})}function groupSkills(from,groups){let byDir=new Map;for(let group of groups)for(let file2 of group.files){let relative4=path65.relative(group.base,file2);if(relative4===""||relative4.startsWith("..")||path65.isAbsolute(relative4))continue;let[first2]=relative4.split(path65.sep),nested=relative4!==first2,dir=nested?path65.join(group.base,first2):group.base,name=nested?first2:withoutExtensions(first2),key=`${dir}\0${nested?"":name}`,skill=byDir.get(key);skill||(skill={name,base:group.base,files:new Set},byDir.set(key,skill)),skill.files.add(path65.relative(dir,file2).split(path65.sep).join("/"))}return[...byDir.entries()].map(([key,skill])=>({name:skill.name,...from,dir:key.slice(0,key.indexOf("\0")),base:skill.base,files:[...skill.files].sort(bytewise)})).sort((a,b)=>bytewise(a.name,b.name)||bytewise(a.dir,b.dir))}function listFiles2(cwd,pattern,exclude){return isDirectory2(cwd)?ts(pattern,{cwd,absolute:!0,nodir:!0,ignore:[...exclude]}).filter(isFile9).sort(bytewise):[]}function resolveProjectDir(entry,project){let substituted=entry.replace(/\$\{(projectRoot|sousDir)\}/g,(_match,name)=>project?name==="projectRoot"?project.root:project.sousDir:_match);return/\$\{[^}]*\}/.test(substituted)?{reason:project?"only ${projectRoot} and ${sousDir} can be used here, so it was skipped.":"there is no project to resolve it in, so it was skipped."}:path65.isAbsolute(substituted)?path65.normalize(substituted):project?path65.resolve(project.root,substituted):{reason:"a relative directory needs a project, and there is none, so it was skipped."}}function withoutExtensions(name){let dot=name.indexOf(".",1);return dot===-1?name:name.slice(0,dot)}function isDirectory2(candidate){try{return fs49.statSync(candidate).isDirectory()}catch{return!1}}function isFile9(candidate){try{return fs49.statSync(candidate).isFile()}catch{return!1}}var ConfigSkillsSources=class{constructor(config2,ctx){this.config=config2;this.ctx=ctx}found;list(){return this.find().skills.map(({base:_base,inline:_inline,...source})=>source)}recipes(){return[...new Set(this.find().skills.flatMap(skill=>skill.recipe===void 0?[]:[skill.recipe]))]}problems(){return this.find().problems.map(problem=>problem.message)}find(){return this.found??=findSkills({recipes:this.ctx.entities.list("active-recipe"),contents:this.ctx.services.get("recipes.contents").of(this.config,"skills"),include:stringsOf(this.config.get("recipes.skills.include")),project:this.ctx.project}),this.found}};import{jsonSchema as jsonSchema19}from"@sous-io/sous-plugin-api";var SKILL_TARGET="skill-target",skillTargetSchema=jsonSchema19({type:"object",properties:{id:{type:"string",description:"The target's name: `claude-code`."},harness:{type:"string",description:"The `harness` entity that reads it."},directory:{type:"string",description:"The directory skills go into; relative paths are under the project root."},description:{type:"string"}},required:["id","directory"]}),SKILL_TARGET_DESCRIPTION="A place a harness reads skills from, with an optional transform of each file.";import path66 from"node:path";var TARGETS_CONTRIBUTOR="skills.targets";function contributeSkillTargets(config2,plugin,contents){let outputs=stringsOf(config2.atPath("recipes.skills.outputs").get()),include=stringsOf(config2.atPath("recipes.skills.include").get()),targets=config2.entities("skill-target"),destinations=skillDestinations(outputs,targets);if(destinations.length===0)return;let input={contents:contents.of(config2,"skills"),recipes:config2.entities("active-recipe"),include,project:config2.project},{skills}=findSkills(input);if(skills.length===0)return;let origins=new Map,list2=config2.atPath("compilation.targets");for(let skill of skills)for(let file2 of skill.files){let entryPoint=path66.join(skill.dir,file2);origins.set(entryPoint,skill.recipe===void 0?{skill:skill.name}:{skill:skill.name,recipe:skill.recipe}),list2.append(compilationTarget(skill,entryPoint,destinations,plugin,config2.project?.root))}for(let target of targets)typeof target.transform=="function"&&destinations.some(d=>d.target===target.id)&&config2.addEntity("compilation-transform",transformEntity(target,origins))}function compilationTarget(skill,entryPoint,destinations,plugin,projectRoot){let fromBase=path66.relative(skill.base,entryPoint).split(path66.sep).join("/"),where3=skill.recipe??`project:${projectRoot?path66.relative(projectRoot,skill.base).split(path66.sep).join("/")||".":skill.base}`,inline=skill.inline?.get(entryPoint);return inline!==void 0?{id:`skills/${where3}/${fromBase}`,content:inlineTemplate(inline,fromBase),origin:{plugin,...skill.recipe===void 0?{}:{recipe:skill.recipe},...skill.repository===void 0?{}:{repository:skill.repository}},outputs:destinations.map(destination=>outputFor(destination,{destinationFile:`${destination.dir.replace(/\/+$/,"")}/${fromBase}`}))}:{id:`skills/${where3}/${fromBase}`,entryPoint,globBase:skill.base,origin:{plugin,...skill.recipe===void 0?{}:{recipe:skill.recipe},...skill.repository===void 0?{}:{repository:skill.repository}},outputs:destinations.map(destination=>outputFor(destination,{destinationDir:destination.dir}))}}function outputFor(destination,where3){return{...where3,...destination.transform===void 0?{}:{transforms:[destination.transform]},...destination.harness===void 0?{}:{harness:destination.harness}}}function inlineTemplate(content,virtualPath){return path66.posix.basename(virtualPath).includes(".tpl.")?content:`{% raw %}${content}{% endraw %}`}function transformEntity(target,origins){let transform2=target.transform;return{id:transformIdFor(target.id),description:`The transform of the skill target "${target.id}".`,async transform(file2,ctx){let origin=origins.get(file2.source)??{skill:path66.basename(path66.dirname(file2.source))},skillFile={...file2,...origin};return transform2(skillFile,ctx)}}}var package_default14={name:"@sous-io/sous-plugin-skills",version:"1.1.4",description:"Skills: where they come from, the skill-target entity, and the compilation targets for them.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-compiler":"workspace:*","@sous-io/sous-plugin-recipes":"workspace:*",glob:"^13.0.6"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME13="@sous-io/sous-plugin-skills",skillsPlugin=definePlugin14({name:PLUGIN_NAME13,version:package_default14.version,description:"Skills: where they come from, the skill-target entity, and the compilation targets for them.",dependsOn:{"@sous-io/sous-plugin-compiler":`^${package_default14.version}`,"@sous-io/sous-plugin-recipes":`^${package_default14.version}`},register(sous){sous.entities.define(SKILL_TARGET,skillTargetSchema,{description:SKILL_TARGET_DESCRIPTION}),sous.entities.add("config-key",skillsConfigKey),sous.services.add("skills.sources",(config2,ctx)=>new ConfigSkillsSources(config2,ctx),{lifetime:"config"});let services=sous.services;sous.config.contribute({id:TARGETS_CONTRIBUTOR,after:["@sous-io/sous-plugin-recipes"],contribute:config2=>contributeSkillTargets(config2,PLUGIN_NAME13,services.get("recipes.contents"))}),sous.on("compiler.compile.before",(_event,ctx)=>{for(let warning of skillWarnings(ctx))ctx.reporter.problem(warning.summary,warning.hint===void 0?{}:{hint:warning.hint})})}});import{definePlugin as definePlugin15}from"@sous-io/sous-plugin-api";import path67 from"node:path";init_src2();var compileRecipeKeyMatcher=compilePatternList,compileRecipeKeyFinder=compilePatternFinder;var FIRST_KEY="recipes.memories.first",EXCLUDE_KEY="recipes.memories.exclude";function dependencyOrder(recipes,compare){let waitingOn=new Map;for(let recipe of recipes)waitingOn.set(recipe.id,new Set);for(let dependency of recipes)for(let holder of dependency.requestedBy)holder!==dependency.id&&waitingOn.get(holder)?.add(dependency.id);let ordered2=[],done2=new Set,remaining=[...waitingOn.keys()].sort(compare);for(;remaining.length>0;){let index=remaining.findIndex(key2=>[...waitingOn.get(key2)].every(dep=>done2.has(dep)));if(index===-1){ordered2.push(...remaining);break}let[key]=remaining.splice(index,1);ordered2.push(key),done2.add(key)}return ordered2}function recipeMemories(recipe,globs,contents,onWarning=()=>{}){let byFile=new Map;for(let content of contents.filter(entry=>entry.recipe===recipe.id))for(let{file:file2,base,content:text}of content.files)if(!byFile.has(file2)){if(text!==void 0){byFile.set(file2,{recipe:recipe.id,repository:recipe.repo,name:globs.toPosix(path67.relative(base,file2)),path:file2,content:text});continue}if(globs.realPathInside(file2,recipe.dir)===void 0){onWarning(`The memory ${file2} of the recipe ${recipe.id} was left out, because it is a link that leads outside the recipe's directory. Replace the link with the file itself.`);continue}byFile.set(file2,{recipe:recipe.id,repository:recipe.repo,name:globs.toPosix(path67.relative(base,file2)),path:file2})}return[...byFile.values()].sort((a,b)=>compareIncludeOrder(a.name,b.name))}function selectMemories(options2){let{recipes,globs,contents}=options2,isMatch=(key,pattern)=>globs.isMatch(key,pattern),isFirst=compileRecipeKeyMatcher(options2.settings?.first,FIRST_KEY,isMatch),excludedBy=compileRecipeKeyFinder(options2.settings?.exclude,EXCLUDE_KEY,isMatch),byKey2=new Map(recipes.map(recipe=>[recipe.id,recipe])),order=dependencyOrder(recipes,(a,b)=>globs.compareBytewise(a,b)),leading=order.filter(key=>isFirst(key)),rest=order.filter(key=>!isFirst(key)),selected2=[],excluded=[];for(let key of[...leading,...rest]){let recipe=byKey2.get(key),memories=recipeMemories(recipe,globs,contents,options2.onWarning),by2=excludedBy(key);by2===void 0?selected2.push(...memories):excluded.push(...memories.map(memory=>({memory,by:by2})))}return{selected:selected2,excluded}}function viewPath(memory){return`${memory.recipe}/${memory.name}`}var memoriesHashName={id:"memories",description:"the memories of every active recipe, listed in dependency order as #memories/<namespace>/<recipe>/<path>.",view:ctx=>ctx.services.get("memories.selection").selected().map(memory=>({path:viewPath(memory),file:memory.path}))};import{jsonSchema as jsonSchema20}from"@sous-io/sous-plugin-api";function refine2(base,extra){let standard=base["~standard"];return{"~standard":{...standard,validate(value){let result=standard.validate(value);if(result.issues)return result;let issues=extra(result.value);return issues.length>0?{issues}:result}}}}var memoryTargetSchema=refine2(jsonSchema20({type:"object",required:["id","outputPath"],properties:{id:{type:"string",minLength:1,description:"The target's id: `claude-code`, `codex`."},harness:{type:"string",description:"The `harness` entity that reads the file; its output is marked with it."},outputPath:{type:"string",minLength:1,description:"The file to write; `${projectRoot}` and other variables allowed, a relative path is under the project root."},prependWith:{type:"string",description:"A file included before the memories; skipped when it does not exist."},backupExisting:{type:"boolean",description:"Back up, warn about and overwrite a file sous did not write at outputPath."}}}),target=>["fileName","directory","readIn","filter","format"].filter(name=>target[name]!==void 0).map(name=>({path:[name],message:`"${name}" was removed from memory targets in sous 1.1.0: a memory target names the file it writes with "outputPath", and its content comes from .sous/MEMORIES.tpl.md.`})));function keyListIssues(entries,where3,key){return entries.flatMap((entry,index)=>{try{return compileRecipeKeyMatcher([entry],`${where3}[${index}]`,()=>!1),[]}catch(error51){return[{path:[key,index],message:error51 instanceof Error?error51.message:String(error51)}]}})}var memoriesSettingsSchema=refine2(jsonSchema20({type:"object",additionalProperties:!1,properties:{first:{type:"array",items:{type:"string"},default:[],description:"Recipe keys, globs or /regular expressions/ whose memories come first, in this order."},exclude:{type:"array",items:{type:"string"},default:[],description:"Recipe keys, globs or /regular expressions/ whose memories are left out."}},default:{},description:"Which recipe memories memory targets and the #memories view take, and in what order."}),settings=>[...keyListIssues(settings.first,FIRST_KEY,"first"),...keyListIssues(settings.exclude,EXCLUDE_KEY,"exclude")]);import{NotFoundError as NotFoundError7}from"@sous-io/sous-plugin-api";var MemoriesSelectionService=class{constructor(config2,ctx){this.config=config2;this.ctx=ctx}result;selected(){return[...this.select().selected]}forTarget(targetId){if(!this.ctx.entities.get("memory-target",targetId))throw new NotFoundError7("memory-target",targetId,`No memory target "${targetId}" exists.`);return this.selected()}excluded(){return[...this.select().excluded]}select(){return this.result??=selectMemories({recipes:this.ctx.entities.list("active-recipe"),settings:this.config.get(["recipes","memories"]),globs:this.ctx.services.get("host.globs"),contents:this.ctx.services.get("recipes.contents").of(this.config,"memories")}),this.result}};import fs50 from"node:fs";import os8 from"node:os";import path68 from"node:path";var TARGETS_CONTRIBUTOR2="memories.targets",MEMORIES_SOURCE="MEMORIES.tpl.md",PROJECT_MEMORIES_DIR="memories";var SKIP_EMPTY_TRANSFORM="memories/skip-empty";function compilationTargetId(target){return`memories/${target.id}`}function defaultFormat(memories){return memories.map(memory=>memory.content===void 0?`@${memory.path}`:inlineMemory(memory.content,memory.path)).join(`
1149
+ `,defaultFactory=()=>{let worker2=new Worker(WORKER_SOURCE,{eval:!0});return worker2.unref(),worker2},factory=defaultFactory,worker,workersUnavailable=!1;function disposeMatcherWorker(){let running=worker;if(worker=void 0,running!==void 0)try{running.terminate()}catch{}}function matcher(){if(!workersUnavailable){if(worker!==void 0)return worker;try{worker=factory()}catch{worker=void 0}return worker===void 0&&(workersUnavailable=!0),worker}}function matchWithBudget(pattern,input,budgetMs=DEFAULT_PATTERN_BUDGET_MS){let running=matcher();if(running===void 0)return inProcessMatch(pattern,input);let shared=new SharedArrayBuffer(2*Int32Array.BYTES_PER_ELEMENT),slots=new Int32Array(shared);try{running.postMessage({pattern,input,shared})}catch{return disposeMatcherWorker(),inProcessMatch(pattern,input)}if(!waitForStart(slots))return disposeMatcherWorker(),workersUnavailable=!0,inProcessMatch(pattern,input);switch(Atomics.load(slots,STATUS)===PENDING&&Atomics.wait(slots,STATUS,PENDING,budgetMs),Atomics.load(slots,STATUS)){case MATCHED:return"match";case DID_NOT_MATCH:return"no-match";case FAILED:return inProcessMatch(pattern,input);default:return disposeMatcherWorker(),"timeout"}}function waitForStart(slots){let deadline=Date.now()+STARTUP_GRACE_MS;for(;Atomics.load(slots,STARTED)===0&&Atomics.load(slots,STATUS)===PENDING;){let remaining=deadline-Date.now();if(remaining<=0)return!1;Atomics.wait(slots,STARTED,0,remaining)}return!0}function inProcessMatch(pattern,input){return new RegExp(pattern).test(input)?"match":"no-match"}var TRUE_WORDS=new Set(["true","yes","y","on","1"]),FALSE_WORDS=new Set(["false","no","n","off","0"]);function canonicalBoolean(value){if(typeof value=="boolean")return value?"true":"false";let word=value.trim().toLowerCase();return TRUE_WORDS.has(word)?"true":FALSE_WORDS.has(word)?"false":void 0}function patternsOf(definition2){return definition2.patterns??(definition2.validate?.pattern===void 0?[]:[definition2.validate.pattern])}function validateAnswer(definition2,raw2,context={}){let trimmed=typeof raw2=="string"?raw2.trim():"";if(trimmed.length===0&&!definition2.required)return{ok:!0,value:""};let rules=definition2.validate,fail=reason=>({ok:!1,message:`${definition2.name} ${reason}.`});switch(definition2.type){case"number":{if(trimmed.length===0||!Number.isFinite(Number(trimmed)))return fail("must be a number");let value=Number(trimmed);return rules?.min!==void 0&&value<rules.min?fail(`must be at least ${rules.min}`):rules?.max!==void 0&&value>rules.max?fail(`must be at most ${rules.max}`):{ok:!0,value}}case"boolean":{let word=trimmed.toLowerCase();return!TRUE_WORDS.has(word)&&!FALSE_WORDS.has(word)?fail("must be 'true' or 'false'"):{ok:!0,value:TRUE_WORDS.has(word)}}case"enum":{let options2=rules?.enum??[];return runString(trimmed,[value=>options2.includes(value)?void 0:`must be one of: ${options2.join(", ")}`,...stringChecks()])}case"url":return runString(trimmed,[value=>isUrl(value)?void 0:"must be a URL, including its scheme (for example 'https://example.com')",...stringChecks()]);case"path":return runString(trimmed,[value=>value.includes("\0")?"must be a filesystem path, with no null characters in it":void 0,...stringChecks()]);default:return runString(trimmed,stringChecks())}function runString(value,checks){for(let check3 of checks){let reason=check3(value);if(reason!==void 0)return fail(reason)}return{ok:!0,value}}function stringChecks(){let checks=[];if(definition2.required&&checks.push(value=>value.length>0?void 0:"must not be empty"),rules?.minLength!==void 0){let min=rules.minLength;checks.push(value=>value.length>=min?void 0:`must be at least ${min} characters long`)}if(rules?.maxLength!==void 0){let max=rules.maxLength;checks.push(value=>value.length<=max?void 0:`must be at most ${max} characters long`)}let budget=context.patternBudgetMs??DEFAULT_PATTERN_BUDGET_MS;for(let pattern of patternsOf(definition2))checks.push(value=>{let outcome=matchWithBudget(pattern,value,budget);if(outcome!=="match")return outcome==="timeout"?patternTooSlowMessage(pattern,budget,context.recipe):`must match the pattern ${pattern}`});return checks}}function isUrl(value){try{return new URL(value).protocol.length>1}catch{return!1}}function patternTooSlowMessage(pattern,budgetMs,recipe){let publisher=recipe===void 0?"the recipe that defines it":`the recipe ${recipe}`;return`could not be checked: the pattern ${pattern}, published by ${publisher}, took longer than ${budgetMs} milliseconds to run, so sous stopped waiting for it. The pattern is too slow to run, and the answer was not the problem; this needs to be reported to whoever publishes the recipe`}function characters(count2){return count2===1?"1 character":`${count2} characters`}function constraintBullets(definition2){let rules=definition2.validate,options2=rules?.enum,bullets=definition2.type==="enum"&&options2!==void 0?[`must be one of: ${options2.join(", ")} (type: enum)`]:[`must be a value of the type ${definition2.type} (type: ${definition2.type})`];options2!==void 0&&definition2.type!=="enum"&&bullets.push(`must be one of: ${options2.join(", ")} (enum: ${options2.join(", ")})`),rules?.minLength!==void 0&&bullets.push(`must be at least ${characters(rules.minLength)} long (minLength: ${rules.minLength})`),rules?.maxLength!==void 0&&bullets.push(`must be at most ${characters(rules.maxLength)} long (maxLength: ${rules.maxLength})`),rules?.min!==void 0&&bullets.push(`must be no less than ${rules.min} (min: ${rules.min})`),rules?.max!==void 0&&bullets.push(`must be no more than ${rules.max} (max: ${rules.max})`);for(let pattern of patternsOf(definition2))bullets.push(`must match the pattern /${pattern}/ (pattern: ${pattern})`);return definition2.required||bullets.push("an answer is optional"),bullets}var validator={validate:(definition2,answer2,options2)=>validateAnswer(definition2,answer2,options2)};function tightest(definers,field){let lower=field==="min"||field==="minLength",best;for(let{definition:definition2,label}of definers){let value=definition2.validate?.[field];value!==void 0&&(best===void 0||(lower?value>best.value:value<best.value))&&(best={value,label})}return best}function combineDefinitions(definers){let[first2]=definers;if(first2===void 0)throw new Error("combineDefinitions needs at least one definition.");if(definers.length===1)return{ok:!0,definition:first2.definition};let name=first2.definition.name,otherType=definers.find(entry=>entry.definition.type!==first2.definition.type);if(otherType!==void 0)return{ok:!1,reason:`${first2.label} defines ${name} as ${article2(first2.definition.type)}, and ${otherType.label} defines it as ${article2(otherType.definition.type)}, so no answer fits both.`};let listing=definers.filter(entry=>entry.definition.validate?.enum!==void 0),options2;for(let entry of listing){let own=entry.definition.validate.enum;options2=options2===void 0?[...own]:options2.filter(option=>own.includes(option))}if(options2!==void 0&&options2.length===0){let lists=listing.map(entry=>`${entry.label} accepts ${entry.definition.validate.enum.join(", ")}`);return{ok:!1,reason:`No value of ${name} is accepted by every definition (${lists.join("; ")}).`}}let min=tightest(definers,"min"),max=tightest(definers,"max");if(min!==void 0&&max!==void 0&&min.value>max.value)return{ok:!1,reason:`${min.label} requires ${name} to be at least ${min.value}, and ${max.label} requires it to be at most ${max.value}, so no answer fits both.`};let minLength=tightest(definers,"minLength"),maxLength=tightest(definers,"maxLength");if(minLength!==void 0&&maxLength!==void 0&&minLength.value>maxLength.value)return{ok:!1,reason:`${minLength.label} requires ${name} to be at least ${minLength.value} characters long, and ${maxLength.label} requires it to be at most ${maxLength.value} characters long, so no answer fits both.`};let patterns=[...new Set(definers.flatMap(entry=>entry.definition.validate?.pattern===void 0?[]:[entry.definition.validate.pattern]))],validate={...first2.definition.validate??{},...options2===void 0?{}:{enum:options2},...min===void 0?{}:{min:min.value},...max===void 0?{}:{max:max.value},...minLength===void 0?{}:{minLength:minLength.value},...maxLength===void 0?{}:{maxLength:maxLength.value},...patterns[0]===void 0?{}:{pattern:patterns[0]}},envs=new Set(definers.map(entry=>entry.definition.env)),rest={...first2.definition};delete rest.default,delete rest.env;let combined={...rest,...envs.size===1&&first2.definition.env!==void 0?{env:first2.definition.env}:{},secret:definers.some(entry=>entry.definition.secret),scope:definers.some(entry=>entry.definition.scope==="local")?"local":"shared",required:definers.some(entry=>entry.definition.required),...Object.keys(validate).length===0?{}:{validate},...patterns.length>1?{patterns}:{}},fallback2=definers.map(entry=>entry.definition.default).find(value=>value!==void 0&&validateAnswer(combined,String(value)).ok);return{ok:!0,definition:fallback2===void 0?combined:{...combined,default:fallback2}}}function article2(type){return/^[aeiou]/.test(type)?`an ${type}`:`a ${type}`}import path60 from"node:path";function resolveUserPath(file2,base){if(path60.isAbsolute(file2))return file2;let from=base.cwd??base.project?.root;return from===void 0?file2:path60.resolve(from,file2)}var LOCAL_FILE_REPO="local",LOCAL_FILE_NAMESPACE="local";function recipeKey(recipe){return`${recipe.namespace}/${recipe.name}`}function variableKey(recipe,variable){return`${recipeKey(recipe)}.${variable}`}function qualifiedKey(defined){return`${defined.recipe.repo}:${defined.key}`}function variableRefOf(recipe,definition2){return{kind:"variable",name:definition2.name,description:definition2.prompt,recipe:{kind:"recipe",name:recipe.name,namespace:{kind:"namespace",name:recipe.namespace,repo:{kind:"repo",name:recipe.repo}}}}}function defineVariable(recipe,definition2,shared={}){let{requiredBy,combined,separate,unanswerable}=shared;return{definition:combined??definition2,recipe,ref:variableRefOf(recipe,definition2),key:variableKey(recipe,definition2.name),...requiredBy===void 0||requiredBy.length===0?{}:{requiredBy},...combined===void 0||combined===definition2?{}:{published:definition2},...separate===void 0?{}:{separate},...unanswerable===void 0?{}:{unanswerable}}}function definersOf(group){let keys=group.map(entry=>recipeKey(entry.recipe));return group.map((entry,index)=>{let key=keys[index];return{definition:entry.published??entry.definition,label:keys.indexOf(key)===keys.lastIndexOf(key)?key:`${key} ${entry.recipe.version}`}})}function holderList(holders){let named=holders.map(holder=>holder==="project"?"this project":holder);return named.length<2?named[0]??"":`${named.slice(0,-1).join(", ")} and ${named.at(-1)}`}function versionConflictWarning(name,skipped,asked,reason){let key=recipeKey(skipped),skippedAt=`${key} ${skipped.version}`,askedAt=`${key} ${asked.version}`,users=[...skipped.holders===void 0||skipped.holders.length===0?[]:[`${skippedAt} is used by ${holderList(skipped.holders)}`],...asked.holders===void 0||asked.holders.length===0?[]:[`${askedAt} by ${holderList(asked.holders)}`]],used=users.length===0?"":` ${users.join(", and ")}.`;return`The variable ${name} of ${skippedAt} cannot be answered alongside ${askedAt}, so it is not asked and gets no answer: where ${skippedAt} is used, ${name} renders empty.${used} ${reason}`}function settleConflict(group,settled){let name=group[0].definition.name,byRecipe=new Map;for(let entry of group)byRecipe.set(recipeKey(entry.recipe),[...byRecipe.get(recipeKey(entry.recipe))??[],entry]);let ownCombination=new Map;for(let versions of byRecipe.values()){let asked=versions.find(entry=>entry.recipe.pinned!==!0)??versions[0],kept=[asked];for(let other of versions){if(other===asked)continue;let combination2=combineDefinitions(definersOf([...kept,other]));combination2.ok?kept.push(other):settled.set(other,{unanswerable:versionConflictWarning(name,other.recipe,asked.recipe,combination2.reason)})}let own=combineDefinitions(definersOf(kept));for(let entry of kept)ownCombination.set(entry,own.ok?own.definition:entry.published??entry.definition)}let remaining=group.filter(entry=>!settled.has(entry));if(remaining.length<2)return;let combination=combineDefinitions(definersOf(remaining));for(let entry of remaining)settled.set(entry,combination.ok?{combined:combination.definition}:{combined:ownCombination.get(entry),separate:combination.reason})}function combineSharedNames(variables){let byName=new Map;for(let entry of variables){let group=byName.get(entry.definition.name)??[];group.push(entry),byName.set(entry.definition.name,group)}let settled=new Map;for(let group of byName.values()){if(group.length<2)continue;let combination=combineDefinitions(definersOf(group));if(combination.ok)for(let entry of group)settled.set(entry,{combined:combination.definition});else settleConflict(group,settled)}return variables.map(entry=>{let outcome=settled.get(entry),group=byName.get(entry.definition.name)??[];if(group.length<2)return entry;let others=group.filter(other=>other!==entry&&(outcome?.unanswerable!==void 0||settled.get(other)?.unanswerable===void 0)).map(other=>other.recipe);return defineVariable(entry.recipe,entry.published??entry.definition,{requiredBy:others,...outcome??{}})})}function definitionsFromRecipes(recipes,repos={}){let defined=[];for(let active of recipes){let url2=repos[active.repo]?.url,recipe={repo:active.repo,namespace:active.namespace,name:active.name,version:active.version,dir:active.dir,identity:active.identity,direct:active.requestedBy.includes("project"),...url2===void 0?{}:{url:url2}},pinnedFor=new Map;for(let pin of active.pins??[]){let same=pinnedFor.get(pin.version);same===void 0?pinnedFor.set(pin.version,{version:pin.version,dir:pin.dir,manifest:pin.manifest,holders:[pin.holder]}):same.holders.push(pin.holder)}let pinnedHolders=new Set((active.pins??[]).map(pin=>pin.holder)),shared={...recipe,holders:active.requestedBy.filter(holder=>!pinnedHolders.has(holder))};for(let definition2 of active.manifest.variables??[])defined.push(defineVariable(pinnedFor.size===0?recipe:shared,definition2));for(let pin of pinnedFor.values()){let pinned={...recipe,version:pin.version,dir:pin.dir,direct:!1,holders:pin.holders,pinned:!0};for(let definition2 of pin.manifest.variables??[])defined.push(defineVariable(pinned,definition2))}}return combineSharedNames(defined)}function pseudoRecipeName(filePath){let slug=path61.basename(filePath).replace(/\.[^.]+$/,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return slug.length===0||!/^[a-z]/.test(slug)?`file-${slug}`:slug}async function loadDefinitionsFile(filePath,reader){let raw2=await reader.readFile(filePath),variables=raw2?.variables;if(raw2===null||typeof raw2!="object"||Array.isArray(raw2)||!Array.isArray(variables)||variables.length===0)throw new ConfigError41(`The variable definitions file at ${filePath} is not valid.`,{details:["variables: must list at least one variable, in the form a recipe manifest uses."]});let recipe={repo:LOCAL_FILE_REPO,namespace:LOCAL_FILE_NAMESPACE,name:pseudoRecipeName(filePath),version:"0.0.0",dir:filePath,direct:!0},problems=[],defined=[];for(let[index,value]of variables.entries()){let checked3=reader.definition.check(value,`${filePath}, variables[${index}]`);if(checked3.issues===void 0)defined.push(defineVariable(recipe,checked3.value));else{let issues=checked3.issues.filter(issue2=>!/^Invalid .*:$/.test(issue2));problems.push(...issues.map(issue2=>placeIssue(issue2,index)))}}if(problems.length>0)throw new ConfigError41(`Invalid variable definitions file at ${filePath}:`,{details:problems});return combineSharedNames(defined)}function placeIssue(issue2,index){let text=issue2.replace(/^\s*-\s*/,"");return/^([\w.[\]]+): /.exec(text)===null?`- variables[${index}]: ${text}`:`- variables[${index}].${text}`}function namesVariable(defined,name){return defined.definition.name===name||defined.key===name||qualifiedKey(defined)===name}var DefinitionsService=class{constructor(ctx){this.ctx=ctx}listSync(){let recipes=this.ctx.entities.kinds().includes("active-recipe")?this.ctx.entities.list("active-recipe"):[];return definitionsFromRecipes(recipes,this.ctx.config.get("repos")??{})}async list(options2={}){return options2.file===void 0?this.listSync():loadDefinitionsFile(resolveUserPath(options2.file,this.ctx),{readFile:file2=>this.ctx.services.get("formats.manifests").readFile(file2),definition:this.ctx.services.get("formats.variable-definition")})}async find(nameOrRef,options2={}){return(await this.list(options2)).filter(entry=>namesVariable(entry,nameOrRef))}combine(variables){return combineSharedNames(variables)}};function answerFor(variable,ladder){if(variable.unanswerable!==void 0)return;let resolved=ladder.resolve(variable),fallback2=variable.definition.default,value=resolved!==void 0?resolved.value:fallback2===void 0?void 0:String(fallback2);return value===void 0||variable.definition.type!=="boolean"?value:canonicalBoolean(value)??value}function booleanNames(variables){return[...new Set(variables.filter(variable=>variable.definition.type==="boolean").map(variable=>variable.definition.name))]}function computeAnswers(variables,ladder){let merged={},byRecipe={},unanswered=[],unanswerable=[],secrets=new Set;for(let variable of variables){let name=variable.definition.name,value=answerFor(variable,ladder);if(variable.definition.secret&&secrets.add(name),variable.unanswerable!==void 0){unanswerable.push(variable);continue}if(value===void 0){variable.definition.required&&unanswered.push(variable);continue}name in merged||(merged[name]=value);let key=recipeKey(variable.recipe);byRecipe[key]={...byRecipe[key]??{},[name]:value}}for(let variable of unanswerable){let name=variable.definition.name;for(let holder of variable.recipe.holders??[])variables.some(other=>other.definition.name===name&&recipeKey(other.recipe)===holder)||(byRecipe[holder]={...byRecipe[holder]??{},[name]:""})}return{merged,byRecipe,unanswered,unanswerable,secrets}}function answersForRecipe(answers,key){return{...answers.merged,...answers.byRecipe[key]??{}}}var AnswersService=class{constructor(compute){this.compute=compute}cached;get(){return this.cached??=this.compute(),this.cached}forRecipe(key){return answersForRecipe(this.get(),key)}};import{commandVariables as commandVariables2,ConfigError as ConfigError44,InputError as InputError5,IntentOutput as IntentOutput9,IntentOutputs as IntentOutputs10,jsonSchema as jsonSchema16,ReportEntryStyle as ReportEntryStyle5,TextBlock as TextBlock6}from"@sous-io/sous-plugin-api";import{LogLevel as LogLevel11,NonInteractiveError as NonInteractiveError4}from"@sous-io/sous-plugin-api";import{ConfigError as ConfigError42,InputError as InputError3}from"@sous-io/sous-plugin-api";var VAR_MAPPINGS_FILE="520-var-mappings.jsonc",VAR_MAPPINGS_DESCRIPTION=["Each entry under 'varMappings' binds an environment variable to one recipe","variable, so an answer can be stored under a name of your choosing when the","usual names are taken. The 'sous vars ask' and 'sous vars map' commands write","them; run 'sous vars' to see which name answered what."],TARGET_HELP="A mapping target is written as 'namespace/recipe/variableName', optionally qualified with a repository as 'repo:namespace/recipe/variableName'.",STORED_NAME=/^[a-z][a-z0-9-]*$/,VARIABLE_NAME2=/^[a-z][a-zA-Z0-9]*$/;function parseMappingTarget(input){let fail=problem=>{throw new ConfigError42(`Invalid variable mapping target '${input}': ${problem}`,{details:[TARGET_HELP]})},trimmed=typeof input=="string"?input.trim():"";trimmed.length===0&&fail("a target must not be empty.");let colon=trimmed.indexOf(":"),repo=colon===-1?void 0:trimmed.slice(0,colon),parts=trimmed.slice(colon+1).split("/");(parts.length!==3||parts.some(part=>part.length===0))&&fail("a target names a namespace, a recipe and a variable, joined by slashes.");let[namespace,recipe,variable]=parts,named=[...repo===void 0?[]:[repo],namespace,recipe];for(let name of named)STORED_NAME.test(name)||fail(name.toLowerCase()!==name&&STORED_NAME.test(name.toLowerCase())?`the repository, namespace and recipe in '${trimmed.slice(0,trimmed.lastIndexOf("/"))}' must be lowercase.`:`'${name}' is not a repository, namespace or recipe name: a lowercase letter, then lowercase letters, digits or dashes.`);return VARIABLE_NAME2.test(variable)||fail(`the variable name '${variable}' must be camelCase: a lowercase letter, then letters or digits.`),{...repo===void 0?{}:{repo},namespace,recipe,variable}}function formatMappingTarget(target){return`${target.repo===void 0?"":`${target.repo}:`}${target.namespace}/${target.recipe}/${target.variable}`}function mappingTargetFor(defined){return{repo:defined.recipe.repo,namespace:defined.recipe.namespace,recipe:defined.recipe.name,variable:defined.definition.name}}function mappingMatches(target,defined){return target.repo!==void 0&&target.repo!==defined.recipe.repo?!1:target.namespace===defined.recipe.namespace&&target.recipe===defined.recipe.name&&target.variable===defined.definition.name}function mappedNamesFor(mappings,defined){let names2=[];for(let[envName,target]of Object.entries(mappings))mappingMatches(parseMappingTarget(target),defined)&&names2.push(envName);return names2.sort()}var MappingsService=class{constructor(ctx){this.ctx=ctx}list(){let records=this.ctx.config.get("varMappings")??{},parsed={};for(let[envName,target]of Object.entries(records))parsed[envName]=parseMappingTarget(target);return parsed}parseTarget(text){return parseMappingTarget(text)}formatTarget(target){return formatMappingTarget(target)}async set(envName,target,options2={}){this.checkEnvName(envName);let written=formatMappingTarget(parseMappingTarget(formatMappingTarget(target))),result=await this.ctx.services.get("confd.managed").set(VAR_MAPPINGS_FILE,`varMappings.${envName}`,written,{description:VAR_MAPPINGS_DESCRIPTION,...options2.dryRun===void 0?{}:{dryRun:options2.dryRun}});return{file:result.file,changed:result.changed}}async remove(envName,options2={}){this.checkEnvName(envName);let result=await this.ctx.services.get("confd.managed").delete(VAR_MAPPINGS_FILE,`varMappings.${envName}`,{description:VAR_MAPPINGS_DESCRIPTION,...options2.dryRun===void 0?{}:{dryRun:options2.dryRun}});return{file:result.file,changed:result.changed}}checkEnvName(envName){if(!this.ctx.services.get("variables.names").isEnvName(envName))throw new InputError3("vars.map",[{path:"envName",message:`'${envName}' is not an environment variable name: a letter or underscore, then letters, digits or underscores.`}])}};var RUNG_LABELS2={mapping:"mapping record",recipe:"recipe scope",namespace:"namespace scope",shared:"shared scope",bare:"declared name"},SOURCE_LABELS2={shell:"the shell environment",local:"the .env.local file",shared:"the .env file"},ENV_FILE_NAMES={shared:".env",local:".env.local"};function layersFrom(files,env){let local2={...files?.local??{}},shared={...files?.shared??{}},shell={};for(let[name,value]of Object.entries(env))value===void 0||local2[name]===value||shared[name]===value||(shell[name]=value);return{shell,local:local2,shared}}var Ladder=class{constructor(names2,layers,mappings={}){this.names=names2;this.layers={shell:{...layers.shell},local:{...layers.local},shared:{...layers.shared}},this.mappingRecords={...mappings}}layers;mappingRecords;get mappings(){return this.mappingRecords}namesInFiles(){return new Set([...Object.keys(this.layers.local),...Object.keys(this.layers.shared)])}candidates(variable){let{namespace,name:recipe}=variable.recipe,name=variable.definition.name,ordered2=[...mappedNamesFor(this.mappingRecords,variable).map(envName=>({rung:"mapping",envName})),{rung:"recipe",envName:this.names.recipeScopedName(namespace,recipe,name)},{rung:"namespace",envName:this.names.namespaceScopedName(namespace,name)},{rung:"shared",envName:this.names.sharedName(name)},{rung:"bare",envName:this.names.bareName(variable.published??variable.definition)}],seen=new Set;return ordered2.filter(candidate=>seen.has(candidate.envName)?!1:(seen.add(candidate.envName),!0))}bareName(variable){return variable.separate===void 0?this.names.bareName(variable.definition):this.recipeScopedName(variable)}recipeScopedName(variable){return this.names.recipeScopedName(variable.recipe.namespace,variable.recipe.name,variable.definition.name)}lookupIn(file2,envName){return this.layers[file2][envName]}lookup(envName){for(let file2 of["shell","local","shared"]){let value=this.layers[file2][envName];if(value!==void 0)return{value,file:file2}}}resolve(variable){return this.diagnose(variable).resolved}diagnose(variable){let candidates=this.candidates(variable);if(variable.unanswerable!==void 0)return{candidates};for(let candidate of candidates){let hit=this.lookup(candidate.envName);if(hit!==void 0)return{resolved:{value:hit.value,source:{...candidate,file:hit.file}},candidates}}return{candidates}}record(file2,envName,value){this.layers[file2][envName]=value}addMapping(envName,target){this.mappingRecords={...this.mappingRecords,[envName]:target}}};function describeSource2(source){let label=RUNG_LABELS2[source.rung];return`the ${label.endsWith(" name")?label:`${label} name`} ${source.envName}, from ${SOURCE_LABELS2[source.file]??source.file}`}function buildLadder(inputs){let files=inputs.services.has("config-files.env")?inputs.services.get("config-files.env").readSync():void 0;return new Ladder(inputs.services.get("variables.names"),layersFrom(files,inputs.env),inputs.config.get("varMappings")??{})}function answerFileFor(definition2){return definition2.secret||definition2.scope==="local"?"local":"shared"}var UNANSWERED_VALUE="(unanswered)";function displayValue(value,secret,hidden){return value===void 0?UNANSWERED_VALUE:secret?hidden:value}function hiddenValue(services){return services.has("variables.secrets")?services.get("variables.secrets").hiddenValue:"(hidden)"}var OPTIONAL_REASON="no answer yet, and this variable is optional",OPTIONAL_HINT="To answer an optional variable, run 'sous vars ask <name>'. 'sous vars ask --all' asks every variable, including the ones already answered.",TRUE_WORDS2=["true","yes","y","on","1"];function answerCount(count2){return count2===1?"1 answer":`${count2} answers`}function answeredBy(variable){return`--answer ${variable.definition.name}=<value>`}function askLeadIn(groups){if(groups.length<2)return;let parts=groups.map((group,index)=>{let relation=index===0||group.direct?"":", which it depends on,",needs=index===0?answerCount(group.count):String(group.count);return`${group.key}${relation} needs ${needs}`}),last2=parts.pop();return`${[...parts,`and ${last2}`].join(", ")}.`}function recipeOpeningLine(key,count2){return`${key} needs ${answerCount(count2)} before it can be used.`}function answerComment(variable){return`Set by sous for ${recipeKey(variable.recipe)}: ${variable.definition.prompt}`}function nonInteractiveError(pending){let details=["Set one of the environment variables listed under each variable, pass --answer <name>=<value>, or run 'sous vars ask' from a terminal."];for(let entry of pending){details.push("",`${entry.variable.definition.name} (${recipeKey(entry.variable.recipe)}): ${entry.variable.definition.prompt}`),entry.current!==void 0&&details.push(` The value currently in scope does not fit this variable: ${entry.current}`),entry.variable.separate!==void 0&&details.push(` ${entry.variable.separate} Each recipe needs its own answer.`);for(let candidate of entry.candidates)details.push(` ${candidate.envName} (${RUNG_LABELS2[candidate.rung]})`)}let first2=pending[0],question=pending.length===1?first2.variable.definition.prompt:`${pending.length} questions about recipe variables`,error51=new NonInteractiveError4(question,pending.length===1?answeredBy(first2.variable):"--answer <name>=<value>",{details,exitCode:1});return error51.message=pending.length===1?"One variable still needs an answer, and there is no terminal to ask on.":`${pending.length} variables still need answers, and there is no terminal to ask on.`,error51}function askedFor(variable){let others=variable.separate===void 0?variable.requiredBy??[]:[];return others.length===0?recipeKey(variable.recipe):`${recipeKey(variable.recipe)}, also used by ${others.map(recipeKey).join(", ")}`}function separateNote(variable){return variable.separate===void 0?void 0:`${variable.separate} Each recipe is asked for its own answer, stored under its recipe-scoped name.`}function unanswerableReason(variable){let key=recipeKey(variable.recipe);return`not asked for ${key} ${variable.recipe.version}, which cannot share an answer with another version of ${key}`}function committedFileWarning(variable,file2){let what=variable.definition.secret?"a secret":"machine-specific";return`${variable.published===void 0||variable.requiredBy===void 0?`${recipeKey(variable.recipe)} declared this variable ${what}`:`${recipeKey(variable.recipe)} shares this variable with ${variable.requiredBy.map(recipeKey).join(", ")}, and one of their definitions declares it ${what}`}, and ${file2} is committed to git. An answer stored there enters your project's git history, is pushed with every clone, and is visible to everyone who can read the repository.`}async function allowedFile(variable,file2,run){if(file2!=="shared"||run.envFile!=="shared"||answerFileFor(variable.definition)!=="local"||run.yes===!0)return!0;let name=ENV_FILE_NAMES.shared;return run.reporter.warning(committedFileWarning(variable,`.sous/${name}`)),run.prompter.confirm({message:`Store this answer in .sous/${name} anyway?`,answeredBy:"--yes",default:!1})}function check2(variable,value){return validateAnswer(variable.definition,value,{recipe:recipeKey(variable.recipe)})}async function storeGivenAnswers(applicable,ladder,run){let stored=[],keys=new Set,written=new Set;for(let entry of applicable){keys.add(entry.target.key);let existing=ladder.resolve(entry.target),fallback2={file:run.envFile??answerFileFor(entry.target.definition),envName:ladder.bareName(entry.target)},plan2=run.envFile===void 0&&existing!==void 0&&existing.source.file!=="shell"?{file:existing.source.file,envName:existing.source.envName}:fallback2,slot=`${plan2.file}:${plan2.envName}`;if(written.has(slot)||(written.add(slot),!await allowedFile(entry.target,plan2.file,run)))continue;let outcome=run.dryRun?"not written":ladder.lookupIn(plan2.file,plan2.envName)===void 0?"appended":"updated";run.dryRun||await run.store.writeAnswer(plan2.file,plan2.envName,entry.value,answerComment(entry.target)),ladder.record(plan2.file,plan2.envName,entry.value),stored.push({variable:entry.target,envName:plan2.envName,file:plan2.file,filePath:run.store.envPath(plan2.file),value:displayValue(entry.value,entry.target.definition.secret,run.hidden),outcome,...existing===void 0||existing.value===entry.value?{}:{replaced:displayValue(existing.value,entry.target.definition.secret,run.hidden)},...existing?.source.file==="shell"?{shadowedBy:existing.source.envName}:{}})}return{stored,keys}}async function askForMissing(variables,ladder,options2,run){let report={answered:[],inherited:[],skipped:[],wouldAsk:[]},announced=!1,announce=()=>{announced||(announced=!0,run.beforeReporting?.())},pending=[],questions=[],deferred=[],plannedNames=new Set,named=options2.only!==void 0;for(let variable of variables){if(options2.only!==void 0&&!options2.only.has(variable.key)||options2.within!==void 0&&!options2.within.has(recipeKey(variable.recipe)))continue;if(variable.unanswerable!==void 0){announce(),run.reporter.warning(variable.unanswerable),report.skipped.push({variable,reason:unanswerableReason(variable)});continue}if(options2.skip?.has(variable.key)===!0)continue;let{definition:definition2}=variable,diagnosis=ladder.diagnose(variable),existing=diagnosis.resolved,validity=existing===void 0?void 0:check2(variable,existing.value);if(existing!==void 0&&validity?.ok===!0&&options2.reask!==!0&&!named){report.inherited.push({variable,resolved:existing});continue}if((existing===void 0||validity?.ok===!1)&&options2.reask!==!0&&!named&&diagnosis.candidates.some(candidate=>plannedNames.has(candidate.envName))){deferred.push(variable);continue}if(!(existing!==void 0&&validity?.ok===!1||existing===void 0&&definition2.required||options2.reask===!0||named)){report.skipped.push({variable,reason:OPTIONAL_REASON});continue}if(!run.prompter.interactive&&existing===void 0&&!named&&options2.reask!==!0&&definition2.default!==void 0&&check2(variable,String(definition2.default)).ok){report.skipped.push({variable,reason:definition2.secret?"no answer yet, so its default is used":`no answer yet, so its default is used: ${String(definition2.default)}`});continue}if(!run.prompter.interactive&&run.dryRun){report.wouldAsk.push({variable,...validity?.ok===!1?{current:validity.message}:{}});continue}if(!run.prompter.interactive){pending.push({variable,candidates:diagnosis.candidates,...validity?.ok===!1?{current:validity.message}:{}});continue}let suggestion=existing!==void 0&&validity?.ok===!0?existing.value:definition2.default!==void 0?String(definition2.default):void 0;plannedNames.add(ladder.bareName(variable)),questions.push({variable,...suggestion===void 0?{}:{suggestion}})}if(pending.length>0)throw nonInteractiveError(pending);questions.length>0&&announce();for(let note of new Set(questions.map(question=>separateNote(question.variable))))note!==void 0&&run.reporter.note(note);let groups=groupQuestions(questions),leadIn=askLeadIn(groups.map(group=>({key:group.key,count:group.questions.length,direct:group.direct})));leadIn!==void 0&&run.reporter.note(leadIn);for(let group of groups){run.reporter.note(recipeOpeningLine(group.key,group.questions.length));for(let[position,question]of group.questions.entries())await runQuestion(question,{index:position+1,total:group.questions.length},ladder,run,report)}for(let variable of deferred){let resolved=ladder.resolve(variable);if(resolved!==void 0&&check2(variable,resolved.value).ok){report.inherited.push({variable,resolved});continue}announce(),run.reporter.note(recipeOpeningLine(recipeKey(variable.recipe),1)),await runQuestion({variable},{index:1,total:1},ladder,run,report)}return report}function groupQuestions(questions){let groups=new Map;for(let question of questions){let key=recipeKey(question.variable.recipe),group=groups.get(key);group===void 0?groups.set(key,{key,direct:question.variable.recipe.direct!==!1,questions:[question]}):group.questions.push(question)}return[...groups.values()]}async function askByType(definition2,variable,suggestion,prompter){let by2=answeredBy(variable);if(definition2.type==="enum"){let options2=definition2.validate?.enum??[],index=suggestion===void 0?-1:options2.indexOf(suggestion);return prompter.askChoice({message:definition2.prompt,answeredBy:by2,choices:options2.map(option=>({label:option,value:option})),...index===-1?{}:{defaultIndex:index}})}if(definition2.type==="boolean"){let current=suggestion??String(definition2.default??"");return String(await prompter.confirm({message:definition2.prompt,answeredBy:by2,default:TRUE_WORDS2.includes(current.toLowerCase())}))}return prompter.askValue({message:definition2.prompt,answeredBy:by2,validate:value=>{let result=check2(variable,value);return result.ok?void 0:result.message},...suggestion===void 0?{}:{default:suggestion},...definition2.secret?{secret:!0}:{}})}async function runQuestion(question,place,ladder,run,report){let{variable}=question,{definition:definition2}=variable,plan2={file:run.envFile??answerFileFor(definition2),envName:ladder.bareName(variable)};if(!await allowedFile(variable,plan2.file,run)){report.skipped.push({variable,reason:`not stored in .sous/${ENV_FILE_NAMES.shared}, which is committed to git`});return}run.reporter.question({index:place.index,total:place.total,name:definition2.name,...definition2.description===void 0?{}:{description:definition2.description},...definition2.example===void 0?{}:{example:String(definition2.example)},recipe:askedFor(variable),storedIn:run.store.envPath(plan2.file),storedAs:plan2.envName});let answer2=await askByType(definition2,variable,question.suggestion,run.prompter),checked3=check2(variable,answer2);if(!checked3.ok){report.skipped.push({variable,reason:checked3.message});return}let stored=await storeAnswer(variable,String(checked3.value),plan2,ladder,run);report.answered.push(stored),run.reporter.variables([{label:"Answer",value:`${stored.envName}=${stored.value}`},{label:run.dryRun?"Would be saved to":"Saved to",value:stored.filePath}],void 0,LogLevel11.Notice)}async function storeAnswer(variable,value,plan2,ladder,run){let envName=plan2.envName,mapping,occupant=ladder.lookup(envName);if(occupant!==void 0&&!check2(variable,occupant.value).ok){let scoped=ladder.recipeScopedName(variable),target=formatMappingTarget(mappingTargetFor(variable));(!run.prompter.interactive||await run.prompter.askChoice({message:`${envName} already holds a value that does not fit ${variable.definition.name}. Where should this answer go?`,choices:[{label:`${scoped}, with a mapping record (recommended)`,value:!0},{label:`${envName}, replacing what is there`,value:!1}]}))&&(envName=scoped,mapping={envName:scoped,target,filePath:run.dryRun?run.store.mappingPath():await run.store.writeMapping(scoped,target)},ladder.addMapping(scoped,target))}let outcome=run.dryRun?"not written":ladder.lookupIn(plan2.file,envName)===void 0?"appended":"updated";run.dryRun||(await run.store.writeAnswer(plan2.file,envName,value,answerComment(variable)),ladder.record(plan2.file,envName,value));let winner=ladder.resolve(variable),shadowedBy=winner?.source.file==="shell"&&(winner.source.envName!==envName||winner.value!==value)?winner.source.envName:void 0;return{variable,envName,file:plan2.file,filePath:run.store.envPath(plan2.file),value:displayValue(value,variable.definition.secret,run.hidden),outcome,...mapping===void 0?{}:{mapping},...shadowedBy===void 0?{}:{shadowedBy}}}function reportedOnce(entries,sameness){let lines3=new Map,linesPerName=new Map;for(let entry of entries){let name=entry.variable.definition.name,key=JSON.stringify([name,sameness(entry)]),recipe=recipeKey(entry.variable.recipe),line=lines3.get(key);line===void 0?(lines3.set(key,{entry,recipes:[recipe]}),linesPerName.set(name,(linesPerName.get(name)??0)+1)):line.recipes.includes(recipe)||line.recipes.push(recipe)}return[...lines3.values()].map(({entry,recipes})=>({entry,recipes,named:recipes.length>1||(linesPerName.get(entry.variable.definition.name)??0)>1}))}function inheritedSameness(entry){return JSON.stringify([entry.resolved.source.envName,entry.resolved.source.file,entry.resolved.value])}import path62 from"node:path";import{IntentOutput as IntentOutput8,Table as Table3,VariableSet as VariableSet4}from"@sous-io/sous-plugin-api";function rungLabel(rung){return RUNG_LABELS2[rung]??rung}function sourceLabel(file2){return SOURCE_LABELS2[file2]??file2}function envFileName(file2){return ENV_FILE_NAMES[file2]??file2}function variableKeyOf(variable){return`${recipeKey(variable.recipe)}.${variable.definition.name}`}function isHostedUrl(location){return/^[a-z][a-z0-9+.-]*:\/\//i.test(location)||location.startsWith("git@")}function recipeLocation(recipe){let{url:url2,path:folder,dir}=recipe;if(url2!==void 0&&isHostedUrl(url2)){let base=url2.replace(/\/+$/,"");return folder===void 0?base:`${base}/${folder}`}return url2!==void 0?folder===void 0?url2:`${url2.replace(/\/+$/,"")}/${folder}`:dir}function recipeLink(recipe,label){let location=recipeLocation(recipe);return location===void 0?{label,value:recipeKey(recipe)}:{label,value:recipeKey(recipe),detail:location}}function variableFacts(detail){let{variable}=detail,{definition:definition2}=variable,entries=[];definition2.default!==void 0&&entries.push({label:"default",value:String(definition2.default)}),entries.push({label:"example",value:String(definition2.example)});let chain=variable.requiredBy!==void 0&&variable.requiredBy.length>0?variable.requiredBy:[variable.recipe];return entries.push(recipeLink(chain[0]??variable.recipe,"required-by")),chain.length>1&&entries.push({label:"",value:`pulled in through ${chain.map(recipeKey).join(" then ")}`}),entries.push(recipeLink(variable.recipe,"defined-by")),variable.unanswerable!==void 0?entries.push({label:"not-answerable",value:variable.unanswerable}):variable.separate!==void 0?entries.push({label:"asked-separately",value:variable.separate}):variable.requiredBy!==void 0&&variable.requiredBy.length>0&&entries.push({label:"combined-with",value:variable.requiredBy.map(recipeKey).join(", ")}),entries.push({label:"stored-as",value:detail.storedAs}),detail.constraints.forEach((line,index)=>entries.push({label:index===0?"constraints":"",value:line})),entries}var LIST_COLUMNS=[{key:"name",header:"Variable",overflow:"truncate",minWidth:8},{key:"recipe",header:"Recipe",kind:"path",overflow:"truncate",priority:"medium",minWidth:8},{key:"envName",header:"Answered by",overflow:"truncate",truncate:"start",priority:"medium",minWidth:11},{key:"value",header:"Value",overflow:"truncate",truncate:"end",flex:1,minWidth:10},{key:"source",header:"Source",priority:"low"}],LADDER_COLUMNS=[{key:"envName",header:"Environment variable",overflow:"truncate",truncate:"start"},{key:"rung",header:"Rung",priority:"medium"},{key:"status",header:"Status",flex:1,priority:"medium"}];function variableListOutput(listings,hidden){let rows=[...listings].sort((left,right)=>variableKeyOf(left.variable).localeCompare(variableKeyOf(right.variable))).map(listing=>({name:listing.variable.definition.name,recipe:recipeKey(listing.variable.recipe),envName:listing.source?.envName??"",value:displayValue(listing.answered||listing.usesDefault===!0?listing.value??"":void 0,listing.variable.definition.secret,hidden),source:listing.variable.unanswerable!==void 0?"not answerable alongside another version of this recipe":listing.usesDefault===!0?"its default; no answer is stored":listing.source===void 0?"nothing yet":`${rungLabel(listing.source.rung)}, ${sourceLabel(listing.source.file)}`}));return new IntentOutput8({title:"Variables in play",result:new Table3(LIST_COLUMNS,rows,{empty:"No recipe in this project defines any variables yet. Subscribe to a recipe that publishes some, or read a definitions file with --file."})})}function envFileShown(file2,sousDir){return sousDir===void 0?envFileName(file2):path62.join(sousDir,envFileName(file2))}function variableDetailOutputs(detail,hidden,sousDir){let{variable}=detail,{definition:definition2}=variable,resolved=detail.diagnosis.resolved,key=recipeKey(variable.recipe),rows=detail.diagnosis.candidates.map(candidate=>({envName:candidate.envName,rung:rungLabel(candidate.rung),status:candidate.envName===resolved?.source.envName?`answered it, from ${sourceLabel(resolved.source.file)}`:"not set"}));return withOneLabelWidth([new IntentOutput8({title:`${definition2.name} (${key})`,result:new VariableSet4({Question:definition2.prompt,About:definition2.description,"For example":String(definition2.example),Recipe:`${key} version ${variable.recipe.version} from ${variable.recipe.repo}`,"Stored in":resolved===void 0?"nowhere yet":resolved.source.file==="shell"?sourceLabel("shell"):envFileShown(resolved.source.file,sousDir),"Saved to":`${envFileShown(detail.storeIn,sousDir)} (where new answers go)`,Value:detail.usesDefault===!0?`${displayValue(detail.value,definition2.secret,hidden)} (default)`:displayValue(resolved===void 0?void 0:resolved.value,definition2.secret,hidden),Answer:variable.unanswerable!==void 0?`none: this version of ${key} is not asked this variable, because another version of ${key} is`:detail.usesDefault===!0?"nothing in scope answers this variable, so its default is used":resolved===void 0?"nothing in scope answers this variable yet":detail.problem===void 0?"the value in scope fits this definition":`the value in scope does not fit: ${detail.problem}`})}),new IntentOutput8({result:new VariableSet4(variableFacts(detail))}),new IntentOutput8({result:new Table3(LADDER_COLUMNS,rows,{title:"Environment variables sous looks at, most specific first"})})])}function withOneLabelWidth(outputs){let sets=outputs.map(output=>output.result).filter(result=>result instanceof VariableSet4),labelWidth=Math.max(0,...sets.flatMap(set2=>set2.entries.map(entry=>entry.label.length)));return outputs.map(output=>output.result instanceof VariableSet4?new IntentOutput8({...output.title===void 0?{}:{title:output.title},...output.summary===void 0?{}:{summary:output.summary},...output.data===void 0?{}:{data:output.data},...output.style===void 0?{}:{style:output.style},result:new VariableSet4(output.result.entries,{...output.result.title===void 0?{}:{title:output.result.title},labelWidth})}):output)}function answeredEntries(entry,dryRun4,hidden){let secret=entry.variable.definition.secret,note=text=>({label:"",value:text}),entries=[{label:entry.variable.definition.name,value:displayValue(entry.value,secret,hidden),detail:`${entry.envName} in ${envFileName(entry.file)}`}];return entry.mapping!==void 0&&entries.push(note(`mapped to ${entry.mapping.target} in the conf.d layer`)),entry.replaced!==void 0&&entries.push(note(`${dryRun4?"replacing":"replaced"} the answer already there: ${displayValue(entry.replaced,secret,hidden)}`)),entry.shadowedBy!==void 0&&entries.push(note(`${entry.shadowedBy} is set in your shell environment and answers this variable first; unset it for the stored answer to take effect`)),entries}function askReportOutputs(report,hidden){let outputs=[];return report.inherited.length>0&&outputs.push(new IntentOutput8({title:"Answers already in scope",result:new VariableSet4(reportedOnce(report.inherited,inheritedSameness).map(({entry,recipes,named})=>({label:entry.variable.definition.name,value:displayValue(entry.resolved.value,entry.variable.definition.secret,hidden),detail:`from ${describeSource2(entry.resolved.source)}${named?`; used by ${recipes.join(", ")}`:""}`})))})),report.answered.length>0&&outputs.push(new IntentOutput8({title:report.dryRun?"Answers that would be stored":"Answers stored",result:new VariableSet4(report.answered.flatMap(entry=>answeredEntries(entry,report.dryRun,hidden)))})),report.skipped.length>0&&(outputs.push(new IntentOutput8({title:"Left unanswered",result:new VariableSet4(reportedOnce(report.skipped,entry=>entry.reason).map(({entry,recipes,named})=>({label:entry.variable.definition.name,value:named?`${entry.reason} (used by ${recipes.join(", ")})`:entry.reason})))})),report.skipped.some(entry=>entry.reason===OPTIONAL_REASON)&&outputs.push(new IntentOutput8({summary:OPTIONAL_HINT}))),report.wouldAsk!==void 0&&report.wouldAsk.length>0&&outputs.push(new IntentOutput8({title:"Questions that would be asked",result:new VariableSet4(report.wouldAsk.flatMap(entry=>[{label:entry.variable.definition.name,value:entry.variable.definition.prompt,detail:recipeKey(entry.variable.recipe)},...entry.current===void 0?[]:[{label:"",value:`the value in scope does not fit: ${entry.current}`}],{label:"",value:`answer it ahead of time with ${answeredBy(entry.variable)}`}]))})),outputs.length===0&&outputs.push(new IntentOutput8({summary:"Every variable in play already has an answer that fits its definition."})),outputs}import{readFile as readFile2}from"node:fs/promises";import path63 from"node:path";import{InputError as InputError4}from"@sous-io/sous-plugin-api";var ANSWER_FLAG_FORM="--answer <name>=<value>",ANSWER_NAME_HELP="A name is spelled exactly as the recipe declares it, in camelCase; the full 'namespace/recipe.name' key works too.",INTENT="vars.ask";function answerError(field,lines3){return new InputError4(INTENT,[{path:field,message:lines3[0]??""}],{details:lines3})}function parseAnswerPair(entry,from="--answer"){let at2=entry.indexOf("="),name=at2===-1?"":entry.slice(0,at2).trim();if(at2===-1||name.length===0)throw answerError("answer",[`'${entry}' is not an answer sous can read.`,`Write one as '${ANSWER_FLAG_FORM}', for example '--answer apiUrl=https://api.example.com'.`,"Everything after the first '=' is the answer, so a value may contain more of them."]);return{name,value:entry.slice(at2+1),from}}function isEnvFile(filePath){let base=path63.basename(filePath);return base===".env"||base.startsWith(".env.")||base.endsWith(".env")}function answersFromData(raw2,filePath){if(typeof raw2!="object"||raw2===null||Array.isArray(raw2))throw answerError("answersFile",[`The answers file at ${filePath} is not a map of answers.`,"It holds one entry per variable, written as 'name: value'."]);let answers=[];for(let[name,value]of Object.entries(raw2)){if(typeof value=="object"&&value!==null)throw answerError("answersFile",[`The answer for '${name}' in ${filePath} is a list or a map, and an answer is a single value.`,"Answers are stored in environment files, which hold text; write the answer as a string, a number or a boolean."]);if(value==null)throw answerError("answersFile",[`The answer for '${name}' in ${filePath} is empty.`,"Write the value the variable should be given, or leave the entry out entirely so sous asks for it."]);answers.push({name:name.trim(),value:String(value),from:filePath})}return answers}function collectAnswers(fromFile,flags){let collected=new Map;for(let answer2 of fromFile)collected.set(answer2.name,answer2);for(let entry of flags){let answer2=parseAnswerPair(entry);collected.set(answer2.name,answer2)}return[...collected.values()]}function unknownAnswerError(answer2,variables){let lines3=[`Nothing in this project defines a variable called '${answer2.name}', so the answer given with ${answer2.from} cannot be stored.`];if(variables.length===0)return lines3.push("No recipe this project subscribes to defines any variables yet, so there is nothing to answer."),answerError(answer2.from==="--answer"?"answer":"answersFile",lines3);let groups=new Map;for(let entry of variables){let key=recipeKey(entry.recipe),names2=groups.get(key)??[];names2.includes(entry.definition.name)||names2.push(entry.definition.name),groups.set(key,names2)}lines3.push("","These are the variables in play, and the recipes that declare them:","");for(let[key,names2]of groups)lines3.push(` ${key}`,...names2.map(name=>` ${name}`));return lines3.push("",ANSWER_NAME_HELP),answerError(answer2.from==="--answer"?"answer":"answersFile",lines3)}function invalidAnswerError(answer2,variable,message2,hidden){let shown=variable.definition.secret?hidden:answer2.value;return answerError(answer2.from==="--answer"?"answer":"answersFile",[`The answer given for '${answer2.name}' does not fit the definition ${recipeKey(variable.recipe)} publishes.`,message2,`For example: ${String(variable.definition.example)}`,`The answer given with ${answer2.from} was: ${shown}`,"Nothing was written; fix the answer and run the command again."])}function matchAnswers(answers,variables,hidden="(hidden)"){let applicable=[];for(let answer2 of answers){let targets=variables.filter(entry=>namesVariable(entry,answer2.name));if(targets.length===0)throw unknownAnswerError(answer2,variables);for(let target of targets){if(target.unanswerable!==void 0)continue;let checked3=validateAnswer(target.definition,answer2.value,{recipe:recipeKey(target.recipe)});if(!checked3.ok)throw invalidAnswerError(answer2,target,checked3.message,hidden);applicable.push({answer:answer2,target,value:String(checked3.value)})}}return applicable}var PreanswersService=class{constructor(ctx){this.ctx=ctx}async read(inputs){let fromFile=inputs.answersFile===void 0?[]:await this.readFile(resolveUserPath(inputs.answersFile,this.ctx));return collectAnswers(fromFile,inputs.answer??[])}match(answers,variables){let secrets=this.ctx.services.has("variables.secrets")?this.ctx.services.get("variables.secrets"):void 0;return matchAnswers(answers,variables,secrets?.hiddenValue)}async readFile(filePath){if(isEnvFile(filePath)){let text;try{text=await readFile2(filePath,"utf8")}catch(error51){throw answerError("answersFile",[`Could not read the answers file at ${filePath}: ${error51.message}`])}return answersFromData(this.ctx.services.get("config-files.env").parse(text),filePath)}return answersFromData(await this.ctx.services.get("formats.manifests").readFile(filePath),filePath)}};import{ConfigError as ConfigError43,isSousErrorOfKind as isSousErrorOfKind4,NonInteractiveError as NonInteractiveError5}from"@sous-io/sous-plugin-api";var GLOB_CHARS3=/[*?[\]{}]/;function globToRegExp(pattern,ignoreCase){let source="",braces=0;for(let index=0;index<pattern.length;index+=1){let character=pattern[index];if(character==="*")source+=".*";else if(character==="?")source+=".";else if(character==="["){let end=pattern.indexOf("]",index+1);if(end===-1)source+="\\[";else{let body2=pattern.slice(index+1,end).replace(/^!/,"^").replace(/\\/g,"\\\\");source+=`[${body2}]`,index=end}}else character==="{"?(braces+=1,source+="(?:"):character==="}"&&braces>0?(braces-=1,source+=")"):character===","&&braces>0?source+="|":source+=character.replace(/[.+^$()|\\]/g,"\\$&")}return new RegExp(`^${source}$`,ignoreCase?"i":"")}function matchName(written,known){return GLOB_CHARS3.test(written)?globToRegExp(written,!1).test(known)?"exact":globToRegExp(written,!0).test(known)?"folded":void 0:written===known?"exact":written.toLowerCase()===known.toLowerCase()?"folded":void 0}function both2(left,right){if(!(left===void 0||right===void 0))return left==="folded"||right==="folded"?"folded":"exact"}function qualifies2(qualifier,variable){if(qualifier===void 0)return"exact";let result="exact";if(qualifier.name!==void 0&&(result=matchName(qualifier.name,variable.recipe.repo)),!(qualifier.location!==void 0&&qualifier.location.identity!==variable.recipe.identity))return result}function repoRef(variable){return{kind:"repo",name:variable.recipe.repo}}function namespaceRef2(variable){return{kind:"namespace",name:variable.recipe.namespace,repo:repoRef(variable)}}function recipeRef2(variable){return{kind:"recipe",name:variable.recipe.name,namespace:namespaceRef2(variable)}}function keyOf(ref){switch(ref.kind){case"repo":return`repo ${ref.name??""}`;case"namespace":return`namespace ${ref.repo?.name??""}:${ref.name}`;case"recipe":return`recipe ${ref.namespace?.repo?.name??""}:${ref.namespace?.name??""}/${ref.name}`;case"variable":return`variable ${ref.recipe?.namespace?.repo?.name??""}:${ref.recipe?.namespace?.name??""}/${ref.recipe?.name??""}.${ref.name}`;default:return`${ref.kind} ${"name"in ref?String(ref.name):""}`}}function carry2(candidate,known){return candidate.vars===void 0?known:{...known,vars:candidate.vars}}function envNamesOf(variable,ladder){let inUse=ladder.namesInFiles(),names2=new Set([ladder.bareName(variable)]);for(let candidate of ladder.candidates(variable))inUse.has(candidate.envName)&&names2.add(candidate.envName);return names2}function matchVariables(pool,candidate,ladder){let found=new Map,add=(ref,spelling)=>{if(spelling===void 0)return;let key=keyOf(ref),known=found.get(key);(known===void 0||!known.exactSpelling&&spelling==="exact")&&found.set(key,{ref,exactSpelling:spelling==="exact"})};if(candidate.kind==="envVar"){if(ladder===void 0)return[];let variables=pool.filter(entry=>envNamesOf(entry,ladder).has(candidate.name)).map(entry=>entry.ref);return variables.length===0?[]:[{ref:carry2(candidate,{kind:"envVar",name:candidate.name,variables}),exactSpelling:!0}]}for(let variable of pool)switch(candidate.kind){case"repo":(candidate.name!==void 0||candidate.location!==void 0)&&add(carry2(candidate,repoRef(variable)),qualifies2(candidate,variable));break;case"namespace":add(carry2(candidate,namespaceRef2(variable)),both2(qualifies2(candidate.repo,variable),matchName(candidate.name,variable.recipe.namespace)));break;case"recipe":{let inNamespace=candidate.namespace===void 0?"exact":matchName(candidate.namespace.name,variable.recipe.namespace),spelling=both2(both2(qualifies2(candidate.namespace?.repo??candidate.repo,variable),inNamespace),matchName(candidate.name,variable.recipe.name));add(carry2(candidate,{...recipeRef2(variable),...candidate.range===void 0?{}:{range:candidate.range}}),spelling);break}case"variable":{let spelling=qualifies2(candidate.recipe?.namespace?.repo??candidate.recipe?.repo??candidate.repo,variable);candidate.recipe!==void 0&&(spelling=both2(spelling,matchName(candidate.recipe.name,variable.recipe.name)),candidate.recipe.namespace!==void 0&&(spelling=both2(spelling,matchName(candidate.recipe.namespace.name,variable.recipe.namespace)))),add(carry2(candidate,variable.ref),both2(spelling,matchName(candidate.name,variable.definition.name)));break}default:break}return[...found.values()].sort((left,right)=>keyOf(left.ref)<keyOf(right.ref)?-1:keyOf(left.ref)>keyOf(right.ref)?1:0)}function partsOf(ref){switch(ref.kind){case"repo":return{...ref.name===void 0?{}:{repo:ref.name}};case"namespace":return{...ref.repo?.name===void 0?{}:{repo:ref.repo.name},namespace:ref.name};case"recipe":{let repo=ref.namespace?.repo?.name??ref.repo?.name;return{...repo===void 0?{}:{repo},...ref.namespace===void 0?{}:{namespace:ref.namespace.name},recipe:ref.name}}case"variable":return ref.recipe===void 0?{...ref.repo?.name===void 0?{}:{repo:ref.repo.name}}:partsOf(ref.recipe);default:return{}}}function narrowTo(pool,match2){let target=match2.kind==="envVar"?match2.variables?.[0]:match2;if(target===void 0||target.kind==="recipeFile")return[];let{repo,namespace,recipe}=partsOf(target);return pool.filter(entry=>repo!==void 0&&entry.recipe.repo!==repo?!1:target.kind==="repo"?!0:namespace!==void 0&&entry.recipe.namespace!==namespace?!1:target.kind==="namespace"?!0:recipe!==void 0&&entry.recipe.name!==recipe?!1:target.kind==="recipe"?!0:entry.definition.name===target.name)}var SEE_ALL="Run 'sous vars' to see every variable this project's recipes define.";function describeSelection(input){let parts=[];input.repo!==void 0&&parts.push(`the repository '${input.repo}'`),input.namespace!==void 0&&parts.push(`the namespace '${input.namespace}'`),input.recipe!==void 0&&parts.push(`the recipe '${input.recipe}'`),input.name!==void 0&&parts.push(`'${input.name}'`);for(let wanted of input.var??[])parts.push(`the variable '${wanted}'`);return parts.length===0?input.all===!0?"every variable":"everything unanswered":parts.join(", ")}async function resolveSelection(pool,ladder,input,io){let{name,repo,namespace,recipe}=input,vars=input.var;if(name===void 0&&repo===void 0&&namespace===void 0&&recipe===void 0&&vars===void 0)return;let left=[...pool],pick3=(search2,kinds)=>pickOne(search2,left,ladder,kinds,input.acceptFirst===!0,io);if(repo!==void 0&&(left=narrowTo(left,await pick3(repo,["repo"]))),namespace!==void 0&&(left=narrowTo(left,await pick3(namespace,["namespace"]))),recipe!==void 0){let exact=left.filter(entry=>recipeKey(entry.recipe)===recipe);left=exact.length>0?exact:narrowTo(left,await pick3(recipe,["recipe"]))}if(name!==void 0&&(left=narrowTo(left,await pick3(name))),vars!==void 0){let chosen=[];for(let wanted of vars)chosen.push(...narrowTo(left,await pick3(wanted,["variable","envVar"])));left=chosen}if(left.length===0)throw new ConfigError43(`Nothing is left to ask: ${describeSelection({...input,all:!1})} names no variable this project holds.`,{details:[SEE_ALL]});return new Set(left.map(entry=>entry.key))}function candidatesFor(search2,pool,ladder,kinds,services){let readings;try{readings=services.get("refs.resolver").parse(search2,"commandLine").refs}catch{readings=[]}let found=new Map;for(let reading of readings)if(!(kinds!==void 0&&!kinds.includes(reading.kind)))for(let match2 of matchVariables(pool,reading,ladder)){let key=`${match2.ref.kind} ${JSON.stringify(match2.ref)}`;found.has(key)||found.set(key,{ref:match2.ref,exact:match2.exactSpelling})}let all=[...found.values()];return(all.some(entry=>entry.exact)?all.filter(entry=>entry.exact):all).flatMap(({ref})=>ref.kind==="envVar"&&(ref.variables?.length??0)>1?ref.variables.map(variable=>({...ref,variables:[variable]})):[ref])}async function pickOne(search2,pool,ladder,kinds,acceptFirst2,io){let candidates=candidatesFor(search2,pool,ladder,kinds,io.services);if(candidates.length===0)throw new ConfigError43(`Nothing called '${search2}' was found.`,{details:[SEE_ALL]});if(candidates.length===1)return candidates[0];try{return await io.services.get("refs.picker").pick(candidates,{search:search2,acceptFirst:acceptFirst2,announce:!1,details:[SEE_ALL]},io)}catch(error51){throw isSousErrorOfKind4(error51,"non-interactive")?ambiguityError(search2,error51):error51}}function ambiguityError(search2,cause){let error51=new NonInteractiveError5(cause.question,cause.answeredBy,{cause,details:cause.details,exitCode:1});return error51.message=`Sous has to ask which '${search2}' you meant, and it is not running where it can ask.`,error51}var FILE_FIELD={type:"string",description:"Read the variable definitions from a standalone definitions file instead of the project's recipes"};function definitionsLabel(file2){return file2??"the project's subscribed recipes"}function ladderFor(ctx){return buildLadder({services:ctx.services,env:ctx.env,config:ctx.config})}function listingOf(variable,ladder,hidden){let resolved=ladder.resolve(variable),fallback2=resolved===void 0&&variable.unanswerable===void 0?variable.definition.default:void 0;return{variable,answered:resolved!==void 0,...resolved===void 0?{}:{value:displayValue(resolved.value,variable.definition.secret,hidden),source:resolved.source},...fallback2===void 0?{}:{value:displayValue(String(fallback2),variable.definition.secret,hidden),usesDefault:!0},storedAs:resolved?.source.envName??ladder.bareName(variable),storeIn:answerFileFor(variable.definition)}}function detailOf(variable,ladder,hidden){let diagnosis=ladder.diagnose(variable),checked3=diagnosis.resolved===void 0?void 0:validateAnswer(variable.definition,diagnosis.resolved.value,{recipe:recipeKey(variable.recipe)}),mapping=diagnosis.resolved?.source.rung==="mapping"?diagnosis.resolved.source.envName:void 0,shownDiagnosis=diagnosis.resolved===void 0||!variable.definition.secret?diagnosis:{...diagnosis,resolved:{...diagnosis.resolved,value:hidden}};return{...listingOf(variable,ladder,hidden),diagnosis:shownDiagnosis,constraints:constraintBullets(variable.definition),...checked3?.ok===!1?{problem:checked3.message}:{},...mapping===void 0?{}:{mapping:{envName:mapping,target:ladder.mappings[mapping]??""}}}}function variablesNamed(variables,name,ladder){let byName=variables.filter(entry=>namesVariable(entry,name)),matches=byName.length>0?byName:variables.filter(entry=>ladder.candidates(entry).some(candidate=>candidate.envName===name));if(matches.length===0)throw new ConfigError44(`No variable named '${name}' is in play.`,{details:["Run 'sous vars list' to see every variable this project's recipes define."]});return matches}function storeFor(ctx){let env=ctx.services.get("config-files.env");return{envPath:file2=>env.paths()?.[file2]??(file2==="local"?".sous/.env.local":".sous/.env"),mappingPath:()=>ctx.services.get("confd.managed").path(VAR_MAPPINGS_FILE),writeAnswer:async(file2,envName,value,comment)=>{await env.write(file2,{[envName]:value},{comment})},writeMapping:async(envName,target)=>{let mappings=ctx.services.get("recipe-answers.mappings");return(await mappings.set(envName,mappings.parseTarget(target))).file}}}function chosenEnvFile(input){if(input.saveLocally===!0&&input.saveShared===!0)throw new ConfigError44("--save-locally and --save-shared cannot be used together: each names a different file for every answer of the run.");return input.saveLocally===!0?"local":input.saveShared===!0?"shared":void 0}function holdingStore(real3){let writes=[];return{envPath:file2=>real3.envPath(file2),mappingPath:()=>real3.mappingPath(),writeAnswer:async(file2,envName,value,comment)=>{writes.push(()=>real3.writeAnswer(file2,envName,value,comment))},writeMapping:async(envName,target)=>(writes.push(()=>real3.writeMapping(envName,target)),real3.mappingPath()),get held(){return writes.length},write:async()=>{for(let one of writes.splice(0))await one()}}}async function handleAsk(input,ctx){return(await askOnce(input,ctx,storeFor(ctx))).outputs}var asking={async hold(variables,input,ctx){let store2=holdingStore(storeFor(ctx));return{outputs:(await askOnce({within:[...input.within],...input.answer===void 0?{}:{answer:[...input.answer]},...input.answersFile===void 0?{}:{answersFile:input.answersFile},...input.yes===!0?{yes:!0}:{}},ctx,store2,variables)).outputs,empty:store2.held===0,write:()=>store2.write()}}};async function askOnce(input,ctx,store2,defined){let dryRun4=input.dryRun===!0,hidden=hiddenValue(ctx.services),envFile=chosenEnvFile(input),reportSettings=()=>ctx.reporter.variables([{label:"Definitions",value:definitionsLabel(input.file)},{label:"Asking",value:describeSelection(input)},...envFile===void 0?[]:[{label:"Env file",value:store2.envPath(envFile)}]]),deferSettings=input.within!==void 0;deferSettings||reportSettings(),dryRun4&&ctx.reporter.dryRun("No answers will be written.");let preanswers=ctx.services.get("recipe-answers.preanswers"),provided=await preanswers.read(input.answersFile===void 0?input:{...input,answersFile:resolveUserPath(input.answersFile,ctx)}),variables=defined===void 0?await ctx.services.get("recipe-answers.definitions").list(input.file===void 0?{}:{file:resolveUserPath(input.file,ctx)}):[...defined];if(variables.length===0){if(provided[0]!==void 0)throw unknownAnswerError(provided[0],variables);let empty={answered:[],inherited:[],skipped:[],dryRun:dryRun4};return{outputs:new IntentOutputs10([new IntentOutput9({title:"Answering variables"}),new IntentOutput9({result:new TextBlock6("No recipe in this project defines any variables yet, so there is nothing to ask. Subscribe to a recipe that publishes some, or read a definitions file with --file."),style:ReportEntryStyle5.Note})]).withData(empty)}}let ladder=ladderFor(ctx),only=await resolveSelection(variables,ladder,input,ctx),run={prompter:ctx.prompter,reporter:ctx.reporter,store:store2,hidden,dryRun:dryRun4,...envFile===void 0?{}:{envFile},yes:input.yes===!0,...deferSettings?{beforeReporting:reportSettings}:{}},given=await storeGivenAnswers(preanswers.match(provided,variables),ladder,run),report=await askForMissing(variables,ladder,{...only===void 0?{}:{only},...input.within===void 0?{}:{within:new Set(input.within)},skip:given.keys,reask:input.all===!0},run),result={answered:[...given.stored,...report.answered],inherited:report.inherited.map(({variable,resolved})=>({variable,resolved:variable.definition.secret?{...resolved,value:hidden}:resolved})),skipped:report.skipped,...report.wouldAsk.length===0?{}:{wouldAsk:report.wouldAsk},dryRun:dryRun4};!dryRun4&&result.answered.some(entry=>entry.outcome!=="not written")&&ctx.configChanged();let entries=result.answered.length>0||result.inherited.length>0||result.skipped.length>0||report.wouldAsk.length>0?askReportOutputs(result,hidden):[];return{outputs:new IntentOutputs10([new IntentOutput9({title:"Answering variables"}),...entries]).withData(result)}}async function handleList(input,ctx){let variables=await ctx.services.get("recipe-answers.definitions").list(input.file===void 0?{}:{file:resolveUserPath(input.file,ctx)}),ladder=ladderFor(ctx),hidden=hiddenValue(ctx.services),opening=commandVariables2(ctx,{Definitions:definitionsLabel(input.file)});if(input.name!==void 0){let details=variablesNamed(variables,input.name,ladder).map(variable=>detailOf(variable,ladder,hidden)),shown=details.flatMap(detail=>variableDetailOutputs(detail,hidden,ctx.project?.sousDir));return new IntentOutputs10([opening,...shown]).withData({variables:details})}let listings=variables.map(variable=>listingOf(variable,ladder,hidden));return new IntentOutputs10([opening,variableListOutput(listings,hidden)]).withData({variables:listings})}async function handleShow(input,ctx){let variables=await ctx.services.get("recipe-answers.definitions").list(input.file===void 0?{}:{file:resolveUserPath(input.file,ctx)}),ladder=ladderFor(ctx),matches=variablesNamed(variables,input.name,ladder),hidden=hiddenValue(ctx.services),opening=commandVariables2(ctx,{Definitions:definitionsLabel(input.file)}),outputsOf2=variable=>{let detail=detailOf(variable,ladder,hidden);return new IntentOutputs10([opening,...variableDetailOutputs(detail,hidden,ctx.project?.sousDir)]).withData(detail)};if(matches.length===1)return outputsOf2(matches[0]);let picked=await ctx.services.get("refs.picker").pick(matches.map(entry=>entry.ref),{search:input.name,acceptFirst:input.acceptFirst===!0,announce:!1,details:[SEE_ALL]},ctx),chosen=matches.find(entry=>entry.ref===picked)??matches.find(entry=>JSON.stringify(entry.ref)===JSON.stringify(picked))??matches[0];return outputsOf2(chosen)}async function handleMap(input,ctx){let mappings=ctx.services.get("recipe-answers.mappings"),dryRun4=input.dryRun===!0;if(input.remove===!0){let{file:file3,changed:changed3}=await mappings.remove(input.envName,{dryRun:dryRun4});changed3&&!dryRun4&&ctx.configChanged();let removal=changed3?`${dryRun4?"Would remove":"Removed"} the mapping of ${input.envName} in ${file3}.`:`${input.envName} has no mapping in ${file3}.`;return IntentOutputs10.of({envName:input.envName,file:file3,changed:changed3,dryRun:dryRun4},{summary:removal})}if(input.target===void 0)throw new InputError5("vars.map",[{path:"target",message:"Name the variable to bind, as 'namespace/recipe/variableName', or pass --remove."}]);let target=mappings.formatTarget(mappings.parseTarget(input.target)),{file:file2,changed:changed2}=await mappings.set(input.envName,mappings.parseTarget(target),{dryRun:dryRun4});return changed2&&!dryRun4&&ctx.configChanged(),IntentOutputs10.of({envName:input.envName,target,file:file2,changed:changed2,dryRun:dryRun4},{summary:changed2?`${dryRun4?"Would map":"Mapped"} ${input.envName} to ${target} in ${file2}.`:`${input.envName} is already mapped to ${target}.`})}var varsIntents=[{intent:"vars.ask",needsRecipeFiles:!0,summary:"Answer the variables this project's recipes define, storing the answers in the .sous env files",description:"Asks only what is unanswered or no longer fits; --all asks everything again. The name may be a variable, an environment variable name, a recipe, a namespace or a repository. Every question can be answered ahead of time with --answer <name>=<value> or --answers-file.",input:jsonSchema16({type:"object",properties:{name:{type:"string",description:"What to ask about: a variable, an environment variable name, a recipe, a namespace or a repository"},all:{type:"boolean",default:!1,description:"Ask every variable again, including the ones already answered"},repo:{type:"string",description:"Ask only the variables published by this repository"},namespace:{type:"string",description:"Ask only the variables published in this namespace"},recipe:{type:"string",description:"Ask only the variables published by this recipe (namespace/recipe)"},var:{type:"array",items:{type:"string"},description:"Ask only this variable"},within:{type:"array",items:{type:"string"},description:"Ask only what the recipes named here (namespace/recipe) still need"},acceptFirst:{type:"boolean",default:!1,description:"When a name matches several things, take the first one listed"},file:FILE_FIELD,dryRun:{type:"boolean",default:!1,description:"Report what would be asked and written, without writing anything"},answer:{type:"array",items:{type:"string"},description:"Answer a variable ahead of its question, as <name>=<value>"},answersFile:{type:"string",description:"Read answers from a YAML, JSON or .env file of name: value pairs"},saveLocally:{type:"boolean",default:!1,description:"Store every answer of this run in .sous/.env.local, which is gitignored and stays on this machine"},saveShared:{type:"boolean",default:!1,description:"Store every answer of this run in .sous/.env, which is committed and shared with everyone on the project"},yes:{type:"boolean",default:!1,description:"Answer yes to storing a secret or machine-specific answer in the committed .sous/.env"}},additionalProperties:!1}),cli:{command:["vars","ask"],positional:["name"],examples:["sous vars ask","sous vars ask apiUrl","sous vars ask SOUS_VAR_API_URL","sous vars ask workflow/task-files","sous vars ask workflow --accept-first","sous vars ask --namespace workflow --var apiUrl","sous vars ask --all","sous vars ask --file ./questions.yaml","sous vars ask --answer apiUrl=https://api.example.com","sous vars ask --answers-file ./answers.yaml","sous vars ask --save-locally"],flags:{within:{hidden:!0},yes:{short:"y",aliases:["force"]}}},agent:{usage:"Pass every answer with `answer` (name=value pairs) or `answersFile`; questions cannot be asked through MCP unless the client supports elicitation."},requiresProject:!0,handle:handleAsk},{intent:"vars.list",needsRecipeFiles:!0,summary:"List every variable this project's recipes define, with its answer",input:jsonSchema16({type:"object",properties:{name:{type:"string",description:"A variable's name, its namespace/recipe.name key, or an environment variable name that answers it, to show in full"},file:FILE_FIELD},additionalProperties:!1}),parallel:!0,cli:{command:["vars","list"],aliases:[["vars","ls"],["vars"]],positional:["name"],examples:["sous vars","sous vars apiUrl","sous vars list","sous vars list --file ./questions.yaml"]},requiresProject:!0,handle:handleList},{intent:"vars.show",needsRecipeFiles:!0,summary:"Show everything about one variable, including how it was answered",input:jsonSchema16({type:"object",properties:{name:{type:"string",description:"A variable's name, its namespace/recipe.name key, or an environment variable name that answers it"},file:FILE_FIELD,acceptFirst:{type:"boolean",default:!1,description:"When the name matches several variables, take the first one listed"}},required:["name"],additionalProperties:!1}),parallel:!0,cli:{command:["vars","show"],positional:["name"],examples:["sous vars show apiUrl","sous vars show workflow/task-files.apiUrl","sous vars show SOUS_VAR_API_URL"]},requiresProject:!0,handle:handleShow},{intent:"vars.map",needsRecipeFiles:!0,summary:"Bind an environment variable to one recipe variable, in conf.d/520-var-mappings.jsonc",input:jsonSchema16({type:"object",properties:{envName:{type:"string",description:"The environment variable name, in upper snake case"},target:{type:"string",description:"The variable it answers: namespace/recipe/variableName, optionally repo:-qualified"},remove:{type:"boolean",default:!1,description:"Remove the mapping instead"},dryRun:{type:"boolean",default:!1,description:"Report what would change, without writing anything"}},required:["envName"],additionalProperties:!1}),changesConfig:!0,cli:{command:["vars","map"],positional:["envName","target"],examples:["sous vars map TEAM_API_URL sous-recipes:misc/stuff/apiUrl","sous vars map TEAM_API_URL --remove"]},requiresProject:!0,handle:handleMap}];var VARIABLES_TAG="variables",variableLookup={id:"recipe-answers.variables",description:"the variables the active recipes define",kinds:["repo","namespace","recipe","variable"],tags:[VARIABLES_TAG],optIn:!0,find:async(candidate,ctx)=>variableLookup.findSync(candidate,ctx),findSync:(candidate,ctx)=>matchVariables(ctx.services.get("recipe-answers.definitions").listSync(),candidate)},envVarLookup={id:"recipe-answers.env-vars",description:"the environment variable names that answer recipe variables",kinds:["envVar"],tags:[VARIABLES_TAG],optIn:!0,find:async(candidate,ctx)=>envVarLookup.findSync(candidate,ctx),findSync:(candidate,ctx)=>matchVariables(ctx.services.get("recipe-answers.definitions").listSync(),candidate,buildLadder({services:ctx.services,env:ctx.env,config:ctx.config}))};var VARIABLE_SOURCE_ID="recipe-answers",FORBIDDEN_UNDER=["subscriptions","repos"];function recipeAnswersSource(variables,services){let answers=ctx=>computeAnswers(variables,buildLadder({services,env:ctx.env,config:ctx.config})),scopeKeys=new Set([...variables.map(entry=>`${entry.recipe.namespace}/${entry.recipe.name}`),...variables.flatMap(entry=>entry.unanswerable===void 0?[]:entry.recipe.holders??[])]);return{id:VARIABLE_SOURCE_ID,description:"recipe answers",definitions:variables,variables:ctx=>variables.length===0?{}:answers(ctx).merged,scoped:(scopeKey,ctx)=>{if(scopeKeys.has(scopeKey))return answersForRecipe(answers(ctx),scopeKey)},secrets:()=>variables.filter(entry=>entry.definition.secret).map(entry=>entry.definition.name),booleans:()=>booleanNames(variables),forbiddenUnder:FORBIDDEN_UNDER}}function variableSourceContributor(services){return{id:"recipe-answers.variable-source",after:["@sous-io/sous-plugin-recipes"],contribute(config2){let variables=definitionsFromRecipes(config2.entities("active-recipe"));config2.addEntity("variable-source",recipeAnswersSource(variables,services))}}}var package_default13={name:"@sous-io/sous-plugin-recipe-answers",version:"1.1.6",description:"Recipe variable definitions, the answer ladder, asking for answers, answer files and variable mappings.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-recipes":"workspace:*","@sous-io/sous-plugin-confd":"workspace:*","@sous-io/sous-plugin-config-files":"workspace:*","@sous-io/sous-plugin-formats":"workspace:*","@sous-io/sous-plugin-refs":"workspace:*","@sous-io/sous-plugin-variables":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME12="@sous-io/sous-plugin-recipe-answers",recipeAnswersPlugin=definePlugin13({name:PLUGIN_NAME12,version:package_default13.version,description:"Recipe variable definitions, the answer ladder, asking for answers, answer files and variable mappings.",dependsOn:{"@sous-io/sous-plugin-recipes":`^${package_default13.version}`,"@sous-io/sous-plugin-confd":`^${package_default13.version}`,"@sous-io/sous-plugin-config-files":`^${package_default13.version}`,"@sous-io/sous-plugin-formats":`^${package_default13.version}`,"@sous-io/sous-plugin-refs":`^${package_default13.version}`,"@sous-io/sous-plugin-variables":`^${package_default13.version}`},register(sous){sous.services.add("recipe-answers.definitions",(_config,ctx)=>new DefinitionsService(ctx),{lifetime:"config"}),sous.services.add("recipe-answers.ladder",(config2,ctx)=>buildLadder({services:ctx.services,env:ctx.env,config:config2}),{lifetime:"config"}),sous.services.add("recipe-answers.answers",(_config,ctx)=>new AnswersService(()=>computeAnswers(ctx.services.get("recipe-answers.definitions").listSync(),ctx.services.get("recipe-answers.ladder"))),{lifetime:"config"}),sous.services.add("recipe-answers.preanswers",(_config,ctx)=>new PreanswersService(ctx),{lifetime:"factory"}),sous.services.add("recipe-answers.mappings",(_config,ctx)=>new MappingsService(ctx),{lifetime:"config"}),sous.services.add("recipe-answers.validator",()=>validator,{lifetime:"singleton"}),sous.services.add("recipe-answers.asking",()=>asking,{lifetime:"singleton"}),sous.entities.add("config-key",{id:"varMappings",description:"Environment variable names bound to recipe variables (conf.d/520-var-mappings.jsonc).",schema:jsonSchema17({type:"object",additionalProperties:{type:"string"},default:{}})}),sous.entities.add("ref-lookup",variableLookup),sous.entities.add("ref-lookup",envVarLookup),sous.config.contribute(variableSourceContributor(sous.services));for(let intent of varsIntents)sous.intents.add(intent)}});import{definePlugin as definePlugin14}from"@sous-io/sous-plugin-api";import path64 from"node:path";function transformIdFor(targetId){return`skills/${targetId}`}function outputDir(directory){let trimmed=directory.trim();if(path64.isAbsolute(trimmed))return stripTrailingSlash(path64.normalize(trimmed));if(trimmed.startsWith("${"))return stripTrailingSlash(trimmed);let relative4=path64.posix.normalize(trimmed.split(path64.sep).join("/"));return relative4==="."?"${projectRoot}":`\${projectRoot}/${stripTrailingSlash(relative4.replace(/^\.\//,""))}`}function skillDestinations(outputs,targets){let destinations=[],seen=new Set;for(let target of targets){if(typeof target.directory!="string"||target.directory.trim()==="")continue;let dir=outputDir(target.directory);seen.has(dir)||(seen.add(dir),destinations.push({dir,target:target.id,...typeof target.transform=="function"?{transform:transformIdFor(target.id)}:{},...typeof target.harness=="string"&&target.harness!==""?{harness:target.harness}:{}}))}for(let output of outputs){let dir=outputDir(output);seen.has(dir)||(seen.add(dir),destinations.push({dir}))}return destinations}function stripTrailingSlash(value){return value.length>1&&value.endsWith("/")?value.slice(0,-1):value}import{jsonSchema as jsonSchema18}from"@sous-io/sous-plugin-api";var SKILLS_KEY="recipes.skills",stringList2={type:"array",items:{type:"string"},default:[]},skillsConfigKey={id:SKILLS_KEY,description:"Where skills go (outputs, `${var}` allowed) and directories of your own skills (include).",schema:jsonSchema18({type:"object",properties:{outputs:{...stringList2,description:"Directories skills are also written to."},include:{...stringList2,description:"Directories of your own skills, compiled like a recipe's."}},additionalProperties:!1,default:{}})};function stringsOf(value){return Array.isArray(value)?value.filter(item=>typeof item=="string"&&item.trim()!==""):[]}function describeNowhere(sources){let recipes=new Set(sources.flatMap(source=>source.recipe===void 0?[]:[source.recipe])).size,own=sources.filter(source=>source.origin==="project").length,parts=[];if(recipes>0&&parts.push(`the skills of ${recipes} ${recipes===1?"recipe":"recipes"}`),own>0&&parts.push(`${own} ${own===1?"skill":"skills"} of your own`),parts.length!==0)return{summary:`Skipped ${parts.join(" and ")}: nothing says where skills go.`,hint:"Set recipes.skills.outputs in the config, or enable an agent plugin (such as @sous-io/sous-plugin-claude-code)."}}function skillWarnings(ctx){if(!ctx.services.has("skills.sources"))return[];let sources=ctx.services.get("skills.sources"),warnings=(sources.problems?.()??[]).map(summary2=>({summary:summary2}));if(skillDestinations(stringsOf(ctx.config.get("recipes.skills.outputs")),ctx.entities.list("skill-target")).length===0){let nowhere=describeNowhere(sources.list());nowhere&&warnings.push(nowhere)}return warnings}init_index_min();import fs49 from"node:fs";import path65 from"node:path";function bytewise(a,b){return a<b?-1:a>b?1:0}function findSkills(input){let skills=[],problems=[],repositories=new Map(input.recipes.map(recipe=>[recipe.id,recipe.repo]));for(let content of input.contents)skills.push(...recipeSkills(content,repositories.get(content.recipe)));return input.include.forEach((entry,index)=>{let setting=`recipes.skills.include[${index}]`,dir=resolveProjectDir(entry,input.project);if(typeof dir!="string"){problems.push({setting,message:`${setting} is "${entry}": ${dir.reason}`});return}if(!isDirectory2(dir)){problems.push({setting,message:`${setting} is "${entry}", which is not a directory, so it was skipped.`});return}skills.push(...groupSkills({origin:"project"},[{base:dir,files:listFiles2(dir,"**/*",[])}]))}),{skills,problems}}function recipeSkills(content,repository){let byBase=new Map,inline=new Map;for(let{base,file:file2,content:text}of content.files)byBase.set(base,[...byBase.get(base)??[],file2]),text!==void 0&&inline.set(file2,text);let skills=groupSkills({origin:"recipe",recipe:content.recipe,...repository===void 0?{}:{repository}},[...byBase].map(([base,files])=>({base,files})));return inline.size===0?skills:skills.map(skill=>{let own=new Map([...inline].filter(([file2])=>skill.files.some(relative4=>path65.join(skill.dir,relative4)===file2)));return own.size===0?skill:{...skill,inline:own}})}function groupSkills(from,groups){let byDir=new Map;for(let group of groups)for(let file2 of group.files){let relative4=path65.relative(group.base,file2);if(relative4===""||relative4.startsWith("..")||path65.isAbsolute(relative4))continue;let[first2]=relative4.split(path65.sep),nested=relative4!==first2,dir=nested?path65.join(group.base,first2):group.base,name=nested?first2:withoutExtensions(first2),key=`${dir}\0${nested?"":name}`,skill=byDir.get(key);skill||(skill={name,base:group.base,files:new Set},byDir.set(key,skill)),skill.files.add(path65.relative(dir,file2).split(path65.sep).join("/"))}return[...byDir.entries()].map(([key,skill])=>({name:skill.name,...from,dir:key.slice(0,key.indexOf("\0")),base:skill.base,files:[...skill.files].sort(bytewise)})).sort((a,b)=>bytewise(a.name,b.name)||bytewise(a.dir,b.dir))}function listFiles2(cwd,pattern,exclude){return isDirectory2(cwd)?ts(pattern,{cwd,absolute:!0,nodir:!0,ignore:[...exclude]}).filter(isFile9).sort(bytewise):[]}function resolveProjectDir(entry,project){let substituted=entry.replace(/\$\{(projectRoot|sousDir)\}/g,(_match,name)=>project?name==="projectRoot"?project.root:project.sousDir:_match);return/\$\{[^}]*\}/.test(substituted)?{reason:project?"only ${projectRoot} and ${sousDir} can be used here, so it was skipped.":"there is no project to resolve it in, so it was skipped."}:path65.isAbsolute(substituted)?path65.normalize(substituted):project?path65.resolve(project.root,substituted):{reason:"a relative directory needs a project, and there is none, so it was skipped."}}function withoutExtensions(name){let dot=name.indexOf(".",1);return dot===-1?name:name.slice(0,dot)}function isDirectory2(candidate){try{return fs49.statSync(candidate).isDirectory()}catch{return!1}}function isFile9(candidate){try{return fs49.statSync(candidate).isFile()}catch{return!1}}var ConfigSkillsSources=class{constructor(config2,ctx){this.config=config2;this.ctx=ctx}found;list(){return this.find().skills.map(({base:_base,inline:_inline,...source})=>source)}recipes(){return[...new Set(this.find().skills.flatMap(skill=>skill.recipe===void 0?[]:[skill.recipe]))]}problems(){return this.find().problems.map(problem=>problem.message)}find(){return this.found??=findSkills({recipes:this.ctx.entities.list("active-recipe"),contents:this.ctx.services.get("recipes.contents").of(this.config,"skills"),include:stringsOf(this.config.get("recipes.skills.include")),project:this.ctx.project}),this.found}};import{jsonSchema as jsonSchema19}from"@sous-io/sous-plugin-api";var SKILL_TARGET="skill-target",skillTargetSchema=jsonSchema19({type:"object",properties:{id:{type:"string",description:"The target's name: `claude-code`."},harness:{type:"string",description:"The `harness` entity that reads it."},directory:{type:"string",description:"The directory skills go into; relative paths are under the project root."},description:{type:"string"}},required:["id","directory"]}),SKILL_TARGET_DESCRIPTION="A place a harness reads skills from, with an optional transform of each file.";import path66 from"node:path";var TARGETS_CONTRIBUTOR="skills.targets";function contributeSkillTargets(config2,plugin,contents){let outputs=stringsOf(config2.atPath("recipes.skills.outputs").get()),include=stringsOf(config2.atPath("recipes.skills.include").get()),targets=config2.entities("skill-target"),destinations=skillDestinations(outputs,targets);if(destinations.length===0)return;let input={contents:contents.of(config2,"skills"),recipes:config2.entities("active-recipe"),include,project:config2.project},{skills}=findSkills(input);if(skills.length===0)return;let origins=new Map,list2=config2.atPath("compilation.targets");for(let skill of skills)for(let file2 of skill.files){let entryPoint=path66.join(skill.dir,file2);origins.set(entryPoint,skill.recipe===void 0?{skill:skill.name}:{skill:skill.name,recipe:skill.recipe}),list2.append(compilationTarget(skill,entryPoint,destinations,plugin,config2.project?.root))}for(let target of targets)typeof target.transform=="function"&&destinations.some(d=>d.target===target.id)&&config2.addEntity("compilation-transform",transformEntity(target,origins))}function compilationTarget(skill,entryPoint,destinations,plugin,projectRoot){let fromBase=path66.relative(skill.base,entryPoint).split(path66.sep).join("/"),where3=skill.recipe??`project:${projectRoot?path66.relative(projectRoot,skill.base).split(path66.sep).join("/")||".":skill.base}`,inline=skill.inline?.get(entryPoint);return inline!==void 0?{id:`skills/${where3}/${fromBase}`,content:inlineTemplate(inline,fromBase),origin:{plugin,...skill.recipe===void 0?{}:{recipe:skill.recipe},...skill.repository===void 0?{}:{repository:skill.repository}},outputs:destinations.map(destination=>outputFor(destination,{destinationFile:`${destination.dir.replace(/\/+$/,"")}/${fromBase}`}))}:{id:`skills/${where3}/${fromBase}`,entryPoint,globBase:skill.base,origin:{plugin,...skill.recipe===void 0?{}:{recipe:skill.recipe},...skill.repository===void 0?{}:{repository:skill.repository}},outputs:destinations.map(destination=>outputFor(destination,{destinationDir:destination.dir}))}}function outputFor(destination,where3){return{...where3,...destination.transform===void 0?{}:{transforms:[destination.transform]},...destination.harness===void 0?{}:{harness:destination.harness}}}function inlineTemplate(content,virtualPath){return path66.posix.basename(virtualPath).includes(".tpl.")?content:`{% raw %}${content}{% endraw %}`}function transformEntity(target,origins){let transform2=target.transform;return{id:transformIdFor(target.id),description:`The transform of the skill target "${target.id}".`,async transform(file2,ctx){let origin=origins.get(file2.source)??{skill:path66.basename(path66.dirname(file2.source))},skillFile={...file2,...origin};return transform2(skillFile,ctx)}}}var package_default14={name:"@sous-io/sous-plugin-skills",version:"1.1.6",description:"Skills: where they come from, the skill-target entity, and the compilation targets for them.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-compiler":"workspace:*","@sous-io/sous-plugin-recipes":"workspace:*",glob:"^13.0.6"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME13="@sous-io/sous-plugin-skills",skillsPlugin=definePlugin14({name:PLUGIN_NAME13,version:package_default14.version,description:"Skills: where they come from, the skill-target entity, and the compilation targets for them.",dependsOn:{"@sous-io/sous-plugin-compiler":`^${package_default14.version}`,"@sous-io/sous-plugin-recipes":`^${package_default14.version}`},register(sous){sous.entities.define(SKILL_TARGET,skillTargetSchema,{description:SKILL_TARGET_DESCRIPTION}),sous.entities.add("config-key",skillsConfigKey),sous.services.add("skills.sources",(config2,ctx)=>new ConfigSkillsSources(config2,ctx),{lifetime:"config"});let services=sous.services;sous.config.contribute({id:TARGETS_CONTRIBUTOR,after:["@sous-io/sous-plugin-recipes"],contribute:config2=>contributeSkillTargets(config2,PLUGIN_NAME13,services.get("recipes.contents"))}),sous.on("compiler.compile.before",(_event,ctx)=>{for(let warning of skillWarnings(ctx))ctx.reporter.problem(warning.summary,warning.hint===void 0?{}:{hint:warning.hint})})}});import{definePlugin as definePlugin15}from"@sous-io/sous-plugin-api";import path67 from"node:path";init_src2();var compileRecipeKeyMatcher=compilePatternList,compileRecipeKeyFinder=compilePatternFinder;var FIRST_KEY="recipes.memories.first",EXCLUDE_KEY="recipes.memories.exclude";function dependencyOrder(recipes,compare){let waitingOn=new Map;for(let recipe of recipes)waitingOn.set(recipe.id,new Set);for(let dependency of recipes)for(let holder of dependency.requestedBy)holder!==dependency.id&&waitingOn.get(holder)?.add(dependency.id);let ordered2=[],done2=new Set,remaining=[...waitingOn.keys()].sort(compare);for(;remaining.length>0;){let index=remaining.findIndex(key2=>[...waitingOn.get(key2)].every(dep=>done2.has(dep)));if(index===-1){ordered2.push(...remaining);break}let[key]=remaining.splice(index,1);ordered2.push(key),done2.add(key)}return ordered2}function recipeMemories(recipe,globs,contents,onWarning=()=>{}){let byFile=new Map;for(let content of contents.filter(entry=>entry.recipe===recipe.id))for(let{file:file2,base,content:text}of content.files)if(!byFile.has(file2)){if(text!==void 0){byFile.set(file2,{recipe:recipe.id,repository:recipe.repo,name:globs.toPosix(path67.relative(base,file2)),path:file2,content:text});continue}if(globs.realPathInside(file2,recipe.dir)===void 0){onWarning(`The memory ${file2} of the recipe ${recipe.id} was left out, because it is a link that leads outside the recipe's directory. Replace the link with the file itself.`);continue}byFile.set(file2,{recipe:recipe.id,repository:recipe.repo,name:globs.toPosix(path67.relative(base,file2)),path:file2})}return[...byFile.values()].sort((a,b)=>compareIncludeOrder(a.name,b.name))}function selectMemories(options2){let{recipes,globs,contents}=options2,isMatch=(key,pattern)=>globs.isMatch(key,pattern),isFirst=compileRecipeKeyMatcher(options2.settings?.first,FIRST_KEY,isMatch),excludedBy=compileRecipeKeyFinder(options2.settings?.exclude,EXCLUDE_KEY,isMatch),byKey2=new Map(recipes.map(recipe=>[recipe.id,recipe])),order=dependencyOrder(recipes,(a,b)=>globs.compareBytewise(a,b)),leading=order.filter(key=>isFirst(key)),rest=order.filter(key=>!isFirst(key)),selected2=[],excluded=[];for(let key of[...leading,...rest]){let recipe=byKey2.get(key),memories=recipeMemories(recipe,globs,contents,options2.onWarning),by2=excludedBy(key);by2===void 0?selected2.push(...memories):excluded.push(...memories.map(memory=>({memory,by:by2})))}return{selected:selected2,excluded}}function viewPath(memory){return`${memory.recipe}/${memory.name}`}var memoriesHashName={id:"memories",description:"the memories of every active recipe, listed in dependency order as #memories/<namespace>/<recipe>/<path>.",view:ctx=>ctx.services.get("memories.selection").selected().map(memory=>({path:viewPath(memory),file:memory.path}))};import{jsonSchema as jsonSchema20}from"@sous-io/sous-plugin-api";function refine2(base,extra){let standard=base["~standard"];return{"~standard":{...standard,validate(value){let result=standard.validate(value);if(result.issues)return result;let issues=extra(result.value);return issues.length>0?{issues}:result}}}}var memoryTargetSchema=refine2(jsonSchema20({type:"object",required:["id","outputPath"],properties:{id:{type:"string",minLength:1,description:"The target's id: `claude-code`, `codex`."},harness:{type:"string",description:"The `harness` entity that reads the file; its output is marked with it."},outputPath:{type:"string",minLength:1,description:"The file to write; `${projectRoot}` and other variables allowed, a relative path is under the project root."},prependWith:{type:"string",description:"A file included before the memories; skipped when it does not exist."},backupExisting:{type:"boolean",description:"Back up, warn about and overwrite a file sous did not write at outputPath."}}}),target=>["fileName","directory","readIn","filter","format"].filter(name=>target[name]!==void 0).map(name=>({path:[name],message:`"${name}" was removed from memory targets in sous 1.1.0: a memory target names the file it writes with "outputPath", and its content comes from .sous/MEMORIES.tpl.md.`})));function keyListIssues(entries,where3,key){return entries.flatMap((entry,index)=>{try{return compileRecipeKeyMatcher([entry],`${where3}[${index}]`,()=>!1),[]}catch(error51){return[{path:[key,index],message:error51 instanceof Error?error51.message:String(error51)}]}})}var memoriesSettingsSchema=refine2(jsonSchema20({type:"object",additionalProperties:!1,properties:{first:{type:"array",items:{type:"string"},default:[],description:"Recipe keys, globs or /regular expressions/ whose memories come first, in this order."},exclude:{type:"array",items:{type:"string"},default:[],description:"Recipe keys, globs or /regular expressions/ whose memories are left out."}},default:{},description:"Which recipe memories memory targets and the #memories view take, and in what order."}),settings=>[...keyListIssues(settings.first,FIRST_KEY,"first"),...keyListIssues(settings.exclude,EXCLUDE_KEY,"exclude")]);import{NotFoundError as NotFoundError7}from"@sous-io/sous-plugin-api";var MemoriesSelectionService=class{constructor(config2,ctx){this.config=config2;this.ctx=ctx}result;selected(){return[...this.select().selected]}forTarget(targetId){if(!this.ctx.entities.get("memory-target",targetId))throw new NotFoundError7("memory-target",targetId,`No memory target "${targetId}" exists.`);return this.selected()}excluded(){return[...this.select().excluded]}select(){return this.result??=selectMemories({recipes:this.ctx.entities.list("active-recipe"),settings:this.config.get(["recipes","memories"]),globs:this.ctx.services.get("host.globs"),contents:this.ctx.services.get("recipes.contents").of(this.config,"memories")}),this.result}};import fs50 from"node:fs";import os8 from"node:os";import path68 from"node:path";var TARGETS_CONTRIBUTOR2="memories.targets",MEMORIES_SOURCE="MEMORIES.tpl.md",PROJECT_MEMORIES_DIR="memories";var SKIP_EMPTY_TRANSFORM="memories/skip-empty";function compilationTargetId(target){return`memories/${target.id}`}function defaultFormat(memories,toPosix3){return memories.map(memory=>memory.content===void 0?includeReference(memory.path,toPosix3):inlineMemory(memory.content,memory.path)).join(`
1149
1150
 
1150
- `)}function inlineMemory(content,virtualPath){return virtualPath.split(/[\\/]/).pop().includes(".tpl.")?content:`{% raw %}${content}{% endraw %}`}function configPath(file2){let trimmed=file2.trim();return trimmed.startsWith("${")||trimmed.startsWith("~/")||path68.isAbsolute(trimmed)?trimmed:`\${projectRoot}/${trimmed.replace(/^\.\/+/,"")}`}function diskPath(file2,project){let filled=configPath(file2).replace(/^~\//,`${os8.homedir()}/`).replace(/\$\{projectRoot\}/g,project.root).replace(/\$\{sousDir\}/g,project.sousDir);return filled.includes("${")?void 0:path68.resolve(project.root,filled)}function holdsMarkdown(dir){let entries;try{entries=fs50.readdirSync(dir,{withFileTypes:!0})}catch{return!1}return entries.some(entry=>entry.isDirectory()?holdsMarkdown(path68.join(dir,entry.name)):entry.name.endsWith(".md"))}function memoriesContent(target,source){let exists3=source.exists??fs50.existsSync,parts=[];if(typeof target.prependWith=="string"&&target.prependWith.trim()!==""){let file2=diskPath(target.prependWith,source.project);file2!==void 0&&exists3(file2)&&parts.push(`@${file2}`)}return exists3(path68.join(source.project.sousDir,MEMORIES_SOURCE))?parts.push(`@${path68.join(source.project.sousDir,MEMORIES_SOURCE)}`):(holdsMarkdown(path68.join(source.project.sousDir,PROJECT_MEMORIES_DIR))&&parts.push(`@${path68.join(source.project.sousDir,PROJECT_MEMORIES_DIR)}/**/*.md`),source.selected.length>0&&parts.push(defaultFormat(source.selected))),parts.length===0?void 0:parts.join(`
1151
+ `)}function includeReference(file2,toPosix3){return`@${toPosix3(file2).replaceAll(" ","\\ ")}`}function inlineMemory(content,virtualPath){return virtualPath.split(/[\\/]/).pop().includes(".tpl.")?content:`{% raw %}${content}{% endraw %}`}function configPath(file2){let trimmed=file2.trim();return trimmed.startsWith("${")||trimmed.startsWith("~/")||path68.isAbsolute(trimmed)?trimmed:`\${projectRoot}/${trimmed.replace(/^\.\/+/,"")}`}function diskPath(file2,project){let filled=configPath(file2).replace(/^~\//,`${os8.homedir()}/`).replace(/\$\{projectRoot\}/g,project.root).replace(/\$\{sousDir\}/g,project.sousDir);return filled.includes("${")?void 0:path68.resolve(project.root,filled)}function holdsMarkdown(dir){let entries;try{entries=fs50.readdirSync(dir,{withFileTypes:!0})}catch{return!1}return entries.some(entry=>entry.isDirectory()?holdsMarkdown(path68.join(dir,entry.name)):entry.name.endsWith(".md"))}function memoriesContent(target,source){let exists3=source.exists??fs50.existsSync,parts=[];if(typeof target.prependWith=="string"&&target.prependWith.trim()!==""){let file2=diskPath(target.prependWith,source.project);file2!==void 0&&exists3(file2)&&parts.push(includeReference(file2,source.toPosix))}let memoriesSource=path68.join(source.project.sousDir,MEMORIES_SOURCE);if(exists3(memoriesSource))parts.push(includeReference(memoriesSource,source.toPosix));else{let projectMemories=path68.join(source.project.sousDir,PROJECT_MEMORIES_DIR);holdsMarkdown(projectMemories)&&parts.push(`@${source.toPosix(projectMemories)}/**/*.md`),source.selected.length>0&&parts.push(defaultFormat(source.selected,source.toPosix))}return parts.length===0?void 0:parts.join(`
1151
1152
 
1152
- `)}function compilationTargetFor(target,source,plugin){let content=memoriesContent(target,source);if(content===void 0)return;let output={destinationFile:configPath(target.outputPath),...typeof target.harness=="string"&&target.harness!==""?{harness:target.harness}:{},...target.backupExisting===!0?{backupExisting:!0}:{}};return{id:compilationTargetId(target),content,transforms:[SKIP_EMPTY_TRANSFORM],origin:{plugin},outputs:[output]}}var skipEmptyTransform={id:SKIP_EMPTY_TRANSFORM,description:"Leaves out a memories file that compiled to nothing, so no empty file is written and an earlier copy is removed.",transform:file2=>typeof file2.content=="string"&&file2.content.trim()===""?void 0:file2};function readSettings(config2){let value=config2.atPath(["recipes","memories"]).get();return value!==null&&typeof value=="object"?value:{}}function targetsContributor(plugin,services){let warned=new Set;return{id:TARGETS_CONTRIBUTOR2,contribute(config2){let targets=config2.entities("memory-target"),project=config2.project;if(targets.length===0||project===void 0)return;let globs=services.get("host.globs"),{selected:selected2}=selectMemories({recipes:config2.entities("active-recipe"),settings:readSettings(config2),globs,contents:services.get("recipes.contents").of(config2,"memories"),onWarning:message2=>{warned.has(message2)||(warned.add(message2),config2.warn(message2))}});for(let target of targets){let compilation=compilationTargetFor(target,{project,selected:selected2},plugin);compilation&&config2.atPath(["compilation","targets"]).appendValue(compilation)}}}}var package_default15={name:"@sous-io/sous-plugin-memories",version:"1.1.4",description:"Memories: selecting them, the memory-target entity, the compilation targets for them, the #memories name.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-lib-documents":"workspace:*","@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-compiler":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@sous-io/sous-plugin-recipes":"workspace:*","@sous-io/sous-plugin-refs":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*",glob:"^13.0.6",minimatch:"^10.2.4"},engines:{node:">=22"}};var PLUGIN_NAME14="@sous-io/sous-plugin-memories",memoriesPlugin=definePlugin15({name:PLUGIN_NAME14,version:package_default15.version,description:"Memories: selecting them, the memory-target entity, the compilation targets for them, the #memories name.",dependsOn:{"@sous-io/sous-plugin-compiler":`^${package_default15.version}`,"@sous-io/sous-plugin-recipes":`^${package_default15.version}`,"@sous-io/sous-plugin-refs":`^${package_default15.version}`,"@sous-io/sous-plugin-host":`^${package_default15.version}`},register(sous){sous.entities.define("memory-target",memoryTargetSchema,{description:"The one file a harness reads into every session, compiled from .sous/MEMORIES.tpl.md or the default memories source."}),sous.entities.add("config-key",{id:"recipes.memories",schema:memoriesSettingsSchema,description:"Which recipe memories go to memory targets and the #memories view, and in what order."}),sous.entities.add("hash-name",memoriesHashName),sous.entities.add("compilation-transform",skipEmptyTransform),sous.services.add("memories.selection",(config2,ctx)=>new MemoriesSelectionService(config2,ctx),{lifetime:"config"}),sous.config.contribute(targetsContributor(PLUGIN_NAME14,sous.services))}});init_src8();init_pid();import{definePlugin as definePlugin18}from"@sous-io/sous-plugin-api";init_schemas4();import fs55 from"node:fs";import path71 from"node:path";var UNKNOWN_BRANCH="unknown",RUNTIME_CONTEXT_SOURCE="runtime-context",RuntimeContextService=class{constructor(deps){this.deps=deps}settings(){return this.deps.settings}async generate(){let settings=this.deps.settings;if(!settings)return;let branch=await this.readBranch(settings.gitRoot),branchProblem=branch===void 0?await this.branchProblem(settings.gitRoot):void 0,pattern=new RegExp(settings.branchPattern??DEFAULT_BRANCH_PATTERN),taskFile,taskContent;branch!==void 0&&pattern.test(branch)&&(taskFile=path71.join(settings.taskFileRoot,`${branch}.md`),taskContent=readIfExists(taskFile));let content=renderRuntimeContext({branch:branch??UNKNOWN_BRANCH,matched:taskFile!==void 0,...taskFile===void 0?{}:{taskFile},...taskContent===void 0?{}:{taskContent}});return{...branch===void 0?{}:{branch},...branchProblem===void 0?{}:{branchProblem},...taskFile!==void 0&&taskContent!==void 0?{taskFile}:{},outputPath:settings.outputPath,content}}async write(options2={}){let context=await this.generate();if(context)return this.deps.writer().write(context.outputPath,context.content,{source:RUNTIME_CONTEXT_SOURCE,origin:{plugin:this.deps.plugin},...options2.dryRun?{dryRun:!0}:{},...options2.run===void 0?{}:{run:options2.run}})}async branchProblem(gitRoot){try{let result=await this.deps.git().run(["symbolic-ref","--short","HEAD"],{cwd:gitRoot,reject:!1}),line=result.stderr.split(`
1153
+ `)}function compilationTargetFor(target,source,plugin){let content=memoriesContent(target,source);if(content===void 0)return;let output={destinationFile:configPath(target.outputPath),...typeof target.harness=="string"&&target.harness!==""?{harness:target.harness}:{},...target.backupExisting===!0?{backupExisting:!0}:{}};return{id:compilationTargetId(target),content,transforms:[SKIP_EMPTY_TRANSFORM],origin:{plugin},outputs:[output]}}var skipEmptyTransform={id:SKIP_EMPTY_TRANSFORM,description:"Leaves out a memories file that compiled to nothing, so no empty file is written and an earlier copy is removed.",transform:file2=>typeof file2.content=="string"&&file2.content.trim()===""?void 0:file2};function readSettings(config2){let value=config2.atPath(["recipes","memories"]).get();return value!==null&&typeof value=="object"?value:{}}function targetsContributor(plugin,services){let warned=new Set;return{id:TARGETS_CONTRIBUTOR2,contribute(config2){let targets=config2.entities("memory-target"),project=config2.project;if(targets.length===0||project===void 0)return;let globs=services.get("host.globs"),{selected:selected2}=selectMemories({recipes:config2.entities("active-recipe"),settings:readSettings(config2),globs,contents:services.get("recipes.contents").of(config2,"memories"),onWarning:message2=>{warned.has(message2)||(warned.add(message2),config2.warn(message2))}});for(let target of targets){let compilation=compilationTargetFor(target,{project,selected:selected2,toPosix:globs.toPosix},plugin);compilation&&config2.atPath(["compilation","targets"]).appendValue(compilation)}}}}var package_default15={name:"@sous-io/sous-plugin-memories",version:"1.1.6",description:"Memories: selecting them, the memory-target entity, the compilation targets for them, the #memories name.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-lib-documents":"workspace:*","@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-compiler":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@sous-io/sous-plugin-recipes":"workspace:*","@sous-io/sous-plugin-refs":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*",glob:"^13.0.6",minimatch:"^10.2.4"},engines:{node:">=22"}};var PLUGIN_NAME14="@sous-io/sous-plugin-memories",memoriesPlugin=definePlugin15({name:PLUGIN_NAME14,version:package_default15.version,description:"Memories: selecting them, the memory-target entity, the compilation targets for them, the #memories name.",dependsOn:{"@sous-io/sous-plugin-compiler":`^${package_default15.version}`,"@sous-io/sous-plugin-recipes":`^${package_default15.version}`,"@sous-io/sous-plugin-refs":`^${package_default15.version}`,"@sous-io/sous-plugin-host":`^${package_default15.version}`},register(sous){sous.entities.define("memory-target",memoryTargetSchema,{description:"The one file a harness reads into every session, compiled from .sous/MEMORIES.tpl.md or the default memories source."}),sous.entities.add("config-key",{id:"recipes.memories",schema:memoriesSettingsSchema,description:"Which recipe memories go to memory targets and the #memories view, and in what order."}),sous.entities.add("hash-name",memoriesHashName),sous.entities.add("compilation-transform",skipEmptyTransform),sous.services.add("memories.selection",(config2,ctx)=>new MemoriesSelectionService(config2,ctx),{lifetime:"config"}),sous.config.contribute(targetsContributor(PLUGIN_NAME14,sous.services))}});init_src8();init_pid();import{definePlugin as definePlugin18}from"@sous-io/sous-plugin-api";init_schemas4();import fs55 from"node:fs";import path71 from"node:path";var UNKNOWN_BRANCH="unknown",RUNTIME_CONTEXT_SOURCE="runtime-context",RuntimeContextService=class{constructor(deps){this.deps=deps}settings(){return this.deps.settings}async generate(){let settings=this.deps.settings;if(!settings)return;let branch=await this.readBranch(settings.gitRoot),branchProblem=branch===void 0?await this.branchProblem(settings.gitRoot):void 0,pattern=new RegExp(settings.branchPattern??DEFAULT_BRANCH_PATTERN),taskFile,taskContent;branch!==void 0&&pattern.test(branch)&&(taskFile=path71.join(settings.taskFileRoot,`${branch}.md`),taskContent=readIfExists(taskFile));let content=renderRuntimeContext({branch:branch??UNKNOWN_BRANCH,matched:taskFile!==void 0,...taskFile===void 0?{}:{taskFile},...taskContent===void 0?{}:{taskContent}});return{...branch===void 0?{}:{branch},...branchProblem===void 0?{}:{branchProblem},...taskFile!==void 0&&taskContent!==void 0?{taskFile}:{},outputPath:settings.outputPath,content}}async write(options2={}){let context=await this.generate();if(context)return this.deps.writer().write(context.outputPath,context.content,{source:RUNTIME_CONTEXT_SOURCE,origin:{plugin:this.deps.plugin},...options2.dryRun?{dryRun:!0}:{},...options2.run===void 0?{}:{run:options2.run}})}async branchProblem(gitRoot){try{let result=await this.deps.git().run(["symbolic-ref","--short","HEAD"],{cwd:gitRoot,reject:!1}),line=result.stderr.split(`
1153
1154
  `).map(text=>text.trim()).find(text=>text.length>0);return result.exitCode===0?void 0:line}catch{return}}async readBranch(gitRoot){try{return await this.deps.git().currentBranch(gitRoot)}catch{return}}};function readIfExists(file2){try{return fs55.readFileSync(file2,"utf8")}catch{return}}function renderRuntimeContext(facts){let header=`## Runtime Session Context
1154
1155
 
1155
1156
  The following information is specific to this chat session. It was generated automatically and
@@ -1174,11 +1175,11 @@ file are included below:
1174
1175
  ${facts.taskContent.replace(/\n+$/u,"")}
1175
1176
  --- End Task File: ${facts.taskFile} ---
1176
1177
  `),`${header}${block}
1177
- `}init_schemas4();var package_default18={name:"@sous-io/sous-plugin-build",version:"1.1.4",description:"The build, compile, prune and clear intents, preparing for a build, watch mode, the PID file, the runtime context file.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-compiler":"workspace:*","@sous-io/sous-plugin-git":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@sous-io/sous-plugin-memories":"workspace:*","@sous-io/sous-plugin-recipe-answers":"workspace:*","@sous-io/sous-plugin-recipes":"workspace:*","@sous-io/sous-plugin-variables":"workspace:*","@sous-io/sous-plugin-editor":"workspace:*","@sous-io/sous-plugin-handlers":"workspace:*",chokidar:"^5.0.0",semver:"^7.8.5"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*","@types/semver":"^7.8.0"},engines:{node:">=22"}};init_report();var PLUGIN_NAME17="@sous-io/sous-plugin-build",PLUGIN_VERSION=package_default18.version;function createBuildPlugin(options2={}){let cwd=options2.cwd;return definePlugin18({name:PLUGIN_NAME17,version:PLUGIN_VERSION,description:"The build, compile, prune and clear intents, preparing for a build, watch mode, the PID file, the runtime context file.",dependsOn:{"@sous-io/sous-plugin-compiler":`^${package_default18.version}`,"@sous-io/sous-plugin-recipes":`^${package_default18.version}`,"@sous-io/sous-plugin-recipe-answers":`^${package_default18.version}`,"@sous-io/sous-plugin-git":`^${package_default18.version}`,"@sous-io/sous-plugin-host":`^${package_default18.version}`,"@sous-io/sous-plugin-variables":`^${package_default18.version}`},register(sous){sous.entities.add("config-key",{id:"watch",schema:watchSettingsSchema,description:"Watch mode: more paths that trigger a full rebuild, the debounce, and how often to check upstream."}),sous.entities.add("config-key",{id:"runtimeContext",schema:runtimeContextSchema,description:"The runtime context file a target with generateRuntimeContext includes: git branch and task file."}),sous.services.add("build.pid",(_config,ctx)=>new PidFile({...explicitPidPath(ctx.services),project:ctx.project,cwd:cwd?.()??ctx.cwd??".",isAlive:options2.isProcessAlive??isProcessAlive}),{lifetime:"singleton"}),sous.services.add("build.runtime-context",(config2,ctx)=>new RuntimeContextService({settings:runtimeContextSettings(config2.get("runtimeContext"),ctx.services),git:()=>ctx.services.get("git.runner"),writer:()=>ctx.services.get("compiler.writer"),plugin:PLUGIN_NAME17}),{lifetime:"config"}),sous.intents.add({intent:"build",needsRecipeFiles:!0,requiresProject:!0,summary:"Compile this project's outputs and remove the ones its config no longer produces",input:buildInputSchema,cli:{examples:["sous build","sous build --no-prune","sous build --rebuild","sous build --dry-run","sous build --keep-going"],flags:{watch:{short:"w"},changedFiles:{hidden:!0},reportRemoved:{hidden:!0}}},agent:{usage:"Run after changing the config, a subscription or a template, to write every output again.",whenNotToUse:"Not with watch: an agent cannot stop a watcher; build again instead."},load:async()=>(await Promise.resolve().then(()=>(init_build(),build_exports))).build}),sous.intents.add({intent:"compile",needsRecipeFiles:!0,requiresProject:!0,summary:"Compile markdown templates into output files",description:"Compiles every target in the config without preparing recipes or pruning.",input:compileInputSchema,cli:{examples:["sous compile","sous compile --rebuild","sous compile --dry-run","sous compile --strict"],flags:{watch:{short:"w"},changedFiles:{hidden:!0}}},load:async()=>(await Promise.resolve().then(()=>(init_build(),build_exports))).compile}),sous.intents.add({intent:"build.prepare",needsRecipeFiles:!0,requiresProject:!0,summary:"Seed core, lock new subscriptions, restore the store and check upstream",input:prepareInputSchema,internal:!0,load:async()=>(await Promise.resolve().then(()=>(init_prepare(),prepare_exports))).prepare}),sous.intents.add({intent:"prune",needsRecipeFiles:!0,requiresProject:!0,summary:"Remove output files that are no longer in the current config",input:pruneInputSchema,cli:{examples:["sous prune","sous prune --dry-run"]},load:async()=>(await Promise.resolve().then(()=>(init_build(),build_exports))).prune}),sous.intents.add({intent:"clear",needsRecipeFiles:!0,requiresProject:!0,summary:"Delete all files and directories written by Sous for a project",input:clearInputSchema,cli:{examples:["sous clear","sous clear --force","sous clear --yes"],flags:{force:{short:"f",aliases:["yes"]}}},agent:{usage:"Pass force: true; an agent cannot answer the confirmation."},load:async()=>(await Promise.resolve().then(()=>(init_build(),build_exports))).clear}),sous.intents.add({intent:"build.watch",needsRecipeFiles:!0,requiresProject:!0,summary:"Watch the sources and build on every change",input:watchInputSchema,background:!0,cli:{hidden:!0},agent:{hidden:!0},async handle(input,ctx){let{chokidarWatcher:chokidarWatcher2}=await Promise.resolve().then(()=>(init_watcher(),watcher_exports)),{createWatchHandler:createWatchHandler2,processSignals:processSignals2}=await Promise.resolve().then(()=>(init_intent(),intent_exports));return createWatchHandler2({createWatcher:options2.createWatcher??chokidarWatcher2,signals:options2.signals??processSignals2,cwd,...options2.timers?{timers:options2.timers}:{},...options2.onWatchSession?{onSession:options2.onWatchSession}:{}})(input,ctx)}})}})}function explicitPidPath(services){if(!services.has("variables.resolver"))return{};let value=services.get("variables.resolver").scope().pidFilePath;return value?{explicitPath:value}:{}}function runtimeContextSettings(raw2,services){if(!raw2)return;let resolver=services.get("variables.resolver"),scope=resolver.scope(),substitute3=(value,field)=>resolver.substituteStrict(value,scope,`runtimeContext.${field}`);return{gitRoot:substitute3(raw2.gitRoot,"gitRoot"),outputPath:substitute3(raw2.outputPath,"outputPath"),taskFileRoot:substitute3(raw2.taskFileRoot,"taskFileRoot"),...raw2.branchPattern===void 0?{}:{branchPattern:raw2.branchPattern}}}var buildPlugin=createBuildPlugin();import{definePlugin as definePlugin19,jsonSchema as jsonSchema25}from"@sous-io/sous-plugin-api";import path75 from"node:path";import{jsonSchema as jsonSchema24}from"@sous-io/sous-plugin-api";var TOOLS_KEY="tools",toolsKeySchema=jsonSchema24({type:"object",additionalProperties:{type:"object",properties:{command:{type:"string",description:"The command to run."},args:{type:"array",items:{type:"string"},description:"Arguments always passed, before yours."},promptFile:{type:"string",description:"A file whose content is passed as the last argument."},headless:{type:"object",properties:{command:{type:"string"},args:{type:"array",items:{type:"string"}}},additionalProperties:!1,description:"The command and arguments for a headless run; the prompt is sent on standard input."}},additionalProperties:!1},default:{}});function toolSettings(ctx,id){let value=ctx.config.get(`${TOOLS_KEY}.${id}`);return!value||typeof value!="object"?{}:withVariables(value,ctx,`${TOOLS_KEY}.${id}`)}function withVariables(settings,ctx,key){if(!ctx.services.has("variables.resolver"))return settings;let resolver=ctx.services.get("variables.resolver"),scope=resolver.scope(),strict=(text,field)=>text===void 0?void 0:resolver.substituteStrict(text,scope,`${key}.${field}`),loose=args=>args?.map(arg=>resolver.substitute(arg,scope)),out={...settings};if(assign(out,"command",strict(settings.command,"command")),assign(out,"promptFile",strict(settings.promptFile,"promptFile")),assign(out,"args",loose(settings.args)),settings.headless!==void 0){let headless={...settings.headless};assign(headless,"command",strict(settings.headless.command,"headless.command")),assign(headless,"args",loose(settings.headless.args)),out.headless=headless}return out}function assign(target,field,value){value!==void 0&&(target[field]=value)}function promptFilePath(settings,ctx){if(settings.promptFile!==void 0)return path75.resolve(ctx.project?.root??process.cwd(),settings.promptFile)}import fs57 from"node:fs";import{ConfigError as ConfigError46,SousError as SousError30}from"@sous-io/sous-plugin-api";var MAX_ARGUMENT_BYTES=128*1024;function launchArguments(settings,extra,ctx){let args=[...settings.args??[],...extra],file2=promptFilePath(settings,ctx);if(file2!==void 0){if(!fs57.existsSync(file2))throw new ConfigError46(`promptFile not found: ${file2}`);let content=fs57.readFileSync(file2,"utf8"),bytes=Buffer.byteLength(content,"utf8");if(bytes>=MAX_ARGUMENT_BYTES)throw new ConfigError46(`The prompt file is too large to pass as one argument (${kib(bytes)}, limit 128 KiB): ${file2}`,{details:["Shorten the prompt file, or have the tool read it some other way."]});args.push(content)}return args}function kib(bytes){return`${(bytes/1024).toFixed(1)} KiB`}function headlessArguments(settings){return[...settings.headless?.args??(settings.headless?.command===void 0?settings.args??[]:[])]}function toolHarness(id){return{id,description:`The tool "${id}", as written under "tools" in the config.`,async launch(args,ctx){let settings=toolSettings(ctx,id);if(settings.command===void 0)throw new ConfigError46(`tools.${id} has no "command".`,{details:[`Set tools.${id}.command in your config.`]});return ctx.services.get("host.processes").runInteractive(settings.command,launchArguments(settings,args,ctx),{...ctx.project?{cwd:ctx.project.root}:{},env:ctx.env,label:id})},async runHeadless(request,ctx){let settings=toolSettings(ctx,id),command=settings.headless?.command??settings.command;if(command===void 0)throw new ConfigError46(`tools.${id} has no "command" or "headless.command".`);let result=await ctx.services.get("host.processes").run(command,headlessArguments(settings),{...request.cwd??ctx.project?.root?{cwd:request.cwd??ctx.project?.root}:{},env:ctx.env,input:request.prompt,...request.timeoutMs===void 0?{}:{timeoutMs:request.timeoutMs},...request.signal===void 0?{}:{signal:request.signal},label:`${id} (headless)`});if(result.timedOut)throw new SousError30(`${id} did not finish within ${request.timeoutMs}ms.`);return{harness:id,exitCode:result.exitCode,output:result.stdout.trimEnd(),durationMs:result.durationMs,raw:result}}}}var TOOLS_CONTRIBUTOR="harnesses.tools";function contributeToolHarnesses(config2){let tools=config2.atPath(TOOLS_KEY).get();if(!(!tools||typeof tools!="object"||Array.isArray(tools)))for(let id of Object.keys(tools))config2.entity("harness",id)===void 0&&config2.addEntity("harness",toolHarness(id))}var toolsContributor={id:TOOLS_CONTRIBUTOR,after:["*"],contribute:contributeToolHarnesses};var package_default19={name:"@sous-io/sous-plugin-harnesses",version:"1.1.4",description:"The harness entity, launching a harness, headless runs, and the tools settings.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-build":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@sous-io/sous-plugin-variables":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME18="@sous-io/sous-plugin-harnesses",harnessSchema=jsonSchema25({type:"object",required:["id"],properties:{id:{type:"string",description:"What `sous launch <id>` names: `claude-code`, `codex`."},description:{type:"string"}}}),launchInput=jsonSchema25({type:"object",required:["tool"],properties:{tool:{type:"array",items:{type:"string"},description:"The tool, then arguments passed through to it."},noBuild:{type:"boolean",default:!1,description:"Skip sous build before launching."},continuous:{type:"boolean",default:!1,description:"Restart the tool automatically on exit."}},additionalProperties:!1}),runHeadlessInput=jsonSchema25({type:"object",required:["prompt"],properties:{harness:{type:"string",description:"The harness to run. Default: the only one that can run headless."},prompt:{type:"string",description:"The prompt."},cwd:{type:"string",description:"The directory it runs in. Default: the project root."},model:{type:"string",description:"A model, when the harness lets one be chosen."},timeoutMs:{type:"integer",description:"Stops it after this many milliseconds."},transcript:{type:"boolean",default:!1,description:"Also read the transcript."}},additionalProperties:!1}),harnessesPlugin=definePlugin19({name:PLUGIN_NAME18,version:package_default19.version,description:"The harness entity, launching a harness, headless runs, and the tools settings.",dependsOn:{"@sous-io/sous-plugin-build":`^${package_default19.version}`,"@sous-io/sous-plugin-host":`^${package_default19.version}`},register(sous){sous.entities.define("harness",harnessSchema,{description:"A program that wraps a model, used interactively, headless, or both."}),sous.entities.add("config-key",{id:TOOLS_KEY,schema:toolsKeySchema,description:"Tools you can launch with `sous launch <name>`: command, args, promptFile, headless."}),sous.config.contribute(toolsContributor),sous.intents.add({intent:"launch",needsRecipeFiles:!0,summary:"Build this project's outputs, then start a coding agent configured in its config",input:launchInput,requiresProject:!0,cli:{positional:["tool"],passThrough:!0,examples:["sous launch claude-code","sous launch codex --no-build","sous launch claude-code --continuous","sous launch claude-code -- -c"]},load:()=>Promise.resolve().then(()=>(init_launch(),launch_exports))}),sous.intents.add({intent:"harness.run-headless",needsRecipeFiles:!0,summary:"Run a coding agent with no person at the keyboard, and read its transcript",input:runHeadlessInput,cli:{command:["harness","run-headless"],hidden:!0},load:()=>Promise.resolve().then(()=>(init_run_headless(),run_headless_exports))})}});import{definePlugin as definePlugin20}from"@sous-io/sous-plugin-api";import{jsonSchema as jsonSchema26}from"@sous-io/sous-plugin-api";var yes3={type:"boolean",description:"Answer yes to every confirmation, so nothing is asked"},dryRun3={type:"boolean",description:"Show what would happen, changing nothing"},title={type:"string",description:"The proposal's title; required for a new proposal, and replaces an open one's"},body={type:"string",description:"The proposal's description; required for a new proposal, and replaces an open one's"},releaseInput=jsonSchema26({type:"object",additionalProperties:!1,properties:{directory:{type:"string",description:"The repository to release, or a directory inside it (default: the working directory)"},check:{type:"boolean",description:"Only check: validate, and fail on any problem; reports how merging rewrites the index"},ci:{type:"boolean",description:"Run the way a merge does: never bump, accept the plan, never ask, and fail on anything unbumped"},namespace:{type:"array",items:{type:"string"},description:"Release only this namespace"},recipe:{type:"array",items:{type:"string"},description:"Release only this recipe, as 'namespace/name'"},bump:{type:"string",enum:["patch","minor","major","prerelease"],description:"How far to raise a changed recipe's version. Defaults to a patch step"},noBump:{type:"boolean",description:"Raise no versions; a changed recipe that was never raised is an error"},includeUnchanged:{type:"boolean",description:"Release every recipe in scope, whether its files changed or not"},tag:{type:"boolean",description:"Cut the tags even on a branch other than the default one"},push:{type:"boolean",description:"Push the branch, and every release tag the index publishes that the remote lacks, to the remote"},yes:{...yes3,description:"Accept the plan without being asked"},dryRun:{...dryRun3,description:"Print the plan and stop, changing nothing"}}}),submitInput=jsonSchema26({type:"object",additionalProperties:!1,properties:{repo:{type:"string",description:"The linked repository to propose a change from, when run inside a project"},directory:{type:"string",description:"The directory to start from (default: the working directory)"},title,body,branch:{type:"string",description:"The branch to work with, instead of the one that is checked out"},status:{type:"boolean",description:"Only report where the branch's proposal stands"},commit:{type:"boolean",description:"Commit uncommitted changes for you, after listing them and asking once"},draft:{type:"boolean",description:"Open a new proposal as a draft"},nextBranch:{type:"string",description:"The new branch to continue on when the branch's proposal was already merged"},acceptFirst:{type:"boolean",description:"When the repository named matches several, take the first one listed"},yes:yes3,dryRun:{...dryRun3,description:"Check everything and print the plan without writing or sending anything"}}}),contributeInput=jsonSchema26({type:"object",additionalProperties:!1,required:["ref"],properties:{ref:{type:"string",description:"The repository to contribute to, or a namespace or recipe it publishes"},finish:{type:"boolean",description:"Finish the contribution: submit what no proposal carries yet, then unlink and update the pins"},branch:{type:"string",description:"The existing branch to work on when starting, or to submit from when finishing"},createBranch:{type:"string",description:"Start the contribution on a new branch with this name"},generateBranch:{type:"boolean",description:"Start the contribution on a new branch named sous/edit-<date>-<time>, which is what happens when no branch is named"},from:{type:"string",description:"Start the new branch from this branch instead of the repository's default branch"},global:{type:"boolean",description:"Work with the machine-wide link, sharing one checkout, rather than this project's link"},submit:{type:"boolean",description:"Submit what no proposal carries yet without asking, or with --no-submit, finish without submitting it"},title,body,draft:{type:"boolean",description:"Open a new proposal as a draft"},commit:{type:"boolean",description:"Commit uncommitted changes for you when submitting, after listing them and asking once"},remove:{type:"boolean",description:"Delete the checkout as well when unlinking, when sous cloned it"},yes:yes3,acceptFirst:{type:"boolean",description:"When the reference matches several things, take the first one listed"},dryRun:{...dryRun3,description:"Print each step this would run without running any of them"}}}),initInput=jsonSchema26({type:"object",additionalProperties:!1,properties:{directory:{type:"string",description:"Directory to create the repository in (defaults to the current one)"},name:{type:"string",description:"Short name for the repository (defaults to the directory's own name)"},namespace:{type:"string",description:"Name of the one namespace to declare (defaults to the repository's name)"},force:{type:"boolean",description:"Write the scaffold over a repository that already exists"},host:{type:"string",description:"The repository host whose CI workflow and files to add, such as 'github' or 'gitlab' (default: from the git remote, else 'github')"},yes:{type:"boolean",description:"Accept the default answer to every question sous init asks, which this command runs next"},moveIncludes:{type:"boolean",description:"Move the files an existing CLAUDE.md or AGENTS.md includes into .sous/includes/ (the default)"},copyIncludes:{type:"boolean",description:"Copy the files an existing CLAUDE.md or AGENTS.md includes into .sous/includes/, keeping the originals"},leaveIncludes:{type:"boolean",description:"Leave the files an existing CLAUDE.md or AGENTS.md includes where they are"},noBuild:{type:"boolean",description:"Set the repository up for sous without running its first build"},hooks:{type:"boolean",description:"Install the git hooks that build Sous's output in each new worktree (--no-hooks: do not)"},pullHooks:{type:"boolean",description:"Also install the git hooks that run after a pull and a rebase"},install:{type:"boolean",description:"Run the package manager's install after installing the git hooks (--no-install: do not)"},dryRun:{...dryRun3,description:"Print the files that would be written without writing them"}}});var package_default20={name:"@sous-io/sous-plugin-authoring",version:"1.1.4",description:"Releasing, submitting and contributing to recipe repositories, and scaffolding one.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-lib-documents":"workspace:*","@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-config-files":"workspace:*","@sous-io/sous-plugin-formats":"workspace:*","@sous-io/sous-plugin-git":"workspace:*","@sous-io/sous-plugin-init":"workspace:*","@sous-io/sous-plugin-recipes":"workspace:*","@sous-io/sous-plugin-refs":"workspace:*","@sous-io/sous-plugin-variables":"workspace:*",semver:"^7.8.5"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*","@sous-io/sous-plugin-cli":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@types/semver":"^7.8.0"},engines:{node:">=22"}};var PLUGIN_NAME19="@sous-io/sous-plugin-authoring",yesFlag2={yes:{short:"y",aliases:["force"]}},authoringPlugin=definePlugin20({name:PLUGIN_NAME19,version:package_default20.version,description:"Releasing, submitting and contributing to recipe repositories, and scaffolding one.",dependsOn:{"@sous-io/sous-plugin-recipes":`^${package_default20.version}`,"@sous-io/sous-plugin-formats":`^${package_default20.version}`,"@sous-io/sous-plugin-refs":`^${package_default20.version}`,"@sous-io/sous-plugin-variables":`^${package_default20.version}`,"@sous-io/sous-plugin-git":`^${package_default20.version}`,"@sous-io/sous-plugin-init":`^${package_default20.version}`,"@sous-io/sous-plugin-config-files":`^${package_default20.version}`},register(sous){sous.intents.add({intent:"repo.release",summary:"Publish new versions of this repository's recipes: bump, regenerate the index, commit and tag",description:"Runs inside a recipe repository. Validates it, raises the version of every changed recipe, regenerates sous.index.json, commits the manifests and the index, and tags each version. --check only reads (for a pull request); --ci runs the way a merge does.",input:releaseInput,cli:{flags:{...yesFlag2,directory:{hidden:!0}},examples:["sous repo release","sous repo release --dry-run","sous repo release --namespace workflow --bump minor","sous repo release --recipe workflow/task-files --yes --push","sous repo release --check","sous repo release --ci --push"]},agent:{usage:"Call this inside a recipe repository to publish its changed recipes. Use check: true to validate without writing.",whenNotToUse:"Not for a sous project; it releases the recipe repository it runs in."},load:async()=>(await Promise.resolve().then(()=>(init_release(),release_exports))).handleRelease}),sous.intents.add({intent:"repo.submit",summary:"Propose a recipe repository's changes to its maintainers, and follow the proposal through",description:"Validates the checkout, then pushes its branch and opens or updates a proposal through the repository host. Needs the host's command line tool (gh, glab) signed in.",input:submitInput,cli:{positional:["repo"],flags:{...yesFlag2,directory:{hidden:!0}},examples:['sous repo submit --title "Add a linting recipe" --body "Adds lint rules."',"sous repo submit sous-recipes","sous repo submit --status",'sous repo submit --commit --yes --title "Fix a typo" --body "Fixes it."',"sous repo submit --dry-run"]},agent:{usage:"Call this to propose committed changes in a recipe repository checkout. A new proposal needs title and body."},load:async()=>(await Promise.resolve().then(()=>(init_submit(),submit_exports))).handleSubmit}),sous.intents.add({intent:"repo.contribute",summary:"Start a contribution to a recipe repository on a fresh branch, or finish one with --finish",description:"Starting links the repository on a new branch (repo link --latest). Finishing submits what no proposal carries yet (repo submit), then unlinks and updates the pins (repo unlink --update).",input:contributeInput,changesConfig:!0,requiresProject:!0,cli:{aliases:[["repo","contrib"]],positional:["ref"],flags:yesFlag2,examples:["sous repo contribute sous-recipes","sous repo contribute workflow/task-files","sous repo contribute sous-recipes --create-branch fix-a-typo",'sous repo contribute sous-recipes --finish --title "Fix a typo" --body "Fixes it."',"sous repo contribute sous-recipes --finish --no-submit --remove","sous repo contribute sous-recipes --finish --dry-run"]},agent:{usage:"Call this to start editing a recipe repository from a project, and again with finish: true to propose and unlink."},load:async()=>(await Promise.resolve().then(()=>(init_contribute(),contribute_exports))).handleContribute}),sous.intents.add({intent:"repo.init",summary:"Create a new sous recipe repository in a directory, then set it up for sous",input:initInput,cli:{positional:["directory"],examples:["sous repo init","sous repo init ./my-recipes","sous repo init ./my-recipes --name team-recipes --namespace workflow","sous repo init ./my-recipes --host github","sous repo init ./my-recipes --leave-includes --no-build","sous repo init ./my-recipes --dry-run"],flags:{yes:{short:"y"}}},agent:{usage:"Call this to scaffold a new recipe repository."},load:async()=>(await Promise.resolve().then(()=>(init_scaffold(),scaffold_exports))).handleInit})}});import{definePlugin as definePlugin22,jsonSchema as jsonSchema28}from"@sous-io/sous-plugin-api";init_src7();init_hooks();import fs65 from"node:fs";import path88 from"node:path";function hooksWithBlock(folder){return[...DEFAULT_HOOKS,...PULL_HOOKS].filter(hook=>{try{return fs65.readFileSync(path88.join(folder,hook),"utf8").includes(HOOK_BLOCK_START)}catch{return!1}})}function real(directory){try{return fs65.realpathSync(directory)}catch{return path88.resolve(directory)}}async function gitHooksFolder(ctx,root){if(!ctx.services.has("git.runner"))return;let result=await ctx.services.get("git.runner").run(["rev-parse","--git-path","hooks"],{cwd:root,reject:!1});return result.exitCode===0&&result.stdout.trim()!==""?path88.resolve(root,result.stdout.trim()):void 0}async function checkGitHooks(ctx){let root=ctx.project?.root;if(root===void 0)return{status:"skipped",summary:"There is no project here."};let husky=hooksWithBlock(path88.join(root,HUSKY_DIR)),folder=await gitHooksFolder(ctx,root);if(folder===void 0)return husky.length===0?{status:"ok",summary:"The project is not in a git repository, so it has no git hooks."}:{status:"skipped",summary:"Git cannot read this project's repository, so the hooks could not be checked."};if(husky.length>0){let huskyFolder=path88.join(root,HUSKY_DIR,"_");return real(folder)===real(huskyFolder)&&fs65.existsSync(huskyFolder)?{status:"ok",summary:`The git hooks run through Husky: ${husky.join(", ")}.`}:{status:"problem",summary:`The project was set up with git hooks (${husky.join(", ")} in ${HUSKY_DIR}/), but they are not turned on in this clone.`,details:[`Git runs the hooks in ${folder}; Husky's are in ${huskyFolder}, which its command sets up during the package manager's install.`],fix:"Install the git hooks and run the package manager's install",hint:"Run 'sous init hooks --install'."}}let own=hooksWithBlock(folder);return own.length>0?{status:"ok",summary:`The git hooks are installed: ${own.join(", ")}.`}:{status:"ok",summary:"No git hooks from 'sous init hooks' were found. A project without a package.json keeps them outside git, so a new clone cannot tell; 'sous init hooks' installs them."}}var gitHooksCheck={id:"git-hooks",order:DOCTOR_CHECK_ORDER.gitHooks,description:"The git hooks are installed, when the project was set up with them",check:ctx=>checkGitHooks(ctx),async fix(ctx){let root=ctx.project.root,pullHooks=hooksWithBlock(path88.join(root,HUSKY_DIR)).some(hook=>PULL_HOOKS.includes(hook)),result=(await ctx.run("init.hooks",{directory:root,install:!0,pullHooks})).toPlain();return result.installed?{summary:result.install?.outcome==="ran"?`The git hooks are installed, and '${result.install.command}' ran.`:"The git hooks are written.",details:result.files.map(file2=>`${file2.file}: ${file2.change}`)}:{summary:`The git hooks were not installed: ${result.reason}`,details:[...result.manual]}}};var package_default21={name:"@sous-io/sous-plugin-init",version:"1.1.4",description:"Scaffolding a project's .sous/ (sous init).",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-doctor":"workspace:*","@sous-io/sous-plugin-build":"workspace:*","@sous-io/sous-plugin-config-files":"workspace:*","@sous-io/sous-plugin-git":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@sous-io/sous-plugin-update":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};init_templates2();init_import();init_hooks();init_package_json();init_scaffold2();var PLUGIN_NAME21="@sous-io/sous-plugin-init",initInput2=jsonSchema28({type:"object",properties:{directory:{type:"string",description:"Project directory to set up (defaults to the current one)."},name:{type:"string",description:"Display name for the project (defaults to the directory's own name)."},yes:{type:"boolean",default:!1,description:"Accept the default answer to every question init asks: set the project up even inside another one, move the included files, and install the git hooks (without the pull hooks), running the install."},moveIncludes:{type:"boolean",default:!1,description:"Move the files the existing CLAUDE.md or AGENTS.md include into .sous/includes/ (the default)."},copyIncludes:{type:"boolean",default:!1,description:"Copy the files the existing CLAUDE.md or AGENTS.md include into .sous/includes/, keeping the originals."},leaveIncludes:{type:"boolean",default:!1,description:"Leave the files the existing CLAUDE.md or AGENTS.md include where they are."},dryRun:{type:"boolean",default:!1,description:"Show the files that would be written without writing them."},noBuild:{type:"boolean",default:!1,description:"Write the setup without running the first build."},hooks:{type:"boolean",description:"Install the git hooks that build Sous's output in each new worktree (--no-hooks: do not)."},pullHooks:{type:"boolean",description:"Also install the git hooks that run after a pull and a rebase."},install:{type:"boolean",description:"Run the package manager's install after installing the git hooks (--no-install: do not)."}},additionalProperties:!1}),initHooksInput=jsonSchema28({type:"object",properties:{directory:{type:"string",description:"Project directory, holding .sous/ (defaults to the project sous finds)."},pullHooks:{type:"boolean",description:"Also install the hooks that run after a pull and a rebase (--no-pull-hooks: do not)."},install:{type:"boolean",description:"Run the package manager's install at the end (--no-install: do not)."},yes:{type:"boolean",default:!1,description:"Accept the default answer to every question: no pull hooks, and run the install."},dryRun:{type:"boolean",default:!1,description:"Show the files that would be written without writing them."}},additionalProperties:!1}),initPlugin=definePlugin22({name:PLUGIN_NAME21,version:package_default21.version,description:"Scaffolding a project's .sous/ (sous init).",dependsOn:{"@sous-io/sous-plugin-build":`^${package_default21.version}`,"@sous-io/sous-plugin-config-files":`^${package_default21.version}`,"@sous-io/sous-plugin-host":`^${package_default21.version}`,"@sous-io/sous-plugin-update":`^${package_default21.version}`,"@sous-io/sous-plugin-doctor":`^${package_default21.version}`},register(sous){sous.entities.add("doctor-check",gitHooksCheck),sous.intents.add({intent:"init",summary:"Set a project up for sous: import its agent files into a new .sous/ directory, install the git hooks, then run the first build",input:initInput2,changesConfig:!0,cli:{positional:["directory"],examples:["sous init","sous init ./my-project","sous init --name 'My Project' --no-build","sous init --leave-includes","sous init --dry-run"],flags:{yes:{short:"y",aliases:["force"]}}},agent:{usage:"Set up a new project. Pass yes so no question is asked (or moveIncludes, copyIncludes or leaveIncludes to choose what happens to the files the existing instructions include, and hooks, pullHooks and install for the git hooks), and dryRun first to see the files."},load:()=>Promise.resolve().then(()=>(init_init(),init_exports))}),sous.intents.add({intent:"init.hooks",summary:"Install the git hooks that build Sous's output in each new worktree and checked-out branch",input:initHooksInput,cli:{command:["init","hooks"],positional:["directory"],examples:["sous init hooks","sous init hooks --pull-hooks","sous init hooks --yes","sous init hooks --no-install","sous init hooks --dry-run"],flags:{yes:{short:"y",aliases:["force"]}}},agent:{usage:"Install the git hooks once, in a project whose .sous/ is at the top of its git repository. Pass yes (or install and pullHooks) so no question is asked, and dryRun first to see the files."},load:()=>Promise.resolve().then(()=>(init_init_hooks(),init_hooks_exports))})}});init_src9();init_src7();init_src7();import{definePlugin as definePlugin23,jsonSchema as jsonSchema29}from"@sous-io/sous-plugin-api";var QUIET_INTENTS=new Set(["doctor","migrations.run","upgrade","help","version","completion","completion.words","mcp.serve"]);function noticeText(count2){return`${count2===1?"A migration":`${count2} migrations`} from a newer version of sous ${count2===1?"is":"are"} waiting to run in this project. Run 'sous doctor' to run ${count2===1?"it":"them"}.`}function pendingNotice(){let spoken=new Set;return(event,ctx)=>{let chain=ctx.chain;if(chain===void 0||chain.intent!==event.intent||spoken.has(chain.id)||QUIET_INTENTS.has(event.intent)||(spoken.add(chain.id),ctx.project===void 0||!ctx.services.has("migrations")))return;let count2=0;try{count2=ctx.services.get("migrations").pending().length}catch{return}count2>0&&ctx.reporter.notice(noticeText(count2))}}init_pending2();init_run2();init_pending2();function lockOf(ctx){return ctx.project!==void 0&&ctx.services.has("recipes.lock")?ctx.services.get("recipes.lock"):void 0}function createMigrationsService(ctx,running){let all=()=>orderMigrations(ctx.entities.list("migration"));return{all,migratedVersion(){return lockOf(ctx)?.migratedVersion()},pending(){let lock=lockOf(ctx);if(lock===void 0||!lock.exists())return[];let stored=lock.migratedVersion();return pendingMigrations(all(),stored!==void 0&&isVersion(stored)?stored:void 0)},async markCurrent(){let lock=lockOf(ctx);lock!==void 0&&isVersion(running)&&await lock.setMigratedVersion(running)}}}var package_default23={name:"@sous-io/sous-plugin-migrations",version:"1.1.4",description:"Migrations: the steps that bring a project's files in line with a newer version of sous, and the notice that some are waiting.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-doctor":"workspace:*",semver:"^7.8.5"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*","@sous-io/sous-plugin-formats":"workspace:*","@sous-io/sous-plugin-recipes":"workspace:*","@types/semver":"^7.8.0"},engines:{node:">=22"}};init_pending2();var PLUGIN_NAME22="@sous-io/sous-plugin-migrations",migrationSchema=jsonSchema29({type:"object",required:["id","version","order","description","plugin"],properties:{id:{type:"string"},version:{type:"string",description:"The version of sous this migration belongs to."},order:{type:"number",description:"Among migrations of one version, a higher number runs later."},description:{type:"string"},plugin:{type:"string"}}}),runInput=jsonSchema29({type:"object",properties:{yes:{type:"boolean",default:!1,description:"Take every question's default instead of asking."},answer:{type:"array",items:{type:"string"},description:"Answer a migration's question ahead of time, as <name>=<value>."},dryRun:{type:"boolean",default:!1,description:"List the pending migrations and their answers, and change nothing."}},additionalProperties:!1});function toEntity(migration,plugin,index){if(typeof migration.version!="string"||!isVersion(migration.version))throw new Error(`${plugin} added a migration whose version "${String(migration.version)}" is not a version such as 1.2.0.`);if(typeof migration.up!="function")throw new Error(`${plugin} added the migration for sous ${migration.version} without an up function.`);let id=migration.id??`${plugin}@${migration.version}#${index}`;return{id,version:migration.version,order:migration.order??DEFAULT_ORDER2,description:migration.description??`The migration ${id}`,plugin,up:migration.up,...migration.questions===void 0?{}:{questions:migration.questions}}}var migrationsCheck={id:"migrations",order:DOCTOR_CHECK_ORDER.migrations,description:"Every migration for this version of sous has run",confirm:!1,check(ctx,run){let pending;try{pending=ctx.services.get("migrations").pending()}catch(error51){if(run.configFailed)return{status:"skipped",summary:"Skipped: the config did not load."};throw error51}if(pending.length===0)return{status:"ok"};let given=new Set(answersForMigrations(ctx,run.answers).map(entry=>entry.slice(0,entry.indexOf("=")).trim())),unanswered=migration=>(migration.questions??[]).filter(question=>question.answered?.(ctx,{})===void 0&&!given.has(question.id)),waiting=run.yes||ctx.prompter.interactive?0:pending.reduce((count2,migration)=>count2+unanswered(migration).length,0);return waiting>0?{status:"pending",summary:`${pending.length===1?"1 migration is":`${pending.length} migrations are`} waiting to run, because sous could not ask ${waiting===1?"the question":`the ${waiting} questions`} below without a terminal.`,details:pending.map(migration=>{let questions=unanswered(migration),name=`${migration.description} [sous ${migration.version}]`;return questions.length===0?`${name}: it asks nothing, and waits because migrations run in order and none runs until every question is answered.`:{text:`${name} asks:`,details:questions.map(question=>`${question.message} Answer it with --answer ${question.id}=<${valuesOf(question).join("|")}> (--yes takes ${question.default}).`)}}),waiting:{count:pending.length,label:pending.length===1?"1 migration":`${pending.length} migrations`}}:{status:"problem",summary:`${pending.length===1?"1 migration is":`${pending.length} migrations are`} waiting to run.`,details:pending.map(migration=>`${migration.description} [sous ${migration.version}]`),fix:"Run the pending migrations"}},async fix(ctx,run){let result=(await ctx.run("migrations.run",{...run.yes?{yes:!0}:{},...run.answers.length===0?{}:{answer:answersForMigrations(ctx,run.answers)}})).toPlain();return result.unanswered.length>0?{summary:`No migration ran: sous could not ask ${result.unanswered.length===1?"this question":"these questions"} without a terminal, and none runs until every question is answered.`,details:result.unanswered.map(question=>`${question.message} Answer it with --answer ${question.question}=<${question.values.join("|")}> (--yes takes ${question.default}).`)}:{summary:`${result.migrations.length===1?"1 migration ran":`${result.migrations.length} migrations ran`}; the project is recorded as migrated to sous ${result.to}.`,details:result.migrations.map(report=>`${report.description}${report.outcome?.summary===void 0?"":`: ${report.outcome.summary}`}`)}}};function answersForMigrations(ctx,answers){let ids=new Set(ctx.services.get("migrations").all().flatMap(migration=>(migration.questions??[]).map(question=>question.id)));return answers.filter(entry=>ids.has(entry.slice(0,Math.max(0,entry.indexOf("="))).trim()))}var migrationsPlugin=definePlugin23({name:PLUGIN_NAME22,version:package_default23.version,description:"Sous's own migrations, the version a project last migrated to, and the notice that some are waiting.",dependsOn:{"@sous-io/sous-plugin-doctor":`^${package_default23.version}`},register(sous){sous.entities.define("migration",migrationSchema,{description:"A step that brings a project's files in line with a newer version of sous."});let counts=new Map;sous.extensions.add("migrations",other=>({add(migration){let index=(counts.get(other.plugin.name)??0)+1;counts.set(other.plugin.name,index),other.entities.add("migration",toEntity(migration,other.plugin.name,index))}})),sous.services.add("migrations",(_config,ctx)=>createMigrationsService(ctx,sous.engine.app.version),{lifetime:"config"}),sous.entities.add("doctor-check",migrationsCheck),sous.intents.add({intent:"migrations.run",summary:"Run the migrations from newer versions of sous that this project has not run",input:runInput,requiresProject:!0,toleratesConfigErrors:!0,cli:{command:["migrations","run"],hidden:!0,flags:{yes:{short:"y",aliases:["force"]}}},load:()=>Promise.resolve().then(()=>(init_run2(),run_exports))}),sous.on("*.before",pendingNotice()),sous.on("recipes.locked",async(event,ctx)=>{if(event.payload.created===!0&&ctx.services.has("recipes.lock")){let lock=ctx.services.get("recipes.lock");lock.migratedVersion()===void 0&&isVersion(ctx.engine.app.version)&&await lock.setMigratedVersion(ctx.engine.app.version)}})}});import{definePlugin as definePlugin24}from"@sous-io/sous-plugin-api";init_src();import nodePath2 from"node:path";import{IntentOutputs as IntentOutputs27,NotFoundError as NotFoundError11,SousError as SousError34}from"@sous-io/sous-plugin-api";import{ConfigError as ConfigError66,DataValue as DataValue2,IntentOutput as IntentOutput22,ReportEntryStyle as ReportEntryStyle17,Table as Table5,TextBlock as TextBlock13,Tree as Tree3,VariableSet as VariableSet12}from"@sous-io/sous-plugin-api";function prettyJson(value){return JSON.stringify(value,null,2)??"undefined"}function isScalar3(value){return value===null||typeof value=="string"||typeof value=="number"||typeof value=="boolean"}function plural2(count2,singular,pluralForm=`${singular}s`){return`${count2} ${count2===1?singular:pluralForm}`}function missingValue(path122){return new ConfigError66(`No value at config path '${path122}'.`,{details:["It is not present in the built config.","Run 'sous config show' to see the whole config."]})}function missingInLayers(path122){return new ConfigError66(`No value at config path '${path122}' in any config layer.`,{details:["Run 'sous config show' to see the whole config."]})}function rawFileOutputs(files){return files.map(file2=>new IntentOutput22({result:new TextBlock13(`# ${file2.path} (${file2.contributor})
1178
+ `}init_schemas4();var package_default18={name:"@sous-io/sous-plugin-build",version:"1.1.6",description:"The build, compile, prune and clear intents, preparing for a build, watch mode, the PID file, the runtime context file.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-compiler":"workspace:*","@sous-io/sous-plugin-git":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@sous-io/sous-plugin-memories":"workspace:*","@sous-io/sous-plugin-recipe-answers":"workspace:*","@sous-io/sous-plugin-recipes":"workspace:*","@sous-io/sous-plugin-variables":"workspace:*","@sous-io/sous-plugin-editor":"workspace:*","@sous-io/sous-plugin-handlers":"workspace:*",chokidar:"^5.0.0",semver:"^7.8.5"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*","@types/semver":"^7.8.0"},engines:{node:">=22"}};init_report();var PLUGIN_NAME17="@sous-io/sous-plugin-build",PLUGIN_VERSION=package_default18.version;function createBuildPlugin(options2={}){let cwd=options2.cwd;return definePlugin18({name:PLUGIN_NAME17,version:PLUGIN_VERSION,description:"The build, compile, prune and clear intents, preparing for a build, watch mode, the PID file, the runtime context file.",dependsOn:{"@sous-io/sous-plugin-compiler":`^${package_default18.version}`,"@sous-io/sous-plugin-recipes":`^${package_default18.version}`,"@sous-io/sous-plugin-recipe-answers":`^${package_default18.version}`,"@sous-io/sous-plugin-git":`^${package_default18.version}`,"@sous-io/sous-plugin-host":`^${package_default18.version}`,"@sous-io/sous-plugin-variables":`^${package_default18.version}`},register(sous){sous.entities.add("config-key",{id:"watch",schema:watchSettingsSchema,description:"Watch mode: more paths that trigger a full rebuild, the debounce, and how often to check upstream."}),sous.entities.add("config-key",{id:"runtimeContext",schema:runtimeContextSchema,description:"The runtime context file a target with generateRuntimeContext includes: git branch and task file."}),sous.services.add("build.pid",(_config,ctx)=>new PidFile({...explicitPidPath(ctx.services),project:ctx.project,cwd:cwd?.()??ctx.cwd??".",isAlive:options2.isProcessAlive??isProcessAlive}),{lifetime:"singleton"}),sous.services.add("build.runtime-context",(config2,ctx)=>new RuntimeContextService({settings:runtimeContextSettings(config2.get("runtimeContext"),ctx.services),git:()=>ctx.services.get("git.runner"),writer:()=>ctx.services.get("compiler.writer"),plugin:PLUGIN_NAME17}),{lifetime:"config"}),sous.intents.add({intent:"build",needsRecipeFiles:!0,requiresProject:!0,summary:"Compile this project's outputs and remove the ones its config no longer produces",input:buildInputSchema,cli:{examples:["sous build","sous build --no-prune","sous build --rebuild","sous build --dry-run","sous build --keep-going"],flags:{watch:{short:"w"},changedFiles:{hidden:!0},reportRemoved:{hidden:!0}}},agent:{usage:"Run after changing the config, a subscription or a template, to write every output again.",whenNotToUse:"Not with watch: an agent cannot stop a watcher; build again instead."},load:async()=>(await Promise.resolve().then(()=>(init_build(),build_exports))).build}),sous.intents.add({intent:"compile",needsRecipeFiles:!0,requiresProject:!0,summary:"Compile markdown templates into output files",description:"Compiles every target in the config without preparing recipes or pruning.",input:compileInputSchema,cli:{examples:["sous compile","sous compile --rebuild","sous compile --dry-run","sous compile --strict"],flags:{watch:{short:"w"},changedFiles:{hidden:!0}}},load:async()=>(await Promise.resolve().then(()=>(init_build(),build_exports))).compile}),sous.intents.add({intent:"build.prepare",needsRecipeFiles:!0,requiresProject:!0,summary:"Seed core, lock new subscriptions, restore the store and check upstream",input:prepareInputSchema,internal:!0,load:async()=>(await Promise.resolve().then(()=>(init_prepare(),prepare_exports))).prepare}),sous.intents.add({intent:"prune",needsRecipeFiles:!0,requiresProject:!0,summary:"Remove output files that are no longer in the current config",input:pruneInputSchema,cli:{examples:["sous prune","sous prune --dry-run"]},load:async()=>(await Promise.resolve().then(()=>(init_build(),build_exports))).prune}),sous.intents.add({intent:"clear",needsRecipeFiles:!0,requiresProject:!0,summary:"Delete all files and directories written by Sous for a project",input:clearInputSchema,cli:{examples:["sous clear","sous clear --force","sous clear --yes"],flags:{force:{short:"f",aliases:["yes"]}}},agent:{usage:"Pass force: true; an agent cannot answer the confirmation."},load:async()=>(await Promise.resolve().then(()=>(init_build(),build_exports))).clear}),sous.intents.add({intent:"build.watch",needsRecipeFiles:!0,requiresProject:!0,summary:"Watch the sources and build on every change",input:watchInputSchema,background:!0,cli:{hidden:!0},agent:{hidden:!0},async handle(input,ctx){let{chokidarWatcher:chokidarWatcher2}=await Promise.resolve().then(()=>(init_watcher(),watcher_exports)),{createWatchHandler:createWatchHandler2,processSignals:processSignals2}=await Promise.resolve().then(()=>(init_intent(),intent_exports));return createWatchHandler2({createWatcher:options2.createWatcher??chokidarWatcher2,signals:options2.signals??processSignals2,cwd,...options2.timers?{timers:options2.timers}:{},...options2.onWatchSession?{onSession:options2.onWatchSession}:{}})(input,ctx)}})}})}function explicitPidPath(services){if(!services.has("variables.resolver"))return{};let value=services.get("variables.resolver").scope().pidFilePath;return value?{explicitPath:value}:{}}function runtimeContextSettings(raw2,services){if(!raw2)return;let resolver=services.get("variables.resolver"),scope=resolver.scope(),substitute3=(value,field)=>resolver.substituteStrict(value,scope,`runtimeContext.${field}`);return{gitRoot:substitute3(raw2.gitRoot,"gitRoot"),outputPath:substitute3(raw2.outputPath,"outputPath"),taskFileRoot:substitute3(raw2.taskFileRoot,"taskFileRoot"),...raw2.branchPattern===void 0?{}:{branchPattern:raw2.branchPattern}}}var buildPlugin=createBuildPlugin();import{definePlugin as definePlugin19,jsonSchema as jsonSchema25}from"@sous-io/sous-plugin-api";import path75 from"node:path";import{jsonSchema as jsonSchema24}from"@sous-io/sous-plugin-api";var TOOLS_KEY="tools",toolsKeySchema=jsonSchema24({type:"object",additionalProperties:{type:"object",properties:{command:{type:"string",description:"The command to run."},args:{type:"array",items:{type:"string"},description:"Arguments always passed, before yours."},promptFile:{type:"string",description:"A file whose content is passed as the last argument."},headless:{type:"object",properties:{command:{type:"string"},args:{type:"array",items:{type:"string"}}},additionalProperties:!1,description:"The command and arguments for a headless run; the prompt is sent on standard input."}},additionalProperties:!1},default:{}});function toolSettings(ctx,id){let value=ctx.config.get(`${TOOLS_KEY}.${id}`);return!value||typeof value!="object"?{}:withVariables(value,ctx,`${TOOLS_KEY}.${id}`)}function withVariables(settings,ctx,key){if(!ctx.services.has("variables.resolver"))return settings;let resolver=ctx.services.get("variables.resolver"),scope=resolver.scope(),strict=(text,field)=>text===void 0?void 0:resolver.substituteStrict(text,scope,`${key}.${field}`),loose=args=>args?.map(arg=>resolver.substitute(arg,scope)),out={...settings};if(assign(out,"command",strict(settings.command,"command")),assign(out,"promptFile",strict(settings.promptFile,"promptFile")),assign(out,"args",loose(settings.args)),settings.headless!==void 0){let headless={...settings.headless};assign(headless,"command",strict(settings.headless.command,"headless.command")),assign(headless,"args",loose(settings.headless.args)),out.headless=headless}return out}function assign(target,field,value){value!==void 0&&(target[field]=value)}function promptFilePath(settings,ctx){if(settings.promptFile!==void 0)return path75.resolve(ctx.project?.root??process.cwd(),settings.promptFile)}import fs57 from"node:fs";import{ConfigError as ConfigError46,SousError as SousError30}from"@sous-io/sous-plugin-api";var MAX_ARGUMENT_BYTES=128*1024;function launchArguments(settings,extra,ctx){let args=[...settings.args??[],...extra],file2=promptFilePath(settings,ctx);if(file2!==void 0){if(!fs57.existsSync(file2))throw new ConfigError46(`promptFile not found: ${file2}`);let content=fs57.readFileSync(file2,"utf8"),bytes=Buffer.byteLength(content,"utf8");if(bytes>=MAX_ARGUMENT_BYTES)throw new ConfigError46(`The prompt file is too large to pass as one argument (${kib(bytes)}, limit 128 KiB): ${file2}`,{details:["Shorten the prompt file, or have the tool read it some other way."]});args.push(content)}return args}function kib(bytes){return`${(bytes/1024).toFixed(1)} KiB`}function headlessArguments(settings){return[...settings.headless?.args??(settings.headless?.command===void 0?settings.args??[]:[])]}function toolHarness(id){return{id,description:`The tool "${id}", as written under "tools" in the config.`,async launch(args,ctx){let settings=toolSettings(ctx,id);if(settings.command===void 0)throw new ConfigError46(`tools.${id} has no "command".`,{details:[`Set tools.${id}.command in your config.`]});return ctx.services.get("host.processes").runInteractive(settings.command,launchArguments(settings,args,ctx),{...ctx.project?{cwd:ctx.project.root}:{},env:ctx.env,label:id})},async runHeadless(request,ctx){let settings=toolSettings(ctx,id),command=settings.headless?.command??settings.command;if(command===void 0)throw new ConfigError46(`tools.${id} has no "command" or "headless.command".`);let result=await ctx.services.get("host.processes").run(command,headlessArguments(settings),{...request.cwd??ctx.project?.root?{cwd:request.cwd??ctx.project?.root}:{},env:ctx.env,input:request.prompt,...request.timeoutMs===void 0?{}:{timeoutMs:request.timeoutMs},...request.signal===void 0?{}:{signal:request.signal},label:`${id} (headless)`});if(result.timedOut)throw new SousError30(`${id} did not finish within ${request.timeoutMs}ms.`);return{harness:id,exitCode:result.exitCode,output:result.stdout.trimEnd(),durationMs:result.durationMs,raw:result}}}}var TOOLS_CONTRIBUTOR="harnesses.tools";function contributeToolHarnesses(config2){let tools=config2.atPath(TOOLS_KEY).get();if(!(!tools||typeof tools!="object"||Array.isArray(tools)))for(let id of Object.keys(tools))config2.entity("harness",id)===void 0&&config2.addEntity("harness",toolHarness(id))}var toolsContributor={id:TOOLS_CONTRIBUTOR,after:["*"],contribute:contributeToolHarnesses};var package_default19={name:"@sous-io/sous-plugin-harnesses",version:"1.1.6",description:"The harness entity, launching a harness, headless runs, and the tools settings.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-build":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@sous-io/sous-plugin-variables":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME18="@sous-io/sous-plugin-harnesses",harnessSchema=jsonSchema25({type:"object",required:["id"],properties:{id:{type:"string",description:"What `sous launch <id>` names: `claude-code`, `codex`."},description:{type:"string"}}}),launchInput=jsonSchema25({type:"object",required:["tool"],properties:{tool:{type:"array",items:{type:"string"},description:"The tool, then arguments passed through to it."},noBuild:{type:"boolean",default:!1,description:"Skip sous build before launching."},continuous:{type:"boolean",default:!1,description:"Restart the tool automatically on exit."}},additionalProperties:!1}),runHeadlessInput=jsonSchema25({type:"object",required:["prompt"],properties:{harness:{type:"string",description:"The harness to run. Default: the only one that can run headless."},prompt:{type:"string",description:"The prompt."},cwd:{type:"string",description:"The directory it runs in. Default: the project root."},model:{type:"string",description:"A model, when the harness lets one be chosen."},timeoutMs:{type:"integer",description:"Stops it after this many milliseconds."},transcript:{type:"boolean",default:!1,description:"Also read the transcript."}},additionalProperties:!1}),harnessesPlugin=definePlugin19({name:PLUGIN_NAME18,version:package_default19.version,description:"The harness entity, launching a harness, headless runs, and the tools settings.",dependsOn:{"@sous-io/sous-plugin-build":`^${package_default19.version}`,"@sous-io/sous-plugin-host":`^${package_default19.version}`},register(sous){sous.entities.define("harness",harnessSchema,{description:"A program that wraps a model, used interactively, headless, or both."}),sous.entities.add("config-key",{id:TOOLS_KEY,schema:toolsKeySchema,description:"Tools you can launch with `sous launch <name>`: command, args, promptFile, headless."}),sous.config.contribute(toolsContributor),sous.intents.add({intent:"launch",needsRecipeFiles:!0,summary:"Build this project's outputs, then start a coding agent configured in its config",input:launchInput,requiresProject:!0,cli:{positional:["tool"],passThrough:!0,examples:["sous launch claude-code","sous launch codex --no-build","sous launch claude-code --continuous","sous launch claude-code -- -c"]},load:()=>Promise.resolve().then(()=>(init_launch(),launch_exports))}),sous.intents.add({intent:"harness.run-headless",needsRecipeFiles:!0,summary:"Run a coding agent with no person at the keyboard, and read its transcript",input:runHeadlessInput,cli:{command:["harness","run-headless"],hidden:!0},load:()=>Promise.resolve().then(()=>(init_run_headless(),run_headless_exports))})}});import{definePlugin as definePlugin20}from"@sous-io/sous-plugin-api";import{jsonSchema as jsonSchema26}from"@sous-io/sous-plugin-api";var yes3={type:"boolean",description:"Answer yes to every confirmation, so nothing is asked"},dryRun3={type:"boolean",description:"Show what would happen, changing nothing"},title={type:"string",description:"The proposal's title; required for a new proposal, and replaces an open one's"},body={type:"string",description:"The proposal's description; required for a new proposal, and replaces an open one's"},releaseInput=jsonSchema26({type:"object",additionalProperties:!1,properties:{directory:{type:"string",description:"The repository to release, or a directory inside it (default: the working directory)"},check:{type:"boolean",description:"Only check: validate, and fail on any problem; reports how merging rewrites the index"},ci:{type:"boolean",description:"Run the way a merge does: never bump, accept the plan, never ask, and fail on anything unbumped"},namespace:{type:"array",items:{type:"string"},description:"Release only this namespace"},recipe:{type:"array",items:{type:"string"},description:"Release only this recipe, as 'namespace/name'"},bump:{type:"string",enum:["patch","minor","major","prerelease"],description:"How far to raise a changed recipe's version. Defaults to a patch step"},noBump:{type:"boolean",description:"Raise no versions; a changed recipe that was never raised is an error"},includeUnchanged:{type:"boolean",description:"Release every recipe in scope, whether its files changed or not"},tag:{type:"boolean",description:"Cut the tags even on a branch other than the default one"},push:{type:"boolean",description:"Push the branch, and every release tag the index publishes that the remote lacks, to the remote"},yes:{...yes3,description:"Accept the plan without being asked"},dryRun:{...dryRun3,description:"Print the plan and stop, changing nothing"}}}),submitInput=jsonSchema26({type:"object",additionalProperties:!1,properties:{repo:{type:"string",description:"The linked repository to propose a change from, when run inside a project"},directory:{type:"string",description:"The directory to start from (default: the working directory)"},title,body,branch:{type:"string",description:"The branch to work with, instead of the one that is checked out"},status:{type:"boolean",description:"Only report where the branch's proposal stands"},commit:{type:"boolean",description:"Commit uncommitted changes for you, after listing them and asking once"},draft:{type:"boolean",description:"Open a new proposal as a draft"},nextBranch:{type:"string",description:"The new branch to continue on when the branch's proposal was already merged"},acceptFirst:{type:"boolean",description:"When the repository named matches several, take the first one listed"},yes:yes3,dryRun:{...dryRun3,description:"Check everything and print the plan without writing or sending anything"}}}),contributeInput=jsonSchema26({type:"object",additionalProperties:!1,required:["ref"],properties:{ref:{type:"string",description:"The repository to contribute to, or a namespace or recipe it publishes"},finish:{type:"boolean",description:"Finish the contribution: submit what no proposal carries yet, then unlink and update the pins"},branch:{type:"string",description:"The existing branch to work on when starting, or to submit from when finishing"},createBranch:{type:"string",description:"Start the contribution on a new branch with this name"},generateBranch:{type:"boolean",description:"Start the contribution on a new branch named sous/edit-<date>-<time>, which is what happens when no branch is named"},from:{type:"string",description:"Start the new branch from this branch instead of the repository's default branch"},global:{type:"boolean",description:"Work with the machine-wide link, sharing one checkout, rather than this project's link"},submit:{type:"boolean",description:"Submit what no proposal carries yet without asking, or with --no-submit, finish without submitting it"},title,body,draft:{type:"boolean",description:"Open a new proposal as a draft"},commit:{type:"boolean",description:"Commit uncommitted changes for you when submitting, after listing them and asking once"},remove:{type:"boolean",description:"Delete the checkout as well when unlinking, when sous cloned it"},yes:yes3,acceptFirst:{type:"boolean",description:"When the reference matches several things, take the first one listed"},dryRun:{...dryRun3,description:"Print each step this would run without running any of them"}}}),initInput=jsonSchema26({type:"object",additionalProperties:!1,properties:{directory:{type:"string",description:"Directory to create the repository in (defaults to the current one)"},name:{type:"string",description:"Short name for the repository (defaults to the directory's own name)"},namespace:{type:"string",description:"Name of the one namespace to declare (defaults to the repository's name)"},force:{type:"boolean",description:"Write the scaffold over a repository that already exists"},host:{type:"string",description:"The repository host whose CI workflow and files to add, such as 'github' or 'gitlab' (default: from the git remote, else 'github')"},yes:{type:"boolean",description:"Accept the default answer to every question sous init asks, which this command runs next"},moveIncludes:{type:"boolean",description:"Move the files an existing CLAUDE.md or AGENTS.md includes into .sous/includes/ (the default)"},copyIncludes:{type:"boolean",description:"Copy the files an existing CLAUDE.md or AGENTS.md includes into .sous/includes/, keeping the originals"},leaveIncludes:{type:"boolean",description:"Leave the files an existing CLAUDE.md or AGENTS.md includes where they are"},noBuild:{type:"boolean",description:"Set the repository up for sous without running its first build"},hooks:{type:"boolean",description:"Install the git hooks that build Sous's output in each new worktree (--no-hooks: do not)"},pullHooks:{type:"boolean",description:"Also install the git hooks that run after a pull and a rebase"},install:{type:"boolean",description:"Run the package manager's install after installing the git hooks (--no-install: do not)"},dryRun:{...dryRun3,description:"Print the files that would be written without writing them"}}});var package_default20={name:"@sous-io/sous-plugin-authoring",version:"1.1.6",description:"Releasing, submitting and contributing to recipe repositories, and scaffolding one.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-lib-documents":"workspace:*","@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-config-files":"workspace:*","@sous-io/sous-plugin-formats":"workspace:*","@sous-io/sous-plugin-git":"workspace:*","@sous-io/sous-plugin-init":"workspace:*","@sous-io/sous-plugin-recipes":"workspace:*","@sous-io/sous-plugin-refs":"workspace:*","@sous-io/sous-plugin-variables":"workspace:*",semver:"^7.8.5"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*","@sous-io/sous-plugin-cli":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@types/semver":"^7.8.0"},engines:{node:">=22"}};var PLUGIN_NAME19="@sous-io/sous-plugin-authoring",yesFlag2={yes:{short:"y",aliases:["force"]}},authoringPlugin=definePlugin20({name:PLUGIN_NAME19,version:package_default20.version,description:"Releasing, submitting and contributing to recipe repositories, and scaffolding one.",dependsOn:{"@sous-io/sous-plugin-recipes":`^${package_default20.version}`,"@sous-io/sous-plugin-formats":`^${package_default20.version}`,"@sous-io/sous-plugin-refs":`^${package_default20.version}`,"@sous-io/sous-plugin-variables":`^${package_default20.version}`,"@sous-io/sous-plugin-git":`^${package_default20.version}`,"@sous-io/sous-plugin-init":`^${package_default20.version}`,"@sous-io/sous-plugin-config-files":`^${package_default20.version}`},register(sous){sous.intents.add({intent:"repo.release",summary:"Publish new versions of this repository's recipes: bump, regenerate the index, commit and tag",description:"Runs inside a recipe repository. Validates it, raises the version of every changed recipe, regenerates sous.index.json, commits the manifests and the index, and tags each version. --check only reads (for a pull request); --ci runs the way a merge does.",input:releaseInput,cli:{flags:{...yesFlag2,directory:{hidden:!0}},examples:["sous repo release","sous repo release --dry-run","sous repo release --namespace workflow --bump minor","sous repo release --recipe workflow/task-files --yes --push","sous repo release --check","sous repo release --ci --push"]},agent:{usage:"Call this inside a recipe repository to publish its changed recipes. Use check: true to validate without writing.",whenNotToUse:"Not for a sous project; it releases the recipe repository it runs in."},load:async()=>(await Promise.resolve().then(()=>(init_release(),release_exports))).handleRelease}),sous.intents.add({intent:"repo.submit",summary:"Propose a recipe repository's changes to its maintainers, and follow the proposal through",description:"Validates the checkout, then pushes its branch and opens or updates a proposal through the repository host. Needs the host's command line tool (gh, glab) signed in.",input:submitInput,cli:{positional:["repo"],flags:{...yesFlag2,directory:{hidden:!0}},examples:['sous repo submit --title "Add a linting recipe" --body "Adds lint rules."',"sous repo submit sous-recipes","sous repo submit --status",'sous repo submit --commit --yes --title "Fix a typo" --body "Fixes it."',"sous repo submit --dry-run"]},agent:{usage:"Call this to propose committed changes in a recipe repository checkout. A new proposal needs title and body."},load:async()=>(await Promise.resolve().then(()=>(init_submit(),submit_exports))).handleSubmit}),sous.intents.add({intent:"repo.contribute",summary:"Start a contribution to a recipe repository on a fresh branch, or finish one with --finish",description:"Starting links the repository on a new branch (repo link --latest). Finishing submits what no proposal carries yet (repo submit), then unlinks and updates the pins (repo unlink --update).",input:contributeInput,changesConfig:!0,requiresProject:!0,cli:{aliases:[["repo","contrib"]],positional:["ref"],flags:yesFlag2,examples:["sous repo contribute sous-recipes","sous repo contribute workflow/task-files","sous repo contribute sous-recipes --create-branch fix-a-typo",'sous repo contribute sous-recipes --finish --title "Fix a typo" --body "Fixes it."',"sous repo contribute sous-recipes --finish --no-submit --remove","sous repo contribute sous-recipes --finish --dry-run"]},agent:{usage:"Call this to start editing a recipe repository from a project, and again with finish: true to propose and unlink."},load:async()=>(await Promise.resolve().then(()=>(init_contribute(),contribute_exports))).handleContribute}),sous.intents.add({intent:"repo.init",summary:"Create a new sous recipe repository in a directory, then set it up for sous",input:initInput,cli:{positional:["directory"],examples:["sous repo init","sous repo init ./my-recipes","sous repo init ./my-recipes --name team-recipes --namespace workflow","sous repo init ./my-recipes --host github","sous repo init ./my-recipes --leave-includes --no-build","sous repo init ./my-recipes --dry-run"],flags:{yes:{short:"y"}}},agent:{usage:"Call this to scaffold a new recipe repository."},load:async()=>(await Promise.resolve().then(()=>(init_scaffold(),scaffold_exports))).handleInit})}});import{definePlugin as definePlugin22,jsonSchema as jsonSchema28}from"@sous-io/sous-plugin-api";init_src7();init_hooks();import fs65 from"node:fs";import path88 from"node:path";function hooksWithBlock(folder){return[...DEFAULT_HOOKS,...PULL_HOOKS].filter(hook=>{try{return fs65.readFileSync(path88.join(folder,hook),"utf8").includes(HOOK_BLOCK_START)}catch{return!1}})}function real(directory){try{return fs65.realpathSync(directory)}catch{return path88.resolve(directory)}}async function gitHooksFolder(ctx,root){if(!ctx.services.has("git.runner"))return;let result=await ctx.services.get("git.runner").run(["rev-parse","--git-path","hooks"],{cwd:root,reject:!1});return result.exitCode===0&&result.stdout.trim()!==""?path88.resolve(root,result.stdout.trim()):void 0}async function checkGitHooks(ctx){let root=ctx.project?.root;if(root===void 0)return{status:"skipped",summary:"There is no project here."};let husky=hooksWithBlock(path88.join(root,HUSKY_DIR)),folder=await gitHooksFolder(ctx,root);if(folder===void 0)return husky.length===0?{status:"ok",summary:"The project is not in a git repository, so it has no git hooks."}:{status:"skipped",summary:"Git cannot read this project's repository, so the hooks could not be checked."};if(husky.length>0){let huskyFolder=path88.join(root,HUSKY_DIR,"_");return real(folder)===real(huskyFolder)&&fs65.existsSync(huskyFolder)?{status:"ok",summary:`The git hooks run through Husky: ${husky.join(", ")}.`}:{status:"problem",summary:`The project was set up with git hooks (${husky.join(", ")} in ${HUSKY_DIR}/), but they are not turned on in this clone.`,details:[`Git runs the hooks in ${folder}; Husky's are in ${huskyFolder}, which its command sets up during the package manager's install.`],fix:"Install the git hooks and run the package manager's install",hint:"Run 'sous init hooks --install'."}}let own=hooksWithBlock(folder);return own.length>0?{status:"ok",summary:`The git hooks are installed: ${own.join(", ")}.`}:{status:"ok",summary:"No git hooks from 'sous init hooks' were found. A project without a package.json keeps them outside git, so a new clone cannot tell; 'sous init hooks' installs them."}}var gitHooksCheck={id:"git-hooks",order:DOCTOR_CHECK_ORDER.gitHooks,description:"The git hooks are installed, when the project was set up with them",check:ctx=>checkGitHooks(ctx),async fix(ctx){let root=ctx.project.root,pullHooks=hooksWithBlock(path88.join(root,HUSKY_DIR)).some(hook=>PULL_HOOKS.includes(hook)),result=(await ctx.run("init.hooks",{directory:root,install:!0,pullHooks})).toPlain();return result.installed?{summary:result.install?.outcome==="ran"?`The git hooks are installed, and '${result.install.command}' ran.`:"The git hooks are written.",details:result.files.map(file2=>`${file2.file}: ${file2.change}`)}:{summary:`The git hooks were not installed: ${result.reason}`,details:[...result.manual]}}};var package_default21={name:"@sous-io/sous-plugin-init",version:"1.1.6",description:"Scaffolding a project's .sous/ (sous init).",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-doctor":"workspace:*","@sous-io/sous-plugin-build":"workspace:*","@sous-io/sous-plugin-config-files":"workspace:*","@sous-io/sous-plugin-git":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@sous-io/sous-plugin-update":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};init_templates2();init_import();init_hooks();init_package_json();init_scaffold2();var PLUGIN_NAME21="@sous-io/sous-plugin-init",initInput2=jsonSchema28({type:"object",properties:{directory:{type:"string",description:"Project directory to set up (defaults to the current one)."},name:{type:"string",description:"Display name for the project (defaults to the directory's own name)."},yes:{type:"boolean",default:!1,description:"Accept the default answer to every question init asks: set the project up even inside another one, move the included files, and install the git hooks (without the pull hooks), running the install."},moveIncludes:{type:"boolean",default:!1,description:"Move the files the existing CLAUDE.md or AGENTS.md include into .sous/includes/ (the default)."},copyIncludes:{type:"boolean",default:!1,description:"Copy the files the existing CLAUDE.md or AGENTS.md include into .sous/includes/, keeping the originals."},leaveIncludes:{type:"boolean",default:!1,description:"Leave the files the existing CLAUDE.md or AGENTS.md include where they are."},dryRun:{type:"boolean",default:!1,description:"Show the files that would be written without writing them."},noBuild:{type:"boolean",default:!1,description:"Write the setup without running the first build."},hooks:{type:"boolean",description:"Install the git hooks that build Sous's output in each new worktree (--no-hooks: do not)."},pullHooks:{type:"boolean",description:"Also install the git hooks that run after a pull and a rebase."},install:{type:"boolean",description:"Run the package manager's install after installing the git hooks (--no-install: do not)."}},additionalProperties:!1}),initHooksInput=jsonSchema28({type:"object",properties:{directory:{type:"string",description:"Project directory, holding .sous/ (defaults to the project sous finds)."},pullHooks:{type:"boolean",description:"Also install the hooks that run after a pull and a rebase (--no-pull-hooks: do not)."},install:{type:"boolean",description:"Run the package manager's install at the end (--no-install: do not)."},yes:{type:"boolean",default:!1,description:"Accept the default answer to every question: no pull hooks, and run the install."},dryRun:{type:"boolean",default:!1,description:"Show the files that would be written without writing them."}},additionalProperties:!1}),initPlugin=definePlugin22({name:PLUGIN_NAME21,version:package_default21.version,description:"Scaffolding a project's .sous/ (sous init).",dependsOn:{"@sous-io/sous-plugin-build":`^${package_default21.version}`,"@sous-io/sous-plugin-config-files":`^${package_default21.version}`,"@sous-io/sous-plugin-host":`^${package_default21.version}`,"@sous-io/sous-plugin-update":`^${package_default21.version}`,"@sous-io/sous-plugin-doctor":`^${package_default21.version}`},register(sous){sous.entities.add("doctor-check",gitHooksCheck),sous.intents.add({intent:"init",summary:"Set a project up for sous: import its agent files into a new .sous/ directory, install the git hooks, then run the first build",input:initInput2,changesConfig:!0,cli:{positional:["directory"],examples:["sous init","sous init ./my-project","sous init --name 'My Project' --no-build","sous init --leave-includes","sous init --dry-run"],flags:{yes:{short:"y",aliases:["force"]}}},agent:{usage:"Set up a new project. Pass yes so no question is asked (or moveIncludes, copyIncludes or leaveIncludes to choose what happens to the files the existing instructions include, and hooks, pullHooks and install for the git hooks), and dryRun first to see the files."},load:()=>Promise.resolve().then(()=>(init_init(),init_exports))}),sous.intents.add({intent:"init.hooks",summary:"Install the git hooks that build Sous's output in each new worktree and checked-out branch",input:initHooksInput,cli:{command:["init","hooks"],positional:["directory"],examples:["sous init hooks","sous init hooks --pull-hooks","sous init hooks --yes","sous init hooks --no-install","sous init hooks --dry-run"],flags:{yes:{short:"y",aliases:["force"]}}},agent:{usage:"Install the git hooks once, in a project whose .sous/ is at the top of its git repository. Pass yes (or install and pullHooks) so no question is asked, and dryRun first to see the files."},load:()=>Promise.resolve().then(()=>(init_init_hooks(),init_hooks_exports))})}});init_src9();init_src7();init_src7();import{definePlugin as definePlugin23,jsonSchema as jsonSchema29}from"@sous-io/sous-plugin-api";var QUIET_INTENTS=new Set(["doctor","migrations.run","upgrade","help","version","completion","completion.words","mcp.serve"]);function noticeText(count2){return`${count2===1?"A migration":`${count2} migrations`} from a newer version of sous ${count2===1?"is":"are"} waiting to run in this project. Run 'sous doctor' to run ${count2===1?"it":"them"}.`}function pendingNotice(){let spoken=new Set;return(event,ctx)=>{let chain=ctx.chain;if(chain===void 0||chain.intent!==event.intent||spoken.has(chain.id)||QUIET_INTENTS.has(event.intent)||(spoken.add(chain.id),ctx.project===void 0||!ctx.services.has("migrations")))return;let count2=0;try{count2=ctx.services.get("migrations").pending().length}catch{return}count2>0&&ctx.reporter.notice(noticeText(count2))}}init_pending2();init_run2();init_pending2();function lockOf(ctx){return ctx.project!==void 0&&ctx.services.has("recipes.lock")?ctx.services.get("recipes.lock"):void 0}function createMigrationsService(ctx,running){let all=()=>orderMigrations(ctx.entities.list("migration"));return{all,migratedVersion(){return lockOf(ctx)?.migratedVersion()},pending(){let lock=lockOf(ctx);if(lock===void 0||!lock.exists())return[];let stored=lock.migratedVersion();return pendingMigrations(all(),stored!==void 0&&isVersion(stored)?stored:void 0)},async markCurrent(){let lock=lockOf(ctx);lock!==void 0&&isVersion(running)&&await lock.setMigratedVersion(running)}}}var package_default23={name:"@sous-io/sous-plugin-migrations",version:"1.1.6",description:"Migrations: the steps that bring a project's files in line with a newer version of sous, and the notice that some are waiting.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-doctor":"workspace:*",semver:"^7.8.5"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*","@sous-io/sous-plugin-formats":"workspace:*","@sous-io/sous-plugin-recipes":"workspace:*","@types/semver":"^7.8.0"},engines:{node:">=22"}};init_pending2();var PLUGIN_NAME22="@sous-io/sous-plugin-migrations",migrationSchema=jsonSchema29({type:"object",required:["id","version","order","description","plugin"],properties:{id:{type:"string"},version:{type:"string",description:"The version of sous this migration belongs to."},order:{type:"number",description:"Among migrations of one version, a higher number runs later."},description:{type:"string"},plugin:{type:"string"}}}),runInput=jsonSchema29({type:"object",properties:{yes:{type:"boolean",default:!1,description:"Take every question's default instead of asking."},answer:{type:"array",items:{type:"string"},description:"Answer a migration's question ahead of time, as <name>=<value>."},dryRun:{type:"boolean",default:!1,description:"List the pending migrations and their answers, and change nothing."}},additionalProperties:!1});function toEntity(migration,plugin,index){if(typeof migration.version!="string"||!isVersion(migration.version))throw new Error(`${plugin} added a migration whose version "${String(migration.version)}" is not a version such as 1.2.0.`);if(typeof migration.up!="function")throw new Error(`${plugin} added the migration for sous ${migration.version} without an up function.`);let id=migration.id??`${plugin}@${migration.version}#${index}`;return{id,version:migration.version,order:migration.order??DEFAULT_ORDER2,description:migration.description??`The migration ${id}`,plugin,up:migration.up,...migration.questions===void 0?{}:{questions:migration.questions}}}var migrationsCheck={id:"migrations",order:DOCTOR_CHECK_ORDER.migrations,description:"Every migration for this version of sous has run",confirm:!1,check(ctx,run){let pending;try{pending=ctx.services.get("migrations").pending()}catch(error51){if(run.configFailed)return{status:"skipped",summary:"Skipped: the config did not load."};throw error51}if(pending.length===0)return{status:"ok"};let given=new Set(answersForMigrations(ctx,run.answers).map(entry=>entry.slice(0,entry.indexOf("=")).trim())),unanswered=migration=>(migration.questions??[]).filter(question=>question.answered?.(ctx,{})===void 0&&!given.has(question.id)),waiting=run.yes||ctx.prompter.interactive?0:pending.reduce((count2,migration)=>count2+unanswered(migration).length,0);return waiting>0?{status:"pending",summary:`${pending.length===1?"1 migration is":`${pending.length} migrations are`} waiting to run, because sous could not ask ${waiting===1?"the question":`the ${waiting} questions`} below without a terminal.`,details:pending.map(migration=>{let questions=unanswered(migration),name=`${migration.description} [sous ${migration.version}]`;return questions.length===0?`${name}: it asks nothing, and waits because migrations run in order and none runs until every question is answered.`:{text:`${name} asks:`,details:questions.map(question=>`${question.message} Answer it with --answer ${question.id}=<${valuesOf(question).join("|")}> (--yes takes ${question.default}).`)}}),waiting:{count:pending.length,label:pending.length===1?"1 migration":`${pending.length} migrations`}}:{status:"problem",summary:`${pending.length===1?"1 migration is":`${pending.length} migrations are`} waiting to run.`,details:pending.map(migration=>`${migration.description} [sous ${migration.version}]`),fix:"Run the pending migrations"}},async fix(ctx,run){let result=(await ctx.run("migrations.run",{...run.yes?{yes:!0}:{},...run.answers.length===0?{}:{answer:answersForMigrations(ctx,run.answers)}})).toPlain();return result.unanswered.length>0?{summary:`No migration ran: sous could not ask ${result.unanswered.length===1?"this question":"these questions"} without a terminal, and none runs until every question is answered.`,details:result.unanswered.map(question=>`${question.message} Answer it with --answer ${question.question}=<${question.values.join("|")}> (--yes takes ${question.default}).`)}:{summary:`${result.migrations.length===1?"1 migration ran":`${result.migrations.length} migrations ran`}; the project is recorded as migrated to sous ${result.to}.`,details:result.migrations.map(report=>`${report.description}${report.outcome?.summary===void 0?"":`: ${report.outcome.summary}`}`)}}};function answersForMigrations(ctx,answers){let ids=new Set(ctx.services.get("migrations").all().flatMap(migration=>(migration.questions??[]).map(question=>question.id)));return answers.filter(entry=>ids.has(entry.slice(0,Math.max(0,entry.indexOf("="))).trim()))}var migrationsPlugin=definePlugin23({name:PLUGIN_NAME22,version:package_default23.version,description:"Sous's own migrations, the version a project last migrated to, and the notice that some are waiting.",dependsOn:{"@sous-io/sous-plugin-doctor":`^${package_default23.version}`},register(sous){sous.entities.define("migration",migrationSchema,{description:"A step that brings a project's files in line with a newer version of sous."});let counts=new Map;sous.extensions.add("migrations",other=>({add(migration){let index=(counts.get(other.plugin.name)??0)+1;counts.set(other.plugin.name,index),other.entities.add("migration",toEntity(migration,other.plugin.name,index))}})),sous.services.add("migrations",(_config,ctx)=>createMigrationsService(ctx,sous.engine.app.version),{lifetime:"config"}),sous.entities.add("doctor-check",migrationsCheck),sous.intents.add({intent:"migrations.run",summary:"Run the migrations from newer versions of sous that this project has not run",input:runInput,requiresProject:!0,toleratesConfigErrors:!0,cli:{command:["migrations","run"],hidden:!0,flags:{yes:{short:"y",aliases:["force"]}}},load:()=>Promise.resolve().then(()=>(init_run2(),run_exports))}),sous.on("*.before",pendingNotice()),sous.on("recipes.locked",async(event,ctx)=>{if(event.payload.created===!0&&ctx.services.has("recipes.lock")){let lock=ctx.services.get("recipes.lock");lock.migratedVersion()===void 0&&isVersion(ctx.engine.app.version)&&await lock.setMigratedVersion(ctx.engine.app.version)}})}});import{definePlugin as definePlugin24}from"@sous-io/sous-plugin-api";init_src();import nodePath2 from"node:path";import{IntentOutputs as IntentOutputs27,NotFoundError as NotFoundError11,SousError as SousError34}from"@sous-io/sous-plugin-api";import{ConfigError as ConfigError66,DataValue as DataValue2,IntentOutput as IntentOutput22,ReportEntryStyle as ReportEntryStyle17,Table as Table5,TextBlock as TextBlock13,Tree as Tree3,VariableSet as VariableSet12}from"@sous-io/sous-plugin-api";function prettyJson(value){return JSON.stringify(value,null,2)??"undefined"}function isScalar3(value){return value===null||typeof value=="string"||typeof value=="number"||typeof value=="boolean"}function plural2(count2,singular,pluralForm=`${singular}s`){return`${count2} ${count2===1?singular:pluralForm}`}function missingValue(path122){return new ConfigError66(`No value at config path '${path122}'.`,{details:["It is not present in the built config.","Run 'sous config show' to see the whole config."]})}function missingInLayers(path122){return new ConfigError66(`No value at config path '${path122}' in any config layer.`,{details:["Run 'sous config show' to see the whole config."]})}function rawFileOutputs(files){return files.map(file2=>new IntentOutput22({result:new TextBlock13(`# ${file2.path} (${file2.contributor})
1178
1179
  ${file2.text.replace(/\n$/,"")}`,{verbatim:!0})}))}function configShowOutputs(result){if(!result.layers&&!result.raw)return[new IntentOutput22({result:new DataValue2(result.config)})];let outputs=[];return result.raw&&outputs.push(...rawFileOutputs(result.raw)),result.layers&&(outputs.push(new IntentOutput22({result:layerTree(result.layers)})),outputs.push(new IntentOutput22({result:new VariableSet12([{label:"result",value:`settled after ${plural2(result.passes,"pass","passes")}`}])}))),outputs}function configGetOutputs(result){let outputs=result.raw?rawFileOutputs(result.raw):[];if(result.layers){if(!result.exists&&result.layers.length===0)throw missingInLayers(result.path);outputs.push(new IntentOutput22({result:layerTable(result)}));let shown=result.exists&&result.value!==void 0?prettyJson(result.value):"(not set)";return outputs.push(new IntentOutput22({result:new VariableSet12([{label:"result",value:shown,detail:`settled after ${plural2(result.passes,"pass","passes")}`}])})),outputs}if(!result.exists||result.value===void 0)throw missingValue(result.path);return outputs.push(new IntentOutput22({result:isScalar3(result.value)?new TextBlock13(String(result.value),{verbatim:!0}):new DataValue2(result.value)})),outputs}function configValidateOutputs(result){if(result.ok){let summary2=result.summary;return[new IntentOutput22({title:"Config is valid",...summary2===void 0?{}:{result:new VariableSet12({"Config File":summary2.configFile??"(none)",Layers:summary2.layers,Targets:summary2.targets,Tools:summary2.tools.length>0?summary2.tools.join(", "):"(none)"})}})]}return[new IntentOutput22({title:`The config has ${plural2(result.issues.length,"problem")}`}),...result.issues.map(issue2=>new IntentOutput22({result:new TextBlock13(issue2),style:ReportEntryStyle17.Problem}))]}var REGISTRATION_LABELS={intent:"intents","intent wrapper":"wraps intents",service:"services","service replacement":"replaces","service wrapper":"wraps","entity kind":"entity kinds",entity:"entities",contributor:"contributors","front end":"front ends",listener:"listeners"};function pluginsShowOutputs(plugins){return plugins.map(plugin=>{let notes=[plugin.builtIn?"built in":plugin.loadedBy?`loaded by ${plugin.loadedBy}`:void 0,plugin.active?void 0:"inactive"].filter(note=>note!==void 0),version2=plugin.version?` ${plugin.version}`:"",groups=new Map;for(let registration of plugin.registrations){let label=REGISTRATION_LABELS[registration.kind]??registration.kind,names2=groups.get(label)??[];names2.push(registration.name),groups.set(label,names2)}let entries=[...groups].map(([label,names2])=>({label,value:names2.join(" ")}));plugin.options&&Object.keys(plugin.options).length>0&&entries.push({label:"options",value:JSON.stringify(plugin.options,null,1).replace(/\n\s*/g," ")});let title2=`${plugin.name}${version2}${notes.length>0?` (${notes.join(", ")})`:""}`;return new IntentOutput22(entries.length>0?{title:title2,result:new VariableSet12(entries)}:{title:title2})})}function timingsShowOutput(entries){let rows=[...entries].sort((a,b)=>b.totalMs-a.totalMs).map(entry=>({name:entry.key,calls:entry.count,total:`${entry.totalMs.toFixed(1)} ms`,max:`${entry.maxMs.toFixed(1)} ms`,budget:`${entry.budgetMs===!1?"no budget warning":`budget ${entry.budgetMs} ms`}${entry.overBudget>0?`, ${entry.overBudget} over`:""}`}));return new IntentOutput22({result:new Table5([{key:"name",header:"Name",overflow:"truncate",truncate:"middle"},{key:"calls",header:"Calls",kind:"number"},{key:"total",header:"Total",kind:"number"},{key:"max",header:"Max",kind:"number"},{key:"budget",header:"Budget",priority:"low"}],rows,{title:"Timings",empty:"No timings yet."})})}function layerTree(layers){let roots=[],contributor,build2,named=namesBuilds(layers);for(let layer of layers){if(layer.contributor!==contributor||layer.build!==build2||roots.length===0){contributor=layer.contributor,build2=layer.build;let details=[...layer.source?[layer.contributor]:[],layer.plugin,...applyOrderText(layer),...named?[buildText(layer)]:[]];roots.push({label:layer.source??layer.contributor,detail:details.join(", "),children:[]})}let parent=roots[roots.length-1];for(let helper of layer.helpers){let last2=parent.children[parent.children.length-1];if(last2!==void 0&&last2.label===helper&&last2.children.length>0)parent=last2;else{let node={label:helper,children:[]};parent.children.push(node),parent=node}}parent.children.push({label:describePatch(layer.patch),children:annotationLines(layer).map(line=>({label:line,children:[]}))})}return new Tree3(roots)}function namesBuilds(layers){return layers.some(layer=>(layer.build??"")!=="")}function buildText(layer){return(layer.build??"")===""?"no harness":`harness ${layer.build}`}function applyOrderText(layer){return layer.actualApplyOrder===layer.applyOrder?[`apply order ${layer.applyOrder}`]:[`apply order ${layer.applyOrder}, moved to ${layer.actualApplyOrder}`]}var LAYER_COLUMNS=[{key:"source",header:"Config",overflow:"wrap",kind:"path"},{key:"change",header:"Change",overflow:"wrap",flex:1}],MAX_SOURCE_WORD=40;function layerTable(result){let rows=[],named=namesBuilds(result.layers??[]);for(let layer of result.layers??[]){let text=layer.change?`${shownOrUnset(layer.change,"from")} -> ${shownOrUnset(layer.change,"to")}`:changeAt(layer.patch,result.path),source=layer.source??layer.contributor;rows.push({source:named?`${source} (${buildText(layer)})`:source,change:text});for(let line of annotationLines(layer))rows.push({source:"",change:line})}let longestWord=Math.max(0,...rows.flatMap(row=>row.source.split(/\s+/).map(word=>word.length))),columns=LAYER_COLUMNS.map(column=>column.key==="source"?{...column,minWidth:Math.min(Math.max(longestWord,column.header.length),MAX_SOURCE_WORD)}:column);return new Table5(columns,rows)}function shownOrUnset(change,side){return side in change&&change[side]!==void 0?prettyJson(change[side]):"(unset)"}function changeAt(patch,path122){if(targetOf(patch)===path122)switch(patch.op){case"setKey":case"setIndex":case"insertAt":return prettyJson(patch.value);case"deleteKey":case"removeIndex":return"(not set)";case"renameKey":return`(renamed to ${patch.to})`}return describePatch(patch)}function describePatch(patch){let target=targetOf(patch);switch(patch.op){case"setKey":case"setIndex":case"insertAt":return`${patch.op} ${target} = ${prettyJson(patch.value)}`;case"renameKey":return`${patch.op} ${target} \u2192 ${patch.to}`;default:return`${patch.op} ${target}`}}function targetOf(patch){let base=patch.path;return patch.op==="setIndex"||patch.op==="insertAt"||patch.op==="removeIndex"?`${base}[${patch.index}]`:/^[A-Za-z_$][\w$-]*$/.test(patch.key)?base===""?patch.key:`${base}.${patch.key}`:`${base}${base===""?"":"."}"${patch.key}"`}function annotationLines(layer){return Object.entries(layer.annotations??{}).map(([key,value])=>`${key}: ${typeof value=="string"?value:prettyJson(value)}`)}import path97 from"node:path";var HIDDEN="(hidden)",SECRET_KEY=/(pass(word|wd|phrase)?|secret|token|api[-_]?key|private[-_]?key|credential|authorization|bearer)/i;function isSecretKey(key){return SECRET_KEY.test(key)}var KEY_NAME_POLICY={isSecret:(key,value)=>isSecretKey(key)&&value!==null&&value!=="",isSecretName:isSecretKey};function servicePolicy(secrets){let declared=secrets.declared();return{isSecret:(key,value)=>secrets.isSecret(key,value,declared)||typeof value=="string"&&secrets.hasSecretValue(value),isSecretName:name=>declared.has(name)||secrets.hasSecretName(name)}}function redactValue(value,policy=KEY_NAME_POLICY){if(Array.isArray(value))return value.map(item=>redactValue(item,policy));if(value!==null&&typeof value=="object"){let out={};for(let[key,inner]of Object.entries(value))out[key]=redactUnder(key,inner,policy);return out}return value}function redactUnder(key,value,policy=KEY_NAME_POLICY){return(value!==null&&typeof value=="object"?policy.isSecretName(key):policy.isSecret(key,value))?HIDDEN:redactValue(value,policy)}function pathHasSecret(path122,policy){return path122.split(/[.[\]"]+/).some(segment=>segment!==""&&policy.isSecretName(segment))}function redactPatch(patch,policy=KEY_NAME_POLICY){if(patch.op==="setKey"){let secret=policy.isSecretName(patch.key)||pathHasSecret(patch.path,policy);return{...patch,value:secret?HIDDEN:redactUnder(patch.key,patch.value,policy)}}return patch.op==="setIndex"||patch.op==="insertAt"?{...patch,value:pathHasSecret(patch.path,policy)?HIDDEN:redactValue(patch.value,policy)}:patch}function redactLayer(layer,policy=KEY_NAME_POLICY){return{...layer,patch:redactPatch(layer.patch,policy)}}var KEY_VALUE=/(["']?)([\w$.-]+)\1(\s*[:=]\s*)("(?:\\.|[^"\\])*"|'[^']*'|[^\s,{}[\]#]+)/g;function redactText(text,policy=KEY_NAME_POLICY){return text.replace(KEY_VALUE,(whole,quote2,key,separator)=>policy.isSecretName(key)?`${quote2}${key}${quote2}${separator}"${HIDDEN}"`:whole)}var MAIN_CONTRIBUTOR2="config-files.main",MAIN_PATCH_PREFIX="config-files/";function configFiles2(project,services){let files=[],loader=services.has("config-files.loader")?services.get("config-files.loader"):void 0;project.configPath!==void 0&&files.push({contributor:MAIN_CONTRIBUTOR2,path:project.configPath});for(let file2 of loader?.findPatches(project.sousDir)??[])files.push({contributor:`${MAIN_PATCH_PREFIX}${path97.basename(file2)}`,path:file2});return services.has("confd.files")&&files.push(...services.get("confd.files").list()),files}async function readRawConfigFiles(project,services,policy=KEY_NAME_POLICY){if(project===void 0||!services.has("config-files.loader"))return[];let loader=services.get("config-files.loader"),raw2=[];for(let file2 of configFiles2(project,services))try{let loaded=await loader.load(file2.path);raw2.push({contributor:file2.contributor,path:file2.path,text:redactText(loaded.text,policy)})}catch{}return raw2}function policyOf(ctx){return ctx.services.has("variables.secrets")?servicePolicy(ctx.services.get("variables.secrets")):KEY_NAME_POLICY}var MAIN_CONTRIBUTOR3="config-files.main",MAIN_PATCH_PREFIX2="config-files/";function configFor(ctx,harness){if(harness===void 0)return ctx.config;let found=ctx.config.forHarness(harness);if(found===void 0){let known=ctx.config.harnesses;throw new NotFoundError11("harness",harness,`No config was built for the harness "${harness}".`,{details:[known.length>0?`Configs were built for: ${known.join(", ")}.`:"No harness is registered, so only the config with no harness was built."]})}return found}function layersOf(ctx,config2,path122,policy){let target=parsePath(path122),sources=sourcesOf(ctx,config2),views=[],before=new Map,touching=target.some(segment=>typeof segment=="number")?itemLayers(config2,target):config2.layers(path122).map(layer=>({layer,patch:layer.patch,target}));for(let{layer,patch,target:at2}of touching){let view={...redactLayer(layer,policy),...withSource(sources.get(layer.contributor))},after=valueAfter(redactLayer({...layer,patch},policy).patch,at2),was=before.get(layer.build);if(after===UNKNOWN){views.push(view);continue}JSON.stringify(after)!==JSON.stringify(was)&&(views.push({...view,change:{...was===void 0?{}:{from:was},...after===void 0?{}:{to:after}}}),before.set(layer.build,after))}return views}function withSource(source){return source===void 0?{}:{source}}function itemLayers(built,target){let steps=[],config2={};for(let contribution of built.contributions()){let record2=(patch,helpers)=>{let applied=patch;if(patch.op==="insertAt"&&patch.index==="end"){let array2=getAtPath(config2,parsePath(patch.path));applied={...patch,index:Array.isArray(array2)?array2.length:0}}let failed=!1;if(config2=applyPatch(config2,applied,{onProblem:()=>{failed=!0}}),!failed){let{contributor,plugin,applyOrder,actualApplyOrder,build:build2}=contribution;steps.push({layer:{contributor,plugin,patch,helpers,applyOrder,actualApplyOrder,build:build2},patch:applied})}},walkSet=(set2,helpers)=>{for(let item of set2.patches)isPatch(item)?record2(item,helpers):walkSet(item,[...helpers,item.name])};walkSet(contribution.patches,[])}let found=[],at2=[...target];for(let index=steps.length-1;index>=0;index--){let{layer,patch}=steps[index];if(patch.op==="insertAt"||patch.op==="removeIndex"){let container=parsePath(patch.path),position=at2[container.length];if(container.length<at2.length&&isPathPrefix(container,at2)&&typeof position=="number"){let changed2=patch.index;if(patch.op==="insertAt"&&changed2===position){found.push({layer,patch,target:at2});break}let moved=[...at2];moved[container.length]=patch.op==="insertAt"?changed2<position?position-1:position:changed2<=position?position+1:position,at2=moved;continue}isPathPrefix(at2,container)&&found.push({layer,patch,target:at2});continue}pathsOverlap(primitiveTargetOf(patch),at2)&&found.push({layer,patch,target:at2})}return found.reverse()}function primitiveTargetOf(patch){let container=parsePath(patch.path);switch(patch.op){case"setKey":case"deleteKey":case"renameKey":return[...container,patch.key];case"insertAt":return container;default:return[...container,patch.index]}}var UNKNOWN=Symbol("unknown");function valueAfter(patch,target){if(patch.op==="renameKey")return UNKNOWN;let at2=[...parsePath(patch.path),patch.op==="setKey"||patch.op==="deleteKey"?patch.key:patch.index];if(!isPathPrefix(at2,target))return UNKNOWN;let rest=target.slice(at2.length);switch(patch.op){case"setKey":case"setIndex":return getAtPath(patch.value,rest);case"deleteKey":return;case"insertAt":case"removeIndex":return rest.length>0?UNKNOWN:patch.op==="insertAt"?patch.value:UNKNOWN}}function sourcesOf(ctx,config2){let sources=new Map,project=ctx.project;if(project===void 0)return sources;let fromSousDir=file2=>{let relative4=nodePath2.relative(project.sousDir,file2);return relative4!==""&&!relative4.startsWith("..")?relative4:file2};project.configPath!==void 0&&sources.set(MAIN_CONTRIBUTOR3,fromSousDir(project.configPath));for(let contribution of config2.contributions())contribution.contributor.startsWith(MAIN_PATCH_PREFIX2)&&sources.set(contribution.contributor,fromSousDir(nodePath2.join(project.sousDir,contribution.contributor.slice(MAIN_PATCH_PREFIX2.length))));for(let file2 of ctx.services.has("confd.files")?ctx.services.get("confd.files").list():[])sources.set(file2.contributor,fromSousDir(file2.path));return sources}async function configShow(input,ctx){let policy=policyOf(ctx),config2=configFor(ctx,input.harness),result={config:redactValue(config2.value(),policy),...input.harness===void 0?{}:{harness:input.harness},passes:config2.passes,...input.layers===!0?{layers:layersOf(ctx,config2,"",policy)}:{},...input.raw===!0?{raw:await readRawConfigFiles(ctx.project,ctx.services,policy)}:{}};return new IntentOutputs27(configShowOutputs(result)).withData(result)}async function configGet(input,ctx){let config2=configFor(ctx,input.harness),exists3=config2.has(input.path),value=exists3?config2.get(input.path):void 0,lastKey=input.path.split(/[.[\]"]+/).filter(part=>part!=="").pop()??"",policy=policyOf(ctx),shown=value===void 0?void 0:redactUnder(lastKey,value,policy),result={path:input.path,...input.harness===void 0?{}:{harness:input.harness},exists:exists3,value:shown,passes:config2.passes,...input.layers===!0?{layers:layersOf(ctx,config2,input.path,policy)}:{},...input.raw===!0?{raw:await readRawConfigFiles(ctx.project,ctx.services,policy)}:{}};return new IntentOutputs27(configGetOutputs(result)).withData(result)}async function configValidate(_input,ctx){let issues=[];for(let key of ctx.entities.list("config-key")){if(!ctx.config.has(key.id))continue;let value=ctx.config.get(key.id),result2=await key.schema["~standard"].validate(value);if(result2.issues===void 0)continue;let setBy2=[...new Set(ctx.config.layers(key.id).map(layer=>layer.contributor))],who=setBy2.length>0?` (set by ${setBy2.join(", ")})`:"";for(let issue2 of result2.issues){let inner=(issue2.path??[]).map(segment=>String(typeof segment=="object"?segment.key:segment)),at2=[key.id,...inner].join(".");issues.push(`${at2}: ${issue2.message}${who}`)}}issues.push(...variableIssues(ctx));let result={ok:issues.length===0,issues,summary:summaryOf2(ctx)};return new IntentOutputs27(configValidateOutputs(result),result.ok?{}:{exitCode:1}).withData(result)}function variableIssues(ctx){if(!ctx.services.has("variables.resolver"))return[];let resolver=ctx.services.get("variables.resolver"),targets=ctx.config.get("compilation.targets")??[],issues=[],attempt2=work=>{try{return work(),!0}catch(error51){if(!(error51 instanceof SousError34))throw error51;return issues.push([error51.message,...error51.details].join(`
1179
- `)),!1}};if(!attempt2(()=>resolver.scope({level:"root"})))return issues;for(let[target,value]of targets.entries()){let{outputs,...own}=value??{};attempt2(()=>resolver.substituteValue(withoutVars(own),resolver.scope({level:"target",target}),`compilation.targets[${target}]`));for(let[output,outputValue]of(Array.isArray(outputs)?outputs:[]).entries())attempt2(()=>resolver.substituteValue(withoutVars(outputValue??{}),resolver.scope({level:"output",target,output}),`compilation.targets[${target}].outputs[${output}]`))}return issues}function withoutVars(value){let{_vars:_ignored,...rest}=value;return rest}function summaryOf2(ctx){let confd=ctx.services.has("confd.files")?ctx.services.get("confd.files").list().length:0,main2=ctx.project?.configPath===void 0?0:1,tools=ctx.config.get("tools")??{};return{configFile:ctx.project?.configPath,layers:main2+confd,targets:(ctx.config.get("compilation.targets")??[]).length,tools:Object.keys(tools)}}function pluginsShow(input,ctx){let policy=policyOf(ctx),plugins=ctx.engine.plugins().map(plugin=>plugin.options===void 0?plugin:{...plugin,options:redactValue(plugin.options,policy)}),done2=shown=>new IntentOutputs27(pluginsShowOutputs(shown)).withData({plugins:shown});if(input.name===void 0)return done2(plugins);let found=plugins.filter(plugin=>plugin.name===input.name);if(found.length===0)throw new NotFoundError11("plugin",input.name,`No plugin named "${input.name}" is loaded.`,{details:["Run 'sous plugins show' to see every loaded plugin."]});return done2(found)}function timingsShow(input,ctx){let timings=ctx.engine.timings.entries().filter(entry=>(input.overBudget!==!0||entry.overBudget>0)&&(input.category===void 0||entry.category===input.category)).sort((a,b)=>b.totalMs-a.totalMs);return new IntentOutputs27([timingsShowOutput(timings)]).withData({timings})}import{jsonSchema as jsonSchema30}from"@sous-io/sous-plugin-api";var configShowSchema=jsonSchema30({type:"object",properties:{layers:{type:"boolean",description:"Show each contributor's changes, in order, and the passes."},raw:{type:"boolean",description:"Show each config file as written, in order."},harness:{type:"string",description:"Show this harness's own config build instead of the merged config."}}}),configGetSchema=jsonSchema30({type:"object",properties:{path:{type:"string",description:"Path into the config, with [n] for array indices."},layers:{type:"boolean",description:"Show each contributor's changes to the value, in order."},raw:{type:"boolean",description:"Show each config file as written, in order."},harness:{type:"string",description:"Read the value from this harness's own config build instead of the merged config."}},required:["path"]}),pluginsShowSchema=jsonSchema30({type:"object",properties:{name:{type:"string",description:"Only this plugin."}}}),timingsShowSchema=jsonSchema30({type:"object",properties:{overBudget:{type:"boolean",description:"Only entries that went over budget."},category:{type:"string",description:"Only one category, such as contributor or intent."}}});var package_default24={name:"@sous-io/sous-plugin-inspect",version:"1.1.4",description:"Showing the engine's state: config show, config get, config validate, plugins show, timings.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-lib-documents":"workspace:*","@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-confd":"workspace:*","@sous-io/sous-plugin-config-files":"workspace:*","@sous-io/sous-plugin-variables":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*","@sous-io/sous-plugin-host":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME23="@sous-io/sous-plugin-inspect",inspectPlugin=definePlugin24({name:PLUGIN_NAME23,version:package_default24.version,description:"Showing the engine's state: config show, config get, config validate, plugins show, timings.",dependsOn:{},register(sous){sous.intents.add({intent:"config.show",needsRecipeFiles:!0,requiresProject:!0,summary:"Print the built config",description:"Prints what sous does on this machine. --layers adds each contributor's changes, in order; --raw adds each config file as written; --harness <id> prints that harness's own config build instead of the merged config.",input:configShowSchema,parallel:!0,cli:{examples:["sous config show","sous config show --layers","sous config show --raw","sous config show --harness claude-code"]},agent:{usage:"Read the config as sous built it. Secrets are hidden."},handle:configShow}),sous.intents.add({intent:"config.get",needsRecipeFiles:!0,requiresProject:!0,summary:"Print one value from the built config by path",description:"A path like repos.sous-recipes.url. --layers shows who set the value, in order; --harness <id> reads the value from that harness's own config build.",input:configGetSchema,parallel:!0,cli:{positional:["path"],examples:["sous config get name","sous config get repos.sous-recipes.url","sous config get compilation --layers","sous config get compilation --harness claude-code"]},agent:{usage:"Read one config value by path. Secrets are hidden."},handle:configGet}),sous.intents.add({intent:"config.validate",needsRecipeFiles:!0,requiresProject:!0,summary:"Check the built config against every config key's schema",parallel:!0,cli:{examples:["sous config validate"]},handle:configValidate}),sous.intents.add({intent:"plugins.show",needsRecipeFiles:!0,summary:"Show every plugin, and what it registered, wrapped or replaced",input:pluginsShowSchema,parallel:!0,cli:{positional:["name"],examples:["sous plugins show","sous plugins show @sous-io/sous-plugin-git"]},handle:pluginsShow}),sous.intents.add({intent:"timings.show",summary:"Show every timing of this run and its budget",input:timingsShowSchema,parallel:!0,cli:{examples:["sous timings show","sous timings show --over-budget"]},handle:timingsShow})}});import{definePlugin as definePlugin25,IntentOutputs as IntentOutputs28,jsonSchema as jsonSchema31}from"@sous-io/sous-plugin-api";import{InputError as InputError9,toJsonSchema as toJsonSchema3}from"@sous-io/sous-plugin-api";function toolName(definition2){return definition2.agent?.tool??definition2.intent.replace(/\./g,"_")}function isAgentVisible(definition2){return definition2.internal!==!0&&definition2.agent?.hidden!==!0&&definition2.background!==!0}function toolDescription(definition2){let parts=[],summary2=definition2.summary??definition2.description;return parts.push(summary2??`Runs the sous intent "${definition2.intent}".`),definition2.agent?.usage&&parts.push(definition2.agent.usage),definition2.agent?.whenNotToUse&&parts.push(`When not to use it: ${definition2.agent.whenNotToUse}`),parts.join(`
1180
+ `)),!1}};if(!attempt2(()=>resolver.scope({level:"root"})))return issues;for(let[target,value]of targets.entries()){let{outputs,...own}=value??{};attempt2(()=>resolver.substituteValue(withoutVars(own),resolver.scope({level:"target",target}),`compilation.targets[${target}]`));for(let[output,outputValue]of(Array.isArray(outputs)?outputs:[]).entries())attempt2(()=>resolver.substituteValue(withoutVars(outputValue??{}),resolver.scope({level:"output",target,output}),`compilation.targets[${target}].outputs[${output}]`))}return issues}function withoutVars(value){let{_vars:_ignored,...rest}=value;return rest}function summaryOf2(ctx){let confd=ctx.services.has("confd.files")?ctx.services.get("confd.files").list().length:0,main2=ctx.project?.configPath===void 0?0:1,tools=ctx.config.get("tools")??{};return{configFile:ctx.project?.configPath,layers:main2+confd,targets:(ctx.config.get("compilation.targets")??[]).length,tools:Object.keys(tools)}}function pluginsShow(input,ctx){let policy=policyOf(ctx),plugins=ctx.engine.plugins().map(plugin=>plugin.options===void 0?plugin:{...plugin,options:redactValue(plugin.options,policy)}),done2=shown=>new IntentOutputs27(pluginsShowOutputs(shown)).withData({plugins:shown});if(input.name===void 0)return done2(plugins);let found=plugins.filter(plugin=>plugin.name===input.name);if(found.length===0)throw new NotFoundError11("plugin",input.name,`No plugin named "${input.name}" is loaded.`,{details:["Run 'sous plugins show' to see every loaded plugin."]});return done2(found)}function timingsShow(input,ctx){let timings=ctx.engine.timings.entries().filter(entry=>(input.overBudget!==!0||entry.overBudget>0)&&(input.category===void 0||entry.category===input.category)).sort((a,b)=>b.totalMs-a.totalMs);return new IntentOutputs27([timingsShowOutput(timings)]).withData({timings})}import{jsonSchema as jsonSchema30}from"@sous-io/sous-plugin-api";var configShowSchema=jsonSchema30({type:"object",properties:{layers:{type:"boolean",description:"Show each contributor's changes, in order, and the passes."},raw:{type:"boolean",description:"Show each config file as written, in order."},harness:{type:"string",description:"Show this harness's own config build instead of the merged config."}}}),configGetSchema=jsonSchema30({type:"object",properties:{path:{type:"string",description:"Path into the config, with [n] for array indices."},layers:{type:"boolean",description:"Show each contributor's changes to the value, in order."},raw:{type:"boolean",description:"Show each config file as written, in order."},harness:{type:"string",description:"Read the value from this harness's own config build instead of the merged config."}},required:["path"]}),pluginsShowSchema=jsonSchema30({type:"object",properties:{name:{type:"string",description:"Only this plugin."}}}),timingsShowSchema=jsonSchema30({type:"object",properties:{overBudget:{type:"boolean",description:"Only entries that went over budget."},category:{type:"string",description:"Only one category, such as contributor or intent."}}});var package_default24={name:"@sous-io/sous-plugin-inspect",version:"1.1.6",description:"Showing the engine's state: config show, config get, config validate, plugins show, timings.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-lib-documents":"workspace:*","@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-confd":"workspace:*","@sous-io/sous-plugin-config-files":"workspace:*","@sous-io/sous-plugin-variables":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*","@sous-io/sous-plugin-host":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME23="@sous-io/sous-plugin-inspect",inspectPlugin=definePlugin24({name:PLUGIN_NAME23,version:package_default24.version,description:"Showing the engine's state: config show, config get, config validate, plugins show, timings.",dependsOn:{},register(sous){sous.intents.add({intent:"config.show",needsRecipeFiles:!0,requiresProject:!0,summary:"Print the built config",description:"Prints what sous does on this machine. --layers adds each contributor's changes, in order; --raw adds each config file as written; --harness <id> prints that harness's own config build instead of the merged config.",input:configShowSchema,parallel:!0,cli:{examples:["sous config show","sous config show --layers","sous config show --raw","sous config show --harness claude-code"]},agent:{usage:"Read the config as sous built it. Secrets are hidden."},handle:configShow}),sous.intents.add({intent:"config.get",needsRecipeFiles:!0,requiresProject:!0,summary:"Print one value from the built config by path",description:"A path like repos.sous-recipes.url. --layers shows who set the value, in order; --harness <id> reads the value from that harness's own config build.",input:configGetSchema,parallel:!0,cli:{positional:["path"],examples:["sous config get name","sous config get repos.sous-recipes.url","sous config get compilation --layers","sous config get compilation --harness claude-code"]},agent:{usage:"Read one config value by path. Secrets are hidden."},handle:configGet}),sous.intents.add({intent:"config.validate",needsRecipeFiles:!0,requiresProject:!0,summary:"Check the built config against every config key's schema",parallel:!0,cli:{examples:["sous config validate"]},handle:configValidate}),sous.intents.add({intent:"plugins.show",needsRecipeFiles:!0,summary:"Show every plugin, and what it registered, wrapped or replaced",input:pluginsShowSchema,parallel:!0,cli:{positional:["name"],examples:["sous plugins show","sous plugins show @sous-io/sous-plugin-git"]},handle:pluginsShow}),sous.intents.add({intent:"timings.show",summary:"Show every timing of this run and its budget",input:timingsShowSchema,parallel:!0,cli:{examples:["sous timings show","sous timings show --over-budget"]},handle:timingsShow})}});import{definePlugin as definePlugin25,IntentOutputs as IntentOutputs28,jsonSchema as jsonSchema31}from"@sous-io/sous-plugin-api";import{InputError as InputError9,toJsonSchema as toJsonSchema3}from"@sous-io/sous-plugin-api";function toolName(definition2){return definition2.agent?.tool??definition2.intent.replace(/\./g,"_")}function isAgentVisible(definition2){return definition2.internal!==!0&&definition2.agent?.hidden!==!0&&definition2.background!==!0}function toolDescription(definition2){let parts=[],summary2=definition2.summary??definition2.description;return parts.push(summary2??`Runs the sous intent "${definition2.intent}".`),definition2.agent?.usage&&parts.push(definition2.agent.usage),definition2.agent?.whenNotToUse&&parts.push(`When not to use it: ${definition2.agent.whenNotToUse}`),parts.join(`
1180
1181
 
1181
- `)}function toolInputSchema(definition2){let schema=toJsonSchema3(definition2.input);return schema?schema.type===void 0&&schema.properties!==void 0?{...schema,type:"object"}:{...schema}:{type:"object",properties:{}}}function toolOutputSchema(definition2){let schema=toJsonSchema3(definition2.output);return schema?.type==="object"?{...schema}:void 0}function matchesGlob(name,glob){let pattern=glob.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${pattern}$`).test(name)}function buildTools(intents,settings={}){let tools=[],warnings=[],owners=new Map,include=settings.include,exclude=settings.exclude??[];for(let info of intents){let definition2=info.definition;if(!isAgentVisible(definition2))continue;let name=toolName(definition2);if(include&&!include.some(glob=>matchesGlob(name,glob))||exclude.some(glob=>matchesGlob(name,glob)))continue;let owner=owners.get(name);if(owner){warnings.push(`Two intents claim the MCP tool "${name}": "${owner.definition.intent}" (${owner.plugin}) and "${definition2.intent}" (${info.plugin}). The first keeps it; set agent.tool on one of them.`);continue}owners.set(name,info);let outputSchema2=toolOutputSchema(definition2);tools.push({name,intent:definition2.intent,description:toolDescription(definition2),inputSchema:toolInputSchema(definition2),...outputSchema2?{outputSchema:outputSchema2}:{}})}return{tools,warnings}}function createMcpTools(set2){let byName=new Map(set2.tools.map(tool=>[tool.name,tool]));return{warnings:set2.warnings,list:()=>[...set2.tools],toRequest(tool,args){let found=byName.get(tool);if(!found)throw new InputError9(tool,[{path:"",message:`No MCP tool is named "${tool}".`}]);return{intent:found.intent,input:{...args}}}}}var package_default25={name:"@sous-io/sous-plugin-mcp",version:"1.1.4",description:"The sous mcp front end: tools generated from intents, MCP logging and elicitation.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@modelcontextprotocol/sdk":"^1.32.2","@sous-io/sous-plugin-api":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*","@sous-io/sous-plugin-cli":"workspace:*",zod:"^4.4.3"},engines:{node:">=22"}};init_reporter();init_prompter();var PLUGIN_NAME24="@sous-io/sous-plugin-mcp",settingsSchema=jsonSchema31({type:"object",properties:{include:{type:"array",items:{type:"string"},description:"Only tools whose names match these globs."},exclude:{type:"array",items:{type:"string"},default:[],description:"Leaves out tools whose names match these globs."}},additionalProperties:!1}),serveInputSchema=jsonSchema31({type:"object",properties:{transport:{type:"string",enum:["stdio"],default:"stdio",description:"How the client talks to the server."}},additionalProperties:!1});function createMcpPlugin(options2={}){return definePlugin25({name:PLUGIN_NAME24,version:package_default25.version,description:"The sous mcp front end: tools generated from intents, MCP logging and elicitation.",dependsOn:{},register(sous){sous.entities.add("config-key",{id:"mcp",description:"MCP server settings: mcp.include and mcp.exclude pick tools by name, with globs.",schema:settingsSchema}),sous.services.add("mcp.tools",config2=>createMcpTools(buildTools(sous.engine.intents.list(),{...config2.get("mcp.include")===void 0?{}:{include:config2.get("mcp.include")},exclude:config2.get("mcp.exclude")??[]})),{lifetime:"config"}),sous.intents.add({intent:"mcp.serve",needsRecipeFiles:!0,summary:"Serve this project to agents over MCP",description:"Starts an MCP server on standard input and output. Every command is a tool, and each tool call runs as its own chain, with its messages sent as MCP log messages and its questions as MCP elicitation.",input:serveInputSchema,background:!0,cli:{command:["mcp"],aliases:[["mcp","serve"]],examples:["sous mcp"]},agent:{hidden:!0},async load(){let{serveMcp:serveMcp2}=await Promise.resolve().then(()=>(init_server3(),server_exports));return async(_input,ctx)=>{if(options2.transport)return IntentOutputs28.of(await serveMcp2(ctx,{transport:await options2.transport()}));let{StdioServerTransport:StdioServerTransport2}=await Promise.resolve().then(()=>(init_stdio2(),stdio_exports)),transport=new StdioServerTransport2;return process.stdin.once("end",()=>{transport.close()}),IntentOutputs28.of(await serveMcp2(ctx,{transport,handleSignals:!0}))}}})}})}var mcpPlugin=createMcpPlugin();import{definePlugin as definePlugin26}from"@sous-io/sous-plugin-api";import fs74 from"node:fs";import path99 from"node:path";import fs73 from"node:fs";import path98 from"node:path";var PLUGIN_KEYWORD="sous-plugin";function readPackageJson3(dir){try{let parsed=JSON.parse(fs73.readFileSync(path98.join(dir,"package.json"),"utf8"));return parsed!==null&&typeof parsed=="object"&&!Array.isArray(parsed)?parsed:void 0}catch{return}}function realpathOr3(target){try{return fs73.realpathSync(target)}catch{return target}}function declaredIn(pkg,name){if(pkg!==void 0)for(let section2 of["devDependencies","dependencies"]){let block=pkg[section2],range3=block!==null&&typeof block=="object"?block[name]:void 0;if(typeof range3=="string")return{section:section2,range:range3}}}function isSousPlugin(pkg){return Array.isArray(pkg.keywords)&&pkg.keywords.includes(PLUGIN_KEYWORD)}function packageNames(modules){let entries;try{entries=fs73.readdirSync(modules,{withFileTypes:!0})}catch{return[]}let names2=[];for(let entry of entries.sort((a,b)=>a.name<b.name?-1:1))if(!entry.name.startsWith("."))if(entry.name.startsWith("@"))try{for(let inner of fs73.readdirSync(path98.join(modules,entry.name)).sort())inner.startsWith(".")||names2.push(`${entry.name}/${inner}`)}catch{}else names2.push(entry.name);return names2}function readInstalled(modules,declaring){let installed2=[];for(let name of packageNames(modules)){let location=path98.join(modules,...name.split("/")),pkg=readPackageJson3(location);if(pkg===void 0)continue;let declared=declaredIn(declaring,name);installed2.push({name,version:typeof pkg.version=="string"?pkg.version:"unknown",location,realPath:realpathOr3(location),isSousPlugin:isSousPlugin(pkg),...declared===void 0?{}:{declared}})}return installed2}function packageManagerField(pkg,manager){let field=pkg?.packageManager;if(typeof field!="string")return;let match2=/^([^@]+)@([^+]+)/.exec(field);return match2!==null&&match2[1]===manager?match2[2]:void 0}function packageManagerName(pkg){let field=pkg?.packageManager;return typeof field=="string"?/^([^@]+)@/.exec(field)?.[1]:void 0}var OTHER_MANAGER_FILES=["yarn.lock",".yarnrc.yml",".pnp.cjs","pnpm-lock.yaml","pnpm-workspace.yaml","bun.lock","bun.lockb","deno.lock"];function lastLine(output){let line=output.trim().split(/\r?\n/).pop()?.trim();return line===void 0||line.length===0?void 0:line}var PLUGIN="@sous-io/sous-plugin-npm",FORMER_PLUGIN="@sous-io/plugin-npm";function commandOf(ctx){return(ctx.config.get(["plugins","options",PLUGIN])??ctx.config.get(["plugins","options",FORMER_PLUGIN]))?.command??"npm"}function has3(dir,file2){return fs74.existsSync(path99.join(dir,file2))}var npmManager={id:"npm",description:"npm, the package manager that comes with Node.js.",async detect(projectRoot){let pkg=readPackageJson3(projectRoot),named=packageManagerName(pkg),version2=packageManagerField(pkg,"npm");if(named==="npm"||has3(projectRoot,"package-lock.json")||has3(projectRoot,"npm-shrinkwrap.json"))return{id:"npm",detected:!0,...version2===void 0?{}:{version:version2}};if(!(named!==void 0||OTHER_MANAGER_FILES.some(file2=>has3(projectRoot,file2))))return{id:"npm",detected:!1}},async installed(scope,projectRoot,ctx){if(scope==="project")return projectRoot===void 0?[]:readInstalled(path99.join(projectRoot,"node_modules"),readPackageJson3(projectRoot));let root=await npmManager.globalRoot?.(ctx);return root===void 0?[]:readInstalled(root)},async globalRoot(ctx){try{let result=await ctx.services.get("host.processes").run(commandOf(ctx),["root","-g"],{label:"npm root -g",windowsShell:!0});return result.exitCode===0?lastLine(result.stdout):void 0}catch{return}},addCommand(specs,options2){return{command:"npm",args:["i",...options2.section==="devDependencies"?["-D","-E"]:["-E"],...specs],cwd:options2.cwd}},globalInstallCommand(specs){return{command:"npm",args:["i","-g",...specs]}},installCommand(options2){return{command:"npm",args:["install"],cwd:options2.cwd}},afterInstallScript:"prepare"};var package_default26={name:"@sous-io/sous-plugin-npm",version:"1.1.4",description:"A package-manager entity for npm.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-update":"workspace:*","@sous-io/sous-plugin-host":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME25="@sous-io/sous-plugin-npm",npmPlugin=definePlugin26({name:PLUGIN_NAME25,version:package_default26.version,description:"A package-manager entity for npm.",dependsOn:{"@sous-io/sous-plugin-update":`^${package_default26.version}`,"@sous-io/sous-plugin-host":`^${package_default26.version}`},register(sous){sous.entities.add("package-manager",npmManager)}});import{definePlugin as definePlugin27}from"@sous-io/sous-plugin-api";import fs76 from"node:fs";import path101 from"node:path";import fs75 from"node:fs";import path100 from"node:path";var PLUGIN_KEYWORD2="sous-plugin";function readPackageJson4(dir){try{let parsed=JSON.parse(fs75.readFileSync(path100.join(dir,"package.json"),"utf8"));return parsed!==null&&typeof parsed=="object"&&!Array.isArray(parsed)?parsed:void 0}catch{return}}function realpathOr4(target){try{return fs75.realpathSync(target)}catch{return target}}function findUp(start2,test){let dir=path100.resolve(start2);for(;;){if(test(dir))return dir;let parent=path100.dirname(dir);if(parent===dir)return;dir=parent}}function declaredIn2(pkg,name){if(pkg!==void 0)for(let section2 of["devDependencies","dependencies"]){let block=pkg[section2],range3=block!==null&&typeof block=="object"?block[name]:void 0;if(typeof range3=="string")return{section:section2,range:range3}}}function isSousPlugin2(pkg){return Array.isArray(pkg.keywords)&&pkg.keywords.includes(PLUGIN_KEYWORD2)}function packageNames2(modules){let entries;try{entries=fs75.readdirSync(modules,{withFileTypes:!0})}catch{return[]}let names2=[];for(let entry of entries.sort((a,b)=>a.name<b.name?-1:1))if(!entry.name.startsWith("."))if(entry.name.startsWith("@"))try{for(let inner of fs75.readdirSync(path100.join(modules,entry.name)).sort())inner.startsWith(".")||names2.push(`${entry.name}/${inner}`)}catch{}else names2.push(entry.name);return names2}function readInstalled2(modules,declaring){let installed2=[];for(let name of packageNames2(modules)){let location=path100.join(modules,...name.split("/")),pkg=readPackageJson4(location);if(pkg===void 0)continue;let declared=declaredIn2(declaring,name);installed2.push({name,version:typeof pkg.version=="string"?pkg.version:"unknown",location,realPath:realpathOr4(location),isSousPlugin:isSousPlugin2(pkg),...declared===void 0?{}:{declared}})}return installed2}function packageManagerField2(pkg,manager){let field=pkg?.packageManager;if(typeof field!="string")return;let match2=/^([^@]+)@([^+]+)/.exec(field);return match2!==null&&match2[1]===manager?match2[2]:void 0}function packageManagerName2(pkg){let field=pkg?.packageManager;return typeof field=="string"?/^([^@]+)@/.exec(field)?.[1]:void 0}function lastLine2(output){let line=output.trim().split(/\r?\n/).pop()?.trim();return line===void 0||line.length===0?void 0:line}var PLUGIN2="@sous-io/sous-plugin-pnpm",FORMER_PLUGIN2="@sous-io/plugin-pnpm",WORKSPACE_FILE="pnpm-workspace.yaml";function commandOf2(ctx){return(ctx.config.get(["plugins","options",PLUGIN2])??ctx.config.get(["plugins","options",FORMER_PLUGIN2]))?.command??"pnpm"}function has4(dir,file2){return fs76.existsSync(path101.join(dir,file2))}var pnpmManager={id:"pnpm",description:"pnpm, with its workspaces.",async detect(projectRoot){let pkg=readPackageJson4(projectRoot);if(packageManagerName2(pkg)!=="pnpm"&&!has4(projectRoot,"pnpm-lock.yaml")&&!has4(projectRoot,WORKSPACE_FILE))return;let version2=packageManagerField2(pkg,"pnpm"),workspaceRoot=findUp(projectRoot,dir=>has4(dir,WORKSPACE_FILE));return{id:"pnpm",detected:!0,...version2===void 0?{}:{version:version2},...workspaceRoot===void 0?{}:{workspaceRoot}}},async installed(scope,projectRoot,ctx){if(scope==="project")return projectRoot===void 0?[]:readInstalled2(path101.join(projectRoot,"node_modules"),readPackageJson4(projectRoot));let root=await pnpmManager.globalRoot?.(ctx);return root===void 0?[]:readInstalled2(root)},async globalRoot(ctx){try{let result=await ctx.services.get("host.processes").run(commandOf2(ctx),["root","-g"],{label:"pnpm root -g",windowsShell:!0});return result.exitCode===0?lastLine2(result.stdout):void 0}catch{return}},addCommand(specs,options2){return{command:"pnpm",args:["add",...[...options2.section==="devDependencies"?["-D"]:[],"-E",...options2.workspaceRoot?["-w"]:[]],...specs],cwd:options2.cwd}},globalInstallCommand(specs){return{command:"pnpm",args:["add","-g",...specs]}},installCommand(options2){return{command:"pnpm",args:["install",...options2.updateLockfile===!0?["--no-frozen-lockfile"]:[]],cwd:options2.cwd}},afterInstallScript:"prepare"};var package_default27={name:"@sous-io/sous-plugin-pnpm",version:"1.1.4",description:"A package-manager entity for pnpm.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-update":"workspace:*","@sous-io/sous-plugin-host":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME26="@sous-io/sous-plugin-pnpm",pnpmPlugin=definePlugin27({name:PLUGIN_NAME26,version:package_default27.version,description:"A package-manager entity for pnpm.",dependsOn:{"@sous-io/sous-plugin-update":`^${package_default27.version}`,"@sous-io/sous-plugin-host":`^${package_default27.version}`},register(sous){sous.entities.add("package-manager",pnpmManager)}});import{definePlugin as definePlugin28}from"@sous-io/sous-plugin-api";import fs79 from"node:fs";import path104 from"node:path";import fs77 from"node:fs";import path102 from"node:path";var PLUGIN_KEYWORD3="sous-plugin";function readPackageJson5(dir){try{let parsed=JSON.parse(fs77.readFileSync(path102.join(dir,"package.json"),"utf8"));return parsed!==null&&typeof parsed=="object"&&!Array.isArray(parsed)?parsed:void 0}catch{return}}function realpathOr5(target){try{return fs77.realpathSync(target)}catch{return target}}function findUp2(start2,test){let dir=path102.resolve(start2);for(;;){if(test(dir))return dir;let parent=path102.dirname(dir);if(parent===dir)return;dir=parent}}function declaredIn3(pkg,name){if(pkg!==void 0)for(let section2 of["devDependencies","dependencies"]){let block=pkg[section2],range3=block!==null&&typeof block=="object"?block[name]:void 0;if(typeof range3=="string")return{section:section2,range:range3}}}function isSousPlugin3(pkg){return Array.isArray(pkg.keywords)&&pkg.keywords.includes(PLUGIN_KEYWORD3)}function packageNames3(modules){let entries;try{entries=fs77.readdirSync(modules,{withFileTypes:!0})}catch{return[]}let names2=[];for(let entry of entries.sort((a,b)=>a.name<b.name?-1:1))if(!entry.name.startsWith("."))if(entry.name.startsWith("@"))try{for(let inner of fs77.readdirSync(path102.join(modules,entry.name)).sort())inner.startsWith(".")||names2.push(`${entry.name}/${inner}`)}catch{}else names2.push(entry.name);return names2}function readInstalled3(modules,declaring){let installed2=[];for(let name of packageNames3(modules)){let location=path102.join(modules,...name.split("/")),pkg=readPackageJson5(location);if(pkg===void 0)continue;let declared=declaredIn3(declaring,name);installed2.push({name,version:typeof pkg.version=="string"?pkg.version:"unknown",location,realPath:realpathOr5(location),isSousPlugin:isSousPlugin3(pkg),...declared===void 0?{}:{declared}})}return installed2}function packageManagerField3(pkg,manager){let field=pkg?.packageManager;if(typeof field!="string")return;let match2=/^([^@]+)@([^+]+)/.exec(field);return match2!==null&&match2[1]===manager?match2[2]:void 0}function packageManagerName3(pkg){let field=pkg?.packageManager;return typeof field=="string"?/^([^@]+)@/.exec(field)?.[1]:void 0}function lastLine3(output){let line=output.trim().split(/\r?\n/).pop()?.trim();return line===void 0||line.length===0?void 0:line}import{createRequire as createRequire3}from"node:module";import fs78 from"node:fs";import path103 from"node:path";import{pathToFileURL as pathToFileURL7}from"node:url";var PNP_FILE=".pnp.cjs";function findPnpFile(start2){let dir=findUp2(start2,candidate=>fs78.existsSync(path103.join(candidate,PNP_FILE)));return dir===void 0?void 0:path103.join(dir,PNP_FILE)}function loadPnp(file2){try{let api=createRequire3(file2)(file2);return api!==void 0&&typeof api.resolveRequest=="function"?api:void 0}catch{return}}function versionOfReference(reference){return/npm:([^#:]+)$/.exec(reference)?.[1]??"unknown"}function inZip(location){return/\.zip(\/|$)/.test(location)}function pnpInstalled(projectRoot){let file2=findPnpFile(projectRoot);if(file2===void 0)return[];let api=loadPnp(file2),locator=api?.findPackageLocator(`${projectRoot}/`)??null,info=locator===null?null:api?.getPackageInformation(locator)??null;if(api===void 0||info===null)return lockfileInstalled(projectRoot,file2);let declaring=readPackageJson5(projectRoot),installed2=[];for(let[name,entry]of[...info.packageDependencies].sort(([a],[b])=>a<b?-1:1)){if(entry===null)continue;let reference=typeof entry=="string"?entry:entry[1],dependency=api.getPackageInformation({name,reference});if(dependency===null)continue;let location=dependency.packageLocation.replace(/\/$/,""),pkg=inZip(location)?void 0:readPackageJson5(location),declared=declaredIn3(declaring,name);installed2.push({name,version:typeof pkg?.version=="string"?pkg.version:versionOfReference(reference),location,realPath:realpathOr5(location),isSousPlugin:pkg!==void 0&&isSousPlugin3(pkg),...declared===void 0?{}:{declared}})}return installed2}function lockfileInstalled(projectRoot,pnpFile){let declaring=readPackageJson5(projectRoot),lockfile="";try{lockfile=fs78.readFileSync(path103.join(path103.dirname(pnpFile),"yarn.lock"),"utf8")}catch{}let names2=new Set;for(let section2 of["devDependencies","dependencies"]){let block=declaring?.[section2];if(block!==null&&typeof block=="object")for(let name of Object.keys(block))names2.add(name)}return[...names2].sort().flatMap(name=>{let declared=declaredIn3(declaring,name);return declared===void 0?[]:[{name,version:yarnLockVersion(lockfile,name,declared.range)??"unknown",location:pnpFile,realPath:realpathOr5(pnpFile),isSousPlugin:!1,declared}]})}function yarnLockVersion(lockfile,name,range3){let prefix=`${name}@`,wanted=new Set([`${prefix}${range3}`,`${prefix}npm:${range3}`]),entries=[],entry;for(let line of lockfile.split(/\r?\n/)){if(/^[^\s#].*:$/.test(line)){let descriptors=line.slice(0,-1).split(",").map(part=>part.trim().replace(/^"|"$/g,"")).filter(descriptor=>descriptor.startsWith(prefix));entry=descriptors.length>0?{descriptors}:void 0,entry!==void 0&&entries.push(entry);continue}let version2=/^\s+version:\s*"?([^"\s]+)"?\s*$/.exec(line);entry!==void 0&&version2!==null&&entry.version===void 0&&(entry.version=version2[1])}let exact=entries.find(candidate=>candidate.descriptors.some(descriptor=>wanted.has(descriptor)));if(exact!==void 0)return exact.version;let versions=new Set(entries.flatMap(candidate=>candidate.version??[]));return versions.size===1?[...versions][0]:void 0}function isBare(specifier){return!/^(\.{0,2}\/|[a-z][a-z0-9+.-]*:|\.\.?$)/i.test(specifier)&&!path103.isAbsolute(specifier)}var yarnPnpLocator={id:"yarn-pnp",locate(specifier,context){let root=context.project?.root;if(root===void 0||!isBare(specifier))return;let file2=findPnpFile(root),api=file2===void 0?void 0:loadPnp(file2);if(api!==void 0)try{let resolved=api.resolveRequest(specifier,`${root}/`);return resolved===null||inZip(resolved)?void 0:pathToFileURL7(resolved)}catch{return}}};var PLUGIN3="@sous-io/sous-plugin-yarn",FORMER_PLUGIN3="@sous-io/plugin-yarn";function commandOf3(ctx){return(ctx.config.get(["plugins","options",PLUGIN3])??ctx.config.get(["plugins","options",FORMER_PLUGIN3]))?.command??"yarn"}function has5(dir,file2){return fs79.existsSync(path104.join(dir,file2))}function hasWorkspaces(dir){let pkg=readPackageJson5(dir);return pkg!==void 0&&"workspaces"in pkg}function isBerry(dir){if(has5(dir,".yarnrc.yml")||has5(dir,PNP_FILE))return!0;let version2=packageManagerField3(readPackageJson5(dir),"yarn");if(version2!==void 0)return!version2.startsWith("1.");try{return/^__metadata:/m.test(fs79.readFileSync(path104.join(dir,"yarn.lock"),"utf8"))}catch{return!1}}var yarnManager={id:"yarn",description:"Yarn, Classic (1.x) and Berry (2 and later), with Plug'n'Play.",async detect(projectRoot){let pkg=readPackageJson5(projectRoot);if(packageManagerName3(pkg)!=="yarn"&&!has5(projectRoot,"yarn.lock")&&!has5(projectRoot,".yarnrc.yml")&&!has5(projectRoot,PNP_FILE))return;let version2=packageManagerField3(pkg,"yarn"),workspaceRoot=findUp2(projectRoot,hasWorkspaces),pnpFile=findPnpFile(projectRoot);return{id:isBerry(projectRoot)?"yarn@berry":"yarn",detected:!0,...version2===void 0?{}:{version:version2},...workspaceRoot===void 0?{}:{workspaceRoot},...pnpFile===void 0?{}:{pnpRoot:path104.dirname(pnpFile)}}},async installed(scope,projectRoot,ctx){if(scope==="project")return projectRoot===void 0?[]:findPnpFile(projectRoot)!==void 0&&!has5(projectRoot,"node_modules")?pnpInstalled(projectRoot):readInstalled3(path104.join(projectRoot,"node_modules"),readPackageJson5(projectRoot));let root=await yarnManager.globalRoot?.(ctx);return root===void 0?[]:readInstalled3(root)},async globalRoot(ctx){try{let result=await ctx.services.get("host.processes").run(commandOf3(ctx),["global","dir"],{label:"yarn global dir",windowsShell:!0}),dir=result.exitCode===0?lastLine3(result.stdout):void 0;return dir===void 0?void 0:path104.join(dir,"node_modules")}catch{return}},addCommand(specs,options2){let classicRoot=options2.workspaceRoot&&!isBerry(options2.cwd);return{command:"yarn",args:["add",...[...options2.section==="devDependencies"?["-D"]:[],"-E",...classicRoot?["-W"]:[]],...specs],cwd:options2.cwd}},globalInstallCommand(specs){return{command:"yarn",args:["global","add",...specs]}},installCommand(options2){return{command:"yarn",args:["install",...options2.updateLockfile===!0&&isBerry(options2.cwd)?["--no-immutable"]:[]],cwd:options2.cwd}},afterInstallScript:"postinstall"};var package_default28={name:"@sous-io/sous-plugin-yarn",version:"1.1.4",description:"A package-manager entity for Yarn, and Yarn Plug'n'Play's plugin locator.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-update":"workspace:*","@sous-io/sous-plugin-host":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME27="@sous-io/sous-plugin-yarn",yarnPlugin=definePlugin28({name:PLUGIN_NAME27,version:package_default28.version,description:"A package-manager entity for Yarn, and Yarn Plug'n'Play's plugin locator.",dependsOn:{"@sous-io/sous-plugin-update":`^${package_default28.version}`,"@sous-io/sous-plugin-host":`^${package_default28.version}`},register(sous){sous.entities.add("package-manager",yarnManager),sous.entities.add("plugin-locator",yarnPnpLocator)}});import{definePlugin as definePlugin29}from"@sous-io/sous-plugin-api";import{ConfigError as ConfigError67}from"@sous-io/sous-plugin-api";import{tmpdir}from"node:os";function tokenFromOutput(output){if(output.exitCode===0)return singleWord(output.stdout)}function singleWord(text){let body2=text.replace(/\r?\n$/,"");if(!(body2.length===0||/\s/.test(body2)))return body2}var TOKEN_COMMAND_TIMEOUT_MS=1e4;function commandDirectory(ctx){return ctx.project?.root??tmpdir()}function tokenOf(source){return async(repository,ctx)=>{let found=await source.find(repository,ctx);return"token"in found?found.token:void 0}}function listed(names2){return names2.length<=1?names2[0]??"":`${names2.slice(0,-1).join(", ")} and ${names2[names2.length-1]}`}function envTokenSource(options2){let{variables}=options2,source={id:"env",label:listed(variables),async find(_repository,ctx){for(let name of variables){let value=ctx.env[name]?.trim();if(value!==void 0&&value.length>0)return{token:{value,source:name}}}return{missing:`${listed(variables)} unset`}},token:async()=>{},fix:()=>variables.length===0?void 0:`export ${variables[0]}=<${options2.tokenHint}>`};return source.token=tokenOf(source),source}function gitCredentialTokenSource(){let source={id:"git-credential",label:"git credential fill",async find(repository,ctx){let missing={missing:`git has no stored credential for ${repository.host}`};if(!ctx.services.has("git.runner"))return missing;let result;try{result=await ctx.services.get("git.runner").run(["credential","fill"],{cwd:commandDirectory(ctx),input:`protocol=https
1182
+ `)}function toolInputSchema(definition2){let schema=toJsonSchema3(definition2.input);return schema?schema.type===void 0&&schema.properties!==void 0?{...schema,type:"object"}:{...schema}:{type:"object",properties:{}}}function toolOutputSchema(definition2){let schema=toJsonSchema3(definition2.output);return schema?.type==="object"?{...schema}:void 0}function matchesGlob(name,glob){let pattern=glob.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${pattern}$`).test(name)}function buildTools(intents,settings={}){let tools=[],warnings=[],owners=new Map,include=settings.include,exclude=settings.exclude??[];for(let info of intents){let definition2=info.definition;if(!isAgentVisible(definition2))continue;let name=toolName(definition2);if(include&&!include.some(glob=>matchesGlob(name,glob))||exclude.some(glob=>matchesGlob(name,glob)))continue;let owner=owners.get(name);if(owner){warnings.push(`Two intents claim the MCP tool "${name}": "${owner.definition.intent}" (${owner.plugin}) and "${definition2.intent}" (${info.plugin}). The first keeps it; set agent.tool on one of them.`);continue}owners.set(name,info);let outputSchema2=toolOutputSchema(definition2);tools.push({name,intent:definition2.intent,description:toolDescription(definition2),inputSchema:toolInputSchema(definition2),...outputSchema2?{outputSchema:outputSchema2}:{}})}return{tools,warnings}}function createMcpTools(set2){let byName=new Map(set2.tools.map(tool=>[tool.name,tool]));return{warnings:set2.warnings,list:()=>[...set2.tools],toRequest(tool,args){let found=byName.get(tool);if(!found)throw new InputError9(tool,[{path:"",message:`No MCP tool is named "${tool}".`}]);return{intent:found.intent,input:{...args}}}}}var package_default25={name:"@sous-io/sous-plugin-mcp",version:"1.1.6",description:"The sous mcp front end: tools generated from intents, MCP logging and elicitation.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@modelcontextprotocol/sdk":"^1.32.2","@sous-io/sous-plugin-api":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*","@sous-io/sous-plugin-cli":"workspace:*",zod:"^4.4.3"},engines:{node:">=22"}};init_reporter();init_prompter();var PLUGIN_NAME24="@sous-io/sous-plugin-mcp",settingsSchema=jsonSchema31({type:"object",properties:{include:{type:"array",items:{type:"string"},description:"Only tools whose names match these globs."},exclude:{type:"array",items:{type:"string"},default:[],description:"Leaves out tools whose names match these globs."}},additionalProperties:!1}),serveInputSchema=jsonSchema31({type:"object",properties:{transport:{type:"string",enum:["stdio"],default:"stdio",description:"How the client talks to the server."}},additionalProperties:!1});function createMcpPlugin(options2={}){return definePlugin25({name:PLUGIN_NAME24,version:package_default25.version,description:"The sous mcp front end: tools generated from intents, MCP logging and elicitation.",dependsOn:{},register(sous){sous.entities.add("config-key",{id:"mcp",description:"MCP server settings: mcp.include and mcp.exclude pick tools by name, with globs.",schema:settingsSchema}),sous.services.add("mcp.tools",config2=>createMcpTools(buildTools(sous.engine.intents.list(),{...config2.get("mcp.include")===void 0?{}:{include:config2.get("mcp.include")},exclude:config2.get("mcp.exclude")??[]})),{lifetime:"config"}),sous.intents.add({intent:"mcp.serve",needsRecipeFiles:!0,summary:"Serve this project to agents over MCP",description:"Starts an MCP server on standard input and output. Every command is a tool, and each tool call runs as its own chain, with its messages sent as MCP log messages and its questions as MCP elicitation.",input:serveInputSchema,background:!0,cli:{command:["mcp"],aliases:[["mcp","serve"]],examples:["sous mcp"]},agent:{hidden:!0},async load(){let{serveMcp:serveMcp2}=await Promise.resolve().then(()=>(init_server3(),server_exports));return async(_input,ctx)=>{if(options2.transport)return IntentOutputs28.of(await serveMcp2(ctx,{transport:await options2.transport()}));let{StdioServerTransport:StdioServerTransport2}=await Promise.resolve().then(()=>(init_stdio2(),stdio_exports)),transport=new StdioServerTransport2;return process.stdin.once("end",()=>{transport.close()}),IntentOutputs28.of(await serveMcp2(ctx,{transport,handleSignals:!0}))}}})}})}var mcpPlugin=createMcpPlugin();import{definePlugin as definePlugin26}from"@sous-io/sous-plugin-api";import fs74 from"node:fs";import path99 from"node:path";import fs73 from"node:fs";import path98 from"node:path";var PLUGIN_KEYWORD="sous-plugin";function readPackageJson3(dir){try{let parsed=JSON.parse(fs73.readFileSync(path98.join(dir,"package.json"),"utf8"));return parsed!==null&&typeof parsed=="object"&&!Array.isArray(parsed)?parsed:void 0}catch{return}}function realpathOr3(target){try{return fs73.realpathSync(target)}catch{return target}}function declaredIn(pkg,name){if(pkg!==void 0)for(let section2 of["devDependencies","dependencies"]){let block=pkg[section2],range3=block!==null&&typeof block=="object"?block[name]:void 0;if(typeof range3=="string")return{section:section2,range:range3}}}function isSousPlugin(pkg){return Array.isArray(pkg.keywords)&&pkg.keywords.includes(PLUGIN_KEYWORD)}function packageNames(modules){let entries;try{entries=fs73.readdirSync(modules,{withFileTypes:!0})}catch{return[]}let names2=[];for(let entry of entries.sort((a,b)=>a.name<b.name?-1:1))if(!entry.name.startsWith("."))if(entry.name.startsWith("@"))try{for(let inner of fs73.readdirSync(path98.join(modules,entry.name)).sort())inner.startsWith(".")||names2.push(`${entry.name}/${inner}`)}catch{}else names2.push(entry.name);return names2}function readInstalled(modules,declaring){let installed2=[];for(let name of packageNames(modules)){let location=path98.join(modules,...name.split("/")),pkg=readPackageJson3(location);if(pkg===void 0)continue;let declared=declaredIn(declaring,name);installed2.push({name,version:typeof pkg.version=="string"?pkg.version:"unknown",location,realPath:realpathOr3(location),isSousPlugin:isSousPlugin(pkg),...declared===void 0?{}:{declared}})}return installed2}function packageManagerField(pkg,manager){let field=pkg?.packageManager;if(typeof field!="string")return;let match2=/^([^@]+)@([^+]+)/.exec(field);return match2!==null&&match2[1]===manager?match2[2]:void 0}function packageManagerName(pkg){let field=pkg?.packageManager;return typeof field=="string"?/^([^@]+)@/.exec(field)?.[1]:void 0}var OTHER_MANAGER_FILES=["yarn.lock",".yarnrc.yml",".pnp.cjs","pnpm-lock.yaml","pnpm-workspace.yaml","bun.lock","bun.lockb","deno.lock"];function lastLine(output){let line=output.trim().split(/\r?\n/).pop()?.trim();return line===void 0||line.length===0?void 0:line}var PLUGIN="@sous-io/sous-plugin-npm",FORMER_PLUGIN="@sous-io/plugin-npm";function commandOf(ctx){return(ctx.config.get(["plugins","options",PLUGIN])??ctx.config.get(["plugins","options",FORMER_PLUGIN]))?.command??"npm"}function has3(dir,file2){return fs74.existsSync(path99.join(dir,file2))}var npmManager={id:"npm",description:"npm, the package manager that comes with Node.js.",async detect(projectRoot){let pkg=readPackageJson3(projectRoot),named=packageManagerName(pkg),version2=packageManagerField(pkg,"npm");if(named==="npm"||has3(projectRoot,"package-lock.json")||has3(projectRoot,"npm-shrinkwrap.json"))return{id:"npm",detected:!0,...version2===void 0?{}:{version:version2}};if(!(named!==void 0||OTHER_MANAGER_FILES.some(file2=>has3(projectRoot,file2))))return{id:"npm",detected:!1}},async installed(scope,projectRoot,ctx){if(scope==="project")return projectRoot===void 0?[]:readInstalled(path99.join(projectRoot,"node_modules"),readPackageJson3(projectRoot));let root=await npmManager.globalRoot?.(ctx);return root===void 0?[]:readInstalled(root)},async globalRoot(ctx){try{let result=await ctx.services.get("host.processes").run(commandOf(ctx),["root","-g"],{label:"npm root -g",windowsShell:!0});return result.exitCode===0?lastLine(result.stdout):void 0}catch{return}},addCommand(specs,options2){return{command:"npm",args:["i",...options2.section==="devDependencies"?["-D","-E"]:["-E"],...specs],cwd:options2.cwd}},globalInstallCommand(specs){return{command:"npm",args:["i","-g",...specs]}},installCommand(options2){return{command:"npm",args:["install"],cwd:options2.cwd}},afterInstallScript:"prepare"};var package_default26={name:"@sous-io/sous-plugin-npm",version:"1.1.6",description:"A package-manager entity for npm.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-update":"workspace:*","@sous-io/sous-plugin-host":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME25="@sous-io/sous-plugin-npm",npmPlugin=definePlugin26({name:PLUGIN_NAME25,version:package_default26.version,description:"A package-manager entity for npm.",dependsOn:{"@sous-io/sous-plugin-update":`^${package_default26.version}`,"@sous-io/sous-plugin-host":`^${package_default26.version}`},register(sous){sous.entities.add("package-manager",npmManager)}});import{definePlugin as definePlugin27}from"@sous-io/sous-plugin-api";import fs76 from"node:fs";import path101 from"node:path";import fs75 from"node:fs";import path100 from"node:path";var PLUGIN_KEYWORD2="sous-plugin";function readPackageJson4(dir){try{let parsed=JSON.parse(fs75.readFileSync(path100.join(dir,"package.json"),"utf8"));return parsed!==null&&typeof parsed=="object"&&!Array.isArray(parsed)?parsed:void 0}catch{return}}function realpathOr4(target){try{return fs75.realpathSync(target)}catch{return target}}function findUp(start2,test){let dir=path100.resolve(start2);for(;;){if(test(dir))return dir;let parent=path100.dirname(dir);if(parent===dir)return;dir=parent}}function declaredIn2(pkg,name){if(pkg!==void 0)for(let section2 of["devDependencies","dependencies"]){let block=pkg[section2],range3=block!==null&&typeof block=="object"?block[name]:void 0;if(typeof range3=="string")return{section:section2,range:range3}}}function isSousPlugin2(pkg){return Array.isArray(pkg.keywords)&&pkg.keywords.includes(PLUGIN_KEYWORD2)}function packageNames2(modules){let entries;try{entries=fs75.readdirSync(modules,{withFileTypes:!0})}catch{return[]}let names2=[];for(let entry of entries.sort((a,b)=>a.name<b.name?-1:1))if(!entry.name.startsWith("."))if(entry.name.startsWith("@"))try{for(let inner of fs75.readdirSync(path100.join(modules,entry.name)).sort())inner.startsWith(".")||names2.push(`${entry.name}/${inner}`)}catch{}else names2.push(entry.name);return names2}function readInstalled2(modules,declaring){let installed2=[];for(let name of packageNames2(modules)){let location=path100.join(modules,...name.split("/")),pkg=readPackageJson4(location);if(pkg===void 0)continue;let declared=declaredIn2(declaring,name);installed2.push({name,version:typeof pkg.version=="string"?pkg.version:"unknown",location,realPath:realpathOr4(location),isSousPlugin:isSousPlugin2(pkg),...declared===void 0?{}:{declared}})}return installed2}function packageManagerField2(pkg,manager){let field=pkg?.packageManager;if(typeof field!="string")return;let match2=/^([^@]+)@([^+]+)/.exec(field);return match2!==null&&match2[1]===manager?match2[2]:void 0}function packageManagerName2(pkg){let field=pkg?.packageManager;return typeof field=="string"?/^([^@]+)@/.exec(field)?.[1]:void 0}function lastLine2(output){let line=output.trim().split(/\r?\n/).pop()?.trim();return line===void 0||line.length===0?void 0:line}var PLUGIN2="@sous-io/sous-plugin-pnpm",FORMER_PLUGIN2="@sous-io/plugin-pnpm",WORKSPACE_FILE="pnpm-workspace.yaml";function commandOf2(ctx){return(ctx.config.get(["plugins","options",PLUGIN2])??ctx.config.get(["plugins","options",FORMER_PLUGIN2]))?.command??"pnpm"}function has4(dir,file2){return fs76.existsSync(path101.join(dir,file2))}var pnpmManager={id:"pnpm",description:"pnpm, with its workspaces.",async detect(projectRoot){let pkg=readPackageJson4(projectRoot);if(packageManagerName2(pkg)!=="pnpm"&&!has4(projectRoot,"pnpm-lock.yaml")&&!has4(projectRoot,WORKSPACE_FILE))return;let version2=packageManagerField2(pkg,"pnpm"),workspaceRoot=findUp(projectRoot,dir=>has4(dir,WORKSPACE_FILE));return{id:"pnpm",detected:!0,...version2===void 0?{}:{version:version2},...workspaceRoot===void 0?{}:{workspaceRoot}}},async installed(scope,projectRoot,ctx){if(scope==="project")return projectRoot===void 0?[]:readInstalled2(path101.join(projectRoot,"node_modules"),readPackageJson4(projectRoot));let root=await pnpmManager.globalRoot?.(ctx);return root===void 0?[]:readInstalled2(root)},async globalRoot(ctx){try{let result=await ctx.services.get("host.processes").run(commandOf2(ctx),["root","-g"],{label:"pnpm root -g",windowsShell:!0});return result.exitCode===0?lastLine2(result.stdout):void 0}catch{return}},addCommand(specs,options2){return{command:"pnpm",args:["add",...[...options2.section==="devDependencies"?["-D"]:[],"-E",...options2.workspaceRoot?["-w"]:[]],...specs],cwd:options2.cwd}},globalInstallCommand(specs){return{command:"pnpm",args:["add","-g",...specs]}},installCommand(options2){return{command:"pnpm",args:["install",...options2.updateLockfile===!0?["--no-frozen-lockfile"]:[]],cwd:options2.cwd}},afterInstallScript:"prepare"};var package_default27={name:"@sous-io/sous-plugin-pnpm",version:"1.1.6",description:"A package-manager entity for pnpm.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-update":"workspace:*","@sous-io/sous-plugin-host":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME26="@sous-io/sous-plugin-pnpm",pnpmPlugin=definePlugin27({name:PLUGIN_NAME26,version:package_default27.version,description:"A package-manager entity for pnpm.",dependsOn:{"@sous-io/sous-plugin-update":`^${package_default27.version}`,"@sous-io/sous-plugin-host":`^${package_default27.version}`},register(sous){sous.entities.add("package-manager",pnpmManager)}});import{definePlugin as definePlugin28}from"@sous-io/sous-plugin-api";import fs79 from"node:fs";import path104 from"node:path";import fs77 from"node:fs";import path102 from"node:path";var PLUGIN_KEYWORD3="sous-plugin";function readPackageJson5(dir){try{let parsed=JSON.parse(fs77.readFileSync(path102.join(dir,"package.json"),"utf8"));return parsed!==null&&typeof parsed=="object"&&!Array.isArray(parsed)?parsed:void 0}catch{return}}function realpathOr5(target){try{return fs77.realpathSync(target)}catch{return target}}function findUp2(start2,test){let dir=path102.resolve(start2);for(;;){if(test(dir))return dir;let parent=path102.dirname(dir);if(parent===dir)return;dir=parent}}function declaredIn3(pkg,name){if(pkg!==void 0)for(let section2 of["devDependencies","dependencies"]){let block=pkg[section2],range3=block!==null&&typeof block=="object"?block[name]:void 0;if(typeof range3=="string")return{section:section2,range:range3}}}function isSousPlugin3(pkg){return Array.isArray(pkg.keywords)&&pkg.keywords.includes(PLUGIN_KEYWORD3)}function packageNames3(modules){let entries;try{entries=fs77.readdirSync(modules,{withFileTypes:!0})}catch{return[]}let names2=[];for(let entry of entries.sort((a,b)=>a.name<b.name?-1:1))if(!entry.name.startsWith("."))if(entry.name.startsWith("@"))try{for(let inner of fs77.readdirSync(path102.join(modules,entry.name)).sort())inner.startsWith(".")||names2.push(`${entry.name}/${inner}`)}catch{}else names2.push(entry.name);return names2}function readInstalled3(modules,declaring){let installed2=[];for(let name of packageNames3(modules)){let location=path102.join(modules,...name.split("/")),pkg=readPackageJson5(location);if(pkg===void 0)continue;let declared=declaredIn3(declaring,name);installed2.push({name,version:typeof pkg.version=="string"?pkg.version:"unknown",location,realPath:realpathOr5(location),isSousPlugin:isSousPlugin3(pkg),...declared===void 0?{}:{declared}})}return installed2}function packageManagerField3(pkg,manager){let field=pkg?.packageManager;if(typeof field!="string")return;let match2=/^([^@]+)@([^+]+)/.exec(field);return match2!==null&&match2[1]===manager?match2[2]:void 0}function packageManagerName3(pkg){let field=pkg?.packageManager;return typeof field=="string"?/^([^@]+)@/.exec(field)?.[1]:void 0}function lastLine3(output){let line=output.trim().split(/\r?\n/).pop()?.trim();return line===void 0||line.length===0?void 0:line}import{createRequire as createRequire3}from"node:module";import fs78 from"node:fs";import path103 from"node:path";import{pathToFileURL as pathToFileURL7}from"node:url";var PNP_FILE=".pnp.cjs";function findPnpFile(start2){let dir=findUp2(start2,candidate=>fs78.existsSync(path103.join(candidate,PNP_FILE)));return dir===void 0?void 0:path103.join(dir,PNP_FILE)}function loadPnp(file2){try{let api=createRequire3(file2)(file2);return api!==void 0&&typeof api.resolveRequest=="function"?api:void 0}catch{return}}function versionOfReference(reference){return/npm:([^#:]+)$/.exec(reference)?.[1]??"unknown"}function inZip(location){return/\.zip(\/|$)/.test(location)}function pnpInstalled(projectRoot){let file2=findPnpFile(projectRoot);if(file2===void 0)return[];let api=loadPnp(file2),locator=api?.findPackageLocator(`${projectRoot}/`)??null,info=locator===null?null:api?.getPackageInformation(locator)??null;if(api===void 0||info===null)return lockfileInstalled(projectRoot,file2);let declaring=readPackageJson5(projectRoot),installed2=[];for(let[name,entry]of[...info.packageDependencies].sort(([a],[b])=>a<b?-1:1)){if(entry===null)continue;let reference=typeof entry=="string"?entry:entry[1],dependency=api.getPackageInformation({name,reference});if(dependency===null)continue;let location=dependency.packageLocation.replace(/\/$/,""),pkg=inZip(location)?void 0:readPackageJson5(location),declared=declaredIn3(declaring,name);installed2.push({name,version:typeof pkg?.version=="string"?pkg.version:versionOfReference(reference),location,realPath:realpathOr5(location),isSousPlugin:pkg!==void 0&&isSousPlugin3(pkg),...declared===void 0?{}:{declared}})}return installed2}function lockfileInstalled(projectRoot,pnpFile){let declaring=readPackageJson5(projectRoot),lockfile="";try{lockfile=fs78.readFileSync(path103.join(path103.dirname(pnpFile),"yarn.lock"),"utf8")}catch{}let names2=new Set;for(let section2 of["devDependencies","dependencies"]){let block=declaring?.[section2];if(block!==null&&typeof block=="object")for(let name of Object.keys(block))names2.add(name)}return[...names2].sort().flatMap(name=>{let declared=declaredIn3(declaring,name);return declared===void 0?[]:[{name,version:yarnLockVersion(lockfile,name,declared.range)??"unknown",location:pnpFile,realPath:realpathOr5(pnpFile),isSousPlugin:!1,declared}]})}function yarnLockVersion(lockfile,name,range3){let prefix=`${name}@`,wanted=new Set([`${prefix}${range3}`,`${prefix}npm:${range3}`]),entries=[],entry;for(let line of lockfile.split(/\r?\n/)){if(/^[^\s#].*:$/.test(line)){let descriptors=line.slice(0,-1).split(",").map(part=>part.trim().replace(/^"|"$/g,"")).filter(descriptor=>descriptor.startsWith(prefix));entry=descriptors.length>0?{descriptors}:void 0,entry!==void 0&&entries.push(entry);continue}let version2=/^\s+version:\s*"?([^"\s]+)"?\s*$/.exec(line);entry!==void 0&&version2!==null&&entry.version===void 0&&(entry.version=version2[1])}let exact=entries.find(candidate=>candidate.descriptors.some(descriptor=>wanted.has(descriptor)));if(exact!==void 0)return exact.version;let versions=new Set(entries.flatMap(candidate=>candidate.version??[]));return versions.size===1?[...versions][0]:void 0}function isBare(specifier){return!/^(\.{0,2}\/|[a-z][a-z0-9+.-]*:|\.\.?$)/i.test(specifier)&&!path103.isAbsolute(specifier)}var yarnPnpLocator={id:"yarn-pnp",locate(specifier,context){let root=context.project?.root;if(root===void 0||!isBare(specifier))return;let file2=findPnpFile(root),api=file2===void 0?void 0:loadPnp(file2);if(api!==void 0)try{let resolved=api.resolveRequest(specifier,`${root}/`);return resolved===null||inZip(resolved)?void 0:pathToFileURL7(resolved)}catch{return}}};var PLUGIN3="@sous-io/sous-plugin-yarn",FORMER_PLUGIN3="@sous-io/plugin-yarn";function commandOf3(ctx){return(ctx.config.get(["plugins","options",PLUGIN3])??ctx.config.get(["plugins","options",FORMER_PLUGIN3]))?.command??"yarn"}function has5(dir,file2){return fs79.existsSync(path104.join(dir,file2))}function hasWorkspaces(dir){let pkg=readPackageJson5(dir);return pkg!==void 0&&"workspaces"in pkg}function isBerry(dir){if(has5(dir,".yarnrc.yml")||has5(dir,PNP_FILE))return!0;let version2=packageManagerField3(readPackageJson5(dir),"yarn");if(version2!==void 0)return!version2.startsWith("1.");try{return/^__metadata:/m.test(fs79.readFileSync(path104.join(dir,"yarn.lock"),"utf8"))}catch{return!1}}var yarnManager={id:"yarn",description:"Yarn, Classic (1.x) and Berry (2 and later), with Plug'n'Play.",async detect(projectRoot){let pkg=readPackageJson5(projectRoot);if(packageManagerName3(pkg)!=="yarn"&&!has5(projectRoot,"yarn.lock")&&!has5(projectRoot,".yarnrc.yml")&&!has5(projectRoot,PNP_FILE))return;let version2=packageManagerField3(pkg,"yarn"),workspaceRoot=findUp2(projectRoot,hasWorkspaces),pnpFile=findPnpFile(projectRoot);return{id:isBerry(projectRoot)?"yarn@berry":"yarn",detected:!0,...version2===void 0?{}:{version:version2},...workspaceRoot===void 0?{}:{workspaceRoot},...pnpFile===void 0?{}:{pnpRoot:path104.dirname(pnpFile)}}},async installed(scope,projectRoot,ctx){if(scope==="project")return projectRoot===void 0?[]:findPnpFile(projectRoot)!==void 0&&!has5(projectRoot,"node_modules")?pnpInstalled(projectRoot):readInstalled3(path104.join(projectRoot,"node_modules"),readPackageJson5(projectRoot));let root=await yarnManager.globalRoot?.(ctx);return root===void 0?[]:readInstalled3(root)},async globalRoot(ctx){try{let result=await ctx.services.get("host.processes").run(commandOf3(ctx),["global","dir"],{label:"yarn global dir",windowsShell:!0}),dir=result.exitCode===0?lastLine3(result.stdout):void 0;return dir===void 0?void 0:path104.join(dir,"node_modules")}catch{return}},addCommand(specs,options2){let classicRoot=options2.workspaceRoot&&!isBerry(options2.cwd);return{command:"yarn",args:["add",...[...options2.section==="devDependencies"?["-D"]:[],"-E",...classicRoot?["-W"]:[]],...specs],cwd:options2.cwd}},globalInstallCommand(specs){return{command:"yarn",args:["global","add",...specs]}},installCommand(options2){return{command:"yarn",args:["install",...options2.updateLockfile===!0&&isBerry(options2.cwd)?["--no-immutable"]:[]],cwd:options2.cwd}},afterInstallScript:"postinstall"};var package_default28={name:"@sous-io/sous-plugin-yarn",version:"1.1.6",description:"A package-manager entity for Yarn, and Yarn Plug'n'Play's plugin locator.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-update":"workspace:*","@sous-io/sous-plugin-host":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME27="@sous-io/sous-plugin-yarn",yarnPlugin=definePlugin28({name:PLUGIN_NAME27,version:package_default28.version,description:"A package-manager entity for Yarn, and Yarn Plug'n'Play's plugin locator.",dependsOn:{"@sous-io/sous-plugin-update":`^${package_default28.version}`,"@sous-io/sous-plugin-host":`^${package_default28.version}`},register(sous){sous.entities.add("package-manager",yarnManager),sous.entities.add("plugin-locator",yarnPnpLocator)}});import{definePlugin as definePlugin29}from"@sous-io/sous-plugin-api";import{ConfigError as ConfigError67}from"@sous-io/sous-plugin-api";import{tmpdir}from"node:os";function tokenFromOutput(output){if(output.exitCode===0)return singleWord(output.stdout)}function singleWord(text){let body2=text.replace(/\r?\n$/,"");if(!(body2.length===0||/\s/.test(body2)))return body2}var TOKEN_COMMAND_TIMEOUT_MS=1e4;function commandDirectory(ctx){return ctx.project?.root??tmpdir()}function tokenOf(source){return async(repository,ctx)=>{let found=await source.find(repository,ctx);return"token"in found?found.token:void 0}}function listed(names2){return names2.length<=1?names2[0]??"":`${names2.slice(0,-1).join(", ")} and ${names2[names2.length-1]}`}function envTokenSource(options2){let{variables}=options2,source={id:"env",label:listed(variables),async find(_repository,ctx){for(let name of variables){let value=ctx.env[name]?.trim();if(value!==void 0&&value.length>0)return{token:{value,source:name}}}return{missing:`${listed(variables)} unset`}},token:async()=>{},fix:()=>variables.length===0?void 0:`export ${variables[0]}=<${options2.tokenHint}>`};return source.token=tokenOf(source),source}function gitCredentialTokenSource(){let source={id:"git-credential",label:"git credential fill",async find(repository,ctx){let missing={missing:`git has no stored credential for ${repository.host}`};if(!ctx.services.has("git.runner"))return missing;let result;try{result=await ctx.services.get("git.runner").run(["credential","fill"],{cwd:commandDirectory(ctx),input:`protocol=https
1182
1183
  host=${repository.host}
1183
1184
 
1184
1185
  `,env:{GIT_TERMINAL_PROMPT:"0",GCM_INTERACTIVE:"never",GIT_ASKPASS:"",SSH_ASKPASS:""},timeoutMs:TOKEN_COMMAND_TIMEOUT_MS,reject:!1,...ctx.signal===void 0?{}:{signal:ctx.signal}})}catch{return missing}if(result.exitCode!==0)return missing;let password=passwordIn(result.stdout);return password===void 0?missing:{token:{value:password,source:"git credential fill"}}},token:async()=>{}};return source.token=tokenOf(source),source}function passwordIn(output){for(let line of output.split(/\r?\n/))if(line.startsWith("password="))return singleWord(line.slice(9))}function cliTokenSource(options2){let{command}=options2,source={id:options2.id,label:command,async find(repository,ctx){let processes=ctx.services.get("host.processes");if(await processes.which(command,ctx.env)===void 0)return{missing:void 0};let args=options2.args(repository),result;try{result=await processes.run(command,args,{cwd:commandDirectory(ctx),env:ctx.env,timeoutMs:TOKEN_COMMAND_TIMEOUT_MS,label:`${command} token`,...ctx.signal===void 0?{}:{signal:ctx.signal}})}catch{return{missing:`${command} could not be run`}}let value=tokenFromOutput(result);return value===void 0?{missing:`${command} printed no token for ${repository.host}`}:{token:{value,source:command}}},token:async()=>{},...options2.login===void 0?{}:{fix:options2.login}};return source.token=tokenOf(source),source}async function runCli(cli,args,ctx,options2={}){let processes=ctx.services.get("host.processes");if(await processes.which(cli.command,ctx.env)===void 0)throw new ConfigError67(`${capitalized(cli.label)} ('${cli.command}') is not installed.`,{details:[`Sous needs it only to propose changes. Install it from ${cli.install}, then run '${cli.command} auth login'.`]});return processes.run(cli.command,args,{cwd:commandDirectory(ctx),env:{...ctx.env,...options2.env},label:`${cli.command} ${args.slice(0,2).join(" ")}`,...ctx.signal===void 0?{}:{signal:ctx.signal}})}async function cliOutput(cli,args,ctx,options2={}){try{let result=await runCli(cli,args,ctx,options2),output=result.stdout.trim();return result.exitCode===0&&output.length>0?output:void 0}catch{return}}async function cliJson(cli,args,what,noun2,ctx,options2={}){let result=await runCli(cli,args,ctx,options2);if(result.exitCode!==0)throw cliFailure(cli,what,result,"");try{return JSON.parse(result.stdout)}catch{throw new ConfigError67(`'${cli.command} ${what}' printed something that is not JSON, so sous cannot read the ${noun2} it describes.`)}}function cliFailure(cli,what,result,consequence){let reported=result.stderr.trim()||result.stdout.trim();return new ConfigError67(`'${cli.command} ${what}' did not succeed${consequence.length===0?"":`, ${consequence}`}.`,{details:reported.length===0?[]:reported.split(`
@@ -1253,7 +1254,7 @@ jobs:
1253
1254
  git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
1254
1255
  - name: Publish every new version
1255
1256
  run: npx --yes @sous-io/sous repo release --ci --push --yes
1256
- `}var GH={command:"gh",label:"the GitHub CLI",install:"https://cli.github.com"};function repoArg(repository){return`${repository.owner}/${repository.name}`}function ghEnv(repository){return{env:repository.host==="github.com"?{}:{GH_HOST:repository.host}}}import{ConfigError as ConfigError70}from"@sous-io/sous-plugin-api";var NOUN="pull request";function githubProposals(){return{async canPush(repository,ctx){let answer2=await cliOutput(GH,["api",`repos/${repoArg(repository)}`,"--jq",".permissions.push"],ctx,ghEnv(repository));return answer2==="true"?!0:answer2==="false"?!1:void 0},async fork(repository,ctx){let forked=await runCli(GH,["repo","fork",repoArg(repository),"--remote=false"],ctx,ghEnv(repository));if(forked.exitCode!==0)throw cliFailure(GH,"repo fork",forked,"");let owner=await cliOutput(GH,["api","user","--jq",".login"],ctx,ghEnv(repository));if(owner===void 0)throw new ConfigError70(`The fork was requested, but sous could not read your GitHub login from '${GH.command} api user', so it does not know where the fork lives.`);return{owner,name:repository.name,httpsUrl:`https://${repository.host}/${owner}/${repository.name}.git`,sshUrl:`git@${repository.host}:${owner}/${repository.name}.git`}},async proposeChange(repository,proposal,ctx){let head=proposal.head===void 0?proposal.branch:`${proposal.head.owner}:${proposal.branch}`,args=["pr","create","--repo",repoArg(repository)];proposal.base!==void 0&&args.push("--base",proposal.base),args.push("--head",head,"--title",proposal.title,"--body",proposal.body),proposal.draft&&args.push("--draft");let result=await runCli(GH,args,ctx,ghEnv(repository));if(result.exitCode!==0)throw cliFailure(GH,"pr create",result,"so no proposal was opened");let url2=firstUrlIn(result.stdout);return url2===void 0?{detail:`The ${NOUN} was opened, but '${GH.command}' printed no address for it.`}:{url:url2,detail:`The ${NOUN} is at ${url2}.`}},async findProposal(repository,query,ctx){let forkOwner=query.fromFork?query.forkOwner??await signedInLogin(repository,ctx):void 0,mine=(await cliJson(GH,["pr","list","--repo",repoArg(repository),"--head",query.branch,"--state","all","--limit","50","--json","number,url,state,title,isDraft,baseRefName,headRepositoryOwner,isCrossRepository"],"pr list",NOUN,ctx,ghEnv(repository))).filter(entry=>query.fromFork?entry.isCrossRepository===!0&&entry.headRepositoryOwner?.login===forkOwner:entry.isCrossRepository!==!0);if(mine.length===0)return;let chosen=mine.find(entry=>entry.state==="OPEN")??[...mine].sort((a,b)=>b.number-a.number)[0];return summarizePullRequest(chosen)},async proposalStatus(repository,id,ctx){let viewed=await cliJson(GH,["pr","view",id,"--repo",repoArg(repository),"--json","number,url,state,title,isDraft,baseRefName,reviewDecision,statusCheckRollup,mergeable"],"pr view",NOUN,ctx,ghEnv(repository));return statusOf2(viewed)},async updateProposal(repository,id,update,ctx){let args=["pr","edit",id,"--repo",repoArg(repository)];update.title!==void 0&&args.push("--title",update.title),update.body!==void 0&&args.push("--body",update.body);let result=await runCli(GH,args,ctx,ghEnv(repository));if(result.exitCode!==0)throw cliFailure(GH,"pr edit",result,`so the ${NOUN} kept its title and body`);let url2=firstUrlIn(result.stdout);return url2===void 0?{detail:`The ${NOUN} was updated.`}:{url:url2,detail:`The ${NOUN} at ${url2} was updated.`}}}}async function signedInLogin(repository,ctx){let login=await cliOutput(GH,["api","user","--jq",".login"],ctx,ghEnv(repository));if(login===void 0)throw new ConfigError70(`Sous could not read your GitHub login from '${GH.command} api user', so it cannot tell which fork a ${NOUN} would come from.`);return login}function stateOf(state){return state==="MERGED"?"merged":state==="CLOSED"?"closed":"open"}function summarizePullRequest(entry){return{id:String(entry.number),...entry.url===void 0?{}:{url:entry.url},state:stateOf(entry.state),title:entry.title??"",draft:entry.isDraft===!0,...entry.baseRefName===void 0?{}:{base:entry.baseRefName}}}function statusOf2(viewed){let review=reviewOf(viewed.reviewDecision),checks=checksOf(viewed.statusCheckRollup),mergeable=viewed.mergeable==="MERGEABLE"?!0:viewed.mergeable==="CONFLICTING"?!1:void 0;return{proposal:summarizePullRequest(viewed),...review===void 0?{}:{review},...checks===void 0?{}:{checks},...mergeable===void 0?{}:{mergeable}}}function reviewOf(decision){switch(decision){case"APPROVED":return"approved";case"CHANGES_REQUESTED":return"changes requested";case"REVIEW_REQUIRED":return"review required";default:return}}var PASSING=new Set(["SUCCESS","NEUTRAL","SKIPPED"]);function checksOf(rollup){if(rollup==null||rollup.length===0)return;let counts={passed:0,failed:0,pending:0};for(let check3 of rollup)check3.__typename==="StatusContext"||check3.status===void 0&&check3.state!==void 0?check3.state==="SUCCESS"?counts.passed+=1:check3.state==="PENDING"||check3.state==="EXPECTED"?counts.pending+=1:counts.failed+=1:check3.status!=="COMPLETED"?counts.pending+=1:PASSING.has(check3.conclusion??"")?counts.passed+=1:counts.failed+=1;return counts}var GITHUB_HOST="github.com",GITHUB_TOKEN_VARIABLES=["GITHUB_TOKEN","GH_TOKEN"];function encodedPath(path122){return path122.split("/").map(encodeURIComponent).join("/")}function githubApiFileUrl(request){let{repository}=request;return`${repository.host===GITHUB_HOST?"https://api.github.com":`https://${repository.host}/api/v3`}/repos/${repository.owner}/${repository.name}/contents/${encodedPath(request.path)}?ref=${encodeURIComponent(request.ref)}`}function githubRawFileUrl(request){let{repository}=request;return`${repository.host===GITHUB_HOST?`https://raw.githubusercontent.com/${repository.owner}/${repository.name}`:`https://${repository.host}/${repository.owner}/${repository.name}/raw`}/${encodeURIComponent(request.ref)}/${encodedPath(request.path)}`}var API_HEADERS={Accept:"application/vnd.github.raw+json","X-GitHub-Api-Version":"2022-11-28"};function createGithubHost(options2={}){let extraHosts=new Set((options2.hosts??[]).map(host=>host.toLowerCase())),variables=options2.tokenVariables??GITHUB_TOKEN_VARIABLES;return{id:"github",defaultHost:GITHUB_HOST,schemes:["github"],features:["fetch","submit","proposals"],readLocation:readGithubLocation,formatLocator:(host,repoPath,rest)=>formatHostedLocator("github",GITHUB_HOST,host,repoPath,rest),matches(url2){let parts=splitRepoUrl(url2);return parts!==void 0&&(parts.host===GITHUB_HOST||extraHosts.has(parts.host))},canonicalize(url2){let parts=splitRepoUrl(url2);if(parts===void 0)throw invalidRepoUrl("github",url2,GITHUB_HOST);return canonicalRepository(parts.host,parts.owner,parts.name,parts.sshPort===void 0?{}:{sshPort:parts.sshPort})},tokenSources:[envTokenSource({variables,tokenHint:"a token that can read the repository"}),gitCredentialTokenSource(),cliTokenSource({id:"gh",command:GH.command,args:repository=>["auth","token","--hostname",repository.host],login:repository=>`gh auth login --hostname ${repository.host}`})],readStrategies:[httpReadStrategy({id:"http-token",label:"HTTP with token",usesToken:!0,url:githubApiFileUrl,headers:()=>API_HEADERS}),httpReadStrategy({id:"http",label:"HTTP without token",usesToken:!1,url:githubRawFileUrl,headers:()=>({Accept:"*/*"}),servesCachedCopies:!0}),httpReadStrategy({id:"http-api",label:"API without token",usesToken:!1,url:githubApiFileUrl,headers:()=>API_HEADERS,onlyForCurrentReads:!0}),gitReadStrategy()],fetchRecipeTree:(repository,recipePath,tag,destination,ctx,options3={})=>fetchRecipeTree({urls:[repository.httpsUrl,repository.sshUrl],tag,recipePath,destination,...options3,tokenUser:"x-access-token"},ctx),proposalNoun:"pull request",cli:GH,authStatus:ctx=>cliAuthStatus(GH,ctx),...githubProposals(),scaffoldFiles:githubWorkflowFiles,fileUrl:(repositoryUrl,branch,file2)=>`${repositoryUrl}/blob/${branch}/${file2}`}}function readGithubLocation(location){let{segments}=location;return segments.length<2?[]:readingsAfterRepository(`${segments[0]}/${withoutGitSuffix(segments[1])}`,segments.slice(2))}var package_default29={name:"@sous-io/sous-plugin-github",version:"1.1.4",description:"A repository-host entity for GitHub: reading indexes, the token, proposing changes, the CI workflow.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-recipes":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@sous-io/sous-plugin-git":"workspace:*","@sous-io/sous-lib-repository-hosts":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME28="@sous-io/sous-plugin-github",githubPlugin=definePlugin29({name:PLUGIN_NAME28,version:package_default29.version,description:"A repository-host entity for GitHub: reading indexes, the token, proposing changes, the CI workflow.",dependsOn:{"@sous-io/sous-plugin-recipes":`^${package_default29.version}`,"@sous-io/sous-plugin-host":`^${package_default29.version}`,"@sous-io/sous-plugin-git":`^${package_default29.version}`},register(sous){sous.config.contribute({id:"github/repository-host",before:["@sous-io/sous-plugin-recipes"],contribute(config2){config2.addEntity("repository-host",createGithubHost(config2.options()??{}))}})}});import{definePlugin as definePlugin30}from"@sous-io/sous-plugin-api";var GITLAB_CI_PATH=".gitlab-ci.yml",RELEASE_TOKEN_VARIABLE="SOUS_RELEASE_TOKEN",RELEASE_TOKEN_WARNING=`The release job in ${GITLAB_CI_PATH} needs a masked CI/CD variable named ${RELEASE_TOKEN_VARIABLE}, holding a project access token with the write_repository scope and the Maintainer role. Until it is set, every release job fails before it commits or tags. Set it in the GitLab project under Settings, CI/CD, Variables.`;function gitlabCiFiles(_options){return[{path:GITLAB_CI_PATH,content:buildGitlabPipeline(),warning:RELEASE_TOKEN_WARNING}]}function buildGitlabPipeline(){return`# Release automation for this sous recipe repository.
1257
+ `}var GH={command:"gh",label:"the GitHub CLI",install:"https://cli.github.com"};function repoArg(repository){return`${repository.owner}/${repository.name}`}function ghEnv(repository){return{env:repository.host==="github.com"?{}:{GH_HOST:repository.host}}}import{ConfigError as ConfigError70}from"@sous-io/sous-plugin-api";var NOUN="pull request";function githubProposals(){return{async canPush(repository,ctx){let answer2=await cliOutput(GH,["api",`repos/${repoArg(repository)}`,"--jq",".permissions.push"],ctx,ghEnv(repository));return answer2==="true"?!0:answer2==="false"?!1:void 0},async fork(repository,ctx){let forked=await runCli(GH,["repo","fork",repoArg(repository),"--remote=false"],ctx,ghEnv(repository));if(forked.exitCode!==0)throw cliFailure(GH,"repo fork",forked,"");let owner=await cliOutput(GH,["api","user","--jq",".login"],ctx,ghEnv(repository));if(owner===void 0)throw new ConfigError70(`The fork was requested, but sous could not read your GitHub login from '${GH.command} api user', so it does not know where the fork lives.`);return{owner,name:repository.name,httpsUrl:`https://${repository.host}/${owner}/${repository.name}.git`,sshUrl:`git@${repository.host}:${owner}/${repository.name}.git`}},async proposeChange(repository,proposal,ctx){let head=proposal.head===void 0?proposal.branch:`${proposal.head.owner}:${proposal.branch}`,args=["pr","create","--repo",repoArg(repository)];proposal.base!==void 0&&args.push("--base",proposal.base),args.push("--head",head,"--title",proposal.title,"--body",proposal.body),proposal.draft&&args.push("--draft");let result=await runCli(GH,args,ctx,ghEnv(repository));if(result.exitCode!==0)throw cliFailure(GH,"pr create",result,"so no proposal was opened");let url2=firstUrlIn(result.stdout);return url2===void 0?{detail:`The ${NOUN} was opened, but '${GH.command}' printed no address for it.`}:{url:url2,detail:`The ${NOUN} is at ${url2}.`}},async findProposal(repository,query,ctx){let forkOwner=query.fromFork?query.forkOwner??await signedInLogin(repository,ctx):void 0,mine=(await cliJson(GH,["pr","list","--repo",repoArg(repository),"--head",query.branch,"--state","all","--limit","50","--json","number,url,state,title,isDraft,baseRefName,headRepositoryOwner,isCrossRepository"],"pr list",NOUN,ctx,ghEnv(repository))).filter(entry=>query.fromFork?entry.isCrossRepository===!0&&entry.headRepositoryOwner?.login===forkOwner:entry.isCrossRepository!==!0);if(mine.length===0)return;let chosen=mine.find(entry=>entry.state==="OPEN")??[...mine].sort((a,b)=>b.number-a.number)[0];return summarizePullRequest(chosen)},async proposalStatus(repository,id,ctx){let viewed=await cliJson(GH,["pr","view",id,"--repo",repoArg(repository),"--json","number,url,state,title,isDraft,baseRefName,reviewDecision,statusCheckRollup,mergeable"],"pr view",NOUN,ctx,ghEnv(repository));return statusOf2(viewed)},async updateProposal(repository,id,update,ctx){let args=["pr","edit",id,"--repo",repoArg(repository)];update.title!==void 0&&args.push("--title",update.title),update.body!==void 0&&args.push("--body",update.body);let result=await runCli(GH,args,ctx,ghEnv(repository));if(result.exitCode!==0)throw cliFailure(GH,"pr edit",result,`so the ${NOUN} kept its title and body`);let url2=firstUrlIn(result.stdout);return url2===void 0?{detail:`The ${NOUN} was updated.`}:{url:url2,detail:`The ${NOUN} at ${url2} was updated.`}}}}async function signedInLogin(repository,ctx){let login=await cliOutput(GH,["api","user","--jq",".login"],ctx,ghEnv(repository));if(login===void 0)throw new ConfigError70(`Sous could not read your GitHub login from '${GH.command} api user', so it cannot tell which fork a ${NOUN} would come from.`);return login}function stateOf(state){return state==="MERGED"?"merged":state==="CLOSED"?"closed":"open"}function summarizePullRequest(entry){return{id:String(entry.number),...entry.url===void 0?{}:{url:entry.url},state:stateOf(entry.state),title:entry.title??"",draft:entry.isDraft===!0,...entry.baseRefName===void 0?{}:{base:entry.baseRefName}}}function statusOf2(viewed){let review=reviewOf(viewed.reviewDecision),checks=checksOf(viewed.statusCheckRollup),mergeable=viewed.mergeable==="MERGEABLE"?!0:viewed.mergeable==="CONFLICTING"?!1:void 0;return{proposal:summarizePullRequest(viewed),...review===void 0?{}:{review},...checks===void 0?{}:{checks},...mergeable===void 0?{}:{mergeable}}}function reviewOf(decision){switch(decision){case"APPROVED":return"approved";case"CHANGES_REQUESTED":return"changes requested";case"REVIEW_REQUIRED":return"review required";default:return}}var PASSING=new Set(["SUCCESS","NEUTRAL","SKIPPED"]);function checksOf(rollup){if(rollup==null||rollup.length===0)return;let counts={passed:0,failed:0,pending:0};for(let check3 of rollup)check3.__typename==="StatusContext"||check3.status===void 0&&check3.state!==void 0?check3.state==="SUCCESS"?counts.passed+=1:check3.state==="PENDING"||check3.state==="EXPECTED"?counts.pending+=1:counts.failed+=1:check3.status!=="COMPLETED"?counts.pending+=1:PASSING.has(check3.conclusion??"")?counts.passed+=1:counts.failed+=1;return counts}var GITHUB_HOST="github.com",GITHUB_TOKEN_VARIABLES=["GITHUB_TOKEN","GH_TOKEN"];function encodedPath(path122){return path122.split("/").map(encodeURIComponent).join("/")}function githubApiFileUrl(request){let{repository}=request;return`${repository.host===GITHUB_HOST?"https://api.github.com":`https://${repository.host}/api/v3`}/repos/${repository.owner}/${repository.name}/contents/${encodedPath(request.path)}?ref=${encodeURIComponent(request.ref)}`}function githubRawFileUrl(request){let{repository}=request;return`${repository.host===GITHUB_HOST?`https://raw.githubusercontent.com/${repository.owner}/${repository.name}`:`https://${repository.host}/${repository.owner}/${repository.name}/raw`}/${encodeURIComponent(request.ref)}/${encodedPath(request.path)}`}var API_HEADERS={Accept:"application/vnd.github.raw+json","X-GitHub-Api-Version":"2022-11-28"};function createGithubHost(options2={}){let extraHosts=new Set((options2.hosts??[]).map(host=>host.toLowerCase())),variables=options2.tokenVariables??GITHUB_TOKEN_VARIABLES;return{id:"github",defaultHost:GITHUB_HOST,schemes:["github"],features:["fetch","submit","proposals"],readLocation:readGithubLocation,formatLocator:(host,repoPath,rest)=>formatHostedLocator("github",GITHUB_HOST,host,repoPath,rest),matches(url2){let parts=splitRepoUrl(url2);return parts!==void 0&&(parts.host===GITHUB_HOST||extraHosts.has(parts.host))},canonicalize(url2){let parts=splitRepoUrl(url2);if(parts===void 0)throw invalidRepoUrl("github",url2,GITHUB_HOST);return canonicalRepository(parts.host,parts.owner,parts.name,parts.sshPort===void 0?{}:{sshPort:parts.sshPort})},tokenSources:[envTokenSource({variables,tokenHint:"a token that can read the repository"}),gitCredentialTokenSource(),cliTokenSource({id:"gh",command:GH.command,args:repository=>["auth","token","--hostname",repository.host],login:repository=>`gh auth login --hostname ${repository.host}`})],readStrategies:[httpReadStrategy({id:"http-token",label:"HTTP with token",usesToken:!0,url:githubApiFileUrl,headers:()=>API_HEADERS}),httpReadStrategy({id:"http",label:"HTTP without token",usesToken:!1,url:githubRawFileUrl,headers:()=>({Accept:"*/*"}),servesCachedCopies:!0}),httpReadStrategy({id:"http-api",label:"API without token",usesToken:!1,url:githubApiFileUrl,headers:()=>API_HEADERS,onlyForCurrentReads:!0}),gitReadStrategy()],fetchRecipeTree:(repository,recipePath,tag,destination,ctx,options3={})=>fetchRecipeTree({urls:[repository.httpsUrl,repository.sshUrl],tag,recipePath,destination,...options3,tokenUser:"x-access-token"},ctx),proposalNoun:"pull request",cli:GH,authStatus:ctx=>cliAuthStatus(GH,ctx),...githubProposals(),scaffoldFiles:githubWorkflowFiles,fileUrl:(repositoryUrl,branch,file2)=>`${repositoryUrl}/blob/${branch}/${file2}`}}function readGithubLocation(location){let{segments}=location;return segments.length<2?[]:readingsAfterRepository(`${segments[0]}/${withoutGitSuffix(segments[1])}`,segments.slice(2))}var package_default29={name:"@sous-io/sous-plugin-github",version:"1.1.6",description:"A repository-host entity for GitHub: reading indexes, the token, proposing changes, the CI workflow.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-recipes":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@sous-io/sous-plugin-git":"workspace:*","@sous-io/sous-lib-repository-hosts":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME28="@sous-io/sous-plugin-github",githubPlugin=definePlugin29({name:PLUGIN_NAME28,version:package_default29.version,description:"A repository-host entity for GitHub: reading indexes, the token, proposing changes, the CI workflow.",dependsOn:{"@sous-io/sous-plugin-recipes":`^${package_default29.version}`,"@sous-io/sous-plugin-host":`^${package_default29.version}`,"@sous-io/sous-plugin-git":`^${package_default29.version}`},register(sous){sous.config.contribute({id:"github/repository-host",before:["@sous-io/sous-plugin-recipes"],contribute(config2){config2.addEntity("repository-host",createGithubHost(config2.options()??{}))}})}});import{definePlugin as definePlugin30}from"@sous-io/sous-plugin-api";var GITLAB_CI_PATH=".gitlab-ci.yml",RELEASE_TOKEN_VARIABLE="SOUS_RELEASE_TOKEN",RELEASE_TOKEN_WARNING=`The release job in ${GITLAB_CI_PATH} needs a masked CI/CD variable named ${RELEASE_TOKEN_VARIABLE}, holding a project access token with the write_repository scope and the Maintainer role. Until it is set, every release job fails before it commits or tags. Set it in the GitLab project under Settings, CI/CD, Variables.`;function gitlabCiFiles(_options){return[{path:GITLAB_CI_PATH,content:buildGitlabPipeline(),warning:RELEASE_TOKEN_WARNING}]}function buildGitlabPipeline(){return`# Release automation for this sous recipe repository.
1257
1258
  #
1258
1259
  # Two jobs, both running the sous CLI straight from npm so nothing needs to be
1259
1260
  # installed into this repository:
@@ -1312,7 +1313,7 @@ release:
1312
1313
  - git remote set-url origin "https://oauth2:$SOUS_RELEASE_TOKEN@$CI_SERVER_HOST/$CI_PROJECT_PATH.git"
1313
1314
  - npx --yes @sous-io/sous repo release --ci --push --yes
1314
1315
  `}var GLAB={command:"glab",label:"the GitLab CLI",install:"https://gitlab.com/gitlab-org/cli"};function projectArg(repository){return`${repository.owner}/${repository.name}`}import fs80 from"node:fs";import path106 from"node:path";import{LogLevel as LogLevel16}from"@sous-io/sous-plugin-api";var GITLAB_INSTANCES_FILENAME="gitlab-instances.json",CHECK_TIMEOUT_MS=1e4;function configuredHost(entry){let bare=entry.trim().replace(/^[a-z][a-z0-9+.-]*:\/\//i,"").toLowerCase(),slash=bare.indexOf("/"),host=slash===-1?bare:bare.slice(0,slash),basePath=slash===-1?"":bare.slice(slash+1).replace(/^\/+|\/+$/g,"");return basePath.length===0?{host}:{host,basePath}}var InstanceMemory=class{constructor(file2){this.file=file2}read(){try{let parsed=JSON.parse(fs80.readFileSync(this.file,"utf8"));return parsed&&typeof parsed=="object"&&!Array.isArray(parsed)?parsed:{}}catch{return{}}}remember(host,entry){let memory={...this.read(),[host]:entry},sorted2=Object.fromEntries(Object.keys(memory).sort().map(key=>[key,memory[key]]));try{fs80.mkdirSync(path106.dirname(this.file),{recursive:!0}),fs80.writeFileSync(this.file,`${JSON.stringify(sorted2,null,4)}
1315
- `,"utf8")}catch{}}};function candidateBasePaths(owner){let segments=owner.split("/").filter(segment=>segment.length>0);return segments.length<2?[]:Array.from({length:segments.length},(_unused,count2)=>segments.slice(0,count2).join("/"))}function answeredByGitlab(status,contentType){return(status===200||status===401||status===403)&&/json/i.test(contentType??"")}var GitlabInstances=class{constructor(configured){this.configured=configured}pending=new Map;configuredFor(host){return this.configured.get(hostWithoutPort(host))}async settle(repository,ctx){if(repository.basePath!==void 0||candidateBasePaths(repository.owner).length===0)return repository;let basePath=this.configuredFor(repository.host)?.basePath;if(basePath===void 0){let key=repository.host,pending=this.pending.get(key);pending===void 0&&(pending=this.find(repository,ctx),this.pending.set(key,pending)),basePath=await pending}return basePath===void 0||basePath===""||!repository.owner.startsWith(`${basePath}/`)?repository:canonicalRepository(repository.host,repository.owner,repository.name,{basePath,...repository.sshPort===void 0?{}:{sshPort:repository.sshPort}})}async find(repository,ctx){let memory=memoryOf(ctx),remembered=memory?.read()[repository.host];if(remembered!==void 0&&typeof remembered.basePath=="string")return remembered.basePath;let found=await ask2(repository,ctx);if(found!==void 0){if(memory?.remember(repository.host,{basePath:found,checkedAt:new Date().toISOString()}),found!==""){let settled=canonicalRepository(repository.host,repository.owner,repository.name,{basePath:found,...repository.sshPort===void 0?{}:{sshPort:repository.sshPort}});ctx.reporter.variables({Host:repository.host,"Installed under":`/${found}`,"API address":`https://${repository.host}/${found}/api/v4`,"SSH clone URL":settled.sshUrl,"Remembered in":memory?.file??"nowhere (no sous home)"},`GitLab on ${repository.host} is installed under a sub-path`,LogLevel16.Notice),ctx.reporter.note(`The GitLab API answered at /${found}/api/v4 on ${repository.host}, so sous reads /${found} as where GitLab is installed, not as a group.`)}return found}}};function memoryOf(ctx){if(ctx.services.has("host.sous-home"))return new InstanceMemory(path106.join(ctx.services.get("host.sous-home").paths(ctx.env).store,GITLAB_INSTANCES_FILENAME))}async function ask2(repository,ctx){if(!ctx.services.has("host.http"))return;let http=ctx.services.get("host.http");for(let candidate of candidateBasePaths(repository.owner)){let prefix=candidate===""?"":`/${candidate}`;try{let response=await http.get(`https://${repository.host}${prefix}/api/v4/version`,{headers:{Accept:"application/json"},redirect:"manual",timeoutMs:CHECK_TIMEOUT_MS,label:`find GitLab on ${repository.host}`,...ctx.signal===void 0?{}:{signal:ctx.signal}});if(answeredByGitlab(response.status,response.headers["content-type"]))return candidate}catch{return}}}import{ConfigError as ConfigError71}from"@sous-io/sous-plugin-api";var NOUN2="merge request";function glabEnv(repository){return{env:{GITLAB_HOST:repository.host}}}function gitlabProposals(){return{canPush:async()=>{},async fork(repository){throw new ConfigError71(`Sous does not fork ${repository.owner}/${repository.name} for you on ${GLAB.label}; it opens a ${NOUN2} from a branch you can already push.`,{details:[`Fork the project yourself, push your branch to the fork, then open the ${NOUN2} from there.`]})},async proposeChange(repository,proposal,ctx){let args=["mr","create","--repo",projectArg(repository),"--source-branch",proposal.branch];proposal.base!==void 0&&args.push("--target-branch",proposal.base),args.push("--title",proposal.title,"--description",proposal.body,"--yes"),proposal.draft&&args.push("--draft");let result=await runCli(GLAB,args,ctx,glabEnv(repository));if(result.exitCode!==0)throw cliFailure(GLAB,"mr create",result,"so no proposal was opened");let url2=firstUrlIn(result.stdout);return url2===void 0?{detail:`The ${NOUN2} was opened, but '${GLAB.command}' printed no address for it.`}:{url:url2,detail:`The ${NOUN2} is at ${url2}.`}},async findProposal(repository,query,ctx){let forkOwner=query.fromFork?query.forkOwner??await signedInUser(repository,ctx):void 0,mine=(await cliJson(GLAB,["mr","list","--repo",projectArg(repository),"--source-branch",query.branch,"--all","--per-page","50","--output","json"],"mr list",NOUN2,ctx,glabEnv(repository))).filter(entry=>{let crossProject=entry.source_project_id!==void 0&&entry.source_project_id!==entry.target_project_id;return query.fromFork?crossProject&&entry.author?.username===forkOwner:!crossProject});if(mine.length===0)return;let chosen=mine.find(entry=>stateOf2(entry.state)==="open")??[...mine].sort((a,b)=>b.iid-a.iid)[0];return summarize(chosen)},async proposalStatus(repository,id,ctx){let viewed=await cliJson(GLAB,["mr","view",id,"--repo",projectArg(repository),"--output","json"],"mr view",NOUN2,ctx,glabEnv(repository));return statusOf3(viewed)},async updateProposal(repository,id,update,ctx){let args=["mr","update",id,"--repo",projectArg(repository)];update.title!==void 0&&args.push("--title",update.title),update.body!==void 0&&args.push("--description",update.body);let result=await runCli(GLAB,args,ctx,glabEnv(repository));if(result.exitCode!==0)throw cliFailure(GLAB,"mr update",result,`so the ${NOUN2} kept its title and body`);let url2=firstUrlIn(result.stdout);return url2===void 0?{detail:`The ${NOUN2} was updated.`}:{url:url2,detail:`The ${NOUN2} at ${url2} was updated.`}}}}async function signedInUser(repository,ctx){let output=await cliOutput(GLAB,["api","user"],ctx,glabEnv(repository)),username;try{username=output===void 0?void 0:JSON.parse(output).username}catch{username=void 0}if(typeof username!="string"||username.length===0)throw new ConfigError71(`Sous could not read your GitLab username from '${GLAB.command} api user', so it cannot tell which fork a ${NOUN2} would come from.`);return username}function stateOf2(state){return state==="merged"?"merged":state==="closed"||state==="locked"?"closed":"open"}function summarize(entry){return{id:String(entry.iid),...entry.web_url===void 0?{}:{url:entry.web_url},state:stateOf2(entry.state),title:entry.title??"",draft:entry.draft===!0||entry.work_in_progress===!0,...entry.target_branch===void 0?{}:{base:entry.target_branch}}}var PENDING_PIPELINES=new Set(["created","waiting_for_resource","preparing","pending","running","scheduled","manual"]);function statusOf3(entry){let pipeline=entry.head_pipeline?.status,checks=pipeline===void 0?void 0:{passed:pipeline==="success"?1:0,failed:pipeline==="failed"||pipeline==="canceled"?1:0,pending:PENDING_PIPELINES.has(pipeline)?1:0},review=entry.detailed_merge_status==="not_approved"?"review required":void 0,mergeable=entry.has_conflicts===!0||entry.merge_status==="cannot_be_merged"?!1:entry.merge_status==="can_be_merged"||entry.detailed_merge_status==="mergeable"?!0:void 0;return{proposal:summarize(entry),...review===void 0?{}:{review},...checks===void 0?{}:{checks},...mergeable===void 0?{}:{mergeable}}}var GITLAB_HOST="gitlab.com",GITLAB_TOKEN_VARIABLES=["GITLAB_TOKEN"],GITLAB_CONTENT_HASH_HEADER="x-gitlab-content-sha256";function gitlabApi(repository){let base=repository.basePath,owner=base!==void 0&&repository.owner.startsWith(`${base}/`)?repository.owner.slice(base.length+1):repository.owner;return{root:`https://${repository.host}${base===void 0?"":`/${base}`}/api/v4`,project:`${owner}/${repository.name}`}}function gitlabFileUrl(request){return`${gitlabFileMetaUrl(request).replace(/\?ref=/,"/raw?ref=")}`}function gitlabFileMetaUrl(request){let{root,project}=gitlabApi(request.repository);return`${root}/projects/${encodeURIComponent(project)}/repository/files/${encodeURIComponent(request.path)}?ref=${encodeURIComponent(request.ref)}`}function settling(strategy,instances){return{...strategy,read:async(request,ctx)=>strategy.read({...request,repository:await instances.settle(request.repository,ctx)},ctx)}}function createGitlabHost(options2={}){let configured=new Map((options2.hosts??[]).map(entry=>configuredHost(entry)).map(entry=>[hostWithoutPort(entry.host),entry])),instances=new GitlabInstances(configured),variables=options2.tokenVariables??GITLAB_TOKEN_VARIABLES,isGitlab=host=>{let bare=hostWithoutPort(host);return bare===GITLAB_HOST||bare.startsWith("gitlab.")||configured.has(bare)};return{id:"gitlab",defaultHost:GITLAB_HOST,schemes:["gitlab"],features:["fetch","submit","proposals"],readLocation:readGitlabLocation,formatLocator:(host,repoPath,rest)=>formatHostedLocator("gitlab",GITLAB_HOST,host,repoPath,rest,"/-/"),matches(url2){let parts=splitRepoUrl(url2);return parts!==void 0&&isGitlab(parts.host)},canonicalize(url2){let parts=splitRepoUrl(url2);if(parts===void 0)throw invalidRepoUrl("gitlab",url2,GITLAB_HOST);let entry=configured.get(hostWithoutPort(parts.host)),host=entry!==void 0&&hostWithoutPort(entry.host)!==entry.host&&parts.host===hostWithoutPort(parts.host)?entry.host:parts.host;return canonicalRepository(host,parts.owner,parts.name,{...parts.sshPort===void 0?{}:{sshPort:parts.sshPort},...entry?.basePath===void 0?{}:{basePath:entry.basePath}})},tokenSources:[envTokenSource({variables,tokenHint:"a token with read_repository"}),gitCredentialTokenSource(),cliTokenSource({id:"glab",command:GLAB.command,args:repository=>["config","get","token","--host",repository.host],login:repository=>`glab auth login --hostname ${repository.host}`})],readStrategies:[httpReadStrategy({id:"http-token",label:"HTTP with token",usesToken:!0,url:gitlabFileUrl,contentHash:{header:GITLAB_CONTENT_HASH_HEADER,url:gitlabFileMetaUrl}}),httpReadStrategy({id:"http",label:"HTTP without token",usesToken:!1,url:gitlabFileUrl,contentHash:{header:GITLAB_CONTENT_HASH_HEADER,url:gitlabFileMetaUrl}}),gitReadStrategy()].map(strategy=>settling(strategy,instances)),fetchRecipeTree:async(repository,recipePath,tag,destination,ctx,options3={})=>{let settled=await instances.settle(repository,ctx);return fetchRecipeTree({urls:[settled.httpsUrl,settled.sshUrl],tag,recipePath,destination,...options3,tokenUser:"oauth2"},ctx)},proposalNoun:"merge request",cli:GLAB,authStatus:ctx=>cliAuthStatus(GLAB,ctx),...gitlabProposals(),scaffoldFiles:gitlabCiFiles,fileUrl:(repositoryUrl,branch,file2)=>`${repositoryUrl}/-/blob/${branch}/${file2}`}}function readGitlabLocation(location){let{segments}=location,separator=segments.indexOf("-");if(separator>=2)return readingsAfterRepository(projectPath(segments.slice(0,separator)),segments.slice(separator));let suffixed=segments.findIndex(segment=>/\.git$/i.test(segment));if(suffixed>=1)return readingsAfterRepository(projectPath(segments.slice(0,suffixed+1)),segments.slice(suffixed+1));let readings=[];for(let end=2;end<=segments.length;end++){let rest=segments.slice(end);rest.length<=2&&readings.push({repoPath:projectPath(segments.slice(0,end)),named:rest})}return readings}function projectPath(segments){let last2=segments.length-1;return segments.map((segment,index)=>index===last2?withoutGitSuffix(segment):segment).join("/")}var package_default30={name:"@sous-io/sous-plugin-gitlab",version:"1.1.4",description:"A repository-host entity for GitLab, with S4's fixes to the index address and the token.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-recipes":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@sous-io/sous-plugin-git":"workspace:*","@sous-io/sous-lib-repository-hosts":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME29="@sous-io/sous-plugin-gitlab",gitlabPlugin=definePlugin30({name:PLUGIN_NAME29,version:package_default30.version,description:"A repository-host entity for GitLab, with fixes to the index address and the token.",dependsOn:{"@sous-io/sous-plugin-recipes":`^${package_default30.version}`,"@sous-io/sous-plugin-host":`^${package_default30.version}`,"@sous-io/sous-plugin-git":`^${package_default30.version}`},register(sous){sous.config.contribute({id:"gitlab/repository-host",before:["@sous-io/sous-plugin-recipes"],contribute(config2){config2.addEntity("repository-host",createGitlabHost(config2.options()??{}))}})}});import{definePlugin as definePlugin31}from"@sous-io/sous-plugin-api";import{existsSync as existsSync5}from"node:fs";import{readFile as readFile3}from"node:fs/promises";import path108 from"node:path";import{pathToFileURL as pathToFileURL8}from"node:url";import{ConfigError as ConfigError73}from"@sous-io/sous-plugin-api";import path107 from"node:path";import{fileURLToPath as fileURLToPath3}from"node:url";function localRepoPath(url2){let trimmed=url2.trim();if(trimmed.length!==0){if(trimmed.toLowerCase().startsWith("file://"))try{return path107.normalize(fileURLToPath3(trimmed))}catch{return}return path107.isAbsolute(trimmed)?path107.normalize(trimmed):void 0}}function identityOwnerPath(directory,paths=path107){let{root}=paths.parse(directory);return`/${[...root.split(/[\\/]/).map(segment=>segment.replace(/:$/,"")),...directory.slice(root.length).split(paths.sep)].filter(segment=>segment.length>0).join("/")}`}init_src5();import{statSync as statSync2}from"node:fs";import{ConfigError as ConfigError72}from"@sous-io/sous-plugin-api";function assertLocalRepoDirectory(typed,resolved,manifests){let manifestName=`${REPO_MANIFEST_BASENAME}${MANIFEST_EXTENSIONS[0]}`,spellings=MANIFEST_EXTENSIONS.map(extension=>`${REPO_MANIFEST_BASENAME}${extension}`).join(", "),stats;try{stats=statSync2(resolved)}catch{throw new ConfigError72(`There is no directory at '${typed}'.`,{details:[`Sous read that as the path ${resolved}, and nothing is there.`,`A repository on this machine is a directory holding a '${manifestName}' file at its root. Check the path, or create one with 'sous repo init'.`]})}if(!stats.isDirectory())throw new ConfigError72(`'${typed}' is a file, not a directory.`,{details:[`Sous read that as the path ${resolved}.`,`Name the root directory of a repository: the directory holding its '${manifestName}' file.`]});if(manifests.find(resolved,"repo")===void 0)throw new ConfigError72(`The directory '${typed}' is not a sous repository.`,{details:[`Sous read that as the path ${resolved}, and it holds no repository manifest.`,`A repository declares itself with one of ${spellings} at its root. Check the path, or create a repository there with 'sous repo init'.`]})}var LOCAL_HOST="localhost";function repoDirectory(repository){return repository.httpsUrl}var fileStrategy={id:"file",label:"working tree",async read(request){let directory=repoDirectory(request.repository);if(request.ref!=="HEAD")return{ok:!1,reason:`the working tree is not ${request.ref}`};if(!existsSync5(directory))return{ok:!1,reason:`there is no directory at ${directory}`};let file2=path108.join(directory,request.path);return existsSync5(file2)?{ok:!0,text:await readFile3(file2,"utf8"),ref:"working tree"}:{ok:!1,reason:`the working tree has no ${request.path}`}}},gitStrategy={id:"git",label:"git",async read(request,ctx){let directory=repoDirectory(request.repository);if(!existsSync5(directory))return{ok:!1,reason:`there is no directory at ${directory}`};let result=await ctx.services.get("git.runner").run(["show",`${request.ref}:${request.path}`],{cwd:directory,reject:!1,...ctx.signal===void 0?{}:{signal:ctx.signal}});return result.exitCode!==0?{ok:!1,reason:gitFailureReason(new Error(result.stderr||"git show failed"))}:{ok:!0,text:result.stdout,ref:request.ref}}};function createLocalHost(){return{id:"local",features:["fetch"],readLocation:()=>[],formatLocator:(host,repoPath,rest)=>formatHostedLocator("local",void 0,host,repoPath,rest),matches:url2=>localRepoPath(url2)!==void 0,canonicalize(url2){let directory=localRepoPath(url2);if(directory===void 0)throw new ConfigError73(`'${url2}' is not a local repository path that sous can read.`,{details:["A local repository is named by an absolute path, or by the same path in 'file:///...' form. A relative path is not accepted, because a repository entry is read from a config file that several working directories may run against."]});return{host:LOCAL_HOST,owner:identityOwnerPath(path108.dirname(directory)),name:path108.basename(directory),httpsUrl:directory,sshUrl:pathToFileURL8(directory).href}},readStrategies:[fileStrategy,gitStrategy],checkTypedPath:(typed,resolved,ctx)=>assertLocalRepoDirectory(typed,resolved,ctx.services.get("formats.manifests")),fetchRecipeTree:(repository,recipePath,tag,destination,ctx)=>fetchLocalRecipeTree(repository,recipePath,tag,destination,ctx)}}async function fetchLocalRecipeTree(repository,recipePath,tag,destination,ctx){let directory=repoDirectory(repository),git2=ctx.services.get("git.runner");if(await git2.root(directory)!==void 0&&await git2.revParse(`refs/tags/${tag}`,directory)!==void 0){await fetchRecipeTree({urls:[directory],tag,recipePath,destination},ctx);return}let source=path108.join(directory,recipePath);if(!existsSync5(source))throw new ConfigError73(`The repository at ${directory} has no folder '${recipePath}'.`,{details:["Its index says the recipe lives there, so either the index is out of date or the folder has been moved."]});await copyRecipeTree(source,destination)}var package_default31={name:"@sous-io/sous-plugin-local",version:"1.1.4",description:"A repository-host entity for a repository on disk.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-formats":"workspace:*","@sous-io/sous-plugin-git":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@sous-io/sous-plugin-recipes":"workspace:*","@sous-io/sous-lib-repository-hosts":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME30="@sous-io/sous-plugin-local",localPlugin=definePlugin31({name:PLUGIN_NAME30,version:package_default31.version,description:"A repository-host entity for a repository on disk.",dependsOn:{"@sous-io/sous-plugin-recipes":`^${package_default31.version}`,"@sous-io/sous-plugin-host":`^${package_default31.version}`,"@sous-io/sous-plugin-git":`^${package_default31.version}`,"@sous-io/sous-plugin-formats":`^${package_default31.version}`},register(sous){sous.entities.add("repository-host",createLocalHost())}});import{definePlugin as definePlugin32}from"@sous-io/sous-plugin-api";import{SousError as SousError35}from"@sous-io/sous-plugin-api";function parseStream(stdout){let lines3=[];for(let text of stdout.split(`
1316
+ `,"utf8")}catch{}}};function candidateBasePaths(owner){let segments=owner.split("/").filter(segment=>segment.length>0);return segments.length<2?[]:Array.from({length:segments.length},(_unused,count2)=>segments.slice(0,count2).join("/"))}function answeredByGitlab(status,contentType){return(status===200||status===401||status===403)&&/json/i.test(contentType??"")}var GitlabInstances=class{constructor(configured){this.configured=configured}pending=new Map;configuredFor(host){return this.configured.get(hostWithoutPort(host))}async settle(repository,ctx){if(repository.basePath!==void 0||candidateBasePaths(repository.owner).length===0)return repository;let basePath=this.configuredFor(repository.host)?.basePath;if(basePath===void 0){let key=repository.host,pending=this.pending.get(key);pending===void 0&&(pending=this.find(repository,ctx),this.pending.set(key,pending)),basePath=await pending}return basePath===void 0||basePath===""||!repository.owner.startsWith(`${basePath}/`)?repository:canonicalRepository(repository.host,repository.owner,repository.name,{basePath,...repository.sshPort===void 0?{}:{sshPort:repository.sshPort}})}async find(repository,ctx){let memory=memoryOf(ctx),remembered=memory?.read()[repository.host];if(remembered!==void 0&&typeof remembered.basePath=="string")return remembered.basePath;let found=await ask2(repository,ctx);if(found!==void 0){if(memory?.remember(repository.host,{basePath:found,checkedAt:new Date().toISOString()}),found!==""){let settled=canonicalRepository(repository.host,repository.owner,repository.name,{basePath:found,...repository.sshPort===void 0?{}:{sshPort:repository.sshPort}});ctx.reporter.variables({Host:repository.host,"Installed under":`/${found}`,"API address":`https://${repository.host}/${found}/api/v4`,"SSH clone URL":settled.sshUrl,"Remembered in":memory?.file??"nowhere (no sous home)"},`GitLab on ${repository.host} is installed under a sub-path`,LogLevel16.Notice),ctx.reporter.note(`The GitLab API answered at /${found}/api/v4 on ${repository.host}, so sous reads /${found} as where GitLab is installed, not as a group.`)}return found}}};function memoryOf(ctx){if(ctx.services.has("host.sous-home"))return new InstanceMemory(path106.join(ctx.services.get("host.sous-home").paths(ctx.env).store,GITLAB_INSTANCES_FILENAME))}async function ask2(repository,ctx){if(!ctx.services.has("host.http"))return;let http=ctx.services.get("host.http");for(let candidate of candidateBasePaths(repository.owner)){let prefix=candidate===""?"":`/${candidate}`;try{let response=await http.get(`https://${repository.host}${prefix}/api/v4/version`,{headers:{Accept:"application/json"},redirect:"manual",timeoutMs:CHECK_TIMEOUT_MS,label:`find GitLab on ${repository.host}`,...ctx.signal===void 0?{}:{signal:ctx.signal}});if(answeredByGitlab(response.status,response.headers["content-type"]))return candidate}catch{return}}}import{ConfigError as ConfigError71}from"@sous-io/sous-plugin-api";var NOUN2="merge request";function glabEnv(repository){return{env:{GITLAB_HOST:repository.host}}}function gitlabProposals(){return{canPush:async()=>{},async fork(repository){throw new ConfigError71(`Sous does not fork ${repository.owner}/${repository.name} for you on ${GLAB.label}; it opens a ${NOUN2} from a branch you can already push.`,{details:[`Fork the project yourself, push your branch to the fork, then open the ${NOUN2} from there.`]})},async proposeChange(repository,proposal,ctx){let args=["mr","create","--repo",projectArg(repository),"--source-branch",proposal.branch];proposal.base!==void 0&&args.push("--target-branch",proposal.base),args.push("--title",proposal.title,"--description",proposal.body,"--yes"),proposal.draft&&args.push("--draft");let result=await runCli(GLAB,args,ctx,glabEnv(repository));if(result.exitCode!==0)throw cliFailure(GLAB,"mr create",result,"so no proposal was opened");let url2=firstUrlIn(result.stdout);return url2===void 0?{detail:`The ${NOUN2} was opened, but '${GLAB.command}' printed no address for it.`}:{url:url2,detail:`The ${NOUN2} is at ${url2}.`}},async findProposal(repository,query,ctx){let forkOwner=query.fromFork?query.forkOwner??await signedInUser(repository,ctx):void 0,mine=(await cliJson(GLAB,["mr","list","--repo",projectArg(repository),"--source-branch",query.branch,"--all","--per-page","50","--output","json"],"mr list",NOUN2,ctx,glabEnv(repository))).filter(entry=>{let crossProject=entry.source_project_id!==void 0&&entry.source_project_id!==entry.target_project_id;return query.fromFork?crossProject&&entry.author?.username===forkOwner:!crossProject});if(mine.length===0)return;let chosen=mine.find(entry=>stateOf2(entry.state)==="open")??[...mine].sort((a,b)=>b.iid-a.iid)[0];return summarize(chosen)},async proposalStatus(repository,id,ctx){let viewed=await cliJson(GLAB,["mr","view",id,"--repo",projectArg(repository),"--output","json"],"mr view",NOUN2,ctx,glabEnv(repository));return statusOf3(viewed)},async updateProposal(repository,id,update,ctx){let args=["mr","update",id,"--repo",projectArg(repository)];update.title!==void 0&&args.push("--title",update.title),update.body!==void 0&&args.push("--description",update.body);let result=await runCli(GLAB,args,ctx,glabEnv(repository));if(result.exitCode!==0)throw cliFailure(GLAB,"mr update",result,`so the ${NOUN2} kept its title and body`);let url2=firstUrlIn(result.stdout);return url2===void 0?{detail:`The ${NOUN2} was updated.`}:{url:url2,detail:`The ${NOUN2} at ${url2} was updated.`}}}}async function signedInUser(repository,ctx){let output=await cliOutput(GLAB,["api","user"],ctx,glabEnv(repository)),username;try{username=output===void 0?void 0:JSON.parse(output).username}catch{username=void 0}if(typeof username!="string"||username.length===0)throw new ConfigError71(`Sous could not read your GitLab username from '${GLAB.command} api user', so it cannot tell which fork a ${NOUN2} would come from.`);return username}function stateOf2(state){return state==="merged"?"merged":state==="closed"||state==="locked"?"closed":"open"}function summarize(entry){return{id:String(entry.iid),...entry.web_url===void 0?{}:{url:entry.web_url},state:stateOf2(entry.state),title:entry.title??"",draft:entry.draft===!0||entry.work_in_progress===!0,...entry.target_branch===void 0?{}:{base:entry.target_branch}}}var PENDING_PIPELINES=new Set(["created","waiting_for_resource","preparing","pending","running","scheduled","manual"]);function statusOf3(entry){let pipeline=entry.head_pipeline?.status,checks=pipeline===void 0?void 0:{passed:pipeline==="success"?1:0,failed:pipeline==="failed"||pipeline==="canceled"?1:0,pending:PENDING_PIPELINES.has(pipeline)?1:0},review=entry.detailed_merge_status==="not_approved"?"review required":void 0,mergeable=entry.has_conflicts===!0||entry.merge_status==="cannot_be_merged"?!1:entry.merge_status==="can_be_merged"||entry.detailed_merge_status==="mergeable"?!0:void 0;return{proposal:summarize(entry),...review===void 0?{}:{review},...checks===void 0?{}:{checks},...mergeable===void 0?{}:{mergeable}}}var GITLAB_HOST="gitlab.com",GITLAB_TOKEN_VARIABLES=["GITLAB_TOKEN"],GITLAB_CONTENT_HASH_HEADER="x-gitlab-content-sha256";function gitlabApi(repository){let base=repository.basePath,owner=base!==void 0&&repository.owner.startsWith(`${base}/`)?repository.owner.slice(base.length+1):repository.owner;return{root:`https://${repository.host}${base===void 0?"":`/${base}`}/api/v4`,project:`${owner}/${repository.name}`}}function gitlabFileUrl(request){return`${gitlabFileMetaUrl(request).replace(/\?ref=/,"/raw?ref=")}`}function gitlabFileMetaUrl(request){let{root,project}=gitlabApi(request.repository);return`${root}/projects/${encodeURIComponent(project)}/repository/files/${encodeURIComponent(request.path)}?ref=${encodeURIComponent(request.ref)}`}function settling(strategy,instances){return{...strategy,read:async(request,ctx)=>strategy.read({...request,repository:await instances.settle(request.repository,ctx)},ctx)}}function createGitlabHost(options2={}){let configured=new Map((options2.hosts??[]).map(entry=>configuredHost(entry)).map(entry=>[hostWithoutPort(entry.host),entry])),instances=new GitlabInstances(configured),variables=options2.tokenVariables??GITLAB_TOKEN_VARIABLES,isGitlab=host=>{let bare=hostWithoutPort(host);return bare===GITLAB_HOST||bare.startsWith("gitlab.")||configured.has(bare)};return{id:"gitlab",defaultHost:GITLAB_HOST,schemes:["gitlab"],features:["fetch","submit","proposals"],readLocation:readGitlabLocation,formatLocator:(host,repoPath,rest)=>formatHostedLocator("gitlab",GITLAB_HOST,host,repoPath,rest,"/-/"),matches(url2){let parts=splitRepoUrl(url2);return parts!==void 0&&isGitlab(parts.host)},canonicalize(url2){let parts=splitRepoUrl(url2);if(parts===void 0)throw invalidRepoUrl("gitlab",url2,GITLAB_HOST);let entry=configured.get(hostWithoutPort(parts.host)),host=entry!==void 0&&hostWithoutPort(entry.host)!==entry.host&&parts.host===hostWithoutPort(parts.host)?entry.host:parts.host;return canonicalRepository(host,parts.owner,parts.name,{...parts.sshPort===void 0?{}:{sshPort:parts.sshPort},...entry?.basePath===void 0?{}:{basePath:entry.basePath}})},tokenSources:[envTokenSource({variables,tokenHint:"a token with read_repository"}),gitCredentialTokenSource(),cliTokenSource({id:"glab",command:GLAB.command,args:repository=>["config","get","token","--host",repository.host],login:repository=>`glab auth login --hostname ${repository.host}`})],readStrategies:[httpReadStrategy({id:"http-token",label:"HTTP with token",usesToken:!0,url:gitlabFileUrl,contentHash:{header:GITLAB_CONTENT_HASH_HEADER,url:gitlabFileMetaUrl}}),httpReadStrategy({id:"http",label:"HTTP without token",usesToken:!1,url:gitlabFileUrl,contentHash:{header:GITLAB_CONTENT_HASH_HEADER,url:gitlabFileMetaUrl}}),gitReadStrategy()].map(strategy=>settling(strategy,instances)),fetchRecipeTree:async(repository,recipePath,tag,destination,ctx,options3={})=>{let settled=await instances.settle(repository,ctx);return fetchRecipeTree({urls:[settled.httpsUrl,settled.sshUrl],tag,recipePath,destination,...options3,tokenUser:"oauth2"},ctx)},proposalNoun:"merge request",cli:GLAB,authStatus:ctx=>cliAuthStatus(GLAB,ctx),...gitlabProposals(),scaffoldFiles:gitlabCiFiles,fileUrl:(repositoryUrl,branch,file2)=>`${repositoryUrl}/-/blob/${branch}/${file2}`}}function readGitlabLocation(location){let{segments}=location,separator=segments.indexOf("-");if(separator>=2)return readingsAfterRepository(projectPath(segments.slice(0,separator)),segments.slice(separator));let suffixed=segments.findIndex(segment=>/\.git$/i.test(segment));if(suffixed>=1)return readingsAfterRepository(projectPath(segments.slice(0,suffixed+1)),segments.slice(suffixed+1));let readings=[];for(let end=2;end<=segments.length;end++){let rest=segments.slice(end);rest.length<=2&&readings.push({repoPath:projectPath(segments.slice(0,end)),named:rest})}return readings}function projectPath(segments){let last2=segments.length-1;return segments.map((segment,index)=>index===last2?withoutGitSuffix(segment):segment).join("/")}var package_default30={name:"@sous-io/sous-plugin-gitlab",version:"1.1.6",description:"A repository-host entity for GitLab, with S4's fixes to the index address and the token.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-recipes":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@sous-io/sous-plugin-git":"workspace:*","@sous-io/sous-lib-repository-hosts":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME29="@sous-io/sous-plugin-gitlab",gitlabPlugin=definePlugin30({name:PLUGIN_NAME29,version:package_default30.version,description:"A repository-host entity for GitLab, with fixes to the index address and the token.",dependsOn:{"@sous-io/sous-plugin-recipes":`^${package_default30.version}`,"@sous-io/sous-plugin-host":`^${package_default30.version}`,"@sous-io/sous-plugin-git":`^${package_default30.version}`},register(sous){sous.config.contribute({id:"gitlab/repository-host",before:["@sous-io/sous-plugin-recipes"],contribute(config2){config2.addEntity("repository-host",createGitlabHost(config2.options()??{}))}})}});import{definePlugin as definePlugin31}from"@sous-io/sous-plugin-api";import{existsSync as existsSync5}from"node:fs";import{readFile as readFile3}from"node:fs/promises";import path108 from"node:path";import{pathToFileURL as pathToFileURL8}from"node:url";import{ConfigError as ConfigError73}from"@sous-io/sous-plugin-api";import path107 from"node:path";import{fileURLToPath as fileURLToPath3}from"node:url";function localRepoPath(url2){let trimmed=url2.trim();if(trimmed.length!==0){if(trimmed.toLowerCase().startsWith("file://"))try{return path107.normalize(fileURLToPath3(trimmed))}catch{return}return path107.isAbsolute(trimmed)?path107.normalize(trimmed):void 0}}function identityOwnerPath(directory,paths=path107){let{root}=paths.parse(directory);return`/${[...root.split(/[\\/]/).map(segment=>segment.replace(/:$/,"")),...directory.slice(root.length).split(paths.sep)].filter(segment=>segment.length>0).join("/")}`}init_src5();import{statSync as statSync2}from"node:fs";import{ConfigError as ConfigError72}from"@sous-io/sous-plugin-api";function assertLocalRepoDirectory(typed,resolved,manifests){let manifestName=`${REPO_MANIFEST_BASENAME}${MANIFEST_EXTENSIONS[0]}`,spellings=MANIFEST_EXTENSIONS.map(extension=>`${REPO_MANIFEST_BASENAME}${extension}`).join(", "),stats;try{stats=statSync2(resolved)}catch{throw new ConfigError72(`There is no directory at '${typed}'.`,{details:[`Sous read that as the path ${resolved}, and nothing is there.`,`A repository on this machine is a directory holding a '${manifestName}' file at its root. Check the path, or create one with 'sous repo init'.`]})}if(!stats.isDirectory())throw new ConfigError72(`'${typed}' is a file, not a directory.`,{details:[`Sous read that as the path ${resolved}.`,`Name the root directory of a repository: the directory holding its '${manifestName}' file.`]});if(manifests.find(resolved,"repo")===void 0)throw new ConfigError72(`The directory '${typed}' is not a sous repository.`,{details:[`Sous read that as the path ${resolved}, and it holds no repository manifest.`,`A repository declares itself with one of ${spellings} at its root. Check the path, or create a repository there with 'sous repo init'.`]})}var LOCAL_HOST="localhost";function repoDirectory(repository){return repository.httpsUrl}var fileStrategy={id:"file",label:"working tree",async read(request){let directory=repoDirectory(request.repository);if(request.ref!=="HEAD")return{ok:!1,reason:`the working tree is not ${request.ref}`};if(!existsSync5(directory))return{ok:!1,reason:`there is no directory at ${directory}`};let file2=path108.join(directory,request.path);return existsSync5(file2)?{ok:!0,text:await readFile3(file2,"utf8"),ref:"working tree"}:{ok:!1,reason:`the working tree has no ${request.path}`}}},gitStrategy={id:"git",label:"git",async read(request,ctx){let directory=repoDirectory(request.repository);if(!existsSync5(directory))return{ok:!1,reason:`there is no directory at ${directory}`};let result=await ctx.services.get("git.runner").run(["show",`${request.ref}:${request.path}`],{cwd:directory,reject:!1,...ctx.signal===void 0?{}:{signal:ctx.signal}});return result.exitCode!==0?{ok:!1,reason:gitFailureReason(new Error(result.stderr||"git show failed"))}:{ok:!0,text:result.stdout,ref:request.ref}}};function createLocalHost(){return{id:"local",features:["fetch"],readLocation:()=>[],formatLocator:(host,repoPath,rest)=>formatHostedLocator("local",void 0,host,repoPath,rest),matches:url2=>localRepoPath(url2)!==void 0,canonicalize(url2){let directory=localRepoPath(url2);if(directory===void 0)throw new ConfigError73(`'${url2}' is not a local repository path that sous can read.`,{details:["A local repository is named by an absolute path, or by the same path in 'file:///...' form. A relative path is not accepted, because a repository entry is read from a config file that several working directories may run against."]});return{host:LOCAL_HOST,owner:identityOwnerPath(path108.dirname(directory)),name:path108.basename(directory),httpsUrl:directory,sshUrl:pathToFileURL8(directory).href}},readStrategies:[fileStrategy,gitStrategy],checkTypedPath:(typed,resolved,ctx)=>assertLocalRepoDirectory(typed,resolved,ctx.services.get("formats.manifests")),fetchRecipeTree:(repository,recipePath,tag,destination,ctx)=>fetchLocalRecipeTree(repository,recipePath,tag,destination,ctx)}}async function fetchLocalRecipeTree(repository,recipePath,tag,destination,ctx){let directory=repoDirectory(repository),git2=ctx.services.get("git.runner");if(await git2.root(directory)!==void 0&&await git2.revParse(`refs/tags/${tag}`,directory)!==void 0){await fetchRecipeTree({urls:[directory],tag,recipePath,destination},ctx);return}let source=path108.join(directory,recipePath);if(!existsSync5(source))throw new ConfigError73(`The repository at ${directory} has no folder '${recipePath}'.`,{details:["Its index says the recipe lives there, so either the index is out of date or the folder has been moved."]});await copyRecipeTree(source,destination)}var package_default31={name:"@sous-io/sous-plugin-local",version:"1.1.6",description:"A repository-host entity for a repository on disk.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-formats":"workspace:*","@sous-io/sous-plugin-git":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@sous-io/sous-plugin-recipes":"workspace:*","@sous-io/sous-lib-repository-hosts":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME30="@sous-io/sous-plugin-local",localPlugin=definePlugin31({name:PLUGIN_NAME30,version:package_default31.version,description:"A repository-host entity for a repository on disk.",dependsOn:{"@sous-io/sous-plugin-recipes":`^${package_default31.version}`,"@sous-io/sous-plugin-host":`^${package_default31.version}`,"@sous-io/sous-plugin-git":`^${package_default31.version}`,"@sous-io/sous-plugin-formats":`^${package_default31.version}`},register(sous){sous.entities.add("repository-host",createLocalHost())}});import{definePlugin as definePlugin32}from"@sous-io/sous-plugin-api";import{SousError as SousError35}from"@sous-io/sous-plugin-api";function parseStream(stdout){let lines3=[];for(let text of stdout.split(`
1316
1317
  `))if(text.trim().startsWith("{"))try{let value=JSON.parse(text);value&&typeof value=="object"&&!Array.isArray(value)&&lines3.push(value)}catch{}return lines3}function blocksOf(line){let message2=line.message,content=message2&&typeof message2=="object"?message2.content:void 0;return typeof content=="string"?[{type:"text",text:content}]:Array.isArray(content)?content.filter(block=>!!block&&typeof block=="object"):[]}function resultText(content){return typeof content=="string"?content:Array.isArray(content)?content.map(part=>part&&typeof part=="object"&&typeof part.text=="string"?part.text:"").filter(text=>text!=="").join(`
1317
1318
  `):""}function finalText(lines3){let result=[...lines3].reverse().find(line=>line.type==="result");if(result&&typeof result.result=="string")return result.result;for(let line of[...lines3].reverse())if(line.type==="assistant"){let text=blocksOf(line).filter(block=>block.type==="text"&&typeof block.text=="string").map(block=>block.text).join(`
1318
1319
  `);if(text!=="")return text}return""}function transcriptEntries(lines3){let entries=[],toolNames=new Map;for(let line of lines3)if(line.type==="system"&&line.subtype==="init"){let model=typeof line.model=="string"?` (${line.model})`:"";entries.push({role:"system",text:`Session started${model}`})}else if(line.type==="assistant")for(let block of blocksOf(line))block.type==="text"&&typeof block.text=="string"?entries.push({role:"assistant",text:block.text}):block.type==="tool_use"&&typeof block.name=="string"&&(typeof block.id=="string"&&toolNames.set(block.id,block.name),entries.push({role:"assistant",text:"",tool:block.name,input:block.input}));else if(line.type==="user")for(let block of blocksOf(line))if(block.type==="tool_result"){let tool=typeof block.tool_use_id=="string"?toolNames.get(block.tool_use_id):void 0;entries.push({role:"tool",text:resultText(block.content),...tool===void 0?{}:{tool}})}else block.type==="text"&&typeof block.text=="string"&&entries.push({role:"user",text:block.text});return entries}var HARNESS_ID="claude-code",DEFAULT_COMMAND="claude",HEADLESS_ARGS=["-p","--output-format","stream-json","--verbose"],claudeHarness={id:HARNESS_ID,description:"Claude Code, started with the `claude` command.",async launch(args,ctx){let settings=toolSettings(ctx,HARNESS_ID);return ctx.services.get("host.processes").runInteractive(settings.command??DEFAULT_COMMAND,launchArguments(settings,args,ctx),{...ctx.project?{cwd:ctx.project.root}:{},env:ctx.env,label:HARNESS_ID})},async runHeadless(request,ctx){let settings=toolSettings(ctx,HARNESS_ID),model=request.model??ctx.options()?.model,command=settings.headless?.command??settings.command??DEFAULT_COMMAND,args=[...settings.headless?.args??[],...HEADLESS_ARGS,...model===void 0?[]:["--model",model],...passed(request.options)],cwd=request.cwd??ctx.project?.root,result=await ctx.services.get("host.processes").run(command,args,{...cwd===void 0?{}:{cwd},env:ctx.env,input:request.prompt,...request.timeoutMs===void 0?{}:{timeoutMs:request.timeoutMs},...request.signal===void 0?{}:{signal:request.signal},label:`${HARNESS_ID} (headless)`});if(result.timedOut)throw new SousError35(`claude did not finish within ${request.timeoutMs}ms.`);let raw2={stdout:result.stdout,stderr:result.stderr},output=finalText(parseStream(result.stdout));return{harness:HARNESS_ID,exitCode:result.exitCode,output,durationMs:result.durationMs,raw:raw2}},readTranscript(run){let raw2=run.raw;return{harness:HARNESS_ID,entries:transcriptEntries(parseStream(raw2?.stdout??""))}}};function passed(options2){let args=options2?.args;return Array.isArray(args)?args.filter(arg=>typeof arg=="string"):[]}import path109 from"node:path";var TARGETS_CONTRIBUTOR3="claude-code/targets",TARGET_ID="claude-code",SKILLS_DIRECTORY=".claude/skills",MEMORIES_OUTPUT_PATH="${projectRoot}/.claude/rules/SOUS-MEMORIES.md",POINTER_FILE="CLAUDE.md";function contributeTargets(config2){let options2=config2.options()??{},skills={id:TARGET_ID,harness:HARNESS_ID,directory:options2.skillsDirectory??SKILLS_DIRECTORY,description:"Claude Code reads skills from .claude/skills."};if(config2.addEntity("skill-target",skills),config2.addEntity("pointer-file",{id:TARGET_ID,fileName:POINTER_FILE}),options2.memories!==!1){let memories={id:TARGET_ID,harness:HARNESS_ID,outputPath:options2.memoriesOutputPath??MEMORIES_OUTPUT_PATH,backupExisting:!0};config2.addEntity("memory-target",memories)}}function outputDirectory(directory){let trimmed=directory.trim().replace(/\/+$/,"");return trimmed.startsWith("${")||trimmed.startsWith("/")||/^[A-Za-z]:[\\/]/.test(trimmed)?trimmed:`\${projectRoot}/${trimmed.replace(/^\.\/+/,"")}`}var targetsContributor2={id:TARGETS_CONTRIBUTOR3,contribute:contributeTargets};var PLUGIN_KIND="claude-code-plugin",AGENT_KIND="claude-code-agent",AGENTS_DIRECTORY=".claude/agents",KINDS_CONTRIBUTOR="claude-code/kinds",CONTENT_KINDS2=[{id:PLUGIN_KIND,description:"A Claude Code plugin folder (one holding .claude-plugin/plugin.json): each folder directly under the include pattern's fixed part is written to .claude/skills/<folder>, for Claude Code only."},{id:AGENT_KIND,description:"Claude Code agent files (Markdown with frontmatter), written to .claude/agents/ with their sub-folders kept, for Claude Code only."}];function contentTargets(kind,contents,directory,plugin){let targets=[];for(let content of contents)for(let file2 of content.files){let fromBase=path109.relative(file2.base,file2.file).split(path109.sep).join("/"),id=`${kind}/${content.recipe}/${fromBase}`,origin={plugin,recipe:content.recipe};if(!(fromBase===""||fromBase.startsWith("../"))){if(file2.content!==void 0){targets.push({id,content:inlineTemplate2(file2.content,fromBase),origin,outputs:[{destinationFile:`${directory}/${withoutTpl(fromBase)}`,harness:HARNESS_ID}]});continue}targets.push({id,entryPoint:file2.file,globBase:file2.base,origin,outputs:[{destinationDir:directory,harness:HARNESS_ID}]})}}return targets}function withoutTpl(relative4){let name=path109.posix.basename(relative4);return name.includes(".tpl.")?path109.posix.join(path109.posix.dirname(relative4),name.replace(".tpl.",".")):relative4}function inlineTemplate2(content,virtualPath){return path109.posix.basename(virtualPath).includes(".tpl.")?content:`{% raw %}${content}{% endraw %}`}function contributeKinds(config2,contents,plugin){let options2=config2.options()??{},list2=config2.atPath("compilation.targets"),plugins=contentTargets(PLUGIN_KIND,contents.of(config2,PLUGIN_KIND),outputDirectory(options2.skillsDirectory??SKILLS_DIRECTORY),plugin),agents=contentTargets(AGENT_KIND,contents.of(config2,AGENT_KIND),outputDirectory(AGENTS_DIRECTORY),plugin);for(let target of[...plugins,...agents])list2.appendValue(target)}function kindsContributor(plugin,services){return{id:KINDS_CONTRIBUTOR,contribute:config2=>contributeKinds(config2,services.get("recipes.contents"),plugin)}}import fs81 from"node:fs";import path110 from"node:path";var LOCATION_QUESTION="claude-code.memories",REMOVE_LINE_QUESTION="claude-code.memories.remove-line",PLUGIN4="@sous-io/sous-plugin-claude-code",FORMER_PLUGIN4="@sous-io/plugin-claude-code",OUTPUT_PATH_KEY=`plugins.options."${PLUGIN4}".memoriesOutputPath`,ROOT_CLAUDE_MD="${projectRoot}/CLAUDE.md",KEEP_LAYER="600-claude-code-memories.jsonc",OLD_TARGET_ID="memories/claude-code",RECIPES_LINE="@#memories/**/*.md",PROJECT_LINE="@memories/**/*.md",MEMORIES_SOURCE2="MEMORIES.tpl.md";function sourceComment(lines3){let described=lines3.map(line=>line===PROJECT_LINE?` ${PROJECT_LINE} this project's own memories: every markdown file under \`.sous/memories/\``:` ${RECIPES_LINE} the memories of every recipe this project subscribes to`);return`{% comment %}
@@ -1331,7 +1332,7 @@ ${lines3.join(`
1331
1332
  `}var MOVE_SOURCE=sourceComment([PROJECT_LINE,RECIPES_LINE]),KEEP_SOURCE=sourceComment([RECIPES_LINE]);function options(ctx){return ctx.config.get(["plugins","options",PLUGIN4])??ctx.config.get(["plugins","options",FORMER_PLUGIN4])??{}}function rootClaudeMd(root){return path110.join(root,"CLAUDE.md")}function findIncludeLines(ctx){if(ctx.project===void 0)return[];let targets=ctx.config.get("compilation.targets")??[],files=ctx.config.get("compilation.files")??[],destination=rootClaudeMd(ctx.project.root),sources=new Set(files.filter(file2=>path110.resolve(file2.destination)===destination&&targets[file2.targetIndex]?.origin?.plugin===void 0).map(file2=>file2.source)),found=[];for(let source of sources){let text;try{text=fs81.readFileSync(source,"utf8")}catch{continue}text.split(`
1332
1333
  `).forEach((line,index)=>{line.trim()===RECIPES_LINE&&found.push({file:source,line:index+1})})}return found}function compiledFromMemories(ctx){if(ctx.project===void 0)return[];let targets=ctx.config.get("compilation.targets")??[],files=ctx.config.get("compilation.files")??[],memoriesDir=path110.join(ctx.project.sousDir,"memories")+path110.sep;return[...new Set(files.filter(file2=>targets[file2.targetIndex]?.origin?.plugin===void 0&&path110.resolve(file2.source).startsWith(memoriesDir)).map(file2=>file2.source))]}function oldDefaultWrote(ctx){if(ctx.project===void 0||!ctx.services.has("compiler.state"))return!1;let destination=rootClaudeMd(ctx.project.root);return ctx.services.get("compiler.state").entries().some(entry=>entry.target===OLD_TARGET_ID&&path110.resolve(ctx.project.root,entry.dest)===destination)}function oldDefaultWould(ctx){if(ctx.project===void 0||!ctx.services.has("memories.selection"))return!1;let targets=ctx.config.get("compilation.targets")??[],files=ctx.config.get("compilation.files")??[],destination=rootClaudeMd(ctx.project.root);return!files.some(file2=>path110.resolve(file2.destination)===destination&&targets[file2.targetIndex]?.origin?.plugin===void 0)&&ctx.services.get("memories.selection").selected().length>0}function situation(ctx){if(ctx.project===void 0)return{nothing:"There is no project here.",lines:[],alsoCompiled:[]};let own=options(ctx);if(own.memories===!1)return{nothing:"The Claude Code memories file is switched off (memories: false), so nothing changed.",lines:[],alsoCompiled:[]};if(own.memoriesOutputPath!==void 0)return{nothing:`memoriesOutputPath is already set (${own.memoriesOutputPath}), so the choice is made and nothing changed.`,lines:[],alsoCompiled:[]};let lines3=findIncludeLines(ctx);return lines3.length===0&&!oldDefaultWrote(ctx)&&!oldDefaultWould(ctx)?{nothing:"Sous never wrote the recipes' memories into the root CLAUDE.md here, so nothing changed.",lines:lines3,alsoCompiled:[]}:{lines:lines3,alsoCompiled:compiledFromMemories(ctx)}}function writeSource(sousDir,text){let file2=path110.join(sousDir,MEMORIES_SOURCE2);if(!fs81.existsSync(file2))return fs81.mkdirSync(sousDir,{recursive:!0}),fs81.writeFileSync(file2,text),file2}function removeLines(lines3){let byFile=new Map;for(let{file:file2,line}of lines3)byFile.set(file2,(byFile.get(file2)??new Set).add(line));for(let[file2,numbers]of byFile){let source=fs81.readFileSync(file2,"utf8").split(`
1333
1334
  `),kept=[];for(let index=0;index<source.length;index++){let line=source[index]??"";if(!(numbers.has(index+1)&&line.trim()===RECIPES_LINE)){kept.push(line);continue}let blankBefore=kept.length===0||kept.at(-1)?.trim()==="",blankAfter=index+1<source.length-1&&source[index+1]?.trim()==="";blankBefore&&blankAfter&&index++}fs81.writeFileSync(file2,kept.join(`
1334
- `))}}function keepFile(ctx){let main2=ctx.project?.configPath;return main2!==void 0&&/\.(jsonc?|ya?ml)$/.test(main2)?void 0:KEEP_LAYER}async function migrateMemories(ctx,answers){let found=situation(ctx);if(found.nothing!==void 0||ctx.project===void 0)return{summary:found.nothing??"There is no project here."};let label=file2=>path110.relative(ctx.project.root,file2),details=[];if(answers[LOCATION_QUESTION]==="keep"){let file2=keepFile(ctx);file2!==void 0&&fs81.mkdirSync(ctx.project.confDir,{recursive:!0}),await ctx.run("config.set",{path:OUTPUT_PATH_KEY,value:JSON.stringify(ROOT_CLAUDE_MD),...file2===void 0?{}:{file:file2}}),details.push(`Set ${OUTPUT_PATH_KEY} to ${ROOT_CLAUDE_MD} in ${file2===void 0?label(ctx.project.configPath):`.sous/conf.d/${file2}`}.`);let written2=writeSource(ctx.project.sousDir,KEEP_SOURCE);return written2!==void 0&&details.push(`Wrote ${label(written2)}, which includes only the recipes' memories, as CLAUDE.md did.`),ctx.configChanged(),{summary:"The recipes' memories stay in the root CLAUDE.md.",details}}let written=writeSource(ctx.project.sousDir,MOVE_SOURCE);if(written!==void 0&&details.push(`Wrote ${label(written)} with the default lines: this project's memories, then the recipes'.`),found.lines.length>0){let where3=found.lines.map(line=>`${label(line.file)}:${line.line}`).join(", ");answers[REMOVE_LINE_QUESTION]==="yes"?(removeLines(found.lines),details.push(`Removed the line ${RECIPES_LINE} from ${where3}, so the root CLAUDE.md no longer repeats the recipes' memories.`)):details.push(`Left the line ${RECIPES_LINE} in ${where3}: Claude Code will read the recipes' memories twice, in CLAUDE.md and in .claude/rules/SOUS-MEMORIES.md.`)}for(let source of found.alsoCompiled)details.push(`${label(source)} is compiled by a target of this project and is also included by the new memories file, so its text reaches Claude Code twice. Remove that target, or the line ${PROJECT_LINE} from .sous/${MEMORIES_SOURCE2}.`);return ctx.configChanged(),{summary:"The recipes' memories now go to .claude/rules/SOUS-MEMORIES.md.",details}}function memoriesMigration(version2){return{version:version2,id:"claude-code/memories-file",description:"Move the recipes' memories out of the root CLAUDE.md into .claude/rules/SOUS-MEMORIES.md, or keep them in CLAUDE.md.",questions:[{id:LOCATION_QUESTION,message:"Sous now writes the recipes' memories to .claude/rules/SOUS-MEMORIES.md instead of the root CLAUDE.md. Where should they go?",choices:[{value:"move",label:"To .claude/rules/SOUS-MEMORIES.md, the new default (Claude Code reads it beside CLAUDE.md)"},{value:"keep",label:"To the root CLAUDE.md, as before (sets memoriesOutputPath)"}],default:"move",answered:ctx=>situation(ctx).nothing===void 0?void 0:"move"},{id:REMOVE_LINE_QUESTION,message:`Your own source for the root CLAUDE.md includes the recipes' memories with the line ${RECIPES_LINE}, so after the move they would be read twice. Remove that line?`,default:"no",answered:(ctx,earlier)=>earlier[LOCATION_QUESTION]==="keep"||situation(ctx).lines.length===0?"no":void 0}],up:(ctx,{answers})=>migrateMemories(ctx,answers)}}init_src();import fs82 from"node:fs";import path111 from"node:path";var OLD_TOOL_KEY="claude";function editableFormat(file2){let name=path111.basename(file2);if(!(name.endsWith(".patch.json")||name.endsWith(".patch.jsonl"))){if(name.endsWith(".jsonc"))return"jsonc";if(name.endsWith(".json"))return"json";if(name.endsWith(".yaml")||name.endsWith(".yml"))return"yaml"}}function mentionsOldKey(text){return/(^|[\s{,])["']?claude["']?\s*:/m.test(text)||/tools[./]claude(?![-\w])/.test(text)}function renameInFile(file2,options2={}){let text;try{text=fs82.readFileSync(file2,"utf8")}catch{return}let format3=editableFormat(file2);if(format3===void 0)return mentionsOldKey(text)?{file:file2,result:"report"}:void 0;let document=parseDocument2(text,format3),old=document.atPath(["tools",OLD_TOOL_KEY]);if(old.exists())return document.atPath(["tools",HARNESS_ID]).exists()?{file:file2,result:"conflict"}:(old.rename(HARNESS_ID),options2.dryRun!==!0&&fs82.writeFileSync(file2,document.toString()),{file:file2,result:"renamed"})}function projectConfigFiles(ctx){let project=ctx.project;if(project===void 0)return[];let files=[],main2=ctx.services.has("config-files.loader")?ctx.services.get("config-files.loader").findMain(project.sousDir):project.configPath;return main2!==void 0&&files.push(main2),ctx.services.has("confd.files")&&files.push(...ctx.services.get("confd.files").list().map(entry=>entry.path)),files}function migrateToolsKey(ctx){let results=projectConfigFiles(ctx).map(file2=>renameInFile(file2)).filter(result=>result!==void 0),label=file2=>ctx.project===void 0?file2:path111.relative(ctx.project.root,file2),details=results.map(entry=>entry.result==="renamed"?`${label(entry.file)}: renamed tools.claude to tools.claude-code.`:entry.result==="conflict"?`${label(entry.file)}: sets both tools.claude and tools.claude-code, so nothing was changed. Merge tools.claude into tools.claude-code by hand, then remove it.`:`${label(entry.file)}: sous cannot edit this file, and it seems to set tools.claude. Rename that key to "claude-code" by hand.`);return results.length===0?{summary:"No config file sets tools.claude, so nothing changed."}:{summary:results.filter(entry=>entry.result==="renamed").length===results.length?"The Claude Code launch settings moved from tools.claude to tools.claude-code.":"Some config files still set tools.claude and must be changed by hand: the Claude Code settings key is now tools.claude-code.",details}}function toolsKeyMigration(version2){return{version:version2,order:400,id:"claude-code/tools-key",description:"Rename the Claude Code launch settings from tools.claude to tools.claude-code, the harness's new id.",up:ctx=>migrateToolsKey(ctx)}}var MIGRATIONS_VERSION="1.1.0";function registerMigrations(sous){sous.migrations.add(toolsKeyMigration(MIGRATIONS_VERSION)),sous.migrations.add(memoriesMigration(MIGRATIONS_VERSION))}import fs83 from"node:fs";import path112 from"node:path";var PLUGIN_MANIFEST=path112.join(".claude-plugin","plugin.json"),CHANGING=new Set(["created","updated","would-create","would-update"]);function pluginFolderOf(file2,root,exists3,removed=new Set){let resolvedRoot=path112.resolve(root),dir=path112.dirname(path112.resolve(file2));for(;dir===resolvedRoot||dir.startsWith(resolvedRoot+path112.sep);){let manifest=path112.join(dir,PLUGIN_MANIFEST);if(exists3(manifest)||removed.has(manifest))return dir;if(dir===resolvedRoot)break;dir=path112.dirname(dir)}}function reloadLine(names2,dryRun4){if(names2.length===0)return;let sorted2=[...new Set(names2)].sort(),subject2=sorted2.length===1?"A Claude Code plugin":"Claude Code plugins",verb=dryRun4?"would change":"changed",when=dryRun4?" after the build":"";return`${subject2} ${verb} (${sorted2.join(", ")}). Run /reload-plugins in any open Claude Code session${when}.`}function registerReloadLine(sous,exists3=fs83.existsSync){let pending=new Map,changesFor=chain=>{let key=chain??"none",changes=pending.get(key);return changes===void 0&&(changes={files:new Set,removed:new Set,dryRun:!1},pending.set(key,changes)),changes};sous.on("compiler.wrote",(event,ctx)=>{let changes=changesFor(ctx.chain?.id);changes.dryRun||=event.payload.dryRun;for(let file2 of event.payload.files)CHANGING.has(file2.action)&&changes.files.add(path112.resolve(file2.file))}),sous.on("compiler.pruned",(event,ctx)=>{let changes=changesFor(ctx.chain?.id);changes.dryRun||=event.payload.dryRun;for(let file2 of event.payload.removed)changes.files.add(path112.resolve(file2)),changes.removed.add(path112.resolve(file2))}),sous.on("build.after",(_event,ctx)=>{let key=ctx.chain?.id??"none",changes=pending.get(key);if(pending.delete(key),changes===void 0||ctx.project===void 0)return;let folders=new Set;for(let file2 of changes.files){let folder=pluginFolderOf(file2,ctx.project.root,exists3,changes.removed);folder!==void 0&&folders.add(path112.basename(folder))}let line=reloadLine([...folders],changes.dryRun);line!==void 0&&ctx.reporter.notice(line)})}var package_default32={name:"@sous-io/sous-plugin-claude-code",version:"1.1.4",description:"Everything sous knows about Claude Code: its harness, skill and memory targets, its content kinds, and its migrations.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-skills":"workspace:*","@sous-io/sous-plugin-memories":"workspace:*","@sous-io/sous-plugin-harnesses":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@sous-io/sous-plugin-recipes":"workspace:*","@sous-io/sous-plugin-compiler":"workspace:*","@sous-io/sous-plugin-migrations":"workspace:*","@sous-io/sous-lib-documents":"workspace:*","@sous-io/sous-plugin-config-files":"workspace:*","@sous-io/sous-plugin-confd":"workspace:*","@sous-io/sous-plugin-build":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*","@sous-io/sous-plugin-doctor":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME31="@sous-io/sous-plugin-claude-code",claudeCodePlugin=definePlugin32({name:PLUGIN_NAME31,version:package_default32.version,description:"Everything sous knows about Claude Code: its harness, skill and memory targets, its content kinds, and its migrations.",dependsOn:{"@sous-io/sous-plugin-skills":`^${package_default32.version}`,"@sous-io/sous-plugin-memories":`^${package_default32.version}`,"@sous-io/sous-plugin-harnesses":`^${package_default32.version}`,"@sous-io/sous-plugin-host":`^${package_default32.version}`,"@sous-io/sous-plugin-recipes":`^${package_default32.version}`,"@sous-io/sous-plugin-compiler":`^${package_default32.version}`,"@sous-io/sous-plugin-migrations":`^${package_default32.version}`},register(sous){let services=sous.services;sous.entities.add("harness",claudeHarness),sous.config.contribute(targetsContributor2);for(let kind of CONTENT_KINDS2)sous.entities.add("content-kind",{...kind});sous.config.contribute({...kindsContributor(PLUGIN_NAME31,services),after:["@sous-io/sous-plugin-recipes"]}),registerReloadLine(sous),registerMigrations(sous)}});import{definePlugin as definePlugin33}from"@sous-io/sous-plugin-api";import path113 from"node:path";var HARNESS_ID2="codex",DEFAULT_COMMAND2="codex",codexHarness={id:HARNESS_ID2,description:"Codex, started with the `codex` command.",async launch(args,ctx){let settings=toolSettings(ctx,HARNESS_ID2);return ctx.services.get("host.processes").runInteractive(settings.command??DEFAULT_COMMAND2,launchArguments(settings,args,ctx),{...ctx.project?{cwd:ctx.project.root}:{},env:ctx.env,label:HARNESS_ID2})}};var TARGETS_CONTRIBUTOR4="codex/targets",TARGET_ID2="codex",SKILLS_DIRECTORY2=".agents/skills",MEMORY_FILE="AGENTS.override.md",DEFAULT_MEMORIES_OUTPUT_PATH=`\${projectRoot}/${MEMORY_FILE}`,DEFAULT_PREPEND_MEMORIES_WITH="${projectRoot}/AGENTS.md",EDITOR_EDITS_KEY2=["editor","edits"],PROJECT_ROOT_PREFIX="${projectRoot}/";function isCodexOn(config2){let options2=config2.options(),tool=config2.atPath(["tools",HARNESS_ID2]).get();return isObject4(options2)||isObject4(tool)}function configPath2(value){return value.startsWith("${")||path113.isAbsolute(value)?value:`${PROJECT_ROOT_PREFIX}${value.replace(/^(\.\/)+/,"")}`}function ignoreLine(outputPath,projectRoot){let relative4;if(outputPath.startsWith(PROJECT_ROOT_PREFIX))relative4=outputPath.slice(PROJECT_ROOT_PREFIX.length);else if(projectRoot!==void 0&&path113.isAbsolute(outputPath)){let inside2=path113.relative(projectRoot,outputPath);inside2!==""&&!inside2.startsWith("..")&&!path113.isAbsolute(inside2)&&(relative4=inside2)}if(!(relative4===void 0||relative4.includes("${")))return`/${relative4.split(path113.sep).join("/").replace(/^\/+/,"")}`}function contributeTargets2(config2){if(!isCodexOn(config2))return;let options2=config2.options()??{};config2.addEntity("harness",codexHarness);let skills={id:TARGET_ID2,harness:HARNESS_ID2,directory:options2.skillsDirectory??SKILLS_DIRECTORY2,description:"Codex reads skills from .agents/skills."};if(config2.addEntity("skill-target",skills),options2.memories===!1)return;let outputPath=configPath2(options2.memoriesOutputPath??DEFAULT_MEMORIES_OUTPUT_PATH),memories={id:TARGET_ID2,harness:HARNESS_ID2,outputPath,prependWith:configPath2(options2.prependMemoriesWith??DEFAULT_PREPEND_MEMORIES_WITH),backupExisting:!0};config2.addEntity("memory-target",memories);let line=ignoreLine(outputPath,config2.project?.root);line!==void 0&&config2.entity("config-key","editor")!==void 0&&config2.atPath(EDITOR_EDITS_KEY2).append({file:".gitignore",ensureLine:{line}})}var targetsContributor3={id:TARGETS_CONTRIBUTOR4,contribute:contributeTargets2};function isObject4(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}var package_default33={name:"@sous-io/sous-plugin-codex",version:"1.1.4",description:"Everything sous knows about Codex: its harness, its memories file (AGENTS.override.md) and its skills folder. Off until a project turns it on.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-skills":"workspace:*","@sous-io/sous-plugin-memories":"workspace:*","@sous-io/sous-plugin-harnesses":"workspace:*","@sous-io/sous-plugin-host":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME32="@sous-io/sous-plugin-codex",codexPlugin=definePlugin33({name:PLUGIN_NAME32,version:package_default33.version,description:"Everything sous knows about Codex: its harness, its memories file (AGENTS.override.md) and its skills folder. Off until a project turns it on.",dependsOn:{"@sous-io/sous-plugin-skills":`^${package_default33.version}`,"@sous-io/sous-plugin-memories":`^${package_default33.version}`,"@sous-io/sous-plugin-harnesses":`^${package_default33.version}`,"@sous-io/sous-plugin-host":`^${package_default33.version}`},register(sous){sous.config.contribute(targetsContributor3)}});import path118 from"node:path";import{definePlugin as definePlugin34,jsonSchema as jsonSchema32}from"@sous-io/sous-plugin-api";init_src7();import{BufferedReporter as BufferedReporter4}from"@sous-io/sous-plugin-api";init_src();import fs86 from"node:fs";import path116 from"node:path";import{IntentOutput as IntentOutput23,IntentOutputs as IntentOutputs29}from"@sous-io/sous-plugin-api";init_src();import fs85 from"node:fs";import path115 from"node:path";init_src();init_src();var NoSuchDocumentError=class extends Error{constructor(message2){super(message2),this.name="NoSuchDocumentError"}};function openStreamDocument(text,format3,index){if(format3!=="yaml")throw new NoSuchDocumentError(`Only a YAML file holds several documents; this one is ${format3==="text"?"plain text":format3.toUpperCase()}.`);let stream=parseYamlStream(text),doc;try{doc=stream.document(index)}catch(error51){throw new NoSuchDocumentError(error51 instanceof Error?error51.message:String(error51))}return{...wrapTextDocument(doc,format3),toString:()=>stream.toString()}}var UnsupportedFormatError=class extends Error{constructor(format3){super(`Sous cannot edit ${format3.toUpperCase()} files yet.`);this.format=format3;this.name="UnsupportedFormatError"}};function formatForFile(file2){let format3=formatForPath(file2);return format3===void 0?file2.toLowerCase().endsWith(".toml")?"toml":"text":format3==="lines"?"text":format3}function commentStyleFor(file2){return commentStyleForPath(file2)}function openDocument(text,format3){switch(format3){case"json":case"jsonc":case"yaml":case"markdown":return wrapTextDocument(parseDocument2(text,format3),format3);case"text":return linesAsList(parseLines(text));case"toml":throw new UnsupportedFormatError(format3)}}function linesOfText(text){return parseLines(text).lines()}function wrapTextDocument(doc,format3){return{format:format3,root:()=>doc.root(),atPath:path122=>doc.atPath(path122),value:()=>doc.value(),toString:()=>doc.toString(),comments:doc}}function linesAsList(file2){let doc=createDocument(file2.lines());return{format:"text",root:()=>doc.root(),atPath:path122=>doc.atPath(path122),value:()=>doc.value(),toString(){let value=doc.value(),lines3=Array.isArray(value)?value.flatMap(line=>(typeof line=="string"?line:JSON.stringify(line)).split(/\r?\n/)):[];return file2.setLines(lines3),file2.toString()}}}function show(value){return value===void 0?"nothing":JSON.stringify(value)}function contains2(actual,expected){return Array.isArray(actual)?actual.some(item=>deepEqual(item,expected)||isJsonObject(expected)&&isJsonObject(item)&&isSubset(item,expected)):typeof actual=="string"?typeof expected=="string"&&actual.includes(expected):isJsonObject(actual)&&isJsonObject(expected)?isSubset(actual,expected):!1}function isSubset(actual,expected){return isJsonObject(expected)?isJsonObject(actual)&&Object.entries(expected).every(([key,value])=>Object.hasOwn(actual,key)&&isSubset(actual[key],value)):Array.isArray(expected)&&Array.isArray(actual)?expected.every(item=>actual.some(candidate=>deepEqual(candidate,item))):deepEqual(actual,expected)}function matchesFields(item,match2){return isJsonObject(item)&&isJsonObject(match2)&&Object.entries(match2).every(([key,value])=>deepEqual(item[key],value))}function sortOptions(arg){return typeof arg=="string"?{by:arg}:isJsonObject(arg)?{...typeof arg.by=="string"?{by:arg.by}:{},...arg.descending===!0?{descending:!0}:{}}:{}}function compareItems(a,b,options2={}){let left=options2.by!==void 0&&isJsonObject(a)?a[options2.by]:a,right=options2.by!==void 0&&isJsonObject(b)?b[options2.by]:b,result;if(typeof left=="number"&&typeof right=="number")result=left-right;else if(typeof left=="string"&&typeof right=="string")result=left<right?-1:left>right?1:0;else{let l=stableStringify(left??null),r=stableStringify(right??null);result=l<r?-1:l>r?1:0}return options2.descending?-result:result}function isSorted(items2,options2={}){return items2.every((item,index)=>index===0||compareItems(items2[index-1],item,options2)<=0)}function fingerprint(item,by2){return stableStringify(by2!==void 0&&isJsonObject(item)?item[by2]??null:item)}function textAt(subject2,path122){if(path122==="")return subject2.fileExists()?subject2.text():void 0;if(!subject2.parsed())return;let value=subject2.value(path122);return typeof value=="string"?value:void 0}function linesOf2(subject2,path122){let text=textAt(subject2,path122);return text===void 0?void 0:linesOfText(text)}function blockAt(subject2,path122,name){let text=textAt(subject2,path122);if(text!==void 0)try{return parseLines(text,{comment:commentStyleFor(subject2.file),label:subject2.file}).block(name)}catch{return}}function toRegExp(pattern){let literal2=/^\/(.*)\/([dgimsuvy]*)$/s.exec(pattern);return literal2?new RegExp(literal2[1],literal2[2]):new RegExp(pattern)}function textOf2(arg){return typeof arg=="string"?arg:JSON.stringify(arg)}function numberArg(arg){return typeof arg=="number"?arg:Number(arg)}var sizeCheck=(name,measure,max,unit)=>({name,reads:"size",async evaluate(subject2,arg){if(!subject2.fileExists())return!1;let size2=await measure(subject2);return max?size2<=numberArg(arg):size2>=numberArg(arg)},describe:arg=>`hold ${max?"at most":"at least"} ${textOf2(arg)} ${unit}`}),valueComparison=(name,holds,words2)=>({name,reads:"document",evaluate(subject2,arg,path122){let value=subject2.value(path122);return typeof value=="number"&&holds(value,numberArg(arg))},describe:arg=>`be ${words2} ${textOf2(arg)}`}),CHECK_LIST=[{name:"equals",reads:"document",evaluate:(subject2,arg,path122)=>deepEqual(subject2.value(path122),arg),describe:arg=>`equal ${show(arg)}`},{name:"includes",reads:"document",evaluate:(subject2,arg,path122)=>contains2(subject2.value(path122),arg),describe:arg=>`include ${show(arg)}`},{name:"excludes",reads:"document",evaluate:(subject2,arg,path122)=>!contains2(subject2.value(path122),arg),describe:arg=>`not include ${show(arg)}`},{name:"exists",reads:"document",boolean:!0,evaluate:(subject2,_arg,path122)=>subject2.value(path122)!==void 0,describe:()=>"exist"},{name:"first",reads:"document",evaluate(subject2,arg,path122){let value=subject2.value(path122);return Array.isArray(value)&&value.length>0&&deepEqual(value[0],arg)},describe:arg=>`have ${show(arg)} as its first member`},{name:"last",reads:"document",evaluate(subject2,arg,path122){let value=subject2.value(path122);return Array.isArray(value)&&value.length>0&&deepEqual(value[value.length-1],arg)},describe:arg=>`have ${show(arg)} as its last member`},{name:"at",reads:"document",evaluate(subject2,arg,path122){let value=subject2.value(path122);return Array.isArray(value)&&isJsonObject(arg)&&typeof arg.index=="number"&&deepEqual(value[arg.index],arg.item)},describe:arg=>isJsonObject(arg)?`have ${show(arg.item)} at index ${show(arg.index)}`:`have ${show(arg)} at an index`},{name:"itemWhere",reads:"document",evaluate(subject2,arg,path122){let value=subject2.value(path122);if(!Array.isArray(value)||!isJsonObject(arg))return!1;let match2=isJsonObject(arg.match)?arg.match:arg,found=value.find(item=>matchesFields(item,match2));return found!==void 0&&(arg.item===void 0||!isJsonObject(arg.match)||deepEqual(found,arg.item))},describe:arg=>isJsonObject(arg)&&isJsonObject(arg.match)?`have an item matching ${show(arg.match)}${arg.item===void 0?"":` equal to ${show(arg.item)}`}`:`have an item matching ${show(arg)}`},{name:"noItemWhere",reads:"document",evaluate(subject2,arg,path122){let value=subject2.value(path122);return!Array.isArray(value)||!value.some(item=>matchesFields(item,arg))},describe:arg=>`have no item matching ${show(arg)}`},{name:"unique",reads:"document",boolean:!0,evaluate(subject2,arg,path122){let value=subject2.value(path122),{by:by2}=sortOptions(arg);return Array.isArray(value)?new Set(value.map(item=>fingerprint(item,by2))).size===value.length:!1},describe:()=>"have unique members"},{name:"sorted",reads:"document",boolean:!0,evaluate(subject2,arg,path122){let value=subject2.value(path122);return Array.isArray(value)&&isSorted(value,sortOptions(arg))},describe:arg=>{let{by:by2,descending}=sortOptions(arg);return`be sorted${by2===void 0?"":` by ${by2}`}${descending?", descending":""}`}},{name:"sortedKeys",reads:"document",boolean:!0,evaluate(subject2,_arg,path122){let value=subject2.value(path122);return isJsonObject(value)&&isSorted(Object.keys(value))},describe:()=>"have its keys in order"},{name:"type",reads:"document",evaluate(subject2,arg,path122){let value=subject2.value(path122);return(value===void 0?"missing":value===null?"null":Array.isArray(value)?"array":typeof value)===arg},describe:arg=>`be ${/^[aeiou]/.test(textOf2(arg))?"an":"a"} ${textOf2(arg)}`},{name:"matches",reads:"document",evaluate(subject2,arg,path122){let value=subject2.value(path122);return typeof value=="string"&&typeof arg=="string"&&toRegExp(arg).test(value)},describe:arg=>`match ${textOf2(arg)}`},{name:"includesLine",reads:"text",evaluate:(subject2,arg,path122)=>linesOf2(subject2,path122)?.includes(textOf2(arg))??!1,describe:arg=>`contain the line ${show(arg)}`},{name:"includesBlock",reads:"text",evaluate(subject2,arg,path122){let name=isJsonObject(arg)?arg.name:arg,block=typeof name=="string"?blockAt(subject2,path122,name):void 0;if(block===void 0)return!1;let content=isJsonObject(arg)&&typeof arg.content=="string"?linesOfText(arg.content):void 0;return content===void 0||deepEqual(block,content)},describe:arg=>`contain the managed block ${show(isJsonObject(arg)?arg.name??null:arg)}`},valueComparison("lessThan",(a,b)=>a<b,"less than"),valueComparison("lessThanOrEqualTo",(a,b)=>a<=b,"less than or equal to"),valueComparison("greaterThan",(a,b)=>a>b,"greater than"),valueComparison("greaterThanOrEqualTo",(a,b)=>a>=b,"greater than or equal to"),{name:"fileExists",reads:"existence",boolean:!0,evaluate:subject2=>subject2.fileExists(),describe:()=>"exist"},{name:"fileDoesNotExist",reads:"existence",boolean:!0,evaluate:subject2=>!subject2.fileExists(),describe:()=>"not exist"},{name:"directoryExists",reads:"existence",boolean:!0,evaluate:subject2=>subject2.directoryExists(),describe:()=>"exist as a folder"},{name:"directoryDoesNotExist",reads:"existence",boolean:!0,evaluate:subject2=>!subject2.directoryExists(),describe:()=>"not exist as a folder"},sizeCheck("maxBytes",subject2=>Buffer.byteLength(subject2.text(),"utf8"),!0,"bytes"),sizeCheck("minBytes",subject2=>Buffer.byteLength(subject2.text(),"utf8"),!1,"bytes"),sizeCheck("maxCharacters",subject2=>[...subject2.text()].length,!0,"characters"),sizeCheck("minCharacters",subject2=>[...subject2.text()].length,!1,"characters"),sizeCheck("maxTokens",subject2=>subject2.tokens(),!0,"tokens (o200k_base, approximate)"),sizeCheck("minTokens",subject2=>subject2.tokens(),!1,"tokens (o200k_base, approximate)")],CHECKS=new Map(CHECK_LIST.map(check3=>[check3.name,check3]));function normalizeKind(kind){return kind==="include"?"includes":kind}var ASSERT_SETTINGS=new Set(["path","level","message","not"]);async function runCheck2(subject2,check3,arg,path122,not=!1){let definition2=CHECKS.get(check3);if(definition2===void 0)return!1;let negate=not;if(definition2.boolean&&arg===!1&&(negate=!negate),definition2.reads==="document"&&!subject2.parsed())return!1;let holds=await definition2.evaluate(subject2,arg,path122);return negate?!holds:holds}function describeCheck(check3,arg,not=!1){let definition2=CHECKS.get(check3),negate=definition2?.boolean&&arg===!1?!not:not,text=definition2?.describe(arg)??`${check3} ${show(arg)}`;return negate?`not ${text}`:text}import fs84 from"node:fs";import path114 from"node:path";var HISTORY_FILE_NAME="sous.edits.json";function emptyHistory(){return{version:1,entries:[],createdFiles:[],createdFolders:{}}}function toStored(file2,root){if(file2==="")return"";let relative4=path114.relative(root,file2);return relative4!==""&&!relative4.startsWith("..")&&!path114.isAbsolute(relative4)?relative4.split(path114.sep).join("/"):file2}function fromStored(file2,root){return file2===""?"":path114.resolve(root,file2)}function readHistory(file2,root){let parsed;try{parsed=JSON.parse(fs84.readFileSync(file2,"utf8"))}catch{return emptyHistory()}let value=parsed;return value===null||typeof value!="object"||!Array.isArray(value.entries)?emptyHistory():{version:1,entries:value.entries.map(entry=>({...entry,file:fromStored(entry.file,root)})),createdFiles:(value.createdFiles??[]).map(created=>fromStored(created,root)),createdFolders:Object.fromEntries(Object.entries(value.createdFolders??{}).map(([created,dirs])=>[fromStored(created,root),dirs.map(dir=>fromStored(dir,root))]))}}function writeHistory(file2,root,history){let stored={version:1,entries:history.entries.map(entry=>({...entry,file:toStored(entry.file,root)})),createdFiles:[...new Set(history.createdFiles.map(created=>toStored(created,root)))].sort(),createdFolders:Object.fromEntries(Object.entries(history.createdFolders).map(([created,dirs])=>[toStored(created,root),dirs.map(dir=>toStored(dir,root))]).sort(([a],[b])=>a<b?-1:a>b?1:0))};fs84.mkdirSync(path114.dirname(file2),{recursive:!0}),fs84.writeFileSync(file2,`${JSON.stringify(stored,null,2)}
1335
+ `))}}function keepFile(ctx){let main2=ctx.project?.configPath;return main2!==void 0&&/\.(jsonc?|ya?ml)$/.test(main2)?void 0:KEEP_LAYER}async function migrateMemories(ctx,answers){let found=situation(ctx);if(found.nothing!==void 0||ctx.project===void 0)return{summary:found.nothing??"There is no project here."};let label=file2=>path110.relative(ctx.project.root,file2),details=[];if(answers[LOCATION_QUESTION]==="keep"){let file2=keepFile(ctx);file2!==void 0&&fs81.mkdirSync(ctx.project.confDir,{recursive:!0}),await ctx.run("config.set",{path:OUTPUT_PATH_KEY,value:JSON.stringify(ROOT_CLAUDE_MD),...file2===void 0?{}:{file:file2}}),details.push(`Set ${OUTPUT_PATH_KEY} to ${ROOT_CLAUDE_MD} in ${file2===void 0?label(ctx.project.configPath):`.sous/conf.d/${file2}`}.`);let written2=writeSource(ctx.project.sousDir,KEEP_SOURCE);return written2!==void 0&&details.push(`Wrote ${label(written2)}, which includes only the recipes' memories, as CLAUDE.md did.`),ctx.configChanged(),{summary:"The recipes' memories stay in the root CLAUDE.md.",details}}let written=writeSource(ctx.project.sousDir,MOVE_SOURCE);if(written!==void 0&&details.push(`Wrote ${label(written)} with the default lines: this project's memories, then the recipes'.`),found.lines.length>0){let where3=found.lines.map(line=>`${label(line.file)}:${line.line}`).join(", ");answers[REMOVE_LINE_QUESTION]==="yes"?(removeLines(found.lines),details.push(`Removed the line ${RECIPES_LINE} from ${where3}, so the root CLAUDE.md no longer repeats the recipes' memories.`)):details.push(`Left the line ${RECIPES_LINE} in ${where3}: Claude Code will read the recipes' memories twice, in CLAUDE.md and in .claude/rules/SOUS-MEMORIES.md.`)}for(let source of found.alsoCompiled)details.push(`${label(source)} is compiled by a target of this project and is also included by the new memories file, so its text reaches Claude Code twice. Remove that target, or the line ${PROJECT_LINE} from .sous/${MEMORIES_SOURCE2}.`);return ctx.configChanged(),{summary:"The recipes' memories now go to .claude/rules/SOUS-MEMORIES.md.",details}}function memoriesMigration(version2){return{version:version2,id:"claude-code/memories-file",description:"Move the recipes' memories out of the root CLAUDE.md into .claude/rules/SOUS-MEMORIES.md, or keep them in CLAUDE.md.",questions:[{id:LOCATION_QUESTION,message:"Sous now writes the recipes' memories to .claude/rules/SOUS-MEMORIES.md instead of the root CLAUDE.md. Where should they go?",choices:[{value:"move",label:"To .claude/rules/SOUS-MEMORIES.md, the new default (Claude Code reads it beside CLAUDE.md)"},{value:"keep",label:"To the root CLAUDE.md, as before (sets memoriesOutputPath)"}],default:"move",answered:ctx=>situation(ctx).nothing===void 0?void 0:"move"},{id:REMOVE_LINE_QUESTION,message:`Your own source for the root CLAUDE.md includes the recipes' memories with the line ${RECIPES_LINE}, so after the move they would be read twice. Remove that line?`,default:"no",answered:(ctx,earlier)=>earlier[LOCATION_QUESTION]==="keep"||situation(ctx).lines.length===0?"no":void 0}],up:(ctx,{answers})=>migrateMemories(ctx,answers)}}init_src();import fs82 from"node:fs";import path111 from"node:path";var OLD_TOOL_KEY="claude";function editableFormat(file2){let name=path111.basename(file2);if(!(name.endsWith(".patch.json")||name.endsWith(".patch.jsonl"))){if(name.endsWith(".jsonc"))return"jsonc";if(name.endsWith(".json"))return"json";if(name.endsWith(".yaml")||name.endsWith(".yml"))return"yaml"}}function mentionsOldKey(text){return/(^|[\s{,])["']?claude["']?\s*:/m.test(text)||/tools[./]claude(?![-\w])/.test(text)}function renameInFile(file2,options2={}){let text;try{text=fs82.readFileSync(file2,"utf8")}catch{return}let format3=editableFormat(file2);if(format3===void 0)return mentionsOldKey(text)?{file:file2,result:"report"}:void 0;let document=parseDocument2(text,format3),old=document.atPath(["tools",OLD_TOOL_KEY]);if(old.exists())return document.atPath(["tools",HARNESS_ID]).exists()?{file:file2,result:"conflict"}:(old.rename(HARNESS_ID),options2.dryRun!==!0&&fs82.writeFileSync(file2,document.toString()),{file:file2,result:"renamed"})}function projectConfigFiles(ctx){let project=ctx.project;if(project===void 0)return[];let files=[],main2=ctx.services.has("config-files.loader")?ctx.services.get("config-files.loader").findMain(project.sousDir):project.configPath;return main2!==void 0&&files.push(main2),ctx.services.has("confd.files")&&files.push(...ctx.services.get("confd.files").list().map(entry=>entry.path)),files}function migrateToolsKey(ctx){let results=projectConfigFiles(ctx).map(file2=>renameInFile(file2)).filter(result=>result!==void 0),label=file2=>ctx.project===void 0?file2:path111.relative(ctx.project.root,file2),details=results.map(entry=>entry.result==="renamed"?`${label(entry.file)}: renamed tools.claude to tools.claude-code.`:entry.result==="conflict"?`${label(entry.file)}: sets both tools.claude and tools.claude-code, so nothing was changed. Merge tools.claude into tools.claude-code by hand, then remove it.`:`${label(entry.file)}: sous cannot edit this file, and it seems to set tools.claude. Rename that key to "claude-code" by hand.`);return results.length===0?{summary:"No config file sets tools.claude, so nothing changed."}:{summary:results.filter(entry=>entry.result==="renamed").length===results.length?"The Claude Code launch settings moved from tools.claude to tools.claude-code.":"Some config files still set tools.claude and must be changed by hand: the Claude Code settings key is now tools.claude-code.",details}}function toolsKeyMigration(version2){return{version:version2,order:400,id:"claude-code/tools-key",description:"Rename the Claude Code launch settings from tools.claude to tools.claude-code, the harness's new id.",up:ctx=>migrateToolsKey(ctx)}}var MIGRATIONS_VERSION="1.1.0";function registerMigrations(sous){sous.migrations.add(toolsKeyMigration(MIGRATIONS_VERSION)),sous.migrations.add(memoriesMigration(MIGRATIONS_VERSION))}import fs83 from"node:fs";import path112 from"node:path";var PLUGIN_MANIFEST=path112.join(".claude-plugin","plugin.json"),CHANGING=new Set(["created","updated","would-create","would-update"]);function pluginFolderOf(file2,root,exists3,removed=new Set){let resolvedRoot=path112.resolve(root),dir=path112.dirname(path112.resolve(file2));for(;dir===resolvedRoot||dir.startsWith(resolvedRoot+path112.sep);){let manifest=path112.join(dir,PLUGIN_MANIFEST);if(exists3(manifest)||removed.has(manifest))return dir;if(dir===resolvedRoot)break;dir=path112.dirname(dir)}}function reloadLine(names2,dryRun4){if(names2.length===0)return;let sorted2=[...new Set(names2)].sort(),subject2=sorted2.length===1?"A Claude Code plugin":"Claude Code plugins",verb=dryRun4?"would change":"changed",when=dryRun4?" after the build":"";return`${subject2} ${verb} (${sorted2.join(", ")}). Run /reload-plugins in any open Claude Code session${when}.`}function registerReloadLine(sous,exists3=fs83.existsSync){let pending=new Map,changesFor=chain=>{let key=chain??"none",changes=pending.get(key);return changes===void 0&&(changes={files:new Set,removed:new Set,dryRun:!1},pending.set(key,changes)),changes};sous.on("compiler.wrote",(event,ctx)=>{let changes=changesFor(ctx.chain?.id);changes.dryRun||=event.payload.dryRun;for(let file2 of event.payload.files)CHANGING.has(file2.action)&&changes.files.add(path112.resolve(file2.file))}),sous.on("compiler.pruned",(event,ctx)=>{let changes=changesFor(ctx.chain?.id);changes.dryRun||=event.payload.dryRun;for(let file2 of event.payload.removed)changes.files.add(path112.resolve(file2)),changes.removed.add(path112.resolve(file2))}),sous.on("build.after",(_event,ctx)=>{let key=ctx.chain?.id??"none",changes=pending.get(key);if(pending.delete(key),changes===void 0||ctx.project===void 0)return;let folders=new Set;for(let file2 of changes.files){let folder=pluginFolderOf(file2,ctx.project.root,exists3,changes.removed);folder!==void 0&&folders.add(path112.basename(folder))}let line=reloadLine([...folders],changes.dryRun);line!==void 0&&ctx.reporter.notice(line)})}var package_default32={name:"@sous-io/sous-plugin-claude-code",version:"1.1.6",description:"Everything sous knows about Claude Code: its harness, skill and memory targets, its content kinds, and its migrations.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-skills":"workspace:*","@sous-io/sous-plugin-memories":"workspace:*","@sous-io/sous-plugin-harnesses":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@sous-io/sous-plugin-recipes":"workspace:*","@sous-io/sous-plugin-compiler":"workspace:*","@sous-io/sous-plugin-migrations":"workspace:*","@sous-io/sous-lib-documents":"workspace:*","@sous-io/sous-plugin-config-files":"workspace:*","@sous-io/sous-plugin-confd":"workspace:*","@sous-io/sous-plugin-build":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*","@sous-io/sous-plugin-doctor":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME31="@sous-io/sous-plugin-claude-code",claudeCodePlugin=definePlugin32({name:PLUGIN_NAME31,version:package_default32.version,description:"Everything sous knows about Claude Code: its harness, skill and memory targets, its content kinds, and its migrations.",dependsOn:{"@sous-io/sous-plugin-skills":`^${package_default32.version}`,"@sous-io/sous-plugin-memories":`^${package_default32.version}`,"@sous-io/sous-plugin-harnesses":`^${package_default32.version}`,"@sous-io/sous-plugin-host":`^${package_default32.version}`,"@sous-io/sous-plugin-recipes":`^${package_default32.version}`,"@sous-io/sous-plugin-compiler":`^${package_default32.version}`,"@sous-io/sous-plugin-migrations":`^${package_default32.version}`},register(sous){let services=sous.services;sous.entities.add("harness",claudeHarness),sous.config.contribute(targetsContributor2);for(let kind of CONTENT_KINDS2)sous.entities.add("content-kind",{...kind});sous.config.contribute({...kindsContributor(PLUGIN_NAME31,services),after:["@sous-io/sous-plugin-recipes"]}),registerReloadLine(sous),registerMigrations(sous)}});import{definePlugin as definePlugin33}from"@sous-io/sous-plugin-api";import path113 from"node:path";var HARNESS_ID2="codex",DEFAULT_COMMAND2="codex",codexHarness={id:HARNESS_ID2,description:"Codex, started with the `codex` command.",async launch(args,ctx){let settings=toolSettings(ctx,HARNESS_ID2);return ctx.services.get("host.processes").runInteractive(settings.command??DEFAULT_COMMAND2,launchArguments(settings,args,ctx),{...ctx.project?{cwd:ctx.project.root}:{},env:ctx.env,label:HARNESS_ID2})}};var TARGETS_CONTRIBUTOR4="codex/targets",TARGET_ID2="codex",SKILLS_DIRECTORY2=".agents/skills",MEMORY_FILE="AGENTS.override.md",DEFAULT_MEMORIES_OUTPUT_PATH=`\${projectRoot}/${MEMORY_FILE}`,DEFAULT_PREPEND_MEMORIES_WITH="${projectRoot}/AGENTS.md",EDITOR_EDITS_KEY2=["editor","edits"],PROJECT_ROOT_PREFIX="${projectRoot}/";function isCodexOn(config2){let options2=config2.options(),tool=config2.atPath(["tools",HARNESS_ID2]).get();return isObject4(options2)||isObject4(tool)}function configPath2(value){return value.startsWith("${")||path113.isAbsolute(value)?value:`${PROJECT_ROOT_PREFIX}${value.replace(/^(\.\/)+/,"")}`}function ignoreLine(outputPath,projectRoot){let relative4;if(outputPath.startsWith(PROJECT_ROOT_PREFIX))relative4=outputPath.slice(PROJECT_ROOT_PREFIX.length);else if(projectRoot!==void 0&&path113.isAbsolute(outputPath)){let inside2=path113.relative(projectRoot,outputPath);inside2!==""&&!inside2.startsWith("..")&&!path113.isAbsolute(inside2)&&(relative4=inside2)}if(!(relative4===void 0||relative4.includes("${")))return`/${relative4.split(path113.sep).join("/").replace(/^\/+/,"")}`}function contributeTargets2(config2){if(!isCodexOn(config2))return;let options2=config2.options()??{};config2.addEntity("harness",codexHarness);let skills={id:TARGET_ID2,harness:HARNESS_ID2,directory:options2.skillsDirectory??SKILLS_DIRECTORY2,description:"Codex reads skills from .agents/skills."};if(config2.addEntity("skill-target",skills),options2.memories===!1)return;let outputPath=configPath2(options2.memoriesOutputPath??DEFAULT_MEMORIES_OUTPUT_PATH),memories={id:TARGET_ID2,harness:HARNESS_ID2,outputPath,prependWith:configPath2(options2.prependMemoriesWith??DEFAULT_PREPEND_MEMORIES_WITH),backupExisting:!0};config2.addEntity("memory-target",memories);let line=ignoreLine(outputPath,config2.project?.root);line!==void 0&&config2.entity("config-key","editor")!==void 0&&config2.atPath(EDITOR_EDITS_KEY2).append({file:".gitignore",ensureLine:{line}})}var targetsContributor3={id:TARGETS_CONTRIBUTOR4,contribute:contributeTargets2};function isObject4(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}var package_default33={name:"@sous-io/sous-plugin-codex",version:"1.1.6",description:"Everything sous knows about Codex: its harness, its memories file (AGENTS.override.md) and its skills folder. Off until a project turns it on.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-skills":"workspace:*","@sous-io/sous-plugin-memories":"workspace:*","@sous-io/sous-plugin-harnesses":"workspace:*","@sous-io/sous-plugin-host":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};var PLUGIN_NAME32="@sous-io/sous-plugin-codex",codexPlugin=definePlugin33({name:PLUGIN_NAME32,version:package_default33.version,description:"Everything sous knows about Codex: its harness, its memories file (AGENTS.override.md) and its skills folder. Off until a project turns it on.",dependsOn:{"@sous-io/sous-plugin-skills":`^${package_default33.version}`,"@sous-io/sous-plugin-memories":`^${package_default33.version}`,"@sous-io/sous-plugin-harnesses":`^${package_default33.version}`,"@sous-io/sous-plugin-host":`^${package_default33.version}`},register(sous){sous.config.contribute(targetsContributor3)}});import path118 from"node:path";import{definePlugin as definePlugin34,jsonSchema as jsonSchema32}from"@sous-io/sous-plugin-api";init_src7();import{BufferedReporter as BufferedReporter4}from"@sous-io/sous-plugin-api";init_src();import fs86 from"node:fs";import path116 from"node:path";import{IntentOutput as IntentOutput23,IntentOutputs as IntentOutputs29}from"@sous-io/sous-plugin-api";init_src();import fs85 from"node:fs";import path115 from"node:path";init_src();init_src();var NoSuchDocumentError=class extends Error{constructor(message2){super(message2),this.name="NoSuchDocumentError"}};function openStreamDocument(text,format3,index){if(format3!=="yaml")throw new NoSuchDocumentError(`Only a YAML file holds several documents; this one is ${format3==="text"?"plain text":format3.toUpperCase()}.`);let stream=parseYamlStream(text),doc;try{doc=stream.document(index)}catch(error51){throw new NoSuchDocumentError(error51 instanceof Error?error51.message:String(error51))}return{...wrapTextDocument(doc,format3),toString:()=>stream.toString()}}var UnsupportedFormatError=class extends Error{constructor(format3){super(`Sous cannot edit ${format3.toUpperCase()} files yet.`);this.format=format3;this.name="UnsupportedFormatError"}};function formatForFile(file2){let format3=formatForPath(file2);return format3===void 0?file2.toLowerCase().endsWith(".toml")?"toml":"text":format3==="lines"?"text":format3}function commentStyleFor(file2){return commentStyleForPath(file2)}function openDocument(text,format3){switch(format3){case"json":case"jsonc":case"yaml":case"markdown":return wrapTextDocument(parseDocument2(text,format3),format3);case"text":return linesAsList(parseLines(text));case"toml":throw new UnsupportedFormatError(format3)}}function linesOfText(text){return parseLines(text).lines()}function wrapTextDocument(doc,format3){return{format:format3,root:()=>doc.root(),atPath:path122=>doc.atPath(path122),value:()=>doc.value(),toString:()=>doc.toString(),comments:doc}}function linesAsList(file2){let doc=createDocument(file2.lines());return{format:"text",root:()=>doc.root(),atPath:path122=>doc.atPath(path122),value:()=>doc.value(),toString(){let value=doc.value(),lines3=Array.isArray(value)?value.flatMap(line=>(typeof line=="string"?line:JSON.stringify(line)).split(/\r?\n/)):[];return file2.setLines(lines3),file2.toString()}}}function show(value){return value===void 0?"nothing":JSON.stringify(value)}function contains2(actual,expected){return Array.isArray(actual)?actual.some(item=>deepEqual(item,expected)||isJsonObject(expected)&&isJsonObject(item)&&isSubset(item,expected)):typeof actual=="string"?typeof expected=="string"&&actual.includes(expected):isJsonObject(actual)&&isJsonObject(expected)?isSubset(actual,expected):!1}function isSubset(actual,expected){return isJsonObject(expected)?isJsonObject(actual)&&Object.entries(expected).every(([key,value])=>Object.hasOwn(actual,key)&&isSubset(actual[key],value)):Array.isArray(expected)&&Array.isArray(actual)?expected.every(item=>actual.some(candidate=>deepEqual(candidate,item))):deepEqual(actual,expected)}function matchesFields(item,match2){return isJsonObject(item)&&isJsonObject(match2)&&Object.entries(match2).every(([key,value])=>deepEqual(item[key],value))}function sortOptions(arg){return typeof arg=="string"?{by:arg}:isJsonObject(arg)?{...typeof arg.by=="string"?{by:arg.by}:{},...arg.descending===!0?{descending:!0}:{}}:{}}function compareItems(a,b,options2={}){let left=options2.by!==void 0&&isJsonObject(a)?a[options2.by]:a,right=options2.by!==void 0&&isJsonObject(b)?b[options2.by]:b,result;if(typeof left=="number"&&typeof right=="number")result=left-right;else if(typeof left=="string"&&typeof right=="string")result=left<right?-1:left>right?1:0;else{let l=stableStringify(left??null),r=stableStringify(right??null);result=l<r?-1:l>r?1:0}return options2.descending?-result:result}function isSorted(items2,options2={}){return items2.every((item,index)=>index===0||compareItems(items2[index-1],item,options2)<=0)}function fingerprint(item,by2){return stableStringify(by2!==void 0&&isJsonObject(item)?item[by2]??null:item)}function textAt(subject2,path122){if(path122==="")return subject2.fileExists()?subject2.text():void 0;if(!subject2.parsed())return;let value=subject2.value(path122);return typeof value=="string"?value:void 0}function linesOf2(subject2,path122){let text=textAt(subject2,path122);return text===void 0?void 0:linesOfText(text)}function blockAt(subject2,path122,name){let text=textAt(subject2,path122);if(text!==void 0)try{return parseLines(text,{comment:commentStyleFor(subject2.file),label:subject2.file}).block(name)}catch{return}}function toRegExp(pattern){let literal2=/^\/(.*)\/([dgimsuvy]*)$/s.exec(pattern);return literal2?new RegExp(literal2[1],literal2[2]):new RegExp(pattern)}function textOf2(arg){return typeof arg=="string"?arg:JSON.stringify(arg)}function numberArg(arg){return typeof arg=="number"?arg:Number(arg)}var sizeCheck=(name,measure,max,unit)=>({name,reads:"size",async evaluate(subject2,arg){if(!subject2.fileExists())return!1;let size2=await measure(subject2);return max?size2<=numberArg(arg):size2>=numberArg(arg)},describe:arg=>`hold ${max?"at most":"at least"} ${textOf2(arg)} ${unit}`}),valueComparison=(name,holds,words2)=>({name,reads:"document",evaluate(subject2,arg,path122){let value=subject2.value(path122);return typeof value=="number"&&holds(value,numberArg(arg))},describe:arg=>`be ${words2} ${textOf2(arg)}`}),CHECK_LIST=[{name:"equals",reads:"document",evaluate:(subject2,arg,path122)=>deepEqual(subject2.value(path122),arg),describe:arg=>`equal ${show(arg)}`},{name:"includes",reads:"document",evaluate:(subject2,arg,path122)=>contains2(subject2.value(path122),arg),describe:arg=>`include ${show(arg)}`},{name:"excludes",reads:"document",evaluate:(subject2,arg,path122)=>!contains2(subject2.value(path122),arg),describe:arg=>`not include ${show(arg)}`},{name:"exists",reads:"document",boolean:!0,evaluate:(subject2,_arg,path122)=>subject2.value(path122)!==void 0,describe:()=>"exist"},{name:"first",reads:"document",evaluate(subject2,arg,path122){let value=subject2.value(path122);return Array.isArray(value)&&value.length>0&&deepEqual(value[0],arg)},describe:arg=>`have ${show(arg)} as its first member`},{name:"last",reads:"document",evaluate(subject2,arg,path122){let value=subject2.value(path122);return Array.isArray(value)&&value.length>0&&deepEqual(value[value.length-1],arg)},describe:arg=>`have ${show(arg)} as its last member`},{name:"at",reads:"document",evaluate(subject2,arg,path122){let value=subject2.value(path122);return Array.isArray(value)&&isJsonObject(arg)&&typeof arg.index=="number"&&deepEqual(value[arg.index],arg.item)},describe:arg=>isJsonObject(arg)?`have ${show(arg.item)} at index ${show(arg.index)}`:`have ${show(arg)} at an index`},{name:"itemWhere",reads:"document",evaluate(subject2,arg,path122){let value=subject2.value(path122);if(!Array.isArray(value)||!isJsonObject(arg))return!1;let match2=isJsonObject(arg.match)?arg.match:arg,found=value.find(item=>matchesFields(item,match2));return found!==void 0&&(arg.item===void 0||!isJsonObject(arg.match)||deepEqual(found,arg.item))},describe:arg=>isJsonObject(arg)&&isJsonObject(arg.match)?`have an item matching ${show(arg.match)}${arg.item===void 0?"":` equal to ${show(arg.item)}`}`:`have an item matching ${show(arg)}`},{name:"noItemWhere",reads:"document",evaluate(subject2,arg,path122){let value=subject2.value(path122);return!Array.isArray(value)||!value.some(item=>matchesFields(item,arg))},describe:arg=>`have no item matching ${show(arg)}`},{name:"unique",reads:"document",boolean:!0,evaluate(subject2,arg,path122){let value=subject2.value(path122),{by:by2}=sortOptions(arg);return Array.isArray(value)?new Set(value.map(item=>fingerprint(item,by2))).size===value.length:!1},describe:()=>"have unique members"},{name:"sorted",reads:"document",boolean:!0,evaluate(subject2,arg,path122){let value=subject2.value(path122);return Array.isArray(value)&&isSorted(value,sortOptions(arg))},describe:arg=>{let{by:by2,descending}=sortOptions(arg);return`be sorted${by2===void 0?"":` by ${by2}`}${descending?", descending":""}`}},{name:"sortedKeys",reads:"document",boolean:!0,evaluate(subject2,_arg,path122){let value=subject2.value(path122);return isJsonObject(value)&&isSorted(Object.keys(value))},describe:()=>"have its keys in order"},{name:"type",reads:"document",evaluate(subject2,arg,path122){let value=subject2.value(path122);return(value===void 0?"missing":value===null?"null":Array.isArray(value)?"array":typeof value)===arg},describe:arg=>`be ${/^[aeiou]/.test(textOf2(arg))?"an":"a"} ${textOf2(arg)}`},{name:"matches",reads:"document",evaluate(subject2,arg,path122){let value=subject2.value(path122);return typeof value=="string"&&typeof arg=="string"&&toRegExp(arg).test(value)},describe:arg=>`match ${textOf2(arg)}`},{name:"includesLine",reads:"text",evaluate:(subject2,arg,path122)=>linesOf2(subject2,path122)?.includes(textOf2(arg))??!1,describe:arg=>`contain the line ${show(arg)}`},{name:"includesBlock",reads:"text",evaluate(subject2,arg,path122){let name=isJsonObject(arg)?arg.name:arg,block=typeof name=="string"?blockAt(subject2,path122,name):void 0;if(block===void 0)return!1;let content=isJsonObject(arg)&&typeof arg.content=="string"?linesOfText(arg.content):void 0;return content===void 0||deepEqual(block,content)},describe:arg=>`contain the managed block ${show(isJsonObject(arg)?arg.name??null:arg)}`},valueComparison("lessThan",(a,b)=>a<b,"less than"),valueComparison("lessThanOrEqualTo",(a,b)=>a<=b,"less than or equal to"),valueComparison("greaterThan",(a,b)=>a>b,"greater than"),valueComparison("greaterThanOrEqualTo",(a,b)=>a>=b,"greater than or equal to"),{name:"fileExists",reads:"existence",boolean:!0,evaluate:subject2=>subject2.fileExists(),describe:()=>"exist"},{name:"fileDoesNotExist",reads:"existence",boolean:!0,evaluate:subject2=>!subject2.fileExists(),describe:()=>"not exist"},{name:"directoryExists",reads:"existence",boolean:!0,evaluate:subject2=>subject2.directoryExists(),describe:()=>"exist as a folder"},{name:"directoryDoesNotExist",reads:"existence",boolean:!0,evaluate:subject2=>!subject2.directoryExists(),describe:()=>"not exist as a folder"},sizeCheck("maxBytes",subject2=>Buffer.byteLength(subject2.text(),"utf8"),!0,"bytes"),sizeCheck("minBytes",subject2=>Buffer.byteLength(subject2.text(),"utf8"),!1,"bytes"),sizeCheck("maxCharacters",subject2=>[...subject2.text()].length,!0,"characters"),sizeCheck("minCharacters",subject2=>[...subject2.text()].length,!1,"characters"),sizeCheck("maxTokens",subject2=>subject2.tokens(),!0,"tokens (o200k_base, approximate)"),sizeCheck("minTokens",subject2=>subject2.tokens(),!1,"tokens (o200k_base, approximate)")],CHECKS=new Map(CHECK_LIST.map(check3=>[check3.name,check3]));function normalizeKind(kind){return kind==="include"?"includes":kind}var ASSERT_SETTINGS=new Set(["path","level","message","not"]);async function runCheck2(subject2,check3,arg,path122,not=!1){let definition2=CHECKS.get(check3);if(definition2===void 0)return!1;let negate=not;if(definition2.boolean&&arg===!1&&(negate=!negate),definition2.reads==="document"&&!subject2.parsed())return!1;let holds=await definition2.evaluate(subject2,arg,path122);return negate?!holds:holds}function describeCheck(check3,arg,not=!1){let definition2=CHECKS.get(check3),negate=definition2?.boolean&&arg===!1?!not:not,text=definition2?.describe(arg)??`${check3} ${show(arg)}`;return negate?`not ${text}`:text}import fs84 from"node:fs";import path114 from"node:path";var HISTORY_FILE_NAME="sous.edits.json";function emptyHistory(){return{version:1,entries:[],createdFiles:[],createdFolders:{}}}function toStored(file2,root){if(file2==="")return"";let relative4=path114.relative(root,file2);return relative4!==""&&!relative4.startsWith("..")&&!path114.isAbsolute(relative4)?relative4.split(path114.sep).join("/"):file2}function fromStored(file2,root){return file2===""?"":path114.resolve(root,file2)}function readHistory(file2,root){let parsed;try{parsed=JSON.parse(fs84.readFileSync(file2,"utf8"))}catch{return emptyHistory()}let value=parsed;return value===null||typeof value!="object"||!Array.isArray(value.entries)?emptyHistory():{version:1,entries:value.entries.map(entry=>({...entry,file:fromStored(entry.file,root)})),createdFiles:(value.createdFiles??[]).map(created=>fromStored(created,root)),createdFolders:Object.fromEntries(Object.entries(value.createdFolders??{}).map(([created,dirs])=>[fromStored(created,root),dirs.map(dir=>fromStored(dir,root))]))}}function writeHistory(file2,root,history){let stored={version:1,entries:history.entries.map(entry=>({...entry,file:toStored(entry.file,root)})),createdFiles:[...new Set(history.createdFiles.map(created=>toStored(created,root)))].sort(),createdFolders:Object.fromEntries(Object.entries(history.createdFolders).map(([created,dirs])=>[toStored(created,root),dirs.map(dir=>toStored(dir,root))]).sort(([a],[b])=>a<b?-1:a>b?1:0))};fs84.mkdirSync(path114.dirname(file2),{recursive:!0}),fs84.writeFileSync(file2,`${JSON.stringify(stored,null,2)}
1335
1336
  `,"utf8")}init_src();init_src();function commentOperations(){return[setCommentOperation("before"),setCommentOperation("after"),removeCommentOperation()]}function setCommentOperation(place){let name=place==="before"?"setCommentBefore":"setCommentAfter";return{name,order:100,scope:"document",summary:place==="before"?"The key or list item at `path` has this comment on the lines directly above it, indented like it; `text` may have several lines. The comment there is replaced, or one is added.":"The key or list item at `path` has this comment at the end of its line (one line). The comment there is replaced, or one is added.",params:["text"],args:["text"],normalize(raw2){if(commentPath(raw2,name),typeof raw2.text!="string")throw new OperationParamsError(`'${name}' needs 'text', the comment's words (without # or //).`);if(place==="after"&&/\r?\n/.test(raw2.text))throw new OperationParamsError(`'${name}': a comment after a value is one line; use setCommentBefore for several.`);return raw2},up(ctx,params){let comments=commentsOf(ctx,params,name),text=params.text;return onComment(name,()=>{if(sameWords(comments.comment(ctx.path,place),text))return{changed:!1};let source=comments.commentSource(ctx.path,place);return comments.setComment(ctx.path,place,text),{changed:!0,source}})},down(ctx,params,record2){if(isJsonObject(record2)&&record2.changed===!0&&typeof record2.source=="string"){let comments=commentsOf(ctx,params,name);onComment(name,()=>comments.restoreCommentSource(ctx.path,place,record2.source))}},mergeRecords:keepEarlier,assertions:()=>[]}}function removeCommentOperation(){let name="removeComment",placesOf=params=>{let neither=params.before===void 0&&params.after===void 0;return["before","after"].filter(place=>neither||params[place]===!0)};return{name,order:100,scope:"document",summary:"The key or list item at `path` has no comment: before it (`before: true`), after it (`after: true`), or, with neither, both.",params:["before","after"],args:[],normalize(raw2){commentPath(raw2,name);for(let place of["before","after"])if(raw2[place]!==void 0&&typeof raw2[place]!="boolean")throw new OperationParamsError(`'${name}': '${place}' must be true or false.`);if(raw2.before===!1&&raw2.after===!1)throw new OperationParamsError(`'${name}' with before and after both false removes nothing.`);return raw2},up(ctx,params){let comments=commentsOf(ctx,params,name);return onComment(name,()=>{let removed={};for(let place of placesOf(params))comments.comment(ctx.path,place)!==void 0&&(removed[place]=comments.commentSource(ctx.path,place),comments.removeComment(ctx.path,place));return Object.keys(removed).length===0?{changed:!1}:{changed:!0,...removed}})},down(ctx,params,record2){if(!isJsonObject(record2)||record2.changed!==!0)return;let comments=commentsOf(ctx,params,name);for(let place of["before","after"]){let source=record2[place];typeof source=="string"&&onComment(name,()=>comments.restoreCommentSource(ctx.path,place,source))}},mergeRecords(previous,next){return!isJsonObject(previous)||previous.changed!==!0?next:!isJsonObject(next)||next.changed!==!0?previous:{...next,...previous}},assertions:()=>[]}}function inDocument(definition2){return{...definition2,normalize(raw2){let params=definition2.normalize(raw2);return checkDocument(params,definition2),params},up:(ctx,params,previous)=>definition2.up(selected(ctx,params),params,previous),down:(ctx,params,record2)=>definition2.down(selected(ctx,params),params,record2),assertions:(params,path122)=>params.document===void 0?definition2.assertions(params,path122):[]}}function editsWholeText(name){return["ensureLine","removeLine","ensureBlock","appendText","prependText","replaceText","replacePattern"].includes(name)}function checkDocument(params,definition2){let document=params.document;if(document!==void 0){if(typeof document!="number"||!Number.isInteger(document)||document<0)throw new OperationParamsError(`'${definition2.name}': 'document' must be a whole number from 0 (the first document of the file is 0).`);if(definition2.scope!=="document")throw new OperationParamsError(`'${definition2.name}' acts on the whole file, so it takes no 'document'.`);if(editsWholeText(definition2.name)&&(typeof params.path!="string"||params.path===""))throw new OperationParamsError(`'${definition2.name}' at the root edits the whole file's text, so it takes no 'document'; give the 'path' of a string in that document.`)}}function selected(ctx,params){if(params.document===void 0)return ctx;let index=params.document;return{session:ctx.session,path:ctx.path,node:()=>documentAt(ctx.session,index).atPath(ctx.path)}}function documentAt(session,index){try{return session.document(index)}catch(error51){throw error51 instanceof NoSuchDocumentError?new EditNotPossible(error51.message):error51}}function addSelectDocument(fileHandle,valueHandle){for(let prototype of[fileHandle.prototype,valueHandle.prototype]){let record2=prototype.record;Object.defineProperty(prototype,"record",{value(operation2,args){return record2.call(this,operation2,this.document===void 0?args:withDocument(operation2,args,this.document))},writable:!0,configurable:!0})}let file2=fileHandle.prototype,at2=file2.at;Object.defineProperty(file2,"at",{value(path122){let handle9=at2.call(this,path122);return this.document!==void 0&&(handle9.document=this.document),handle9},writable:!0,configurable:!0}),Object.defineProperty(file2,"selectDocument",{value(index){if(!Number.isInteger(index)||index<0)throw new Error("selectDocument() takes the document's index, a whole number from 0.");return Object.assign(Object.create(Object.getPrototypeOf(this)),this,{document:index})},writable:!0,configurable:!0})}function withDocument(operation2,args,document){let names2=ALIASES.get(operation2)?.args??OPERATIONS.get(operation2)?.args??[],options2=args[names2.length];return[...names2.map((_2,index)=>args[index]),{...options2,document}]}function commentPath(raw2,name){if(typeof raw2.path!="string"||raw2.path==="")throw new OperationParamsError(`'${name}' needs the 'path' of a key or list item; the root has no comment of its own.`)}function commentsOf(ctx,params,name){let comments=documentAt(ctx.session,params.document).comments;if(comments===void 0)throw new EditNotPossible(`'${name}' needs a JSONC, YAML or Markdown file; ${ctx.session.file} is plain text, which has no keys.`);return comments}function onComment(name,act){try{return act()}catch(error51){throw error51 instanceof CommentError?new EditNotPossible(`'${name}': ${error51.message}`):error51}}function sameWords(current,text){let words2=value=>value.split(/\r?\n/).map(line=>line.trimEnd()).join(`
1336
1337
  `);return current!==void 0&&words2(current)===words2(text)}function keepEarlier(previous,next){return isJsonObject(previous)&&previous.changed===!0?previous:next}init_src();function commonParams(){return["path","assertion"]}function definition(spec){let allowed=new Set([...commonParams(),...spec.params]);return{...spec,normalize(raw2){for(let key of Object.keys(raw2))if(!allowed.has(key))throw new OperationParamsError(`'${spec.name}' has no parameter '${key}'. Its parameters: ${["path",...spec.params].join(", ")}.`);if(raw2.assertion!==void 0&&raw2.assertion!=="none")throw new OperationParamsError(`'${spec.name}': 'assertion' can only be "none".`);return checkPathParam(raw2,"path",spec.name),spec.normalize?spec.normalize(raw2):raw2}}}function shorthand(spec){let allowed=new Set([...commonParams(),...spec.params]);return{...spec,toCore(raw2){for(let key of Object.keys(raw2))if(!allowed.has(key))throw new OperationParamsError(`'${spec.name}' has no parameter '${key}'. Its parameters: ${["path",...spec.params].join(", ")}.`);return spec.toCore?spec.toCore(raw2):raw2}}}function checkPathParam(raw2,key,operation2){let value=raw2[key];if(value!=null){if(typeof value!="string")throw new OperationParamsError(`'${operation2}': '${key}' must be a string.`);if(!value.includes("${"))try{parsePath(value)}catch(error51){throw new OperationParamsError(`'${operation2}': ${error51 instanceof Error?error51.message:String(error51)}`)}}}function requireKey(raw2,key,operation2){if(raw2[key]===void 0)throw new OperationParamsError(`'${operation2}' needs '${key}'.`);return raw2[key]}function fieldsParam(raw2,key,operation2){let value=requireKey(raw2,key,operation2);if(!isJsonObject(value))throw new OperationParamsError(`'${operation2}': '${key}' must be an object of fields to match.`);return value}function booleanParam(raw2,key,operation2){if(raw2[key]!==void 0&&typeof raw2[key]!="boolean")throw new OperationParamsError(`'${operation2}': '${key}' must be true or false.`)}function itemsOf(raw2,operation2){if(raw2.items!==void 0)return Array.isArray(raw2.items)?[...raw2.items]:[raw2.items];if(raw2.item!==void 0)return[raw2.item];throw new OperationParamsError(`'${operation2}' needs 'items' (or 'item').`)}function without(raw2,...keys){return Object.fromEntries(Object.entries(raw2).filter(([key])=>!keys.includes(key)))}function listOf3(node){let value=node.get();return Array.isArray(value)?value:[]}function notAList(operation2,node){return new EditNotPossible(`'${operation2}' needs a list at ${node.pathString||"the root"}, and the value there is not one.`)}function nodeAt(ctx,path122){return ctx.session.document().atPath(path122)}function acted(record2){return isJsonObject(record2)&&(record2.changed===!0||record2.moved===!0)}function keepEarlier2(previous,next){return acted(previous)?previous:next}function normalizeDestination(raw2,operation2){let to=requireKey(raw2,"to",operation2);if(typeof to!="string"||to==="")throw new OperationParamsError(`'${operation2}' needs 'to', the path to ${operation2} the value to.`);checkPathParam(raw2,"to",operation2),booleanParam(raw2,"ifMissing",operation2);let from=typeof raw2.path=="string"?raw2.path:"";if(from==="")throw new OperationParamsError(`'${operation2}' needs the 'path' of the value to ${operation2}; the whole document cannot be ${operation2==="copy"?"copied":"moved"} into itself.`);if(!from.includes("${")&&!to.includes("${")){let a=parsePath(from),b=parsePath(to);if(isPathPrefix(a,b)||isPathPrefix(b,a))throw new OperationParamsError(`'${operation2}': 'to' (${to}) and 'path' (${from}) overlap; one holds the other.`);if(operation2==="move"&&typeof a.at(-1)=="number")throw new OperationParamsError(`'move' moves the value at a key, and ${from} is a list item; use 'moveItem' to move an item within its list.`)}return raw2}function setRecorded(node,value){let existed=node.exists(),current=node.get();return existed&&deepEqual(current,value)?{changed:!1}:(node.set(value),existed?{changed:!0,existed:!0,previous:current}:{changed:!0,existed:!1})}function restoreRecorded(node,record2){record2.existed===!0?node.set(record2.previous??null):node.exists()&&node.delete()}function checkItemTarget(operation2,target){let index=target.path[target.path.length-1];if(typeof index=="number"&&!target.exists())throw new EditNotPossible(`'${operation2}' cannot put a value at ${target.pathString}: there is no item ${index} there to replace.`)}function copyDefinition(){return definition({name:"copy",order:20,scope:"document",summary:"The value at `to` is a copy of the value at `path`; what `to` held is recorded and restored on a rollback. Nothing happens while `path` is missing. With `ifMissing: true`, only a missing `to` is filled.",params:["to","ifMissing"],args:["to"],normalize:raw2=>normalizeDestination(raw2,"copy"),up(ctx,params){let source=ctx.node();if(!source.exists())return{changed:!1};let target=nodeAt(ctx,params.to);return params.ifMissing===!0&&target.exists()?{changed:!1}:(checkItemTarget("copy",target),setRecorded(target,source.get()))},down(ctx,params,record2){acted(record2)&&restoreRecorded(nodeAt(ctx,params.to),record2)},mergeRecords:keepEarlier2,assertions:()=>[]})}function splitKey(path122){let segments=parsePath(path122),last2=segments[segments.length-1];return typeof last2=="string"?{parent:segments.slice(0,-1),key:last2}:void 0}function sameObject(ctx,from,to){let a=splitKey(from),b=splitKey(to);if(!(a===void 0||b===void 0||formatPath(a.parent)!==formatPath(b.parent)))return isJsonObject(ctx.session.document().atPath(a.parent).get())?{fromKey:a.key,toKey:b.key}:void 0}function placeOf(node){let keys=node.parent().keys(),at2=keys.indexOf(node.path[node.path.length-1]);return at2<=0?{first:!0}:{after:keys[at2-1]}}function putBack(node,record2){let value=record2.value??null,last2=node.path[node.path.length-1],parent=node.parent(),existed=node.exists();if(isJsonObject(record2.entry)&&!existed){node.restoreEntrySource(value,record2.entry);return}node.set(value),!existed&&(record2.first===!0?parent.moveKeyFirst(last2):typeof record2.after=="string"&&parent.moveKeyAfter(last2,record2.after))}function setMoved(target,value,entry){let key=target.path[target.path.length-1],parent=target.parent();if(entry===void 0||target.exists()||typeof key!="string"||!parent.isObject()){target.set(value);return}parent.insertKey(key,value,{index:parent.keys().length},entry.source)}function moveDefinition(){return definition({name:"move",order:20,scope:"document",summary:"The value at `path` moves to `to`, replacing what `to` held (recorded, and restored on a rollback). Within one object it is a rename, keeping the value's text, comments and place. Nothing happens while `path` is missing. With `ifMissing: true`, it moves only when `to` is missing.",params:["to","ifMissing"],args:["to"],normalize:raw2=>normalizeDestination(raw2,"move"),up(ctx,params){let source=ctx.node();if(!source.exists())return{moved:!1};let to=params.to,target=nodeAt(ctx,to),existed=target.exists();if(params.ifMissing===!0&&existed)return{moved:!1};let value=source.get(),replaced=existed?{existed:!0,previous:target.get()}:{existed:!1},rename3=sameObject(ctx,ctx.path,to);if(rename3!==void 0)return source.rename(rename3.toKey),{moved:!0,renamed:!0,...replaced};checkItemTarget("move",target);let place=placeOf(source),entry=source.entrySource();return source.delete(),setMoved(target,value,entry),{moved:!0,value,...place,...entry===void 0?{}:{entry},...replaced}},down(ctx,params,record2){if(!acted(record2))return;let entry=record2,source=ctx.node(),target=nodeAt(ctx,params.to);if(entry.renamed===!0){let key=splitKey(ctx.path).key;target.exists()&&!source.exists()&&target.rename(key)}else putBack(source,entry);restoreRecorded(target,entry)},mergeRecords:keepEarlier2,assertions:(params,path122)=>params.ifMissing===!0?[]:[{check:"exists",arg:!1,path:path122}]})}function insertWhereDefinition(name){let before=name==="insertBeforeWhere";return definition({name,order:40,scope:"document",action:!0,summary:`Adds the items just ${before?"before":"after"} the first item matching \`where\`, or at the end when no item matches, even if they are already there (an action: Sous does it once, when the entry is first applied). A missing list is created.`,params:["where","items","item"],args:["where","item"],normalize(raw2){return fieldsParam(raw2,"where",name),{...without(raw2,"item"),items:itemsOf(raw2,name)}},up(ctx,params){let node=ctx.node(),value=node.get();if(value!==void 0&&!Array.isArray(value))throw notAList(name,node);value===void 0&&node.set([]);let list2=listOf3(node),at2=list2.findIndex(item=>matchesFields(item,params.where)),index=at2===-1?list2.length:before?at2:at2+1,added=[];for(let item of params.items)node.insertAt(index,item),added.push({item,index}),index+=1;return{added,matched:at2!==-1,...value===void 0?{created:!0}:{}}},down(ctx,_params,record2){if(!isJsonObject(record2))return;let node=ctx.node();for(let entry of[...record2.added??[]].reverse()){let list2=listOf3(node),at2=entry.index,index=deepEqual(list2[at2],entry.item)?at2:-1;for(let i=list2.length-1;index===-1&&i>=0;i--)deepEqual(list2[i],entry.item)&&(index=i);index!==-1&&node.removeAt(index)}record2.created===!0&&Array.isArray(node.get())&&listOf3(node).length===0&&node.delete()},assertions:(params,path122)=>params.items.map(item=>({check:"includes",arg:item,path:path122}))})}function readPlace(value,operation2){let message2=`'${operation2}': 'position' must be first, last, an index from 0, { before: item }, { after: item }, { beforeWhere: {...} } or { afterWhere: {...} }.`;if(value==null)throw new OperationParamsError(`'${operation2}' needs 'position', where the item goes.`);if(isJsonObject(value)){for(let side of["before","after"]){let fields=value[`${side}Where`];if(fields!==void 0){if(!isJsonObject(fields))throw new OperationParamsError(`'${operation2}': '${side}Where' must be an object of fields to match.`);return{kind:side,anchor:fields,where:!0}}if(value[side]!==void 0)return{kind:side,anchor:value[side],where:!1}}if(value.line!==void 0)throw new OperationParamsError(message2)}let position;try{position=parsePosition(value,operation2)}catch{throw new OperationParamsError(message2)}switch(position.kind){case"start":return{kind:"start"};case"index":return{kind:"index",index:position.index};default:return{kind:"end"}}}function findItem(items2,params){return params.where!==void 0?items2.findIndex(item=>matchesFields(item,params.where)):items2.findIndex(item=>deepEqual(item,params.item))}function moveItemDefinition(){return definition({name:"moveItem",order:95,scope:"document",summary:"The list item equal to `item` (or the first matching `where`) is at `position`: first, last, an index, or just before or after another item. Nothing happens when the item, or the item to put it beside, is not in the list. Undone by moving it back.",params:["item","where","position"],args:["item","position"],normalize(raw2){if(raw2.item===void 0==(raw2.where===void 0))throw new OperationParamsError("'moveItem' needs exactly one of 'item' (the item itself) and 'where' (fields it has).");return raw2.where!==void 0&&fieldsParam(raw2,"where","moveItem"),readPlace(raw2.position,"moveItem"),raw2},up(ctx,params){let node=ctx.node(),value=node.get();if(value===void 0)return{moved:!1};if(!Array.isArray(value))throw notAList("moveItem",node);let from=findItem(value,params);if(from===-1)return{moved:!1};let item=value[from],others=value.filter((_2,index)=>index!==from),place=readPlace(params.position,"moveItem"),to;switch(place.kind){case"start":to=0;break;case"end":to=others.length;break;case"index":to=Math.min(place.index,others.length);break;default:{let at2=place.where?others.findIndex(other=>matchesFields(other,place.anchor)):others.findIndex(other=>deepEqual(other,place.anchor));if(at2===-1)return{moved:!1};to=place.kind==="before"?at2:at2+1}}return to===from?{moved:!1}:(node.move(from,to),{moved:!0,item,from,to})},down(ctx,_params,record2){if(!acted(record2))return;let entry=record2,node=ctx.node(),list2=listOf3(node),to=entry.to,at2=deepEqual(list2[to],entry.item)?to:list2.findIndex(item=>deepEqual(item,entry.item));at2!==-1&&node.move(at2,Math.min(entry.from,list2.length-1))},mergeRecords:keepEarlier2,assertions:()=>[]})}function registerRelocateOperations(definitions2,aliases2){definitions2.push(copyDefinition(),moveDefinition(),insertWhereDefinition("insertBeforeWhere"),insertWhereDefinition("insertAfterWhere"),moveItemDefinition()),aliases2.push(shorthand({name:"moveItemWhere",target:"moveItem",means:"moveItem with where: {...}",params:["where","position"],args:["where","position"]}))}var EditNotPossible=class extends Error{constructor(message2){super(message2),this.name="EditNotPossible"}},OperationParamsError=class extends Error{constructor(message2){super(message2),this.name="OperationParamsError"}},COMMON=["path","assertion","document"];function changed(record2){return isJsonObject(record2)?record2.changed===!0||record2.created===!0||record2.added===!0||record2.renamed===!0||typeof record2.action=="string"&&record2.action!=="none"?!0:Object.values(record2).some(value=>Array.isArray(value)&&value.length>0):!1}function keepEarlier3(previous,next){return changed(previous)?previous:next}function joinLists(...keys){return(previous,next)=>{if(!isJsonObject(previous)||!isJsonObject(next))return next;let joined={...next};for(let key of keys){let before=Array.isArray(previous[key])?previous[key]:[],after=Array.isArray(next[key])?next[key]:[];joined[key]=[...before,...after.filter(item=>!before.some(old=>deepEqual(old,item)))]}return joined}}function requireKey2(raw2,key,operation2){if(raw2[key]===void 0)throw new OperationParamsError(`'${operation2}' needs '${key}'.`);return raw2[key]}function requireString(raw2,key,operation2){let value=requireKey2(raw2,key,operation2);if(typeof value!="string")throw new OperationParamsError(`'${operation2}': '${key}' must be a string.`);return value}function optionalString(raw2,key,operation2){let value=raw2[key];if(value!==void 0&&typeof value!="string")throw new OperationParamsError(`'${operation2}': '${key}' must be a string.`);return value}function checkPath(raw2,operation2){let path122=raw2.path;if(path122!=null){if(typeof path122!="string")throw new OperationParamsError(`'${operation2}': 'path' must be a string.`);if(!path122.includes("${"))try{parsePath(path122)}catch(error51){throw new OperationParamsError(`'${operation2}': ${error51 instanceof Error?error51.message:String(error51)}`)}}}function itemsOf2(raw2,operation2,single="item",plural3="items"){if(raw2[plural3]!==void 0)return Array.isArray(raw2[plural3])?[...raw2[plural3]]:[raw2[plural3]];if(raw2[single]!==void 0)return[raw2[single]];throw new OperationParamsError(`'${operation2}' needs '${plural3}' (or '${single}').`)}function without2(raw2,...keys){return Object.fromEntries(Object.entries(raw2).filter(([key])=>!keys.includes(key)))}function parsePosition(value,operation2="position"){if(value==null)return{kind:"default"};if(value==="first"||value==="start")return{kind:"start"};if(value==="last"||value==="end")return{kind:"end"};if(typeof value=="number"&&Number.isInteger(value)&&value>=0)return{kind:"index",index:value};if(isJsonObject(value)){if(value.after!==void 0)return{kind:"after",anchor:value.after};if(value.before!==void 0)return{kind:"before",anchor:value.before};if(typeof value.line=="number"&&Number.isInteger(value.line)&&value.line>=1)return{kind:"index",index:value.line-1};if(typeof value.index=="number"&&Number.isInteger(value.index)&&value.index>=0)return{kind:"index",index:value.index}}throw new OperationParamsError(`'${operation2}': 'position' must be first, last, start, end, an index from 0, { after: ... }, { before: ... } or { line: n }.`)}function placementIndex(items2,position){switch(position.kind){case"start":return 0;case"index":return Math.min(position.index,items2.length);case"after":{let at2=items2.findIndex(item=>deepEqual(item,position.anchor));return at2===-1?items2.length:at2+1}case"before":{let at2=items2.findIndex(item=>deepEqual(item,position.anchor));return at2===-1?items2.length:at2}default:return items2.length}}function listOf4(node){let value=node.get();return Array.isArray(value)?value:[]}function prepareList(node,operation2){let value=node.get();if(value===void 0)return node.set([]),[];if(!Array.isArray(value))throw new EditNotPossible(`'${operation2}' needs a list at ${node.pathString||"the root"}, and the value there is not one.`);return value}function existingList(node,operation2){let value=node.get();if(value!==void 0){if(!Array.isArray(value))throw new EditNotPossible(`'${operation2}' needs a list at ${node.pathString||"the root"}, and the value there is not one.`);return value}}function indexOf(items2,value){return items2.findIndex(item=>deepEqual(item,value))}function lastIndexOf(items2,value){for(let index=items2.length-1;index>=0;index--)if(deepEqual(items2[index],value))return index;return-1}function removeFirst(node,value){let index=indexOf(listOf4(node),value);index!==-1&&node.removeAt(index)}function linesAccess(ctx,operation2,comment){let options2={comment:comment??commentStyleFor(ctx.session.file),label:ctx.session.file};if(ctx.path===""){let doc2=parseLines(ctx.session.text(),options2);return{doc:doc2,save:(finish4=text=>text)=>{doc2.changed()&&ctx.session.setText(finish4(doc2.toString()))}}}let node=ctx.node(),value=node.get();if(value!==void 0&&typeof value!="string")throw new EditNotPossible(`'${operation2}' needs text at ${node.pathString}, and the value there is not a string.`);let doc=parseLines(value??"",options2);return{doc,save:(finish4=text=>text)=>{doc.changed()&&node.set(finish4(doc.toString()))}}}function linePosition(position){switch(position.kind){case"start":return"start";case"index":return{line:position.index+1};case"after":return{after:typeof position.anchor=="string"?position.anchor:JSON.stringify(position.anchor)};case"before":return{before:typeof position.anchor=="string"?position.anchor:JSON.stringify(position.anchor)};default:return"end"}}function onBlock(operation2,act){try{return act()}catch(error51){throw error51 instanceof Error&&error51.name==="ConfigError"?new EditNotPossible(`'${operation2}': ${error51.message}`):error51}}function textAccess(ctx,operation2){if(ctx.path==="")return{get:()=>ctx.session.text(),set:text=>ctx.session.setText(text)};let node=ctx.node();return{get(){let value=node.get();if(value!==void 0&&typeof value!="string")throw new EditNotPossible(`'${operation2}' needs text at ${node.pathString}, and the value there is not a string.`);return value??""},set:text=>node.set(text)}}function contentText(content,format3){if(content==null)return"";if(typeof content=="string")return content;if(format3==="json"||format3==="jsonc")return`${JSON.stringify(content,null,2)}
1337
1338
  `;if(format3==="yaml"||format3==="markdown"){let doc=openDocument("",format3);return doc.root().set(content),doc.toString()}return Array.isArray(content)?content.length===0?"":`${content.map(line=>typeof line=="string"?line:JSON.stringify(line)).join(`
@@ -1346,10 +1347,10 @@ ${lines3.join(`
1346
1347
  `):text;return emptied&&record2.finalBreak===!1&&(restored=restored.replace(/\r?\n$/,"")),restored})},mergeRecords:keepEarlier3,assertions:(params,path122)=>[{check:"includesLine",arg:params.line,path:path122,not:!0}]});define({name:"ensureBlock",order:60,scope:"document",summary:"The text contains a block Sous keeps between two marker lines, `>>> sous managed: <name> (do not edit between these markers)` and `<<< sous managed: <name>`, in the file's comment style, holding exactly `content`.",params:["name","content","position","comment"],args:["name","content"],normalize(raw2){return requireString(raw2,"name","ensureBlock"),requireString(raw2,"content","ensureBlock"),parsePosition(raw2.position,"ensureBlock"),raw2},up(ctx,params){let{doc,save}=linesAccess(ctx,"ensureBlock",commentOf(ctx,params)),name=params.name,content=linesOfText(params.content);return onBlock("ensureBlock",()=>{let current=doc.block(name);return current!==void 0&&deepEqual(current,content)?{created:!1}:(doc.setBlock(name,content,linePosition(parsePosition(params.position))),save(),current===void 0?{created:!0}:{created:!1,previous:current.join(`
1347
1348
  `)})})},down(ctx,params,record2){if(!isJsonObject(record2))return;let{doc,save}=linesAccess(ctx,"ensureBlock",commentOf(ctx,params)),name=params.name;onBlock("ensureBlock",()=>{if(doc.hasBlock(name)){if(record2.created===!0)doc.removeBlock(name);else if(typeof record2.previous=="string")doc.setBlock(name,linesOfText(record2.previous));else return;save()}})},mergeRecords:(previous,next)=>isJsonObject(previous)&&(previous.created===!0||previous.previous!==void 0)?previous:next,assertions:(params,path122)=>[{check:"includesBlock",arg:{name:params.name,content:params.content},path:path122}]});for(let[name,atEnd]of[["appendText",!0],["prependText",!1]])define({name,order:60,scope:"document",action:!0,summary:`Adds \`value\` to the ${atEnd?"end":"start"} of the text (an action: Sous does it once, when the entry is first applied).`,params:["value"],args:["value"],normalize(raw2){return requireString(raw2,"value",name),raw2},up(ctx,params){let access=textAccess(ctx,name),text=access.get();return access.set(atEnd?text+params.value:params.value+text),{added:!0}},down(ctx,params){let access=textAccess(ctx,name),text=access.get(),value=params.value;atEnd&&text.endsWith(value)&&access.set(text.slice(0,text.length-value.length)),!atEnd&&text.startsWith(value)&&access.set(text.slice(value.length))},assertions:(params,path122)=>path122===""?[]:[{check:"includes",arg:params.value,path:path122}]});define({name:"replaceText",order:60,scope:"document",summary:"Every occurrence of `match` in the text becomes `value`. Undone by turning `value` back into `match`.",params:["match","value"],args:["match","value"],normalize(raw2){return requireString(raw2,"match","replaceText"),requireString(raw2,"value","replaceText"),raw2},up(ctx,params){let access=textAccess(ctx,"replaceText"),text=access.get(),match2=params.match;return match2===""||!text.includes(match2)?{changed:!1}:(access.set(text.split(match2).join(params.value)),{changed:!0})},down(ctx,params,record2){if(!isJsonObject(record2)||record2.changed!==!0||params.value==="")return;let access=textAccess(ctx,"replaceText");access.set(access.get().split(params.value).join(params.match))},mergeRecords:keepEarlier3,assertions:(params,path122)=>path122===""?[]:[{check:"includes",arg:params.match,path:path122,not:!0}]});define({name:"replacePattern",order:60,scope:"document",summary:'Every match of the regular expression `match` (`"^a"` or `"/^a/i"`) becomes `value`, with `$1` and so on. Undone by putting back the text it replaced, while the text is still what Sous left.',params:["match","value"],args:["match","value"],normalize(raw2){let match2=requireString(raw2,"match","replacePattern");requireString(raw2,"value","replacePattern");try{toRegExp(match2)}catch(error51){throw new OperationParamsError(`'replacePattern': ${error51 instanceof Error?error51.message:String(error51)}`)}return raw2},up(ctx,params){let access=textAccess(ctx,"replacePattern"),pattern=toRegExp(params.match),global2=new RegExp(pattern.source,pattern.flags.includes("g")?pattern.flags:`${pattern.flags}g`),text=access.get(),next=text.replace(global2,params.value);return next===text?{changed:!1}:(access.set(next),{changed:!0,previous:text,result:next})},down(ctx,_params,record2){if(!isJsonObject(record2)||record2.changed!==!0||typeof record2.previous!="string")return;let access=textAccess(ctx,"replacePattern");access.get()===record2.result&&access.set(record2.previous)},mergeRecords:(previous,next)=>isJsonObject(next)&&next.changed===!0?next:previous,assertions:()=>[]});for(let[name,sign]of[["increment",1],["decrement",-1]])define({name,order:70,scope:"document",action:!0,summary:`${sign>0?"Adds":"Subtracts"} \`value\` (default 1) ${sign>0?"to":"from"} a number; a missing one counts as 0 (an action: Sous does it once).`,params:["value"],args:["value"],normalize(raw2){if(raw2.value!==void 0&&typeof raw2.value!="number")throw new OperationParamsError(`'${name}': 'value' must be a number.`);return raw2},up(ctx,params){let node=ctx.node(),current=node.get();if(current!==void 0&&typeof current!="number")throw new EditNotPossible(`'${name}' needs a number at ${node.pathString||"the root"}.`);return setValue2(node,(current??0)+sign*(params.value??1))},down:(ctx,_params,record2)=>restoreValue(ctx.node(),record2),assertions:()=>[]});define({name:"toggle",order:70,scope:"document",action:!0,summary:"Turns true into false and false into true; a missing value becomes true (an action: Sous does it once).",params:[],args:[],up(ctx){let node=ctx.node(),current=node.get();if(current!==void 0&&typeof current!="boolean")throw new EditNotPossible(`'toggle' needs true or false at ${node.pathString||"the root"}.`);return setValue2(node,current!==!0)},down:(ctx,_params,record2)=>restoreValue(ctx.node(),record2),assertions:()=>[]});commentOperations().forEach(define);var aliases=[];function alias(name,target,means,options2={}){let core=definitions.find(definition2=>definition2.name===target);aliases.push({name,target,means,params:options2.params??core.params,args:options2.args??core.args,toCore(raw2){let allowed=new Set([...COMMON,...options2.params??core.params]);for(let key of Object.keys(raw2))if(!allowed.has(key))throw new OperationParamsError(`'${name}' has no parameter '${key}'. Its parameters: ${["path",...options2.params??core.params].join(", ")}.`);return options2.toCore?options2.toCore(raw2):raw2}})}var itemParams=["item","items"];alias("ensureValue","set","set",{params:["value"]});alias("replace","set","set",{params:["value"]});alias("setIfMissing","set","set with ifMissing: true",{params:["value"],toCore:raw2=>({...raw2,ifMissing:!0})});alias("ensureDefault","set","set with ifMissing: true",{params:["value"],toCore:raw2=>({...raw2,ifMissing:!0})});alias("ensureAbsent","delete","delete");alias("ensureKeys","merge","merge",{params:["value"]});alias("deepMerge","merge","merge",{params:["value"]});alias("mergeIfMissing","merge","merge with ifMissing: true",{params:["value"],toCore:raw2=>({...raw2,ifMissing:!0})});alias("ensureFirst","ensureIncludes","ensureIncludes with position: first",{params:itemParams,args:["item"],toCore:raw2=>({...raw2,position:"first"})});alias("ensureLast","ensureIncludes","ensureIncludes with position: last",{params:itemParams,args:["item"],toCore:raw2=>({...raw2,position:"last"})});alias("ensureAt","ensureIncludes","ensureIncludes with position: <index>",{params:[...itemParams,"index"],args:["index","item"],toCore(raw2){if(typeof raw2.index!="number")throw new OperationParamsError("'ensureAt' needs 'index', a whole number from 0.");return{...without2(raw2,"index"),position:raw2.index}}});alias("appendIfMissing","ensureIncludes","ensureIncludes",{params:itemParams,args:["items"]});alias("union","ensureIncludes","ensureIncludes",{params:itemParams,args:["items"]});alias("prepend","append","append with position: first",{params:itemParams,args:["item"],toCore:raw2=>({...raw2,position:"first"})});alias("insertAt","append","append with position: <index>",{params:[...itemParams,"index"],args:["index","item"],toCore(raw2){if(typeof raw2.index!="number")throw new OperationParamsError("'insertAt' needs 'index', a whole number from 0.");return{...without2(raw2,"index"),position:raw2.index}}});for(let[name,side]of[["insertBefore","before"],["insertAfter","after"]])alias(name,"append",`append with position: { ${side}: ... }`,{params:[...itemParams,side],args:[side,"item"],toCore(raw2){if(raw2[side]===void 0)throw new OperationParamsError(`'${name}' needs '${side}', the item to put it ${side}.`);return{...without2(raw2,side),position:{[side]:raw2[side]}}}});alias("ensureItemWhere","upsertWhere","upsertWhere");alias("removeValues","remove","remove with values: [...]",{params:["values"],args:["values"]});alias("ensureExcludes","remove","remove with values: [...]",{params:["values"],args:["values"]});alias("removeValue","remove","remove with values: [value]",{params:["value"],args:["value"],toCore:raw2=>({...without2(raw2,"value"),values:[requireKey2(raw2,"value","removeValue")]})});alias("removeWhere","remove","remove with where: {...}",{params:["where"],args:["where"]});alias("ensureNoItemWhere","remove","remove with where: {...}",{params:["where"],args:["where"]});alias("ensureUnique","dedupe","dedupe");alias("dedupeBy","dedupe","dedupe with by",{args:["by"],toCore(raw2){return requireString(raw2,"by","dedupeBy"),raw2}});alias("ensureSorted","sort","sort");alias("sortBy","sort","sort with by",{args:["by"],toCore(raw2){return requireString(raw2,"by","sortBy"),raw2}});alias("createIfMissing","ensureFileExists","ensureFileExists");registerRelocateOperations(definitions,aliases);var OPERATIONS=new Map(definitions.map(definition2=>[definition2.name,definition2])),ALIASES=new Map(aliases.map(entry=>[entry.name,entry]));function isOperationName(name){return OPERATIONS.has(name)||ALIASES.has(name)}function resolveOperation(name,raw2){if(!isJsonObject(raw2))throw new OperationParamsError(`'${name}' must hold an object with its parameters (use {} when it needs none).`);let aliasDefinition=ALIASES.get(name),definition2=OPERATIONS.get(aliasDefinition?.target??name);if(definition2===void 0)throw new OperationParamsError(`There is no operation named '${name}'.`);let core=aliasDefinition?aliasDefinition.toCore(raw2):raw2,params=definition2.normalize(core),path122=typeof params.path=="string"?params.path:"";return{definition:definition2,written:name,params:without2(params,"assertion"),path:path122===""||path122.includes("${")?path122:formatPath(parsePath(path122)),assertion:params.assertion!=="none"}}function chainParams(name,args){let names2=ALIASES.get(name)?.args??OPERATIONS.get(name)?.args??[],params={};names2.forEach((param,index)=>{index<args.length&&args[index]!==void 0&&(params[param]=args[index])});let options2=args[names2.length];if(options2!==void 0){if(!isJsonObject(options2))throw new OperationParamsError(`'${name}' takes ${names2.length===0?"only":`${names2.join(", ")}, then`} an object of options.`);Object.assign(params,options2)}return params}function operationInfo(){return[...OPERATIONS.values()].sort((a,b)=>a.order-b.order||(a.name<b.name?-1:1)).map(definition2=>({name:definition2.name,order:definition2.order,scope:definition2.scope,action:definition2.action===!0,params:definition2.params,args:definition2.args,aliases:aliases.filter(entry=>entry.target===definition2.name).map(entry=>({name:entry.name,means:entry.means})),summary:definition2.summary}))}var UnparseableFileError=class extends Error{constructor(file2,cause){super(`Sous cannot parse ${file2}: ${cause instanceof Error?cause.message:String(cause)}`,{cause});this.file=file2;this.name="UnparseableFileError"}},FileSession=class{constructor(file2,format3,original){this.file=file2;this.format=format3;this.original=original;this.current=original}current;doc;docIndex;exists(){return this.doc!==void 0||this.current!==void 0}document(index){if(this.doc!==void 0&&this.docIndex!==index&&(this.current=this.final(),this.doc=void 0),this.doc===void 0)try{this.doc=index===void 0?openDocument(this.current??"",this.format):openStreamDocument(this.current??"",this.format,index),this.docIndex=index}catch(error51){throw error51 instanceof NoSuchDocumentError?error51:new UnparseableFileError(this.file,error51)}return this.doc}parses(){try{return this.document(),!0}catch{return!1}}text(){return this.final()??""}setText(text){this.doc=void 0,this.current=text}remove(){this.doc=void 0,this.current=void 0}final(){if(this.doc!==void 0){let text=this.doc.toString();if(this.current===void 0&&text===""||this.current===void 0&&this.isEmptyDocument())return;this.current=text}return this.current}changed(){return this.final()!==this.original}isEmptyDocument(){let value=this.doc.value();return value===null||typeof value=="object"&&Object.keys(value).length===0}};var TEXT_OPERATIONS=new Set(["ensureLine","removeLine","ensureBlock","appendText","prependText","replaceText","replacePattern"]),NEGATIVE_CHECKS=new Set(["noItemWhere","excludes"]);function needsDocument(step){let name="definition"in step?step.definition.name:step.op,target="definition"in step?step.path:step.params.path??"";return name==="ensureFileExists"||name==="ensureDirectoryExists"||step.params.document!==void 0?!1:!(TEXT_OPERATIONS.has(name)&&target==="")}function readText2(file2){try{return fs85.readFileSync(file2,"utf8")}catch{return}}function isDirectory5(dir){try{return fs85.statSync(dir).isDirectory()}catch{return!1}}function mainValue(step){let params=step.params;for(let key of["value","items","item","line","match","where","values","content","name","keys"])if(params[key]!==void 0)return show(params[key]);return""}function silenceCovers(silence,path122,kind){let at2=parsePath(silence.path),target=parsePath(path122),equal=at2.length===target.length&&isPathPrefix(at2,target);if(!(silence.scope==="key-only"?equal:silence.scope==="below"?!equal&&isPathPrefix(at2,target):isPathPrefix(at2,target)))return!1;let normalized=normalizeKind(kind);return silence.kinds!==void 0?silence.kinds.includes(normalized):silence.except!==void 0?!silence.except.includes(normalized):!0}function createDirectories2(dirs,dryRun4){let created=[];for(let dir of dirs){let missing=[],current=path115.resolve(dir);for(;!isDirectory5(current)&&!created.includes(current);){missing.unshift(current);let parent=path115.dirname(current);if(parent===current)break;current=parent}for(let level of missing)dryRun4||fs85.mkdirSync(level),created.push(level)}return created}function removeEmptyDirectories(dirs,dryRun4){let removed=[],ordered2=[...new Set(dirs)].sort((a,b)=>b.split(path115.sep).length-a.split(path115.sep).length||(a<b?1:-1));for(let dir of ordered2)!isDirectory5(dir)||fs85.readdirSync(dir).filter(name=>!removed.includes(path115.join(dir,name))).length>0||(dryRun4||fs85.rmdirSync(dir),removed.push(dir));return removed}function runUp(step,ctx,previous){let record2=step.definition.up(ctx,step.params,previous?.record);return previous===void 0?record2:step.definition.mergeRecords?step.definition.mergeRecords(previous.record,record2):record2}function contextFor(session,step){return{session,path:step.path,node:()=>session.document().atPath(step.path)}}function stepPath(step){return typeof step.params.path=="string"?step.params.path:""}function display(file2,root){return toStored(file2,root)}async function applyEdits2(declared,env,options2,lookup){let{projectRoot:root,reporter}=env,dryRun4=options2.dryRun===!0,history=readHistory(env.historyFile,root),declaredIds=new Set(declared.map(entry=>entry.identity)),previousById=new Map(history.entries.map(entry=>[entry.identity,entry])),undeclared=history.entries.filter(entry=>!declaredIds.has(entry.identity)),toUndo=options2.undo?undeclared:[],next={version:1,entries:options2.undo?[]:[...undeclared],createdFiles:[...history.createdFiles],createdFolders:{...history.createdFolders}},fileFolders=[],kept=new Map,files=[],assertions=[],directories={created:[],removed:[]},now=(env.now??(()=>new Date))().toISOString(),ok=!0,applied=0,undone=0,tokenCount,countTokens=async text=>(tokenCount?.text!==text&&(tokenCount={text,count:await env.countTokens(text)}),tokenCount.count);for(let entry of declared.filter(item=>item.file===void 0)){let previous=previousById.get(entry.identity);if(previous!==void 0&&entry.settings.once){kept.set(entry.identity,previous);continue}let steps=entry.steps.map((step,index)=>{let dirs=step.params.paths.map(dir=>path115.resolve(root,dir)),created=createDirectories2(dirs,dryRun4),before=previous?.steps[index]?.record,earlier=isJsonObject(before)&&Array.isArray(before.created)?before.created:[];for(let dir of created)reporter.debug(`${dryRun4?"Would create":"Created"} the folder ${display(dir,root)} (declared by ${entry.declarer}).`);return directories.created.push(...created),{op:step.definition.name,params:step.params,record:{created:[...new Set([...earlier,...created.map(dir=>toStored(dir,root))])]}}});kept.set(entry.identity,{identity:entry.identity,declarer:entry.declarer,file:"",rollback:entry.settings.rollback,backupOnRemoval:entry.settings.backupOnRemoval,steps,appliedAt:previous?.appliedAt??now}),previous===void 0&&(applied+=1);for(let step of entry.steps)for(let dir of step.params.paths)assertions.push({file:dir,path:"",check:"directoryExists",declarer:entry.declarer,level:"warn",automatic:!0,passed:dryRun4||isDirectory5(path115.resolve(root,dir))})}let fileNames=[...new Set([...declared.filter(entry=>entry.file!==void 0).map(entry=>entry.file),...toUndo.filter(entry=>entry.file!=="").map(entry=>entry.file)])];for(let file2 of fileNames){let here=declared.filter(entry=>entry.file===file2),editing=here.filter(entry=>entry.steps.length>0),undoing=toUndo.filter(entry=>entry.file===file2),original=readText2(file2),session=new FileSession(file2,formatForFile(file2),original),shown=display(file2,root),needsDoc=editing.some(entry=>entry.steps.some(needsDocument))||undoing.some(entry=>entry.rollback&&entry.steps.some(needsDocument)),unparseable;if(original!==void 0&&needsDoc&&!session.parses()){try{session.document()}catch(error51){unparseable=error51 instanceof Error?error51.message:String(error51)}reporter.warning(`${unparseable} None of the edits declared for it were made.`)}let events=[],fileEntries=[];if(unparseable===void 0){for(let entry of[...undoing].reverse()){if(!entry.rollback){reporter.debug(`Left the edits of ${entry.declarer} in ${shown} in place: it is no longer declared, and its rollback is off.`);continue}for(let step of[...entry.steps].reverse()){let definition2=lookup(step.op);if(definition2!==void 0)try{definition2.down(contextFor(session,{path:stepPath(step)}),step.params,step.record),reporter.debug(`Undid ${step.op} at ${stepPath(step)||"the root"} in ${shown} (declared by ${entry.declarer}, no longer declared).`)}catch(error51){reporter.warning(`Could not undo ${step.op} in ${shown}: ${error51 instanceof Error?error51.message:String(error51)}`)}}undone+=1}for(let entry of editing){let previous=previousById.get(entry.identity);if(previous!==void 0&&entry.settings.once){fileEntries.push(previous);continue}let steps=[];entry.steps.forEach((step,index)=>{let before=previous?.steps[index];if(before!==void 0&&step.definition.action){steps.push(before);return}let record2=before?.record??null;try{record2=runUp(step,contextFor(session,step),before),reporter.debug(`Applied ${step.written} at ${step.path||"the root"} in ${shown} (declared by ${entry.declarer}).`)}catch(error51){if(!(error51 instanceof EditNotPossible)&&!(error51 instanceof UnparseableFileError))throw error51;reporter.warning(`${shown}: ${error51.message} Declared by ${entry.declarer}; the edit was skipped.`)}steps.push({op:step.definition.name,params:step.params,record:record2}),events.push({path:step.path,declarer:entry.declarer,operation:step.written,value:mainValue(step)})}),previous===void 0&&(applied+=1),fileEntries.push({identity:entry.identity,declarer:entry.declarer,file:file2,rollback:entry.settings.rollback,backupOnRemoval:entry.settings.backupOnRemoval,steps,appliedAt:previous?.appliedAt??now})}}let backups=[],removing=!1;unparseable===void 0&&editing.length===0&&undoing.length>0&&undoing.every(entry=>entry.rollback)&&history.createdFiles.includes(file2)&&session.exists()&&(removing=!0,original!==void 0&&undoing.some(entry=>entry.backupOnRemoval)&&backups.push(dryRun4?"(a backup)":env.backup(file2)),session.remove());let authored=here.flatMap(entry=>entry.asserts.map(assertion=>({...assertion,declarer:entry.declarer,automatic:!1}))),authoredAt=new Set(authored.map(assertion=>`${assertion.declarer}\0${assertion.path}`)),pending=[...authored];for(let entry of editing){if(entry.settings.once)continue;let silences=here.filter(other=>other.declarer===entry.declarer).flatMap(other=>other.silences);for(let step of entry.steps)if(!(!step.assertion||authoredAt.has(`${entry.declarer}\0${step.path}`))){for(let implied of step.definition.assertions(step.params,step.path))if(!authoredAt.has(`${entry.declarer}\0${implied.path}`)){if(silences.some(silence=>silenceCovers(silence,implied.path,implied.check))){assertions.push({file:shown,path:implied.path,check:implied.check,declarer:entry.declarer,level:"warn",automatic:!0,passed:!0,silenced:!0});continue}pending.push({path:implied.path,check:implied.check,arg:implied.arg,not:implied.not===!0,declarer:entry.declarer,level:"warn",message:void 0,automatic:!0})}}}let finalText2=session.final(),subject2={file:file2,fileExists:()=>session.final()!==void 0,directoryExists:()=>isDirectory5(file2),parsed:()=>unparseable===void 0&&session.final()!==void 0&&session.parses(),value:at2=>getAtPath(session.document().value(),parsePath(at2)),text:()=>session.text(),tokens:()=>countTokens(session.text())},blocked=!1;for(let assertion of pending){let passed2=finalText2===void 0&&assertion.automatic&&(NEGATIVE_CHECKS.has(assertion.check)||assertion.not||assertion.arg===!1)||await runCheck2(subject2,assertion.check,assertion.arg,assertion.path,assertion.not),report;passed2||(report=failureReport(shown,assertion,events,finalText2===void 0?"missing":unparseable!==void 0?"unparseable":void 0),assertion.level==="error"&&!options2.ignoreFailedAssertions?(reporter.error(report),blocked=!0,ok=!1):reporter.warning(report)),assertions.push({file:shown,path:assertion.path,check:assertion.check,declarer:assertion.declarer,level:assertion.level,automatic:assertion.automatic,passed:passed2,...report===void 0?{}:{report}})}if(unparseable!==void 0){files.push({file:shown,action:"skipped",reason:unparseable});for(let entry of[...undoing,...editing.map(item=>previousById.get(item.identity)).filter(item=>item!==void 0)])kept.set(entry.identity,entry);continue}if(blocked){files.push({file:shown,action:"not-written",reason:"an assertion at level error failed"});for(let entry of[...undoing,...editing.map(item=>previousById.get(item.identity)).filter(item=>item!==void 0)])kept.set(entry.identity,entry);continue}for(let entry of fileEntries)kept.set(entry.identity,entry);if(!session.changed()){(editing.length>0||undoing.length>0)&&files.push({file:shown,action:"unchanged"});continue}let action=finalText2===void 0?"removed":original===void 0?"created":"updated";action==="updated"&&editing.some(entry=>entry.settings.backupBeforeChange)&&backups.push(dryRun4?"(a backup)":env.backup(file2));let madeFolders=finalText2!==void 0?createDirectories2([path115.dirname(file2)],dryRun4):[];for(let dir of madeFolders)reporter.debug(`${dryRun4?"Would create":"Created"} the folder ${display(dir,root)} to hold ${shown}.`);directories.created.push(...madeFolders),dryRun4||(finalText2===void 0?fs85.rmSync(file2,{force:!0}):fs85.writeFileSync(file2,finalText2,"utf8")),action==="created"&&!next.createdFiles.includes(file2)&&next.createdFiles.push(file2),action==="created"&&madeFolders.length>0&&(next.createdFolders[file2]=madeFolders),(removing||action==="removed")&&(next.createdFiles=next.createdFiles.filter(created=>created!==file2),fileFolders.push(...next.createdFolders[file2]??[]),delete next.createdFolders[file2]),reporter.debug(`${dryRun4?"Would have ":""}${action} ${shown}${backups.length>0?` (backed up to ${backups.join(", ")})`:""}.`),files.push({file:shown,action,...backups.length>0?{backups}:{}})}let folderEntries=toUndo.filter(entry=>entry.file===""),candidates=[...fileFolders];for(let entry of folderEntries)if(entry.rollback){for(let step of entry.steps){let record2=step.record;isJsonObject(record2)&&Array.isArray(record2.created)&&candidates.push(...record2.created.map(dir=>fromStored(dir,root)))}undone+=1}let wanted=new Set(declared.filter(entry=>entry.file===void 0).flatMap(entry=>entry.steps.flatMap(step=>step.params.paths.map(dir=>path115.resolve(root,dir))))),removable=candidates.filter(dir=>![...wanted].some(want=>want===dir||want.startsWith(dir+path115.sep)));directories.removed=removeEmptyDirectories(removable,dryRun4);for(let dir of directories.removed)reporter.debug(`${dryRun4?"Would remove":"Removed"} the empty folder ${display(dir,root)}, which Sous created and nothing declares any more.`);for(let entry of declared){let record2=kept.get(entry.identity);record2!==void 0&&entry.steps.length>0&&next.entries.push(record2)}options2.undo&&next.entries.push(...undeclared.filter(entry=>kept.has(entry.identity)));let stillNamed=new Set(next.entries.map(entry=>entry.file));next.createdFiles=next.createdFiles.filter(file2=>stillNamed.has(file2));for(let file2 of Object.keys(next.createdFolders))next.createdFiles.includes(file2)||delete next.createdFolders[file2];let nothingToRecord=next.entries.length===0&&next.createdFiles.length===0;return!dryRun4&&!(nothingToRecord&&!fs85.existsSync(env.historyFile))&&writeHistory(env.historyFile,root,next),{ok,dryRun:dryRun4,files,directories,assertions,applied,undone}}function failureReport(file2,assertion,events,state){let lines3=[assertion.path===""?`Assertion failed in ${file2}`:`Assertion failed in ${file2} at ${assertion.path}`,` ${assertion.declarer} expects ${assertion.path===""?"the file":"it"} to ${describeCheck(assertion.check,assertion.arg,assertion.not)}.`];assertion.message!==void 0&&lines3.push(` ${assertion.message}`),assertion.automatic&&lines3.push(" (An automatic assertion: the edit's result did not hold after every edit to the file.)"),state==="missing"&&lines3.push(" The file does not exist."),state==="unparseable"&&lines3.push(" Sous could not parse the file, so none of its edits were made.");let target=parsePath(assertion.path),touching=events.filter(event=>pathsOverlap(parsePath(event.path),target));if(touching.length>0){let width=Math.max(...touching.map(event=>event.declarer.length)),opWidth=Math.max(...touching.map(event=>event.operation.length));lines3.push(""," What changed this value, in order:"),touching.forEach((event,index)=>{lines3.push(` ${index+1}. ${event.declarer.padEnd(width)} ${event.operation.padEnd(opWidth)} ${event.value}`.trimEnd())})}else state===void 0&&lines3.push(""," No edit Sous made in this build changed this value.");return lines3.join(`
1348
1349
  `)}init_src();import{createHash as createHash7}from"node:crypto";var EDITS_KEY="editor.edits",DEFAULT_SETTINGS=Object.freeze({once:!1,rollback:!0,backupBeforeChange:!1,backupOnRemoval:!0}),ENTRY_SETTINGS=["once","rollback","backupBeforeChange","backupOnRemoval"],ENTRY_KEYS=new Set(["file","recipe","operations","assert","silence",...ENTRY_SETTINGS]),SCOPES=new Set(["key-and-below","key-only","below"]);function stringOrList(value,what){if(value===void 0)return;let list2=Array.isArray(value)?value:[value];if(!list2.every(item=>typeof item=="string"))throw new OperationParamsError(`${what} must be a kind or a list of kinds.`);return list2.map(normalizeKind)}function pathOf(value,what){if(value==null||value==="")return"";if(typeof value!="string")throw new OperationParamsError(`${what}: 'path' must be a string.`);return value}function normalizeAssert(raw2){if(!isJsonObject(raw2))throw new OperationParamsError("'assert' must hold an object: a 'path' and one or more checks.");let level=raw2.level??"error";if(level!=="error"&&level!=="warn")throw new OperationParamsError("'assert': 'level' must be error or warn.");if(raw2.message!==void 0&&typeof raw2.message!="string")throw new OperationParamsError("'assert': 'message' must be a string.");if(raw2.not!==void 0&&typeof raw2.not!="boolean")throw new OperationParamsError("'assert': 'not' must be true or false.");let path122=pathOf(raw2.path,"'assert'"),checks=Object.keys(raw2).filter(key=>!ASSERT_SETTINGS.has(key));if(checks.length===0)throw new OperationParamsError(`'assert' names no check. The checks: ${[...CHECKS.keys()].join(", ")}.`);return checks.map(check3=>{if(!CHECKS.has(check3))throw new OperationParamsError(`'assert' has no check named '${check3}'. The checks: ${[...CHECKS.keys()].join(", ")}.`);return{path:path122,check:check3,arg:raw2[check3],not:raw2.not===!0,level,message:raw2.message}})}function normalizeSilence(raw2){if(!isJsonObject(raw2))throw new OperationParamsError("'silence' must hold an object ({} silences the whole file).");for(let key of Object.keys(raw2))if(!["path","kinds","except","scope"].includes(key))throw new OperationParamsError(`'silence' has no setting '${key}'. Its settings: path, kinds, except, scope.`);let kinds=stringOrList(raw2.kinds,"'silence': 'kinds'"),except=stringOrList(raw2.except,"'silence': 'except'");if(kinds!==void 0&&except!==void 0)throw new OperationParamsError("'silence': 'except' only goes with no 'kinds' (it means every kind except these).");let scope=raw2.scope??"key-and-below";if(typeof scope!="string"||!SCOPES.has(scope))throw new OperationParamsError("'silence': 'scope' must be key-and-below, key-only or below.");return{path:pathOf(raw2.path,"'silence'"),kinds,except,scope}}function normalizeEntry(raw2){if(!isJsonObject(raw2))throw new OperationParamsError("An entry of editor.edits must be an object.");let entry=raw2,operationKeys=[];for(let key of Object.keys(entry))if(!ENTRY_KEYS.has(key)){if(!isOperationName(key))throw new OperationParamsError(`'${key}' is not an operation or a setting of an entry.`);operationKeys.push(key)}for(let setting of ENTRY_SETTINGS)if(entry[setting]!==void 0&&typeof entry[setting]!="boolean")throw new OperationParamsError(`'${setting}' must be true or false.`);if(entry.file!==void 0&&(typeof entry.file!="string"||entry.file===""))throw new OperationParamsError("'file' must be a path.");if(entry.recipe!==void 0&&typeof entry.recipe!="string")throw new OperationParamsError("'recipe' must be a recipe's id.");if(operationKeys.length>0&&entry.operations!==void 0)throw new OperationParamsError("An entry has operation keys or an 'operations' list, not both.");let steps;if(entry.operations!==void 0){if(!Array.isArray(entry.operations))throw new OperationParamsError("'operations' must be a list, each item holding one operation.");steps=entry.operations.map((item,index)=>{let keys=isJsonObject(item)?Object.keys(item):[];if(keys.length!==1)throw new OperationParamsError(`operations[${index}] must hold exactly one operation.`);return resolveOperation(keys[0],item[keys[0]])})}else steps=operationKeys.map(key=>resolveOperation(key,entry[key])).sort((a,b)=>a.definition.order-b.definition.order||(a.definition.name<b.definition.name?-1:1));let asserts=entry.assert===void 0?[]:normalizeAssert(entry.assert),silences=entry.silence===void 0?[]:[normalizeSilence(entry.silence)],folders=steps.filter(step=>step.definition.scope==="directory");if(steps.length===0&&asserts.length===0&&silences.length===0)throw new OperationParamsError("An entry needs an operation, an 'assert' or a 'silence'.");if(folders.length>0&&folders.length!==steps.length)throw new OperationParamsError("'ensureDirectoryExists' goes in an entry of its own.");if(entry.file===void 0&&(folders.length===0||asserts.length>0||silences.length>0))throw new OperationParamsError("An entry needs a 'file' (only 'ensureDirectoryExists' goes without one).");let settings={...DEFAULT_SETTINGS};for(let setting of ENTRY_SETTINGS)typeof entry[setting]=="boolean"&&(settings[setting]=entry[setting]);return{file:entry.file,settings,steps,asserts,silences,recipe:entry.recipe}}function entryIdentity(declarer,file2,steps,occurrence=0){let said=stableStringify({declarer,file:file2,steps:steps.map(step=>({op:step.definition.name,params:step.params})),occurrence});return createHash7("sha256").update(said).digest("hex").slice(0,24)}var PROJECT_PLUGINS=new Set(["@sous-io/sous-plugin-config-files","@sous-io/sous-plugin-confd"]);function declarerLabel(owner,recipe){return recipe!==void 0?recipe:owner===void 0?"unknown":PROJECT_PLUGINS.has(owner.plugin)?"project":owner.plugin}function walkPatches(set2,visit3){for(let item of set2.patches)"op"in item?visit3(item):walkPatches(item,visit3)}function samePath(a,b){return a.length===b.length&&a.every((segment,index)=>segment===b[index])}function listOwners(contributions,key,finalLength){let target=parsePath(key),owners=[];for(let contribution of contributions){let owner={plugin:contribution.plugin,contributor:contribution.contributor};walkPatches(contribution.patches,patch=>{let at2=parsePath(patch.path);if(samePath(at2,target)){switch(patch.op){case"insertAt":{let index=patch.index==="end"?owners.length:Math.min(patch.index,owners.length);owners.splice(index,0,owner);break}case"setIndex":owners[patch.index]=owner;break;case"removeIndex":owners.splice(patch.index,1);break;default:break}return}if((patch.op==="setKey"||patch.op==="deleteKey")&&isPathPrefix([...at2,patch.key],target))if(patch.op==="deleteKey")owners=[];else{let value=getAtPath(patch.value,target.slice(at2.length+1));owners=Array.isArray(value)?value.map(()=>owner):[]}})}return owners.length===finalLength?owners:void 0}function substitute2(entry,config2,resolver,where3){if(resolver===void 0)return entry;let recipe=isJsonObject(entry)&&typeof entry.recipe=="string"?entry.recipe:void 0,scope=resolver.scopeIn(config2,recipe===void 0?{}:{scopeKey:recipe});return resolver.substituteValue(entry,scope,where3)}function resolveFile(file2,root,resolver){let normalized=resolver===void 0?file2:resolver.normalizePath(file2);return path116.resolve(root,normalized)}function declaredEntries(config2,root,resolver,warn){let raw2=config2.get(EDITS_KEY)??[],owners=listOwners(config2.contributions(),EDITS_KEY,raw2.length),entries=[],seen=new Map,complete=!0;return raw2.forEach((item,index)=>{let where3=`${EDITS_KEY}[${index}]`;try{let resolved=substitute2(item,config2,resolver,where3),normalized=normalizeEntry(resolved),declarer=declarerLabel(owners?.[index],normalized.recipe),file2=normalized.file===void 0?void 0:resolveFile(normalized.file,root,resolver),said=entryIdentity(declarer,file2===void 0?"":toStored(file2,root),normalized.steps),occurrence=seen.get(said)??0;seen.set(said,occurrence+1),entries.push({identity:occurrence===0?said:entryIdentity(declarer,file2===void 0?"":toStored(file2,root),normalized.steps,occurrence),declarer,file:file2,settings:normalized.settings,steps:normalized.steps,asserts:normalized.asserts,silences:normalized.silences})}catch(error51){complete=!1,warn(`${where3} was skipped: ${error51 instanceof Error?error51.message:String(error51)}`)}}),{entries,complete}}async function ensureIgnored(ctx,sousDir,historyFile){if(!ctx.services.has("host.gitignore"))return;let relative4=path116.relative(sousDir,historyFile),lines3=[...relative4.startsWith("..")||path116.isAbsolute(relative4)?[]:[relative4.split(path116.sep).join("/")],"backups/"];try{await ctx.services.get("host.gitignore").add(path116.join(sousDir,".gitignore"),lines3)}catch(error51){ctx.reporter.warning(`Sous could not add ${lines3.join(" and ")} to .sous/.gitignore: ${error51 instanceof Error?error51.message:String(error51)}`)}}async function applyIntent(input,ctx){let project=ctx.project,dryRun4=input.dryRun===!0;if(project===void 0){let empty={ok:!0,dryRun:dryRun4,files:[],directories:{created:[],removed:[]},assertions:[],applied:0,undone:0};return new IntentOutputs29(new IntentOutput23({data:empty}))}let resolver=ctx.services.has("variables.resolver")?ctx.services.get("variables.resolver"):void 0,{entries,complete}=declaredEntries(ctx.config,project.root,resolver,message2=>ctx.reporter.warning(message2)),configured=ctx.config.get("editor.historyFile"),historyFile=configured===void 0?path116.join(project.sousDir,HISTORY_FILE_NAME):resolveFile(resolver===void 0?configured:resolver.substitute(configured,resolver.scopeIn(ctx.config)),project.root,resolver),backups=new Backups(path116.join(project.sousDir,"backups"),project.root),counter=await createTokenCounter();try{let undo=complete&&ctx.engine.configError===void 0,hadHistory=fs86.existsSync(historyFile),result=await applyEdits2(entries,{projectRoot:project.root,historyFile,reporter:ctx.reporter,backup:file2=>backups.copy(file2,ctx.chain?.id),countTokens:async text=>counter.count(text)},{dryRun:dryRun4,ignoreFailedAssertions:input.ignoreFailedAssertions===!0,undo},op=>OPERATIONS.get(op));return!dryRun4&&(entries.length>0||hadHistory)&&await ensureIgnored(ctx,project.sousDir,historyFile),new IntentOutputs29(new IntentOutput23({data:result}),result.ok?{}:{exitCode:1})}finally{counter.free()}}function describe5(outcome){let first2=outcome.report?.split(`
1349
- `)[0]?.trim();return first2!==void 0&&first2!==""?`${first2} (${outcome.declarer} expects ${outcome.check})`:`${outcome.file} at ${outcome.path||"the root"}: ${outcome.check}, declared by ${outcome.declarer}`}async function checkAssertions(ctx,run){if(run.configFailed)return{status:"skipped",summary:"The config did not load, so the edits and assertions it declares could not be checked."};if(ctx.project===void 0)return{status:"skipped",summary:"There is no project here."};let quiet=Object.create(ctx,{reporter:{value:new BufferedReporter4}}),result=(await applyIntent({dryRun:!0},quiet)).toPlain(),failed=result.assertions.filter(outcome=>!outcome.passed&&outcome.silenced!==!0),errors=failed.filter(outcome=>outcome.level==="error"),warnings=failed.filter(outcome=>outcome.level==="warn"),checked3=result.assertions.filter(outcome=>outcome.silenced!==!0).length;return checked3===0?{status:"ok",summary:"No assertion is declared."}:errors.length>0?{status:"problem",summary:`${errors.length===1?"An assertion fails":`${errors.length} assertions fail`}, so a build would not write ${errors.length===1?"that file":"those files"} and would fail.`,details:[...errors,...warnings].map(describe5),hint:"Put right what each one expects; 'sous build --ignore-failed-assertions' builds anyway."}:warnings.length>0?{status:"warning",summary:`${warnings.length===1?"An assertion at level warn fails":`${warnings.length} assertions at level warn fail`}.`,details:warnings.map(describe5)}:{status:"ok",summary:`${checked3===1?"The one assertion holds":`All ${checked3} assertions hold`}.`}}var assertionsCheck={id:"assertions",order:DOCTOR_CHECK_ORDER.assertions,description:"Every assertion on the files Sous edits holds, checked without writing",check:(ctx,run)=>checkAssertions(ctx,run)};init_zod();var entrySchema=external_exports.record(external_exports.string(),external_exports.unknown()).superRefine((entry,ctx)=>{try{normalizeEntry(entry)}catch(error51){ctx.addIssue({code:"custom",message:error51 instanceof Error?error51.message:String(error51)})}}),editorSchema=external_exports.object({edits:external_exports.array(entrySchema).default([]).describe("The master list of edits to files Sous does not own: each entry names a file and one or more operations, an assertion or a silence. Sous applies them after the compiler, records them, and undoes the ones no longer declared."),historyFile:external_exports.string().optional().describe("Where Sous records the edits it applied, so it can undo them. Default: <sousDir>/sous.edits.json (git-ignored).")}).strict(),EDITOR_CONFIG_KEY={id:"editor",schema:editorSchema.optional(),description:"Edits to files Sous does not own (editor.edits), applied, recorded and undone by the editor."};init_src();import fs87 from"node:fs";import path117 from"node:path";var OpenFile=class{constructor(path122,format3,original,resolve4,countTokens){this.path=path122;this.format=format3;this.original=original;this.resolve=resolve4;this.countTokens=countTokens;this.session=new FileSession(path122||"(text)",format3,original)}session;get existed(){return this.original!==void 0}get document(){return this.session.document()}apply(operation2,params={}){let step=resolveOperation(operation2,params);return step.definition.scope==="directory"?{created:createDirectories2(step.params.paths.map(dir=>this.resolve(dir)),!1)}:step.definition.up({session:this.session,path:step.path,node:()=>this.session.document().atPath(step.path)},step.params,void 0)}undo(operation2,params,record2){let step=resolveOperation(operation2,params);if(step.definition.scope==="directory"){let created=record2?.created??[];removeEmptyDirectories(created,!1);return}if(step.definition.scope==="file"){record2?.created===!0&&this.session.remove();return}step.definition.down({session:this.session,path:step.path,node:()=>this.session.document().atPath(step.path)},step.params,record2)}check(check3,arg,options2={}){let session=this.session,file2=this.path;return runCheck2({file:file2,fileExists:()=>session.final()!==void 0,directoryExists:()=>{try{return fs87.statSync(file2).isDirectory()}catch{return!1}},parsed:()=>session.final()!==void 0&&session.parses(),value:at2=>getAtPath(session.document().value(),parsePath(at2)),text:()=>session.text(),tokens:()=>this.countTokens(session.text())},check3,arg,options2.path??"",options2.not??!1)}text(){return this.session.text()}changed(){return this.session.changed()}write(){if(this.path==="")throw new Error("This document was parsed from text, so it has no file to write; use text().");if(!this.session.changed())return!1;let text=this.session.final();return text===void 0?fs87.rmSync(this.path,{force:!0}):(fs87.mkdirSync(path117.dirname(this.path),{recursive:!0}),fs87.writeFileSync(this.path,text,"utf8")),!0}},EditorServiceImpl=class{constructor(resolve4,countTokens){this.resolve=resolve4;this.countTokens=countTokens}open(file2,options2={}){let absolute=this.resolve(file2),text;try{text=fs87.readFileSync(absolute,"utf8")}catch{text=void 0}return new OpenFile(absolute,options2.format??formatForFile(absolute),text,this.resolve,this.countTokens)}parse(text,format3){return new OpenFile("",format3,text,this.resolve,this.countTokens)}formatOf(file2){return formatForFile(file2)}operations(){return operationInfo()}checks(){return[...CHECKS.keys()]}};var package_default34={name:"@sous-io/sous-plugin-editor",version:"1.1.4",description:"The editor: declared, recorded and undoable edits to files Sous does not own, the assertions on them, and the editor service.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-lib-documents":"workspace:*","@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-doctor":"workspace:*","@sous-io/sous-plugin-compiler":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@sous-io/sous-plugin-variables":"workspace:*",zod:"^4.4.3"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};var CHAIN_OPERATION_NAMES=[...[...OPERATIONS.values()].filter(definition2=>definition2.scope==="document").map(definition2=>definition2.name),...[...ALIASES.values()].filter(entry=>OPERATIONS.get(entry.target)?.scope==="document").map(entry=>entry.name)],ValueHandleImpl=class{constructor(recorder,file2,path122,settings){this.recorder=recorder;this.file=file2;this.path=path122;this.settings=settings}last;lastOperation;record(operation2,args){let params=chainParams(operation2,args),object3=this.path===""?params:{path:this.path,...params},entry={file:this.file,...this.settings,[operation2]:object3};return this.last=this.recorder.append(entry),this.lastOperation=operation2,this}withoutAssertion(){if(this.last===void 0||this.lastOperation===void 0)throw new Error('withoutAssertion() follows an operation: settings.at("a").sort().withoutAssertion().');let operation2=this.lastOperation;return this.recorder.update(this.last,entry=>{entry[operation2].assertion="none"}),this}};for(let name of CHAIN_OPERATION_NAMES)Object.defineProperty(ValueHandleImpl.prototype,name,{value(...args){return this.record(name,args)},writable:!0,configurable:!0});var SilenceHandleImpl=class{constructor(recorder,entry,hasKinds){this.recorder=recorder;this.entry=entry;this.hasKinds=hasKinds}change(key,value){return this.recorder.update(this.entry,entry=>{entry.silence[key]=value}),this}thisKeyOnly(){return this.change("scope","key-only")}belowOnly(){return this.change("scope","below")}except(kinds){if(this.hasKinds)throw new Error('except() only follows a silence with no kinds: settings.silence("permissions.allow").except(["include"]).');return this.change("except",[kinds].flat())}},FileHandleImpl=class extends ValueHandleImpl{constructor(recorder,file2,settings){super(recorder,file2,"",settings)}at(path122){return new ValueHandleImpl(this.recorder,this.file,path122,this.settings)}record(operation2,args){return new ValueHandleImpl(this.recorder,this.file,"",this.settings).record(operation2,args)}ensureFileExists(content){let object3=content===void 0?{}:{content};return this.recorder.append({file:this.file,...this.settings,ensureFileExists:object3}),this}silence(path122="",kinds){let silence={...path122===""?{}:{path:path122},...kinds===void 0?{}:{kinds:[kinds].flat()}},entry=this.recorder.append({file:this.file,silence});return new SilenceHandleImpl(this.recorder,entry,kinds!==void 0)}withoutAutomaticAssertions(){return this.recorder.append({file:this.file,silence:{}}),this}};var sizeOwners=new WeakMap;for(let[name,measure]of[["byteCount","bytes"],["characterCount","characters"],["tokenCount","tokens"]])Object.defineProperty(FileHandleImpl.prototype,name,{get(){let reference=Object.freeze({kind:"size",file:this.file,measure});return sizeOwners.set(reference,this.recorder),reference},configurable:!0});addSelectDocument(FileHandleImpl,ValueHandleImpl);var PLUGIN_NAME33="@sous-io/sous-plugin-editor",applyInput=jsonSchema32({type:"object",properties:{dryRun:{type:"boolean",description:"Works everything out and reports it, writing nothing."},ignoreFailedAssertions:{type:"boolean",description:"A failed assertion at level error is printed as a warning, and the build carries on."}},additionalProperties:!1}),editorPlugin=definePlugin34({name:PLUGIN_NAME33,version:package_default34.version,description:"Edits to files Sous does not own: declared, recorded, undone and checked by assertions; and the editor service.",dependsOn:{"@sous-io/sous-plugin-compiler":`^${package_default34.version}`,"@sous-io/sous-plugin-variables":`^${package_default34.version}`,"@sous-io/sous-plugin-doctor":`^${package_default34.version}`},register(sous){sous.entities.add("config-key",EDITOR_CONFIG_KEY),sous.services.add("editor",(config2,ctx)=>{let root=ctx.project?.root??path118.resolve("/"),resolver=ctx.services.has("variables.resolver")?ctx.services.get("variables.resolver"):void 0,scope=()=>resolver?.scopeIn(config2),counter;return new EditorServiceImpl(file2=>{let substituted=resolver===void 0?file2:resolver.substitute(file2,scope());return path118.resolve(root,resolver===void 0?substituted:resolver.normalizePath(substituted))},async text=>(counter??=createTokenCounter(),(await counter).count(text)))},{lifetime:"config"}),sous.intents.add({intent:"editor.apply",summary:"Apply the declared edits to files Sous does not own, undo the ones no longer declared, and check the assertions",internal:!0,input:applyInput,handle:(input,ctx)=>applyIntent(input,ctx)}),sous.entities.add("doctor-check",assertionsCheck)}});var package_default35={name:"@sous-io/sous",version:"1.1.4",description:"Compiles AI coding agent configuration (CLAUDE.md, skills, memories) from LiquidJS templates",type:"module",license:"Apache-2.0",author:"Luke Chavers",repository:{type:"git",url:"git+https://github.com/sous-io/sous.git",directory:"packages/sous"},homepage:"https://sous.io",bugs:"https://github.com/sous-io/sous/issues",keywords:["cli","ai","agents","claude","claude-code","codex","prompts","skills","templates","liquidjs"],publishConfig:{access:"public"},bin:{sous:"./dist/bin.js"},files:["dist/bin.js","dist/sous.js","dist/tiktoken_bg.wasm","recipes","docs/markdown/*.md","sous.config.schema.json"],scripts:{test:"vitest run",typecheck:"tsc --noEmit -p .",build:"node scripts/bundle.mjs",prepack:"node scripts/bundle.mjs && node scripts/pack-files.mjs copy",postpack:"node scripts/pack-files.mjs clean"},dependencies:{"@sous-io/sous-plugin-api":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*","@sous-io/sous-lib-documents":"workspace:*","@sous-io/sous-plugin-authoring":"workspace:*","@sous-io/sous-plugin-build":"workspace:*","@sous-io/sous-plugin-claude-code":"workspace:*","@sous-io/sous-plugin-cli":"workspace:*","@sous-io/sous-plugin-compiler":"workspace:*","@sous-io/sous-plugin-confd":"workspace:*","@sous-io/sous-plugin-config-files":"workspace:*","@sous-io/sous-plugin-expressions":"workspace:*","@sous-io/sous-plugin-formats":"workspace:*","@sous-io/sous-plugin-git":"workspace:*","@sous-io/sous-plugin-github":"workspace:*","@sous-io/sous-plugin-gitlab":"workspace:*","@sous-io/sous-plugin-harnesses":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@sous-io/sous-plugin-init":"workspace:*","@sous-io/sous-plugin-inspect":"workspace:*","@sous-io/sous-plugin-liquid":"workspace:*","@sous-io/sous-plugin-local":"workspace:*","@sous-io/sous-plugin-mcp":"workspace:*","@sous-io/sous-plugin-memories":"workspace:*","@sous-io/sous-plugin-npm":"workspace:*","@sous-io/sous-plugin-pnpm":"workspace:*","@sous-io/sous-plugin-recipe-answers":"workspace:*","@sous-io/sous-plugin-recipes":"workspace:*","@sous-io/sous-plugin-refs":"workspace:*","@sous-io/sous-plugin-skills":"workspace:*","@sous-io/sous-plugin-update":"workspace:*","@sous-io/sous-plugin-variables":"workspace:*","@sous-io/sous-plugin-yarn":"workspace:*","@sous-io/sous-plugin-handlers":"workspace:*","@sous-io/sous-plugin-editor":"workspace:*","@sous-io/sous-plugin-doctor":"workspace:*","@sous-io/sous-plugin-migrations":"workspace:*","@sous-io/sous-plugin-codex":"workspace:*",esbuild:"^0.27.4","jsonc-parser":"^3.3.1",yaml:"^2.9.0",zod:"^4.4.3"},engines:{node:">=22"}};var envPluginsPlugin=definePlugin35({name:"@sous-io/sous",version:package_default35.version,description:"Loads the plugins named in SOUS_PLUGINS.",register(sous){sous.config.contribute({id:"sous/env-plugins",contribute(config2){let listed2=(config2.env.SOUS_PLUGINS??"").split(",").map(item=>item.trim()).filter(item=>item!=="");for(let specifier of listed2)config2.atPath("plugins.load").append(specifier)}})}}),BUILT_IN_PLUGINS=[hostPlugin,doctorPlugin,migrationsPlugin,gitPlugin,refsPlugin,variablesPlugin,liquidPlugin,formatsPlugin,expressionsPlugin,configFilesPlugin,confdPlugin,compilerPlugin,recipesPlugin,recipeAnswersPlugin,skillsPlugin,memoriesPlugin,handlersPlugin,editorPlugin,buildPlugin,harnessesPlugin,authoringPlugin,initPlugin,updatePlugin,cliPlugin,inspectPlugin,mcpPlugin,npmPlugin,pnpmPlugin,yarnPlugin,githubPlugin,gitlabPlugin,localPlugin,claudeCodePlugin,codexPlugin,envPluginsPlugin];import{existsSync as existsSync6,statSync as statSync3}from"node:fs";import path119 from"node:path";var CONFIG_FILE_NAMES=["sous.config.ts","sous.config.mts","sous.config.js","sous.config.mjs","sous.config.jsonc","sous.config.json","sous.config.yaml","sous.config.yml"];function findProject(cwd,confDir){for(let dir=path119.resolve(cwd);;dir=path119.dirname(dir)){let sousDir=path119.join(dir,".sous"),configPath3=isDirectory6(sousDir)?configIn(sousDir):void 0;if(configPath3!==void 0)return projectAt(sousDir,configPath3,confDir);if(path119.dirname(dir)===dir)return}}function readOverrides(argv2,env,cwd){let flags=readFlags(argv2,["config","c","sous-config","sous-dir","sous-confd"]),chosen=[[flags.config??flags.c,flags.c!==void 0&&flags.config===void 0?"-c":"--config"],[flags["sous-config"],"--sous-config"],[blank(env.SOUS_CONFIG),"SOUS_CONFIG"],[flags["sous-dir"],"--sous-dir"],[blank(env.SOUS_DIR),"SOUS_DIR"]].find(([value])=>value!==void 0),confd=flags["sous-confd"]??blank(env.SOUS_CONFD);return{config:chosen===void 0?void 0:{value:resolvePath(chosen[0],cwd,env),source:chosen[1]},confDir:confd===void 0?void 0:resolvePath(confd,cwd,env)}}function locateProject(cwd,overrides){if(overrides.config===void 0)return findProject(cwd,overrides.confDir);let{value,source}=overrides.config;if(!existsSync6(value))throw new Error(`${source} path not found: ${value}`);if(!isDirectory6(value))return projectAt(path119.dirname(value),value,overrides.confDir);let direct=configIn(value);if(direct!==void 0)return projectAt(value,direct,overrides.confDir);let nested=path119.join(value,".sous"),nestedConfig=isDirectory6(nested)?configIn(nested):void 0;if(nestedConfig!==void 0)return projectAt(nested,nestedConfig,overrides.confDir);throw new Error(`${source} points at a directory with no sous config file: ${value}
1350
+ `)[0]?.trim();return first2!==void 0&&first2!==""?`${first2} (${outcome.declarer} expects ${outcome.check})`:`${outcome.file} at ${outcome.path||"the root"}: ${outcome.check}, declared by ${outcome.declarer}`}async function checkAssertions(ctx,run){if(run.configFailed)return{status:"skipped",summary:"The config did not load, so the edits and assertions it declares could not be checked."};if(ctx.project===void 0)return{status:"skipped",summary:"There is no project here."};let quiet=Object.create(ctx,{reporter:{value:new BufferedReporter4}}),result=(await applyIntent({dryRun:!0},quiet)).toPlain(),failed=result.assertions.filter(outcome=>!outcome.passed&&outcome.silenced!==!0),errors=failed.filter(outcome=>outcome.level==="error"),warnings=failed.filter(outcome=>outcome.level==="warn"),checked3=result.assertions.filter(outcome=>outcome.silenced!==!0).length;return checked3===0?{status:"ok",summary:"No assertion is declared."}:errors.length>0?{status:"problem",summary:`${errors.length===1?"An assertion fails":`${errors.length} assertions fail`}, so a build would not write ${errors.length===1?"that file":"those files"} and would fail.`,details:[...errors,...warnings].map(describe5),hint:"Put right what each one expects; 'sous build --ignore-failed-assertions' builds anyway."}:warnings.length>0?{status:"warning",summary:`${warnings.length===1?"An assertion at level warn fails":`${warnings.length} assertions at level warn fail`}.`,details:warnings.map(describe5)}:{status:"ok",summary:`${checked3===1?"The one assertion holds":`All ${checked3} assertions hold`}.`}}var assertionsCheck={id:"assertions",order:DOCTOR_CHECK_ORDER.assertions,description:"Every assertion on the files Sous edits holds, checked without writing",check:(ctx,run)=>checkAssertions(ctx,run)};init_zod();var entrySchema=external_exports.record(external_exports.string(),external_exports.unknown()).superRefine((entry,ctx)=>{try{normalizeEntry(entry)}catch(error51){ctx.addIssue({code:"custom",message:error51 instanceof Error?error51.message:String(error51)})}}),editorSchema=external_exports.object({edits:external_exports.array(entrySchema).default([]).describe("The master list of edits to files Sous does not own: each entry names a file and one or more operations, an assertion or a silence. Sous applies them after the compiler, records them, and undoes the ones no longer declared."),historyFile:external_exports.string().optional().describe("Where Sous records the edits it applied, so it can undo them. Default: <sousDir>/sous.edits.json (git-ignored).")}).strict(),EDITOR_CONFIG_KEY={id:"editor",schema:editorSchema.optional(),description:"Edits to files Sous does not own (editor.edits), applied, recorded and undone by the editor."};init_src();import fs87 from"node:fs";import path117 from"node:path";var OpenFile=class{constructor(path122,format3,original,resolve4,countTokens){this.path=path122;this.format=format3;this.original=original;this.resolve=resolve4;this.countTokens=countTokens;this.session=new FileSession(path122||"(text)",format3,original)}session;get existed(){return this.original!==void 0}get document(){return this.session.document()}apply(operation2,params={}){let step=resolveOperation(operation2,params);return step.definition.scope==="directory"?{created:createDirectories2(step.params.paths.map(dir=>this.resolve(dir)),!1)}:step.definition.up({session:this.session,path:step.path,node:()=>this.session.document().atPath(step.path)},step.params,void 0)}undo(operation2,params,record2){let step=resolveOperation(operation2,params);if(step.definition.scope==="directory"){let created=record2?.created??[];removeEmptyDirectories(created,!1);return}if(step.definition.scope==="file"){record2?.created===!0&&this.session.remove();return}step.definition.down({session:this.session,path:step.path,node:()=>this.session.document().atPath(step.path)},step.params,record2)}check(check3,arg,options2={}){let session=this.session,file2=this.path;return runCheck2({file:file2,fileExists:()=>session.final()!==void 0,directoryExists:()=>{try{return fs87.statSync(file2).isDirectory()}catch{return!1}},parsed:()=>session.final()!==void 0&&session.parses(),value:at2=>getAtPath(session.document().value(),parsePath(at2)),text:()=>session.text(),tokens:()=>this.countTokens(session.text())},check3,arg,options2.path??"",options2.not??!1)}text(){return this.session.text()}changed(){return this.session.changed()}write(){if(this.path==="")throw new Error("This document was parsed from text, so it has no file to write; use text().");if(!this.session.changed())return!1;let text=this.session.final();return text===void 0?fs87.rmSync(this.path,{force:!0}):(fs87.mkdirSync(path117.dirname(this.path),{recursive:!0}),fs87.writeFileSync(this.path,text,"utf8")),!0}},EditorServiceImpl=class{constructor(resolve4,countTokens){this.resolve=resolve4;this.countTokens=countTokens}open(file2,options2={}){let absolute=this.resolve(file2),text;try{text=fs87.readFileSync(absolute,"utf8")}catch{text=void 0}return new OpenFile(absolute,options2.format??formatForFile(absolute),text,this.resolve,this.countTokens)}parse(text,format3){return new OpenFile("",format3,text,this.resolve,this.countTokens)}formatOf(file2){return formatForFile(file2)}operations(){return operationInfo()}checks(){return[...CHECKS.keys()]}};var package_default34={name:"@sous-io/sous-plugin-editor",version:"1.1.6",description:"The editor: declared, recorded and undoable edits to files Sous does not own, the assertions on them, and the editor service.",type:"module",license:"Apache-2.0",private:!0,exports:{".":{source:"./src/index.ts",types:"./dist/index.d.ts",default:"./dist/index.js"},"./types":{source:"./src/types.ts",types:"./dist/types.d.ts",default:"./dist/types.js"}},scripts:{test:"vitest run",typecheck:"tsc --noEmit -p ."},dependencies:{"@sous-io/sous-lib-documents":"workspace:*","@sous-io/sous-plugin-api":"workspace:*","@sous-io/sous-plugin-doctor":"workspace:*","@sous-io/sous-plugin-compiler":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@sous-io/sous-plugin-variables":"workspace:*",zod:"^4.4.3"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*"},engines:{node:">=22"}};var CHAIN_OPERATION_NAMES=[...[...OPERATIONS.values()].filter(definition2=>definition2.scope==="document").map(definition2=>definition2.name),...[...ALIASES.values()].filter(entry=>OPERATIONS.get(entry.target)?.scope==="document").map(entry=>entry.name)],ValueHandleImpl=class{constructor(recorder,file2,path122,settings){this.recorder=recorder;this.file=file2;this.path=path122;this.settings=settings}last;lastOperation;record(operation2,args){let params=chainParams(operation2,args),object3=this.path===""?params:{path:this.path,...params},entry={file:this.file,...this.settings,[operation2]:object3};return this.last=this.recorder.append(entry),this.lastOperation=operation2,this}withoutAssertion(){if(this.last===void 0||this.lastOperation===void 0)throw new Error('withoutAssertion() follows an operation: settings.at("a").sort().withoutAssertion().');let operation2=this.lastOperation;return this.recorder.update(this.last,entry=>{entry[operation2].assertion="none"}),this}};for(let name of CHAIN_OPERATION_NAMES)Object.defineProperty(ValueHandleImpl.prototype,name,{value(...args){return this.record(name,args)},writable:!0,configurable:!0});var SilenceHandleImpl=class{constructor(recorder,entry,hasKinds){this.recorder=recorder;this.entry=entry;this.hasKinds=hasKinds}change(key,value){return this.recorder.update(this.entry,entry=>{entry.silence[key]=value}),this}thisKeyOnly(){return this.change("scope","key-only")}belowOnly(){return this.change("scope","below")}except(kinds){if(this.hasKinds)throw new Error('except() only follows a silence with no kinds: settings.silence("permissions.allow").except(["include"]).');return this.change("except",[kinds].flat())}},FileHandleImpl=class extends ValueHandleImpl{constructor(recorder,file2,settings){super(recorder,file2,"",settings)}at(path122){return new ValueHandleImpl(this.recorder,this.file,path122,this.settings)}record(operation2,args){return new ValueHandleImpl(this.recorder,this.file,"",this.settings).record(operation2,args)}ensureFileExists(content){let object3=content===void 0?{}:{content};return this.recorder.append({file:this.file,...this.settings,ensureFileExists:object3}),this}silence(path122="",kinds){let silence={...path122===""?{}:{path:path122},...kinds===void 0?{}:{kinds:[kinds].flat()}},entry=this.recorder.append({file:this.file,silence});return new SilenceHandleImpl(this.recorder,entry,kinds!==void 0)}withoutAutomaticAssertions(){return this.recorder.append({file:this.file,silence:{}}),this}};var sizeOwners=new WeakMap;for(let[name,measure]of[["byteCount","bytes"],["characterCount","characters"],["tokenCount","tokens"]])Object.defineProperty(FileHandleImpl.prototype,name,{get(){let reference=Object.freeze({kind:"size",file:this.file,measure});return sizeOwners.set(reference,this.recorder),reference},configurable:!0});addSelectDocument(FileHandleImpl,ValueHandleImpl);var PLUGIN_NAME33="@sous-io/sous-plugin-editor",applyInput=jsonSchema32({type:"object",properties:{dryRun:{type:"boolean",description:"Works everything out and reports it, writing nothing."},ignoreFailedAssertions:{type:"boolean",description:"A failed assertion at level error is printed as a warning, and the build carries on."}},additionalProperties:!1}),editorPlugin=definePlugin34({name:PLUGIN_NAME33,version:package_default34.version,description:"Edits to files Sous does not own: declared, recorded, undone and checked by assertions; and the editor service.",dependsOn:{"@sous-io/sous-plugin-compiler":`^${package_default34.version}`,"@sous-io/sous-plugin-variables":`^${package_default34.version}`,"@sous-io/sous-plugin-doctor":`^${package_default34.version}`},register(sous){sous.entities.add("config-key",EDITOR_CONFIG_KEY),sous.services.add("editor",(config2,ctx)=>{let root=ctx.project?.root??path118.resolve("/"),resolver=ctx.services.has("variables.resolver")?ctx.services.get("variables.resolver"):void 0,scope=()=>resolver?.scopeIn(config2),counter;return new EditorServiceImpl(file2=>{let substituted=resolver===void 0?file2:resolver.substitute(file2,scope());return path118.resolve(root,resolver===void 0?substituted:resolver.normalizePath(substituted))},async text=>(counter??=createTokenCounter(),(await counter).count(text)))},{lifetime:"config"}),sous.intents.add({intent:"editor.apply",summary:"Apply the declared edits to files Sous does not own, undo the ones no longer declared, and check the assertions",internal:!0,input:applyInput,handle:(input,ctx)=>applyIntent(input,ctx)}),sous.entities.add("doctor-check",assertionsCheck)}});var package_default35={name:"@sous-io/sous",version:"1.1.6",description:"Compiles AI coding agent configuration (CLAUDE.md, skills, memories) from LiquidJS templates",type:"module",license:"Apache-2.0",author:"Luke Chavers",repository:{type:"git",url:"git+https://github.com/sous-io/sous.git",directory:"packages/sous"},homepage:"https://sous.io",bugs:"https://github.com/sous-io/sous/issues",keywords:["cli","ai","agents","claude","claude-code","codex","prompts","skills","templates","liquidjs"],publishConfig:{access:"public"},bin:{sous:"./dist/bin.js"},files:["dist/bin.js","dist/sous.js","dist/tiktoken_bg.wasm","recipes","docs/markdown/*.md","sous.config.schema.json"],scripts:{test:"vitest run",typecheck:"tsc --noEmit -p .",build:"node scripts/bundle.mjs",prepack:"node scripts/bundle.mjs && node scripts/pack-files.mjs copy",postpack:"node scripts/pack-files.mjs clean"},dependencies:{"@sous-io/sous-plugin-api":"workspace:*"},devDependencies:{"@sous-io/sous-lib-core":"workspace:*","@sous-io/sous-lib-documents":"workspace:*","@sous-io/sous-plugin-authoring":"workspace:*","@sous-io/sous-plugin-build":"workspace:*","@sous-io/sous-plugin-claude-code":"workspace:*","@sous-io/sous-plugin-cli":"workspace:*","@sous-io/sous-plugin-compiler":"workspace:*","@sous-io/sous-plugin-confd":"workspace:*","@sous-io/sous-plugin-config-files":"workspace:*","@sous-io/sous-plugin-expressions":"workspace:*","@sous-io/sous-plugin-formats":"workspace:*","@sous-io/sous-plugin-git":"workspace:*","@sous-io/sous-plugin-github":"workspace:*","@sous-io/sous-plugin-gitlab":"workspace:*","@sous-io/sous-plugin-harnesses":"workspace:*","@sous-io/sous-plugin-host":"workspace:*","@sous-io/sous-plugin-init":"workspace:*","@sous-io/sous-plugin-inspect":"workspace:*","@sous-io/sous-plugin-liquid":"workspace:*","@sous-io/sous-plugin-local":"workspace:*","@sous-io/sous-plugin-mcp":"workspace:*","@sous-io/sous-plugin-memories":"workspace:*","@sous-io/sous-plugin-npm":"workspace:*","@sous-io/sous-plugin-pnpm":"workspace:*","@sous-io/sous-plugin-recipe-answers":"workspace:*","@sous-io/sous-plugin-recipes":"workspace:*","@sous-io/sous-plugin-refs":"workspace:*","@sous-io/sous-plugin-skills":"workspace:*","@sous-io/sous-plugin-update":"workspace:*","@sous-io/sous-plugin-variables":"workspace:*","@sous-io/sous-plugin-yarn":"workspace:*","@sous-io/sous-plugin-handlers":"workspace:*","@sous-io/sous-plugin-editor":"workspace:*","@sous-io/sous-plugin-doctor":"workspace:*","@sous-io/sous-plugin-migrations":"workspace:*","@sous-io/sous-plugin-codex":"workspace:*",esbuild:"^0.27.4","jsonc-parser":"^3.3.1",yaml:"^2.9.0",zod:"^4.4.3"},engines:{node:">=22"}};var envPluginsPlugin=definePlugin35({name:"@sous-io/sous",version:package_default35.version,description:"Loads the plugins named in SOUS_PLUGINS.",register(sous){sous.config.contribute({id:"sous/env-plugins",contribute(config2){let listed2=(config2.env.SOUS_PLUGINS??"").split(",").map(item=>item.trim()).filter(item=>item!=="");for(let specifier of listed2)config2.atPath("plugins.load").append(specifier)}})}}),BUILT_IN_PLUGINS=[hostPlugin,doctorPlugin,migrationsPlugin,gitPlugin,refsPlugin,variablesPlugin,liquidPlugin,formatsPlugin,expressionsPlugin,configFilesPlugin,confdPlugin,compilerPlugin,recipesPlugin,recipeAnswersPlugin,skillsPlugin,memoriesPlugin,handlersPlugin,editorPlugin,buildPlugin,harnessesPlugin,authoringPlugin,initPlugin,updatePlugin,cliPlugin,inspectPlugin,mcpPlugin,npmPlugin,pnpmPlugin,yarnPlugin,githubPlugin,gitlabPlugin,localPlugin,claudeCodePlugin,codexPlugin,envPluginsPlugin];import{existsSync as existsSync6,statSync as statSync3}from"node:fs";import path119 from"node:path";var CONFIG_FILE_NAMES=["sous.config.ts","sous.config.mts","sous.config.js","sous.config.mjs","sous.config.jsonc","sous.config.json","sous.config.yaml","sous.config.yml"];function findProject(cwd,confDir){for(let dir=path119.resolve(cwd);;dir=path119.dirname(dir)){let sousDir=path119.join(dir,".sous"),configPath3=isDirectory6(sousDir)?configIn(sousDir):void 0;if(configPath3!==void 0)return projectAt(sousDir,configPath3,confDir);if(path119.dirname(dir)===dir)return}}function readOverrides(argv2,env,cwd){let flags=readFlags(argv2,["config","c","sous-config","sous-dir","sous-confd"]),chosen=[[flags.config??flags.c,flags.c!==void 0&&flags.config===void 0?"-c":"--config"],[flags["sous-config"],"--sous-config"],[blank(env.SOUS_CONFIG),"SOUS_CONFIG"],[flags["sous-dir"],"--sous-dir"],[blank(env.SOUS_DIR),"SOUS_DIR"]].find(([value])=>value!==void 0),confd=flags["sous-confd"]??blank(env.SOUS_CONFD);return{config:chosen===void 0?void 0:{value:resolvePath(chosen[0],cwd,env),source:chosen[1]},confDir:confd===void 0?void 0:resolvePath(confd,cwd,env)}}function locateProject(cwd,overrides){if(overrides.config===void 0)return findProject(cwd,overrides.confDir);let{value,source}=overrides.config;if(!existsSync6(value))throw new Error(`${source} path not found: ${value}`);if(!isDirectory6(value))return projectAt(path119.dirname(value),value,overrides.confDir);let direct=configIn(value);if(direct!==void 0)return projectAt(value,direct,overrides.confDir);let nested=path119.join(value,".sous"),nestedConfig=isDirectory6(nested)?configIn(nested):void 0;if(nestedConfig!==void 0)return projectAt(nested,nestedConfig,overrides.confDir);throw new Error(`${source} points at a directory with no sous config file: ${value}
1350
1351
  Looked for: ${CONFIG_FILE_NAMES.join(", ")}`)}function projectAt(sousDir,configPath3,confDir){return{root:path119.dirname(sousDir),sousDir,configPath:configPath3,confDir:confDir??path119.join(sousDir,"conf.d")}}function configIn(sousDir){let name=CONFIG_FILE_NAMES.find(candidate=>isFile10(path119.join(sousDir,candidate)));return name===void 0?void 0:path119.join(sousDir,name)}function readFlags(argv2,names2){let found={};for(let i=0;i<argv2.length;i++){let arg=argv2[i];if(arg==="--")break;for(let name of names2){let flag=name.length===1?`-${name}`:`--${name}`;found[name]===void 0&&(arg===flag?found[name]=blank(argv2[i+1]):arg.startsWith(`${flag}=`)?found[name]=blank(arg.slice(flag.length+1)):name.length===1&&arg.startsWith(flag)&&arg.length>2&&!arg.startsWith(`${flag}-`)&&(found[name]=blank(arg.slice(2))))}}return found}function blank(value){return value===void 0||value.trim()===""?void 0:value}function resolvePath(value,cwd,env){let home=env.HOME;return home!==void 0&&(value==="~"||value.startsWith("~/"))?path119.join(home,value.slice(1)):path119.resolve(cwd,value)}function isDirectory6(file2){try{return statSync3(file2).isDirectory()}catch{return!1}}function isFile10(file2){try{return statSync3(file2).isFile()}catch{return!1}}init_src2();import{createHash as createHash8}from"node:crypto";import{existsSync as existsSync7,mkdirSync,readdirSync,readFileSync as readFileSync4,statSync as statSync4,writeFileSync}from"node:fs";import path120 from"node:path";var STARTUP_FACT_FILENAME="sous.startup.json",IGNORED_FILES=new Set([STARTUP_FACT_FILENAME,"sous.state.json","sous.pid"]),IGNORED_HOME_DIRECTORIES=new Set(["cache","repos"]);function factFile(project,env){let name=project===void 0?"no-project":createHash8("sha256").update(project.sousDir).digest("hex").slice(0,16);return path120.join(resolveSousHomePaths(env).root,"cache","startup",`${name}.json`)}function signature(file2){try{let stats=statSync4(file2);return`${file2} ${stats.size} ${stats.mtimeMs}`}catch{return`${file2} -`}}function signaturesIn(directory,recurse,skip=new Set){let entries;try{entries=readdirSync(directory,{withFileTypes:!0})}catch{return[]}let lines3=[];for(let entry of entries){let full=path120.join(directory,entry.name);entry.isDirectory()?recurse&&!skip.has(entry.name)&&lines3.push(...signaturesIn(full,!0)):IGNORED_FILES.has(entry.name)||lines3.push(signature(full))}return lines3}function startupKey(project,env,version2,bundle){let lines3=[version2,signature(bundle),JSON.stringify(project??null)];for(let name of Object.keys(env).sort())name.startsWith("SOUS_")&&lines3.push(`${name}=${env[name]}`);project!==void 0&&(lines3.push(...signaturesIn(project.sousDir,!1)),lines3.push(...signaturesIn(project.confDir,!0)),project.configPath!==void 0&&lines3.push(signature(project.configPath)));let home=resolveSousHomePaths(env).root;return lines3.push(...signaturesIn(home,!0,IGNORED_HOME_DIRECTORIES)),createHash8("sha1").update(lines3.sort().join(`
1351
1352
  `)).digest("hex")}function readFact(file2){try{let parsed=JSON.parse(readFileSync4(file2,"utf8"));return typeof parsed.key=="string"&&typeof parsed.builtInsOnly=="boolean"?{key:parsed.key,builtInsOnly:parsed.builtInsOnly}:void 0}catch{return}}function loadsOnlyBuiltIns(project,env,key){let fact=readFact(factFile(project,env));return fact!==void 0&&fact.key===key&&fact.builtInsOnly}function recordStartupFact(project,env,key,builtInsOnly){let file2=factFile(project,env),previous=readFact(file2);if(!(previous?.key===key&&previous.builtInsOnly===builtInsOnly))try{if(!existsSync7(resolveSousHomePaths(env).root))return;mkdirSync(path120.dirname(file2),{recursive:!0}),writeFileSync(file2,`${JSON.stringify({key,builtInsOnly})}
1352
- `,"utf8")}catch{}}function sousVersion(){try{let manifest=JSON.parse(readFileSync5(new URL("../package.json",import.meta.url),"utf8"));if(manifest.name==="@sous-io/sous"&&typeof manifest.version=="string")return manifest.version}catch{}return"1.1.4"}async function main(argv2,options2){let overrides=readOverrides(argv2,options2.env,options2.cwd),project;try{project=locateProject(options2.cwd,overrides)}catch(error51){options2.stderr.write(`Error: ${error51 instanceof Error?error51.message:String(error51)}
1353
+ `,"utf8")}catch{}}function sousVersion(){try{let manifest=JSON.parse(readFileSync5(new URL("../package.json",import.meta.url),"utf8"));if(manifest.name==="@sous-io/sous"&&typeof manifest.version=="string")return manifest.version}catch{}return"1.1.6"}async function main(argv2,options2){let overrides=readOverrides(argv2,options2.env,options2.cwd),project;try{project=locateProject(options2.cwd,overrides)}catch(error51){options2.stderr.write(`Error: ${error51 instanceof Error?error51.message:String(error51)}
1353
1354
  `),options2.setExitCode(1);return}let engine=createEngine({project,env:projectEnvironment(project,options2.env),cwd:options2.cwd,app:{name:"sous",version:sousVersion()},builtIns:BUILT_IN_PLUGINS,budgets:budgetsOff(options2.env.SOUS_BUDGETS)?noBudgets():void 0,locateProject:directory=>findProject(directory,overrides.confDir)}),key=startupKey(project,options2.env,sousVersion(),fileURLToPath4(import.meta.url)),quiet=!1,plan2;if(await engine.loadBuiltInsOnly(),hasFrontEnd(engine,"cli")&&(plan2=engine.frontEnd("cli").plan(argv2),!engine.frontEnd("cli").needsConfig(argv2))){if(loadsOnlyBuiltIns(project,options2.env,key)){await engine.frontEnd("cli").start(argv2),await engine.whenBackgroundIntentsReturn();return}quiet=!0}try{await engine.buildConfig({...quiet?{reportBudgets:!1}:{},...plan2===void 0?{}:{plan:plan2}}),recordStartupFact(project,options2.env,key,engine.pluginInfo().every(plugin=>plugin.builtIn))}catch(error51){if(hasFrontEnd(engine,"cli")){await engine.frontEnd("cli").start(argv2),await engine.whenBackgroundIntentsReturn();return}let message2=error51 instanceof Error?error51.message:String(error51),details=isSousError7(error51)?error51.details.map(line=>`
1354
1355
  ${line}`).join(""):"";options2.stderr.write(`Error: ${message2}${details}
1355
1356
  `),options2.setExitCode(isSousError7(error51)?error51.exitCode:1);return}await engine.frontEnd("cli").start(argv2),await engine.whenBackgroundIntentsReturn()}function budgetsOff(value){return["0","false","no","off"].includes((value??"").trim().toLowerCase())}function noBudgets(){return Object.fromEntries(Object.keys(DEFAULT_BUDGETS).map(category=>[category,!1]))}function hasFrontEnd(engine,id){try{return engine.frontEnd(id),!0}catch{return!1}}var argv=process.argv.slice(2),ownRoot=path121.resolve(path121.dirname(fileURLToPath5(import.meta.url)),".."),handedOff=await handOffToProjectInstall({ownRoot,cwd:process.cwd(),env:process.env,argv,stderr:process.stderr});handedOff||await main(argv,{cwd:process.cwd(),env:process.env,stderr:process.stderr,setExitCode(code){process.exitCode=code}});