@punks/cli 3.1.0 → 3.1.1-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -1
- package/dist/BASELINE_CHANGELOG.md +6 -0
- package/dist/CHANGELOG.md +19 -0
- package/dist/baseline/scaffold-baseline/baseline.json +5 -5
- package/dist/baseline/scaffold-baseline.json +5 -5
- package/dist/baseline/scaffold-baseline.tgz +0 -0
- package/dist/index.js +11 -11
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -186,7 +186,7 @@ ${prefix}}`}return stack};var FiberTypeId=`~effect/Fiber/${version}`;var fiberVa
|
|
|
186
186
|
`)){filepath=filepath.replace(newlineRegExp,"%0A")}if(filepath.includes("\r")){filepath=filepath.replace(carriageReturnRegExp,"%0D")}if(filepath.includes("\t")){filepath=filepath.replace(tabRegExp,"%09")}return filepath}var posixImpl=Path.of({[TypeId29]:TypeId29,resolve:resolve2,normalize(path){if(path.length===0)return".";const isAbsolute=path.charCodeAt(0)===47;const trailingSeparator=path.charCodeAt(path.length-1)===47;path=normalizeStringPosix(path,!isAbsolute);if(path.length===0&&!isAbsolute)path=".";if(path.length>0&&trailingSeparator)path+="/";if(isAbsolute)return"/"+path;return path},isAbsolute(path){return path.length>0&&path.charCodeAt(0)===47},join(){if(arguments.length===0){return"."}let joined;for(let i=0;i<arguments.length;++i){const arg=arguments[i];if(arg.length>0){if(joined===undefined){joined=arg}else{joined+="/"+arg}}}if(joined===undefined){return"."}return posixImpl.normalize(joined)},relative(from,to){if(from===to)return"";from=posixImpl.resolve(from);to=posixImpl.resolve(to);if(from===to)return"";let fromStart=1;for(;fromStart<from.length;++fromStart){if(from.charCodeAt(fromStart)!==47){break}}const fromEnd=from.length;const fromLen=fromEnd-fromStart;let toStart=1;for(;toStart<to.length;++toStart){if(to.charCodeAt(toStart)!==47){break}}const toEnd=to.length;const toLen=toEnd-toStart;const length=fromLen<toLen?fromLen:toLen;let lastCommonSep=-1;let i=0;for(;i<=length;++i){if(i===length){if(toLen>length){if(to.charCodeAt(toStart+i)===47){return to.slice(toStart+i+1)}else if(i===0){return to.slice(toStart+i)}}else if(fromLen>length){if(from.charCodeAt(fromStart+i)===47){lastCommonSep=i}else if(i===0){lastCommonSep=0}}break}const fromCode=from.charCodeAt(fromStart+i);const toCode=to.charCodeAt(toStart+i);if(fromCode!==toCode){break}else if(fromCode===47){lastCommonSep=i}}let out="";for(i=fromStart+lastCommonSep+1;i<=fromEnd;++i){if(i===fromEnd||from.charCodeAt(i)===47){if(out.length===0){out+=".."}else{out+="/.."}}}if(out.length>0){return out+to.slice(toStart+lastCommonSep)}else{toStart+=lastCommonSep;if(to.charCodeAt(toStart)===47){++toStart}return to.slice(toStart)}},dirname(path){if(path.length===0)return".";let code=path.charCodeAt(0);const hasRoot=code===47;let end=-1;let matchedSlash=true;for(let i=path.length-1;i>=1;--i){code=path.charCodeAt(i);if(code===47){if(!matchedSlash){end=i;break}}else{matchedSlash=false}}if(end===-1)return hasRoot?"/":".";if(hasRoot&&end===1)return"//";return path.slice(0,end)},basename(path,ext){let start=0;let end=-1;let matchedSlash=true;let i;if(ext!==undefined&&ext.length>0&&ext.length<=path.length){if(ext.length===path.length&&ext===path)return"";let extIdx=ext.length-1;let firstNonSlashEnd=-1;for(i=path.length-1;i>=0;--i){const code=path.charCodeAt(i);if(code===47){if(!matchedSlash){start=i+1;break}}else{if(firstNonSlashEnd===-1){matchedSlash=false;firstNonSlashEnd=i+1}if(extIdx>=0){if(code===ext.charCodeAt(extIdx)){if(--extIdx===-1){end=i}}else{extIdx=-1;end=firstNonSlashEnd}}}}if(start===end)end=firstNonSlashEnd;else if(end===-1)end=path.length;return path.slice(start,end)}else{for(i=path.length-1;i>=0;--i){if(path.charCodeAt(i)===47){if(!matchedSlash){start=i+1;break}}else if(end===-1){matchedSlash=false;end=i+1}}if(end===-1)return"";return path.slice(start,end)}},extname(path){let startDot=-1;let startPart=0;let end=-1;let matchedSlash=true;let preDotState=0;for(let i=path.length-1;i>=0;--i){const code=path.charCodeAt(i);if(code===47){if(!matchedSlash){startPart=i+1;break}continue}if(end===-1){matchedSlash=false;end=i+1}if(code===46){if(startDot===-1){startDot=i}else if(preDotState!==1){preDotState=1}}else if(startDot!==-1){preDotState=-1}}if(startDot===-1||end===-1||preDotState===0||preDotState===1&&startDot===end-1&&startDot===startPart+1){return""}return path.slice(startDot,end)},format:function format4(pathObject){if(pathObject===null||typeof pathObject!=="object"){throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof pathObject)}return _format("/",pathObject)},parse(path){const ret={root:"",dir:"",base:"",ext:"",name:""};if(path.length===0)return ret;let code=path.charCodeAt(0);const isAbsolute=code===47;let start;if(isAbsolute){ret.root="/";start=1}else{start=0}let startDot=-1;let startPart=0;let end=-1;let matchedSlash=true;let i=path.length-1;let preDotState=0;for(;i>=start;--i){code=path.charCodeAt(i);if(code===47){if(!matchedSlash){startPart=i+1;break}continue}if(end===-1){matchedSlash=false;end=i+1}if(code===46){if(startDot===-1)startDot=i;else if(preDotState!==1)preDotState=1}else if(startDot!==-1){preDotState=-1}}if(startDot===-1||end===-1||preDotState===0||preDotState===1&&startDot===end-1&&startDot===startPart+1){if(end!==-1){if(startPart===0&&isAbsolute)ret.base=ret.name=path.slice(1,end);else ret.base=ret.name=path.slice(startPart,end)}}else{if(startPart===0&&isAbsolute){ret.name=path.slice(1,startDot);ret.base=path.slice(1,end)}else{ret.name=path.slice(startPart,startDot);ret.base=path.slice(startPart,end)}ret.ext=path.slice(startDot,end)}if(startPart>0)ret.dir=path.slice(0,startPart-1);else if(isAbsolute)ret.dir="/";return ret},sep:"/",fromFileUrl,toFileUrl,toNamespacedPath:identity});function makeValue(value3){return{_tag:"Value",value:value3}}function makeRecord(keys2,value3){return{_tag:"Record",keys:keys2,value:value3}}function makeArray(length,value3){return{_tag:"Array",length,value:value3}}class SourceError extends TaggedError2("SourceError"){}var ConfigProvider=Reference("effect/ConfigProvider",{defaultValue:()=>fromEnv()});var Proto5={...PipeInspectableProto,toJSON(){return{_id:"ConfigProvider"}}};var identityPath=(path)=>path;function makeProvider(state,load){const self=Object.create(Proto5);self.state=state;self.load=load;return self}function makeSource(get4,transform3){const state={_tag:"Source",get:get4,transform:transform3};return makeProvider(state,(path)=>state.get(state.transform(path)))}function makeOrElse(first,second){const state={_tag:"OrElse",first,second};return makeProvider(state,(path)=>flatMap4(state.first.load(path),(node)=>node?succeed6(node):state.second.load(path)))}function make20(get4){return makeSource(get4,identityPath)}var orElse=dual(2,(self,that)=>makeOrElse(self,that));var mapInput2=dual(2,(self,f)=>{const state=self.state;switch(state._tag){case"Source":return makeSource(state.get,flow(state.transform,f));case"OrElse":return makeOrElse(mapInput2(state.first,f),mapInput2(state.second,f))}});var constantCase=mapInput2((path)=>path.map((seg)=>typeof seg==="number"?seg:configCase(seg)));var nested=dual(2,(self,prefix)=>{const path=typeof prefix==="string"?[prefix]:prefix;const state=self.state;switch(state._tag){case"Source":return makeSource(state.get,flow(state.transform,(input)=>[...path,...input]));case"OrElse":return makeOrElse(nested(state.first,path),nested(state.second,path))}});var layer=(self)=>isEffect2(self)?effect(ConfigProvider)(self):succeed5(ConfigProvider)(self);var layerAdd=(self,options)=>effect(ConfigProvider)(gen2(function*(){const current=yield*ConfigProvider;const configProvider=isEffect2(self)?yield*self:self;return options?.asPrimary?orElse(configProvider,current):orElse(current,configProvider)}));function fromUnknown(root,options){const preserveEmptyStrings=options?.preserveEmptyStrings===true;return make20((path)=>succeed6(nodeAtJson(root,path,preserveEmptyStrings)))}function nodeAtJson(root,path,preserveEmptyStrings){let cur=root;for(const seg of path){if(cur===null||cur===undefined)return;if(Array.isArray(cur)){if(typeof seg!=="number"||!Number.isInteger(seg)||seg<0||seg>=cur.length)return;cur=cur[seg];continue}if(isObject(cur)){if(typeof seg!=="string")return;if(!Object.hasOwn(cur,seg))return;cur=cur[seg];continue}return}return describeUnknown(cur,preserveEmptyStrings)}function describeUnknown(u,preserveEmptyStrings){if(u===undefined||u===null)return;if(typeof u==="string")return stringNode(u,preserveEmptyStrings);if(typeof u==="number"||typeof u==="boolean"||typeof u==="bigint"){return makeValue(String(u))}if(Array.isArray(u))return makeArray(u.length);if(isObject(u)){return makeRecord(new Set(Object.keys(u)))}return makeValue(format(u))}function stringNode(value3,preserveEmptyStrings){const normalized=emptyStringAsMissing(value3,preserveEmptyStrings);return normalized===undefined?undefined:makeValue(normalized)}function emptyStringAsMissing(value3,preserveEmptyStrings){return value3===""&&!preserveEmptyStrings?undefined:value3}function fromEnv(options){const env=options?.env??{...globalThis?.process?.env,...import.meta?.env};const preserveEmptyStrings=options?.preserveEmptyStrings===true;const trie=buildEnvTrie(env);return make20((path)=>succeed6(nodeAtEnv(trie,env,path,preserveEmptyStrings)))}function buildEnvTrie(env){const trie={};for(const[name,value3]of Object.entries(env)){if(value3===undefined)continue;const segments=name.split("_");let node=trie;for(const seg of segments){node.children??={};node=node.children[seg]??={}}}return trie}var NUMERIC_INDEX=/^(0|[1-9][0-9]*)$/;function nodeAtEnv(trie,env,path,preserveEmptyStrings){const key=path.map(String).join("_");const leafValue=emptyStringAsMissing(env[key],preserveEmptyStrings);const trieNode=trieNodeAt(trie,path);const children=trieNode?.children?Object.keys(trieNode.children):[];if(children.length===0){return leafValue===undefined?undefined:makeValue(leafValue)}const allNumeric=children.every((k)=>NUMERIC_INDEX.test(k));if(allNumeric){const length=Math.max(...children.map((k)=>parseInt(k,10)))+1;return makeArray(length,leafValue)}return makeRecord(new Set(children),leafValue)}function trieNodeAt(root,path){if(path.length===0)return root;let node=root;for(const seg of path){node=node?.children?.[String(seg)];if(!node)return}return node}function fromDotEnvContents(lines,options){let env=parseDotEnvContents(lines);if(options?.expandVariables){env=dotEnvExpand(env)}return fromEnv({env,preserveEmptyStrings:options?.preserveEmptyStrings})}var DOT_ENV_LINE=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function parseDotEnvContents(lines){const obj={};lines=lines.replace(/\r\n?/gm,`
|
|
187
187
|
`);let match8;while((match8=DOT_ENV_LINE.exec(lines))!=null){const key=match8[1];let value3=match8[2]||"";value3=value3.trim();const maybeQuote=value3[0];value3=value3.replace(/^(['"`])([\s\S]*)\1$/gm,"$2");if(maybeQuote==='"'){value3=value3.replace(/\\n/g,`
|
|
188
188
|
`);value3=value3.replace(/\\r/g,"\r")}obj[key]=value3}return obj}function dotEnvExpand(parsed){const newParsed={};for(const configKey in parsed){newParsed[configKey]=interpolate(parsed[configKey],parsed).replace(/\\\$/g,"$")}return newParsed}function interpolate(envValue,parsed){const lastUnescapedDollarSignIndex=searchLast(envValue,/(?!(?<=\\))\$/g);if(lastUnescapedDollarSignIndex===-1)return envValue;const rightMostGroup=envValue.slice(lastUnescapedDollarSignIndex);const matchGroup=/((?!(?<=\\))\${?([\w]+)(?::-([^}\\]*))?}?)/;const match8=rightMostGroup.match(matchGroup);if(match8!==null){const[_,group,variableName,defaultValue]=match8;return interpolate(envValue.replace(group,defaultValue||parsed[variableName]||""),parsed)}return envValue}function searchLast(str,rgx){const matches=Array.from(str.matchAll(rgx));return matches.length>0?matches.slice(-1)[0].index:-1}var fromDotEnv=fnUntraced2(function*(options){const fs=yield*FileSystem;const content=yield*fs.readFileString(options?.path??".env");return fromDotEnvContents(content,options)});var fromDir=fnUntraced2(function*(options){const platformPath=yield*Path;const fs=yield*FileSystem;const rootPath=options?.rootPath??"/";const preserveEmptyStrings=options?.preserveEmptyStrings===true;return make20((path)=>{const fullPath=platformPath.join(rootPath,...path.map(String));const asFile=fs.readFileString(fullPath).pipe(map7((content)=>stringNode(content.trim(),preserveEmptyStrings)));const asDirectory=fs.readDirectory(fullPath).pipe(map7((entries)=>makeRecord(new Set(entries.map((entry)=>platformPath.basename(entry))))));return asFile.pipe(catch_2((fileCause)=>asDirectory.pipe(catch_2((dirCause)=>isNotFound(fileCause)&&isNotFound(dirCause)?succeed6(undefined):fail6(isNotFound(fileCause)?dirCause:fileCause)))),mapError3((cause)=>new SourceError({message:`Failed to read file at ${platformPath.join(rootPath,...path.map(String))}`,cause})))})});var isNotFound=(cause)=>cause.reason._tag==="NotFound";var values=["All","Fatal","Error","Warn","Info","Debug","Trace","None"];var exports_Schema={};__export(exports_Schema,{withDecodingDefaultTypeKey:()=>withDecodingDefaultTypeKey,withDecodingDefaultType:()=>withDecodingDefaultType,withDecodingDefaultKey:()=>withDecodingDefaultKey,withDecodingDefault:()=>withDecodingDefault,withConstructorDefault:()=>withConstructorDefault2,toType:()=>toType2,toTaggedUnion:()=>toTaggedUnion,toStandardSchemaV1:()=>toStandardSchemaV1,toStandardJSONSchemaV1:()=>toStandardJSONSchemaV1,toRepresentation:()=>toRepresentation,toJsonSchemaDocument:()=>toJsonSchemaDocument2,toIsoSource:()=>toIsoSource,toIsoFocus:()=>toIsoFocus,toIso:()=>toIso,toFormatter:()=>toFormatter,toEquivalence:()=>toEquivalence2,toEncoderXml:()=>toEncoderXml,toEncoded:()=>toEncoded2,toDifferJsonPatch:()=>toDifferJsonPatch,toCodecStringTree:()=>toCodecStringTree,toCodecJson:()=>toCodecJson,toCodecIso:()=>toCodecIso,toCodecArrayFromSingle:()=>toCodecArrayFromSingle,toArbitraryLazy:()=>toArbitraryLazy,toArbitrary:()=>toArbitrary,tagDefaultOmit:()=>tagDefaultOmit,tag:()=>tag,suspend:()=>suspend5,revealCodec:()=>revealCodec,revealBottom:()=>revealBottom,resolveAnnotationsKey:()=>resolveAnnotationsKey,resolveAnnotations:()=>resolveAnnotations,requiredKey:()=>requiredKey,required:()=>required,refine:()=>refine,redact:()=>redact3,readonlyKey:()=>readonlyKey,overrideToFormatter:()=>overrideToFormatter,overrideToEquivalence:()=>overrideToEquivalence,overrideToCodecIso:()=>overrideToCodecIso,optionalKey:()=>optionalKey2,optional:()=>optional,mutableKey:()=>mutableKey2,mutable:()=>mutable,middlewareEncoding:()=>middlewareEncoding2,middlewareDecoding:()=>middlewareDecoding2,makeIsMultipleOf:()=>makeIsMultipleOf,makeIsLessThanOrEqualTo:()=>makeIsLessThanOrEqualTo,makeIsLessThan:()=>makeIsLessThan,makeIsGreaterThanOrEqualTo:()=>makeIsGreaterThanOrEqualTo,makeIsGreaterThan:()=>makeIsGreaterThan,makeIsBetween:()=>makeIsBetween,makeFilterGroup:()=>makeFilterGroup,makeFilter:()=>makeFilter2,make:()=>make26,link:()=>link,isUppercased:()=>isUppercased,isUnique:()=>isUnique,isUncapitalized:()=>isUncapitalized,isUint32:()=>isUint32,isUUID:()=>isUUID,isULID:()=>isULID,isTrimmed:()=>isTrimmed,isStringSymbol:()=>isStringSymbol2,isStringFinite:()=>isStringFinite2,isStringBigInt:()=>isStringBigInt2,isStartsWith:()=>isStartsWith,isSizeBetween:()=>isSizeBetween,isSchemaError:()=>isSchemaError,isSchema:()=>isSchema,isPropertyNames:()=>isPropertyNames,isPropertiesLengthBetween:()=>isPropertiesLengthBetween,isPattern:()=>isPattern2,isNonEmpty:()=>isNonEmpty,isMultipleOf:()=>isMultipleOf,isMinSize:()=>isMinSize,isMinProperties:()=>isMinProperties,isMinLength:()=>isMinLength,isMaxSize:()=>isMaxSize,isMaxProperties:()=>isMaxProperties,isMaxLength:()=>isMaxLength,isLowercased:()=>isLowercased,isLessThanOrEqualToDate:()=>isLessThanOrEqualToDate,isLessThanOrEqualToBigInt:()=>isLessThanOrEqualToBigInt,isLessThanOrEqualToBigDecimal:()=>isLessThanOrEqualToBigDecimal,isLessThanOrEqualTo:()=>isLessThanOrEqualTo4,isLessThanDate:()=>isLessThanDate,isLessThanBigInt:()=>isLessThanBigInt,isLessThanBigDecimal:()=>isLessThanBigDecimal,isLessThan:()=>isLessThan4,isLengthBetween:()=>isLengthBetween,isInt32:()=>isInt32,isInt:()=>isInt,isIncludes:()=>isIncludes,isGreaterThanOrEqualToDate:()=>isGreaterThanOrEqualToDate,isGreaterThanOrEqualToBigInt:()=>isGreaterThanOrEqualToBigInt,isGreaterThanOrEqualToBigDecimal:()=>isGreaterThanOrEqualToBigDecimal,isGreaterThanOrEqualTo:()=>isGreaterThanOrEqualTo3,isGreaterThanDate:()=>isGreaterThanDate,isGreaterThanBigInt:()=>isGreaterThanBigInt,isGreaterThanBigDecimal:()=>isGreaterThanBigDecimal,isGreaterThan:()=>isGreaterThan4,isGUID:()=>isGUID,isFinite:()=>isFinite3,isEndsWith:()=>isEndsWith,isDateValid:()=>isDateValid,isCapitalized:()=>isCapitalized,isBetweenDate:()=>isBetweenDate,isBetweenBigInt:()=>isBetweenBigInt,isBetweenBigDecimal:()=>isBetweenBigDecimal,isBetween:()=>isBetween2,isBase64Url:()=>isBase64Url,isBase64:()=>isBase64,is:()=>is2,instanceOf:()=>instanceOf,fromURLSearchParams:()=>fromURLSearchParams2,fromJsonString:()=>fromJsonString2,fromFormData:()=>fromFormData2,fromBrand:()=>fromBrand,flip:()=>flip4,fieldsAssign:()=>fieldsAssign,extendTo:()=>extendTo,encodeUnknownSync:()=>encodeUnknownSync2,encodeUnknownResult:()=>encodeUnknownResult2,encodeUnknownPromise:()=>encodeUnknownPromise,encodeUnknownOption:()=>encodeUnknownOption2,encodeUnknownExit:()=>encodeUnknownExit2,encodeUnknownEffect:()=>encodeUnknownEffect2,encodeTo:()=>encodeTo,encodeSync:()=>encodeSync2,encodeResult:()=>encodeResult,encodePromise:()=>encodePromise,encodeOption:()=>encodeOption2,encodeKeys:()=>encodeKeys,encodeExit:()=>encodeExit,encodeEffect:()=>encodeEffect,encode:()=>encode,decodeUnknownSync:()=>decodeUnknownSync2,decodeUnknownResult:()=>decodeUnknownResult2,decodeUnknownPromise:()=>decodeUnknownPromise,decodeUnknownOption:()=>decodeUnknownOption2,decodeUnknownExit:()=>decodeUnknownExit2,decodeUnknownEffect:()=>decodeUnknownEffect2,decodeTo:()=>decodeTo2,decodeSync:()=>decodeSync2,decodeResult:()=>decodeResult,decodePromise:()=>decodePromise,decodeOption:()=>decodeOption2,decodeExit:()=>decodeExit,decodeEffect:()=>decodeEffect2,decode:()=>decode,declareConstructor:()=>declareConstructor,declare:()=>declare,check:()=>check2,catchEncodingWithContext:()=>catchEncodingWithContext,catchEncoding:()=>catchEncoding,catchDecodingWithContext:()=>catchDecodingWithContext,catchDecoding:()=>catchDecoding,brand:()=>brand2,asserts:()=>asserts2,asClass:()=>asClass,annotateKey:()=>annotateKey2,annotateEncoded:()=>annotateEncoded,annotate:()=>annotate2,Void:()=>Void2,UnknownFromJsonString:()=>UnknownFromJsonString,Unknown:()=>Unknown2,UniqueSymbol:()=>UniqueSymbol2,UniqueArray:()=>UniqueArray,Union:()=>Union2,UndefinedOr:()=>UndefinedOr,Undefined:()=>Undefined2,Uint8ArrayFromHex:()=>Uint8ArrayFromHex,Uint8ArrayFromBase64Url:()=>Uint8ArrayFromBase64Url,Uint8ArrayFromBase64:()=>Uint8ArrayFromBase64,Uint8Array:()=>Uint8Array2,URLSearchParams:()=>URLSearchParams2,URLFromString:()=>URLFromString,URL:()=>URL2,TupleWithRest:()=>TupleWithRest,Tuple:()=>Tuple2,Trimmed:()=>Trimmed,Trim:()=>Trim,Tree:()=>Tree,TimeZoneOffset:()=>TimeZoneOffset,TimeZoneNamedFromString:()=>TimeZoneNamedFromString,TimeZoneNamed:()=>TimeZoneNamed,TimeZoneFromString:()=>TimeZoneFromString,TimeZone:()=>TimeZone,TemplateLiteralParser:()=>TemplateLiteralParser,TemplateLiteral:()=>TemplateLiteral2,TaggedUnion:()=>TaggedUnion,TaggedStruct:()=>TaggedStruct,TaggedErrorClass:()=>TaggedErrorClass,TaggedClass:()=>TaggedClass2,Symbol:()=>Symbol3,StructWithRest:()=>StructWithRest,Struct:()=>Struct,StringFromUriComponent:()=>StringFromUriComponent,StringFromHex:()=>StringFromHex,StringFromBase64Url:()=>StringFromBase64Url,StringFromBase64:()=>StringFromBase64,String:()=>String5,StandardSchemaV1FailureResult:()=>StandardSchemaV1FailureResult,SchemaError:()=>SchemaError,Result:()=>Result,RegExp:()=>RegExp3,RedactedFromValue:()=>RedactedFromValue,Redacted:()=>Redacted,Record:()=>Record,ReadonlySet:()=>ReadonlySet,ReadonlyMap:()=>ReadonlyMap,PropertyKey:()=>PropertyKey,OptionFromUndefinedOr:()=>OptionFromUndefinedOr,OptionFromOptionalNullOr:()=>OptionFromOptionalNullOr,OptionFromOptionalKey:()=>OptionFromOptionalKey,OptionFromOptional:()=>OptionFromOptional,OptionFromNullishOr:()=>OptionFromNullishOr,OptionFromNullOr:()=>OptionFromNullOr,Option:()=>Option,Opaque:()=>Opaque,ObjectKeyword:()=>ObjectKeyword2,NumberFromString:()=>NumberFromString,Number:()=>Number6,NullishOr:()=>NullishOr,NullOr:()=>NullOr,Null:()=>Null2,NonEmptyString:()=>NonEmptyString,NonEmptyArray:()=>NonEmptyArray,Never:()=>Never2,MutableJson:()=>MutableJson2,Literals:()=>Literals,Literal:()=>Literal2,Json:()=>Json2,Int:()=>Int,HashSet:()=>HashSet,HashMap:()=>HashMap,FormData:()=>FormData2,FiniteFromString:()=>FiniteFromString,Finite:()=>Finite,File:()=>File,Exit:()=>Exit,ErrorClass:()=>ErrorClass,Error:()=>Error4,Enum:()=>Enum2,DurationFromString:()=>DurationFromString,DurationFromNanos:()=>DurationFromNanos,DurationFromMillis:()=>DurationFromMillis,Duration:()=>Duration,Defect:()=>Defect,DateValid:()=>DateValid,DateTimeZonedFromString:()=>DateTimeZonedFromString,DateTimeZoned:()=>DateTimeZoned,DateTimeUtcFromString:()=>DateTimeUtcFromString,DateTimeUtcFromMillis:()=>DateTimeUtcFromMillis,DateTimeUtcFromDate:()=>DateTimeUtcFromDate,DateTimeUtc:()=>DateTimeUtc,DateFromString:()=>DateFromString,DateFromMillis:()=>DateFromMillis,Date:()=>Date4,Class:()=>Class4,Chunk:()=>Chunk,Char:()=>Char,CauseReason:()=>CauseReason,Cause:()=>Cause,BooleanFromBit:()=>BooleanFromBit,Boolean:()=>Boolean4,BigIntFromString:()=>BigIntFromString,BigInt:()=>BigInt5,BigDecimalFromString:()=>BigDecimalFromString,BigDecimal:()=>BigDecimal,ArrayEnsure:()=>ArrayEnsure,Array:()=>ArraySchema,Any:()=>Any2});var HashMapTypeId="~effect/collections/HashMap";var SHIFT=5;var BUCKET_SIZE=1<<SHIFT;var MIN_ARRAY_NODE=BUCKET_SIZE/4;var MAX_INDEX_NODE=BUCKET_SIZE/2;var BITMAP_INDEX_MASK=BUCKET_SIZE-1;var popcount=(n)=>{n=n-(n>>>1&1431655765);n=(n&858993459)+(n>>>2&858993459);return(n+(n>>>4)&252645135)*16843009>>>24};var mask=(hash2,shift)=>hash2>>>shift&BITMAP_INDEX_MASK;var bitpos=(hash2,shift)=>1<<mask(hash2,shift);var index=(bitmap,bit)=>popcount(bitmap&bit-1);function mergeLeaves(edit,shift,hash1,node1,hash2,node2){if(shift>32){throw new Error("HashMap: max depth exceeded")}const bit1=bitpos(hash1,shift);const bit2=bitpos(hash2,shift);if(bit1===bit2){const child=mergeLeaves(edit,shift+SHIFT,hash1,node1,hash2,node2);return new IndexedNode(edit,bit1,[child])}const bitmap=bit1|bit2;const children=bit1>>>0<bit2>>>0?[node1,node2]:[node2,node1];return new IndexedNode(edit,bitmap,children)}class Node{canEdit(edit){return this.edit===edit}}class EmptyNode extends Node{_tag="EmptyNode";edit=0;get size(){return 0}get(_shift,_hash,_key){return none2()}has(_shift,_hash,_key){return false}set(edit,_shift,hash2,key,value3,added){added.value=true;return new LeafNode(edit,hash2,key,value3)}remove(_edit,_shift,_hash,_key,_removed){return this}iterator(){return[][Symbol.iterator]()}[Symbol.iterator](){return this.iterator()}canEdit(_edit){return false}}class LeafNode extends Node{_tag="LeafNode";edit;hash;key;value;constructor(edit,hash2,key,value3){super();this.edit=edit;this.hash=hash2;this.key=key;this.value=value3}get size(){return 1}get(_shift,hash2,key){if(this.hash===hash2&&equals(this.key,key)){return some2(this.value)}return none2()}has(_shift,hash2,key){return this.hash===hash2&&equals(this.key,key)}set(edit,shift,hash2,key,value3,added){if(this.hash===hash2&&equals(this.key,key)){if(equals(this.value,value3)){return this}if(this.canEdit(edit)){this.value=value3;return this}return new LeafNode(edit,hash2,key,value3)}added.value=true;if(this.hash===hash2){return new CollisionNode(edit,hash2,[[this.key,this.value],[key,value3]])}const newBit=bitpos(hash2,shift);const existingBit=bitpos(this.hash,shift);if(newBit===existingBit){return new IndexedNode(edit,newBit,[this.set(edit,shift+SHIFT,hash2,key,value3,added)])}const bitmap=newBit|existingBit;const nodes=newBit>>>0<existingBit>>>0?[new LeafNode(edit,hash2,key,value3),this]:[this,new LeafNode(edit,hash2,key,value3)];return new IndexedNode(edit,bitmap,nodes)}remove(_edit,_shift,hash2,key,removed){if(this.hash===hash2&&equals(this.key,key)){removed.value=true;return}return this}iterator(){return[[this.key,this.value]][Symbol.iterator]()}[Symbol.iterator](){return this.iterator()}}class CollisionNode extends Node{_tag="CollisionNode";edit;hash;entries;constructor(edit,hash2,entries){super();this.edit=edit;this.hash=hash2;this.entries=entries}get size(){return this.entries.length}get(_shift,hash2,key){if(this.hash!==hash2){return none2()}for(const[k,v]of this.entries){if(equals(k,key)){return some2(v)}}return none2()}has(_shift,hash2,key){if(this.hash!==hash2){return false}for(const[k]of this.entries){if(equals(k,key)){return true}}return false}set(edit,shift,hash2,key,value3,added){if(this.hash!==hash2){added.value=true;return mergeLeaves(edit,shift,this.hash,this,hash2,new LeafNode(edit,hash2,key,value3))}for(let i=0;i<this.entries.length;i++){if(equals(this.entries[i][0],key)){if(equals(this.entries[i][1],value3)){return this}if(this.canEdit(edit)){this.entries[i]=[key,value3];return this}const newEntries=[...this.entries];newEntries[i]=[key,value3];return new CollisionNode(edit,this.hash,newEntries)}}added.value=true;if(this.canEdit(edit)){this.entries.push([key,value3]);return this}return new CollisionNode(edit,this.hash,[...this.entries,[key,value3]])}remove(edit,_shift,hash2,key,removed){if(this.hash!==hash2){return this}const idx=this.entries.findIndex(([k])=>equals(k,key));if(idx===-1){return this}removed.value=true;if(this.entries.length===1){return}if(this.entries.length===2){const remaining=this.entries[idx===0?1:0];return new LeafNode(edit,this.hash,remaining[0],remaining[1])}if(this.canEdit(edit)){this.entries.splice(idx,1);return this}const newEntries=[...this.entries];newEntries.splice(idx,1);return new CollisionNode(edit,this.hash,newEntries)}iterator(){return this.entries[Symbol.iterator]()}[Symbol.iterator](){return this.iterator()}}class IndexedNode extends Node{_tag="IndexedNode";edit;_size;bitmap;children;constructor(edit,bitmap,children){super();this.edit=edit;this.bitmap=bitmap;this.children=children}get size(){if(this._size===undefined){this._size=this.children.reduce((acc,child)=>acc+child.size,0)}return this._size}get(shift,hash2,key){const bit=bitpos(hash2,shift);if((this.bitmap&bit)===0){return none2()}const idx=index(this.bitmap,bit);return this.children[idx].get(shift+SHIFT,hash2,key)}has(shift,hash2,key){const bit=bitpos(hash2,shift);if((this.bitmap&bit)===0){return false}const idx=index(this.bitmap,bit);return this.children[idx].has(shift+SHIFT,hash2,key)}set(edit,shift,hash2,key,value3,added){const bit=bitpos(hash2,shift);const idx=index(this.bitmap,bit);if((this.bitmap&bit)!==0){const child=this.children[idx];const newChild=child.set(edit,shift+SHIFT,hash2,key,value3,added);if(child===newChild){return this}if(this.canEdit(edit)){this.children[idx]=newChild;return this}const newChildren=[...this.children];newChildren[idx]=newChild;return new IndexedNode(edit,this.bitmap,newChildren)}else{added.value=true;const newChild=new LeafNode(edit,hash2,key,value3);const newBitmap=this.bitmap|bit;if(this.canEdit(edit)){this.children.splice(idx,0,newChild);this.bitmap=newBitmap;this._size=undefined;if(this.children.length>MAX_INDEX_NODE){return this.expand(edit,newBitmap,this.children)}return this}const newChildren=[...this.children];newChildren.splice(idx,0,newChild);if(newChildren.length>MAX_INDEX_NODE){return this.expand(edit,newBitmap,newChildren)}return new IndexedNode(edit,newBitmap,newChildren)}}remove(edit,shift,hash2,key,removed){const bit=bitpos(hash2,shift);if((this.bitmap&bit)===0){return this}const idx=index(this.bitmap,bit);const child=this.children[idx];const newChild=child.remove(edit,shift+SHIFT,hash2,key,removed);if(!removed.value){return this}if(newChild===undefined){const newBitmap=this.bitmap^bit;if(newBitmap===0){return}if(this.children.length===2){const remaining=this.children[idx===0?1:0];if(remaining._tag==="LeafNode"){return remaining}}if(this.canEdit(edit)){this.children.splice(idx,1);this.bitmap=newBitmap;this._size=undefined;return this}const newChildren2=[...this.children];newChildren2.splice(idx,1);return new IndexedNode(edit,newBitmap,newChildren2)}if(child===newChild){return this}if(this.canEdit(edit)){this.children[idx]=newChild;return this}const newChildren=[...this.children];newChildren[idx]=newChild;return new IndexedNode(edit,this.bitmap,newChildren)}expand(edit,bitmap,children){const nodes=new globalThis.Array(BUCKET_SIZE);let j=0;for(let i=0;i<BUCKET_SIZE;i++){if((bitmap&1<<i)!==0){nodes[i]=children[j++]}}return new ArrayNode(edit,children.length,nodes)}iterator(){let childIndex=0;let currentIterator;return{next:()=>{while(childIndex<this.children.length){if(!currentIterator){currentIterator=this.children[childIndex].iterator()}const result3=currentIterator.next();if(!result3.done){return result3}currentIterator=undefined;childIndex++}return{done:true,value:undefined}}}}[Symbol.iterator](){return this.iterator()}}class ArrayNode extends Node{_tag="ArrayNode";edit;_size;count;children;constructor(edit,count,children){super();this.edit=edit;this.count=count;this.children=children}get size(){if(this._size===undefined){this._size=this.children.reduce((acc,child)=>acc+(child?.size??0),0)}return this._size}get(shift,hash2,key){const idx=mask(hash2,shift);const child=this.children[idx];return child?child.get(shift+SHIFT,hash2,key):none2()}has(shift,hash2,key){const idx=mask(hash2,shift);const child=this.children[idx];return child?child.has(shift+SHIFT,hash2,key):false}set(edit,shift,hash2,key,value3,added){const idx=mask(hash2,shift);const child=this.children[idx];if(child){const newChild=child.set(edit,shift+SHIFT,hash2,key,value3,added);if(child===newChild){return this}if(this.canEdit(edit)){this.children[idx]=newChild;return this}const newChildren=[...this.children];newChildren[idx]=newChild;return new ArrayNode(edit,this.count,newChildren)}else{added.value=true;const newChild=new LeafNode(edit,hash2,key,value3);if(this.canEdit(edit)){this.children[idx]=newChild;this.count++;this._size=undefined;return this}const newChildren=[...this.children];newChildren[idx]=newChild;return new ArrayNode(edit,this.count+1,newChildren)}}remove(edit,shift,hash2,key,removed){const idx=mask(hash2,shift);const child=this.children[idx];if(!child){return this}const newChild=child.remove(edit,shift+SHIFT,hash2,key,removed);if(!removed.value){return this}const newCount=this.count-(newChild?0:1);if(newCount<MIN_ARRAY_NODE){return this.pack(edit,idx,newChild)}if(child===newChild){return this}if(this.canEdit(edit)){this.children[idx]=newChild;if(!newChild){this.count=newCount}this._size=undefined;return this}const newChildren=[...this.children];newChildren[idx]=newChild;return new ArrayNode(edit,newCount,newChildren)}pack(edit,excludeIdx,newChild){const children=[];let bitmap=0;let bit=1;for(let i=0;i<this.children.length;i++){const child=i===excludeIdx?newChild:this.children[i];if(child){children.push(child);bitmap|=bit}bit<<=1}return new IndexedNode(edit,bitmap,children)}iterator(){let childIndex=0;let currentIterator;return{next:()=>{while(childIndex<this.children.length){const child=this.children[childIndex];if(!child){childIndex++;continue}if(!currentIterator){currentIterator=child.iterator()}const result3=currentIterator.next();if(!result3.done){return result3}currentIterator=undefined;childIndex++}return{done:true,value:undefined}}}}[Symbol.iterator](){return this.iterator()}}class HashMapImpl{[HashMapTypeId]=HashMapTypeId;_editable;_edit;_root;_size;constructor(editable,edit,root,size2){this._editable=editable;this._edit=edit;this._root=root;this._size=size2}get size(){return this._size}[Symbol.iterator](){return this._root.iterator()}[symbol2](that){if(isHashMap(that)){const thatImpl=that;if(this.size!==thatImpl.size){return false}for(const[key,value3]of this){const otherValue=pipe(that,get4(key));if(isNone2(otherValue)||!equals(value3,otherValue.value)){return false}}return true}return false}[symbol](){let hash2=string("HashMap");for(const[key,value3]of this){hash2=hash2^hash(key)+hash(value3)}return hash2}[NodeInspectSymbol](){return toJson(this)}toString(){return`HashMap(${format(Array.from(this))})`}toJSON(){return{_id:"HashMap",values:Array.from(this).map(([k,v])=>[toJson(k),toJson(v)])}}pipe(){return pipeArguments(this,arguments)}}var emptyNode=new EmptyNode;var isHashMap=(u)=>hasProperty(u,HashMapTypeId);var empty8=()=>new HashMapImpl(false,0,emptyNode,0);var fromIterable3=(entries)=>{let root=emptyNode;let size2=0;const added={value:false};for(const[key,value3]of entries){const hash2=hash(key);added.value=false;root=root.set(NaN,0,hash2,key,value3,added);if(added.value){size2++}}return new HashMapImpl(false,0,root,size2)};var get4=dual(2,(self,key)=>{const impl=self;return impl._root.get(0,hash(key),key)});var has2=dual(2,(self,key)=>{const impl=self;return impl._root.has(0,hash(key),key)});var set2=dual(3,(self,key,value3)=>{const impl=self;const hash2=hash(key);const added={value:false};const edit=impl._editable?impl._edit:NaN;const newRoot=impl._root.set(edit,0,hash2,key,value3,added);if(impl._editable){impl._root=newRoot;if(added.value){impl._size++}return self}if(impl._root===newRoot){return self}return new HashMapImpl(false,impl._edit,newRoot,impl._size+(added.value?1:0))});var keys2=(self)=>{const iterator=self[Symbol.iterator]();return{[Symbol.iterator](){return this},next(){const result3=iterator.next();if(result3.done){return{done:true,value:undefined}}return{done:false,value:result3.value[0]}}}};var entries=(self)=>{const iterator=self[Symbol.iterator]();return{[Symbol.iterator](){return this},next(){return iterator.next()}}};var size2=(self)=>self.size;var isHashMap2=isHashMap;var fromIterable4=fromIterable3;var entries2=entries;var toEntries=(self)=>Array.from(entries2(self));var size3=size2;var HashSetTypeId="~effect/collections/HashSet";var HashSetProto={[symbol](){return hash(HashSetTypeId)},[symbol2](that){return isHashSet(that)&&size4(this)===size4(that)&&every2(this,(value3)=>has3(that,value3))},[Symbol.iterator](){return keys2(keyMap(this))},toString(){return`HashSet(${format(Array.from(this))})`},toJSON(){return{_id:"HashSet",values:toJson(Array.from(this))}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}};var makeImpl=(keyMap)=>{const set3=Object.create(HashSetProto);set3[HashSetTypeId]=HashSetTypeId;set3.keyMap=keyMap;return set3};var isHashSet=(u)=>hasProperty(u,HashSetTypeId);var keyMap=(self)=>self.keyMap;var fromIterable5=(values3)=>{let map11=empty8();for(const value3 of values3){map11=set2(map11,value3,true)}return makeImpl(map11)};var has3=(self,value3)=>has2(keyMap(self),value3);var size4=(self)=>size2(keyMap(self));var every2=(self,predicate)=>{for(const value3 of self){if(!predicate(value3)){return false}}return true};var fromIterable6=fromIterable5;var isHashSet2=isHashSet;var size5=size4;var Boolean3=globalThis.Boolean;var ReducerOr=make2((a,b)=>a||b,false);var pick=dual(2,(self,keys3)=>{return buildStruct(self,(k,v)=>keys3.includes(k)?[k,v]:undefined)});var omit2=dual(2,(self,keys3)=>{return buildStruct(self,(k,v)=>!keys3.includes(k)?[k,v]:undefined)});var assign=dual(2,(self,that)=>{return{...self,...that}});var renameKeys=dual(2,(self,mapping)=>{return buildStruct(self,(k,v)=>[Object.hasOwn(mapping,k)?mapping[k]:k,v])});var lambda=(f)=>f;function buildStruct(source,f){const out={};for(const k of Reflect.ownKeys(source)){if(!Object.prototype.propertyIsEnumerable.call(source,k))continue;const res=f(k,source[k]);if(res){const[nk,nv]=res;out[nk]=nv}}return out}function makeCombiner(combiners,options){const omitKeyWhen=options?.omitKeyWhen??(()=>false);return make((self,that)=>{const keys3=Reflect.ownKeys(combiners);const out={};for(const key of keys3){const merge5=combiners[key].combine(self[key],that[key]);if(omitKeyWhen(merge5))continue;out[key]=merge5}return out})}var map12=dual(2,(self,f)=>self===undefined?undefined:f(self));function makeReducer(combiner){return make2((self,that)=>{if(self===undefined)return that;if(that===undefined)return self;return combiner.combine(self,that)},undefined)}function errorWithPath(message,path){if(path.length>0){message+=`
|
|
189
|
-
at ${formatPath(path)}`}return new Error(message)}var arbitraryMemoMap=new WeakMap;var suspendDepthIdentifierMap=new WeakMap;var emptyRecursionStack=[];function makeReport(){return{warnings:[]}}function toReport(report){return{warnings:report.warnings.slice()}}function arbitraryError(what){return new Error(`Unable to derive an arbitrary for ${what}`)}var entryComparator=([a],[b])=>equals(a,b);function applyChecks(ast,filters,arbitrary){return filters.reduce((acc,filter10)=>acc.filter((a)=>filter10.run(a,ast,defaultParseOptions)===undefined),arbitrary)}function validateArrayConstraints(constraint,label){if(constraint?.minLength!==undefined&&constraint.maxLength!==undefined&&constraint.minLength>constraint.maxLength){throw arbitraryError(`${label} constraints`)}}function lengthToFastCheckConstraints(constraint){return constraint===undefined||constraint.minLength===undefined&&constraint.maxLength===undefined?undefined:{...constraint.minLength!==undefined?{minLength:constraint.minLength}:{},...constraint.maxLength!==undefined?{maxLength:constraint.maxLength}:{}}}function arrayWithConstraints(fc,item,constraint,comparator){return comparator?fc.uniqueArray(item,{...constraint,comparator}):fc.array(item,constraint)}function array2(fc,ctx,item,terminal=false){const constraint=ctx.constraint;const arrayConstraints=lengthToFastCheckConstraints(constraint);validateArrayConstraints(arrayConstraints,"array");return arrayWithConstraints(fc,item,terminal?{...arrayConstraints,maxLength:arrayConstraints?.minLength??0}:arrayConstraints,constraint?.unique?equals:undefined)}function appendArray(fc,out,len,rest){return out.chain((as3)=>as3.length<len?fc.constant(as3):rest.map((rest2)=>[...as3,...rest2]))}function appendObjectEntries(out,entries3){return out.chain((o)=>entries3.map((entries4)=>({...Object.fromEntries(entries4),...o})))}var max4=makeReducer(ReducerMax);var min4=makeReducer(ReducerMin);var or2=makeReducer(ReducerOr);var concat=makeReducer(makeReducerConcat());var combiner=makeCombiner({integer:or2,maxLength:min4,minLength:max4,noInfinity:or2,noNaN:or2,patterns:concat,unique:or2,valid:or2},{omitKeyWhen:isUndefined});function mergeOrderedBound(order,self,selfExclusive,that,thatExclusive,takeComparison){if(that===undefined||self===undefined){return that===undefined?[self,selfExclusive]:[that,thatExclusive]}const comparison=order(self,that);return comparison===takeComparison?[that,thatExclusive]:comparison===0?[self,selfExclusive||thatExclusive]:[self,selfExclusive]}function mergeOrderedConstraints(self,that){if(self===undefined){return that}if(self.order!==that.order){throw new Error("Cannot merge ordered arbitrary constraints with different Order instances")}const[minimum,exclusiveMinimum]=mergeOrderedBound(self.order,self.minimum,self.exclusiveMinimum,that.minimum,that.exclusiveMinimum,-1);const[maximum,exclusiveMaximum]=mergeOrderedBound(self.order,self.maximum,self.exclusiveMaximum,that.maximum,that.exclusiveMaximum,1);return{order:self.order,...minimum!==undefined?{minimum}:{},...exclusiveMinimum!==undefined?{exclusiveMinimum}:{},...maximum!==undefined?{maximum}:{},...exclusiveMaximum!==undefined?{exclusiveMaximum}:{}}}function mergeConstraint(self,that){const{ordered:selfOrdered,...selfRest}=self??{};const{ordered:thatOrdered,...thatRest}=that;const ordered=thatOrdered===undefined?selfOrdered:mergeOrderedConstraints(selfOrdered,thatOrdered);const out=combiner.combine(selfRest,thatRest);return{...out,...ordered===undefined?{}:{ordered}}}function collectChecks(checks){const filters=[];const arbitraries=[];function visit(check){if(check.annotations?.arbitrary){arbitraries.push(check.annotations.arbitrary)}if(check._tag!=="Filter"){for(const child of check.checks){visit(child)}}else{filters.push(check)}}checks?.forEach(visit);return{filters,arbitraries}}function constraintContext(arbitraries){const constraintAnnotations=arbitraries.map(({constraint})=>constraint).filter(isNotUndefined);return(ctx)=>{const constraint=constraintAnnotations.reduce((acc,c)=>mergeConstraint(acc,c),ctx.constraint);return{...ctx,constraint}}}function resetContext(ctx){return{...ctx,constraint:undefined}}function objectEntriesConstraints(ast,constraint,requiredKeys){if(constraint===undefined||constraint.minLength===undefined&&constraint.maxLength===undefined){return}if(constraint.minLength!==undefined&&ast.indexSignatures.length===0&&constraint.minLength>ast.propertySignatures.length){throw arbitraryError("object property constraints")}const out={};if(constraint.minLength!==undefined){out.minLength=Math.max(0,constraint.minLength-requiredKeys)}if(constraint.maxLength!==undefined){out.maxLength=constraint.maxLength-requiredKeys;if(out.maxLength<0){throw arbitraryError("object property constraints")}}validateArrayConstraints(out,"object property");return out}function objectWithOptionalCount(fc,pss,orderedNames,requiredKeys,optionalNames,constraint){const requiredCount=requiredKeys.length;if(constraint.maxLength!==undefined&&constraint.maxLength<requiredCount){throw arbitraryError("object property constraints")}const minOptional=constraint.minLength===undefined?0:Math.max(0,constraint.minLength-requiredCount);const maxOptional=constraint.maxLength===undefined?optionalNames.length:Math.min(optionalNames.length,constraint.maxLength-requiredCount);if(minOptional>maxOptional){throw arbitraryError("object property constraints")}const full=fc.record(pss,{requiredKeys:[...requiredKeys,...optionalNames]});const chosen=fc.shuffledSubarray([...optionalNames],{minLength:minOptional,maxLength:maxOptional});return fc.tuple(full,chosen).map(([base,names])=>{const keep=new Set([...requiredKeys,...names]);const out={};for(const name of orderedNames){if(keep.has(name)){out[name]=base[name]}}return out})}function toRangeConstraints(ordered,min5,max5,error){const out={};if(ordered?.minimum!==undefined){out.min=min5(ordered.minimum,ordered.exclusiveMinimum===true)}if(ordered?.maximum!==undefined){out.max=max5(ordered.maximum,ordered.exclusiveMaximum===true)}if(out.min!==undefined&&out.max!==undefined&&out.min>out.max){throw arbitraryError(error)}return out}function toIntegerConstraints(ordered){return toRangeConstraints(ordered,(minimum,excluded)=>excluded?Math.floor(minimum)+1:Math.ceil(minimum),(maximum,excluded)=>excluded?Math.ceil(maximum)-1:Math.floor(maximum),"integer constraints")}function toFloatConstraints(constraint,ordered){const out={...constraint?.noInfinity?{noDefaultInfinity:true}:{},...constraint?.noNaN?{noNaN:true}:{},...ordered?.minimum!==undefined?{min:ordered.minimum}:{},...ordered?.exclusiveMinimum!==undefined?{minExcluded:ordered.exclusiveMinimum}:{},...ordered?.maximum!==undefined?{max:ordered.maximum}:{},...ordered?.exclusiveMaximum!==undefined?{maxExcluded:ordered.exclusiveMaximum}:{}};if(out.min!==undefined&&out.max!==undefined&&(out.min>out.max||out.min===out.max&&(out.minExcluded||out.maxExcluded))){throw arbitraryError("number constraints")}return out}function toBigIntConstraints(ordered){return toRangeConstraints(ordered,(minimum,excluded)=>excluded?minimum+BigInt(1):minimum,(maximum,excluded)=>excluded?maximum-BigInt(1):maximum,"the ordered bigint constraints")}function makeLazy(normal,terminal){const out=(fc,ctx,recursionStack=emptyRecursionStack)=>normal(fc,ctx,recursionStack);out.terminal=(fc,ctx,recursionStack=emptyRecursionStack)=>terminal(fc,ctx,recursionStack);return out}function same(f){return makeLazy(f,f)}function getSuspendRecursion(fc,ast){const depthIdentifier=suspendDepthIdentifierMap.get(ast)??fc.createDepthIdentifier();suspendDepthIdentifierMap.set(ast,depthIdentifier);return{maxDepth:2,depthIdentifier}}function oneOf(fc,arbitraries){return arbitraries.length===0?undefined:arbitraries.length===1?arbitraries[0]:fc.oneof(...arbitraries)}var finiteNumberConstraint={noInfinity:true,noNaN:true};function finiteNumberContext(ctx){return{...ctx,constraint:finiteNumberConstraint}}function reportChecks(report,checks,path){function visit(check,covered){const arbitrary=check.annotations?.arbitrary;const nextCovered=covered||arbitrary?.constraint!==undefined||arbitrary?.candidate!==undefined;if(check._tag!=="Filter"){for(const child of check.checks){visit(child,nextCovered)}}else if(!nextCovered){const meta=check.annotations?.meta;const description=typeof meta==="object"&&meta!==null&&"_tag"in meta&&typeof meta._tag==="string"?meta._tag:check.annotations?.identifier??check.annotations?.expected;report.warnings.push({_tag:"OpaqueFilter",path,...description===undefined?{}:{description}})}}checks?.forEach((check)=>visit(check,false))}function collectReport(ast,report){const stack=new WeakSet;function visit(ast2,path){if(stack.has(ast2)){return}stack.add(ast2);reportChecks(report,ast2.checks,path);switch(ast2._tag){case"Declaration":ast2.typeParameters.forEach((tp)=>visit(tp,path));break;case"Arrays":{for(const[i,type]of[...ast2.elements,...ast2.rest].entries()){visit(type,[...path,i])}break}case"Objects":ast2.propertySignatures.forEach((ps)=>visit(ps.type,[...path,ps.name]));ast2.indexSignatures.forEach((is)=>{visit(is.parameter,path);visit(is.type,path)});break;case"Union":ast2.types.forEach((type)=>visit(type,path));break;case"TemplateLiteral":ast2.parts.forEach((part,i)=>visit(toEncoded(part),[...path,i]));break;case"Suspend":visit(ast2.thunk(),path);break}stack.delete(ast2)}visit(ast,[])}function applyCandidates(fc,ctx,arbitraries,base){const weighted=base===undefined?[]:[{arbitrary:base,weight:1}];for(const{candidate}of arbitraries){if(!candidate){continue}const arbitrary=candidate.make(fc,ctx);if(arbitrary===undefined){continue}const weight=candidate.weight??1;if(!globalThis.Number.isInteger(weight)||weight<=0){throw arbitraryError("a candidate with an invalid weight")}weighted.push({arbitrary,weight})}return weighted.length===0?undefined:weighted.length===1?weighted[0].arbitrary:fc.oneof(...weighted)}function applyFilterLayer(ast,checks,fc,ctx,base){const out=applyCandidates(fc,ctx,checks.arbitraries,base);return out===undefined?undefined:applyChecks(ast,checks.filters,out)}function normalizeDerivation(output,hasTypeParameters){if(!(typeof output==="object"&&output!==null&&("arbitrary"in output))){return{arbitrary:output,terminal:hasTypeParameters?undefined:output}}const terminal="terminal"in output?output.terminal:hasTypeParameters?undefined:output.arbitrary;return{arbitrary:output.arbitrary,terminal}}function makeTypeParameters(typeParameters,fc,ctx,recursionStack,lazyNormal){return typeParameters.map((tp)=>({arbitrary:lazyNormal?fc.constant(null).chain(()=>tp(fc,ctx,recursionStack)):tp(fc,ctx,recursionStack),terminal:tp.terminal(fc,ctx,recursionStack)}))}function filterLayer(ast,checks,normalBase,terminalBase){const f=constraintContext(checks.arbitraries);return makeLazy((fc,ctx,recursionStack)=>{const nextCtx=f(ctx);return applyFilterLayer(ast,checks,fc,nextCtx,normalBase(fc,ctx,nextCtx,recursionStack))},(fc,ctx,recursionStack)=>{const nextCtx=f(ctx);return applyFilterLayer(ast,checks,fc,nextCtx,terminalBase(fc,ctx,nextCtx,recursionStack))})}var memoized=memoize((ast)=>recur(ast,[]));function recur(ast,path){const annotation=resolve(ast)?.toArbitrary;if(annotation){const typeParameters=isDeclaration(ast)?ast.typeParameters.map((tp)=>recur(tp,path)):[];const checks=collectChecks(ast.checks);const derive=(lazyNormal)=>(fc,ctx,nextCtx,recursionStack)=>normalizeDerivation(annotation(makeTypeParameters(typeParameters,fc,resetContext(ctx),recursionStack,lazyNormal))(fc,nextCtx),typeParameters.length>0)[lazyNormal?"terminal":"arbitrary"];return filterLayer(ast,checks,derive(false),derive(true))}if(ast.checks){const checks=collectChecks(ast.checks);const lawc=recur(replaceChecks(ast,undefined),path);return filterLayer(ast,checks,(fc,_ctx,nextCtx,recursionStack)=>lawc(fc,nextCtx,recursionStack),(fc,_ctx,nextCtx,recursionStack)=>lawc.terminal(fc,nextCtx,recursionStack))}return base(ast,path)}function base(ast,path){switch(ast._tag){case"Never":case"Declaration":throw errorWithPath(`Unsupported AST ${ast._tag}`,path);case"Null":return same((fc)=>fc.constant(null));case"Void":case"Undefined":return same((fc)=>fc.constant(undefined));case"Unknown":case"Any":return same((fc)=>fc.anything());case"String":return same((fc,ctx)=>{const constraint=ctx.constraint;const patterns=constraint?.patterns;return patterns?fc.oneof(...patterns.map((pattern)=>fc.stringMatching(new RegExp(pattern)))):fc.string(lengthToFastCheckConstraints(constraint))});case"Number":return same((fc,ctx)=>{const constraint=ctx.constraint;const ordered=constraint?.ordered?.order===Number2?constraint.ordered:undefined;return constraint?.integer?fc.integer(toIntegerConstraints(ordered)):fc.float(toFloatConstraints(constraint,ordered))});case"Boolean":return same((fc)=>fc.boolean());case"BigInt":return same((fc,ctx)=>{const ordered=ctx.constraint?.ordered?.order===BigInt2?ctx.constraint.ordered:undefined;return fc.bigInt(toBigIntConstraints(ordered))});case"Symbol":return same((fc)=>fc.string().map(Symbol.for));case"Literal":return same((fc)=>fc.constant(ast.literal));case"UniqueSymbol":return same((fc)=>fc.constant(ast.symbol));case"ObjectKeyword":return same((fc)=>fc.oneof(fc.object(),fc.array(fc.anything())));case"Enum":return recur(enumsToLiterals(ast),path);case"TemplateLiteral":{const parts=ast.parts.map((part,i)=>recur(toEncoded(part),[...path,i]));return same((fc,ctx,recursionStack)=>fc.tuple(...parts.map((part)=>part(fc,finiteNumberContext(ctx),recursionStack))).map((segments)=>segments.map((segment)=>globalThis.String(segment)).join("")))}case"Arrays":{const elements=ast.elements.map((ast2,i)=>({ast:ast2,arbitrary:recur(ast2,[...path,i])}));const len=ast.elements.length;const rest=ast.rest.map((ast2,i)=>({ast:ast2,arbitrary:recur(ast2,[...path,len+i])}));const terminal=(fc,ctx,recursionStack)=>{const reset=resetContext(ctx);const elementArbitraries=[];const optionals=[];let length=0;for(const element of elements){const out2=element.arbitrary.terminal(fc,reset,recursionStack);if(isOptional(element.ast)){optionals.push(out2);continue}if(out2===undefined){return}length++;elementArbitraries.push(out2.map(some2))}const minLength=ctx.constraint?.minLength??0;const needsRest=isReadonlyArrayNonEmpty(rest)&&minLength>length+optionals.length;const optionalTarget=needsRest?optionals.length:Math.max(0,minLength-length);let includedOptionals=0;for(const out2 of optionals){if(includedOptionals>=optionalTarget||out2===undefined){elementArbitraries.push(fc.constant(none2()));continue}includedOptionals++;length++;elementArbitraries.push(out2.map(some2))}if(includedOptionals<optionalTarget){return}let out=fc.tuple(...elementArbitraries).map(getSomes);if(isReadonlyArrayNonEmpty(rest)){const[head,...tail]=rest;const restCtx=ast.elements.length===0?ctx:reset;const minRestLength=Math.max(0,minLength-length-tail.length);const headArbitrary=minRestLength===0?undefined:head.arbitrary.terminal(fc,reset,recursionStack);if(minRestLength>0&&headArbitrary===undefined){return}const restArbitrary=minRestLength===0?fc.constant([]):array2(fc,{...restCtx,constraint:{...restCtx.constraint,minLength:minRestLength}},headArbitrary,true);out=appendArray(fc,out,len,restArbitrary);if(tail.length>0){const tailArbitraries=[];for(const element of tail){const out2=element.arbitrary.terminal(fc,reset,recursionStack);if(out2===undefined){return}tailArbitraries.push(out2)}const t=fc.tuple(...tailArbitraries);out=appendArray(fc,out,len,t)}}return out};return makeLazy((fc,ctx,recursionStack)=>{const reset=resetContext(ctx);const elementArbitraries=elements.map(({ast:ast2,arbitrary})=>{const out2=arbitrary(fc,reset,recursionStack);return isOptional(ast2)?out2.chain((a)=>fc.boolean().map((b)=>b?some2(a):none2())):out2.map(some2)});let out=fc.tuple(...elementArbitraries).map(getSomes);if(isReadonlyArrayNonEmpty(rest)){const[head,...tail]=rest.map(({arbitrary})=>arbitrary(fc,reset,recursionStack));const restArbitrary=array2(fc,ast.elements.length===0?ctx:reset,head);out=appendArray(fc,out,len,restArbitrary);if(tail.length>0){const t=fc.tuple(...tail);out=appendArray(fc,out,len,t)}}if(ctx.recursion){const terminalOut=terminal(fc,ctx,recursionStack);if(terminalOut!==undefined){return fc.oneof(ctx.recursion,terminalOut,out)}}return out},terminal)}case"Objects":{const propertySignatures=ast.propertySignatures.map((ps)=>({ps,arbitrary:recur(ps.type,[...path,ps.name])}));const indexSignatures=ast.indexSignatures.map((is)=>({is,parameter:recur(is.parameter,path),type:recur(is.type,path)}));const terminal=(fc,ctx,recursionStack)=>{const reset=resetContext(ctx);const pss={};const requiredKeys=[];const optionals=[];for(const{ps,arbitrary}of propertySignatures){const name=ps.name;const out2=arbitrary.terminal(fc,reset,recursionStack);if(isOptional(ps.type)){if(out2!==undefined){optionals.push([name,out2])}continue}if(out2===undefined){return}requiredKeys.push(name);pss[name]=out2}let optionalCount=Math.max(0,(ctx.constraint?.minLength??0)-requiredKeys.length);for(const[name,out2]of optionals){if(optionalCount===0){break}optionalCount--;requiredKeys.push(name);pss[name]=out2}if(optionalCount>0&&ast.indexSignatures.length===0){return}let out=fc.record(pss,{requiredKeys});const entriesConstraints=objectEntriesConstraints(ast,ctx.constraint,requiredKeys.length);const minEntries=entriesConstraints?.minLength??0;for(const{parameter,type}of indexSignatures){let entries3;if(minEntries===0){entries3=fc.constant([])}else{const key=parameter.terminal(fc,reset,recursionStack);const value3=type.terminal(fc,reset,recursionStack);if(key===undefined||value3===undefined){return}entries3=arrayWithConstraints(fc,fc.tuple(key,value3),{...entriesConstraints,maxLength:minEntries},entryComparator)}out=appendObjectEntries(out,entries3)}return out};return makeLazy((fc,ctx,recursionStack)=>{const reset=resetContext(ctx);const pss={};const orderedNames=[];const requiredKeys=[];const optionalNames=[];for(const{ps,arbitrary}of propertySignatures){const name=ps.name;orderedNames.push(name);if(isOptional(ps.type)){optionalNames.push(name)}else{requiredKeys.push(name)}pss[name]=arbitrary(fc,reset,recursionStack)}const constraint=ctx.constraint;if(optionalNames.length>0&&indexSignatures.length===0&&constraint!==undefined&&(constraint.minLength!==undefined||constraint.maxLength!==undefined)){return objectWithOptionalCount(fc,pss,orderedNames,requiredKeys,optionalNames,constraint)}let out=fc.record(pss,{requiredKeys});const entriesConstraints=objectEntriesConstraints(ast,ctx.constraint,requiredKeys.length);for(const{parameter,type}of indexSignatures){const entry=fc.tuple(parameter(fc,reset,recursionStack),type(fc,reset,recursionStack));const entries3=arrayWithConstraints(fc,entry,entriesConstraints,entryComparator);out=appendObjectEntries(out,entries3)}return out},terminal)}case"Union":{const types=ast.types.map((ast2)=>recur(ast2,path));const terminal=(fc,ctx,recursionStack)=>oneOf(fc,types.map((type)=>type.terminal(fc,ctx,recursionStack)).filter(isNotUndefined));return makeLazy((fc,ctx,recursionStack)=>{const arbitraries=types.map((type)=>type(fc,ctx,recursionStack));if(ctx.recursion){const terminalOut=terminal(fc,ctx,recursionStack);if(terminalOut!==undefined){return fc.oneof(ctx.recursion,terminalOut,...arbitraries)}}const out=oneOf(fc,arbitraries);if(out===undefined){throw arbitraryError("a union with no members")}return out},terminal)}case"Suspend":{const memo=arbitraryMemoMap.get(ast);if(memo)return memo;const get5=memoizeThunk(()=>recur(ast.thunk(),path));const out=makeLazy((fc,ctx,recursionStack)=>{const recursion=getSuspendRecursion(fc,ast);const nextCtx={...ctx,recursion};const nextStack=recursionStack.includes(ast)?recursionStack:[...recursionStack,ast];const terminal=get5().terminal(fc,nextCtx,nextStack);if(terminal===undefined){throw errorWithPath("Unable to derive an arbitrary for a recursive schema without a finite generation path",path)}return fc.oneof(recursion,terminal,fc.constant(null).chain(()=>get5()(fc,nextCtx,nextStack)))},(fc,ctx,recursionStack)=>{if(recursionStack.includes(ast)){return}const recursion=getSuspendRecursion(fc,ast);return get5().terminal(fc,{...ctx,recursion},[...recursionStack,ast])});arbitraryMemoMap.set(ast,out);return out}}}var toConstructorAST=memoize((ast)=>{switch(ast._tag){case"Declaration":{const getLink=ast.annotations?.[ClassTypeId];if(isFunction(getLink)){const link=getLink(ast.typeParameters);const to=toConstructorAST(link.to);return replaceEncoding(ast,to===link.to?[link]:[new Link(to,link.transformation)])}return ast}case"Objects":case"Arrays":return ast.recur((ast2)=>{const defaultValue=ast2.context?.defaultValue;if(defaultValue){const out=toConstructorAST(ast2);return replaceEncoding(out,out.encoding?[...out.encoding,...defaultValue]:defaultValue)}return toConstructorAST(ast2)});case"Suspend":return ast.recur(toConstructorAST);default:return ast}});function makeEffect(schema){const ast=toConstructorAST(toType(schema.ast));const parser=run2(ast);return(input,options)=>{return parser(input,options?.disableChecks?options?.parseOptions?{...options.parseOptions,disableChecks:true}:{disableChecks:true}:options?.parseOptions)}}function makeOption(schema){const parser=makeEffect(schema);return(input,options)=>{const exit3=runSyncExit2(parser(input,options));if(isSuccess4(exit3)){return some2(exit3.value)}getSchemaIssueOrThrow(exit3.cause,"Option adapter can only return none for schema issues");return none2()}}function make23(schema){const parser=makeEffect(schema);return(input,options)=>{const exit3=runSyncExit2(parser(input,options));if(isSuccess4(exit3)){return exit3.value}const issue=getSchemaIssueOrThrow(exit3.cause,"Constructor adapter can only throw schema issues");throw new Error(issue.toString(),{cause:issue})}}function is(schema){return _is(schema.ast)}function _is(ast){const parser=asExit(run2(toType(ast)));return(input)=>{const exit3=parser(input,defaultParseOptions);if(isSuccess4(exit3)){return true}getSchemaIssueOrThrow(exit3.cause,"Type guard adapter can only return false for schema issues");return false}}function _issue(ast){const parser=run2(ast);return(input,options)=>{const exit3=runSyncExit2(parser(input,options));if(isSuccess4(exit3)){return}return getSchemaIssueOrThrow(exit3.cause,"Issue adapter can only return schema issues")}}function asserts(schema,input){const parser=asExit(run2(toType(schema.ast)));const exit3=parser(input,defaultParseOptions);if(isFailure4(exit3)){const issue=getSchemaIssueOrThrow(exit3.cause,"Assertion adapter can only throw schema issues");throw new Error(issue.toString(),{cause:issue})}}function decodeUnknownEffect(schema,options){const parser=run2(schema.ast);return options===undefined?parser:(input,overrideOptions)=>parser(input,mergeParseOptions(options,overrideOptions))}var decodeEffect=decodeUnknownEffect;function decodeUnknownExit(schema,options){return asExit(decodeUnknownEffect(schema,options))}function decodeUnknownOption(schema,options){return asOption(decodeUnknownEffect(schema,options))}var decodeOption=decodeUnknownOption;function decodeUnknownResult(schema,options){return asResult(decodeUnknownEffect(schema,options))}function decodeUnknownSync(schema,options){return asSync(decodeUnknownEffect(schema,options))}var decodeSync=decodeUnknownSync;function encodeUnknownEffect(schema,options){const parser=run2(flip3(schema.ast));return options===undefined?parser:(input,overrideOptions)=>parser(input,mergeParseOptions(options,overrideOptions))}function encodeUnknownExit(schema,options){return asExit(encodeUnknownEffect(schema,options))}function encodeUnknownOption(schema,options){return asOption(encodeUnknownEffect(schema,options))}var encodeOption=encodeUnknownOption;function encodeUnknownResult(schema,options){return asResult(encodeUnknownEffect(schema,options))}function encodeUnknownSync(schema,options){return asSync(encodeUnknownEffect(schema,options))}var encodeSync=encodeUnknownSync;var mergeParseOptions=(options,overrideOptions)=>overrideOptions===undefined?options:{...options,...overrideOptions};function run2(ast){const parser=recur2(ast);return(input,options)=>flatMapEager2(parser(some2(input),options??defaultParseOptions),(oa)=>{if(oa._tag==="None"){return fail6(new InvalidValue(oa))}return succeed6(oa.value)})}function asExit(parser){return(input,options)=>runSyncExit2(parser(input,options))}function asOption(parser){const parserExit=asExit(parser);return(input,options)=>{const exit3=parserExit(input,options);if(isSuccess4(exit3)){return some2(exit3.value)}getSchemaIssueOrThrow(exit3.cause,"Option adapter can only return none for schema issues");return none2()}}function asResult(parser){const parserExit=asExit(parser);return(input,options)=>{const exit3=parserExit(input,options);if(isSuccess4(exit3)){return succeed2(exit3.value)}return fail2(getSchemaIssueOrThrow(exit3.cause,"Result adapter can only return schema issues"))}}function asSync(parser){const parserExit=asExit(parser);return(input,options)=>{const exit3=parserExit(input,options);if(isSuccess4(exit3)){return exit3.value}const issue=getSchemaIssueOrThrow(exit3.cause,"Sync adapter can only throw schema issues");throw new Error(issue.toString(),{cause:issue})}}function mapSchemaIssueEffect(self,f){return catchCause2(self,(cause)=>failCauseSync2(()=>map6(cause,f)))}var recur2=memoize((ast)=>{let parser;const checks=ast.checks;const encoding=ast.encoding;const links=encoding;const len=links?.length??0;const encodingChecks=ast.encodingChecks;const astOptions=(checks?checks[checks.length-1].annotations:ast.annotations)?.["parseOptions"];if(!ast.context&&!encoding&&!checks&&!encodingChecks){return(ou,options)=>{parser??=ast.getParser(recur2);if(astOptions){options={...options,...astOptions}}return parser(ou,options)}}const isStructural=isArrays(ast)||isObjects(ast)||isDeclaration(ast)&&ast.typeParameters.length>0;const structuralChecks=checks&&isStructural?checks.filter((check)=>check.annotations?.[STRUCTURAL_ANNOTATION_KEY]):undefined;return(ou,options)=>{if(astOptions){options={...options,...astOptions}}let srou;if(links){for(let i=len-1;i>=0;i--){const link=links[i];const to=link.to;const parser2=recur2(to);srou=srou?flatMapEager2(srou,(ou2)=>parser2(ou2,options)):parser2(ou,options);if(link.transformation._tag==="Transformation"){const getter=link.transformation.decode;srou=flatMapEager2(srou,(ou2)=>getter.run(ou2,options))}else{srou=link.transformation.decode(srou,options)}}srou=mapSchemaIssueEffect(srou,(issue)=>new Encoding(ast,ou,issue))}parser??=ast.getParser(recur2);const parseLocal=(localOu)=>{let sroa2=parser(localOu,options);if(encodingChecks&&!options?.disableChecks){sroa2=flatMapEager2(sroa2,(oa)=>{if(isSome2(localOu)&&isSome2(oa)){const issues=[];collectIssues(encodingChecks,localOu.value,issues,ast,options);if(isArrayNonEmpty2(issues)){return fail6(new Composite(ast,localOu,issues))}}return succeed6(oa)})}if(checks&&!options?.disableChecks){if(options?.errors==="all"&&structuralChecks&&structuralChecks.length>0&&isSome2(localOu)){sroa2=mapSchemaIssueEffect(sroa2,(issue)=>{const issues=[];collectIssues(structuralChecks,localOu.value,issues,ast,options);const out=isArrayNonEmpty2(issues)?issue._tag==="Composite"&&issue.ast===ast?new Composite(ast,issue.actual,[...issue.issues,...issues]):new Composite(ast,localOu,[issue,...issues]):issue;return out})}sroa2=flatMapEager2(sroa2,(oa)=>{if(isSome2(oa)){const value3=oa.value;const issues=[];collectIssues(checks,value3,issues,ast,options);if(isArrayNonEmpty2(issues)){return fail6(new Composite(ast,oa,issues))}}return succeed6(oa)})}return sroa2};const sroa=srou?flatMapEager2(srou,parseLocal):parseLocal(ou);return sroa}});var toEquivalence=memoize((ast)=>{return recur3(ast,[])});function recur3(ast,path){const annotation=resolve(ast)?.["toEquivalence"];if(annotation){return annotation(isDeclaration(ast)?ast.typeParameters.map((tp)=>recur3(tp,path)):[])}switch(ast._tag){case"Never":throw errorWithPath(`Unsupported AST ${ast._tag}`,path);case"Declaration":case"Null":case"Undefined":case"Void":case"Unknown":case"Any":case"String":case"Number":case"Boolean":case"BigInt":case"Symbol":case"Literal":case"UniqueSymbol":case"ObjectKeyword":case"Enum":case"TemplateLiteral":return equals;case"Arrays":{const elements=ast.elements.map((e,i)=>recur3(e,[...path,i]));const len=ast.elements.length;const rest=ast.rest.map((r,i)=>recur3(r,[...path,len+i]));return make3((a,b)=>{if(!Array.isArray(a)||!Array.isArray(b)){return false}const len2=a.length;if(len2!==b.length){return false}let i=0;for(;i<Math.min(len2,ast.elements.length);i++){if(!elements[i](a[i],b[i])){return false}}if(rest.length>0){const[head,...tail]=rest;for(;i<len2-tail.length;i++){if(!head(a[i],b[i])){return false}}for(let j=0;j<tail.length;j++){if(!tail[j](a[i+j],b[i+j])){return false}}}return true})}case"Objects":{if(ast.propertySignatures.length===0&&ast.indexSignatures.length===0){return equals}const propertySignatures=ast.propertySignatures.map((ps)=>recur3(ps.type,[...path,ps.name]));const indexSignatures=ast.indexSignatures.map((is2)=>recur3(is2.type,path));return make3((a,b)=>{if(!isObject(a)||!isObject(b)){return false}for(let i=0;i<propertySignatures.length;i++){const ps=ast.propertySignatures[i];const name=ps.name;const aHas=Object.hasOwn(a,name);const bHas=Object.hasOwn(b,name);if(isOptional(ps.type)){if(aHas!==bHas){return false}}if(aHas&&bHas&&!propertySignatures[i](a[name],b[name])){return false}}for(let i=0;i<indexSignatures.length;i++){const is2=ast.indexSignatures[i];const aKeys=getIndexSignatureKeys(a,is2.parameter);const bKeys=getIndexSignatureKeys(b,is2.parameter);if(aKeys.length!==bKeys.length)return false;for(let j=0;j<aKeys.length;j++){const key=aKeys[j];if(!Object.hasOwn(b,key)||!indexSignatures[i](a[key],b[key])){return false}}}return true})}case"Union":return make3((a,b)=>{const candidates=getCandidates(a,ast.types);const types=candidates.map(_is);for(let i=0;i<candidates.length;i++){const is2=types[i];if(is2(a)&&is2(b)){return recur3(candidates[i],path)(a,b)}}return false});case"Suspend":{const get5=memoizeThunk(()=>recur3(ast.thunk(),path));return make3((a,b)=>get5()(a,b))}}}function escapeToken(token){return token.replace(/~/g,"~0").replace(/\//g,"~1")}function unescapeToken(token){return token.replace(/~1/g,"/").replace(/~0/g,"~")}var RegExp2=globalThis.RegExp;var escape=(string3)=>string3.replace(/[/\\^$*+?.()|[\]{}]/g,"\\$&");var TypeId30="~effect/SchemaError/SchemaError";class SchemaError extends TaggedError2("SchemaError"){[TypeId30]=TypeId30;constructor(issue){super({issue})}get message(){return this.issue.toString()}toString(){return`SchemaError(${this.message})`}}function isSchemaError(u){return hasProperty(u,TypeId30)}var TypeId31="~effect/Schema/Schema";var SchemaProto={[TypeId31]:TypeId31,pipe(){return pipeArguments(this,arguments)},annotate(annotations){return this.rebuild(annotate(this.ast,annotations))},annotateKey(annotations){return this.rebuild(annotateKey(this.ast,annotations))},check(...checks){return this.rebuild(appendChecks(this.ast,checks))}};function make24(ast,options){const self=Object.create(SchemaProto);if(options){Object.assign(self,options)}self.ast=ast;self.rebuild=(ast2)=>make24(ast2,options);const makeEffect2=makeEffect(self);self.makeEffect=(input,options2)=>fromIssueEffect(makeEffect2(input,options2));self.make=make23(self);self.makeOption=makeOption(self);return self}function fromIssueEffect(self){return catchCause2(self,(cause)=>failCauseSync2(()=>map6(cause,(issue)=>new SchemaError(issue))))}var jsonReorder=makeReorder(getJsonPriority);function getJsonPriority(ast){switch(ast._tag){case"BigInt":case"Symbol":case"UniqueSymbol":return 0;default:return 1}}function makeReorder(getPriority){return(types)=>{const indexMap=new Map;for(let i=0;i<types.length;i++){indexMap.set(toEncoded(types[i]),i)}const sortedTypes=[...types].sort((a,b)=>{a=toEncoded(a);b=toEncoded(b);const pa=getPriority(a);const pb=getPriority(b);if(pa!==pb)return pa-pb;return indexMap.get(a)-indexMap.get(b)});const orderChanged=sortedTypes.some((ast,index2)=>ast!==types[index2]);if(!orderChanged)return types;return sortedTypes}}function fromAST(ast){const{references,representations:schemas}=fromASTs([ast]);return{representation:schemas[0],references}}function fromASTs(asts){const references={};const referenceMap=new Map;const uniqueReferences=new Set;const visiting=new Set;const schemas=map4(asts,(ast)=>recur4(ast));return{representations:schemas,references};function gen3(prefix){let candidate=prefix;let suffix=0;while(uniqueReferences.has(candidate)){candidate=`${prefix}${++suffix}`}uniqueReferences.add(candidate);return candidate}function recur4(ast,prefix){const found=referenceMap.get(ast);if(found!==undefined){return{_tag:"Reference",$ref:found}}const last=getLastEncoding(ast);const identifier2=resolveIdentifier(ast)??prefix;if(ast!==last){return recur4(last,identifier2)}if(identifier2!==undefined){const reference=gen3(identifier2);referenceMap.set(ast,reference);const out2=on(ast);const found2=references[identifier2];if(found2!==undefined&&equals(out2,found2)){referenceMap.set(ast,identifier2);return{_tag:"Reference",$ref:identifier2}}references[reference]=out2;return{_tag:"Reference",$ref:reference}}if(visiting.has(ast)){const reference=gen3(`${ast._tag}_`);referenceMap.set(ast,reference);return{_tag:"Reference",$ref:reference}}visiting.add(ast);const out=on(ast);visiting.delete(ast);const ref=referenceMap.get(ast);if(ref!==undefined){references[ref]=out;return{_tag:"Reference",$ref:ref}}return out}function getEncodedSchema(last){const getLink=last.annotations?.toCodecJson??last.annotations?.toCodec;if(isFunction(getLink)){return replaceEncoding(last,[getLink(last.typeParameters.map((tp)=>make24(toEncoded(tp))))])}return null_}function on(last){const annotations=fromASTAnnotations(last.annotations);switch(last._tag){case"Declaration":{const encodedSchema=recur4(getEncodedSchema(last));return{_tag:"Declaration",typeParameters:last.typeParameters.map((ast)=>recur4(ast)),encodedSchema,checks:fromASTChecks(last.checks),...annotations}}case"Null":case"Undefined":case"Void":case"Never":case"Unknown":case"Any":case"Boolean":case"Symbol":case"ObjectKeyword":return{_tag:last._tag,...annotations};case"String":{const contentMediaType=last.annotations?.contentMediaType;const contentSchema=last.annotations?.contentSchema;return{_tag:last._tag,checks:fromASTChecks(last.checks),...annotations,...typeof contentMediaType==="string"&&isAST(contentSchema)?{contentSchema:recur4(contentSchema)}:undefined}}case"Number":case"BigInt":return{_tag:last._tag,checks:fromASTChecks(last.checks),...annotations};case"Literal":return{_tag:last._tag,literal:last.literal,...annotations};case"UniqueSymbol":return{_tag:last._tag,symbol:last.symbol,...annotations};case"Enum":return{_tag:last._tag,enums:last.enums,...annotations};case"TemplateLiteral":return{_tag:last._tag,parts:last.parts.map((ast)=>recur4(ast)),...annotations};case"Arrays":return{_tag:last._tag,elements:last.elements.map((e)=>{const last2=getLastEncoding(e);return{isOptional:isOptional(last2),type:recur4(e),...fromASTAnnotations(last2.context?.annotations)}}),rest:last.rest.map((ast)=>recur4(ast)),checks:fromASTChecks(last.checks),...annotations};case"Objects":return{_tag:last._tag,propertySignatures:last.propertySignatures.map((ps)=>{const last2=getLastEncoding(ps.type);return{name:ps.name,type:recur4(ps.type),isOptional:isOptional(last2),isMutable:isMutable(last2),...fromASTAnnotations(last2.context?.annotations)}}),indexSignatures:last.indexSignatures.map((is2)=>({parameter:recur4(is2.parameter),type:recur4(is2.type)})),checks:fromASTChecks(last.checks),...annotations};case"Union":{const types=jsonReorder(last.types);return{_tag:last._tag,types:types.map((ast)=>recur4(ast)),mode:last.mode,...annotations}}case"Suspend":{return{_tag:"Suspend",checks:[],thunk:recur4(last.thunk()),...annotations}}}}function fromASTChecks(checks){if(!checks)return[];return checks.map(getCheck).filter((c)=>c!==undefined);function getCheck(c){switch(c._tag){case"Filter":{const meta=c.annotations?.meta;if(meta){return{_tag:"Filter",meta:meta._tag==="isPropertyNames"?{_tag:"isPropertyNames",propertyNames:recur4(meta.propertyNames)}:meta,...fromASTAnnotations(c.annotations)}}return}case"FilterGroup":{const checks2=fromASTChecks(c.checks);if(isArrayNonEmpty2(checks2)){return{_tag:"FilterGroup",checks:checks2,...fromASTAnnotations(c.annotations)}}}}}}}var fromASTBlacklist=new Set(["~structural","~sentinels","meta","arbitrary","toArbitrary","toEquivalence","toFormatter","toCodec","toCodecJson","toCodecIso",ClassTypeId]);var standardJsonSchemaAnnotationKeys=new Set(["title","description","default","examples","readOnly","writeOnly","format","contentEncoding","contentMediaType","contentSchema"]);function fromASTAnnotations(annotations){if(annotations!==undefined){const filtered=filter3(annotations,(_,k)=>!fromASTBlacklist.has(k));if(!isEmptyRecord(filtered)){return{annotations:filtered}}}return}function toJsonSchemaDocument(document,options){const{definitions,dialect:source,schemas}=toJsonSchemaMultiDocument({representations:[document.representation],references:document.references},options);const schema=schemas[0];return{dialect:source,schema,definitions}}function toJsonSchemaMultiDocument(multiDocument,options){const generateDescriptions=options?.generateDescriptions??false;const additionalProperties=options?.additionalProperties??false;const includeAnnotationKey=options?.includeAnnotationKey;const definitions=map3(multiDocument.references,(d)=>recur4(d));return{dialect:"draft-2020-12",schemas:map4(multiDocument.representations,(s)=>recur4(s)),definitions};function recur4(s){let js=on(s);if("annotations"in s){const a=collectJsonSchemaAnnotations(s.annotations);if(a){js={...js,...a}}}if("checks"in s){const checks=collectJsonSchemaChecks(s.checks,js.type);for(const check of checks){js=appendJsonSchema(js,check)}}return js}function on(schema){switch(schema._tag){case"Any":case"Unknown":return{};case"ObjectKeyword":return{anyOf:[{type:"object"},{type:"array"}]};case"Void":case"Undefined":return{type:"null"};case"BigInt":return{type:"string",allOf:[{pattern:"^-?\\d+$"}]};case"Symbol":case"UniqueSymbol":return{type:"string",allOf:[{pattern:"^Symbol\\((.*)\\)$"}]};case"Declaration":return recur4(schema.encodedSchema);case"Suspend":return recur4(schema.thunk);case"Reference":return{$ref:`#/$defs/${escapeToken(schema.$ref)}`};case"Null":return{type:"null"};case"Never":return{not:{}};case"String":{const out={type:"string"};if(schema.contentMediaType!==undefined){out.contentMediaType=schema.contentMediaType}if(schema.contentSchema!==undefined){out.contentSchema=recur4(schema.contentSchema)}return out}case"Number":return hasCheck2(schema.checks,"isInt")?{type:"integer"}:hasCheck2(schema.checks,"isFinite")?{type:"number"}:{anyOf:[{type:"number"},{type:"string",enum:["NaN"]},{type:"string",enum:["Infinity"]},{type:"string",enum:["-Infinity"]}]};case"Boolean":return{type:"boolean"};case"Literal":{const literal=schema.literal;if(typeof literal==="string"){return{type:"string",enum:[literal]}}if(typeof literal==="number"){return{type:"number",enum:[literal]}}if(typeof literal==="boolean"){return{type:"boolean",enum:[literal]}}return{type:"string",enum:[String(literal)]}}case"Enum":{return recur4({_tag:"Union",types:schema.enums.map(([title,value3])=>({_tag:"Literal",literal:value3,annotations:{title}})),mode:"anyOf",annotations:schema.annotations})}case"TemplateLiteral":{const pattern=schema.parts.map(getPartPattern).join("");return{type:"string",pattern:`^${pattern}$`}}case"Arrays":{if(schema.rest.length>1){throw new globalThis.Error("Generating a JSON Schema for post-rest elements is not supported")}const out={type:"array"};let minItems=schema.elements.length;const prefixItems=schema.elements.map((e)=>{if(e.isOptional){minItems--}const v=recur4(e.type);const a=collectJsonSchemaAnnotations(e.annotations);return a?appendJsonSchema(v,a):v});if(prefixItems.length>0){out.prefixItems=prefixItems;out.maxItems=schema.elements.length;if(minItems>0){out.minItems=minItems}}else{out.items=false}if(schema.rest.length>0){delete out.maxItems;const rest=recur4(schema.rest[0]);if(Object.keys(rest).length>0){out.items=rest}else{delete out.items}}return out}case"Objects":{if(schema.propertySignatures.length===0&&schema.indexSignatures.length===0){return{anyOf:[{type:"object"},{type:"array"}]}}const out={type:"object"};const properties={};const required=[];for(const ps of schema.propertySignatures){const name=ps.name;if(typeof name!=="string"){throw new globalThis.Error(`Unsupported property signature name: ${format(name)}`)}const v=recur4(ps.type);const a=collectJsonSchemaAnnotations(ps.annotations);properties[name]=a?appendJsonSchema(v,a):v;if(!ps.isOptional){required.push(name)}}if(Object.keys(properties).length>0){out.properties=properties}if(required.length>0){out.required=required}out.additionalProperties=additionalProperties;const patternProperties={};for(const is2 of schema.indexSignatures){let type=recur4(is2.type);if(Object.keys(type).length===1&&"not"in type){type=false}const patterns=getParameterPatterns(is2.parameter);if(patterns.length>0){for(const pattern of patterns){patternProperties[pattern]=type}}else{out.additionalProperties=type}}if(Object.keys(patternProperties).length>0){out.patternProperties=patternProperties;delete out.additionalProperties}if(isObject(out.additionalProperties)&&isEmptyRecord(out.additionalProperties)){delete out.additionalProperties}return out}case"Union":{const types=schema.types.map(recur4);if(types.length===0){return{not:{}}}if(types.length>1){const compacted=compactEnums(types);if(compacted)return compacted}return schema.mode==="anyOf"?{anyOf:types}:{oneOf:types}}}}function compactEnums(types){let sharedType;const values3=[];for(const t of types){const keys3=Object.keys(t);if(keys3.length!==2||t.type===undefined||!Array.isArray(t.enum)||t.enum.length===0){return}if(sharedType===undefined){sharedType=t.type}else if(t.type!==sharedType){return}for(const v of t.enum){values3.push(v)}}return{type:sharedType,enum:values3}}function collectJsonSchemaAnnotations(annotations){if(annotations===undefined)return;const out={};if(typeof annotations.title==="string")out.title=annotations.title;if(typeof annotations.description==="string")out.description=annotations.description;else if(generateDescriptions&&typeof annotations.expected==="string")out.description=annotations.expected;if(annotations.default!==undefined)out.default=annotations.default;if(Array.isArray(annotations.examples))out.examples=annotations.examples;if(typeof annotations.readOnly==="boolean")out.readOnly=annotations.readOnly;if(typeof annotations.writeOnly==="boolean")out.writeOnly=annotations.writeOnly;if(typeof annotations.format==="string")out.format=annotations.format;if(typeof annotations.contentEncoding==="string")out.contentEncoding=annotations.contentEncoding;if(typeof annotations.contentMediaType==="string")out.contentMediaType=annotations.contentMediaType;if(includeAnnotationKey){for(const[key,value3]of Object.entries(annotations)){if(value3===undefined)continue;if(standardJsonSchemaAnnotationKeys.has(key))continue;if(!includeAnnotationKey(key))continue;out[key]=value3}}if(Object.keys(out).length>0)return out}function collectJsonSchemaChecks(checks,type){return checks.map(collectJsonSchemaCheck).filter((c)=>c!==undefined);function collectJsonSchemaCheck(check){switch(check._tag){case"Filter":return filterToJsonSchema(check,type);case"FilterGroup":{const checks2=check.checks.map(collectJsonSchemaCheck).filter((c)=>c!==undefined);if(checks2.length===0)return;let out={allOf:checks2};const a=collectJsonSchemaAnnotations(check.annotations);if(a){out={...out,...a}}return out}}}}function filterToJsonSchema(filter10,type){const meta=filter10.meta;if(!meta)return;let out=on2(meta);const a=collectJsonSchemaAnnotations(filter10.annotations);if(a){out={...out,...a}}return out;function on2(meta2){switch(meta2._tag){case"isMinLength":return type==="array"?{minItems:meta2.minLength}:{minLength:meta2.minLength};case"isMaxLength":return type==="array"?{maxItems:meta2.maxLength}:{maxLength:meta2.maxLength};case"isLengthBetween":return type==="array"?{allOf:[{minItems:meta2.minimum},{maxItems:meta2.maximum}]}:{allOf:[{minLength:meta2.minimum},{maxLength:meta2.maximum}]};case"isPattern":case"isGUID":case"isULID":case"isBase64":case"isBase64Url":case"isStartsWith":case"isEndsWith":case"isIncludes":case"isUppercased":case"isLowercased":case"isCapitalized":case"isUncapitalized":case"isTrimmed":case"isStringFinite":case"isStringBigInt":case"isStringSymbol":return{pattern:meta2.regExp.source};case"isUUID":return{pattern:meta2.regExp.source,format:"uuid"};case"isFinite":case"isInt":return;case"isMultipleOf":return{multipleOf:meta2.divisor};case"isGreaterThanOrEqualTo":return{minimum:meta2.minimum};case"isLessThanOrEqualTo":return{maximum:meta2.maximum};case"isGreaterThan":return{exclusiveMinimum:meta2.exclusiveMinimum};case"isLessThan":return{exclusiveMaximum:meta2.exclusiveMaximum};case"isBetween":{return{[meta2.exclusiveMinimum?"exclusiveMinimum":"minimum"]:meta2.minimum,[meta2.exclusiveMaximum?"exclusiveMaximum":"maximum"]:meta2.maximum}}case"isUnique":return{uniqueItems:true};case"isMinProperties":return{minProperties:meta2.minProperties};case"isMaxProperties":return{maxProperties:meta2.maxProperties};case"isPropertiesLengthBetween":return{minProperties:meta2.minimum,maxProperties:meta2.maximum};case"isPropertyNames":return{propertyNames:recur4(meta2.propertyNames)};case"isDateValid":return{format:"date-time"}}}}function getParameterPatterns(parameter){switch(parameter._tag){default:throw new globalThis.Error(`Unsupported index signature parameter: ${parameter._tag}`);case"Reference":return getParameterPatterns(multiDocument.references[parameter.$ref]);case"String":return getPatterns(parameter);case"TemplateLiteral":return[`^${parameter.parts.map(getPartPattern).join("")}$`];case"Union":return parameter.types.flatMap(getParameterPatterns)}}}function getPatterns(s){return recur4(s.checks);function recur4(checks){return checks.flatMap((c)=>{switch(c._tag){case"Filter":{if("regExp"in c.meta){return[c.meta.regExp.source]}return[]}case"FilterGroup":return recur4(c.checks)}})}}function hasCheck2(checks,tag){return checks.some((c)=>{switch(c._tag){case"Filter":return c.meta._tag===tag;case"FilterGroup":return hasCheck2(c.checks,tag)}})}function appendJsonSchema(a,b){if(Object.keys(a).length===0)return b;const len=Object.keys(b).length;if(len===0)return a;const members=Array.isArray(b.allOf)&&len===1?b.allOf:[b];if(Array.isArray(a.allOf)){return{...a,allOf:[...a.allOf,...members]}}if(typeof a.$ref==="string"){return{allOf:[a,...members]}}return{...a,allOf:members}}function getPartPattern(part){switch(part._tag){case"Literal":return escape(globalThis.String(part.literal));case"String":return STRING_PATTERN;case"Number":return FINITE_PATTERN;case"TemplateLiteral":return part.parts.map(getPartPattern).join("");case"Union":return part.types.map(getPartPattern).join("|");default:throw new globalThis.Error("Unsupported part",{cause:part})}}function get5(oldValue,newValue){if(Object.is(oldValue,newValue))return[];const patches=[];if(Array.isArray(oldValue)&&Array.isArray(newValue)){const len1=oldValue.length;const len2=newValue.length;const shared=Math.min(len1,len2);for(let i=0;i<shared;i++){const path=`/${i}`;const patch=get5(oldValue[i],newValue[i]);for(const op of patch){prefixPathInPlace(op,path);patches.push(op)}}for(let i=len1-1;i>=len2;i--){patches.push({op:"remove",path:`/${i}`})}for(let i=len1;i<len2;i++){patches.push({op:"add",path:`/${i}`,value:newValue[i]})}return patches}if(isJsonObject(oldValue)&&isJsonObject(newValue)){const keys1=Object.keys(oldValue);const keys22=Object.keys(newValue);const allKeys=Array.from(new Set([...keys1,...keys22])).sort();for(const key of allKeys){const esc=escapeToken(key);const path=`/${esc}`;const hasKey1=Object.hasOwn(oldValue,key);const hasKey2=Object.hasOwn(newValue,key);if(hasKey1&&hasKey2){const patch=get5(oldValue[key],newValue[key]);for(const op of patch){prefixPathInPlace(op,path);patches.push(op)}}else if(!hasKey1&&hasKey2){patches.push({op:"add",path,value:newValue[key]})}else if(hasKey1&&!hasKey2){patches.push({op:"remove",path})}}return patches}patches.push({op:"replace",path:"",value:newValue});return patches}function apply(patch,oldValue){let doc=oldValue;for(const op of patch){switch(op.op){case"replace":{doc=op.path===""?op.value:setAt(doc,op.path,op.value,"replace");break}case"add":{doc=addAt(doc,op.path,op.value);break}case"remove":{doc=setAt(doc,op.path,undefined,"remove");break}}}return doc}function prefixPathInPlace(op,parent){op.path=op.path===""?parent:parent+op.path}function isJsonObject(value3){return isObject(value3)}function tokenize(pointer){if(pointer==="")return[];if(pointer.charCodeAt(0)!==47){throw new Error(`Invalid JSON Pointer, it must start with "/": ${format(pointer)}`)}return pointer.split("/").slice(1).map(unescapeToken)}function toIndex(token){if(!/^(0|[1-9]\d*)$/.test(token)){throw new Error(`Invalid array index: "${token}"`)}return Number(token)}function addAt(doc,pointer,val){if(pointer==="")return val;const resolved=resolveParent(doc,pointer);if(resolved===null){throw new Error(`Cannot add at "${pointer}" (parent not found or not a container).`)}const{lastToken,parent,stack}=resolved;if(Array.isArray(parent)){const idx=lastToken==="-"?parent.length:toIndex(lastToken);if(idx<0||idx>parent.length)throw new Error(`Array index out of bounds at "${pointer}".`);const updated=parent.slice();updated.splice(idx,0,val);return rebuildFromStack(stack,updated)}if(isJsonObject(parent)){const updated={...parent};updated[lastToken]=val;return rebuildFromStack(stack,updated)}throw new Error(`Cannot add at "${pointer}" (parent not found or not a container).`)}function setAt(doc,pointer,val,mode){if(pointer===""){if(mode==="remove"||val===undefined)throw new Error("Unsupported operation at the root");return val}const resolved=resolveParent(doc,pointer);if(resolved===null){throw new Error(`Cannot ${mode} at "${pointer}" (parent not found or not a container).`)}const{lastToken,parent,stack}=resolved;if(Array.isArray(parent)){if(lastToken==="-")throw new Error(`"-" is not valid for ${mode} at "${pointer}".`);const idx=toIndex(lastToken);if(idx<0||idx>=parent.length)throw new Error(`Array index out of bounds at "${pointer}".`);const updated=parent.slice();if(mode==="remove")updated.splice(idx,1);else updated[idx]=val;return rebuildFromStack(stack,updated)}if(isJsonObject(parent)){if(!Object.hasOwn(parent,lastToken)){throw new Error(`Property "${lastToken}" does not exist at "${pointer}".`)}const updated={...parent};if(mode==="remove")delete updated[lastToken];else updated[lastToken]=val;return rebuildFromStack(stack,updated)}throw new Error(`Cannot ${mode} at "${pointer}" (parent not found or not a container).`)}function resolveParent(doc,pointer){const tokens=tokenize(pointer);if(tokens.length===0)return null;const lastToken=tokens[tokens.length-1];const stack=[];let cur=doc;for(let i=0;i<tokens.length-1;i++){const token=tokens[i];if(cur==null)return null;if(Array.isArray(cur)){const idx=toIndex(token);if(idx<0||idx>=cur.length)return null;stack.push({container:cur,token:idx});cur=cur[idx];continue}if(cur&&typeof cur==="object"){if(!Object.hasOwn(cur,token))return null;stack.push({container:cur,token});cur=cur[token];continue}return null}return{stack,parent:cur,lastToken}}function rebuildFromStack(stack,newParent){let acc=newParent;for(let i=stack.length-1;i>=0;i--){const{container,token}=stack[i];if(Array.isArray(container)){const copy2=container.slice();copy2[token]=acc;acc=copy2}else{const copy2={...container};copy2[token]=acc;acc=copy2}}return acc}var RE_DEFS=/^#\/\$defs(?=\/|$)/;function toDocumentDraft07(document){return{dialect:"draft-07",schema:toSchemaDraft07(document.schema),definitions:map3(document.definitions,toSchemaDraft07)}}function toSchemaDraft07(schema){return rewrite(schema);function rewrite(node){return walk(rewrite_refs(node,(ref)=>ref.replace(RE_DEFS,"#/definitions")),true)}function walk(node,_isRoot){if(Array.isArray(node))return node.map((v)=>walk(v,false));if(!isObject(node))return node;const src=node;const out={};let prefixItems=undefined;let items=undefined;for(const k of Object.keys(src)){const v=src[k];switch(k){case"$ref":case"type":case"required":case"enum":case"const":case"title":case"description":case"default":case"examples":case"format":case"pattern":case"minimum":case"maximum":case"exclusiveMinimum":case"exclusiveMaximum":case"minLength":case"maxLength":case"minItems":case"maxItems":case"minProperties":case"maxProperties":case"multipleOf":case"uniqueItems":out[k]=v;break;case"properties":case"patternProperties":{const mapped=walk_object(v,walk);out[k]=mapped??v;break}case"additionalProperties":case"propertyNames":out[k]=walk(v,false);break;case"allOf":case"anyOf":case"oneOf":out[k]=Array.isArray(v)?v.map((x)=>walk(x,false)):v;break;case"prefixItems":prefixItems=v;break;case"items":items=v;break;default:break}}if(prefixItems!==undefined){if(Array.isArray(prefixItems)){out.items=prefixItems.map((x)=>walk(x,false));if(items!==undefined)out.additionalItems=walk(items,false)}else{out.items=walk(prefixItems,false)}}else if(items!==undefined){out.items=walk(items,false)}return out}}function toMultiDocumentOpenApi3_1(multiDocument){const keyMap2=new Map;for(const key of Object.keys(multiDocument.definitions)){const sanitized=sanitizeOpenApiComponentsSchemasKey(key);if(sanitized!==key){keyMap2.set(key,sanitized)}}function rewrite(schema){return rewrite_refs(schema,($ref)=>{const tokens=$ref.split("/");if(tokens.length>0){const identifier2=unescapeToken(tokens[tokens.length-1]);const sanitized=keyMap2.get(identifier2);if(sanitized!==undefined){$ref=tokens.slice(0,-1).join("/")+"/"+sanitized}}return $ref.replace(RE_DEFS,"#/components/schemas")})}return{dialect:"openapi-3.1",schemas:map4(multiDocument.schemas,rewrite),definitions:mapEntries(multiDocument.definitions,(definition,key)=>[keyMap2.get(key)??key,rewrite(definition)])}}var VALID_OPEN_API_COMPONENTS_SCHEMAS_KEY_REGEXP=/^[a-zA-Z0-9.\-_]+$/;function sanitizeOpenApiComponentsSchemasKey(s){if(s.length===0)return"_";if(VALID_OPEN_API_COMPONENTS_SCHEMAS_KEY_REGEXP.test(s))return s;const out=[];for(const ch of s){const code=ch.codePointAt(0);if(code!==undefined&&(code>=48&&code<=57||code>=65&&code<=90||code>=97&&code<=122||code===46||code===45||code===95)){out.push(ch)}else{out.push("_")}}return out.join("")}function rewrite_refs(node,f){if(Array.isArray(node))return node.map((v)=>rewrite_refs(v,f));if(!isObject(node))return node;const out={};for(const k of Object.keys(node)){const v=node[k];if(k==="$ref"){out[k]=typeof v==="string"?f(v):v}else if(Array.isArray(v)||isObject(v)){out[k]=rewrite_refs(v,f)}else{out[k]=v}}return out}function walk_object(value3,walk){if(!isObject(value3))return;const out={};for(const k of Object.keys(value3))out[k]=walk(value3[k],false);return out}function makeIso(get6,set3){return make25(new IsoNode(get6,set3))}function makeLens(get6,replace){return make25(new LensNode(get6,replace))}class IdentityNode{_tag="IdentityNode"}var identityNode=new IdentityNode;class CompositionNode{_tag="CompositionNode";nodes;constructor(nodes){this.nodes=nodes}}class IsoNode{_tag="IsoNode";get;set;constructor(get6,set3){this.get=get6;this.set=set3}}class LensNode{_tag="LensNode";get;set;constructor(get6,set3){this.get=get6;this.set=set3}}class PrismNode{_tag="PrismNode";get;set;constructor(get6,set3){this.get=get6;this.set=set3}}class OptionalNode{_tag="OptionalNode";get;set;constructor(get6,set3){this.get=get6;this.set=set3}}class PathNode{_tag="PathNode";path;constructor(path){this.path=path}}class CheckNode{_tag="CheckNode";checks;constructor(checks){this.checks=checks}}function pushNormalized(acc,node){const last=acc[acc.length-1];if(last){if(last._tag==="PathNode"&&node._tag==="PathNode"){acc[acc.length-1]=new PathNode([...last.path,...node.path]);return}if(last._tag==="CheckNode"&&node._tag==="CheckNode"){acc[acc.length-1]=new CheckNode([...last.checks,...node.checks]);return}}acc.push(node)}function collect(node,acc){if(node._tag==="IdentityNode")return;if(node._tag==="CompositionNode"){for(let i=0;i<node.nodes.length;i++)collect(node.nodes[i],acc);return}pushNormalized(acc,node)}function compose(a,b){const nodes=[];collect(a,nodes);collect(b,nodes);switch(nodes.length){case 0:return identityNode;case 1:return nodes[0];default:return new CompositionNode(nodes)}}function makeOptional(getResult,set3){return make25(new OptionalNode(getResult,set3))}class OptionalImpl{node;getResult;replaceResult;constructor(node,getResult,replaceResult){this.node=node;this.getResult=getResult;this.replaceResult=replaceResult}replace(a,s){return getOrElse3(this.replaceResult(a,s),()=>s)}modify(f){return(s)=>getOrElse3(flatMap2(this.getResult(s),(a)=>this.replaceResult(f(a),s)),()=>s)}compose(that){return make25(compose(this.node,that.node))}key(key){return make25(compose(this.node,new PathNode([key])))}optionalKey(key){return make25(compose(this.node,new LensNode((s)=>s[key],(a,s)=>{const copy2=cloneShallow(s);if(a===undefined){if(Array.isArray(copy2)&&typeof key==="number"){copy2.splice(key,1)}else{delete copy2[key]}}else{copy2[key]=a}return copy2})))}check(...checks){return make25(compose(this.node,new CheckNode(checks)))}refine(refinement,annotations){return make25(compose(this.node,new CheckNode([makeFilterByGuard(refinement,annotations)])))}tag(tag){return make25(compose(this.node,new PrismNode((s)=>s._tag===tag?succeed2(s):fail2(`Expected ${format(tag)} tag, got ${format(s._tag)}`),identity)))}at(key,..._rest){const err=fail2(`Key ${format(key)} not found`);return make25(compose(this.node,new OptionalNode((s)=>Object.hasOwn(s,key)?succeed2(s[key]):err,(a,s)=>{if(Object.hasOwn(s,key)){const copy2=cloneShallow(s);copy2[key]=a;return succeed2(copy2)}else{return err}})))}pick(keys3){return this.compose(makeLens(pick(keys3),(p,a)=>({...a,...p})))}omit(keys3){return this.compose(makeLens(omit2(keys3),(o,a)=>({...a,...o})))}notUndefined(){return this.refine(isNotUndefined,{expected:"a value other than `undefined`"})}forEach(f){const inner=f(id());return makeOptional((s)=>map2(this.getResult(s),(as3)=>{const bs=[];for(let i=0;i<as3.length;i++){const r=inner.getResult(as3[i]);if(isSuccess2(r))bs.push(r.success)}return bs}),(bs,s)=>flatMap2(this.getResult(s),(as3)=>{const idxs=[];for(let i=0;i<as3.length;i++){if(isSuccess2(inner.getResult(as3[i])))idxs.push(i)}if(bs.length!==idxs.length){return fail2(`each: replacement length mismatch: ${bs.length} !== ${idxs.length}`)}const out=as3.slice();for(let k=0;k<idxs.length;k++){const i=idxs[k];const r=inner.replaceResult(bs[k],as3[i]);if(isFailure2(r)){return fail2(`each: could not set element ${i}`)}out[i]=r.success}return this.replaceResult(out,s)}))}modifyAll(f){return(s)=>getOrElse3(flatMap2(this.getResult(s),(as3)=>this.replaceResult(as3.map(f),s)),()=>s)}}class IsoImpl extends OptionalImpl{get;set;constructor(node,get6,set3){super(node,(s)=>succeed2(get6(s)),(a)=>succeed2(set3(a)));this.get=get6;this.set=set3}replace(a,_){return this.set(a)}modify(f){return(s)=>this.set(f(this.get(s)))}}class LensImpl extends OptionalImpl{get;constructor(node,get6,replace){super(node,(s)=>succeed2(get6(s)),(a,s)=>succeed2(replace(a,s)));this.get=get6;this.replace=replace}modify(f){return(s)=>this.replace(f(this.get(s)),s)}}class PrismImpl extends OptionalImpl{set;constructor(node,getResult,set3){super(node,getResult,(a,_)=>succeed2(set3(a)));this.set=set3}replace(a,_){return this.set(a)}modify(f){return(s)=>getOrElse3(map2(this.getResult(s),(a)=>this.set(f(a))),()=>s)}}function make25(node){const op=recur4(node);switch(op._tag){case"IsoNode":return new IsoImpl(node,op.get,op.set);case"LensNode":return new LensImpl(node,op.get,op.set);case"PrismNode":return new PrismImpl(node,op.get,op.set);case"OptionalNode":return new OptionalImpl(node,op.get,op.set)}}function cloneShallow(pojo){if(Array.isArray(pojo))return pojo.slice();if(typeof pojo==="object"&&pojo!==null){const proto=Object.getPrototypeOf(pojo);if(proto!==Object.prototype&&proto!==null){throw new Error("Cannot clone object with non-Object constructor or null prototype")}return{...pojo}}return pojo}var recur4=memoize((node)=>{switch(node._tag){case"IdentityNode":return{_tag:"IsoNode",get:identity,set:identity};case"IsoNode":case"LensNode":case"PrismNode":case"OptionalNode":return{_tag:node._tag,get:node.get,set:node.set};case"PathNode":{return{_tag:"LensNode",get:(s)=>{const path=node.path;let out=s;for(let i=0,n=path.length;i<n;i++){out=out[path[i]]}return out},set:(a,s)=>{const path=node.path;const out=cloneShallow(s);let current=out;let i=0;for(;i<path.length-1;i++){const key=path[i];current[key]=cloneShallow(current[key]);current=current[key]}const finalKey=path[i];current[finalKey]=a;return out}}}case"CheckNode":return{_tag:"PrismNode",get:(s)=>mapError(runChecks(node.checks,s),String),set:identity};case"CompositionNode":{const ops=node.nodes.map(recur4);const _tag=ops.reduce((tag,op)=>getCompositionTag(tag,op._tag),"IsoNode");return{_tag,get:(s)=>{for(let i=0;i<ops.length;i++){const op=ops[i];const result3=op.get(s);if(hasFailingGet(op._tag)){if(isFailure2(result3)){return result3}s=result3.success}else{s=result3}}return hasFailingGet(_tag)?succeed2(s):s},set:(a,s)=>{const source=s;const len=ops.length;const ss=new Array(len+1);ss[0]=s;for(let i=0;i<len;i++){const op=ops[i];if(hasFailingGet(op._tag)){const result3=op.get(s);if(isFailure2(result3)){return _tag==="OptionalNode"?result3:source}s=result3.success}else{s=op.get(s)}ss[i+1]=s}for(let i=len-1;i>=0;i--){const op=ops[i];if(hasSet(op._tag)){a=op.set(a)}else if(op._tag==="LensNode"){a=op.set(a,ss[i])}else{const result3=op.set(a,ss[i]);if(isFailure2(result3)){return result3}a=result3.success}}return _tag==="OptionalNode"?succeed2(a):a}}}}});function hasFailingGet(tag){return tag==="PrismNode"||tag==="OptionalNode"}function hasSet(tag){return tag==="IsoNode"||tag==="PrismNode"}function getCompositionTag(a,b){switch(a){case"IsoNode":return b;case"LensNode":return hasFailingGet(b)?"OptionalNode":"LensNode";case"PrismNode":return hasSet(b)?"PrismNode":"OptionalNode";case"OptionalNode":return"OptionalNode"}}var identityIso=make25(identityNode);function id(){return identityIso}var exports_FastCheck={};__export(exports_FastCheck,{webUrl:()=>webUrl,webSegment:()=>webSegment,webQueryParameters:()=>webQueryParameters,webPath:()=>webPath,webFragments:()=>webFragments,webAuthority:()=>webAuthority,uuid:()=>uuid,uniqueArray:()=>uniqueArray,ulid:()=>ulid,uint8ClampedArray:()=>uint8ClampedArray,uint8Array:()=>uint8Array,uint32Array:()=>uint32Array,uint16Array:()=>uint16Array,tuple:()=>tuple2,toStringMethod:()=>toStringMethod,subarray:()=>subarray,stringify:()=>stringify,stringMatching:()=>stringMatching,string:()=>string3,stream:()=>stream,statistics:()=>statistics,sparseArray:()=>sparseArray,shuffledSubarray:()=>shuffledSubarray,set:()=>set3,schedulerFor:()=>schedulerFor,scheduler:()=>scheduler,scheduledModelRun:()=>scheduledModelRun,sample:()=>sample,resetConfigureGlobal:()=>resetConfigureGlobal,record:()=>record2,readConfigureGlobal:()=>readConfigureGlobal,property:()=>property,pre:()=>pre,option:()=>option3,oneof:()=>oneof,object:()=>object,noShrink:()=>noShrink,noBias:()=>noBias,nat:()=>nat,modelRun:()=>modelRun,mixedCase:()=>mixedCase,memo:()=>memo,maxSafeNat:()=>maxSafeNat,maxSafeInteger:()=>maxSafeInteger,mapToConstant:()=>mapToConstant,map:()=>map13,lorem:()=>lorem,limitShrink:()=>limitShrink,letrec:()=>letrec,jsonValue:()=>jsonValue,json:()=>json,ipV6:()=>ipV6,ipV4Extended:()=>ipV4Extended,ipV4:()=>ipV4,integer:()=>integer,int8Array:()=>int8Array,int32Array:()=>int32Array,int16Array:()=>int16Array,infiniteStream:()=>infiniteStream,hash:()=>hash2,hasToStringMethod:()=>hasToStringMethod,hasCloneMethod:()=>hasCloneMethod,hasAsyncToStringMethod:()=>hasAsyncToStringMethod,getDepthContextFor:()=>getDepthContextFor,gen:()=>gen3,func:()=>func,float64Array:()=>float64Array,float32Array:()=>float32Array,float:()=>float,falsy:()=>falsy,entityGraph:()=>entityGraph,emailAddress:()=>emailAddress,double:()=>double,domain:()=>domain,dictionary:()=>dictionary,defaultReportMessage:()=>defaultReportMessage,date:()=>date,createDepthIdentifier:()=>createDepthIdentifier,context:()=>context3,constantFrom:()=>constantFrom,constant:()=>constant2,configureGlobal:()=>configureGlobal,compareFunc:()=>compareFunc,compareBooleanFunc:()=>compareBooleanFunc,commands:()=>commands,cloneMethod:()=>cloneMethod,cloneIfNeeded:()=>cloneIfNeeded,clone:()=>clone,check:()=>check,chainUntil:()=>chainUntil,boolean:()=>boolean2,bigUint64Array:()=>bigUint64Array,bigInt64Array:()=>bigInt64Array,bigInt:()=>bigInt2,base64String:()=>base64String,asyncToStringMethod:()=>asyncToStringMethod,asyncStringify:()=>asyncStringify,asyncProperty:()=>asyncProperty,asyncModelRun:()=>asyncModelRun,asyncDefaultReportMessage:()=>asyncDefaultReportMessage,assert:()=>assert,array:()=>array3,anything:()=>anything,__version:()=>__version,__type:()=>__type,__commitHash:()=>__commitHash,VerbosityLevel:()=>VerbosityLevel,Value:()=>Value,Stream:()=>Stream,Random:()=>Random,PreconditionFailure:()=>PreconditionFailure,ExecutionStatus:()=>ExecutionStatus,Arbitrary:()=>Arbitrary});var MULTIPLIER=214013;var INCREMENT=2531011;var MASK=4294967295;var MASK_2=-2147483649;var MULTIPLIER_2=-1443076087;var INCREMENT_2=505908858;var MULTIPLIER_3=1170746341;var INCREMENT_3=-755606699;var JUMP_MULTIPLIER=1994129409;var JUMP_INCREMENT=916127744;var LinearCongruential32=class LinearCongruential322{constructor(seed){this.seed=seed}clone(){return new LinearCongruential322(this.seed)}next(){const s0=this.seed;const s1=Math.imul(s0,MULTIPLIER)+INCREMENT|0;const s2=Math.imul(s0,MULTIPLIER_2)+INCREMENT_2|0;const s3=Math.imul(s0,MULTIPLIER_3)+INCREMENT_3|0;this.seed=s3;const v1=(s1&MASK_2)>>16;const v2=(s2&MASK_2)>>16;return(s3&MASK_2)>>16|v2<<15|v1<<30}jump(){this.seed=Math.imul(this.seed,JUMP_MULTIPLIER)+JUMP_INCREMENT&MASK}getState(){return[this.seed]}};function congruential32(seed){return new LinearCongruential32(seed)}var N=624;var M=397;var A=2567483615;var F=1812433253;var U=11;var S=7;var B=2636928640;var T=15;var C=4022730752;var L=18;var MASK_LOWER=2147483647;var MASK_UPPER=2147483648;var JUMP_COEFS="SUSgbA\\W`E[]KN2RUSo8XVU?HKBFRl11E\\KoWOg5B]XEWG;BE;1:oVK[`B^Z9Qd23^XTnhL>]Unda4f[X;_j9H5QD=cN<5H`3bW>9bk1mjoI2fK0obmAAINOV:>Mek_V9dd<hZ\\gC3?Fm7FEk07QH_3PLm^@?^i\\QMkgP<]oLHmFnlecg5F@7U^@4jhZ?WZS0k@GHehmM36:5^9;>Hmm`co>k:KOSkSbIINb1VFf>LXgP>GUAQTD>Ci>XMGkUflLlb?_FaFUk@?5N7i70@;1o68ah@I<HFH7R2^J:G][Gf962ITWID9GWK8ElD2G5=DcHcL]cA]P2n7A=[<bInM;IHDQnJMReRXDWbVldnGEIPij`E08Xdci3@0c:IBbD4:Nk]?lEN9j^;T`0blZX7eiWE8c`<ak7j05FZi>AjUDh?M1B?^??FAXKThf<aBOXZf7jXYGK>R<;NHk3S9YhM7STJ6`:MIE`S@7298X8W>PNK=@;lLX<i\\TXLL<W@X[X54H]in8M;;n?kkQbajgAMY=Tf9b;ZKf0QUB2FHYWfnfkDoU9YkcLd95T>lK6GM1YL\\lid:J>KYS=iJ]Y>QlF>?R5_[5QeYC=66;A32Ac>OHk_ne^0g>bK:g;KFPgbGUcPR_Z=TX3H9d03bKZ2IhEPKBo>LSGWd0iFdV8C<Y:<>T[O6lC\\blaZ>GoAYP4clf^j1IfnZJ]QeDe2X<HE[LJNWnaCg[P]Co^:IRbWPY?97UePBlZNNHY6LOBM8P>=h?Ye:_f_Sb9Ki5GDYBF4dWeMfdg^ccPllNWM7G1\\UMdoYeOOD5^e@foA22G?ADYo5:FVG[bWo96;>3kc_c1Ab30>30;1@4F8g2hY?DJ4[LOL;ZLLKo2]jo>[KMDUcR279N_kF=3WL@Dd620bMTdA\\U9k``ef2iD9JgJ8CZBHS>F^Uk;<laeaeHS<15OSeS`PcSSKBRBFY]aQ=EgUXGNg=?d56`KA@2BejY0^[_DCX`L=CGMT=BW^6S1i@2ATBVk>3_ocRA>2U:4GPQ6o>5jX2HIcV3S@On6KB<[SKB?FC_AAji9agbBFkAi\\;4I\\UJ]c36Ub@[;gQACVGY<V]SDJBUU]La\\_a@JdOO8gm2T0DJMa:8Hf7>E]noQ[1Kambn??QQ]S?1i0oMGOijb\\aGY6lQ^CJ?9bFle8<eH4UUjBINX;n8@VOA5ah^URV49B[A?ONHhHAC1J5;;h0SXYlG^0W=eJdHh^K4SGe=1HZLLam;D<Q3AOdbPcdX``82\\jo0En8jRVGC73WMCF9`d:0heS?80?C188cSn7H9<daZ]MgS4Pb^1HkA:1PU^5>^h_g[RQV@PnYBRI_]`B]Bh@Uk03eXGY`I16L76H28X`R>IROMeNVUdU[:lghLhPCQZ:4a<30YBZCYnXe[?;jc8gKI2QH2MjnWBm4nGCZW`aVU2a;P<AMI25mlW_Nm][2?b6o851X@lAm]YZ`bWRF1g<Ga:T]1NXH5Veja5P9S9>:aNg:Th1Y=5o78K>LQ8hW@5S?I83Lk5Xk;j5@I3o[d:4RjE^oS30:WP9gC\\i8aSI>QRE@4lP:7lDg8g2`Ql[2I8aBU\\BQ?B4_clL9Q]S;^e1Ob5[>3JER2`c7B=o]fPOWO<DGi;Niba1PoWPPE_Q3aX0OB0mZej\\f_M[J4Y6]1`h2MkF[GiW8Q^d3^_=<I1N2Q7]2<2j[iP7V3V821FaI]A`93bC^Z\\G=WJ;^Ih?B97_iIF@\\Dl<eK1je8SNTWo_=XFMZH<<JYLZ^YQMPgYOV45K_:]kSI8^XlO0]GY=VUfe_C_F6TOcoAlVUH:o=WhhT@K`2KFhe<3\\KXQ>W:M?S_4S5d@J^`[AGA7@3]DnGSCO`\\?E8HT75^d9\\:m\\m1egIfk8cd6bD9\\eU8\\n[Pb0Cgd^S0n9kGJHb]i5XodlKHc34Fhi9K>0U5WK`>7Ff2^KL=WC6:kc?e5C^a1T1:4:^S5flXlGNIj08AfO?Dh7T7dWO>E]NI9?ob7B7P_h[4TEP[EU;GllFTnSmg9:\\[N]<SAoKP_kPlG56A:I3T6EG8Hj=XnUE`KT5U@OQ?]7[N^MFN1_NU4KO_3::Le`8IL9[1Z1H1;V3SC\\N3]S@4U[F2mhT5dYM7[4Pg_Na0_8WTH0`bgceQS8]EG;XgD4Ib4iLTP@kE79Mn>AYRJA1U5^Blhgno:aHVYc03c3J0Vc9FjEV^M75Zfd8kVC9>iJDk`AJ[6f7DK2D^DL\\AX:6b5h31XH;RQB\\N<ZSM=J;6L[`UW^eOIFc1Y]6_dfedIe4ARh72mTXC0WND_IDHVCZRDE0eODARCEETQI5TPUQE=jEH5bS?LP[ai`F5ABRYDo2o\\@=]GT?_9;hc4Lm:\\SF9k1T<0E@fX9BG[]g0nY7k[Qmi@la8`PF0j6@Q?Ii7bLkXQ<lLHf]`:DCh@9JY5>hEVLTdhL\\b1EB0lLh<=WaO@F<;8g<d:@e:LA:cFIEdmQh7hNHfSRToW?8N4:Z1K;XEDRO;OIDh<UdVln?bjgL>?VE98[B\\K<BVjkG8LiSX;fb>jf?DUK00Aih<WY6QD6cEnHBZ8iN_fd<G8Ci`11RUW2QlW]IXV:m?;J0GXXHfGNQ>:D`=fLPbO?VOTEYLj^cNj5PM>jKB5HVjJ4U7lXaTQNL9<@\\1`m\\Ug@VQHd7>jW=ca0`miF7;N0F=GjoQ`RFchKMGTmn8cF@Oh4GGCm7m2`U9j93Tb>=kSERjE_J939F01I1;`<ijk_=_Vn=7RVAI6fnQI5KlF:C44bN<<8K=Z<2TP<1]5?<dB>^LA=ebloE2Y2:9lkh0\\<YKbHD97iE`<C5oj^1>X:??`H6BXF2hG1Q[dF0Q=>W=J?7C\\k1T?<;R44oW?1hY^G8Zm]ZKnfOf0eCFYo6?=D8?<`6HU5SXh1;=:23LmV_FSi;OJfV<^?GkIDPISeHg1LaGE:V3Y3K3H<QJfbY?=;ldZRhnhQT_mGXDLFXXhSONE6Do_0iNZagB:BPGOTH;VhHUTd6LhQm^[;dO]5Hlkg<R:F<Kn\\:I:EGojgWZ2X@SYO_dlH;G8S<>oEKabY`:oU;=JW7ig?S?EYb86b7n8ce\\]IRa]koiWY<RfO;5kUI;7lVeC?[@ZaXDiF04B8R]bg@>O<mQDoUcBLcf^f>m2kMBUloD>Ze@NN^Z11TM`inXYhE_I=kA`:ZF4d\\>`L@;ZP[`ENU5cL[BV6\\Z?Di76:jg3hE6oG6jFc8kP=[GS1;WSedYQW1:U4\\OF32GgmMC<AjO]872bdBb`bKAA?8j78b>T3VfcUB2m4J^CPRU;8dScI]LU]^bBYA5_3:Y0N5i^?200000";var MersenneTwister=class MersenneTwister2{constructor(states,index2){this.states=states;this.index=index2}clone(){return new MersenneTwister2(this.states.slice(),this.index)}next(){let y=this.states[this.index];y^=y>>>U;y^=y<<S&B;y^=y<<T&C;y^=y>>>L;this.index=twistedNext(this.states,this.index);return y}getState(){return[this.index,...this.states]}jump(){const originalStates=this.states.slice();const originalIndex=this.index;this.index=twistedNext(this.states,this.index);for(let i=19932;i>0;--i){if(JUMP_COEFS.charCodeAt(i/6|0)-48&1<<i%6)addState(this.states,this.index,originalStates,originalIndex);this.index=twistedNext(this.states,this.index)}addState(this.states,this.index,originalStates,originalIndex)}};function addState(mt,idx,originalMt,originalIdx){let i=0;if(originalIdx>=idx){for(;i<N-originalIdx;i++)mt[i+idx]^=originalMt[i+originalIdx];for(;i<N-idx;i++)mt[i+idx]^=originalMt[i+originalIdx-N];for(;i<N;i++)mt[i+idx-N]^=originalMt[i+originalIdx-N]}else{for(;i<N-idx;i++)mt[i+idx]^=originalMt[i+originalIdx];for(;i<N-originalIdx;i++)mt[i+idx-N]^=originalMt[i+originalIdx];for(;i<N;i++)mt[i+idx-N]^=originalMt[i+originalIdx-N]}}function twistedNext(mt,idx){if(idx<N-M){const y=mt[idx]&MASK_UPPER|mt[idx+1]&MASK_LOWER;mt[idx]=mt[idx+M]^y>>>1^-(y&1)&A;return idx+1}else if(idx<N-1){const y=mt[idx]&MASK_UPPER|mt[idx+1]&MASK_LOWER;mt[idx]=mt[idx+M-N]^y>>>1^-(y&1)&A;return idx+1}else{const y=mt[idx]&MASK_UPPER|mt[0]&MASK_LOWER;mt[idx]=mt[M-1]^y>>>1^-(y&1)&A;return 0}}function twist(mt){for(let idx=0;idx!==N;++idx)twistedNext(mt,idx)}function mersenne(seed){const out=[seed|0];for(let idx=1;idx!==N;++idx){const xored=out[idx-1]^out[idx-1]>>>30;out.push(Math.imul(F,xored)+idx|0)}twist(out);return new MersenneTwister(out,0)}var jumps=[1667051007,2321340297,1548169110,304075285];var XorShift128Plus=class XorShift128Plus2{constructor(s01,s00,s11,s10){this.s01=s01;this.s00=s00;this.s11=s11;this.s10=s10}clone(){return new XorShift128Plus2(this.s01,this.s00,this.s11,this.s10)}next(){const a0=this.s00^this.s00<<23;const a1=this.s01^(this.s01<<23|this.s00>>>9);const s10=this.s10;const s11=this.s11;const out=this.s00+s10|0;this.s01=s11;this.s00=s10;this.s11=a1^s11^a1>>>18^s11>>>5;this.s10=a0^s10^(a0>>>18|a1<<14)^(s10>>>5|s11<<27);return out}jump(){let ns01=0;let ns00=0;let ns11=0;let ns10=0;let s01=this.s01;let s00=this.s00;let s11=this.s11;let s10=this.s10;for(let i=0;i!==4;++i){const ji=jumps[i];for(let mask2=1;mask2;mask2<<=1){if(ji&mask2){ns01^=s01;ns00^=s00;ns11^=s11;ns10^=s10}const a0=s00^s00<<23;const a1=s01^(s01<<23|s00>>>9);s01=s11;s00=s10;s10=a0^s10^(a0>>>18|a1<<14)^(s10>>>5|s11<<27);s11=a1^s11^a1>>>18^s11>>>5}}this.s01=ns01;this.s00=ns00;this.s11=ns11;this.s10=ns10}getState(){return[this.s01,this.s00,this.s11,this.s10]}};function xorshift128plus(seed){return new XorShift128Plus(-1,~seed,seed|0,0)}var jumps2=[3639956645,3750757012,1261568508,386426335];var XoroShiro128Plus=class XoroShiro128Plus2{constructor(s01,s00,s11,s10){this.s01=s01;this.s00=s00;this.s11=s11;this.s10=s10}clone(){return new XoroShiro128Plus2(this.s01,this.s00,this.s11,this.s10)}next(){const out=this.s00+this.s10|0;const a0=this.s10^this.s00;const a1=this.s11^this.s01;const s00=this.s00;const s01=this.s01;this.s00=s00<<24^s01>>>8^a0^a0<<16;this.s01=s01<<24^s00>>>8^a1^(a1<<16|a0>>>16);this.s10=a1<<5^a0>>>27;this.s11=a0<<5^a1>>>27;return out}jump(){let ns01=0;let ns00=0;let ns11=0;let ns10=0;let s01=this.s01;let s00=this.s00;let s11=this.s11;let s10=this.s10;for(let i=0;i!==4;++i){const ji=jumps2[i];for(let mask2=1;mask2;mask2<<=1){if(ji&mask2){ns01^=s01;ns00^=s00;ns11^=s11;ns10^=s10}const a0=s10^s00;const a1=s11^s01;const s00_=s00;const s01_=s01;s00=s00_<<24^s01_>>>8^a0^a0<<16;s01=s01_<<24^s00_>>>8^a1^(a1<<16|a0>>>16);s10=a1<<5^a0>>>27;s11=a0<<5^a1>>>27}}this.s01=ns01;this.s00=ns00;this.s11=ns11;this.s10=ns10}getState(){return[this.s01,this.s00,this.s11,this.s10]}};function xoroshiro128plus(seed){return new XoroShiro128Plus(-1,~seed,seed|0,0)}function skipN(rng,num){for(let idx=0;idx!==num;++idx)rng.next()}var SBigInt=BigInt;var NumValues=4294967296n;function uniformBigInt(rng,from,to){const diff=to-from+1n;let FinalNumValues=NumValues;let NumIterations=1;while(FinalNumValues<diff){FinalNumValues<<=32n;++NumIterations}let value3=generateNext(NumIterations,rng);if(value3<diff)return value3+from;if(value3+diff<FinalNumValues)return value3%diff+from;const MaxAcceptedRandom=FinalNumValues-FinalNumValues%diff;while(value3>=MaxAcceptedRandom)value3=generateNext(NumIterations,rng);return value3%diff+from}function generateNext(NumIterations,rng){let value3=SBigInt(rng.next()+2147483648);for(let num=1;num<NumIterations;++num){const out=rng.next();value3=(value3<<32n)+SBigInt(out+2147483648)}return value3}function uniformIntInternal(rng,rangeSize){const MaxAllowed=rangeSize>2?~~(4294967296/rangeSize)*rangeSize:4294967296;let deltaV=rng.next()+2147483648;while(deltaV>=MaxAllowed)deltaV=rng.next()+2147483648;return deltaV%rangeSize}function fromNumberToArrayInt64(out,n){if(n<0){const posN=-n;out.sign=-1;out.data[0]=~~(posN/4294967296);out.data[1]=posN>>>0}else{out.sign=1;out.data[0]=~~(n/4294967296);out.data[1]=n>>>0}return out}function substractArrayInt64(out,arrayIntA,arrayIntB){const lowA=arrayIntA.data[1];const highA=arrayIntA.data[0];const signA=arrayIntA.sign;const lowB=arrayIntB.data[1];const highB=arrayIntB.data[0];const signB=arrayIntB.sign;out.sign=1;if(signA===1&&signB===-1){const low2=lowA+lowB;const high=highA+highB+(low2>4294967295?1:0);out.data[0]=high>>>0;out.data[1]=low2>>>0;return out}let lowFirst=lowA;let highFirst=highA;let lowSecond=lowB;let highSecond=highB;if(signA===-1){lowFirst=lowB;highFirst=highB;lowSecond=lowA;highSecond=highA}let reminderLow=0;let low=lowFirst-lowSecond;if(low<0){reminderLow=1;low=low>>>0}out.data[0]=highFirst-highSecond-reminderLow;out.data[1]=low;return out}function uniformArrayIntInternal(rng,out,rangeSize){const maxIndex0=rangeSize[0]+1;out[0]=uniformIntInternal(rng,maxIndex0);out[1]=uniformIntInternal(rng,4294967296);while(out[0]>=rangeSize[0]&&(out[0]!==rangeSize[0]||out[1]>=rangeSize[1])){out[0]=uniformIntInternal(rng,maxIndex0);out[1]=uniformIntInternal(rng,4294967296)}return out}var safeNumberMaxSafeInteger=Number.MAX_SAFE_INTEGER;var sharedA={sign:1,data:[0,0]};var sharedB={sign:1,data:[0,0]};var sharedC={sign:1,data:[0,0]};var sharedData=[0,0];function uniformLargeIntInternal(rng,from,to,rangeSize){const rangeSizeArrayIntValue=rangeSize<=safeNumberMaxSafeInteger?fromNumberToArrayInt64(sharedC,rangeSize):substractArrayInt64(sharedC,fromNumberToArrayInt64(sharedA,to),fromNumberToArrayInt64(sharedB,from));if(rangeSizeArrayIntValue.data[1]===4294967295){rangeSizeArrayIntValue.data[0]+=1;rangeSizeArrayIntValue.data[1]=0}else rangeSizeArrayIntValue.data[1]+=1;uniformArrayIntInternal(rng,sharedData,rangeSizeArrayIntValue.data);return sharedData[0]*4294967296+sharedData[1]+from}function uniformInt(rng,from,to){const rangeSize=to-from;if(rangeSize<=4294967295)return uniformIntInternal(rng,rangeSize+1)+from;return uniformLargeIntInternal(rng,from,to,rangeSize)}var SharedFootPrint=Symbol.for("fast-check/PreconditionFailure");var PreconditionFailure=class extends Error{constructor(interruptExecution=false){super();this.interruptExecution=interruptExecution;this.footprint=SharedFootPrint}static isFailure(err){return err!==null&&err!==undefined&&err.footprint===SharedFootPrint}};function pre(expectTruthy){if(!expectTruthy)throw new PreconditionFailure}var Nil=class{[Symbol.iterator](){return this}next(value3){return{value:value3,done:true}}};var nil=new Nil;function nilHelper(){return nil}function*mapHelper(g,f){for(const v of g)yield f(v)}function*flatMapHelper(g,f){for(const v of g)yield*f(v)}function*filterHelper(g,f){for(const v of g)if(f(v))yield v}function*takeNHelper(g,n){for(let i=0;i<n;++i){const cur=g.next();if(cur.done)break;yield cur.value}}function*takeWhileHelper(g,f){let cur=g.next();while(!cur.done&&f(cur.value)){yield cur.value;cur=g.next()}}function*joinHelper(g,others){for(let cur=g.next();!cur.done;cur=g.next())yield cur.value;for(const s of others)for(let cur=s.next();!cur.done;cur=s.next())yield cur.value}var safeSymbolIterator$1=Symbol.iterator;var Stream=class Stream2{static nil(){return new Stream2(nilHelper())}static of(...elements){return new Stream2(elements[safeSymbolIterator$1]())}constructor(g){this.g=g}next(){return this.g.next()}[Symbol.iterator](){return this.g}map(f){return new Stream2(mapHelper(this.g,f))}flatMap(f){return new Stream2(flatMapHelper(this.g,f))}dropWhile(f){let foundEligible=false;function*helper(v){if(foundEligible||!f(v)){foundEligible=true;yield v}}return this.flatMap(helper)}drop(n){if(n<=0)return this;let idx=0;function helper(){return idx++<n}return this.dropWhile(helper)}takeWhile(f){return new Stream2(takeWhileHelper(this.g,f))}take(n){return new Stream2(takeNHelper(this.g,n))}filter(f){return new Stream2(filterHelper(this.g,f))}every(f){for(const v of this.g)if(!f(v))return false;return true}has(f){for(const v of this.g)if(f(v))return[true,v];return[false,null]}join(...others){return new Stream2(joinHelper(this.g,others))}getNthOrLast(nth){let remaining=nth;let last=null;for(const v of this.g){if(remaining--===0)return v;last=v}return last}};function stream(g){return new Stream(g)}var cloneMethod=Symbol.for("fast-check/cloneMethod");function hasCloneMethod(instance){return instance!==null&&(typeof instance==="object"||typeof instance==="function")&&cloneMethod in instance&&typeof instance[cloneMethod]==="function"}function cloneIfNeeded(instance){return hasCloneMethod(instance)?instance[cloneMethod]():instance}var safeObjectDefineProperty$4=Object.defineProperty;var Value=class{constructor(value_,context3,customGetValue){this.value_=value_;this.context=context3;this.hasToBeCloned=customGetValue!==undefined||hasCloneMethod(value_);this.readOnce=false;this.value=value_;if(this.hasToBeCloned)safeObjectDefineProperty$4(this,"value",{get:customGetValue!==undefined?customGetValue:this.getValue,enumerable:false,configurable:false})}getValue(){if(this.hasToBeCloned){if(!this.readOnce){this.readOnce=true;return this.value_}return this.value_[cloneMethod]()}return this.value_}};var Arbitrary=class{filter(refinement){return new FilterArbitrary(this,refinement)}map(mapper,unmapper){return new MapArbitrary(this,mapper,unmapper)}chain(chainer){return new ChainArbitrary(this,chainer)}};var ChainArbitrary=class extends Arbitrary{constructor(arb,chainer){super();this.arb=arb;this.chainer=chainer}generate(mrng,biasFactor){const clonedMrng=mrng.clone();const src=this.arb.generate(mrng,biasFactor);return this.valueChainer(src,mrng,clonedMrng,biasFactor)}canShrinkWithoutContext(_value){return false}shrink(value3,context3){if(this.isSafeContext(context3))return(!context3.stoppedForOriginal?this.arb.shrink(context3.originalValue,context3.originalContext).map((v)=>this.valueChainer(v,context3.clonedMrng.clone(),context3.clonedMrng,context3.originalBias)):Stream.nil()).join(context3.chainedArbitrary.shrink(value3,context3.chainedContext).map((dst)=>{const newContext={...context3,chainedContext:dst.context,stoppedForOriginal:true};return new Value(dst.value_,newContext)}));return Stream.nil()}valueChainer(v,generateMrng,clonedMrng,biasFactor){const chainedArbitrary=this.chainer(v.value_);const dst=chainedArbitrary.generate(generateMrng,biasFactor);const context3={originalBias:biasFactor,originalValue:v.value_,originalContext:v.context,stoppedForOriginal:false,chainedArbitrary,chainedContext:dst.context,clonedMrng};return new Value(dst.value_,context3)}isSafeContext(context3){return context3!==null&&context3!==undefined&&typeof context3==="object"&&"originalBias"in context3&&"originalValue"in context3&&"originalContext"in context3&&"stoppedForOriginal"in context3&&"chainedArbitrary"in context3&&"chainedContext"in context3&&"clonedMrng"in context3}};function mapperWithCloneIfNeeded(v,mapper){const sourceValue=v.value;const mappedValue=mapper(sourceValue);if(v.hasToBeCloned&&(typeof mappedValue==="object"&&mappedValue!==null||typeof mappedValue==="function")&&Object.isExtensible(mappedValue)&&!hasCloneMethod(mappedValue))Object.defineProperty(mappedValue,cloneMethod,{get:()=>()=>mapperWithCloneIfNeeded(v,mapper)[0]});return[mappedValue,sourceValue]}function valueMapper(v,mapper){const[mappedValue,sourceValue]=mapperWithCloneIfNeeded(v,mapper);return new Value(mappedValue,{originalValue:sourceValue,originalContext:v.context})}var MapArbitrary=class extends Arbitrary{constructor(arb,mapper,unmapper){super();this.arb=arb;this.mapper=mapper;this.unmapper=unmapper;this.bindValueMapper=(v)=>valueMapper(v,mapper)}generate(mrng,biasFactor){const g=this.arb.generate(mrng,biasFactor);if(!g.hasToBeCloned){const sourceValue=g.value;return new Value(this.mapper(sourceValue),{originalValue:sourceValue,originalContext:g.context})}return valueMapper(g,this.mapper)}canShrinkWithoutContext(value3){if(this.unmapper!==undefined)try{const unmapped=this.unmapper(value3);return this.arb.canShrinkWithoutContext(unmapped)}catch{return false}return false}shrink(value3,context3){if(this.isSafeContext(context3))return this.arb.shrink(context3.originalValue,context3.originalContext).map(this.bindValueMapper);if(this.unmapper!==undefined){const unmapped=this.unmapper(value3);return this.arb.shrink(unmapped,undefined).map(this.bindValueMapper)}return Stream.nil()}isSafeContext(context3){return context3!==null&&context3!==undefined&&typeof context3==="object"&&"originalValue"in context3&&"originalContext"in context3}};var FilterArbitrary=class extends Arbitrary{constructor(arb,refinement){super();this.arb=arb;this.refinement=refinement;this.bindRefinementOnValue=(v)=>this.refinementOnValue(v)}generate(mrng,biasFactor){while(true){const g=this.arb.generate(mrng,biasFactor);if(this.refinementOnValue(g))return g}}canShrinkWithoutContext(value3){return this.arb.canShrinkWithoutContext(value3)&&this.refinement(value3)}shrink(value3,context3){return this.arb.shrink(value3,context3).filter(this.bindRefinementOnValue)}refinementOnValue(v){return this.refinement(v.value)}};function isArbitrary(instance){return typeof instance==="object"&&instance!==null&&"generate"in instance&&"shrink"in instance&&"canShrinkWithoutContext"in instance}function assertIsArbitrary(instance){if(!isArbitrary(instance))throw new Error("Unexpected value received: not an instance of Arbitrary")}var untouchedApply=Function.prototype.apply;var ApplySymbol=Symbol("apply");function safeExtractApply(f){try{return f.apply}catch{return}}function safeApplyHacky(f,instance,args2){const ff=f;ff[ApplySymbol]=untouchedApply;const out=ff[ApplySymbol](instance,args2);delete ff[ApplySymbol];return out}function safeApply(f,instance,args2){if(safeExtractApply(f)===untouchedApply)return f.apply(instance,args2);return safeApplyHacky(f,instance,args2)}var SArray=Array;var SBigInt2=BigInt;var SBigInt64Array=BigInt64Array;var SBigUint64Array=BigUint64Array;var SBoolean=Boolean;var SDate=Date;var SError=Error;var SFloat32Array=Float32Array;var SFloat64Array=Float64Array;var SInt8Array=Int8Array;var SInt16Array=Int16Array;var SInt32Array=Int32Array;var SNumber=Number;var SString=String;var SSet=Set;var SUint8Array=Uint8Array;var SUint8ClampedArray=Uint8ClampedArray;var SUint16Array=Uint16Array;var SUint32Array=Uint32Array;var SencodeURIComponent=encodeURIComponent;var SMap$1=Map;var SSymbol=Symbol;var untouchedForEach=Array.prototype.forEach;var untouchedIndexOf=Array.prototype.indexOf;var untouchedJoin=Array.prototype.join;var untouchedMap=Array.prototype.map;var untouchedFlat=Array.prototype.flat;var untouchedFilter=Array.prototype.filter;var untouchedPush=Array.prototype.push;var untouchedPop=Array.prototype.pop;var untouchedSplice=Array.prototype.splice;var untouchedSlice=Array.prototype.slice;var untouchedSort=Array.prototype.sort;var untouchedEvery=Array.prototype.every;function extractForEach(instance){try{return instance.forEach}catch{return}}function extractIndexOf(instance){try{return instance.indexOf}catch{return}}function extractJoin(instance){try{return instance.join}catch{return}}function extractMap(instance){try{return instance.map}catch{return}}function extractFlat(instance){try{return instance.flat}catch{return}}function extractFilter(instance){try{return instance.filter}catch{return}}function extractPush(instance){try{return instance.push}catch{return}}function extractPop(instance){try{return instance.pop}catch{return}}function extractSplice(instance){try{return instance.splice}catch{return}}function extractSlice(instance){try{return instance.slice}catch{return}}function extractSort(instance){try{return instance.sort}catch{return}}function extractEvery(instance){try{return instance.every}catch{return}}function safeForEach(instance,fn3){if(extractForEach(instance)===untouchedForEach)return instance.forEach(fn3);return safeApply(untouchedForEach,instance,[fn3])}function safeIndexOf(instance,...args2){if(extractIndexOf(instance)===untouchedIndexOf)return instance.indexOf(...args2);return safeApply(untouchedIndexOf,instance,args2)}function safeJoin(instance,...args2){if(extractJoin(instance)===untouchedJoin)return instance.join(...args2);return safeApply(untouchedJoin,instance,args2)}function safeMap(instance,fn3){if(extractMap(instance)===untouchedMap)return instance.map(fn3);return safeApply(untouchedMap,instance,[fn3])}function safeFlat(instance,depth){if(extractFlat(instance)===untouchedFlat){[].flat();return instance.flat(depth)}return safeApply(untouchedFlat,instance,[depth])}function safeFilter(instance,predicate){if(extractFilter(instance)===untouchedFilter)return instance.filter(predicate);return safeApply(untouchedFilter,instance,[predicate])}function safePush(instance,...args2){if(extractPush(instance)===untouchedPush)return instance.push(...args2);return safeApply(untouchedPush,instance,args2)}function safePop$1(instance){if(extractPop(instance)===untouchedPop)return instance.pop();return safeApply(untouchedPop,instance,[])}function safeSplice(instance,...args2){if(extractSplice(instance)===untouchedSplice)return instance.splice(...args2);return safeApply(untouchedSplice,instance,args2)}function safeSlice(instance,...args2){if(extractSlice(instance)===untouchedSlice)return instance.slice(...args2);return safeApply(untouchedSlice,instance,args2)}function safeSort(instance,...args2){if(extractSort(instance)===untouchedSort)return instance.sort(...args2);return safeApply(untouchedSort,instance,args2)}function safeEvery(instance,...args2){if(extractEvery(instance)===untouchedEvery)return instance.every(...args2);return safeApply(untouchedEvery,instance,args2)}var untouchedGetTime=Date.prototype.getTime;var untouchedToISOString=Date.prototype.toISOString;function extractGetTime(instance){try{return instance.getTime}catch{return}}function extractToISOString(instance){try{return instance.toISOString}catch{return}}function safeGetTime(instance){if(extractGetTime(instance)===untouchedGetTime)return instance.getTime();return safeApply(untouchedGetTime,instance,[])}function safeToISOString(instance){if(extractToISOString(instance)===untouchedToISOString)return instance.toISOString();return safeApply(untouchedToISOString,instance,[])}var untouchedAdd=Set.prototype.add;var untouchedHas=Set.prototype.has;function extractAdd(instance){try{return instance.add}catch{return}}function extractHas(instance){try{return instance.has}catch(err){return}}function safeAdd(instance,value3){if(extractAdd(instance)===untouchedAdd)return instance.add(value3);return safeApply(untouchedAdd,instance,[value3])}function safeHas(instance,value3){if(extractHas(instance)===untouchedHas)return instance.has(value3);return safeApply(untouchedHas,instance,[value3])}var untouchedSet=WeakMap.prototype.set;var untouchedGet=WeakMap.prototype.get;function extractSet(instance){try{return instance.set}catch(err){return}}function extractGet(instance){try{return instance.get}catch(err){return}}function safeSet(instance,key,value3){if(extractSet(instance)===untouchedSet)return instance.set(key,value3);return safeApply(untouchedSet,instance,[key,value3])}function safeGet(instance,key){if(extractGet(instance)===untouchedGet)return instance.get(key);return safeApply(untouchedGet,instance,[key])}var untouchedMapSet=Map.prototype.set;var untouchedMapGet=Map.prototype.get;var untouchedMapHas=Map.prototype.has;function extractMapSet(instance){try{return instance.set}catch(err){return}}function extractMapGet(instance){try{return instance.get}catch(err){return}}function extractMapHas(instance){try{return instance.has}catch(err){return}}function safeMapSet(instance,key,value3){if(extractMapSet(instance)===untouchedMapSet)return instance.set(key,value3);return safeApply(untouchedMapSet,instance,[key,value3])}function safeMapGet(instance,key){if(extractMapGet(instance)===untouchedMapGet)return instance.get(key);return safeApply(untouchedMapGet,instance,[key])}function safeMapHas(instance,key){if(extractMapHas(instance)===untouchedMapHas)return instance.has(key);return safeApply(untouchedMapHas,instance,[key])}var untouchedSplit=String.prototype.split;var untouchedStartsWith=String.prototype.startsWith;var untouchedEndsWith=String.prototype.endsWith;var untouchedSubstring=String.prototype.substring;var untouchedToLowerCase=String.prototype.toLowerCase;var untouchedToUpperCase=String.prototype.toUpperCase;var untouchedPadStart=String.prototype.padStart;var untouchedCharCodeAt=String.prototype.charCodeAt;var untouchedNormalize=String.prototype.normalize;var untouchedReplace=String.prototype.replace;function extractSplit(instance){try{return instance.split}catch{return}}function extractStartsWith(instance){try{return instance.startsWith}catch{return}}function extractEndsWith(instance){try{return instance.endsWith}catch{return}}function extractSubstring(instance){try{return instance.substring}catch{return}}function extractToLowerCase(instance){try{return instance.toLowerCase}catch{return}}function extractToUpperCase(instance){try{return instance.toUpperCase}catch{return}}function extractPadStart(instance){try{return instance.padStart}catch{return}}function extractCharCodeAt(instance){try{return instance.charCodeAt}catch{return}}function extractNormalize(instance){try{return instance.normalize}catch(err){return}}function extractReplace(instance){try{return instance.replace}catch{return}}function safeSplit(instance,...args2){if(extractSplit(instance)===untouchedSplit)return instance.split(...args2);return safeApply(untouchedSplit,instance,args2)}function safeStartsWith(instance,...args2){if(extractStartsWith(instance)===untouchedStartsWith)return instance.startsWith(...args2);return safeApply(untouchedStartsWith,instance,args2)}function safeEndsWith(instance,...args2){if(extractEndsWith(instance)===untouchedEndsWith)return instance.endsWith(...args2);return safeApply(untouchedEndsWith,instance,args2)}function safeSubstring(instance,...args2){if(extractSubstring(instance)===untouchedSubstring)return instance.substring(...args2);return safeApply(untouchedSubstring,instance,args2)}function safeToLowerCase(instance){if(extractToLowerCase(instance)===untouchedToLowerCase)return instance.toLowerCase();return safeApply(untouchedToLowerCase,instance,[])}function safeToUpperCase(instance){if(extractToUpperCase(instance)===untouchedToUpperCase)return instance.toUpperCase();return safeApply(untouchedToUpperCase,instance,[])}function safePadStart(instance,...args2){if(extractPadStart(instance)===untouchedPadStart)return instance.padStart(...args2);return safeApply(untouchedPadStart,instance,args2)}function safeCharCodeAt(instance,index2){if(extractCharCodeAt(instance)===untouchedCharCodeAt)return instance.charCodeAt(index2);return safeApply(untouchedCharCodeAt,instance,[index2])}function safeNormalize(instance,form){if(extractNormalize(instance)===untouchedNormalize)return instance.normalize(form);return safeApply(untouchedNormalize,instance,[form])}function safeReplace(instance,pattern,replacement){if(extractReplace(instance)===untouchedReplace)return instance.replace(pattern,replacement);return safeApply(untouchedReplace,instance,[pattern,replacement])}var untouchedNumberToString=Number.prototype.toString;function extractNumberToString(instance){try{return instance.toString}catch{return}}function safeNumberToString(instance,...args2){if(extractNumberToString(instance)===untouchedNumberToString)return instance.toString(...args2);return safeApply(untouchedNumberToString,instance,args2)}var untouchedHasOwnProperty=Object.prototype.hasOwnProperty;var untouchedToString=Object.prototype.toString;function safeHasOwnProperty(instance,v){return safeApply(untouchedHasOwnProperty,instance,[v])}function safeToString2(instance){return safeApply(untouchedToString,instance,[])}var untouchedErrorToString=Error.prototype.toString;function safeErrorToString(instance){return safeApply(untouchedErrorToString,instance,[])}var LazyIterableIterator=class{constructor(producer){this.producer=producer}[Symbol.iterator](){if(this.it===undefined)this.it=this.producer();return this.it}next(){if(this.it===undefined)this.it=this.producer();return this.it.next()}};function makeLazy2(producer){return new LazyIterableIterator(producer)}var safeArrayIsArray$4=Array.isArray;var safeObjectDefineProperty$3=Object.defineProperty;function tupleMakeItCloneable(vs,ctxs,values3){return safeObjectDefineProperty$3(vs,cloneMethod,{value:()=>{const cloned=[];for(let idx=0;idx!==values3.length;++idx){let current=values3[idx];if(current===undefined)current=new Value(vs[idx],ctxs[idx]);safePush(cloned,current.value)}tupleMakeItCloneable(cloned,ctxs,values3);return cloned}})}function tupleShrink(arbs,value3,context3){const shrinks=[];const safeContext=safeArrayIsArray$4(context3)?context3:[];for(let idx=0;idx!==arbs.length;++idx)safePush(shrinks,makeLazy2(()=>arbs[idx].shrink(value3[idx],safeContext[idx]).map((v)=>{let cloneable=false;const vs=[];const ctxs=[];const mapped=[];for(let nestedIdx=0;nestedIdx!==arbs.length;++nestedIdx){const nestedV=nestedIdx===idx?v:new Value(cloneIfNeeded(value3[nestedIdx]),safeContext[nestedIdx]);if(nestedV.hasToBeCloned){cloneable=true;mapped[nestedIdx]=nestedV}safePush(vs,nestedV.value);safePush(ctxs,nestedV.context)}if(cloneable)tupleMakeItCloneable(vs,ctxs,mapped);return new Value(vs,ctxs)})));return Stream.nil().join(...shrinks)}var TupleArbitrary=class extends Arbitrary{constructor(arbs){super();this.arbs=arbs;for(let idx=0;idx!==arbs.length;++idx){const arb=arbs[idx];if(arb===null||arb===undefined||arb.generate===null||arb.generate===undefined)throw new Error(`Invalid parameter encountered at index ${idx}: expecting an Arbitrary`)}}generate(mrng,biasFactor){let cloneable=false;const vs=[];const ctxs=[];const mapped=[];for(let idx=0;idx!==this.arbs.length;++idx){const v=this.arbs[idx].generate(mrng,biasFactor);if(v.hasToBeCloned){cloneable=true;mapped[idx]=v}safePush(vs,v.value);safePush(ctxs,v.context)}if(cloneable)tupleMakeItCloneable(vs,ctxs,mapped);return new Value(vs,ctxs)}canShrinkWithoutContext(value3){if(!safeArrayIsArray$4(value3)||value3.length!==this.arbs.length)return false;for(let index2=0;index2!==this.arbs.length;++index2)if(!this.arbs[index2].canShrinkWithoutContext(value3[index2]))return false;return true}shrink(value3,context3){return tupleShrink(this.arbs,value3,context3)}};function tuple2(...arbs){return new TupleArbitrary(arbs)}var safeMathLog$3=Math.log;function runIdToFrequency(runId){return 2+~~(safeMathLog$3(runId+1)*0.4342944819032518)}var globalParameters={};function configureGlobal(parameters){globalParameters=parameters}function readConfigureGlobal(){return globalParameters}function resetConfigureGlobal(){globalParameters={}}var UndefinedContextPlaceholder=Symbol("UndefinedContextPlaceholder");function noUndefinedAsContext(value3){if(value3.context!==undefined)return value3;if(value3.hasToBeCloned)return new Value(value3.value_,UndefinedContextPlaceholder,()=>value3.value);return new Value(value3.value_,UndefinedContextPlaceholder)}var dummyHook$1=()=>{};var AsyncProperty=class{constructor(arb,predicate){this.arb=arb;this.predicate=predicate;const{asyncBeforeEach,asyncAfterEach,beforeEach,afterEach}=readConfigureGlobal()||{};if(asyncBeforeEach!==undefined&&beforeEach!==undefined)throw SError(`Global "asyncBeforeEach" and "beforeEach" parameters can't be set at the same time when running async properties`);if(asyncAfterEach!==undefined&&afterEach!==undefined)throw SError(`Global "asyncAfterEach" and "afterEach" parameters can't be set at the same time when running async properties`);this.beforeEachHook=asyncBeforeEach||beforeEach||dummyHook$1;this.afterEachHook=asyncAfterEach||afterEach||dummyHook$1}isAsync(){return true}generate(mrng,runId){return noUndefinedAsContext(this.arb.generate(mrng,runId!==undefined?runIdToFrequency(runId):undefined))}shrink(value3){if(value3.context===undefined&&!this.arb.canShrinkWithoutContext(value3.value_))return Stream.nil();const safeContext=value3.context!==UndefinedContextPlaceholder?value3.context:undefined;return this.arb.shrink(value3.value_,safeContext).map(noUndefinedAsContext)}async runBeforeEach(){await this.beforeEachHook()}async runAfterEach(){await this.afterEachHook()}async run(v){try{const output=await this.predicate(v);return output===undefined||output===true?null:{error:new SError("Property failed by returning false")}}catch(err){if(PreconditionFailure.isFailure(err))return err;return{error:err}}}beforeEach(hookFunction){const previousBeforeEachHook=this.beforeEachHook;this.beforeEachHook=()=>hookFunction(previousBeforeEachHook);return this}afterEach(hookFunction){const previousAfterEachHook=this.afterEachHook;this.afterEachHook=()=>hookFunction(previousAfterEachHook);return this}};var AlwaysShrinkableArbitrary=class extends Arbitrary{constructor(arb){super();this.arb=arb}generate(mrng,biasFactor){return noUndefinedAsContext(this.arb.generate(mrng,biasFactor))}canShrinkWithoutContext(_value){return true}shrink(value3,context3){if(context3===undefined&&!this.arb.canShrinkWithoutContext(value3))return Stream.nil();const safeContext=context3!==UndefinedContextPlaceholder?context3:undefined;return this.arb.shrink(value3,safeContext).map(noUndefinedAsContext)}};function asyncProperty(...args2){if(args2.length<2)throw new Error("asyncProperty expects at least two parameters");const arbs=safeSlice(args2,0,args2.length-1);const p=args2[args2.length-1];safeForEach(arbs,assertIsArbitrary);return new AsyncProperty(tuple2(...safeMap(arbs,(arb)=>new AlwaysShrinkableArbitrary(arb))),(t)=>p(...t))}var dummyHook=()=>{};var Property=class{constructor(arb,predicate){this.arb=arb;this.predicate=predicate;const{beforeEach=dummyHook,afterEach=dummyHook,asyncBeforeEach,asyncAfterEach}=readConfigureGlobal()||{};if(asyncBeforeEach!==undefined)throw SError(`"asyncBeforeEach" can't be set when running synchronous properties`);if(asyncAfterEach!==undefined)throw SError(`"asyncAfterEach" can't be set when running synchronous properties`);this.beforeEachHook=beforeEach;this.afterEachHook=afterEach}isAsync(){return false}generate(mrng,runId){return noUndefinedAsContext(this.arb.generate(mrng,runId!==undefined?runIdToFrequency(runId):undefined))}shrink(value3){if(value3.context===undefined&&!this.arb.canShrinkWithoutContext(value3.value_))return Stream.nil();const safeContext=value3.context!==UndefinedContextPlaceholder?value3.context:undefined;return this.arb.shrink(value3.value_,safeContext).map(noUndefinedAsContext)}runBeforeEach(){this.beforeEachHook()}runAfterEach(){this.afterEachHook()}run(v){try{const output=this.predicate(v);return output===undefined||output===true?null:{error:new SError("Property failed by returning false")}}catch(err){if(PreconditionFailure.isFailure(err))return err;return{error:err}}}beforeEach(hookFunction){const previousBeforeEachHook=this.beforeEachHook;this.beforeEachHook=()=>hookFunction(previousBeforeEachHook);return this}afterEach(hookFunction){const previousAfterEachHook=this.afterEachHook;this.afterEachHook=()=>hookFunction(previousAfterEachHook);return this}};function property(...args2){if(args2.length<2)throw new Error("property expects at least two parameters");const arbs=safeSlice(args2,0,args2.length-1);const p=args2[args2.length-1];safeForEach(arbs,assertIsArbitrary);return new Property(tuple2(...safeMap(arbs,(arb)=>new AlwaysShrinkableArbitrary(arb))),(t)=>p(...t))}var VerbosityLevel=function(VerbosityLevel2){VerbosityLevel2[VerbosityLevel2["None"]=0]="None";VerbosityLevel2[VerbosityLevel2["Verbose"]=1]="Verbose";VerbosityLevel2[VerbosityLevel2["VeryVerbose"]=2]="VeryVerbose";return VerbosityLevel2}({});function adaptRandomGeneratorTo8x(rng){if("unsafeNext"in rng){if(rng.unsafeJump===undefined)return{clone:()=>adaptRandomGeneratorTo8x(rng),next:()=>rng.unsafeNext(),getState:()=>rng.getState()};return{clone:()=>adaptRandomGeneratorTo8x(rng),next:()=>rng.unsafeNext(),jump:()=>rng.unsafeJump(),getState:()=>rng.getState()}}return rng}function adaptRandomGeneratorToInternal(rng){if("jump"in rng&&typeof rng.jump==="function")return rng;return{clone:()=>adaptRandomGeneratorToInternal(rng),next:()=>rng.next(),jump:()=>skipN(rng,42),getState:()=>rng.getState()}}function adaptRandomGenerator(rng){return adaptRandomGeneratorToInternal(adaptRandomGeneratorTo8x(rng))}var safeDateNow$1=Date.now;var safeMathMin$6=Math.min;var safeMathRandom=Math.random;var QualifiedParameters=class{constructor(op){const p=op||{};this.seed=readSeed(p);this.randomType=readRandomType(p);this.numRuns=readNumRuns(p);this.verbose=readVerbose(p);this.maxSkipsPerRun=p.maxSkipsPerRun!==undefined?p.maxSkipsPerRun:100;this.timeout=safeTimeout(p.timeout);this.skipAllAfterTimeLimit=safeTimeout(p.skipAllAfterTimeLimit);this.interruptAfterTimeLimit=safeTimeout(p.interruptAfterTimeLimit);this.markInterruptAsFailure=p.markInterruptAsFailure===true;this.skipEqualValues=p.skipEqualValues===true;this.ignoreEqualValues=p.ignoreEqualValues===true;this.logger=p.logger!==undefined?p.logger:(v)=>{console.log(v)};this.path=p.path!==undefined?p.path:"";this.unbiased=p.unbiased===true;this.examples=p.examples!==undefined?p.examples:[];this.endOnFailure=p.endOnFailure===true;this.reporter=p.reporter;this.asyncReporter=p.asyncReporter;this.includeErrorInReport=p.includeErrorInReport===true}toParameters(){return{seed:this.seed,randomType:this.randomType,numRuns:this.numRuns,maxSkipsPerRun:this.maxSkipsPerRun,timeout:this.timeout,skipAllAfterTimeLimit:this.skipAllAfterTimeLimit,interruptAfterTimeLimit:this.interruptAfterTimeLimit,markInterruptAsFailure:this.markInterruptAsFailure,skipEqualValues:this.skipEqualValues,ignoreEqualValues:this.ignoreEqualValues,path:this.path,logger:this.logger,unbiased:this.unbiased,verbose:this.verbose,examples:this.examples,endOnFailure:this.endOnFailure,reporter:this.reporter,asyncReporter:this.asyncReporter,includeErrorInReport:this.includeErrorInReport}}};function createQualifiedRandomGenerator(random2){return(seed)=>{return adaptRandomGenerator(random2(seed))}}function readSeed(p){if(p.seed===undefined)return safeDateNow$1()^safeMathRandom()*4294967296;const seed32=p.seed|0;if(p.seed===seed32)return seed32;return seed32^(p.seed-seed32)*4294967296}function readRandomType(p){if(p.randomType===undefined)return xorshift128plus;if(typeof p.randomType==="string")switch(p.randomType){case"mersenne":return createQualifiedRandomGenerator(mersenne);case"congruential":case"congruential32":return createQualifiedRandomGenerator(congruential32);case"xorshift128plus":return xorshift128plus;case"xoroshiro128plus":return xoroshiro128plus;default:throw new Error(`Invalid random specified: '${p.randomType}'`)}const mrng=p.randomType(0);if("min"in mrng&&mrng.min!==-2147483648)throw new Error(`Invalid random number generator: min must equal -0x80000000, got ${String(mrng.min)}`);if("max"in mrng&&mrng.max!==2147483647)throw new Error(`Invalid random number generator: max must equal 0x7fffffff, got ${String(mrng.max)}`);if(mrng===adaptRandomGenerator(mrng))return p.randomType;return createQualifiedRandomGenerator(p.randomType)}function readNumRuns(p){const defaultValue=100;if(p.numRuns!==undefined)return p.numRuns;if(p.num_runs!==undefined)return p.num_runs;return defaultValue}function readVerbose(p){if(p.verbose===undefined)return 0;if(typeof p.verbose==="boolean")return p.verbose===true?1:0;if(p.verbose<=0)return 0;if(p.verbose>=2)return 2;return p.verbose|0}function safeTimeout(value3){if(value3===undefined)return;return safeMathMin$6(value3,2147483647)}function read(op){return new QualifiedParameters(op)}function interruptAfter(timeMs,setTimeoutSafe,clearTimeoutSafe){let timeoutHandle=null;return{clear:()=>clearTimeoutSafe(timeoutHandle),promise:new Promise((resolve4)=>{timeoutHandle=setTimeoutSafe(()=>{resolve4(new PreconditionFailure(true))},timeMs)})}}var SkipAfterProperty=class{constructor(property2,getTime,timeLimit,interruptExecution,setTimeoutSafe,clearTimeoutSafe){this.property=property2;this.getTime=getTime;this.interruptExecution=interruptExecution;this.setTimeoutSafe=setTimeoutSafe;this.clearTimeoutSafe=clearTimeoutSafe;this.skipAfterTime=this.getTime()+timeLimit}isAsync(){return this.property.isAsync()}generate(mrng,runId){return this.property.generate(mrng,runId)}shrink(value3){return this.property.shrink(value3)}run(v){const remainingTime=this.skipAfterTime-this.getTime();if(remainingTime<=0){const preconditionFailure=new PreconditionFailure(this.interruptExecution);if(this.isAsync())return Promise.resolve(preconditionFailure);else return preconditionFailure}if(this.interruptExecution&&this.isAsync()){const t=interruptAfter(remainingTime,this.setTimeoutSafe,this.clearTimeoutSafe);const propRun=Promise.race([this.property.run(v),t.promise]);propRun.then(t.clear,t.clear);return propRun}return this.property.run(v)}runBeforeEach(){return this.property.runBeforeEach()}runAfterEach(){return this.property.runAfterEach()}};var timeoutAfter=(timeMs,setTimeoutSafe,clearTimeoutSafe)=>{let timeoutHandle=null;return{clear:()=>clearTimeoutSafe(timeoutHandle),promise:new Promise((resolve4)=>{timeoutHandle=setTimeoutSafe(()=>{resolve4({error:new SError(`Property timeout: exceeded limit of ${timeMs} milliseconds`)})},timeMs)})}};var TimeoutProperty=class{constructor(property2,timeMs,setTimeoutSafe,clearTimeoutSafe){this.property=property2;this.timeMs=timeMs;this.setTimeoutSafe=setTimeoutSafe;this.clearTimeoutSafe=clearTimeoutSafe}isAsync(){return true}generate(mrng,runId){return this.property.generate(mrng,runId)}shrink(value3){return this.property.shrink(value3)}async run(v){const t=timeoutAfter(this.timeMs,this.setTimeoutSafe,this.clearTimeoutSafe);const propRun=Promise.race([this.property.run(v),t.promise]);propRun.then(t.clear,t.clear);return propRun}runBeforeEach(){return Promise.resolve(this.property.runBeforeEach())}runAfterEach(){return Promise.resolve(this.property.runAfterEach())}};var UnbiasedProperty=class{constructor(property2){this.property=property2}isAsync(){return this.property.isAsync()}generate(mrng,_runId){return this.property.generate(mrng,undefined)}shrink(value3){return this.property.shrink(value3)}run(v){return this.property.run(v)}runBeforeEach(){return this.property.runBeforeEach()}runAfterEach(){return this.property.runAfterEach()}};var safeArrayFrom=Array.from;var safeBufferIsBuffer=typeof Buffer!=="undefined"?Buffer.isBuffer:undefined;var safeJsonStringify$1=JSON.stringify;var safeNumberIsNaN$5=Number.isNaN;var safeObjectKeys$5=Object.keys;var safeObjectGetOwnPropertySymbols$2=Object.getOwnPropertySymbols;var safeObjectGetOwnPropertyDescriptor$3=Object.getOwnPropertyDescriptor;var safeObjectGetPrototypeOf$2=Object.getPrototypeOf;var safeNegativeInfinity$7=Number.NEGATIVE_INFINITY;var safePositiveInfinity$8=Number.POSITIVE_INFINITY;var toStringMethod=Symbol.for("fast-check/toStringMethod");function hasToStringMethod(instance){return instance!==null&&(typeof instance==="object"||typeof instance==="function")&&toStringMethod in instance&&typeof instance[toStringMethod]==="function"}var asyncToStringMethod=Symbol.for("fast-check/asyncToStringMethod");function hasAsyncToStringMethod(instance){return instance!==null&&(typeof instance==="object"||typeof instance==="function")&&asyncToStringMethod in instance&&typeof instance[asyncToStringMethod]==="function"}var findSymbolNameRegex=/^Symbol\((.*)\)$/;function getSymbolDescription(s){if(s.description!==undefined)return s.description;const m=findSymbolNameRegex.exec(SString(s));return m&&m[1].length?m[1]:null}function stringifyNumber(numValue){switch(numValue){case 0:return 1/numValue===safeNegativeInfinity$7?"-0":"0";case safeNegativeInfinity$7:return"Number.NEGATIVE_INFINITY";case safePositiveInfinity$8:return"Number.POSITIVE_INFINITY";default:return numValue===numValue?SString(numValue):"Number.NaN"}}function isSparseArray(arr){let previousNumberedIndex=-1;for(const index2 in arr){const numberedIndex=Number(index2);if(numberedIndex!==previousNumberedIndex+1)return true;previousNumberedIndex=numberedIndex}return previousNumberedIndex+1!==arr.length}function stringifyInternal(value3,previousValues,getAsyncContent){const currentValues=[...previousValues,value3];if(typeof value3==="object"){if(safeIndexOf(previousValues,value3)!==-1)return"[cyclic]"}if(hasAsyncToStringMethod(value3)){const content=getAsyncContent(value3);if(content.state==="fulfilled")return content.value}if(hasToStringMethod(value3))try{return value3[toStringMethod]()}catch{}switch(safeToString2(value3)){case"[object Array]":{const arr=value3;if(arr.length>=50&&isSparseArray(arr)){const assignments=[];for(const index2 in arr)if(!safeNumberIsNaN$5(Number(index2)))safePush(assignments,`${index2}:${stringifyInternal(arr[index2],currentValues,getAsyncContent)}`);return assignments.length!==0?`Object.assign(Array(${arr.length}),{${safeJoin(assignments,",")}})`:`Array(${arr.length})`}const stringifiedArray=safeJoin(safeMap(arr,(v)=>stringifyInternal(v,currentValues,getAsyncContent)),",");return arr.length===0||arr.length-1 in arr?`[${stringifiedArray}]`:`[${stringifiedArray},]`}case"[object BigInt]":return`${value3}n`;case"[object Boolean]":{const unboxedToString=value3==true?"true":"false";return typeof value3==="boolean"?unboxedToString:`new Boolean(${unboxedToString})`}case"[object Date]":{const d=value3;return safeNumberIsNaN$5(safeGetTime(d))?`new Date(NaN)`:`new Date(${safeJsonStringify$1(safeToISOString(d))})`}case"[object Map]":return`new Map(${stringifyInternal(Array.from(value3),currentValues,getAsyncContent)})`;case"[object Null]":return`null`;case"[object Number]":return typeof value3==="number"?stringifyNumber(value3):`new Number(${stringifyNumber(Number(value3))})`;case"[object Object]":{try{const toStringAccessor=value3.toString;if(typeof toStringAccessor==="function"&&toStringAccessor!==Object.prototype.toString)return value3.toString()}catch{return"[object Object]"}const mapper=(k)=>`${k==="__proto__"?'["__proto__"]':typeof k==="symbol"?`[${stringifyInternal(k,currentValues,getAsyncContent)}]`:safeJsonStringify$1(k)}:${stringifyInternal(value3[k],currentValues,getAsyncContent)}`;return"{"+safeJoin([...safeObjectGetPrototypeOf$2(value3)===null?["__proto__:null"]:[],...safeMap(safeObjectKeys$5(value3),mapper),...safeMap(safeFilter(safeObjectGetOwnPropertySymbols$2(value3),(s)=>{const descriptor=safeObjectGetOwnPropertyDescriptor$3(value3,s);return descriptor&&descriptor.enumerable}),mapper)],",")+"}"}case"[object Set]":return`new Set(${stringifyInternal(Array.from(value3),currentValues,getAsyncContent)})`;case"[object String]":return typeof value3==="string"?safeJsonStringify$1(value3):`new String(${safeJsonStringify$1(value3)})`;case"[object Symbol]":{const s=value3;if(SSymbol.keyFor(s)!==undefined)return`Symbol.for(${safeJsonStringify$1(SSymbol.keyFor(s))})`;const desc=getSymbolDescription(s);if(desc===null)return"Symbol()";return s===(desc.startsWith("Symbol.")&&SSymbol[desc.substring(7)])?desc:`Symbol(${safeJsonStringify$1(desc)})`}case"[object Promise]":{const promiseContent=getAsyncContent(value3);switch(promiseContent.state){case"fulfilled":return`Promise.resolve(${stringifyInternal(promiseContent.value,currentValues,getAsyncContent)})`;case"rejected":return`Promise.reject(${stringifyInternal(promiseContent.value,currentValues,getAsyncContent)})`;case"pending":return`new Promise(() => {/*pending*/})`;default:return`new Promise(() => {/*unknown*/})`}}case"[object Error]":if(value3 instanceof Error)return`new Error(${stringifyInternal(value3.message,currentValues,getAsyncContent)})`;break;case"[object Undefined]":return`undefined`;case"[object Int8Array]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Int16Array]":case"[object Uint16Array]":case"[object Int32Array]":case"[object Uint32Array]":case"[object Float32Array]":case"[object Float64Array]":case"[object BigInt64Array]":case"[object BigUint64Array]":{if(typeof safeBufferIsBuffer==="function"&&safeBufferIsBuffer(value3))return`Buffer.from(${value3.buffer.detached?"/*detached ArrayBuffer*/":stringifyInternal(safeArrayFrom(value3.values()),currentValues,getAsyncContent)})`;const valuePrototype=safeObjectGetPrototypeOf$2(value3);const className=valuePrototype&&valuePrototype.constructor&&valuePrototype.constructor.name;if(typeof className==="string"){const typedArray=value3;if(typedArray.buffer.detached)return`${className}.from(/*detached ArrayBuffer*/)`;const valuesFromTypedArr=typedArray.values();return`${className}.from(${stringifyInternal(safeArrayFrom(valuesFromTypedArr),currentValues,getAsyncContent)})`}break}}try{return value3.toString()}catch{return safeToString2(value3)}}function stringify(value3){return stringifyInternal(value3,[],()=>({state:"unknown",value:undefined}))}function possiblyAsyncStringify(value3){const stillPendingMarker=SSymbol();const pendingPromisesForCache=[];const cache=new SMap$1;function createDelay0(){let handleId=null;const cancel=()=>{if(handleId!==null)clearTimeout(handleId)};return{delay:new Promise((resolve4)=>{handleId=setTimeout(()=>{handleId=null;resolve4(stillPendingMarker)},0)}),cancel}}const unknownState={state:"unknown",value:undefined};const getAsyncContent=function getAsyncContent(data){const cacheKey=data;if(cache.has(cacheKey))return cache.get(cacheKey);const delay0=createDelay0();const p=asyncToStringMethod in data?Promise.resolve().then(()=>data[asyncToStringMethod]()):data;p.catch(()=>{});pendingPromisesForCache.push(Promise.race([p,delay0.delay]).then((successValue)=>{if(successValue===stillPendingMarker)cache.set(cacheKey,{state:"pending",value:undefined});else cache.set(cacheKey,{state:"fulfilled",value:successValue});delay0.cancel()},(errorValue)=>{cache.set(cacheKey,{state:"rejected",value:errorValue});delay0.cancel()}));cache.set(cacheKey,unknownState);return unknownState};function loop(){const stringifiedValue=stringifyInternal(value3,[],getAsyncContent);if(pendingPromisesForCache.length===0)return stringifiedValue;return Promise.all(pendingPromisesForCache.splice(0)).then(loop)}return loop()}async function asyncStringify(value3){return Promise.resolve(possiblyAsyncStringify(value3))}function fromSyncCached(cachedValue){return cachedValue===null?new PreconditionFailure:cachedValue}function fromCached(...data){if(data[1])return data[0].then(fromSyncCached);return fromSyncCached(data[0])}function fromCachedUnsafe(cachedValue,isAsync){return fromCached(cachedValue,isAsync)}var IgnoreEqualValuesProperty=class{constructor(property2,skipRuns){this.property=property2;this.skipRuns=skipRuns;this.coveredCases=new Map}isAsync(){return this.property.isAsync()}generate(mrng,runId){return this.property.generate(mrng,runId)}shrink(value3){return this.property.shrink(value3)}run(v){const stringifiedValue=stringify(v);if(this.coveredCases.has(stringifiedValue)){const lastOutput=this.coveredCases.get(stringifiedValue);if(!this.skipRuns)return lastOutput;return fromCachedUnsafe(lastOutput,this.property.isAsync())}const out=this.property.run(v);this.coveredCases.set(stringifiedValue,out);return out}runBeforeEach(){return this.property.runBeforeEach()}runAfterEach(){return this.property.runAfterEach()}};var safeDateNow=Date.now;var safeSetTimeout=setTimeout;var safeClearTimeout=clearTimeout;function decorateProperty(rawProperty,qParams){let prop=rawProperty;if(rawProperty.isAsync()&&qParams.timeout!==undefined)prop=new TimeoutProperty(prop,qParams.timeout,safeSetTimeout,safeClearTimeout);if(qParams.unbiased)prop=new UnbiasedProperty(prop);if(qParams.skipAllAfterTimeLimit!==undefined)prop=new SkipAfterProperty(prop,safeDateNow,qParams.skipAllAfterTimeLimit,false,safeSetTimeout,safeClearTimeout);if(qParams.interruptAfterTimeLimit!==undefined)prop=new SkipAfterProperty(prop,safeDateNow,qParams.interruptAfterTimeLimit,true,safeSetTimeout,safeClearTimeout);if(qParams.skipEqualValues)prop=new IgnoreEqualValuesProperty(prop,true);if(qParams.ignoreEqualValues)prop=new IgnoreEqualValuesProperty(prop,false);return prop}var ExecutionStatus=function(ExecutionStatus2){ExecutionStatus2[ExecutionStatus2["Success"]=0]="Success";ExecutionStatus2[ExecutionStatus2["Skipped"]=-1]="Skipped";ExecutionStatus2[ExecutionStatus2["Failure"]=1]="Failure";return ExecutionStatus2}({});var RunExecution=class RunExecution2{constructor(verbosity,interruptedAsFailure){this.verbosity=verbosity;this.interruptedAsFailure=interruptedAsFailure;this.rootExecutionTrees=[];this.currentLevelExecutionTrees=this.rootExecutionTrees;this.failure=null;this.numSkips=0;this.numSuccesses=0;this.interrupted=false}appendExecutionTree(status,value3){const currentTree={status,value:value3,children:[]};this.currentLevelExecutionTrees.push(currentTree);return currentTree}fail(value3,id2,failure){if(this.verbosity>=1){const currentTree=this.appendExecutionTree(1,value3);this.currentLevelExecutionTrees=currentTree.children}if(this.pathToFailure===undefined)this.pathToFailure=`${id2}`;else this.pathToFailure+=`:${id2}`;this.value=value3;this.failure=failure}skip(value3){if(this.verbosity>=2)this.appendExecutionTree(-1,value3);if(this.pathToFailure===undefined)++this.numSkips}success(value3){if(this.verbosity>=2)this.appendExecutionTree(0,value3);if(this.pathToFailure===undefined)++this.numSuccesses}interrupt(){this.interrupted=true}isSuccess(){return this.pathToFailure===undefined}firstFailure(){return this.pathToFailure!==undefined?+safeSplit(this.pathToFailure,":")[0]:-1}numShrinks(){return this.pathToFailure!==undefined?safeSplit(this.pathToFailure,":").length-1:0}extractFailures(){if(this.isSuccess())return[];const failures=[];let cursor=this.rootExecutionTrees;while(cursor.length>0&&cursor[cursor.length-1].status===1){const failureTree=cursor[cursor.length-1];failures.push(failureTree.value);cursor=failureTree.children}return failures}static mergePaths(offsetPath,path){if(offsetPath.length===0)return path;const offsetItems=offsetPath.split(":");const remainingItems=path.split(":");const middle=+offsetItems[offsetItems.length-1]+ +remainingItems[0];return[...offsetItems.slice(0,offsetItems.length-1),`${middle}`,...remainingItems.slice(1)].join(":")}toRunDetails(seed,basePath,maxSkips,qParams){if(!this.isSuccess())return{failed:true,interrupted:this.interrupted,numRuns:this.firstFailure()+1-this.numSkips,numSkips:this.numSkips,numShrinks:this.numShrinks(),seed,counterexample:this.value,counterexamplePath:RunExecution2.mergePaths(basePath,this.pathToFailure),errorInstance:this.failure.error,failures:this.extractFailures(),executionSummary:this.rootExecutionTrees,verbose:this.verbosity,runConfiguration:qParams.toParameters()};const considerInterruptedAsFailure=this.interruptedAsFailure||this.numSuccesses===0;return{failed:this.numSkips>maxSkips||this.interrupted&&considerInterruptedAsFailure,interrupted:this.interrupted,numRuns:this.numSuccesses,numSkips:this.numSkips,numShrinks:0,seed,counterexample:null,counterexamplePath:null,error:null,errorInstance:null,failures:[],executionSummary:this.rootExecutionTrees,verbose:this.verbosity,runConfiguration:qParams.toParameters()}}};var RunnerIterator=class{constructor(sourceValues,shrink,verbose,interruptedAsFailure){this.sourceValues=sourceValues;this.shrink=shrink;this.runExecution=new RunExecution(verbose,interruptedAsFailure);this.currentIdx=-1;this.nextValues=sourceValues}[Symbol.iterator](){return this}next(){const nextValue=this.nextValues.next();if(nextValue.done||this.runExecution.interrupted)return{done:true,value:undefined};this.currentValue=nextValue.value;++this.currentIdx;return{done:false,value:nextValue.value.value_}}handleResult(result3){if(result3!==null&&typeof result3==="object"&&!PreconditionFailure.isFailure(result3)){this.runExecution.fail(this.currentValue.value_,this.currentIdx,result3);this.currentIdx=-1;this.nextValues=this.shrink(this.currentValue)}else if(result3!==null)if(!result3.interruptExecution){this.runExecution.skip(this.currentValue.value_);this.sourceValues.skippedOne()}else this.runExecution.interrupt();else this.runExecution.success(this.currentValue.value_)}};var SourceValuesIterator=class{constructor(initialValues,maxInitialIterations,remainingSkips){this.initialValues=initialValues;this.maxInitialIterations=maxInitialIterations;this.remainingSkips=remainingSkips}[Symbol.iterator](){return this}next(){if(--this.maxInitialIterations!==-1&&this.remainingSkips>=0){const n=this.initialValues.next();if(!n.done)return{value:n.value,done:false}}return{value:undefined,done:true}}skippedOne(){--this.remainingSkips;++this.maxInitialIterations}};var MIN_INT=-2147483648;var MAX_INT=2147483647;var DBL_FACTOR=Math.pow(2,27);var DBL_DIVISOR=Math.pow(2,-53);var Random=class Random2{constructor(sourceRng){this.internalRng=adaptRandomGenerator(sourceRng.clone())}clone(){return new Random2(this.internalRng)}next(bits){return uniformInt(this.internalRng,0,(1<<bits)-1)}nextBoolean(){return uniformInt(this.internalRng,0,1)===1}nextInt(min5,max5){return uniformInt(this.internalRng,min5===undefined?MIN_INT:min5,max5===undefined?MAX_INT:max5)}nextBigInt(min5,max5){return uniformBigInt(this.internalRng,min5,max5)}nextDouble(){const a=this.next(26);const b=this.next(27);return(a*DBL_FACTOR+b)*DBL_DIVISOR}getState(){if("getState"in this.internalRng&&typeof this.internalRng.getState==="function")return this.internalRng.getState()}};function tossNext(generator,rng,index2){rng.jump();return generator.generate(new Random(rng),index2)}function*toss(generator,seed,random2,examples){for(let idx=0;idx!==examples.length;++idx)yield new Value(examples[idx],undefined);for(let idx=0,rng=random2(seed);;++idx)yield tossNext(generator,rng,idx)}function lazyGenerate(generator,rng,idx){return()=>generator.generate(new Random(rng),idx)}function*lazyToss(generator,seed,random2,examples){yield*safeMap(examples,(e)=>()=>new Value(e,undefined));let idx=0;const rng=adaptRandomGenerator(random2(seed));for(;;){rng.jump();yield lazyGenerate(generator,rng,idx++)}}function produce(producer){return producer()}function pathWalk(path,initialProducers,shrink){const producers=initialProducers;const segments=path.split(":").map((text)=>+text);if(segments.length===0)return producers.map(produce);if(!segments.every((v)=>!Number.isNaN(v)))throw new Error(`Unable to replay, got invalid path=${path}`);let values3=producers.drop(segments[0]).map(produce);for(const s of segments.slice(1)){const valueToShrink=values3.getNthOrLast(0);if(valueToShrink===null)throw new Error(`Unable to replay, got wrong path=${path}`);values3=shrink(valueToShrink).drop(s)}return values3}var safeObjectAssign$6=Object.assign;function formatHints(hints){if(hints.length===1)return`Hint: ${hints[0]}`;return hints.map((h,idx)=>`Hint (${idx+1}): ${h}`).join(`
|
|
189
|
+
at ${formatPath(path)}`}return new Error(message)}var arbitraryMemoMap=new WeakMap;var suspendDepthIdentifierMap=new WeakMap;var emptyRecursionStack=[];function makeReport(){return{warnings:[]}}function toReport(report){return{warnings:report.warnings.slice()}}function arbitraryError(what){return new Error(`Unable to derive an arbitrary for ${what}`)}var entryComparator=([a],[b])=>equals(a,b);function applyChecks(ast,filters,arbitrary){return filters.reduce((acc,filter10)=>acc.filter((a)=>filter10.run(a,ast,defaultParseOptions)===undefined),arbitrary)}function validateArrayConstraints(constraint,label){if(constraint?.minLength!==undefined&&constraint.maxLength!==undefined&&constraint.minLength>constraint.maxLength){throw arbitraryError(`${label} constraints`)}}function lengthToFastCheckConstraints(constraint){return constraint===undefined||constraint.minLength===undefined&&constraint.maxLength===undefined?undefined:{...constraint.minLength!==undefined?{minLength:constraint.minLength}:{},...constraint.maxLength!==undefined?{maxLength:constraint.maxLength}:{}}}function arrayWithConstraints(fc,item,constraint,comparator){return comparator?fc.uniqueArray(item,{...constraint,comparator}):fc.array(item,constraint)}function array2(fc,ctx,item,terminal=false){const constraint=ctx.constraint;const arrayConstraints=lengthToFastCheckConstraints(constraint);validateArrayConstraints(arrayConstraints,"array");return arrayWithConstraints(fc,item,terminal?{...arrayConstraints,maxLength:arrayConstraints?.minLength??0}:arrayConstraints,constraint?.unique?equals:undefined)}function appendArray(fc,out,len,rest){return out.chain((as3)=>as3.length<len?fc.constant(as3):rest.map((rest2)=>[...as3,...rest2]))}function appendObjectEntries(out,entries3){return out.chain((o)=>entries3.map((entries4)=>({...Object.fromEntries(entries4),...o})))}var max4=makeReducer(ReducerMax);var min4=makeReducer(ReducerMin);var or2=makeReducer(ReducerOr);var concat=makeReducer(makeReducerConcat());var combiner=makeCombiner({integer:or2,maxLength:min4,minLength:max4,noInfinity:or2,noNaN:or2,patterns:concat,unique:or2,valid:or2},{omitKeyWhen:isUndefined});function mergeOrderedBound(order,self,selfExclusive,that,thatExclusive,takeComparison){if(that===undefined||self===undefined){return that===undefined?[self,selfExclusive]:[that,thatExclusive]}const comparison=order(self,that);return comparison===takeComparison?[that,thatExclusive]:comparison===0?[self,selfExclusive||thatExclusive]:[self,selfExclusive]}function mergeOrderedConstraints(self,that){if(self===undefined){return that}if(self.order!==that.order){throw new Error("Cannot merge ordered arbitrary constraints with different Order instances")}const[minimum,exclusiveMinimum]=mergeOrderedBound(self.order,self.minimum,self.exclusiveMinimum,that.minimum,that.exclusiveMinimum,-1);const[maximum,exclusiveMaximum]=mergeOrderedBound(self.order,self.maximum,self.exclusiveMaximum,that.maximum,that.exclusiveMaximum,1);return{order:self.order,...minimum!==undefined?{minimum}:{},...exclusiveMinimum!==undefined?{exclusiveMinimum}:{},...maximum!==undefined?{maximum}:{},...exclusiveMaximum!==undefined?{exclusiveMaximum}:{}}}function mergeConstraint(self,that){const{ordered:selfOrdered,...selfRest}=self??{};const{ordered:thatOrdered,...thatRest}=that;const ordered=thatOrdered===undefined?selfOrdered:mergeOrderedConstraints(selfOrdered,thatOrdered);const out=combiner.combine(selfRest,thatRest);return{...out,...ordered===undefined?{}:{ordered}}}function collectChecks(checks){const filters=[];const arbitraries=[];function visit(check){if(check.annotations?.arbitrary){arbitraries.push(check.annotations.arbitrary)}if(check._tag!=="Filter"){for(const child of check.checks){visit(child)}}else{filters.push(check)}}checks?.forEach(visit);return{filters,arbitraries}}function constraintContext(arbitraries){const constraintAnnotations=arbitraries.map(({constraint})=>constraint).filter(isNotUndefined);return(ctx)=>{const constraint=constraintAnnotations.reduce((acc,c)=>mergeConstraint(acc,c),ctx.constraint);return{...ctx,constraint}}}function resetContext(ctx){return{...ctx,constraint:undefined}}function objectEntriesConstraints(ast,constraint,requiredKeys){if(constraint===undefined||constraint.minLength===undefined&&constraint.maxLength===undefined){return}if(constraint.minLength!==undefined&&ast.indexSignatures.length===0&&constraint.minLength>ast.propertySignatures.length){throw arbitraryError("object property constraints")}const out={};if(constraint.minLength!==undefined){out.minLength=Math.max(0,constraint.minLength-requiredKeys)}if(constraint.maxLength!==undefined){out.maxLength=constraint.maxLength-requiredKeys;if(out.maxLength<0){throw arbitraryError("object property constraints")}}validateArrayConstraints(out,"object property");return out}function objectWithOptionalCount(fc,pss,orderedNames,requiredKeys,optionalNames,constraint){const requiredCount=requiredKeys.length;if(constraint.maxLength!==undefined&&constraint.maxLength<requiredCount){throw arbitraryError("object property constraints")}const minOptional=constraint.minLength===undefined?0:Math.max(0,constraint.minLength-requiredCount);const maxOptional=constraint.maxLength===undefined?optionalNames.length:Math.min(optionalNames.length,constraint.maxLength-requiredCount);if(minOptional>maxOptional){throw arbitraryError("object property constraints")}const full=fc.record(pss,{requiredKeys:[...requiredKeys,...optionalNames]});const chosen=fc.shuffledSubarray([...optionalNames],{minLength:minOptional,maxLength:maxOptional});return fc.tuple(full,chosen).map(([base,names])=>{const keep=new Set([...requiredKeys,...names]);const out={};for(const name of orderedNames){if(keep.has(name)){out[name]=base[name]}}return out})}function toRangeConstraints(ordered,min5,max5,error){const out={};if(ordered?.minimum!==undefined){out.min=min5(ordered.minimum,ordered.exclusiveMinimum===true)}if(ordered?.maximum!==undefined){out.max=max5(ordered.maximum,ordered.exclusiveMaximum===true)}if(out.min!==undefined&&out.max!==undefined&&out.min>out.max){throw arbitraryError(error)}return out}function toIntegerConstraints(ordered){return toRangeConstraints(ordered,(minimum,excluded)=>excluded?Math.floor(minimum)+1:Math.ceil(minimum),(maximum,excluded)=>excluded?Math.ceil(maximum)-1:Math.floor(maximum),"integer constraints")}function toFloatConstraints(constraint,ordered){const out={...constraint?.noInfinity?{noDefaultInfinity:true}:{},...constraint?.noNaN?{noNaN:true}:{},...ordered?.minimum!==undefined?{min:ordered.minimum}:{},...ordered?.exclusiveMinimum!==undefined?{minExcluded:ordered.exclusiveMinimum}:{},...ordered?.maximum!==undefined?{max:ordered.maximum}:{},...ordered?.exclusiveMaximum!==undefined?{maxExcluded:ordered.exclusiveMaximum}:{}};if(out.min!==undefined&&out.max!==undefined&&(out.min>out.max||out.min===out.max&&(out.minExcluded||out.maxExcluded))){throw arbitraryError("number constraints")}return out}function toBigIntConstraints(ordered){return toRangeConstraints(ordered,(minimum,excluded)=>excluded?minimum+BigInt(1):minimum,(maximum,excluded)=>excluded?maximum-BigInt(1):maximum,"the ordered bigint constraints")}function makeLazy(normal,terminal){const out=(fc,ctx,recursionStack=emptyRecursionStack)=>normal(fc,ctx,recursionStack);out.terminal=(fc,ctx,recursionStack=emptyRecursionStack)=>terminal(fc,ctx,recursionStack);return out}function same(f){return makeLazy(f,f)}function getSuspendRecursion(fc,ast){const depthIdentifier=suspendDepthIdentifierMap.get(ast)??fc.createDepthIdentifier();suspendDepthIdentifierMap.set(ast,depthIdentifier);return{maxDepth:2,depthIdentifier}}function oneOf(fc,arbitraries){return arbitraries.length===0?undefined:arbitraries.length===1?arbitraries[0]:fc.oneof(...arbitraries)}var finiteNumberConstraint={noInfinity:true,noNaN:true};function finiteNumberContext(ctx){return{...ctx,constraint:finiteNumberConstraint}}function reportChecks(report,checks,path){function visit(check,covered){const arbitrary=check.annotations?.arbitrary;const nextCovered=covered||arbitrary?.constraint!==undefined||arbitrary?.candidate!==undefined;if(check._tag!=="Filter"){for(const child of check.checks){visit(child,nextCovered)}}else if(!nextCovered){const meta=check.annotations?.meta;const description=typeof meta==="object"&&meta!==null&&"_tag"in meta&&typeof meta._tag==="string"?meta._tag:check.annotations?.identifier??check.annotations?.expected;report.warnings.push({_tag:"OpaqueFilter",path,...description===undefined?{}:{description}})}}checks?.forEach((check)=>visit(check,false))}function collectReport(ast,report){const stack=new WeakSet;function visit(ast2,path){if(stack.has(ast2)){return}stack.add(ast2);reportChecks(report,ast2.checks,path);switch(ast2._tag){case"Declaration":ast2.typeParameters.forEach((tp)=>visit(tp,path));break;case"Arrays":{for(const[i,type]of[...ast2.elements,...ast2.rest].entries()){visit(type,[...path,i])}break}case"Objects":ast2.propertySignatures.forEach((ps)=>visit(ps.type,[...path,ps.name]));ast2.indexSignatures.forEach((is)=>{visit(is.parameter,path);visit(is.type,path)});break;case"Union":ast2.types.forEach((type)=>visit(type,path));break;case"TemplateLiteral":ast2.parts.forEach((part,i)=>visit(toEncoded(part),[...path,i]));break;case"Suspend":visit(ast2.thunk(),path);break}stack.delete(ast2)}visit(ast,[])}function applyCandidates(fc,ctx,arbitraries,base){const weighted=base===undefined?[]:[{arbitrary:base,weight:1}];for(const{candidate}of arbitraries){if(!candidate){continue}const arbitrary=candidate.make(fc,ctx);if(arbitrary===undefined){continue}const weight=candidate.weight??1;if(!globalThis.Number.isInteger(weight)||weight<=0){throw arbitraryError("a candidate with an invalid weight")}weighted.push({arbitrary,weight})}return weighted.length===0?undefined:weighted.length===1?weighted[0].arbitrary:fc.oneof(...weighted)}function applyFilterLayer(ast,checks,fc,ctx,base){const out=applyCandidates(fc,ctx,checks.arbitraries,base);return out===undefined?undefined:applyChecks(ast,checks.filters,out)}function normalizeDerivation(output,hasTypeParameters){if(!(typeof output==="object"&&output!==null&&("arbitrary"in output))){return{arbitrary:output,terminal:hasTypeParameters?undefined:output}}const terminal="terminal"in output?output.terminal:hasTypeParameters?undefined:output.arbitrary;return{arbitrary:output.arbitrary,terminal}}function makeTypeParameters(typeParameters,fc,ctx,recursionStack,lazyNormal){return typeParameters.map((tp)=>({arbitrary:lazyNormal?fc.constant(null).chain(()=>tp(fc,ctx,recursionStack)):tp(fc,ctx,recursionStack),terminal:tp.terminal(fc,ctx,recursionStack)}))}function filterLayer(ast,checks,normalBase,terminalBase){const f=constraintContext(checks.arbitraries);return makeLazy((fc,ctx,recursionStack)=>{const nextCtx=f(ctx);return applyFilterLayer(ast,checks,fc,nextCtx,normalBase(fc,ctx,nextCtx,recursionStack))},(fc,ctx,recursionStack)=>{const nextCtx=f(ctx);return applyFilterLayer(ast,checks,fc,nextCtx,terminalBase(fc,ctx,nextCtx,recursionStack))})}var memoized=memoize((ast)=>recur(ast,[]));function recur(ast,path){const annotation=resolve(ast)?.toArbitrary;if(annotation){const typeParameters=isDeclaration(ast)?ast.typeParameters.map((tp)=>recur(tp,path)):[];const checks=collectChecks(ast.checks);const derive=(lazyNormal)=>(fc,ctx,nextCtx,recursionStack)=>normalizeDerivation(annotation(makeTypeParameters(typeParameters,fc,resetContext(ctx),recursionStack,lazyNormal))(fc,nextCtx),typeParameters.length>0)[lazyNormal?"terminal":"arbitrary"];return filterLayer(ast,checks,derive(false),derive(true))}if(ast.checks){const checks=collectChecks(ast.checks);const lawc=recur(replaceChecks(ast,undefined),path);return filterLayer(ast,checks,(fc,_ctx,nextCtx,recursionStack)=>lawc(fc,nextCtx,recursionStack),(fc,_ctx,nextCtx,recursionStack)=>lawc.terminal(fc,nextCtx,recursionStack))}return base(ast,path)}function base(ast,path){switch(ast._tag){case"Never":case"Declaration":throw errorWithPath(`Unsupported AST ${ast._tag}`,path);case"Null":return same((fc)=>fc.constant(null));case"Void":case"Undefined":return same((fc)=>fc.constant(undefined));case"Unknown":case"Any":return same((fc)=>fc.anything());case"String":return same((fc,ctx)=>{const constraint=ctx.constraint;const patterns=constraint?.patterns;return patterns?fc.oneof(...patterns.map((pattern)=>fc.stringMatching(new RegExp(pattern)))):fc.string(lengthToFastCheckConstraints(constraint))});case"Number":return same((fc,ctx)=>{const constraint=ctx.constraint;const ordered=constraint?.ordered?.order===Number2?constraint.ordered:undefined;return constraint?.integer?fc.integer(toIntegerConstraints(ordered)):fc.float(toFloatConstraints(constraint,ordered))});case"Boolean":return same((fc)=>fc.boolean());case"BigInt":return same((fc,ctx)=>{const ordered=ctx.constraint?.ordered?.order===BigInt2?ctx.constraint.ordered:undefined;return fc.bigInt(toBigIntConstraints(ordered))});case"Symbol":return same((fc)=>fc.string().map(Symbol.for));case"Literal":return same((fc)=>fc.constant(ast.literal));case"UniqueSymbol":return same((fc)=>fc.constant(ast.symbol));case"ObjectKeyword":return same((fc)=>fc.oneof(fc.object(),fc.array(fc.anything())));case"Enum":return recur(enumsToLiterals(ast),path);case"TemplateLiteral":{const parts=ast.parts.map((part,i)=>recur(toEncoded(part),[...path,i]));return same((fc,ctx,recursionStack)=>fc.tuple(...parts.map((part)=>part(fc,finiteNumberContext(ctx),recursionStack))).map((segments)=>segments.map((segment)=>globalThis.String(segment)).join("")))}case"Arrays":{const elements=ast.elements.map((ast2,i)=>({ast:ast2,arbitrary:recur(ast2,[...path,i])}));const len=ast.elements.length;const rest=ast.rest.map((ast2,i)=>({ast:ast2,arbitrary:recur(ast2,[...path,len+i])}));const terminal=(fc,ctx,recursionStack)=>{const reset=resetContext(ctx);const elementArbitraries=[];const optionals=[];let length=0;for(const element of elements){const out2=element.arbitrary.terminal(fc,reset,recursionStack);if(isOptional(element.ast)){optionals.push(out2);continue}if(out2===undefined){return}length++;elementArbitraries.push(out2.map(some2))}const minLength=ctx.constraint?.minLength??0;const needsRest=isReadonlyArrayNonEmpty(rest)&&minLength>length+optionals.length;const optionalTarget=needsRest?optionals.length:Math.max(0,minLength-length);let includedOptionals=0;for(const out2 of optionals){if(includedOptionals>=optionalTarget||out2===undefined){elementArbitraries.push(fc.constant(none2()));continue}includedOptionals++;length++;elementArbitraries.push(out2.map(some2))}if(includedOptionals<optionalTarget){return}let out=fc.tuple(...elementArbitraries).map(getSomes);if(isReadonlyArrayNonEmpty(rest)){const[head,...tail]=rest;const restCtx=ast.elements.length===0?ctx:reset;const minRestLength=Math.max(0,minLength-length-tail.length);const headArbitrary=minRestLength===0?undefined:head.arbitrary.terminal(fc,reset,recursionStack);if(minRestLength>0&&headArbitrary===undefined){return}const restArbitrary=minRestLength===0?fc.constant([]):array2(fc,{...restCtx,constraint:{...restCtx.constraint,minLength:minRestLength}},headArbitrary,true);out=appendArray(fc,out,len,restArbitrary);if(tail.length>0){const tailArbitraries=[];for(const element of tail){const out2=element.arbitrary.terminal(fc,reset,recursionStack);if(out2===undefined){return}tailArbitraries.push(out2)}const t=fc.tuple(...tailArbitraries);out=appendArray(fc,out,len,t)}}return out};return makeLazy((fc,ctx,recursionStack)=>{const reset=resetContext(ctx);const elementArbitraries=elements.map(({ast:ast2,arbitrary})=>{const out2=arbitrary(fc,reset,recursionStack);return isOptional(ast2)?out2.chain((a)=>fc.boolean().map((b)=>b?some2(a):none2())):out2.map(some2)});let out=fc.tuple(...elementArbitraries).map(getSomes);if(isReadonlyArrayNonEmpty(rest)){const[head,...tail]=rest.map(({arbitrary})=>arbitrary(fc,reset,recursionStack));const restArbitrary=array2(fc,ast.elements.length===0?ctx:reset,head);out=appendArray(fc,out,len,restArbitrary);if(tail.length>0){const t=fc.tuple(...tail);out=appendArray(fc,out,len,t)}}if(ctx.recursion){const terminalOut=terminal(fc,ctx,recursionStack);if(terminalOut!==undefined){return fc.oneof(ctx.recursion,terminalOut,out)}}return out},terminal)}case"Objects":{const propertySignatures=ast.propertySignatures.map((ps)=>({ps,arbitrary:recur(ps.type,[...path,ps.name])}));const indexSignatures=ast.indexSignatures.map((is)=>({is,parameter:recur(is.parameter,path),type:recur(is.type,path)}));const terminal=(fc,ctx,recursionStack)=>{const reset=resetContext(ctx);const pss={};const requiredKeys=[];const optionals=[];for(const{ps,arbitrary}of propertySignatures){const name=ps.name;const out2=arbitrary.terminal(fc,reset,recursionStack);if(isOptional(ps.type)){if(out2!==undefined){optionals.push([name,out2])}continue}if(out2===undefined){return}requiredKeys.push(name);pss[name]=out2}let optionalCount=Math.max(0,(ctx.constraint?.minLength??0)-requiredKeys.length);for(const[name,out2]of optionals){if(optionalCount===0){break}optionalCount--;requiredKeys.push(name);pss[name]=out2}if(optionalCount>0&&ast.indexSignatures.length===0){return}let out=fc.record(pss,{requiredKeys});const entriesConstraints=objectEntriesConstraints(ast,ctx.constraint,requiredKeys.length);const minEntries=entriesConstraints?.minLength??0;for(const{parameter,type}of indexSignatures){let entries3;if(minEntries===0){entries3=fc.constant([])}else{const key=parameter.terminal(fc,reset,recursionStack);const value3=type.terminal(fc,reset,recursionStack);if(key===undefined||value3===undefined){return}entries3=arrayWithConstraints(fc,fc.tuple(key,value3),{...entriesConstraints,maxLength:minEntries},entryComparator)}out=appendObjectEntries(out,entries3)}return out};return makeLazy((fc,ctx,recursionStack)=>{const reset=resetContext(ctx);const pss={};const orderedNames=[];const requiredKeys=[];const optionalNames=[];for(const{ps,arbitrary}of propertySignatures){const name=ps.name;orderedNames.push(name);if(isOptional(ps.type)){optionalNames.push(name)}else{requiredKeys.push(name)}pss[name]=arbitrary(fc,reset,recursionStack)}const constraint=ctx.constraint;if(optionalNames.length>0&&indexSignatures.length===0&&constraint!==undefined&&(constraint.minLength!==undefined||constraint.maxLength!==undefined)){return objectWithOptionalCount(fc,pss,orderedNames,requiredKeys,optionalNames,constraint)}let out=fc.record(pss,{requiredKeys});const entriesConstraints=objectEntriesConstraints(ast,ctx.constraint,requiredKeys.length);for(const{parameter,type}of indexSignatures){const entry=fc.tuple(parameter(fc,reset,recursionStack),type(fc,reset,recursionStack));const entries3=arrayWithConstraints(fc,entry,entriesConstraints,entryComparator);out=appendObjectEntries(out,entries3)}return out},terminal)}case"Union":{const types=ast.types.map((ast2)=>recur(ast2,path));const terminal=(fc,ctx,recursionStack)=>oneOf(fc,types.map((type)=>type.terminal(fc,ctx,recursionStack)).filter(isNotUndefined));return makeLazy((fc,ctx,recursionStack)=>{const arbitraries=types.map((type)=>type(fc,ctx,recursionStack));if(ctx.recursion){const terminalOut=terminal(fc,ctx,recursionStack);if(terminalOut!==undefined){return fc.oneof(ctx.recursion,terminalOut,...arbitraries)}}const out=oneOf(fc,arbitraries);if(out===undefined){throw arbitraryError("a union with no members")}return out},terminal)}case"Suspend":{const memo=arbitraryMemoMap.get(ast);if(memo)return memo;const get5=memoizeThunk(()=>recur(ast.thunk(),path));const out=makeLazy((fc,ctx,recursionStack)=>{const recursion=getSuspendRecursion(fc,ast);const nextCtx={...ctx,recursion};const nextStack=recursionStack.includes(ast)?recursionStack:[...recursionStack,ast];const terminal=get5().terminal(fc,nextCtx,nextStack);if(terminal===undefined){throw errorWithPath("Unable to derive an arbitrary for a recursive schema without a finite generation path",path)}return fc.oneof(recursion,terminal,fc.constant(null).chain(()=>get5()(fc,nextCtx,nextStack)))},(fc,ctx,recursionStack)=>{if(recursionStack.includes(ast)){return}const recursion=getSuspendRecursion(fc,ast);return get5().terminal(fc,{...ctx,recursion},[...recursionStack,ast])});arbitraryMemoMap.set(ast,out);return out}}}var toConstructorAST=memoize((ast)=>{switch(ast._tag){case"Declaration":{const getLink=ast.annotations?.[ClassTypeId];if(isFunction(getLink)){const link=getLink(ast.typeParameters);const to=toConstructorAST(link.to);return replaceEncoding(ast,to===link.to?[link]:[new Link(to,link.transformation)])}return ast}case"Objects":case"Arrays":return ast.recur((ast2)=>{const defaultValue=ast2.context?.defaultValue;if(defaultValue){const out=toConstructorAST(ast2);return replaceEncoding(out,out.encoding?[...out.encoding,...defaultValue]:defaultValue)}return toConstructorAST(ast2)});case"Suspend":return ast.recur(toConstructorAST);default:return ast}});function makeEffect(schema){const ast=toConstructorAST(toType(schema.ast));const parser=run2(ast);return(input,options)=>{return parser(input,options?.disableChecks?options?.parseOptions?{...options.parseOptions,disableChecks:true}:{disableChecks:true}:options?.parseOptions)}}function makeOption(schema){const parser=makeEffect(schema);return(input,options)=>{const exit3=runSyncExit2(parser(input,options));if(isSuccess4(exit3)){return some2(exit3.value)}getSchemaIssueOrThrow(exit3.cause,"Option adapter can only return none for schema issues");return none2()}}function make23(schema){const parser=makeEffect(schema);return(input,options)=>{const exit3=runSyncExit2(parser(input,options));if(isSuccess4(exit3)){return exit3.value}const issue=getSchemaIssueOrThrow(exit3.cause,"Constructor adapter can only throw schema issues");throw new Error(issue.toString(),{cause:issue})}}function is(schema){return _is(schema.ast)}function _is(ast){const parser=asExit(run2(toType(ast)));return(input)=>{const exit3=parser(input,defaultParseOptions);if(isSuccess4(exit3)){return true}getSchemaIssueOrThrow(exit3.cause,"Type guard adapter can only return false for schema issues");return false}}function _issue(ast){const parser=run2(ast);return(input,options)=>{const exit3=runSyncExit2(parser(input,options));if(isSuccess4(exit3)){return}return getSchemaIssueOrThrow(exit3.cause,"Issue adapter can only return schema issues")}}function asserts(schema,input){const parser=asExit(run2(toType(schema.ast)));const exit3=parser(input,defaultParseOptions);if(isFailure4(exit3)){const issue=getSchemaIssueOrThrow(exit3.cause,"Assertion adapter can only throw schema issues");throw new Error(issue.toString(),{cause:issue})}}function decodeUnknownEffect(schema,options){const parser=run2(schema.ast);return options===undefined?parser:(input,overrideOptions)=>parser(input,mergeParseOptions(options,overrideOptions))}var decodeEffect=decodeUnknownEffect;function decodeUnknownExit(schema,options){return asExit(decodeUnknownEffect(schema,options))}function decodeUnknownOption(schema,options){return asOption(decodeUnknownEffect(schema,options))}var decodeOption=decodeUnknownOption;function decodeUnknownResult(schema,options){return asResult(decodeUnknownEffect(schema,options))}function decodeUnknownSync(schema,options){return asSync(decodeUnknownEffect(schema,options))}var decodeSync=decodeUnknownSync;function encodeUnknownEffect(schema,options){const parser=run2(flip3(schema.ast));return options===undefined?parser:(input,overrideOptions)=>parser(input,mergeParseOptions(options,overrideOptions))}function encodeUnknownExit(schema,options){return asExit(encodeUnknownEffect(schema,options))}function encodeUnknownOption(schema,options){return asOption(encodeUnknownEffect(schema,options))}var encodeOption=encodeUnknownOption;function encodeUnknownResult(schema,options){return asResult(encodeUnknownEffect(schema,options))}function encodeUnknownSync(schema,options){return asSync(encodeUnknownEffect(schema,options))}var encodeSync=encodeUnknownSync;var mergeParseOptions=(options,overrideOptions)=>overrideOptions===undefined?options:{...options,...overrideOptions};function run2(ast){const parser=recur2(ast);return(input,options)=>flatMapEager2(parser(some2(input),options??defaultParseOptions),(oa)=>{if(oa._tag==="None"){return fail6(new InvalidValue(oa))}return succeed6(oa.value)})}function asExit(parser){return(input,options)=>runSyncExit2(parser(input,options))}function asOption(parser){const parserExit=asExit(parser);return(input,options)=>{const exit3=parserExit(input,options);if(isSuccess4(exit3)){return some2(exit3.value)}getSchemaIssueOrThrow(exit3.cause,"Option adapter can only return none for schema issues");return none2()}}function asResult(parser){const parserExit=asExit(parser);return(input,options)=>{const exit3=parserExit(input,options);if(isSuccess4(exit3)){return succeed2(exit3.value)}return fail2(getSchemaIssueOrThrow(exit3.cause,"Result adapter can only return schema issues"))}}function asSync(parser){const parserExit=asExit(parser);return(input,options)=>{const exit3=parserExit(input,options);if(isSuccess4(exit3)){return exit3.value}const issue=getSchemaIssueOrThrow(exit3.cause,"Sync adapter can only throw schema issues");throw new Error(issue.toString(),{cause:issue})}}function mapSchemaIssueEffect(self,f){return catchCause2(self,(cause)=>failCauseSync2(()=>map6(cause,f)))}var recur2=memoize((ast)=>{let parser;const checks=ast.checks;const encoding=ast.encoding;const links=encoding;const len=links?.length??0;const encodingChecks=ast.encodingChecks;const astOptions=(checks?checks[checks.length-1].annotations:ast.annotations)?.["parseOptions"];if(!ast.context&&!encoding&&!checks&&!encodingChecks){return(ou,options)=>{parser??=ast.getParser(recur2);if(astOptions){options={...options,...astOptions}}return parser(ou,options)}}const isStructural=isArrays(ast)||isObjects(ast)||isDeclaration(ast)&&ast.typeParameters.length>0;const structuralChecks=checks&&isStructural?checks.filter((check)=>check.annotations?.[STRUCTURAL_ANNOTATION_KEY]):undefined;return(ou,options)=>{if(astOptions){options={...options,...astOptions}}let srou;if(links){for(let i=len-1;i>=0;i--){const link=links[i];const to=link.to;const parser2=recur2(to);srou=srou?flatMapEager2(srou,(ou2)=>parser2(ou2,options)):parser2(ou,options);if(link.transformation._tag==="Transformation"){const getter=link.transformation.decode;srou=flatMapEager2(srou,(ou2)=>getter.run(ou2,options))}else{srou=link.transformation.decode(srou,options)}}srou=mapSchemaIssueEffect(srou,(issue)=>new Encoding(ast,ou,issue))}parser??=ast.getParser(recur2);const parseLocal=(localOu)=>{let sroa2=parser(localOu,options);if(encodingChecks&&!options?.disableChecks){sroa2=flatMapEager2(sroa2,(oa)=>{if(isSome2(localOu)&&isSome2(oa)){const issues=[];collectIssues(encodingChecks,localOu.value,issues,ast,options);if(isArrayNonEmpty2(issues)){return fail6(new Composite(ast,localOu,issues))}}return succeed6(oa)})}if(checks&&!options?.disableChecks){if(options?.errors==="all"&&structuralChecks&&structuralChecks.length>0&&isSome2(localOu)){sroa2=mapSchemaIssueEffect(sroa2,(issue)=>{const issues=[];collectIssues(structuralChecks,localOu.value,issues,ast,options);const out=isArrayNonEmpty2(issues)?issue._tag==="Composite"&&issue.ast===ast?new Composite(ast,issue.actual,[...issue.issues,...issues]):new Composite(ast,localOu,[issue,...issues]):issue;return out})}sroa2=flatMapEager2(sroa2,(oa)=>{if(isSome2(oa)){const value3=oa.value;const issues=[];collectIssues(checks,value3,issues,ast,options);if(isArrayNonEmpty2(issues)){return fail6(new Composite(ast,oa,issues))}}return succeed6(oa)})}return sroa2};const sroa=srou?flatMapEager2(srou,parseLocal):parseLocal(ou);return sroa}});var toEquivalence=memoize((ast)=>{return recur3(ast,[])});function recur3(ast,path){const annotation=resolve(ast)?.["toEquivalence"];if(annotation){return annotation(isDeclaration(ast)?ast.typeParameters.map((tp)=>recur3(tp,path)):[])}switch(ast._tag){case"Never":throw errorWithPath(`Unsupported AST ${ast._tag}`,path);case"Declaration":case"Null":case"Undefined":case"Void":case"Unknown":case"Any":case"String":case"Number":case"Boolean":case"BigInt":case"Symbol":case"Literal":case"UniqueSymbol":case"ObjectKeyword":case"Enum":case"TemplateLiteral":return equals;case"Arrays":{const elements=ast.elements.map((e,i)=>recur3(e,[...path,i]));const len=ast.elements.length;const rest=ast.rest.map((r,i)=>recur3(r,[...path,len+i]));return make3((a,b)=>{if(!Array.isArray(a)||!Array.isArray(b)){return false}const len2=a.length;if(len2!==b.length){return false}let i=0;for(;i<Math.min(len2,ast.elements.length);i++){if(!elements[i](a[i],b[i])){return false}}if(rest.length>0){const[head,...tail]=rest;for(;i<len2-tail.length;i++){if(!head(a[i],b[i])){return false}}for(let j=0;j<tail.length;j++){if(!tail[j](a[i+j],b[i+j])){return false}}}return true})}case"Objects":{if(ast.propertySignatures.length===0&&ast.indexSignatures.length===0){return equals}const propertySignatures=ast.propertySignatures.map((ps)=>recur3(ps.type,[...path,ps.name]));const indexSignatures=ast.indexSignatures.map((is2)=>recur3(is2.type,path));return make3((a,b)=>{if(!isObject(a)||!isObject(b)){return false}for(let i=0;i<propertySignatures.length;i++){const ps=ast.propertySignatures[i];const name=ps.name;const aHas=Object.hasOwn(a,name);const bHas=Object.hasOwn(b,name);if(isOptional(ps.type)){if(aHas!==bHas){return false}}if(aHas&&bHas&&!propertySignatures[i](a[name],b[name])){return false}}for(let i=0;i<indexSignatures.length;i++){const is2=ast.indexSignatures[i];const aKeys=getIndexSignatureKeys(a,is2.parameter);const bKeys=getIndexSignatureKeys(b,is2.parameter);if(aKeys.length!==bKeys.length)return false;for(let j=0;j<aKeys.length;j++){const key=aKeys[j];if(!Object.hasOwn(b,key)||!indexSignatures[i](a[key],b[key])){return false}}}return true})}case"Union":return make3((a,b)=>{const candidates=getCandidates(a,ast.types);const types=candidates.map(_is);for(let i=0;i<candidates.length;i++){const is2=types[i];if(is2(a)&&is2(b)){return recur3(candidates[i],path)(a,b)}}return false});case"Suspend":{const get5=memoizeThunk(()=>recur3(ast.thunk(),path));return make3((a,b)=>get5()(a,b))}}}function escapeToken(token){return token.replace(/~/g,"~0").replace(/\//g,"~1")}function unescapeToken(token){return token.replace(/~1/g,"/").replace(/~0/g,"~")}var RegExp2=globalThis.RegExp;var escape=(string3)=>string3.replace(/[/\\^$*+?.()|[\]{}]/g,"\\$&");var TypeId30="~effect/SchemaError/SchemaError";class SchemaError extends TaggedError2("SchemaError"){[TypeId30]=TypeId30;constructor(issue){super({issue})}get message(){return this.issue.toString()}toString(){return`SchemaError(${this.message})`}}function isSchemaError(u){return hasProperty(u,TypeId30)}var TypeId31="~effect/Schema/Schema";var SchemaProto={[TypeId31]:TypeId31,pipe(){return pipeArguments(this,arguments)},annotate(annotations){return this.rebuild(annotate(this.ast,annotations))},annotateKey(annotations){return this.rebuild(annotateKey(this.ast,annotations))},check(...checks){return this.rebuild(appendChecks(this.ast,checks))}};function make24(ast,options){const self=Object.create(SchemaProto);if(options){Object.assign(self,options)}self.ast=ast;self.rebuild=(ast2)=>make24(ast2,options);const makeEffect2=makeEffect(self);self.makeEffect=(input,options2)=>fromIssueEffect(makeEffect2(input,options2));self.make=make23(self);self.makeOption=makeOption(self);return self}function fromIssueEffect(self){return catchCause2(self,(cause)=>failCauseSync2(()=>map6(cause,(issue)=>new SchemaError(issue))))}var jsonReorder=makeReorder(getJsonPriority);function getJsonPriority(ast){switch(ast._tag){case"BigInt":case"Symbol":case"UniqueSymbol":return 0;default:return 1}}function makeReorder(getPriority){return(types)=>{const indexMap=new Map;for(let i=0;i<types.length;i++){indexMap.set(toEncoded(types[i]),i)}const sortedTypes=[...types].sort((a,b)=>{a=toEncoded(a);b=toEncoded(b);const pa=getPriority(a);const pb=getPriority(b);if(pa!==pb)return pa-pb;return indexMap.get(a)-indexMap.get(b)});const orderChanged=sortedTypes.some((ast,index2)=>ast!==types[index2]);if(!orderChanged)return types;return sortedTypes}}function fromAST(ast){const{references,representations:schemas}=fromASTs([ast]);return{representation:schemas[0],references}}function fromASTs(asts){const references={};const referenceMap=new Map;const uniqueReferences=new Set;const visiting=new Set;const schemas=map4(asts,(ast)=>recur4(ast));return{representations:schemas,references};function gen3(prefix){let candidate=prefix;let suffix=0;while(uniqueReferences.has(candidate)){candidate=`${prefix}${++suffix}`}uniqueReferences.add(candidate);return candidate}function recur4(ast,prefix){const found=referenceMap.get(ast);if(found!==undefined){return{_tag:"Reference",$ref:found}}const last=getLastEncoding(ast);const identifier2=resolveIdentifier(ast)??prefix;if(ast!==last){return recur4(last,identifier2)}if(identifier2!==undefined){const reference=gen3(identifier2);referenceMap.set(ast,reference);const out2=on(ast);const found2=references[identifier2];if(found2!==undefined&&equals(out2,found2)){referenceMap.set(ast,identifier2);return{_tag:"Reference",$ref:identifier2}}references[reference]=out2;return{_tag:"Reference",$ref:reference}}if(visiting.has(ast)){const reference=gen3(`${ast._tag}_`);referenceMap.set(ast,reference);return{_tag:"Reference",$ref:reference}}visiting.add(ast);const out=on(ast);visiting.delete(ast);const ref=referenceMap.get(ast);if(ref!==undefined){references[ref]=out;return{_tag:"Reference",$ref:ref}}return out}function getEncodedSchema(last){const getLink=last.annotations?.toCodecJson??last.annotations?.toCodec;if(isFunction(getLink)){return replaceEncoding(last,[getLink(last.typeParameters.map((tp)=>make24(toEncoded(tp))))])}return null_}function on(last){const annotations=fromASTAnnotations(last.annotations);switch(last._tag){case"Declaration":{const encodedSchema=recur4(getEncodedSchema(last));return{_tag:"Declaration",typeParameters:last.typeParameters.map((ast)=>recur4(ast)),encodedSchema,checks:fromASTChecks(last.checks),...annotations}}case"Null":case"Undefined":case"Void":case"Never":case"Unknown":case"Any":case"Boolean":case"Symbol":case"ObjectKeyword":return{_tag:last._tag,...annotations};case"String":{const contentMediaType=last.annotations?.contentMediaType;const contentSchema=last.annotations?.contentSchema;return{_tag:last._tag,checks:fromASTChecks(last.checks),...annotations,...typeof contentMediaType==="string"&&isAST(contentSchema)?{contentSchema:recur4(contentSchema)}:undefined}}case"Number":case"BigInt":return{_tag:last._tag,checks:fromASTChecks(last.checks),...annotations};case"Literal":return{_tag:last._tag,literal:last.literal,...annotations};case"UniqueSymbol":return{_tag:last._tag,symbol:last.symbol,...annotations};case"Enum":return{_tag:last._tag,enums:last.enums,...annotations};case"TemplateLiteral":return{_tag:last._tag,parts:last.parts.map((ast)=>recur4(ast)),...annotations};case"Arrays":return{_tag:last._tag,elements:last.elements.map((e)=>{const last2=getLastEncoding(e);return{isOptional:isOptional(last2),type:recur4(e),...fromASTAnnotations(last2.context?.annotations)}}),rest:last.rest.map((ast)=>recur4(ast)),checks:fromASTChecks(last.checks),...annotations};case"Objects":return{_tag:last._tag,propertySignatures:last.propertySignatures.map((ps)=>{const last2=getLastEncoding(ps.type);return{name:ps.name,type:recur4(ps.type),isOptional:isOptional(last2),isMutable:isMutable(last2),...fromASTAnnotations(last2.context?.annotations)}}),indexSignatures:last.indexSignatures.map((is2)=>({parameter:recur4(is2.parameter),type:recur4(is2.type)})),checks:fromASTChecks(last.checks),...annotations};case"Union":{const types=jsonReorder(last.types);return{_tag:last._tag,types:types.map((ast)=>recur4(ast)),mode:last.mode,...annotations}}case"Suspend":{return{_tag:"Suspend",checks:[],thunk:recur4(last.thunk()),...annotations}}}}function fromASTChecks(checks){if(!checks)return[];return checks.map(getCheck).filter((c)=>c!==undefined);function getCheck(c){switch(c._tag){case"Filter":{const meta=c.annotations?.meta;if(meta){return{_tag:"Filter",meta:meta._tag==="isPropertyNames"?{_tag:"isPropertyNames",propertyNames:recur4(meta.propertyNames)}:meta,...fromASTAnnotations(c.annotations)}}return}case"FilterGroup":{const checks2=fromASTChecks(c.checks);if(isArrayNonEmpty2(checks2)){return{_tag:"FilterGroup",checks:checks2,...fromASTAnnotations(c.annotations)}}}}}}}var fromASTBlacklist=new Set(["~structural","~sentinels","meta","arbitrary","toArbitrary","toEquivalence","toFormatter","toCodec","toCodecJson","toCodecIso",ClassTypeId]);var standardJsonSchemaAnnotationKeys=new Set(["title","description","default","examples","readOnly","writeOnly","format","contentEncoding","contentMediaType","contentSchema"]);function fromASTAnnotations(annotations){if(annotations!==undefined){const filtered=filter3(annotations,(_,k)=>!fromASTBlacklist.has(k));if(!isEmptyRecord(filtered)){return{annotations:filtered}}}return}function toJsonSchemaDocument(document,options){const{definitions,dialect:source,schemas}=toJsonSchemaMultiDocument({representations:[document.representation],references:document.references},options);const schema=schemas[0];return{dialect:source,schema,definitions}}function toJsonSchemaMultiDocument(multiDocument,options){const generateDescriptions=options?.generateDescriptions??false;const additionalProperties=options?.additionalProperties??false;const includeAnnotationKey=options?.includeAnnotationKey;const definitions=map3(multiDocument.references,(d)=>recur4(d));return{dialect:"draft-2020-12",schemas:map4(multiDocument.representations,(s)=>recur4(s)),definitions};function recur4(s){let js=on(s);if("annotations"in s){const a=collectJsonSchemaAnnotations(s.annotations);if(a){js={...js,...a}}}if("checks"in s){const checks=collectJsonSchemaChecks(s.checks,js.type);for(const check of checks){js=appendJsonSchema(js,check)}}return js}function on(schema){switch(schema._tag){case"Any":case"Unknown":return{};case"ObjectKeyword":return{anyOf:[{type:"object"},{type:"array"}]};case"Void":case"Undefined":return{type:"null"};case"BigInt":return{type:"string",allOf:[{pattern:"^-?\\d+$"}]};case"Symbol":case"UniqueSymbol":return{type:"string",allOf:[{pattern:"^Symbol\\((.*)\\)$"}]};case"Declaration":return recur4(schema.encodedSchema);case"Suspend":return recur4(schema.thunk);case"Reference":return{$ref:`#/$defs/${escapeToken(schema.$ref)}`};case"Null":return{type:"null"};case"Never":return{not:{}};case"String":{const out={type:"string"};if(schema.contentMediaType!==undefined){out.contentMediaType=schema.contentMediaType}if(schema.contentSchema!==undefined){out.contentSchema=recur4(schema.contentSchema)}return out}case"Number":return hasCheck2(schema.checks,"isInt")?{type:"integer"}:hasCheck2(schema.checks,"isFinite")?{type:"number"}:{anyOf:[{type:"number"},{type:"string",enum:["NaN"]},{type:"string",enum:["Infinity"]},{type:"string",enum:["-Infinity"]}]};case"Boolean":return{type:"boolean"};case"Literal":{const literal=schema.literal;if(typeof literal==="string"){return{type:"string",enum:[literal]}}if(typeof literal==="number"){return{type:"number",enum:[literal]}}if(typeof literal==="boolean"){return{type:"boolean",enum:[literal]}}return{type:"string",enum:[String(literal)]}}case"Enum":{return recur4({_tag:"Union",types:schema.enums.map(([title,value3])=>({_tag:"Literal",literal:value3,annotations:{title}})),mode:"anyOf",annotations:schema.annotations})}case"TemplateLiteral":{const pattern=schema.parts.map(getPartPattern).join("");return{type:"string",pattern:`^${pattern}$`}}case"Arrays":{if(schema.rest.length>1){throw new globalThis.Error("Generating a JSON Schema for post-rest elements is not supported")}const out={type:"array"};let minItems=schema.elements.length;const prefixItems=schema.elements.map((e)=>{if(e.isOptional){minItems--}const v=recur4(e.type);const a=collectJsonSchemaAnnotations(e.annotations);return a?appendJsonSchema(v,a):v});if(prefixItems.length>0){out.prefixItems=prefixItems;out.maxItems=schema.elements.length;if(minItems>0){out.minItems=minItems}}else{out.items=false}if(schema.rest.length>0){delete out.maxItems;const rest=recur4(schema.rest[0]);if(Object.keys(rest).length>0){out.items=rest}else{delete out.items}}return out}case"Objects":{if(schema.propertySignatures.length===0&&schema.indexSignatures.length===0){return{anyOf:[{type:"object"},{type:"array"}]}}const out={type:"object"};const properties={};const required=[];for(const ps of schema.propertySignatures){const name=ps.name;if(typeof name!=="string"){throw new globalThis.Error(`Unsupported property signature name: ${format(name)}`)}const v=recur4(ps.type);const a=collectJsonSchemaAnnotations(ps.annotations);properties[name]=a?appendJsonSchema(v,a):v;if(!ps.isOptional){required.push(name)}}if(Object.keys(properties).length>0){out.properties=properties}if(required.length>0){out.required=required}out.additionalProperties=additionalProperties;const patternProperties={};for(const is2 of schema.indexSignatures){let type=recur4(is2.type);if(Object.keys(type).length===1&&"not"in type){type=false}const patterns=getParameterPatterns(is2.parameter);if(patterns.length>0){for(const pattern of patterns){patternProperties[pattern]=type}}else{out.additionalProperties=type}}if(Object.keys(patternProperties).length>0){out.patternProperties=patternProperties;delete out.additionalProperties}if(isObject(out.additionalProperties)&&isEmptyRecord(out.additionalProperties)){delete out.additionalProperties}return out}case"Union":{const types=schema.types.map(recur4);if(types.length===0){return{not:{}}}if(types.length>1){const compacted=compactEnums(types);if(compacted)return compacted}return schema.mode==="anyOf"?{anyOf:types}:{oneOf:types}}}}function compactEnums(types){let sharedType;const values3=[];for(const t of types){const keys3=Object.keys(t);if(keys3.length!==2||t.type===undefined||!Array.isArray(t.enum)||t.enum.length===0){return}if(sharedType===undefined){sharedType=t.type}else if(t.type!==sharedType){return}for(const v of t.enum){values3.push(v)}}return{type:sharedType,enum:values3}}function collectJsonSchemaAnnotations(annotations){if(annotations===undefined)return;const out={};if(typeof annotations.title==="string")out.title=annotations.title;if(typeof annotations.description==="string")out.description=annotations.description;else if(generateDescriptions&&typeof annotations.expected==="string")out.description=annotations.expected;if(annotations.default!==undefined)out.default=annotations.default;if(Array.isArray(annotations.examples))out.examples=annotations.examples;if(typeof annotations.readOnly==="boolean")out.readOnly=annotations.readOnly;if(typeof annotations.writeOnly==="boolean")out.writeOnly=annotations.writeOnly;if(typeof annotations.format==="string")out.format=annotations.format;if(typeof annotations.contentEncoding==="string")out.contentEncoding=annotations.contentEncoding;if(typeof annotations.contentMediaType==="string")out.contentMediaType=annotations.contentMediaType;if(includeAnnotationKey){for(const[key,value3]of Object.entries(annotations)){if(value3===undefined)continue;if(standardJsonSchemaAnnotationKeys.has(key))continue;if(!includeAnnotationKey(key))continue;out[key]=value3}}if(Object.keys(out).length>0)return out}function collectJsonSchemaChecks(checks,type){return checks.map(collectJsonSchemaCheck).filter((c)=>c!==undefined);function collectJsonSchemaCheck(check){switch(check._tag){case"Filter":return filterToJsonSchema(check,type);case"FilterGroup":{const checks2=check.checks.map(collectJsonSchemaCheck).filter((c)=>c!==undefined);if(checks2.length===0)return;let out={allOf:checks2};const a=collectJsonSchemaAnnotations(check.annotations);if(a){out={...out,...a}}return out}}}}function filterToJsonSchema(filter10,type){const meta=filter10.meta;if(!meta)return;let out=on2(meta);const a=collectJsonSchemaAnnotations(filter10.annotations);if(a){out={...out,...a}}return out;function on2(meta2){switch(meta2._tag){case"isMinLength":return type==="array"?{minItems:meta2.minLength}:{minLength:meta2.minLength};case"isMaxLength":return type==="array"?{maxItems:meta2.maxLength}:{maxLength:meta2.maxLength};case"isLengthBetween":return type==="array"?{allOf:[{minItems:meta2.minimum},{maxItems:meta2.maximum}]}:{allOf:[{minLength:meta2.minimum},{maxLength:meta2.maximum}]};case"isPattern":case"isGUID":case"isULID":case"isBase64":case"isBase64Url":case"isStartsWith":case"isEndsWith":case"isIncludes":case"isUppercased":case"isLowercased":case"isCapitalized":case"isUncapitalized":case"isTrimmed":case"isStringFinite":case"isStringBigInt":case"isStringSymbol":return{pattern:meta2.regExp.source};case"isUUID":return{pattern:meta2.regExp.source,format:"uuid"};case"isFinite":case"isInt":return;case"isMultipleOf":return{multipleOf:meta2.divisor};case"isGreaterThanOrEqualTo":return{minimum:meta2.minimum};case"isLessThanOrEqualTo":return{maximum:meta2.maximum};case"isGreaterThan":return{exclusiveMinimum:meta2.exclusiveMinimum};case"isLessThan":return{exclusiveMaximum:meta2.exclusiveMaximum};case"isBetween":{return{[meta2.exclusiveMinimum?"exclusiveMinimum":"minimum"]:meta2.minimum,[meta2.exclusiveMaximum?"exclusiveMaximum":"maximum"]:meta2.maximum}}case"isUnique":return{uniqueItems:true};case"isMinProperties":return{minProperties:meta2.minProperties};case"isMaxProperties":return{maxProperties:meta2.maxProperties};case"isPropertiesLengthBetween":return{minProperties:meta2.minimum,maxProperties:meta2.maximum};case"isPropertyNames":return{propertyNames:recur4(meta2.propertyNames)};case"isDateValid":return{format:"date-time"}}}}function getParameterPatterns(parameter){switch(parameter._tag){default:throw new globalThis.Error(`Unsupported index signature parameter: ${parameter._tag}`);case"Reference":return getParameterPatterns(multiDocument.references[parameter.$ref]);case"String":return getPatterns(parameter);case"TemplateLiteral":return[`^${parameter.parts.map(getPartPattern).join("")}$`];case"Union":return parameter.types.flatMap(getParameterPatterns)}}}function getPatterns(s){return recur4(s.checks);function recur4(checks){return checks.flatMap((c)=>{switch(c._tag){case"Filter":{if("regExp"in c.meta){return[c.meta.regExp.source]}return[]}case"FilterGroup":return recur4(c.checks)}})}}function hasCheck2(checks,tag){return checks.some((c)=>{switch(c._tag){case"Filter":return c.meta._tag===tag;case"FilterGroup":return hasCheck2(c.checks,tag)}})}function appendJsonSchema(a,b){if(Object.keys(a).length===0)return b;const len=Object.keys(b).length;if(len===0)return a;const members=Array.isArray(b.allOf)&&len===1?b.allOf:[b];if(Array.isArray(a.allOf)){return{...a,allOf:[...a.allOf,...members]}}if(typeof a.$ref==="string"){return{allOf:[a,...members]}}return{...a,allOf:members}}function getPartPattern(part){switch(part._tag){case"Literal":return escape(globalThis.String(part.literal));case"String":return STRING_PATTERN;case"Number":return FINITE_PATTERN;case"TemplateLiteral":return part.parts.map(getPartPattern).join("");case"Union":return part.types.map(getPartPattern).join("|");default:throw new globalThis.Error("Unsupported part",{cause:part})}}function get5(oldValue,newValue){if(Object.is(oldValue,newValue))return[];const patches=[];if(Array.isArray(oldValue)&&Array.isArray(newValue)){const len1=oldValue.length;const len2=newValue.length;const shared=Math.min(len1,len2);for(let i=0;i<shared;i++){const path=`/${i}`;const patch=get5(oldValue[i],newValue[i]);for(const op of patch){prefixPathInPlace(op,path);patches.push(op)}}for(let i=len1-1;i>=len2;i--){patches.push({op:"remove",path:`/${i}`})}for(let i=len1;i<len2;i++){patches.push({op:"add",path:`/${i}`,value:newValue[i]})}return patches}if(isJsonObject(oldValue)&&isJsonObject(newValue)){const keys1=Object.keys(oldValue);const keys22=Object.keys(newValue);const allKeys=Array.from(new Set([...keys1,...keys22])).sort();for(const key of allKeys){const esc=escapeToken(key);const path=`/${esc}`;const hasKey1=Object.hasOwn(oldValue,key);const hasKey2=Object.hasOwn(newValue,key);if(hasKey1&&hasKey2){const patch=get5(oldValue[key],newValue[key]);for(const op of patch){prefixPathInPlace(op,path);patches.push(op)}}else if(!hasKey1&&hasKey2){patches.push({op:"add",path,value:newValue[key]})}else if(hasKey1&&!hasKey2){patches.push({op:"remove",path})}}return patches}patches.push({op:"replace",path:"",value:newValue});return patches}function apply(patch,oldValue){let doc=oldValue;for(const op of patch){switch(op.op){case"replace":{doc=op.path===""?op.value:setAt(doc,op.path,op.value,"replace");break}case"add":{doc=addAt(doc,op.path,op.value);break}case"remove":{doc=setAt(doc,op.path,undefined,"remove");break}}}return doc}function prefixPathInPlace(op,parent){op.path=op.path===""?parent:parent+op.path}function isJsonObject(value3){return isObject(value3)}function tokenize(pointer){if(pointer==="")return[];if(pointer.charCodeAt(0)!==47){throw new Error(`Invalid JSON Pointer, it must start with "/": ${format(pointer)}`)}return pointer.split("/").slice(1).map(unescapeToken)}function toIndex(token){if(!/^(0|[1-9]\d*)$/.test(token)){throw new Error(`Invalid array index: "${token}"`)}return Number(token)}function addAt(doc,pointer,val){if(pointer==="")return val;const resolved=resolveParent(doc,pointer);if(resolved===null){throw new Error(`Cannot add at "${pointer}" (parent not found or not a container).`)}const{lastToken,parent,stack}=resolved;if(Array.isArray(parent)){const idx=lastToken==="-"?parent.length:toIndex(lastToken);if(idx<0||idx>parent.length)throw new Error(`Array index out of bounds at "${pointer}".`);const updated=parent.slice();updated.splice(idx,0,val);return rebuildFromStack(stack,updated)}if(isJsonObject(parent)){const updated={...parent};updated[lastToken]=val;return rebuildFromStack(stack,updated)}throw new Error(`Cannot add at "${pointer}" (parent not found or not a container).`)}function setAt(doc,pointer,val,mode){if(pointer===""){if(mode==="remove"||val===undefined)throw new Error("Unsupported operation at the root");return val}const resolved=resolveParent(doc,pointer);if(resolved===null){throw new Error(`Cannot ${mode} at "${pointer}" (parent not found or not a container).`)}const{lastToken,parent,stack}=resolved;if(Array.isArray(parent)){if(lastToken==="-")throw new Error(`"-" is not valid for ${mode} at "${pointer}".`);const idx=toIndex(lastToken);if(idx<0||idx>=parent.length)throw new Error(`Array index out of bounds at "${pointer}".`);const updated=parent.slice();if(mode==="remove")updated.splice(idx,1);else updated[idx]=val;return rebuildFromStack(stack,updated)}if(isJsonObject(parent)){if(!Object.hasOwn(parent,lastToken)){throw new Error(`Property "${lastToken}" does not exist at "${pointer}".`)}const updated={...parent};if(mode==="remove")delete updated[lastToken];else updated[lastToken]=val;return rebuildFromStack(stack,updated)}throw new Error(`Cannot ${mode} at "${pointer}" (parent not found or not a container).`)}function resolveParent(doc,pointer){const tokens=tokenize(pointer);if(tokens.length===0)return null;const lastToken=tokens[tokens.length-1];const stack=[];let cur=doc;for(let i=0;i<tokens.length-1;i++){const token=tokens[i];if(cur==null)return null;if(Array.isArray(cur)){const idx=toIndex(token);if(idx<0||idx>=cur.length)return null;stack.push({container:cur,token:idx});cur=cur[idx];continue}if(cur&&typeof cur==="object"){if(!Object.hasOwn(cur,token))return null;stack.push({container:cur,token});cur=cur[token];continue}return null}return{stack,parent:cur,lastToken}}function rebuildFromStack(stack,newParent){let acc=newParent;for(let i=stack.length-1;i>=0;i--){const{container,token}=stack[i];if(Array.isArray(container)){const copy2=container.slice();copy2[token]=acc;acc=copy2}else{const copy2={...container};copy2[token]=acc;acc=copy2}}return acc}var RE_DEFS=/^#\/\$defs(?=\/|$)/;function toDocumentDraft07(document){return{dialect:"draft-07",schema:toSchemaDraft07(document.schema),definitions:map3(document.definitions,toSchemaDraft07)}}function toSchemaDraft07(schema){return rewrite(schema);function rewrite(node){return walk(rewrite_refs(node,(ref)=>ref.replace(RE_DEFS,"#/definitions")),true)}function walk(node,_isRoot){if(Array.isArray(node))return node.map((v)=>walk(v,false));if(!isObject(node))return node;const src=node;const out={};let prefixItems=undefined;let items=undefined;for(const k of Object.keys(src)){const v=src[k];switch(k){case"$ref":case"type":case"required":case"enum":case"const":case"title":case"description":case"default":case"examples":case"format":case"pattern":case"minimum":case"maximum":case"exclusiveMinimum":case"exclusiveMaximum":case"minLength":case"maxLength":case"minItems":case"maxItems":case"minProperties":case"maxProperties":case"multipleOf":case"uniqueItems":out[k]=v;break;case"properties":case"patternProperties":{const mapped=walk_object(v,walk);out[k]=mapped??v;break}case"additionalProperties":case"propertyNames":out[k]=walk(v,false);break;case"allOf":case"anyOf":case"oneOf":out[k]=Array.isArray(v)?v.map((x)=>walk(x,false)):v;break;case"prefixItems":prefixItems=v;break;case"items":items=v;break;default:break}}if(prefixItems!==undefined){if(Array.isArray(prefixItems)){out.items=prefixItems.map((x)=>walk(x,false));if(items!==undefined)out.additionalItems=walk(items,false)}else{out.items=walk(prefixItems,false)}}else if(items!==undefined){out.items=walk(items,false)}return out}}function toMultiDocumentOpenApi3_1(multiDocument){const keyMap2=new Map;for(const key of Object.keys(multiDocument.definitions)){const sanitized=sanitizeOpenApiComponentsSchemasKey(key);if(sanitized!==key){keyMap2.set(key,sanitized)}}function rewrite(schema){return rewrite_refs(schema,($ref)=>{const tokens=$ref.split("/");if(tokens.length>0){const identifier2=unescapeToken(tokens[tokens.length-1]);const sanitized=keyMap2.get(identifier2);if(sanitized!==undefined){$ref=tokens.slice(0,-1).join("/")+"/"+sanitized}}return $ref.replace(RE_DEFS,"#/components/schemas")})}return{dialect:"openapi-3.1",schemas:map4(multiDocument.schemas,rewrite),definitions:mapEntries(multiDocument.definitions,(definition,key)=>[keyMap2.get(key)??key,rewrite(definition)])}}var VALID_OPEN_API_COMPONENTS_SCHEMAS_KEY_REGEXP=/^[a-zA-Z0-9.\-_]+$/;function sanitizeOpenApiComponentsSchemasKey(s){if(s.length===0)return"_";if(VALID_OPEN_API_COMPONENTS_SCHEMAS_KEY_REGEXP.test(s))return s;const out=[];for(const ch of s){const code=ch.codePointAt(0);if(code!==undefined&&(code>=48&&code<=57||code>=65&&code<=90||code>=97&&code<=122||code===46||code===45||code===95)){out.push(ch)}else{out.push("_")}}return out.join("")}function rewrite_refs(node,f){if(Array.isArray(node))return node.map((v)=>rewrite_refs(v,f));if(!isObject(node))return node;const out={};for(const k of Object.keys(node)){const v=node[k];if(k==="$ref"){out[k]=typeof v==="string"?f(v):v}else if(Array.isArray(v)||isObject(v)){out[k]=rewrite_refs(v,f)}else{out[k]=v}}return out}function walk_object(value3,walk){if(!isObject(value3))return;const out={};for(const k of Object.keys(value3))out[k]=walk(value3[k],false);return out}function makeIso(get6,set3){return make25(new IsoNode(get6,set3))}function makeLens(get6,replace){return make25(new LensNode(get6,replace))}class IdentityNode{_tag="IdentityNode"}var identityNode=new IdentityNode;class CompositionNode{_tag="CompositionNode";nodes;constructor(nodes){this.nodes=nodes}}class IsoNode{_tag="IsoNode";get;set;constructor(get6,set3){this.get=get6;this.set=set3}}class LensNode{_tag="LensNode";get;set;constructor(get6,set3){this.get=get6;this.set=set3}}class PrismNode{_tag="PrismNode";get;set;constructor(get6,set3){this.get=get6;this.set=set3}}class OptionalNode{_tag="OptionalNode";get;set;constructor(get6,set3){this.get=get6;this.set=set3}}class PathNode{_tag="PathNode";path;constructor(path){this.path=path}}class CheckNode{_tag="CheckNode";checks;constructor(checks){this.checks=checks}}function pushNormalized(acc,node){const last=acc[acc.length-1];if(last){if(last._tag==="PathNode"&&node._tag==="PathNode"){acc[acc.length-1]=new PathNode([...last.path,...node.path]);return}if(last._tag==="CheckNode"&&node._tag==="CheckNode"){acc[acc.length-1]=new CheckNode([...last.checks,...node.checks]);return}}acc.push(node)}function collect(node,acc){if(node._tag==="IdentityNode")return;if(node._tag==="CompositionNode"){for(let i=0;i<node.nodes.length;i++)collect(node.nodes[i],acc);return}pushNormalized(acc,node)}function compose(a,b){const nodes=[];collect(a,nodes);collect(b,nodes);switch(nodes.length){case 0:return identityNode;case 1:return nodes[0];default:return new CompositionNode(nodes)}}function makeOptional(getResult,set3){return make25(new OptionalNode(getResult,set3))}class OptionalImpl{node;getResult;replaceResult;constructor(node,getResult,replaceResult){this.node=node;this.getResult=getResult;this.replaceResult=replaceResult}replace(a,s){return getOrElse3(this.replaceResult(a,s),()=>s)}modify(f){return(s)=>getOrElse3(flatMap2(this.getResult(s),(a)=>this.replaceResult(f(a),s)),()=>s)}compose(that){return make25(compose(this.node,that.node))}key(key){return make25(compose(this.node,new PathNode([key])))}optionalKey(key){return make25(compose(this.node,new LensNode((s)=>s[key],(a,s)=>{const copy2=cloneShallow(s);if(a===undefined){if(Array.isArray(copy2)&&typeof key==="number"){copy2.splice(key,1)}else{delete copy2[key]}}else{copy2[key]=a}return copy2})))}check(...checks){return make25(compose(this.node,new CheckNode(checks)))}refine(refinement,annotations){return make25(compose(this.node,new CheckNode([makeFilterByGuard(refinement,annotations)])))}tag(tag){return make25(compose(this.node,new PrismNode((s)=>s._tag===tag?succeed2(s):fail2(`Expected ${format(tag)} tag, got ${format(s._tag)}`),identity)))}at(key,..._rest){const err=fail2(`Key ${format(key)} not found`);return make25(compose(this.node,new OptionalNode((s)=>Object.hasOwn(s,key)?succeed2(s[key]):err,(a,s)=>{if(Object.hasOwn(s,key)){const copy2=cloneShallow(s);copy2[key]=a;return succeed2(copy2)}else{return err}})))}pick(keys3){return this.compose(makeLens(pick(keys3),(p,a)=>({...a,...p})))}omit(keys3){return this.compose(makeLens(omit2(keys3),(o,a)=>({...a,...o})))}notUndefined(){return this.refine(isNotUndefined,{expected:"a value other than `undefined`"})}forEach(f){const inner=f(id());return makeOptional((s)=>map2(this.getResult(s),(as3)=>{const bs=[];for(let i=0;i<as3.length;i++){const r=inner.getResult(as3[i]);if(isSuccess2(r))bs.push(r.success)}return bs}),(bs,s)=>flatMap2(this.getResult(s),(as3)=>{const idxs=[];for(let i=0;i<as3.length;i++){if(isSuccess2(inner.getResult(as3[i])))idxs.push(i)}if(bs.length!==idxs.length){return fail2(`each: replacement length mismatch: ${bs.length} !== ${idxs.length}`)}const out=as3.slice();for(let k=0;k<idxs.length;k++){const i=idxs[k];const r=inner.replaceResult(bs[k],as3[i]);if(isFailure2(r)){return fail2(`each: could not set element ${i}`)}out[i]=r.success}return this.replaceResult(out,s)}))}modifyAll(f){return(s)=>getOrElse3(flatMap2(this.getResult(s),(as3)=>this.replaceResult(as3.map(f),s)),()=>s)}}class IsoImpl extends OptionalImpl{get;set;constructor(node,get6,set3){super(node,(s)=>succeed2(get6(s)),(a)=>succeed2(set3(a)));this.get=get6;this.set=set3}replace(a,_){return this.set(a)}modify(f){return(s)=>this.set(f(this.get(s)))}}class LensImpl extends OptionalImpl{get;constructor(node,get6,replace){super(node,(s)=>succeed2(get6(s)),(a,s)=>succeed2(replace(a,s)));this.get=get6;this.replace=replace}modify(f){return(s)=>this.replace(f(this.get(s)),s)}}class PrismImpl extends OptionalImpl{set;constructor(node,getResult,set3){super(node,getResult,(a,_)=>succeed2(set3(a)));this.set=set3}replace(a,_){return this.set(a)}modify(f){return(s)=>getOrElse3(map2(this.getResult(s),(a)=>this.set(f(a))),()=>s)}}function make25(node){const op=recur4(node);switch(op._tag){case"IsoNode":return new IsoImpl(node,op.get,op.set);case"LensNode":return new LensImpl(node,op.get,op.set);case"PrismNode":return new PrismImpl(node,op.get,op.set);case"OptionalNode":return new OptionalImpl(node,op.get,op.set)}}function cloneShallow(pojo){if(Array.isArray(pojo))return pojo.slice();if(typeof pojo==="object"&&pojo!==null){const proto=Object.getPrototypeOf(pojo);if(proto!==Object.prototype&&proto!==null){throw new Error("Cannot clone object with non-Object constructor or null prototype")}return{...pojo}}return pojo}var recur4=memoize((node)=>{switch(node._tag){case"IdentityNode":return{_tag:"IsoNode",get:identity,set:identity};case"IsoNode":case"LensNode":case"PrismNode":case"OptionalNode":return{_tag:node._tag,get:node.get,set:node.set};case"PathNode":{return{_tag:"LensNode",get:(s)=>{const path=node.path;let out=s;for(let i=0,n=path.length;i<n;i++){out=out[path[i]]}return out},set:(a,s)=>{const path=node.path;const out=cloneShallow(s);let current=out;let i=0;for(;i<path.length-1;i++){const key=path[i];current[key]=cloneShallow(current[key]);current=current[key]}const finalKey=path[i];current[finalKey]=a;return out}}}case"CheckNode":return{_tag:"PrismNode",get:(s)=>mapError(runChecks(node.checks,s),String),set:identity};case"CompositionNode":{const ops=node.nodes.map(recur4);const _tag=ops.reduce((tag,op)=>getCompositionTag(tag,op._tag),"IsoNode");return{_tag,get:(s)=>{for(let i=0;i<ops.length;i++){const op=ops[i];const result3=op.get(s);if(hasFailingGet(op._tag)){if(isFailure2(result3)){return result3}s=result3.success}else{s=result3}}return hasFailingGet(_tag)?succeed2(s):s},set:(a,s)=>{const source=s;const len=ops.length;const ss=new Array(len+1);ss[0]=s;for(let i=0;i<len;i++){const op=ops[i];if(hasFailingGet(op._tag)){const result3=op.get(s);if(isFailure2(result3)){return _tag==="OptionalNode"?result3:source}s=result3.success}else{s=op.get(s)}ss[i+1]=s}for(let i=len-1;i>=0;i--){const op=ops[i];if(hasSet(op._tag)){a=op.set(a)}else if(op._tag==="LensNode"){a=op.set(a,ss[i])}else{const result3=op.set(a,ss[i]);if(isFailure2(result3)){return result3}a=result3.success}}return _tag==="OptionalNode"?succeed2(a):a}}}}});function hasFailingGet(tag){return tag==="PrismNode"||tag==="OptionalNode"}function hasSet(tag){return tag==="IsoNode"||tag==="PrismNode"}function getCompositionTag(a,b){switch(a){case"IsoNode":return b;case"LensNode":return hasFailingGet(b)?"OptionalNode":"LensNode";case"PrismNode":return hasSet(b)?"PrismNode":"OptionalNode";case"OptionalNode":return"OptionalNode"}}var identityIso=make25(identityNode);function id(){return identityIso}var exports_FastCheck={};__export(exports_FastCheck,{webUrl:()=>webUrl,webSegment:()=>webSegment,webQueryParameters:()=>webQueryParameters,webPath:()=>webPath,webFragments:()=>webFragments,webAuthority:()=>webAuthority,uuid:()=>uuid,uniqueArray:()=>uniqueArray,ulid:()=>ulid,uint8ClampedArray:()=>uint8ClampedArray,uint8Array:()=>uint8Array,uint32Array:()=>uint32Array,uint16Array:()=>uint16Array,tuple:()=>tuple2,toStringMethod:()=>toStringMethod,subarray:()=>subarray,stringify:()=>stringify,stringMatching:()=>stringMatching,string:()=>string3,stream:()=>stream,statistics:()=>statistics,sparseArray:()=>sparseArray,shuffledSubarray:()=>shuffledSubarray,set:()=>set3,schedulerFor:()=>schedulerFor,scheduler:()=>scheduler,scheduledModelRun:()=>scheduledModelRun,sample:()=>sample,resetConfigureGlobal:()=>resetConfigureGlobal,record:()=>record2,readConfigureGlobal:()=>readConfigureGlobal,property:()=>property,pre:()=>pre,option:()=>option3,oneof:()=>oneof,object:()=>object,noShrink:()=>noShrink,noBias:()=>noBias,nat:()=>nat,modelRun:()=>modelRun,mixedCase:()=>mixedCase,memo:()=>memo,maxSafeNat:()=>maxSafeNat,maxSafeInteger:()=>maxSafeInteger,mapToConstant:()=>mapToConstant,map:()=>map13,lorem:()=>lorem,limitShrink:()=>limitShrink,letrec:()=>letrec,jsonValue:()=>jsonValue,json:()=>json,ipV6:()=>ipV6,ipV4Extended:()=>ipV4Extended,ipV4:()=>ipV4,integer:()=>integer,int8Array:()=>int8Array,int32Array:()=>int32Array,int16Array:()=>int16Array,infiniteStream:()=>infiniteStream,hash:()=>hash2,hasToStringMethod:()=>hasToStringMethod,hasCloneMethod:()=>hasCloneMethod,hasAsyncToStringMethod:()=>hasAsyncToStringMethod,getDepthContextFor:()=>getDepthContextFor,gen:()=>gen3,func:()=>func,float64Array:()=>float64Array,float32Array:()=>float32Array,float:()=>float,falsy:()=>falsy,entityGraph:()=>entityGraph,emailAddress:()=>emailAddress,double:()=>double,domain:()=>domain,dictionary:()=>dictionary,defaultReportMessage:()=>defaultReportMessage,date:()=>date,createDepthIdentifier:()=>createDepthIdentifier,context:()=>context3,constantFrom:()=>constantFrom,constant:()=>constant2,configureGlobal:()=>configureGlobal,compareFunc:()=>compareFunc,compareBooleanFunc:()=>compareBooleanFunc,commands:()=>commands,cloneMethod:()=>cloneMethod,cloneIfNeeded:()=>cloneIfNeeded,clone:()=>clone,check:()=>check,chainUntil:()=>chainUntil,boolean:()=>boolean2,bigUint64Array:()=>bigUint64Array,bigInt64Array:()=>bigInt64Array,bigInt:()=>bigInt2,base64String:()=>base64String,asyncToStringMethod:()=>asyncToStringMethod,asyncStringify:()=>asyncStringify,asyncProperty:()=>asyncProperty,asyncModelRun:()=>asyncModelRun,asyncDefaultReportMessage:()=>asyncDefaultReportMessage,assert:()=>assert,array:()=>array3,anything:()=>anything,__version:()=>__version,__type:()=>__type,__commitHash:()=>__commitHash,VerbosityLevel:()=>VerbosityLevel,Value:()=>Value,Stream:()=>Stream,Random:()=>Random,PreconditionFailure:()=>PreconditionFailure,ExecutionStatus:()=>ExecutionStatus,Arbitrary:()=>Arbitrary});var MULTIPLIER=214013;var INCREMENT=2531011;var MASK=4294967295;var MASK_2=-2147483649;var MULTIPLIER_2=-1443076087;var INCREMENT_2=505908858;var MULTIPLIER_3=1170746341;var INCREMENT_3=-755606699;var JUMP_MULTIPLIER=1994129409;var JUMP_INCREMENT=916127744;var LinearCongruential32=class LinearCongruential322{constructor(seed){this.seed=seed}clone(){return new LinearCongruential322(this.seed)}next(){const s0=this.seed;const s1=Math.imul(s0,MULTIPLIER)+INCREMENT|0;const s2=Math.imul(s0,MULTIPLIER_2)+INCREMENT_2|0;const s3=Math.imul(s0,MULTIPLIER_3)+INCREMENT_3|0;this.seed=s3;const v1=(s1&MASK_2)>>16;const v2=(s2&MASK_2)>>16;return(s3&MASK_2)>>16|v2<<15|v1<<30}jump(){this.seed=Math.imul(this.seed,JUMP_MULTIPLIER)+JUMP_INCREMENT&MASK}getState(){return[this.seed]}};function congruential32(seed){return new LinearCongruential32(seed)}var N=624;var M=397;var A=2567483615;var F=1812433253;var U=11;var S=7;var B=2636928640;var T=15;var C=4022730752;var L=18;var MASK_LOWER=2147483647;var MASK_UPPER=2147483648;var JUMP_COEFS="SUSgbA\\W`E[]KN2RUSo8XVU?HKBFRl11E\\KoWOg5B]XEWG;BE;1:oVK[`B^Z9Qd23^XTnhL>]Unda4f[X;_j9H5QD=cN<5H`3bW>9bk1mjoI2fK0obmAAINOV:>Mek_V9dd<hZ\\gC3?Fm7FEk07QH_3PLm^@?^i\\QMkgP<]oLHmFnlecg5F@7U^@4jhZ?WZS0k@GHehmM36:5^9;>Hmm`co>k:KOSkSbIINb1VFf>LXgP>GUAQTD>Ci>XMGkUflLlb?_FaFUk@?5N7i70@;1o68ah@I<HFH7R2^J:G][Gf962ITWID9GWK8ElD2G5=DcHcL]cA]P2n7A=[<bInM;IHDQnJMReRXDWbVldnGEIPij`E08Xdci3@0c:IBbD4:Nk]?lEN9j^;T`0blZX7eiWE8c`<ak7j05FZi>AjUDh?M1B?^??FAXKThf<aBOXZf7jXYGK>R<;NHk3S9YhM7STJ6`:MIE`S@7298X8W>PNK=@;lLX<i\\TXLL<W@X[X54H]in8M;;n?kkQbajgAMY=Tf9b;ZKf0QUB2FHYWfnfkDoU9YkcLd95T>lK6GM1YL\\lid:J>KYS=iJ]Y>QlF>?R5_[5QeYC=66;A32Ac>OHk_ne^0g>bK:g;KFPgbGUcPR_Z=TX3H9d03bKZ2IhEPKBo>LSGWd0iFdV8C<Y:<>T[O6lC\\blaZ>GoAYP4clf^j1IfnZJ]QeDe2X<HE[LJNWnaCg[P]Co^:IRbWPY?97UePBlZNNHY6LOBM8P>=h?Ye:_f_Sb9Ki5GDYBF4dWeMfdg^ccPllNWM7G1\\UMdoYeOOD5^e@foA22G?ADYo5:FVG[bWo96;>3kc_c1Ab30>30;1@4F8g2hY?DJ4[LOL;ZLLKo2]jo>[KMDUcR279N_kF=3WL@Dd620bMTdA\\U9k``ef2iD9JgJ8CZBHS>F^Uk;<laeaeHS<15OSeS`PcSSKBRBFY]aQ=EgUXGNg=?d56`KA@2BejY0^[_DCX`L=CGMT=BW^6S1i@2ATBVk>3_ocRA>2U:4GPQ6o>5jX2HIcV3S@On6KB<[SKB?FC_AAji9agbBFkAi\\;4I\\UJ]c36Ub@[;gQACVGY<V]SDJBUU]La\\_a@JdOO8gm2T0DJMa:8Hf7>E]noQ[1Kambn??QQ]S?1i0oMGOijb\\aGY6lQ^CJ?9bFle8<eH4UUjBINX;n8@VOA5ah^URV49B[A?ONHhHAC1J5;;h0SXYlG^0W=eJdHh^K4SGe=1HZLLam;D<Q3AOdbPcdX``82\\jo0En8jRVGC73WMCF9`d:0heS?80?C188cSn7H9<daZ]MgS4Pb^1HkA:1PU^5>^h_g[RQV@PnYBRI_]`B]Bh@Uk03eXGY`I16L76H28X`R>IROMeNVUdU[:lghLhPCQZ:4a<30YBZCYnXe[?;jc8gKI2QH2MjnWBm4nGCZW`aVU2a;P<AMI25mlW_Nm][2?b6o851X@lAm]YZ`bWRF1g<Ga:T]1NXH5Veja5P9S9>:aNg:Th1Y=5o78K>LQ8hW@5S?I83Lk5Xk;j5@I3o[d:4RjE^oS30:WP9gC\\i8aSI>QRE@4lP:7lDg8g2`Ql[2I8aBU\\BQ?B4_clL9Q]S;^e1Ob5[>3JER2`c7B=o]fPOWO<DGi;Niba1PoWPPE_Q3aX0OB0mZej\\f_M[J4Y6]1`h2MkF[GiW8Q^d3^_=<I1N2Q7]2<2j[iP7V3V821FaI]A`93bC^Z\\G=WJ;^Ih?B97_iIF@\\Dl<eK1je8SNTWo_=XFMZH<<JYLZ^YQMPgYOV45K_:]kSI8^XlO0]GY=VUfe_C_F6TOcoAlVUH:o=WhhT@K`2KFhe<3\\KXQ>W:M?S_4S5d@J^`[AGA7@3]DnGSCO`\\?E8HT75^d9\\:m\\m1egIfk8cd6bD9\\eU8\\n[Pb0Cgd^S0n9kGJHb]i5XodlKHc34Fhi9K>0U5WK`>7Ff2^KL=WC6:kc?e5C^a1T1:4:^S5flXlGNIj08AfO?Dh7T7dWO>E]NI9?ob7B7P_h[4TEP[EU;GllFTnSmg9:\\[N]<SAoKP_kPlG56A:I3T6EG8Hj=XnUE`KT5U@OQ?]7[N^MFN1_NU4KO_3::Le`8IL9[1Z1H1;V3SC\\N3]S@4U[F2mhT5dYM7[4Pg_Na0_8WTH0`bgceQS8]EG;XgD4Ib4iLTP@kE79Mn>AYRJA1U5^Blhgno:aHVYc03c3J0Vc9FjEV^M75Zfd8kVC9>iJDk`AJ[6f7DK2D^DL\\AX:6b5h31XH;RQB\\N<ZSM=J;6L[`UW^eOIFc1Y]6_dfedIe4ARh72mTXC0WND_IDHVCZRDE0eODARCEETQI5TPUQE=jEH5bS?LP[ai`F5ABRYDo2o\\@=]GT?_9;hc4Lm:\\SF9k1T<0E@fX9BG[]g0nY7k[Qmi@la8`PF0j6@Q?Ii7bLkXQ<lLHf]`:DCh@9JY5>hEVLTdhL\\b1EB0lLh<=WaO@F<;8g<d:@e:LA:cFIEdmQh7hNHfSRToW?8N4:Z1K;XEDRO;OIDh<UdVln?bjgL>?VE98[B\\K<BVjkG8LiSX;fb>jf?DUK00Aih<WY6QD6cEnHBZ8iN_fd<G8Ci`11RUW2QlW]IXV:m?;J0GXXHfGNQ>:D`=fLPbO?VOTEYLj^cNj5PM>jKB5HVjJ4U7lXaTQNL9<@\\1`m\\Ug@VQHd7>jW=ca0`miF7;N0F=GjoQ`RFchKMGTmn8cF@Oh4GGCm7m2`U9j93Tb>=kSERjE_J939F01I1;`<ijk_=_Vn=7RVAI6fnQI5KlF:C44bN<<8K=Z<2TP<1]5?<dB>^LA=ebloE2Y2:9lkh0\\<YKbHD97iE`<C5oj^1>X:??`H6BXF2hG1Q[dF0Q=>W=J?7C\\k1T?<;R44oW?1hY^G8Zm]ZKnfOf0eCFYo6?=D8?<`6HU5SXh1;=:23LmV_FSi;OJfV<^?GkIDPISeHg1LaGE:V3Y3K3H<QJfbY?=;ldZRhnhQT_mGXDLFXXhSONE6Do_0iNZagB:BPGOTH;VhHUTd6LhQm^[;dO]5Hlkg<R:F<Kn\\:I:EGojgWZ2X@SYO_dlH;G8S<>oEKabY`:oU;=JW7ig?S?EYb86b7n8ce\\]IRa]koiWY<RfO;5kUI;7lVeC?[@ZaXDiF04B8R]bg@>O<mQDoUcBLcf^f>m2kMBUloD>Ze@NN^Z11TM`inXYhE_I=kA`:ZF4d\\>`L@;ZP[`ENU5cL[BV6\\Z?Di76:jg3hE6oG6jFc8kP=[GS1;WSedYQW1:U4\\OF32GgmMC<AjO]872bdBb`bKAA?8j78b>T3VfcUB2m4J^CPRU;8dScI]LU]^bBYA5_3:Y0N5i^?200000";var MersenneTwister=class MersenneTwister2{constructor(states,index2){this.states=states;this.index=index2}clone(){return new MersenneTwister2(this.states.slice(),this.index)}next(){let y=this.states[this.index];y^=y>>>U;y^=y<<S&B;y^=y<<T&C;y^=y>>>L;this.index=twistedNext(this.states,this.index);return y}getState(){return[this.index,...this.states]}jump(){const originalStates=this.states.slice();const originalIndex=this.index;this.index=twistedNext(this.states,this.index);for(let i=19932;i>0;--i){if(JUMP_COEFS.charCodeAt(i/6|0)-48&1<<i%6)addState(this.states,this.index,originalStates,originalIndex);this.index=twistedNext(this.states,this.index)}addState(this.states,this.index,originalStates,originalIndex)}};function addState(mt,idx,originalMt,originalIdx){let i=0;if(originalIdx>=idx){for(;i<N-originalIdx;i++)mt[i+idx]^=originalMt[i+originalIdx];for(;i<N-idx;i++)mt[i+idx]^=originalMt[i+originalIdx-N];for(;i<N;i++)mt[i+idx-N]^=originalMt[i+originalIdx-N]}else{for(;i<N-idx;i++)mt[i+idx]^=originalMt[i+originalIdx];for(;i<N-originalIdx;i++)mt[i+idx-N]^=originalMt[i+originalIdx];for(;i<N;i++)mt[i+idx-N]^=originalMt[i+originalIdx-N]}}function twistedNext(mt,idx){if(idx<N-M){const y=mt[idx]&MASK_UPPER|mt[idx+1]&MASK_LOWER;mt[idx]=mt[idx+M]^y>>>1^-(y&1)&A;return idx+1}else if(idx<N-1){const y=mt[idx]&MASK_UPPER|mt[idx+1]&MASK_LOWER;mt[idx]=mt[idx+M-N]^y>>>1^-(y&1)&A;return idx+1}else{const y=mt[idx]&MASK_UPPER|mt[0]&MASK_LOWER;mt[idx]=mt[M-1]^y>>>1^-(y&1)&A;return 0}}function twist(mt){for(let idx=0;idx!==N;++idx)twistedNext(mt,idx)}function mersenne(seed){const out=[seed|0];for(let idx=1;idx!==N;++idx){const xored=out[idx-1]^out[idx-1]>>>30;out.push(Math.imul(F,xored)+idx|0)}twist(out);return new MersenneTwister(out,0)}var jumps=[1667051007,2321340297,1548169110,304075285];var XorShift128Plus=class XorShift128Plus2{constructor(s01,s00,s11,s10){this.s01=s01;this.s00=s00;this.s11=s11;this.s10=s10}clone(){return new XorShift128Plus2(this.s01,this.s00,this.s11,this.s10)}next(){const a0=this.s00^this.s00<<23;const a1=this.s01^(this.s01<<23|this.s00>>>9);const s10=this.s10;const s11=this.s11;const out=this.s00+s10|0;this.s01=s11;this.s00=s10;this.s11=a1^s11^a1>>>18^s11>>>5;this.s10=a0^s10^(a0>>>18|a1<<14)^(s10>>>5|s11<<27);return out}jump(){let ns01=0;let ns00=0;let ns11=0;let ns10=0;let s01=this.s01;let s00=this.s00;let s11=this.s11;let s10=this.s10;for(let i=0;i!==4;++i){const ji=jumps[i];for(let mask2=1;mask2;mask2<<=1){if(ji&mask2){ns01^=s01;ns00^=s00;ns11^=s11;ns10^=s10}const a0=s00^s00<<23;const a1=s01^(s01<<23|s00>>>9);s01=s11;s00=s10;s10=a0^s10^(a0>>>18|a1<<14)^(s10>>>5|s11<<27);s11=a1^s11^a1>>>18^s11>>>5}}this.s01=ns01;this.s00=ns00;this.s11=ns11;this.s10=ns10}getState(){return[this.s01,this.s00,this.s11,this.s10]}};function xorshift128plus(seed){return new XorShift128Plus(-1,~seed,seed|0,0)}var jumps2=[3639956645,3750757012,1261568508,386426335];var XoroShiro128Plus=class XoroShiro128Plus2{constructor(s01,s00,s11,s10){this.s01=s01;this.s00=s00;this.s11=s11;this.s10=s10}clone(){return new XoroShiro128Plus2(this.s01,this.s00,this.s11,this.s10)}next(){const out=this.s00+this.s10|0;const a0=this.s10^this.s00;const a1=this.s11^this.s01;const s00=this.s00;const s01=this.s01;this.s00=s00<<24^s01>>>8^a0^a0<<16;this.s01=s01<<24^s00>>>8^a1^(a1<<16|a0>>>16);this.s10=a1<<5^a0>>>27;this.s11=a0<<5^a1>>>27;return out}jump(){let ns01=0;let ns00=0;let ns11=0;let ns10=0;let s01=this.s01;let s00=this.s00;let s11=this.s11;let s10=this.s10;for(let i=0;i!==4;++i){const ji=jumps2[i];for(let mask2=1;mask2;mask2<<=1){if(ji&mask2){ns01^=s01;ns00^=s00;ns11^=s11;ns10^=s10}const a0=s10^s00;const a1=s11^s01;const s00_=s00;const s01_=s01;s00=s00_<<24^s01_>>>8^a0^a0<<16;s01=s01_<<24^s00_>>>8^a1^(a1<<16|a0>>>16);s10=a1<<5^a0>>>27;s11=a0<<5^a1>>>27}}this.s01=ns01;this.s00=ns00;this.s11=ns11;this.s10=ns10}getState(){return[this.s01,this.s00,this.s11,this.s10]}};function xoroshiro128plus(seed){return new XoroShiro128Plus(-1,~seed,seed|0,0)}function skipN(rng,num){for(let idx=0;idx!==num;++idx)rng.next()}var SBigInt=BigInt;var NumValues=4294967296n;function uniformBigInt(rng,from,to){const diff=to-from+1n;let FinalNumValues=NumValues;let NumIterations=1;while(FinalNumValues<diff){FinalNumValues<<=32n;++NumIterations}let value3=generateNext(NumIterations,rng);if(value3<diff)return value3+from;if(value3+diff<FinalNumValues)return value3%diff+from;const MaxAcceptedRandom=FinalNumValues-FinalNumValues%diff;while(value3>=MaxAcceptedRandom)value3=generateNext(NumIterations,rng);return value3%diff+from}function generateNext(NumIterations,rng){let value3=SBigInt(rng.next()+2147483648);for(let num=1;num<NumIterations;++num){const out=rng.next();value3=(value3<<32n)+SBigInt(out+2147483648)}return value3}function uniformIntInternal(rng,rangeSize){const MaxAllowed=rangeSize>2?~~(4294967296/rangeSize)*rangeSize:4294967296;let deltaV=rng.next()+2147483648;while(deltaV>=MaxAllowed)deltaV=rng.next()+2147483648;return deltaV%rangeSize}function fromNumberToArrayInt64(out,n){if(n<0){const posN=-n;out.sign=-1;out.data[0]=~~(posN/4294967296);out.data[1]=posN>>>0}else{out.sign=1;out.data[0]=~~(n/4294967296);out.data[1]=n>>>0}return out}function substractArrayInt64(out,arrayIntA,arrayIntB){const lowA=arrayIntA.data[1];const highA=arrayIntA.data[0];const signA=arrayIntA.sign;const lowB=arrayIntB.data[1];const highB=arrayIntB.data[0];const signB=arrayIntB.sign;out.sign=1;if(signA===1&&signB===-1){const low2=lowA+lowB;const high=highA+highB+(low2>4294967295?1:0);out.data[0]=high>>>0;out.data[1]=low2>>>0;return out}let lowFirst=lowA;let highFirst=highA;let lowSecond=lowB;let highSecond=highB;if(signA===-1){lowFirst=lowB;highFirst=highB;lowSecond=lowA;highSecond=highA}let reminderLow=0;let low=lowFirst-lowSecond;if(low<0){reminderLow=1;low=low>>>0}out.data[0]=highFirst-highSecond-reminderLow;out.data[1]=low;return out}function uniformArrayIntInternal(rng,out,rangeSize){const maxIndex0=rangeSize[0]+1;out[0]=uniformIntInternal(rng,maxIndex0);out[1]=uniformIntInternal(rng,4294967296);while(out[0]>=rangeSize[0]&&(out[0]!==rangeSize[0]||out[1]>=rangeSize[1])){out[0]=uniformIntInternal(rng,maxIndex0);out[1]=uniformIntInternal(rng,4294967296)}return out}var safeNumberMaxSafeInteger=Number.MAX_SAFE_INTEGER;var sharedA={sign:1,data:[0,0]};var sharedB={sign:1,data:[0,0]};var sharedC={sign:1,data:[0,0]};var sharedData=[0,0];function uniformLargeIntInternal(rng,from,to,rangeSize){const rangeSizeArrayIntValue=rangeSize<=safeNumberMaxSafeInteger?fromNumberToArrayInt64(sharedC,rangeSize):substractArrayInt64(sharedC,fromNumberToArrayInt64(sharedA,to),fromNumberToArrayInt64(sharedB,from));if(rangeSizeArrayIntValue.data[1]===4294967295){rangeSizeArrayIntValue.data[0]+=1;rangeSizeArrayIntValue.data[1]=0}else rangeSizeArrayIntValue.data[1]+=1;uniformArrayIntInternal(rng,sharedData,rangeSizeArrayIntValue.data);return sharedData[0]*4294967296+sharedData[1]+from}function uniformInt(rng,from,to){const rangeSize=to-from;if(rangeSize<=4294967295)return uniformIntInternal(rng,rangeSize+1)+from;return uniformLargeIntInternal(rng,from,to,rangeSize)}var SharedFootPrint=Symbol.for("fast-check/PreconditionFailure");var PreconditionFailure=class extends Error{constructor(interruptExecution=false){super();this.interruptExecution=interruptExecution;this.footprint=SharedFootPrint}static isFailure(err){return err!==null&&err!==undefined&&err.footprint===SharedFootPrint}};function pre(expectTruthy){if(!expectTruthy)throw new PreconditionFailure}var Nil=class{[Symbol.iterator](){return this}next(value3){return{value:value3,done:true}}};var nil=new Nil;function nilHelper(){return nil}function*mapHelper(g,f){for(const v of g)yield f(v)}function*flatMapHelper(g,f){for(const v of g)yield*f(v)}function*filterHelper(g,f){for(const v of g)if(f(v))yield v}function*takeNHelper(g,n){for(let i=0;i<n;++i){const cur=g.next();if(cur.done)break;yield cur.value}}function*takeWhileHelper(g,f){let cur=g.next();while(!cur.done&&f(cur.value)){yield cur.value;cur=g.next()}}function*joinHelper(g,others){for(let cur=g.next();!cur.done;cur=g.next())yield cur.value;for(const s of others)for(let cur=s.next();!cur.done;cur=s.next())yield cur.value}var safeSymbolIterator$1=Symbol.iterator;var Stream=class Stream2{static nil(){return new Stream2(nilHelper())}static of(...elements){return new Stream2(elements[safeSymbolIterator$1]())}constructor(g){this.g=g}next(){return this.g.next()}[Symbol.iterator](){return this.g}map(f){return new Stream2(mapHelper(this.g,f))}flatMap(f){return new Stream2(flatMapHelper(this.g,f))}dropWhile(f){let foundEligible=false;function*helper(v){if(foundEligible||!f(v)){foundEligible=true;yield v}}return this.flatMap(helper)}drop(n){if(n<=0)return this;let idx=0;function helper(){return idx++<n}return this.dropWhile(helper)}takeWhile(f){return new Stream2(takeWhileHelper(this.g,f))}take(n){return new Stream2(takeNHelper(this.g,n))}filter(f){return new Stream2(filterHelper(this.g,f))}every(f){for(const v of this.g)if(!f(v))return false;return true}has(f){for(const v of this.g)if(f(v))return[true,v];return[false,null]}join(...others){return new Stream2(joinHelper(this.g,others))}getNthOrLast(nth){let remaining=nth;let last=null;for(const v of this.g){if(remaining--===0)return v;last=v}return last}};function stream(g){return new Stream(g)}var cloneMethod=Symbol.for("fast-check/cloneMethod");function hasCloneMethod(instance){return instance!==null&&(typeof instance==="object"||typeof instance==="function")&&cloneMethod in instance&&typeof instance[cloneMethod]==="function"}function cloneIfNeeded(instance){return hasCloneMethod(instance)?instance[cloneMethod]():instance}var safeObjectDefineProperty$4=Object.defineProperty;var Value=class{constructor(value_,context3,customGetValue){this.value_=value_;this.context=context3;this.hasToBeCloned=customGetValue!==undefined||hasCloneMethod(value_);this.readOnce=false;this.value=value_;if(this.hasToBeCloned)safeObjectDefineProperty$4(this,"value",{get:customGetValue!==undefined?customGetValue:this.getValue,enumerable:false,configurable:false})}getValue(){if(this.hasToBeCloned){if(!this.readOnce){this.readOnce=true;return this.value_}return this.value_[cloneMethod]()}return this.value_}};var Arbitrary=class{filter(refinement){return new FilterArbitrary(this,refinement)}map(mapper,unmapper){return new MapArbitrary(this,mapper,unmapper)}chain(chainer){return new ChainArbitrary(this,chainer)}};var ChainArbitrary=class extends Arbitrary{constructor(arb,chainer){super();this.arb=arb;this.chainer=chainer}generate(mrng,biasFactor){const clonedMrng=mrng.clone();const src=this.arb.generate(mrng,biasFactor);return this.valueChainer(src,mrng,clonedMrng,biasFactor)}canShrinkWithoutContext(_value){return false}shrink(value3,context3){if(this.isSafeContext(context3))return(!context3.stoppedForOriginal?this.arb.shrink(context3.originalValue,context3.originalContext).map((v)=>this.valueChainer(v,context3.clonedMrng.clone(),context3.clonedMrng,context3.originalBias)):Stream.nil()).join(context3.chainedArbitrary.shrink(value3,context3.chainedContext).map((dst)=>{const newContext={...context3,chainedContext:dst.context,stoppedForOriginal:true};return new Value(dst.value_,newContext)}));return Stream.nil()}valueChainer(v,generateMrng,clonedMrng,biasFactor){const chainedArbitrary=this.chainer(v.value_);const dst=chainedArbitrary.generate(generateMrng,biasFactor);const context3={originalBias:biasFactor,originalValue:v.value_,originalContext:v.context,stoppedForOriginal:false,chainedArbitrary,chainedContext:dst.context,clonedMrng};return new Value(dst.value_,context3)}isSafeContext(context3){return context3!==null&&context3!==undefined&&typeof context3==="object"&&"originalBias"in context3&&"originalValue"in context3&&"originalContext"in context3&&"stoppedForOriginal"in context3&&"chainedArbitrary"in context3&&"chainedContext"in context3&&"clonedMrng"in context3}};function mapperWithCloneIfNeeded(v,mapper){const sourceValue=v.value;const mappedValue=mapper(sourceValue);if(v.hasToBeCloned&&(typeof mappedValue==="object"&&mappedValue!==null||typeof mappedValue==="function")&&Object.isExtensible(mappedValue)&&!hasCloneMethod(mappedValue))Object.defineProperty(mappedValue,cloneMethod,{get:()=>()=>mapperWithCloneIfNeeded(v,mapper)[0]});return[mappedValue,sourceValue]}function valueMapper(v,mapper){const[mappedValue,sourceValue]=mapperWithCloneIfNeeded(v,mapper);return new Value(mappedValue,{originalValue:sourceValue,originalContext:v.context})}var MapArbitrary=class extends Arbitrary{constructor(arb,mapper,unmapper){super();this.arb=arb;this.mapper=mapper;this.unmapper=unmapper;this.bindValueMapper=(v)=>valueMapper(v,mapper)}generate(mrng,biasFactor){const g=this.arb.generate(mrng,biasFactor);if(!g.hasToBeCloned){const sourceValue=g.value;return new Value(this.mapper(sourceValue),{originalValue:sourceValue,originalContext:g.context})}return valueMapper(g,this.mapper)}canShrinkWithoutContext(value3){if(this.unmapper!==undefined)try{const unmapped=this.unmapper(value3);return this.arb.canShrinkWithoutContext(unmapped)}catch{return false}return false}shrink(value3,context3){if(this.isSafeContext(context3))return this.arb.shrink(context3.originalValue,context3.originalContext).map(this.bindValueMapper);if(this.unmapper!==undefined){const unmapped=this.unmapper(value3);return this.arb.shrink(unmapped,undefined).map(this.bindValueMapper)}return Stream.nil()}isSafeContext(context3){return context3!==null&&context3!==undefined&&typeof context3==="object"&&"originalValue"in context3&&"originalContext"in context3}};var FilterArbitrary=class extends Arbitrary{constructor(arb,refinement){super();this.arb=arb;this.refinement=refinement;this.bindRefinementOnValue=(v)=>this.refinementOnValue(v)}generate(mrng,biasFactor){while(true){const g=this.arb.generate(mrng,biasFactor);if(this.refinementOnValue(g))return g}}canShrinkWithoutContext(value3){return this.arb.canShrinkWithoutContext(value3)&&this.refinement(value3)}shrink(value3,context3){return this.arb.shrink(value3,context3).filter(this.bindRefinementOnValue)}refinementOnValue(v){return this.refinement(v.value)}};function isArbitrary(instance){return typeof instance==="object"&&instance!==null&&"generate"in instance&&"shrink"in instance&&"canShrinkWithoutContext"in instance}function assertIsArbitrary(instance){if(!isArbitrary(instance))throw new Error("Unexpected value received: not an instance of Arbitrary")}var untouchedApply=Function.prototype.apply;var ApplySymbol=Symbol("apply");function safeExtractApply(f){try{return f.apply}catch{return}}function safeApplyHacky(f,instance,args2){const ff=f;ff[ApplySymbol]=untouchedApply;const out=ff[ApplySymbol](instance,args2);delete ff[ApplySymbol];return out}function safeApply(f,instance,args2){if(safeExtractApply(f)===untouchedApply)return f.apply(instance,args2);return safeApplyHacky(f,instance,args2)}var SArray=Array;var SBigInt2=BigInt;var SBigInt64Array=BigInt64Array;var SBigUint64Array=BigUint64Array;var SBoolean=Boolean;var SDate=Date;var SError=Error;var SFloat32Array=Float32Array;var SFloat64Array=Float64Array;var SInt8Array=Int8Array;var SInt16Array=Int16Array;var SInt32Array=Int32Array;var SNumber=Number;var SString=String;var SSet=Set;var SUint8Array=Uint8Array;var SUint8ClampedArray=Uint8ClampedArray;var SUint16Array=Uint16Array;var SUint32Array=Uint32Array;var SencodeURIComponent=encodeURIComponent;var SMap$1=Map;var SSymbol=Symbol;var untouchedForEach=Array.prototype.forEach;var untouchedIndexOf=Array.prototype.indexOf;var untouchedJoin=Array.prototype.join;var untouchedMap=Array.prototype.map;var untouchedFlat=Array.prototype.flat;var untouchedFilter=Array.prototype.filter;var untouchedPush=Array.prototype.push;var untouchedPop=Array.prototype.pop;var untouchedSplice=Array.prototype.splice;var untouchedSlice=Array.prototype.slice;var untouchedSort=Array.prototype.sort;var untouchedEvery=Array.prototype.every;function extractForEach(instance){try{return instance.forEach}catch{return}}function extractIndexOf(instance){try{return instance.indexOf}catch{return}}function extractJoin(instance){try{return instance.join}catch{return}}function extractMap(instance){try{return instance.map}catch{return}}function extractFlat(instance){try{return instance.flat}catch{return}}function extractFilter(instance){try{return instance.filter}catch{return}}function extractPush(instance){try{return instance.push}catch{return}}function extractPop(instance){try{return instance.pop}catch{return}}function extractSplice(instance){try{return instance.splice}catch{return}}function extractSlice(instance){try{return instance.slice}catch{return}}function extractSort(instance){try{return instance.sort}catch{return}}function extractEvery(instance){try{return instance.every}catch{return}}function safeForEach(instance,fn3){if(extractForEach(instance)===untouchedForEach)return instance.forEach(fn3);return safeApply(untouchedForEach,instance,[fn3])}function safeIndexOf(instance,...args2){if(extractIndexOf(instance)===untouchedIndexOf)return instance.indexOf(...args2);return safeApply(untouchedIndexOf,instance,args2)}function safeJoin(instance,...args2){if(extractJoin(instance)===untouchedJoin)return instance.join(...args2);return safeApply(untouchedJoin,instance,args2)}function safeMap(instance,fn3){if(extractMap(instance)===untouchedMap)return instance.map(fn3);return safeApply(untouchedMap,instance,[fn3])}function safeFlat(instance,depth){if(extractFlat(instance)===untouchedFlat){[].flat();return instance.flat(depth)}return safeApply(untouchedFlat,instance,[depth])}function safeFilter(instance,predicate){if(extractFilter(instance)===untouchedFilter)return instance.filter(predicate);return safeApply(untouchedFilter,instance,[predicate])}function safePush(instance,...args2){if(extractPush(instance)===untouchedPush)return instance.push(...args2);return safeApply(untouchedPush,instance,args2)}function safePop$1(instance){if(extractPop(instance)===untouchedPop)return instance.pop();return safeApply(untouchedPop,instance,[])}function safeSplice(instance,...args2){if(extractSplice(instance)===untouchedSplice)return instance.splice(...args2);return safeApply(untouchedSplice,instance,args2)}function safeSlice(instance,...args2){if(extractSlice(instance)===untouchedSlice)return instance.slice(...args2);return safeApply(untouchedSlice,instance,args2)}function safeSort(instance,...args2){if(extractSort(instance)===untouchedSort)return instance.sort(...args2);return safeApply(untouchedSort,instance,args2)}function safeEvery(instance,...args2){if(extractEvery(instance)===untouchedEvery)return instance.every(...args2);return safeApply(untouchedEvery,instance,args2)}var untouchedGetTime=Date.prototype.getTime;var untouchedToISOString=Date.prototype.toISOString;function extractGetTime(instance){try{return instance.getTime}catch{return}}function extractToISOString(instance){try{return instance.toISOString}catch{return}}function safeGetTime(instance){if(extractGetTime(instance)===untouchedGetTime)return instance.getTime();return safeApply(untouchedGetTime,instance,[])}function safeToISOString(instance){if(extractToISOString(instance)===untouchedToISOString)return instance.toISOString();return safeApply(untouchedToISOString,instance,[])}var untouchedAdd=Set.prototype.add;var untouchedHas=Set.prototype.has;function extractAdd(instance){try{return instance.add}catch{return}}function extractHas(instance){try{return instance.has}catch(err){return}}function safeAdd(instance,value3){if(extractAdd(instance)===untouchedAdd)return instance.add(value3);return safeApply(untouchedAdd,instance,[value3])}function safeHas(instance,value3){if(extractHas(instance)===untouchedHas)return instance.has(value3);return safeApply(untouchedHas,instance,[value3])}var untouchedSet=WeakMap.prototype.set;var untouchedGet=WeakMap.prototype.get;function extractSet(instance){try{return instance.set}catch(err){return}}function extractGet(instance){try{return instance.get}catch(err){return}}function safeSet(instance,key,value3){if(extractSet(instance)===untouchedSet)return instance.set(key,value3);return safeApply(untouchedSet,instance,[key,value3])}function safeGet(instance,key){if(extractGet(instance)===untouchedGet)return instance.get(key);return safeApply(untouchedGet,instance,[key])}var untouchedMapSet=Map.prototype.set;var untouchedMapGet=Map.prototype.get;var untouchedMapHas=Map.prototype.has;function extractMapSet(instance){try{return instance.set}catch(err){return}}function extractMapGet(instance){try{return instance.get}catch(err){return}}function extractMapHas(instance){try{return instance.has}catch(err){return}}function safeMapSet(instance,key,value3){if(extractMapSet(instance)===untouchedMapSet)return instance.set(key,value3);return safeApply(untouchedMapSet,instance,[key,value3])}function safeMapGet(instance,key){if(extractMapGet(instance)===untouchedMapGet)return instance.get(key);return safeApply(untouchedMapGet,instance,[key])}function safeMapHas(instance,key){if(extractMapHas(instance)===untouchedMapHas)return instance.has(key);return safeApply(untouchedMapHas,instance,[key])}var untouchedSplit=String.prototype.split;var untouchedStartsWith=String.prototype.startsWith;var untouchedEndsWith=String.prototype.endsWith;var untouchedSubstring=String.prototype.substring;var untouchedToLowerCase=String.prototype.toLowerCase;var untouchedToUpperCase=String.prototype.toUpperCase;var untouchedPadStart=String.prototype.padStart;var untouchedCharCodeAt=String.prototype.charCodeAt;var untouchedNormalize=String.prototype.normalize;var untouchedReplace=String.prototype.replace;function extractSplit(instance){try{return instance.split}catch{return}}function extractStartsWith(instance){try{return instance.startsWith}catch{return}}function extractEndsWith(instance){try{return instance.endsWith}catch{return}}function extractSubstring(instance){try{return instance.substring}catch{return}}function extractToLowerCase(instance){try{return instance.toLowerCase}catch{return}}function extractToUpperCase(instance){try{return instance.toUpperCase}catch{return}}function extractPadStart(instance){try{return instance.padStart}catch{return}}function extractCharCodeAt(instance){try{return instance.charCodeAt}catch{return}}function extractNormalize(instance){try{return instance.normalize}catch(err){return}}function extractReplace(instance){try{return instance.replace}catch{return}}function safeSplit(instance,...args2){if(extractSplit(instance)===untouchedSplit)return instance.split(...args2);return safeApply(untouchedSplit,instance,args2)}function safeStartsWith(instance,...args2){if(extractStartsWith(instance)===untouchedStartsWith)return instance.startsWith(...args2);return safeApply(untouchedStartsWith,instance,args2)}function safeEndsWith(instance,...args2){if(extractEndsWith(instance)===untouchedEndsWith)return instance.endsWith(...args2);return safeApply(untouchedEndsWith,instance,args2)}function safeSubstring(instance,...args2){if(extractSubstring(instance)===untouchedSubstring)return instance.substring(...args2);return safeApply(untouchedSubstring,instance,args2)}function safeToLowerCase(instance){if(extractToLowerCase(instance)===untouchedToLowerCase)return instance.toLowerCase();return safeApply(untouchedToLowerCase,instance,[])}function safeToUpperCase(instance){if(extractToUpperCase(instance)===untouchedToUpperCase)return instance.toUpperCase();return safeApply(untouchedToUpperCase,instance,[])}function safePadStart(instance,...args2){if(extractPadStart(instance)===untouchedPadStart)return instance.padStart(...args2);return safeApply(untouchedPadStart,instance,args2)}function safeCharCodeAt(instance,index2){if(extractCharCodeAt(instance)===untouchedCharCodeAt)return instance.charCodeAt(index2);return safeApply(untouchedCharCodeAt,instance,[index2])}function safeNormalize(instance,form){if(extractNormalize(instance)===untouchedNormalize)return instance.normalize(form);return safeApply(untouchedNormalize,instance,[form])}function safeReplace(instance,pattern,replacement){if(extractReplace(instance)===untouchedReplace)return instance.replace(pattern,replacement);return safeApply(untouchedReplace,instance,[pattern,replacement])}var untouchedNumberToString=Number.prototype.toString;function extractNumberToString(instance){try{return instance.toString}catch{return}}function safeNumberToString(instance,...args2){if(extractNumberToString(instance)===untouchedNumberToString)return instance.toString(...args2);return safeApply(untouchedNumberToString,instance,args2)}var untouchedHasOwnProperty=Object.prototype.hasOwnProperty;var untouchedToString=Object.prototype.toString;function safeHasOwnProperty(instance,v){return safeApply(untouchedHasOwnProperty,instance,[v])}function safeToString2(instance){return safeApply(untouchedToString,instance,[])}var untouchedErrorToString=Error.prototype.toString;function safeErrorToString(instance){return safeApply(untouchedErrorToString,instance,[])}var LazyIterableIterator=class{constructor(producer){this.producer=producer}[Symbol.iterator](){if(this.it===undefined)this.it=this.producer();return this.it}next(){if(this.it===undefined)this.it=this.producer();return this.it.next()}};function makeLazy2(producer){return new LazyIterableIterator(producer)}var safeArrayIsArray$4=Array.isArray;var safeObjectDefineProperty$3=Object.defineProperty;function tupleMakeItCloneable(vs,ctxs,values3){return safeObjectDefineProperty$3(vs,cloneMethod,{value:()=>{const cloned=[];for(let idx=0;idx!==values3.length;++idx){let current=values3[idx];if(current===undefined)current=new Value(vs[idx],ctxs[idx]);safePush(cloned,current.value)}tupleMakeItCloneable(cloned,ctxs,values3);return cloned}})}function tupleShrink(arbs,value3,context3){const shrinks=[];const safeContext=safeArrayIsArray$4(context3)?context3:[];for(let idx=0;idx!==arbs.length;++idx)safePush(shrinks,makeLazy2(()=>arbs[idx].shrink(value3[idx],safeContext[idx]).map((v)=>{let cloneable=false;const vs=[];const ctxs=[];const mapped=[];for(let nestedIdx=0;nestedIdx!==arbs.length;++nestedIdx){const nestedV=nestedIdx===idx?v:new Value(cloneIfNeeded(value3[nestedIdx]),safeContext[nestedIdx]);if(nestedV.hasToBeCloned){cloneable=true;mapped[nestedIdx]=nestedV}safePush(vs,nestedV.value);safePush(ctxs,nestedV.context)}if(cloneable)tupleMakeItCloneable(vs,ctxs,mapped);return new Value(vs,ctxs)})));return Stream.nil().join(...shrinks)}var TupleArbitrary=class extends Arbitrary{constructor(arbs){super();this.arbs=arbs;for(let idx=0;idx!==arbs.length;++idx){const arb=arbs[idx];if(arb===null||arb===undefined||arb.generate===null||arb.generate===undefined)throw new Error(`Invalid parameter encountered at index ${idx}: expecting an Arbitrary`)}}generate(mrng,biasFactor){let cloneable=false;const vs=[];const ctxs=[];const mapped=[];for(let idx=0;idx!==this.arbs.length;++idx){const v=this.arbs[idx].generate(mrng,biasFactor);if(v.hasToBeCloned){cloneable=true;mapped[idx]=v}safePush(vs,v.value);safePush(ctxs,v.context)}if(cloneable)tupleMakeItCloneable(vs,ctxs,mapped);return new Value(vs,ctxs)}canShrinkWithoutContext(value3){if(!safeArrayIsArray$4(value3)||value3.length!==this.arbs.length)return false;for(let index2=0;index2!==this.arbs.length;++index2)if(!this.arbs[index2].canShrinkWithoutContext(value3[index2]))return false;return true}shrink(value3,context3){return tupleShrink(this.arbs,value3,context3)}};function tuple2(...arbs){return new TupleArbitrary(arbs)}var safeMathLog$3=Math.log;function runIdToFrequency(runId){return 2+~~(safeMathLog$3(runId+1)*0.4342944819032518)}var globalParameters={};function configureGlobal(parameters){globalParameters=parameters}function readConfigureGlobal(){return globalParameters}function resetConfigureGlobal(){globalParameters={}}var UndefinedContextPlaceholder=Symbol("UndefinedContextPlaceholder");function noUndefinedAsContext(value3){if(value3.context!==undefined)return value3;if(value3.hasToBeCloned)return new Value(value3.value_,UndefinedContextPlaceholder,()=>value3.value);return new Value(value3.value_,UndefinedContextPlaceholder)}var dummyHook$1=()=>{};var AsyncProperty=class{constructor(arb,predicate){this.arb=arb;this.predicate=predicate;const{asyncBeforeEach,asyncAfterEach,beforeEach,afterEach}=readConfigureGlobal()||{};if(asyncBeforeEach!==undefined&&beforeEach!==undefined)throw SError(`Global "asyncBeforeEach" and "beforeEach" parameters can't be set at the same time when running async properties`);if(asyncAfterEach!==undefined&&afterEach!==undefined)throw SError(`Global "asyncAfterEach" and "afterEach" parameters can't be set at the same time when running async properties`);this.beforeEachHook=asyncBeforeEach||beforeEach||dummyHook$1;this.afterEachHook=asyncAfterEach||afterEach||dummyHook$1}isAsync(){return true}generate(mrng,runId){return noUndefinedAsContext(this.arb.generate(mrng,runId!==undefined?runIdToFrequency(runId):undefined))}shrink(value3){if(value3.context===undefined&&!this.arb.canShrinkWithoutContext(value3.value_))return Stream.nil();const safeContext=value3.context!==UndefinedContextPlaceholder?value3.context:undefined;return this.arb.shrink(value3.value_,safeContext).map(noUndefinedAsContext)}async runBeforeEach(){await this.beforeEachHook()}async runAfterEach(){await this.afterEachHook()}async run(v){try{const output=await this.predicate(v);return output===undefined||output===true?null:{error:new SError("Property failed by returning false")}}catch(err){if(PreconditionFailure.isFailure(err))return err;return{error:err}}}beforeEach(hookFunction){const previousBeforeEachHook=this.beforeEachHook;this.beforeEachHook=()=>hookFunction(previousBeforeEachHook);return this}afterEach(hookFunction){const previousAfterEachHook=this.afterEachHook;this.afterEachHook=()=>hookFunction(previousAfterEachHook);return this}};var AlwaysShrinkableArbitrary=class extends Arbitrary{constructor(arb){super();this.arb=arb}generate(mrng,biasFactor){return noUndefinedAsContext(this.arb.generate(mrng,biasFactor))}canShrinkWithoutContext(_value){return true}shrink(value3,context3){if(context3===undefined&&!this.arb.canShrinkWithoutContext(value3))return Stream.nil();const safeContext=context3!==UndefinedContextPlaceholder?context3:undefined;return this.arb.shrink(value3,safeContext).map(noUndefinedAsContext)}};function asyncProperty(...args2){if(args2.length<2)throw new Error("asyncProperty expects at least two parameters");const arbs=safeSlice(args2,0,args2.length-1);const p=args2[args2.length-1];safeForEach(arbs,assertIsArbitrary);return new AsyncProperty(tuple2(...safeMap(arbs,(arb)=>new AlwaysShrinkableArbitrary(arb))),(t)=>p(...t))}var dummyHook=()=>{};var Property=class{constructor(arb,predicate){this.arb=arb;this.predicate=predicate;const{beforeEach=dummyHook,afterEach=dummyHook,asyncBeforeEach,asyncAfterEach}=readConfigureGlobal()||{};if(asyncBeforeEach!==undefined)throw SError(`"asyncBeforeEach" can't be set when running synchronous properties`);if(asyncAfterEach!==undefined)throw SError(`"asyncAfterEach" can't be set when running synchronous properties`);this.beforeEachHook=beforeEach;this.afterEachHook=afterEach}isAsync(){return false}generate(mrng,runId){return noUndefinedAsContext(this.arb.generate(mrng,runId!==undefined?runIdToFrequency(runId):undefined))}shrink(value3){if(value3.context===undefined&&!this.arb.canShrinkWithoutContext(value3.value_))return Stream.nil();const safeContext=value3.context!==UndefinedContextPlaceholder?value3.context:undefined;return this.arb.shrink(value3.value_,safeContext).map(noUndefinedAsContext)}runBeforeEach(){this.beforeEachHook()}runAfterEach(){this.afterEachHook()}run(v){try{const output=this.predicate(v);return output===undefined||output===true?null:{error:new SError("Property failed by returning false")}}catch(err){if(PreconditionFailure.isFailure(err))return err;return{error:err}}}beforeEach(hookFunction){const previousBeforeEachHook=this.beforeEachHook;this.beforeEachHook=()=>hookFunction(previousBeforeEachHook);return this}afterEach(hookFunction){const previousAfterEachHook=this.afterEachHook;this.afterEachHook=()=>hookFunction(previousAfterEachHook);return this}};function property(...args2){if(args2.length<2)throw new Error("property expects at least two parameters");const arbs=safeSlice(args2,0,args2.length-1);const p=args2[args2.length-1];safeForEach(arbs,assertIsArbitrary);return new Property(tuple2(...safeMap(arbs,(arb)=>new AlwaysShrinkableArbitrary(arb))),(t)=>p(...t))}var VerbosityLevel=function(VerbosityLevel2){VerbosityLevel2[VerbosityLevel2["None"]=0]="None";VerbosityLevel2[VerbosityLevel2["Verbose"]=1]="Verbose";VerbosityLevel2[VerbosityLevel2["VeryVerbose"]=2]="VeryVerbose";return VerbosityLevel2}({});function adaptRandomGeneratorTo8x(rng){if("unsafeNext"in rng){if(rng.unsafeJump===undefined)return{clone:()=>adaptRandomGeneratorTo8x(rng),next:()=>rng.unsafeNext(),getState:()=>rng.getState()};return{clone:()=>adaptRandomGeneratorTo8x(rng),next:()=>rng.unsafeNext(),jump:()=>rng.unsafeJump(),getState:()=>rng.getState()}}return rng}function adaptRandomGeneratorToInternal(rng){if("jump"in rng&&typeof rng.jump==="function")return rng;return{clone:()=>adaptRandomGeneratorToInternal(rng),next:()=>rng.next(),jump:()=>skipN(rng,42),getState:()=>rng.getState()}}function adaptRandomGenerator(rng){return adaptRandomGeneratorToInternal(adaptRandomGeneratorTo8x(rng))}var safeDateNow$1=Date.now;var safeMathMin$6=Math.min;var safeMathRandom=Math.random;var QualifiedParameters=class{constructor(op){const p=op||{};this.seed=readSeed(p);this.randomType=readRandomType(p);this.numRuns=readNumRuns(p);this.verbose=readVerbose(p);this.maxSkipsPerRun=p.maxSkipsPerRun!==undefined?p.maxSkipsPerRun:100;this.timeout=safeTimeout(p.timeout);this.skipAllAfterTimeLimit=safeTimeout(p.skipAllAfterTimeLimit);this.interruptAfterTimeLimit=safeTimeout(p.interruptAfterTimeLimit);this.markInterruptAsFailure=p.markInterruptAsFailure===true;this.skipEqualValues=p.skipEqualValues===true;this.ignoreEqualValues=p.ignoreEqualValues===true;this.logger=p.logger!==undefined?p.logger:(v)=>{console.log(v)};this.path=p.path!==undefined?p.path:"";this.unbiased=p.unbiased===true;this.examples=p.examples!==undefined?p.examples:[];this.endOnFailure=p.endOnFailure===true;this.reporter=p.reporter;this.asyncReporter=p.asyncReporter;this.includeErrorInReport=p.includeErrorInReport===true}toParameters(){return{seed:this.seed,randomType:this.randomType,numRuns:this.numRuns,maxSkipsPerRun:this.maxSkipsPerRun,timeout:this.timeout,skipAllAfterTimeLimit:this.skipAllAfterTimeLimit,interruptAfterTimeLimit:this.interruptAfterTimeLimit,markInterruptAsFailure:this.markInterruptAsFailure,skipEqualValues:this.skipEqualValues,ignoreEqualValues:this.ignoreEqualValues,path:this.path,logger:this.logger,unbiased:this.unbiased,verbose:this.verbose,examples:this.examples,endOnFailure:this.endOnFailure,reporter:this.reporter,asyncReporter:this.asyncReporter,includeErrorInReport:this.includeErrorInReport}}};function createQualifiedRandomGenerator(random2){return(seed)=>{return adaptRandomGenerator(random2(seed))}}function readSeed(p){if(p.seed===undefined)return safeDateNow$1()^safeMathRandom()*4294967296;const seed32=p.seed|0;if(p.seed===seed32)return seed32;return seed32^(p.seed-seed32)*4294967296}function readRandomType(p){if(p.randomType===undefined)return xorshift128plus;if(typeof p.randomType==="string")switch(p.randomType){case"mersenne":return createQualifiedRandomGenerator(mersenne);case"congruential":case"congruential32":return createQualifiedRandomGenerator(congruential32);case"xorshift128plus":return xorshift128plus;case"xoroshiro128plus":return xoroshiro128plus;default:throw new Error(`Invalid random specified: '${p.randomType}'`)}const mrng=p.randomType(0);if("min"in mrng&&mrng.min!==-2147483648)throw new Error(`Invalid random number generator: min must equal -0x80000000, got ${String(mrng.min)}`);if("max"in mrng&&mrng.max!==2147483647)throw new Error(`Invalid random number generator: max must equal 0x7fffffff, got ${String(mrng.max)}`);if(mrng===adaptRandomGenerator(mrng))return p.randomType;return createQualifiedRandomGenerator(p.randomType)}function readNumRuns(p){const defaultValue=100;if(p.numRuns!==undefined)return p.numRuns;if(p.num_runs!==undefined)return p.num_runs;return defaultValue}function readVerbose(p){if(p.verbose===undefined)return 0;if(typeof p.verbose==="boolean")return p.verbose===true?1:0;if(p.verbose<=0)return 0;if(p.verbose>=2)return 2;return p.verbose|0}function safeTimeout(value3){if(value3===undefined)return;return safeMathMin$6(value3,2147483647)}function read(op){return new QualifiedParameters(op)}function interruptAfter(timeMs,setTimeoutSafe,clearTimeoutSafe){let timeoutHandle=null;return{clear:()=>clearTimeoutSafe(timeoutHandle),promise:new Promise((resolve4)=>{timeoutHandle=setTimeoutSafe(()=>{resolve4(new PreconditionFailure(true))},timeMs)})}}var SkipAfterProperty=class{constructor(property2,getTime,timeLimit,interruptExecution,setTimeoutSafe,clearTimeoutSafe){this.property=property2;this.getTime=getTime;this.interruptExecution=interruptExecution;this.setTimeoutSafe=setTimeoutSafe;this.clearTimeoutSafe=clearTimeoutSafe;this.skipAfterTime=this.getTime()+timeLimit}isAsync(){return this.property.isAsync()}generate(mrng,runId){return this.property.generate(mrng,runId)}shrink(value3){return this.property.shrink(value3)}run(v){const remainingTime=this.skipAfterTime-this.getTime();if(remainingTime<=0){const preconditionFailure=new PreconditionFailure(this.interruptExecution);if(this.isAsync())return Promise.resolve(preconditionFailure);else return preconditionFailure}if(this.interruptExecution&&this.isAsync()){const t=interruptAfter(remainingTime,this.setTimeoutSafe,this.clearTimeoutSafe);const propRun=Promise.race([this.property.run(v),t.promise]);propRun.then(t.clear,t.clear);return propRun}return this.property.run(v)}runBeforeEach(){return this.property.runBeforeEach()}runAfterEach(){return this.property.runAfterEach()}};var timeoutAfter=(timeMs,setTimeoutSafe,clearTimeoutSafe)=>{let timeoutHandle=null;return{clear:()=>clearTimeoutSafe(timeoutHandle),promise:new Promise((resolve4)=>{timeoutHandle=setTimeoutSafe(()=>{resolve4({error:new SError(`Property timeout: exceeded limit of ${timeMs} milliseconds`)})},timeMs)})}};var TimeoutProperty=class{constructor(property2,timeMs,setTimeoutSafe,clearTimeoutSafe){this.property=property2;this.timeMs=timeMs;this.setTimeoutSafe=setTimeoutSafe;this.clearTimeoutSafe=clearTimeoutSafe}isAsync(){return true}generate(mrng,runId){return this.property.generate(mrng,runId)}shrink(value3){return this.property.shrink(value3)}async run(v){const t=timeoutAfter(this.timeMs,this.setTimeoutSafe,this.clearTimeoutSafe);const propRun=Promise.race([this.property.run(v),t.promise]);propRun.then(t.clear,t.clear);return propRun}runBeforeEach(){return Promise.resolve(this.property.runBeforeEach())}runAfterEach(){return Promise.resolve(this.property.runAfterEach())}};var UnbiasedProperty=class{constructor(property2){this.property=property2}isAsync(){return this.property.isAsync()}generate(mrng,_runId){return this.property.generate(mrng,undefined)}shrink(value3){return this.property.shrink(value3)}run(v){return this.property.run(v)}runBeforeEach(){return this.property.runBeforeEach()}runAfterEach(){return this.property.runAfterEach()}};var safeArrayFrom=Array.from;var safeBufferIsBuffer=typeof Buffer!=="undefined"?Buffer.isBuffer:undefined;var safeJsonStringify$1=JSON.stringify;var safeNumberIsNaN$5=Number.isNaN;var safeObjectKeys$5=Object.keys;var safeObjectGetOwnPropertySymbols$2=Object.getOwnPropertySymbols;var safeObjectGetOwnPropertyDescriptor$3=Object.getOwnPropertyDescriptor;var safeObjectGetPrototypeOf$2=Object.getPrototypeOf;var safeNegativeInfinity$7=Number.NEGATIVE_INFINITY;var safePositiveInfinity$8=Number.POSITIVE_INFINITY;var toStringMethod=Symbol.for("fast-check/toStringMethod");function hasToStringMethod(instance){return instance!==null&&(typeof instance==="object"||typeof instance==="function")&&toStringMethod in instance&&typeof instance[toStringMethod]==="function"}var asyncToStringMethod=Symbol.for("fast-check/asyncToStringMethod");function hasAsyncToStringMethod(instance){return instance!==null&&(typeof instance==="object"||typeof instance==="function")&&asyncToStringMethod in instance&&typeof instance[asyncToStringMethod]==="function"}var findSymbolNameRegex=/^Symbol\((.*)\)$/;function getSymbolDescription(s){if(s.description!==undefined)return s.description;const m=findSymbolNameRegex.exec(SString(s));return m&&m[1].length?m[1]:null}function stringifyNumber(numValue){switch(numValue){case 0:return 1/numValue===safeNegativeInfinity$7?"-0":"0";case safeNegativeInfinity$7:return"Number.NEGATIVE_INFINITY";case safePositiveInfinity$8:return"Number.POSITIVE_INFINITY";default:return numValue===numValue?SString(numValue):"Number.NaN"}}function isSparseArray(arr){let previousNumberedIndex=-1;for(const index2 in arr){const numberedIndex=Number(index2);if(numberedIndex!==previousNumberedIndex+1)return true;previousNumberedIndex=numberedIndex}return previousNumberedIndex+1!==arr.length}function stringifyInternal(value3,previousValues,getAsyncContent){const currentValues=[...previousValues,value3];if(typeof value3==="object"){if(safeIndexOf(previousValues,value3)!==-1)return"[cyclic]"}if(hasAsyncToStringMethod(value3)){const content=getAsyncContent(value3);if(content.state==="fulfilled")return content.value}if(hasToStringMethod(value3))try{return value3[toStringMethod]()}catch{}switch(safeToString2(value3)){case"[object Array]":{const arr=value3;if(arr.length>=50&&isSparseArray(arr)){const assignments=[];for(const index2 in arr)if(!safeNumberIsNaN$5(Number(index2)))safePush(assignments,`${index2}:${stringifyInternal(arr[index2],currentValues,getAsyncContent)}`);return assignments.length!==0?`Object.assign(Array(${arr.length}),{${safeJoin(assignments,",")}})`:`Array(${arr.length})`}const stringifiedArray=safeJoin(safeMap(arr,(v)=>stringifyInternal(v,currentValues,getAsyncContent)),",");return arr.length===0||arr.length-1 in arr?`[${stringifiedArray}]`:`[${stringifiedArray},]`}case"[object BigInt]":return`${value3}n`;case"[object Boolean]":{const unboxedToString=value3==true?"true":"false";return typeof value3==="boolean"?unboxedToString:`new Boolean(${unboxedToString})`}case"[object Date]":{const d=value3;return safeNumberIsNaN$5(safeGetTime(d))?`new Date(NaN)`:`new Date(${safeJsonStringify$1(safeToISOString(d))})`}case"[object Map]":return`new Map(${stringifyInternal(Array.from(value3),currentValues,getAsyncContent)})`;case"[object Null]":return`null`;case"[object Number]":return typeof value3==="number"?stringifyNumber(value3):`new Number(${stringifyNumber(Number(value3))})`;case"[object Object]":{try{const toStringAccessor=value3.toString;if(typeof toStringAccessor==="function"&&toStringAccessor!==Object.prototype.toString)return value3.toString()}catch{return"[object Object]"}const mapper=(k)=>`${k==="__proto__"?'["__proto__"]':typeof k==="symbol"?`[${stringifyInternal(k,currentValues,getAsyncContent)}]`:safeJsonStringify$1(k)}:${stringifyInternal(value3[k],currentValues,getAsyncContent)}`;return"{"+safeJoin([...safeObjectGetPrototypeOf$2(value3)===null?["__proto__:null"]:[],...safeMap(safeObjectKeys$5(value3),mapper),...safeMap(safeFilter(safeObjectGetOwnPropertySymbols$2(value3),(s)=>{const descriptor=safeObjectGetOwnPropertyDescriptor$3(value3,s);return descriptor&&descriptor.enumerable}),mapper)],",")+"}"}case"[object Set]":return`new Set(${stringifyInternal(Array.from(value3),currentValues,getAsyncContent)})`;case"[object String]":return typeof value3==="string"?safeJsonStringify$1(value3):`new String(${safeJsonStringify$1(value3)})`;case"[object Symbol]":{const s=value3;if(SSymbol.keyFor(s)!==undefined)return`Symbol.for(${safeJsonStringify$1(SSymbol.keyFor(s))})`;const desc=getSymbolDescription(s);if(desc===null)return"Symbol()";return s===(desc.startsWith("Symbol.")&&SSymbol[desc.substring(7)])?desc:`Symbol(${safeJsonStringify$1(desc)})`}case"[object Promise]":{const promiseContent=getAsyncContent(value3);switch(promiseContent.state){case"fulfilled":return`Promise.resolve(${stringifyInternal(promiseContent.value,currentValues,getAsyncContent)})`;case"rejected":return`Promise.reject(${stringifyInternal(promiseContent.value,currentValues,getAsyncContent)})`;case"pending":return`new Promise(() => {/*pending*/})`;default:return`new Promise(() => {/*unknown*/})`}}case"[object Error]":if(value3 instanceof Error)return`new Error(${stringifyInternal(value3.message,currentValues,getAsyncContent)})`;break;case"[object Undefined]":return`undefined`;case"[object Int8Array]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Int16Array]":case"[object Uint16Array]":case"[object Int32Array]":case"[object Uint32Array]":case"[object Float32Array]":case"[object Float64Array]":case"[object BigInt64Array]":case"[object BigUint64Array]":{if(typeof safeBufferIsBuffer==="function"&&safeBufferIsBuffer(value3))return`Buffer.from(${value3.buffer.detached?"/*detached ArrayBuffer*/":stringifyInternal(safeArrayFrom(value3.values()),currentValues,getAsyncContent)})`;const valuePrototype=safeObjectGetPrototypeOf$2(value3);const className=valuePrototype&&valuePrototype.constructor&&valuePrototype.constructor.name;if(typeof className==="string"){const typedArray=value3;if(typedArray.buffer.detached)return`${className}.from(/*detached ArrayBuffer*/)`;const valuesFromTypedArr=typedArray.values();return`${className}.from(${stringifyInternal(safeArrayFrom(valuesFromTypedArr),currentValues,getAsyncContent)})`}break}}try{return value3.toString()}catch{return safeToString2(value3)}}function stringify(value3){return stringifyInternal(value3,[],()=>({state:"unknown",value:undefined}))}function possiblyAsyncStringify(value3){const stillPendingMarker=SSymbol();const pendingPromisesForCache=[];const cache=new SMap$1;function createDelay0(){let handleId=null;const cancel=()=>{if(handleId!==null)clearTimeout(handleId)};return{delay:new Promise((resolve4)=>{handleId=setTimeout(()=>{handleId=null;resolve4(stillPendingMarker)},0)}),cancel}}const unknownState={state:"unknown",value:undefined};const getAsyncContent=function getAsyncContent2(data){const cacheKey=data;if(cache.has(cacheKey))return cache.get(cacheKey);const delay0=createDelay0();const p=asyncToStringMethod in data?Promise.resolve().then(()=>data[asyncToStringMethod]()):data;p.catch(()=>{});pendingPromisesForCache.push(Promise.race([p,delay0.delay]).then((successValue)=>{if(successValue===stillPendingMarker)cache.set(cacheKey,{state:"pending",value:undefined});else cache.set(cacheKey,{state:"fulfilled",value:successValue});delay0.cancel()},(errorValue)=>{cache.set(cacheKey,{state:"rejected",value:errorValue});delay0.cancel()}));cache.set(cacheKey,unknownState);return unknownState};function loop(){const stringifiedValue=stringifyInternal(value3,[],getAsyncContent);if(pendingPromisesForCache.length===0)return stringifiedValue;return Promise.all(pendingPromisesForCache.splice(0)).then(loop)}return loop()}async function asyncStringify(value3){return Promise.resolve(possiblyAsyncStringify(value3))}function fromSyncCached(cachedValue){return cachedValue===null?new PreconditionFailure:cachedValue}function fromCached(...data){if(data[1])return data[0].then(fromSyncCached);return fromSyncCached(data[0])}function fromCachedUnsafe(cachedValue,isAsync){return fromCached(cachedValue,isAsync)}var IgnoreEqualValuesProperty=class{constructor(property2,skipRuns){this.property=property2;this.skipRuns=skipRuns;this.coveredCases=new Map}isAsync(){return this.property.isAsync()}generate(mrng,runId){return this.property.generate(mrng,runId)}shrink(value3){return this.property.shrink(value3)}run(v){const stringifiedValue=stringify(v);if(this.coveredCases.has(stringifiedValue)){const lastOutput=this.coveredCases.get(stringifiedValue);if(!this.skipRuns)return lastOutput;return fromCachedUnsafe(lastOutput,this.property.isAsync())}const out=this.property.run(v);this.coveredCases.set(stringifiedValue,out);return out}runBeforeEach(){return this.property.runBeforeEach()}runAfterEach(){return this.property.runAfterEach()}};var safeDateNow=Date.now;var safeSetTimeout=setTimeout;var safeClearTimeout=clearTimeout;function decorateProperty(rawProperty,qParams){let prop=rawProperty;if(rawProperty.isAsync()&&qParams.timeout!==undefined)prop=new TimeoutProperty(prop,qParams.timeout,safeSetTimeout,safeClearTimeout);if(qParams.unbiased)prop=new UnbiasedProperty(prop);if(qParams.skipAllAfterTimeLimit!==undefined)prop=new SkipAfterProperty(prop,safeDateNow,qParams.skipAllAfterTimeLimit,false,safeSetTimeout,safeClearTimeout);if(qParams.interruptAfterTimeLimit!==undefined)prop=new SkipAfterProperty(prop,safeDateNow,qParams.interruptAfterTimeLimit,true,safeSetTimeout,safeClearTimeout);if(qParams.skipEqualValues)prop=new IgnoreEqualValuesProperty(prop,true);if(qParams.ignoreEqualValues)prop=new IgnoreEqualValuesProperty(prop,false);return prop}var ExecutionStatus=function(ExecutionStatus2){ExecutionStatus2[ExecutionStatus2["Success"]=0]="Success";ExecutionStatus2[ExecutionStatus2["Skipped"]=-1]="Skipped";ExecutionStatus2[ExecutionStatus2["Failure"]=1]="Failure";return ExecutionStatus2}({});var RunExecution=class RunExecution2{constructor(verbosity,interruptedAsFailure){this.verbosity=verbosity;this.interruptedAsFailure=interruptedAsFailure;this.rootExecutionTrees=[];this.currentLevelExecutionTrees=this.rootExecutionTrees;this.failure=null;this.numSkips=0;this.numSuccesses=0;this.interrupted=false}appendExecutionTree(status,value3){const currentTree={status,value:value3,children:[]};this.currentLevelExecutionTrees.push(currentTree);return currentTree}fail(value3,id2,failure){if(this.verbosity>=1){const currentTree=this.appendExecutionTree(1,value3);this.currentLevelExecutionTrees=currentTree.children}if(this.pathToFailure===undefined)this.pathToFailure=`${id2}`;else this.pathToFailure+=`:${id2}`;this.value=value3;this.failure=failure}skip(value3){if(this.verbosity>=2)this.appendExecutionTree(-1,value3);if(this.pathToFailure===undefined)++this.numSkips}success(value3){if(this.verbosity>=2)this.appendExecutionTree(0,value3);if(this.pathToFailure===undefined)++this.numSuccesses}interrupt(){this.interrupted=true}isSuccess(){return this.pathToFailure===undefined}firstFailure(){return this.pathToFailure!==undefined?+safeSplit(this.pathToFailure,":")[0]:-1}numShrinks(){return this.pathToFailure!==undefined?safeSplit(this.pathToFailure,":").length-1:0}extractFailures(){if(this.isSuccess())return[];const failures=[];let cursor=this.rootExecutionTrees;while(cursor.length>0&&cursor[cursor.length-1].status===1){const failureTree=cursor[cursor.length-1];failures.push(failureTree.value);cursor=failureTree.children}return failures}static mergePaths(offsetPath,path){if(offsetPath.length===0)return path;const offsetItems=offsetPath.split(":");const remainingItems=path.split(":");const middle=+offsetItems[offsetItems.length-1]+ +remainingItems[0];return[...offsetItems.slice(0,offsetItems.length-1),`${middle}`,...remainingItems.slice(1)].join(":")}toRunDetails(seed,basePath,maxSkips,qParams){if(!this.isSuccess())return{failed:true,interrupted:this.interrupted,numRuns:this.firstFailure()+1-this.numSkips,numSkips:this.numSkips,numShrinks:this.numShrinks(),seed,counterexample:this.value,counterexamplePath:RunExecution2.mergePaths(basePath,this.pathToFailure),errorInstance:this.failure.error,failures:this.extractFailures(),executionSummary:this.rootExecutionTrees,verbose:this.verbosity,runConfiguration:qParams.toParameters()};const considerInterruptedAsFailure=this.interruptedAsFailure||this.numSuccesses===0;return{failed:this.numSkips>maxSkips||this.interrupted&&considerInterruptedAsFailure,interrupted:this.interrupted,numRuns:this.numSuccesses,numSkips:this.numSkips,numShrinks:0,seed,counterexample:null,counterexamplePath:null,error:null,errorInstance:null,failures:[],executionSummary:this.rootExecutionTrees,verbose:this.verbosity,runConfiguration:qParams.toParameters()}}};var RunnerIterator=class{constructor(sourceValues,shrink,verbose,interruptedAsFailure){this.sourceValues=sourceValues;this.shrink=shrink;this.runExecution=new RunExecution(verbose,interruptedAsFailure);this.currentIdx=-1;this.nextValues=sourceValues}[Symbol.iterator](){return this}next(){const nextValue=this.nextValues.next();if(nextValue.done||this.runExecution.interrupted)return{done:true,value:undefined};this.currentValue=nextValue.value;++this.currentIdx;return{done:false,value:nextValue.value.value_}}handleResult(result3){if(result3!==null&&typeof result3==="object"&&!PreconditionFailure.isFailure(result3)){this.runExecution.fail(this.currentValue.value_,this.currentIdx,result3);this.currentIdx=-1;this.nextValues=this.shrink(this.currentValue)}else if(result3!==null)if(!result3.interruptExecution){this.runExecution.skip(this.currentValue.value_);this.sourceValues.skippedOne()}else this.runExecution.interrupt();else this.runExecution.success(this.currentValue.value_)}};var SourceValuesIterator=class{constructor(initialValues,maxInitialIterations,remainingSkips){this.initialValues=initialValues;this.maxInitialIterations=maxInitialIterations;this.remainingSkips=remainingSkips}[Symbol.iterator](){return this}next(){if(--this.maxInitialIterations!==-1&&this.remainingSkips>=0){const n=this.initialValues.next();if(!n.done)return{value:n.value,done:false}}return{value:undefined,done:true}}skippedOne(){--this.remainingSkips;++this.maxInitialIterations}};var MIN_INT=-2147483648;var MAX_INT=2147483647;var DBL_FACTOR=Math.pow(2,27);var DBL_DIVISOR=Math.pow(2,-53);var Random=class Random2{constructor(sourceRng){this.internalRng=adaptRandomGenerator(sourceRng.clone())}clone(){return new Random2(this.internalRng)}next(bits){return uniformInt(this.internalRng,0,(1<<bits)-1)}nextBoolean(){return uniformInt(this.internalRng,0,1)===1}nextInt(min5,max5){return uniformInt(this.internalRng,min5===undefined?MIN_INT:min5,max5===undefined?MAX_INT:max5)}nextBigInt(min5,max5){return uniformBigInt(this.internalRng,min5,max5)}nextDouble(){const a=this.next(26);const b=this.next(27);return(a*DBL_FACTOR+b)*DBL_DIVISOR}getState(){if("getState"in this.internalRng&&typeof this.internalRng.getState==="function")return this.internalRng.getState()}};function tossNext(generator,rng,index2){rng.jump();return generator.generate(new Random(rng),index2)}function*toss(generator,seed,random2,examples){for(let idx=0;idx!==examples.length;++idx)yield new Value(examples[idx],undefined);for(let idx=0,rng=random2(seed);;++idx)yield tossNext(generator,rng,idx)}function lazyGenerate(generator,rng,idx){return()=>generator.generate(new Random(rng),idx)}function*lazyToss(generator,seed,random2,examples){yield*safeMap(examples,(e)=>()=>new Value(e,undefined));let idx=0;const rng=adaptRandomGenerator(random2(seed));for(;;){rng.jump();yield lazyGenerate(generator,rng,idx++)}}function produce(producer){return producer()}function pathWalk(path,initialProducers,shrink){const producers=initialProducers;const segments=path.split(":").map((text)=>+text);if(segments.length===0)return producers.map(produce);if(!segments.every((v)=>!Number.isNaN(v)))throw new Error(`Unable to replay, got invalid path=${path}`);let values3=producers.drop(segments[0]).map(produce);for(const s of segments.slice(1)){const valueToShrink=values3.getNthOrLast(0);if(valueToShrink===null)throw new Error(`Unable to replay, got wrong path=${path}`);values3=shrink(valueToShrink).drop(s)}return values3}var safeObjectAssign$6=Object.assign;function formatHints(hints){if(hints.length===1)return`Hint: ${hints[0]}`;return hints.map((h,idx)=>`Hint (${idx+1}): ${h}`).join(`
|
|
190
190
|
`)}function formatFailures(failures,stringifyOne){return`Encountered failures were:
|
|
191
191
|
- ${failures.map(stringifyOne).join(`
|
|
192
192
|
- `)}`}function formatExecutionSummary(executionTrees,stringifyOne){const summaryLines=[];const remainingTreesAndDepth=[];for(let i=executionTrees.length-1;i>=0;--i)remainingTreesAndDepth.push({depth:1,tree:executionTrees[i]});while(remainingTreesAndDepth.length!==0){const currentTreeAndDepth=remainingTreesAndDepth.pop();const currentTree=currentTreeAndDepth.tree;const currentDepth=currentTreeAndDepth.depth;const statusIcon=currentTree.status===0?"\x1B[32m√\x1B[0m":currentTree.status===1?"\x1B[31m×\x1B[0m":"\x1B[33m!\x1B[0m";const leftPadding=currentDepth!==0?". ".repeat(currentDepth-1):"";summaryLines.push(`${leftPadding}${statusIcon} ${stringifyOne(currentTree.value)}`);for(let i=currentTree.children.length-1;i>=0;--i)remainingTreesAndDepth.push({depth:currentDepth+1,tree:currentTree.children[i]})}return`Execution summary:
|
|
@@ -218,7 +218,7 @@ ${formatHints(hints)}`;return errorMessage}function defaultReportMessage(out){re
|
|
|
218
218
|
`)}`:""}
|
|
219
219
|
const outs = ${stringifiedOuts};
|
|
220
220
|
return outs[hash('${seed}' + stringify(args)) % outs.length];
|
|
221
|
-
}`}return safeObjectDefineProperties$1(f,{toString:{value:()=>prettyPrint(stringify(outs))},[toStringMethod]:{value:()=>prettyPrint(stringify(outs))},[asyncToStringMethod]:{value:async()=>prettyPrint(await asyncStringify(outs))},[cloneMethod]:{value:producer,configurable:true}})};return producer()})}var safeMinSafeInteger=Number.MIN_SAFE_INTEGER;var safeMaxSafeInteger$1=Number.MAX_SAFE_INTEGER;function maxSafeInteger(){return new IntegerArbitrary(safeMinSafeInteger,safeMaxSafeInteger$1)}var safeMaxSafeInteger=Number.MAX_SAFE_INTEGER;function maxSafeNat(){return new IntegerArbitrary(0,safeMaxSafeInteger)}var safeNumberParseInt=Number.parseInt;function natToStringifiedNatMapper(options){const[style,v]=options;switch(style){case"oct":return`0${safeNumberToString(v,8)}`;case"hex":return`0x${safeNumberToString(v,16)}`;default:return`${v}`}}function tryParseStringifiedNat(stringValue,radix){const parsedNat=safeNumberParseInt(stringValue,radix);if(safeNumberToString(parsedNat,radix)!==stringValue)throw new Error("Invalid value");return parsedNat}function natToStringifiedNatUnmapper(value3){if(typeof value3!=="string")throw new Error("Invalid type");if(value3.length>=2&&value3[0]==="0"){if(value3[1]==="x")return["hex",tryParseStringifiedNat(safeSubstring(value3,2),16)];return["oct",tryParseStringifiedNat(safeSubstring(value3,1),8)]}return["dec",tryParseStringifiedNat(value3,10)]}function dotJoinerMapper$1(data){return safeJoin(data,".")}function dotJoinerUnmapper$1(value3){if(typeof value3!=="string")throw new Error("Invalid type");return safeMap(safeSplit(value3,"."),(v)=>tryParseStringifiedNat(v,10))}function ipV4(){return tuple2(nat(255),nat(255),nat(255),nat(255)).map(dotJoinerMapper$1,dotJoinerUnmapper$1)}function buildStringifiedNatArbitrary(maxValue){return tuple2(constantFrom("dec","oct","hex"),nat(maxValue)).map(natToStringifiedNatMapper,natToStringifiedNatUnmapper)}function dotJoinerMapper(data){return safeJoin(data,".")}function dotJoinerUnmapper(value3){if(typeof value3!=="string")throw new Error("Invalid type");return safeSplit(value3,".")}function ipV4Extended(){return oneof(tuple2(buildStringifiedNatArbitrary(255),buildStringifiedNatArbitrary(255),buildStringifiedNatArbitrary(255),buildStringifiedNatArbitrary(255)).map(dotJoinerMapper,dotJoinerUnmapper),tuple2(buildStringifiedNatArbitrary(255),buildStringifiedNatArbitrary(255),buildStringifiedNatArbitrary(65535)).map(dotJoinerMapper,dotJoinerUnmapper),tuple2(buildStringifiedNatArbitrary(255),buildStringifiedNatArbitrary(16777215)).map(dotJoinerMapper,dotJoinerUnmapper),buildStringifiedNatArbitrary(4294967295))}function readBh(value3){if(value3.length===0)return[];else return safeSplit(value3,":")}function extractEhAndL(value3){const valueSplits=safeSplit(value3,":");if(valueSplits.length>=2&&valueSplits[valueSplits.length-1].length<=4)return[safeSlice(valueSplits,0,valueSplits.length-2),`${valueSplits[valueSplits.length-2]}:${valueSplits[valueSplits.length-1]}`];return[safeSlice(valueSplits,0,valueSplits.length-1),valueSplits[valueSplits.length-1]]}function fullySpecifiedMapper(data){return`${safeJoin(data[0],":")}:${data[1]}`}function fullySpecifiedUnmapper(value3){if(typeof value3!=="string")throw new Error("Invalid type");return extractEhAndL(value3)}function onlyTrailingMapper(data){return`::${safeJoin(data[0],":")}:${data[1]}`}function onlyTrailingUnmapper(value3){if(typeof value3!=="string")throw new Error("Invalid type");if(!safeStartsWith(value3,"::"))throw new Error("Invalid value");return extractEhAndL(safeSubstring(value3,2))}function multiTrailingMapper(data){return`${safeJoin(data[0],":")}::${safeJoin(data[1],":")}:${data[2]}`}function multiTrailingUnmapper(value3){if(typeof value3!=="string")throw new Error("Invalid type");const[bhString,trailingString]=safeSplit(value3,"::",2);const[eh,l]=extractEhAndL(trailingString);return[readBh(bhString),eh,l]}function multiTrailingMapperOne(data){return multiTrailingMapper([data[0],[data[1]],data[2]])}function multiTrailingUnmapperOne(value3){const out=multiTrailingUnmapper(value3);return[out[0],safeJoin(out[1],":"),out[2]]}function singleTrailingMapper(data){return`${safeJoin(data[0],":")}::${data[1]}`}function singleTrailingUnmapper(value3){if(typeof value3!=="string")throw new Error("Invalid type");const[bhString,trailing]=safeSplit(value3,"::",2);return[readBh(bhString),trailing]}function noTrailingMapper(data){return`${safeJoin(data[0],":")}::`}function noTrailingUnmapper(value3){if(typeof value3!=="string")throw new Error("Invalid type");if(!safeEndsWith(value3,"::"))throw new Error("Invalid value");return[readBh(safeSubstring(value3,0,value3.length-2))]}function h16sTol32Mapper([a,b]){return`${a}:${b}`}function h16sTol32Unmapper(value3){if(typeof value3!=="string")throw new SError("Invalid type");if(!value3.includes(":"))throw new SError("Invalid value");return value3.split(":",2)}var items="0123456789abcdef";var cachedHexa=undefined;function hexa(){if(cachedHexa===undefined)cachedHexa=integer({min:0,max:15}).map((n)=>items[n],(c)=>{if(typeof c!=="string")throw new SError("Not a string");if(c.length!==1)throw new SError("Invalid length");const code=safeCharCodeAt(c,0);if(code<=57)return code-48;if(code<97)throw new SError("Invalid character");return code-87});return cachedHexa}function ipV6(){const h16Arb=string3({unit:hexa(),minLength:1,maxLength:4,size:"max"});const ls32Arb=oneof(tuple2(h16Arb,h16Arb).map(h16sTol32Mapper,h16sTol32Unmapper),ipV4());return oneof(tuple2(array3(h16Arb,{minLength:6,maxLength:6,size:"max"}),ls32Arb).map(fullySpecifiedMapper,fullySpecifiedUnmapper),tuple2(array3(h16Arb,{minLength:5,maxLength:5,size:"max"}),ls32Arb).map(onlyTrailingMapper,onlyTrailingUnmapper),tuple2(array3(h16Arb,{minLength:0,maxLength:1,size:"max"}),array3(h16Arb,{minLength:4,maxLength:4,size:"max"}),ls32Arb).map(multiTrailingMapper,multiTrailingUnmapper),tuple2(array3(h16Arb,{minLength:0,maxLength:2,size:"max"}),array3(h16Arb,{minLength:3,maxLength:3,size:"max"}),ls32Arb).map(multiTrailingMapper,multiTrailingUnmapper),tuple2(array3(h16Arb,{minLength:0,maxLength:3,size:"max"}),array3(h16Arb,{minLength:2,maxLength:2,size:"max"}),ls32Arb).map(multiTrailingMapper,multiTrailingUnmapper),tuple2(array3(h16Arb,{minLength:0,maxLength:4,size:"max"}),h16Arb,ls32Arb).map(multiTrailingMapperOne,multiTrailingUnmapperOne),tuple2(array3(h16Arb,{minLength:0,maxLength:5,size:"max"}),ls32Arb).map(singleTrailingMapper,singleTrailingUnmapper),tuple2(array3(h16Arb,{minLength:0,maxLength:6,size:"max"}),h16Arb).map(singleTrailingMapper,singleTrailingUnmapper),tuple2(array3(h16Arb,{minLength:0,maxLength:7,size:"max"})).map(noTrailingMapper,noTrailingUnmapper))}var LazyArbitrary=class extends Arbitrary{constructor(name){super();this.name=name;this.underlying=null}generate(mrng,biasFactor){if(this.underlying===null)throw new Error(`Lazy arbitrary ${JSON.stringify(this.name)} not correctly initialized`);return this.underlying.generate(mrng,biasFactor)}canShrinkWithoutContext(value3){if(this.underlying===null)throw new Error(`Lazy arbitrary ${JSON.stringify(this.name)} not correctly initialized`);return this.underlying.canShrinkWithoutContext(value3)}shrink(value3,context4){if(this.underlying===null)throw new Error(`Lazy arbitrary ${JSON.stringify(this.name)} not correctly initialized`);return this.underlying.shrink(value3,context4)}};var safeGetOwnPropertyNames=Object.getOwnPropertyNames;function createLazyArbsPool(){const lazyArbsPool=new SMap$1;const getLazyFromPool=(key)=>{let lazyArb=safeMapGet(lazyArbsPool,key);if(lazyArb!==undefined)return lazyArb;lazyArb=new LazyArbitrary(String(key));safeMapSet(lazyArbsPool,key,lazyArb);return lazyArb};return getLazyFromPool}function letrec(builder){const getLazyFromPool=createLazyArbsPool();const strictArbs=builder(getLazyFromPool);const declaredArbitraryNames=safeGetOwnPropertyNames(strictArbs);for(const name of declaredArbitraryNames){const lazyArb=getLazyFromPool(name);lazyArb.underlying=strictArbs[name]}return strictArbs}function canHaveAtLeastOneItem(keys3,constraints){for(const key of keys3){const constraintsOnKey=constraints[key]||{};if(constraintsOnKey.maxLength===undefined||constraintsOnKey.maxLength>0)return true}return false}function initialPoolForEntityGraph(keys3,constraints){if(keys3.length===0)return constant2([]);if(!canHaveAtLeastOneItem(keys3,constraints))throw new SError("Contraints on pool must accept at least one entity, maxLength cannot sum to 0");return tuple2(...keys3.map((key)=>array3(constant2(key),constraints[key]))).map((values3)=>safeFlat(values3)).filter((names)=>names.length>0)}var safeObjectAssign$1=Object.assign;var safeObjectCreate$4=Object.create;var safeObjectDefineProperty$1=Object.defineProperty;var safeObjectGetPrototypeOf=Object.getPrototypeOf;var safeObjectPrototype=Object.prototype;function withTargetStringifiedValue(stringifiedValue){return safeObjectDefineProperty$1(safeObjectCreate$4(null),toStringMethod,{configurable:false,enumerable:false,writable:false,value:()=>stringifiedValue})}function withReferenceStringifiedValue(type,index2){return withTargetStringifiedValue(`<${SString(type)}#${index2}>`)}function unlinkedToLinkedEntitiesMapper(unlinkedEntities,producedLinks){const linkedEntities=safeObjectCreate$4(safeObjectPrototype);for(const name in unlinkedEntities){const unlinkedEntitiesForName=unlinkedEntities[name];const linkedEntitiesForName=[];for(const unlinkedEntity of unlinkedEntitiesForName){const linkedEntity=safeObjectAssign$1(safeObjectCreate$4(safeObjectGetPrototypeOf(unlinkedEntity)),unlinkedEntity);linkedEntitiesForName.push(linkedEntity)}linkedEntities[name]=linkedEntitiesForName}for(const name in producedLinks){const entityLinks=producedLinks[name];for(let entityIndex=0;entityIndex!==entityLinks.length;++entityIndex){const entityLinksForInstance=entityLinks[entityIndex];const linkedInstance=linkedEntities[name][entityIndex];for(const prop in entityLinksForInstance){const propValue=entityLinksForInstance[prop];linkedInstance[prop]=propValue.index===undefined?undefined:typeof propValue.index==="number"?linkedEntities[propValue.type][propValue.index]:safeMap(propValue.index,(index2)=>linkedEntities[propValue.type][index2])}safeObjectDefineProperty$1(linkedInstance,toStringMethod,{configurable:false,enumerable:false,writable:false,value:()=>{const unlinkedEntity=unlinkedEntities[name][entityIndex];const entity=safeObjectAssign$1(safeObjectCreate$4(safeObjectGetPrototypeOf(unlinkedEntity)),unlinkedEntity);for(const prop in entityLinksForInstance){const propValue=entityLinksForInstance[prop];entity[prop]=propValue.index===undefined?undefined:typeof propValue.index==="number"?withReferenceStringifiedValue(propValue.type,propValue.index):safeMap(propValue.index,(index2)=>withReferenceStringifiedValue(propValue.type,index2))}return stringify(entity)}})}}return linkedEntities}function buildInversedRelationsMapping(relations){let foundInversedRelations=0;const requestedInversedRelations=new SMap$1;for(const name in relations){const relationsForName=relations[name];for(const fieldName in relationsForName){const relation=relationsForName[fieldName];if(relation.arity!=="inverse")continue;let existingOnes=safeMapGet(requestedInversedRelations,relation.type);if(existingOnes===undefined){existingOnes=new SMap$1;safeMapSet(requestedInversedRelations,relation.type,existingOnes)}if(safeMapHas(existingOnes,relation.forwardRelationship))throw new SError(`Cannot declare multiple inverse relationships for the same forward relationship ${SString(relation.forwardRelationship)} on type ${SString(relation.type)}`);safeMapSet(existingOnes,relation.forwardRelationship,{type:name,property:fieldName});foundInversedRelations+=1}}const inversedRelations=new SMap$1;if(foundInversedRelations===0)return inversedRelations;for(const name in relations){const relationsForName=relations[name];const requestedInversedRelationsForName=safeMapGet(requestedInversedRelations,name);if(requestedInversedRelationsForName===undefined)continue;for(const fieldName in relationsForName){const relation=relationsForName[fieldName];if(relation.arity==="inverse")continue;const requestedIfAny=safeMapGet(requestedInversedRelationsForName,fieldName);if(requestedIfAny===undefined)continue;if(requestedIfAny.type!==relation.type)throw new SError(`Inverse relationship ${SString(requestedIfAny.property)} on type ${SString(requestedIfAny.type)} references forward relationship ${SString(fieldName)} but types do not match`);safeMapSet(inversedRelations,relation,requestedIfAny)}}if(inversedRelations.size!==foundInversedRelations)throw new SError(`Some inverse relationships could not be matched with their corresponding forward relationships`);return inversedRelations}var safeObjectAssign=Object.assign;var safeObjectCreate$3=Object.create;function produceLinkUnitaryIndexArbitrary(strategy,currentIndexIfSameType,countInTargetType){switch(strategy){case"exclusive":return constant2(countInTargetType);case"successor":return noBias(integer({min:currentIndexIfSameType!==undefined?currentIndexIfSameType+1:0,max:countInTargetType}));case"any":return noBias(integer({min:0,max:countInTargetType}))}}function buildLinkIndexArbitrary(arity,strategy,currentIndexIfSameType,countInTargetType,currentEntityDepth){const linkArbitrary=produceLinkUnitaryIndexArbitrary(strategy,currentIndexIfSameType,countInTargetType);switch(arity){case"0-1":return option3(linkArbitrary,{nil:undefined,depthIdentifier:currentEntityDepth});case"1":return linkArbitrary;case"many":{let randomUnicity=0;return option3(uniqueArray(linkArbitrary,{depthIdentifier:currentEntityDepth,selector:(v)=>v===countInTargetType?v+ ++randomUnicity:v,minLength:1}),{nil:[],depthIdentifier:currentEntityDepth}).map((values3)=>{let offset=0;return safeMap(values3,(v)=>v===countInTargetType?v+offset++:v)})}}}function createEmptyLinksInstanceFor(relations,targetType){const emptyLinksInstance=safeObjectCreate$3(null);const relationsForType=relations[targetType];for(const name in relationsForType){const relation=relationsForType[name];if(relation.arity==="inverse")emptyLinksInstance[name]={type:relation.type,index:[]}}return emptyLinksInstance}function assertAcceptableRelations(relations){const nonExclusiveEntities=new SSet;const exclusiveEntities=new SSet;for(const name in relations){const relationsForName=relations[name];for(const fieldName in relationsForName){const relation=relationsForName[fieldName];if(relation.arity==="inverse")continue;if(relation.strategy==="exclusive"){if(safeHas(nonExclusiveEntities,relation.type))throw new SError(`Cannot mix exclusive with other strategies for type ${SString(relation.type)}`);safeAdd(exclusiveEntities,relation.type)}else{if(safeHas(exclusiveEntities,relation.type))throw new SError(`Cannot mix exclusive with other strategies for type ${SString(relation.type)}`);safeAdd(nonExclusiveEntities,relation.type)}if(relation.strategy==="successor"&&relation.type!==name)throw new SError(`Cannot mix types for the strategy successor`);if(relation.strategy==="successor"&&relation.arity==="1")throw new SError(`Cannot use an arity of 1 for the strategy successor`)}}}function draftNextProductionState(state,offset){const{producedLinks,toBeProducedEntities}=state;const nextIndex=state.nextIndex+offset;const newProducedLinks=safeObjectAssign(safeObjectCreate$3(null),producedLinks);function getOrCreateProducedLinksFor(type){if(newProducedLinks[type]===producedLinks[type])newProducedLinks[type]=safeSlice(producedLinks[type]);return newProducedLinks[type]}function getOrCreateLinksFor(type,indexInType){const producedLinksForType=getOrCreateProducedLinksFor(type);if(producedLinksForType[indexInType]===producedLinks[type][indexInType])producedLinksForType[indexInType]=safeObjectAssign(safeObjectCreate$3(null),producedLinks[type][indexInType]);return producedLinksForType[indexInType]}function getOrCreateRelationFor(type,indexInType,property2){const links=getOrCreateLinksFor(type,indexInType);const originalEntity=producedLinks[type][indexInType];if(originalEntity!==undefined&&links[property2]===originalEntity[property2]){const sharedRelation=links[property2];links[property2]={type:sharedRelation.type,index:typeof sharedRelation.index==="object"?safeSlice(sharedRelation.index):sharedRelation.index}}return links[property2]}let newToBeProducedEntities=undefined;const toBeProduced=toBeProducedEntities[nextIndex];return{setOutboundLink:(name,value3)=>{const currentLinks=getOrCreateLinksFor(toBeProduced.type,toBeProduced.indexInType);currentLinks[name]=value3},enqueueNewEntity:(relations,targetType)=>{const producedLinksInTargetType=getOrCreateProducedLinksFor(targetType);const newEntityIndexInType=producedLinksInTargetType.length;if(newToBeProducedEntities===undefined)newToBeProducedEntities=safeSlice(toBeProducedEntities);safePush(newToBeProducedEntities,{type:targetType,indexInType:newEntityIndexInType,depth:toBeProduced.depth+1});safePush(producedLinksInTargetType,createEmptyLinksInstanceFor(relations,targetType));return newEntityIndexInType},appendBackReference:(targetType,indexInType,property2)=>{const knownInversedLinks=getOrCreateRelationFor(targetType,indexInType,property2).index;safePush(knownInversedLinks,toBeProduced.indexInType)},commit:()=>({producedLinks:newProducedLinks,toBeProducedEntities:newToBeProducedEntities!==undefined?newToBeProducedEntities:toBeProducedEntities,nextIndex:nextIndex+1})}}function buildInitialProductionState(relations,defaultEntities){const producedLinks=safeObjectCreate$3(null);for(const name in relations)producedLinks[name]=[];const toBeProducedEntities=[];for(const name of defaultEntities){safePush(toBeProducedEntities,{type:name,indexInType:producedLinks[name].length,depth:0});safePush(producedLinks[name],createEmptyLinksInstanceFor(relations,name))}return{producedLinks,toBeProducedEntities,nextIndex:0}}function buildEntityStepArbitrary(relations,inversedRelations,lastState,offset){const lastProducedLinks=lastState.producedLinks;const currentEntity=lastState.toBeProducedEntities[lastState.nextIndex+offset];const currentRelations=relations[currentEntity.type];const currentEntityDepth=createDepthIdentifier();currentEntityDepth.depth=currentEntity.depth;const subArbitraries=[];const linkContexts=[];for(const name in currentRelations){const relation=currentRelations[name];if(relation.arity==="inverse")continue;const targetType=relation.type;const countInTargetType=lastProducedLinks[targetType].length;safePush(subArbitraries,buildLinkIndexArbitrary(relation.arity,relation.strategy||"any",targetType===currentEntity.type?currentEntity.indexInType:undefined,countInTargetType,currentEntityDepth));safePush(linkContexts,{name,relation,sentinelLinkIndex:countInTargetType})}if(subArbitraries.length===0)return;return tuple2(...subArbitraries).map((results)=>{const state=draftNextProductionState(lastState,offset);for(let resultIndex=0;resultIndex!==results.length;++resultIndex){const linkOrLinks=results[resultIndex];const{name,relation,sentinelLinkIndex}=linkContexts[resultIndex];const effectiveLinks=[];const links=linkOrLinks===undefined?[]:typeof linkOrLinks==="number"?[linkOrLinks]:linkOrLinks;for(const link of links){let newEntityIndexInType;if(link>=sentinelLinkIndex)newEntityIndexInType=state.enqueueNewEntity(relations,relation.type);else newEntityIndexInType=link;safePush(effectiveLinks,newEntityIndexInType);const inversed=safeMapGet(inversedRelations,relation);if(inversed!==undefined)state.appendBackReference(relation.type,newEntityIndexInType,inversed.property)}state.setOutboundLink(name,{type:relation.type,index:linkOrLinks===undefined?undefined:typeof linkOrLinks==="number"?effectiveLinks[0]:effectiveLinks})}return state.commit()})}function onTheFlyLinksForEntityGraph(relations,defaultEntities){assertAcceptableRelations(relations);const inversedRelations=buildInversedRelationsMapping(relations);return chainUntil(constant2(buildInitialProductionState(relations,defaultEntities)),(state)=>{if(state.nextIndex>=state.toBeProducedEntities.length)return;let offset=0;let next=undefined;while(next===undefined&&state.nextIndex+offset<state.toBeProducedEntities.length){next=buildEntityStepArbitrary(relations,inversedRelations,state,offset);offset+=1}return next}).map((state)=>{return state.producedLinks})}var safeObjectKeys$1=Object.keys;var safeObjectGetOwnPropertySymbols$1=Object.getOwnPropertySymbols;var safeObjectGetOwnPropertyDescriptor$1=Object.getOwnPropertyDescriptor;function extractEnumerableKeys(instance){const keys3=safeObjectKeys$1(instance);const symbols=safeObjectGetOwnPropertySymbols$1(instance);for(let index2=0;index2!==symbols.length;++index2){const symbol4=symbols[index2];const descriptor=safeObjectGetOwnPropertyDescriptor$1(instance,symbol4);if(descriptor&&descriptor.enumerable)keys3.push(symbol4)}return keys3}var safeObjectCreate$2=Object.create;var safeObjectDefineProperty=Object.defineProperty;var safeObjectGetOwnPropertyDescriptor=Object.getOwnPropertyDescriptor;var safeObjectGetOwnPropertyNames=Object.getOwnPropertyNames;var safeObjectGetOwnPropertySymbols=Object.getOwnPropertySymbols;function buildValuesAndSeparateKeysToObjectMapper(keys3,noKeyValue){return function valuesAndSeparateKeysToObjectMapper(definition){const obj=definition[definition.length-1]?safeObjectCreate$2(null):{};for(let idx=0;idx!==keys3.length;++idx){const valueWrapper=definition[idx];if(valueWrapper!==noKeyValue){const key=keys3[idx];if(key==="__proto__")safeObjectDefineProperty(obj,key,{value:valueWrapper,configurable:true,enumerable:true,writable:true});else obj[key]=valueWrapper}}return obj}}function buildValuesAndSeparateKeysToObjectUnmapper(keys3,noKeyValue){return function valuesAndSeparateKeysToObjectUnmapper(value3){if(typeof value3!=="object"||value3===null)throw new Error("Incompatible instance received: should be a non-null object");const hasNullPrototype=Object.getPrototypeOf(value3)===null;const hasObjectPrototype="constructor"in value3&&value3.constructor===Object;if(!hasNullPrototype&&!hasObjectPrototype)throw new Error("Incompatible instance received: should be of exact type Object");let extractedPropertiesCount=0;const extractedValues=[];for(let idx=0;idx!==keys3.length;++idx){const descriptor=safeObjectGetOwnPropertyDescriptor(value3,keys3[idx]);if(descriptor!==undefined){if(!descriptor.configurable||!descriptor.enumerable||!descriptor.writable)throw new Error("Incompatible instance received: should contain only c/e/w properties");if(descriptor.get!==undefined||descriptor.set!==undefined)throw new Error("Incompatible instance received: should contain only no get/set properties");++extractedPropertiesCount;safePush(extractedValues,descriptor.value)}else safePush(extractedValues,noKeyValue)}const namePropertiesCount=safeObjectGetOwnPropertyNames(value3).length;const symbolPropertiesCount=safeObjectGetOwnPropertySymbols(value3).length;if(extractedPropertiesCount!==namePropertiesCount+symbolPropertiesCount)throw new Error("Incompatible instance received: should not contain extra properties");return[...extractedValues,hasNullPrototype]}}var noKeyValue=Symbol("no-key");function buildPartialRecordArbitrary(recordModel,requiredKeys,noNullPrototype){const keys3=extractEnumerableKeys(recordModel);const arbs=[];for(let index2=0;index2!==keys3.length;++index2){const k=keys3[index2];const requiredArbitrary=recordModel[k];if(requiredKeys===undefined||safeIndexOf(requiredKeys,k)!==-1)safePush(arbs,requiredArbitrary);else safePush(arbs,option3(requiredArbitrary,{nil:noKeyValue}))}return tuple2(...arbs,noNullPrototype?constant2(false):boolean2()).map(buildValuesAndSeparateKeysToObjectMapper(keys3,noKeyValue),buildValuesAndSeparateKeysToObjectUnmapper(keys3,noKeyValue))}function record2(recordModel,constraints){const noNullPrototype=constraints!==undefined&&!!constraints.noNullPrototype;if(constraints===undefined)return buildPartialRecordArbitrary(recordModel,undefined,noNullPrototype);if(!(("requiredKeys"in constraints)&&constraints.requiredKeys!==undefined))return buildPartialRecordArbitrary(recordModel,undefined,noNullPrototype);const requiredKeys=("requiredKeys"in constraints?constraints.requiredKeys:undefined)||[];for(let idx=0;idx!==requiredKeys.length;++idx){const descriptor=Object.getOwnPropertyDescriptor(recordModel,requiredKeys[idx]);if(descriptor===undefined)throw new Error(`requiredKeys cannot reference keys that have not been defined in recordModel`);if(!descriptor.enumerable)throw new Error(`requiredKeys cannot reference keys that are not enumerable in recordModel`)}return buildPartialRecordArbitrary(recordModel,requiredKeys,noNullPrototype)}var safeObjectCreate$1=Object.create;function unlinkedEntitiesForEntityGraph(arbitraries,countFor,unicityConstraintsFor,constraints){const recordModel=safeObjectCreate$1(null);for(const name in arbitraries){const entityRecordModel=arbitraries[name];const entityArbitrary=record2(entityRecordModel,constraints);const count=countFor(name);const unicityConstraints=unicityConstraintsFor(name);const arrayConstraints={minLength:count,maxLength:count};recordModel[name]=unicityConstraints!==undefined?uniqueArray(entityArbitrary,{...arrayConstraints,selector:unicityConstraints}):array3(entityArbitrary,arrayConstraints)}return record2(recordModel)}var safeObjectCreate=Object.create;var safeObjectKeys=Object.keys;function entityGraph(arbitraries,relations,constraints={}){const allKeys=safeObjectKeys(arbitraries);const initialPoolConstraints=constraints.initialPoolConstraints||safeObjectCreate(null);const unicityConstraints=constraints.unicityConstraints||safeObjectCreate(null);const unlinkedContraints={noNullPrototype:constraints.noNullPrototype};return initialPoolForEntityGraph(allKeys,initialPoolConstraints).chain((defaultEntities)=>onTheFlyLinksForEntityGraph(relations,defaultEntities).chain((producedLinks)=>unlinkedEntitiesForEntityGraph(arbitraries,(name)=>producedLinks[name].length,(name)=>unicityConstraints[name],unlinkedContraints).map((unlinkedEntities)=>unlinkedToLinkedEntitiesMapper(unlinkedEntities,producedLinks))))}function wordsToJoinedStringMapper(words){return safeJoin(safeMap(words,(w)=>w[w.length-1]===","?safeSubstring(w,0,w.length-1):w)," ")}function wordsToJoinedStringUnmapperFor(wordsArbitrary){return function wordsToJoinedStringUnmapper(value3){if(typeof value3!=="string")throw new Error("Unsupported type");const words=[];for(const candidate of safeSplit(value3," "))if(wordsArbitrary.canShrinkWithoutContext(candidate))safePush(words,candidate);else if(wordsArbitrary.canShrinkWithoutContext(candidate+","))safePush(words,candidate+",");else throw new Error("Unsupported word");return words}}function wordsToSentenceMapper(words){let sentence=safeJoin(words," ");if(sentence[sentence.length-1]===",")sentence=safeSubstring(sentence,0,sentence.length-1);return safeToUpperCase(sentence[0])+safeSubstring(sentence,1)+"."}function wordsToSentenceUnmapperFor(wordsArbitrary){return function wordsToSentenceUnmapper(value3){if(typeof value3!=="string")throw new Error("Unsupported type");if(value3.length<2||value3[value3.length-1]!=="."||value3[value3.length-2]===","||safeToUpperCase(safeToLowerCase(value3[0]))!==value3[0])throw new Error("Unsupported value");const adaptedValue=safeToLowerCase(value3[0])+safeSubstring(value3,1,value3.length-1);const words=[];const candidates=safeSplit(adaptedValue," ");for(let idx=0;idx!==candidates.length;++idx){const candidate=candidates[idx];if(wordsArbitrary.canShrinkWithoutContext(candidate))safePush(words,candidate);else if(idx===candidates.length-1&&wordsArbitrary.canShrinkWithoutContext(candidate+","))safePush(words,candidate+",");else throw new Error("Unsupported word")}return words}}function sentencesToParagraphMapper(sentences){return safeJoin(sentences," ")}function sentencesToParagraphUnmapper(value3){if(typeof value3!=="string")throw new Error("Unsupported type");const sentences=safeSplit(value3,". ");for(let idx=0;idx<sentences.length-1;++idx)sentences[idx]+=".";return sentences}var h=(v,w)=>{return{arbitrary:constant2(v),weight:w}};function loremWord(){return oneof(h("non",6),h("adipiscing",5),h("ligula",5),h("enim",5),h("pellentesque",5),h("in",5),h("augue",5),h("et",5),h("nulla",5),h("lorem",4),h("sit",4),h("sed",4),h("diam",4),h("fermentum",4),h("ut",4),h("eu",4),h("aliquam",4),h("mauris",4),h("vitae",4),h("felis",4),h("ipsum",3),h("dolor",3),h("amet,",3),h("elit",3),h("euismod",3),h("mi",3),h("orci",3),h("erat",3),h("praesent",3),h("egestas",3),h("leo",3),h("vel",3),h("sapien",3),h("integer",3),h("curabitur",3),h("convallis",3),h("purus",3),h("risus",2),h("suspendisse",2),h("lectus",2),h("nec,",2),h("ultricies",2),h("sed,",2),h("cras",2),h("elementum",2),h("ultrices",2),h("maecenas",2),h("massa,",2),h("varius",2),h("a,",2),h("semper",2),h("proin",2),h("nec",2),h("nisl",2),h("amet",2),h("duis",2),h("congue",2),h("libero",2),h("vestibulum",2),h("pede",2),h("blandit",2),h("sodales",2),h("ante",2),h("nibh",2),h("ac",2),h("aenean",2),h("massa",2),h("suscipit",2),h("sollicitudin",2),h("fusce",2),h("tempus",2),h("aliquam,",2),h("nunc",2),h("ullamcorper",2),h("rhoncus",2),h("metus",2),h("faucibus,",2),h("justo",2),h("magna",2),h("at",2),h("tincidunt",2),h("consectetur",1),h("tortor,",1),h("dignissim",1),h("congue,",1),h("non,",1),h("porttitor,",1),h("nonummy",1),h("molestie,",1),h("est",1),h("eleifend",1),h("mi,",1),h("arcu",1),h("scelerisque",1),h("vitae,",1),h("consequat",1),h("in,",1),h("pretium",1),h("volutpat",1),h("pharetra",1),h("tempor",1),h("bibendum",1),h("odio",1),h("dui",1),h("primis",1),h("faucibus",1),h("luctus",1),h("posuere",1),h("cubilia",1),h("curae,",1),h("hendrerit",1),h("velit",1),h("mauris,",1),h("gravida",1),h("ornare",1),h("ut,",1),h("pulvinar",1),h("varius,",1),h("turpis",1),h("nibh,",1),h("eros",1),h("id",1),h("aliquet",1),h("quis",1),h("lobortis",1),h("consectetuer",1),h("morbi",1),h("vehicula",1),h("tortor",1),h("tellus,",1),h("id,",1),h("eu,",1),h("quam",1),h("feugiat,",1),h("posuere,",1),h("iaculis",1),h("lectus,",1),h("tristique",1),h("mollis,",1),h("nisl,",1),h("vulputate",1),h("sem",1),h("vivamus",1),h("placerat",1),h("imperdiet",1),h("cursus",1),h("rutrum",1),h("iaculis,",1),h("augue,",1),h("lacus",1))}function lorem(constraints={}){const{maxCount,mode="words",size:size6}=constraints;if(maxCount!==undefined&&maxCount<1)throw new Error(`lorem has to produce at least one word/sentence`);const wordArbitrary=loremWord();if(mode==="sentences")return array3(array3(wordArbitrary,{minLength:1,size:"small"}).map(wordsToSentenceMapper,wordsToSentenceUnmapperFor(wordArbitrary)),{minLength:1,maxLength:maxCount,size:size6}).map(sentencesToParagraphMapper,sentencesToParagraphUnmapper);else return array3(wordArbitrary,{minLength:1,maxLength:maxCount,size:size6}).map(wordsToJoinedStringMapper,wordsToJoinedStringUnmapperFor(wordArbitrary))}function arrayToMapMapper(data){return new Map(data)}function arrayToMapUnmapper(value3){if(typeof value3!=="object"||value3===null)throw new Error("Incompatible instance received: should be a non-null object");if(!("constructor"in value3)||value3.constructor!==Map)throw new Error("Incompatible instance received: should be of exact type Map");return Array.from(value3)}function mapKeyExtractor(entry){return entry[0]}function map13(keyArb,valueArb,constraints={}){return uniqueArray(tuple2(keyArb,valueArb),{minLength:constraints.minKeys,maxLength:constraints.maxKeys,size:constraints.size,selector:mapKeyExtractor,depthIdentifier:constraints.depthIdentifier,comparator:"SameValueZero"}).map(arrayToMapMapper,arrayToMapUnmapper)}var contextRemainingDepth=10;function memo(builder){const previous={};return(maxDepth)=>{const n=maxDepth!==undefined?maxDepth:contextRemainingDepth;if(!safeHasOwnProperty(previous,n)){const prev=contextRemainingDepth;contextRemainingDepth=n-1;previous[n]=builder(n);contextRemainingDepth=prev}return previous[n]}}function countToggledBits(n){let count=0;while(n>SBigInt2(0)){if(n&SBigInt2(1))++count;n>>=SBigInt2(1)}return count}function computeNextFlags(flags,nextSize){const allowedMask=(SBigInt2(1)<<SBigInt2(nextSize))-SBigInt2(1);const preservedFlags=flags&allowedMask;let numMissingFlags=countToggledBits(flags-preservedFlags);let nFlags=preservedFlags;for(let mask2=SBigInt2(1);mask2<=allowedMask&&numMissingFlags!==0;mask2<<=SBigInt2(1))if(!(nFlags&mask2)){nFlags|=mask2;--numMissingFlags}return nFlags}function computeTogglePositions(chars,toggleCase){const positions=[];for(let idx=chars.length-1;idx!==-1;--idx)if(toggleCase(chars[idx])!==chars[idx])safePush(positions,idx);return positions}function computeFlagsFromChars(untoggledChars,toggledChars,togglePositions){let flags=SBigInt2(0);for(let idx=0,mask2=SBigInt2(1);idx!==togglePositions.length;++idx,mask2<<=SBigInt2(1))if(untoggledChars[togglePositions[idx]]!==toggledChars[togglePositions[idx]])flags|=mask2;return flags}function applyFlagsOnChars(chars,flags,togglePositions,toggleCase){for(let idx=0,mask2=SBigInt2(1);idx!==togglePositions.length;++idx,mask2<<=SBigInt2(1))if(flags&mask2)chars[togglePositions[idx]]=toggleCase(chars[togglePositions[idx]])}var MixedCaseArbitrary=class extends Arbitrary{constructor(stringArb,toggleCase,untoggleAll){super();this.stringArb=stringArb;this.toggleCase=toggleCase;this.untoggleAll=untoggleAll}buildContextFor(rawStringValue,flagsValue){return{rawString:rawStringValue.value,rawStringContext:rawStringValue.context,flags:flagsValue.value,flagsContext:flagsValue.context}}generate(mrng,biasFactor){const rawStringValue=this.stringArb.generate(mrng,biasFactor);const chars=[...rawStringValue.value];const togglePositions=computeTogglePositions(chars,this.toggleCase);const flagsValue=bigInt2(SBigInt2(0),(SBigInt2(1)<<SBigInt2(togglePositions.length))-SBigInt2(1)).generate(mrng,undefined);applyFlagsOnChars(chars,flagsValue.value,togglePositions,this.toggleCase);return new Value(safeJoin(chars,""),this.buildContextFor(rawStringValue,flagsValue))}canShrinkWithoutContext(value3){if(typeof value3!=="string")return false;return this.untoggleAll!==undefined?this.stringArb.canShrinkWithoutContext(this.untoggleAll(value3)):this.stringArb.canShrinkWithoutContext(value3)}shrink(value3,context4){let contextSafe;if(context4!==undefined)contextSafe=context4;else if(this.untoggleAll!==undefined){const untoggledValue=this.untoggleAll(value3);const valueChars=[...value3];const untoggledValueChars=[...untoggledValue];contextSafe={rawString:untoggledValue,rawStringContext:undefined,flags:computeFlagsFromChars(untoggledValueChars,valueChars,computeTogglePositions(untoggledValueChars,this.toggleCase)),flagsContext:undefined}}else contextSafe={rawString:value3,rawStringContext:undefined,flags:SBigInt2(0),flagsContext:undefined};const rawString=contextSafe.rawString;const flags=contextSafe.flags;return this.stringArb.shrink(rawString,contextSafe.rawStringContext).map((nRawStringValue)=>{const nChars=[...nRawStringValue.value];const nTogglePositions=computeTogglePositions(nChars,this.toggleCase);const nFlags=computeNextFlags(flags,nTogglePositions.length);applyFlagsOnChars(nChars,nFlags,nTogglePositions,this.toggleCase);return new Value(safeJoin(nChars,""),this.buildContextFor(nRawStringValue,new Value(nFlags,undefined)))}).join(makeLazy2(()=>{const chars=[...rawString];const togglePositions=computeTogglePositions(chars,this.toggleCase);return bigInt2(SBigInt2(0),(SBigInt2(1)<<SBigInt2(togglePositions.length))-SBigInt2(1)).shrink(flags,contextSafe.flagsContext).map((nFlagsValue)=>{const nChars=safeSlice(chars);applyFlagsOnChars(nChars,nFlagsValue.value,togglePositions,this.toggleCase);return new Value(safeJoin(nChars,""),this.buildContextFor(new Value(rawString,contextSafe.rawStringContext),nFlagsValue))})}))}};function defaultToggleCase(rawChar){const upper=safeToUpperCase(rawChar);if(upper!==rawChar)return upper;return safeToLowerCase(rawChar)}function mixedCase(stringArb,constraints){return new MixedCaseArbitrary(stringArb,constraints&&constraints.toggleCase||defaultToggleCase,constraints&&constraints.untoggleAll)}function toTypedMapper$1(data){return SFloat32Array.from(data)}function fromTypedUnmapper$1(value3){if(!(value3 instanceof SFloat32Array))throw new Error("Unexpected type");return[...value3]}function float32Array(constraints={}){return array3(float(constraints),constraints).map(toTypedMapper$1,fromTypedUnmapper$1)}function toTypedMapper(data){return SFloat64Array.from(data)}function fromTypedUnmapper(value3){if(!(value3 instanceof SFloat64Array))throw new Error("Unexpected type");return[...value3]}function float64Array(constraints={}){return array3(double(constraints),constraints).map(toTypedMapper,fromTypedUnmapper)}function typedIntArrayArbitraryArbitraryBuilder(constraints,defaultMin,defaultMax,TypedArrayClass,arbitraryBuilder){const generatorName=TypedArrayClass.name;const{min:min5=defaultMin,max:max5=defaultMax,...arrayConstraints}=constraints;if(min5>max5)throw new Error(`Invalid range passed to ${generatorName}: min must be lower than or equal to max`);if(min5<defaultMin)throw new Error(`Invalid min value passed to ${generatorName}: min must be greater than or equal to ${defaultMin}`);if(max5>defaultMax)throw new Error(`Invalid max value passed to ${generatorName}: max must be lower than or equal to ${defaultMax}`);return array3(arbitraryBuilder({min:min5,max:max5}),arrayConstraints).map((data)=>TypedArrayClass.from(data),(value3)=>{if(!(value3 instanceof TypedArrayClass))throw new Error("Invalid type");return[...value3]})}function int16Array(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,-32768,32767,SInt16Array,integer)}function int32Array(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,-2147483648,2147483647,SInt32Array,integer)}function int8Array(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,-128,127,SInt8Array,integer)}function uint16Array(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,0,65535,SUint16Array,integer)}function uint32Array(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,0,4294967295,SUint32Array,integer)}function uint8Array(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,0,255,SUint8Array,integer)}function uint8ClampedArray(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,0,255,SUint8ClampedArray,integer)}function isSafeContext(context4){return context4!==undefined}function toGeneratorValue(value3){if(value3.hasToBeCloned)return new Value(value3.value_,{generatorContext:value3.context},()=>value3.value);return new Value(value3.value_,{generatorContext:value3.context})}function toShrinkerValue(value3){if(value3.hasToBeCloned)return new Value(value3.value_,{shrinkerContext:value3.context},()=>value3.value);return new Value(value3.value_,{shrinkerContext:value3.context})}var WithShrinkFromOtherArbitrary=class extends Arbitrary{constructor(generatorArbitrary,shrinkerArbitrary){super();this.generatorArbitrary=generatorArbitrary;this.shrinkerArbitrary=shrinkerArbitrary}generate(mrng,biasFactor){return toGeneratorValue(this.generatorArbitrary.generate(mrng,biasFactor))}canShrinkWithoutContext(value3){return this.shrinkerArbitrary.canShrinkWithoutContext(value3)}shrink(value3,context4){if(!isSafeContext(context4))return this.shrinkerArbitrary.shrink(value3,undefined).map(toShrinkerValue);if("generatorContext"in context4)return this.generatorArbitrary.shrink(value3,context4.generatorContext).map(toGeneratorValue);return this.shrinkerArbitrary.shrink(value3,context4.shrinkerContext).map(toShrinkerValue)}};function restrictedIntegerArbitraryBuilder(min5,maxGenerated,max5){const generatorArbitrary=integer({min:min5,max:maxGenerated});if(maxGenerated===max5)return generatorArbitrary;return new WithShrinkFromOtherArbitrary(generatorArbitrary,integer({min:min5,max:max5}))}var safeMathMin$1=Math.min;var safeMathMax=Math.max;var safeArrayIsArray$1=SArray.isArray;var safeObjectEntries=Object.entries;function extractMaxIndex(indexesAndValues){let maxIndex=-1;for(let index2=0;index2!==indexesAndValues.length;++index2)maxIndex=safeMathMax(maxIndex,indexesAndValues[index2][0]);return maxIndex}function arrayFromItems(length,indexesAndValues){const array4=SArray(length);for(let index2=0;index2!==indexesAndValues.length;++index2){const it=indexesAndValues[index2];if(it[0]<length)array4[it[0]]=it[1]}return array4}function sparseArray(arb,constraints={}){const{size:size6,minNumElements=0,maxLength=MaxLengthUpperBound,maxNumElements=maxLength,noTrailingHole,depthIdentifier}=constraints;const maxGeneratedLength=maxGeneratedLengthFromSizeForArbitrary(size6,maxGeneratedLengthFromSizeForArbitrary(size6,minNumElements,maxNumElements,constraints.maxNumElements!==undefined),maxLength,constraints.maxLength!==undefined);if(minNumElements>maxLength)throw new Error(`The minimal number of non-hole elements cannot be higher than the maximal length of the array`);if(minNumElements>maxNumElements)throw new Error(`The minimal number of non-hole elements cannot be higher than the maximal number of non-holes`);const resultedMaxNumElements=safeMathMin$1(maxNumElements,maxLength);const resultedSizeMaxNumElements=constraints.maxNumElements!==undefined||size6!==undefined?size6:"=";const sparseArrayNoTrailingHole=uniqueArray(tuple2(restrictedIntegerArbitraryBuilder(0,safeMathMax(maxGeneratedLength-1,0),safeMathMax(maxLength-1,0)),arb),{size:resultedSizeMaxNumElements,minLength:minNumElements,maxLength:resultedMaxNumElements,selector:(item)=>item[0],depthIdentifier}).map((items2)=>{return arrayFromItems(extractMaxIndex(items2)+1,items2)},(value3)=>{if(!safeArrayIsArray$1(value3))throw new Error("Not supported entry type");if(noTrailingHole&&value3.length!==0&&!(value3.length-1 in value3))throw new Error("No trailing hole");return safeMap(safeObjectEntries(value3),(entry)=>[Number(entry[0]),entry[1]])});if(noTrailingHole||maxLength===minNumElements)return sparseArrayNoTrailingHole;return tuple2(sparseArrayNoTrailingHole,restrictedIntegerArbitraryBuilder(minNumElements,maxGeneratedLength,maxLength)).map((data)=>{const sparse=data[0];const targetLength=data[1];if(sparse.length>=targetLength)return sparse;const longerSparse=safeSlice(sparse);longerSparse.length=targetLength;return longerSparse},(value3)=>{if(!safeArrayIsArray$1(value3))throw new Error("Not supported entry type");return[value3,value3.length]})}function arrayToSetMapper(data){return new Set(data)}function arrayToSetUnmapper(value3){if(typeof value3!=="object"||value3===null)throw new Error("Incompatible instance received: should be a non-null object");if(!("constructor"in value3)||value3.constructor!==Set)throw new Error("Incompatible instance received: should be of exact type Set");return Array.from(value3)}function set3(arb,constraints={}){return uniqueArray(arb,{minLength:constraints.minLength,maxLength:constraints.maxLength,size:constraints.size,depthIdentifier:constraints.depthIdentifier,comparator:"SameValueZero"}).map(arrayToSetMapper,arrayToSetUnmapper)}function dictOf(ka,va,maxKeys,size6,depthIdentifier,withNullPrototype){return dictionary(ka,va,{maxKeys,noNullPrototype:!withNullPrototype,size:size6,depthIdentifier})}function typedArray(constraints){return oneof(int8Array(constraints),uint8Array(constraints),uint8ClampedArray(constraints),int16Array(constraints),uint16Array(constraints),int32Array(constraints),uint32Array(constraints),float32Array(constraints),float64Array(constraints))}function anyArbitraryBuilder(constraints){const arbitrariesForBase=constraints.values;const depthSize=constraints.depthSize;const depthIdentifier=createDepthIdentifier();const maxDepth=constraints.maxDepth;const maxKeys=constraints.maxKeys;const size6=constraints.size;const baseArb=oneof(...arbitrariesForBase,...constraints.withBigInt?[bigInt2()]:[],...constraints.withDate?[date()]:[]);return letrec((tie)=>({anything:oneof({maxDepth,depthSize,depthIdentifier},baseArb,tie("array"),tie("object"),...constraints.withMap?[tie("map")]:[],...constraints.withSet?[tie("set")]:[],...constraints.withObjectString?[tie("anything").map((o)=>stringify(o))]:[],...constraints.withTypedArray?[typedArray({maxLength:maxKeys,size:size6})]:[],...constraints.withSparseArray?[sparseArray(tie("anything"),{maxNumElements:maxKeys,size:size6,depthIdentifier})]:[]),keys:constraints.withObjectString?oneof({arbitrary:constraints.key,weight:10},{arbitrary:tie("anything").map((o)=>stringify(o)),weight:1}):constraints.key,array:array3(tie("anything"),{maxLength:maxKeys,size:size6,depthIdentifier}),set:set3(tie("anything"),{maxLength:maxKeys,size:size6,depthIdentifier}),map:oneof(map13(tie("keys"),tie("anything"),{maxKeys,size:size6,depthIdentifier}),map13(tie("anything"),tie("anything"),{maxKeys,size:size6,depthIdentifier})),object:dictOf(tie("keys"),tie("anything"),maxKeys,size6,depthIdentifier,constraints.withNullPrototype)})).anything}function unboxedToBoxedMapper(value3){switch(typeof value3){case"boolean":return new SBoolean(value3);case"number":return new SNumber(value3);case"string":return new SString(value3);default:return value3}}function unboxedToBoxedUnmapper(value3){if(typeof value3!=="object"||value3===null||!("constructor"in value3))return value3;return value3.constructor===SBoolean||value3.constructor===SNumber||value3.constructor===SString?value3.valueOf():value3}function boxedArbitraryBuilder(arb){return arb.map(unboxedToBoxedMapper,unboxedToBoxedUnmapper)}function defaultValues(constraints,stringArbitrary){return[boolean2(),maxSafeInteger(),double(),stringArbitrary(constraints),oneof(stringArbitrary(constraints),constant2(null),constant2(undefined))]}function boxArbitraries(arbs){return arbs.map((arb)=>boxedArbitraryBuilder(arb))}function boxArbitrariesIfNeeded(arbs,boxEnabled){return boxEnabled?boxArbitraries(arbs).concat(arbs):arbs}function toQualifiedObjectConstraints(settings={}){const valueConstraints={size:settings.size,unit:"stringUnit"in settings?settings.stringUnit:settings.withUnicodeString?"binary":undefined};return{key:settings.key!==undefined?settings.key:string3(valueConstraints),values:boxArbitrariesIfNeeded(settings.values!==undefined?settings.values:defaultValues(valueConstraints,string3),settings.withBoxedValues===true),depthSize:settings.depthSize,maxDepth:settings.maxDepth,maxKeys:settings.maxKeys,size:settings.size,withSet:settings.withSet===true,withMap:settings.withMap===true,withObjectString:settings.withObjectString===true,withNullPrototype:settings.withNullPrototype===true,withBigInt:settings.withBigInt===true,withDate:settings.withDate===true,withTypedArray:settings.withTypedArray===true,withSparseArray:settings.withSparseArray===true}}function objectInternal(constraints){return dictionary(constraints.key,anyArbitraryBuilder(constraints),{maxKeys:constraints.maxKeys,noNullPrototype:!constraints.withNullPrototype,size:constraints.size})}function object(constraints){return objectInternal(toQualifiedObjectConstraints(constraints))}function jsonConstraintsBuilder(stringArbitrary,constraints){const{depthSize,maxDepth}=constraints;return{key:stringArbitrary,values:[boolean2(),double({noDefaultInfinity:true,noNaN:true}),stringArbitrary,constant2(null)],depthSize,maxDepth}}function anything(constraints){return anyArbitraryBuilder(toQualifiedObjectConstraints(constraints))}function jsonValue(constraints={}){const noUnicodeString=constraints.noUnicodeString===undefined||constraints.noUnicodeString===true;return anything(jsonConstraintsBuilder("stringUnit"in constraints?string3({unit:constraints.stringUnit}):noUnicodeString?string3():string3({unit:"binary"}),constraints))}var safeJsonStringify=JSON.stringify;var safeJsonParse=JSON.parse;function jsonStringUnmapper(value3){if(typeof value3!=="string")throw new SError("Cannot unmap the passed value");return safeJsonParse(value3)}function json(constraints={}){return jsonValue(constraints).map(safeJsonStringify,jsonStringUnmapper)}var safeObjectDefineProperties=Object.defineProperties;function prettyPrint(numSeen,seenValuesStrings){return`Stream(${seenValuesStrings!==undefined?`${safeJoin(seenValuesStrings,",")}…`:`${numSeen} emitted`})`}var StreamArbitrary=class extends Arbitrary{constructor(arb,history){super();this.arb=arb;this.history=history}generate(mrng,biasFactor){const appliedBiasFactor=biasFactor!==undefined&&mrng.nextInt(1,biasFactor)===1?biasFactor:undefined;const enrichedProducer=()=>{const seenValues=this.history?[]:null;let numSeenValues=0;const g=function*(arb,clonedMrng){while(true){const value3=arb.generate(clonedMrng,appliedBiasFactor).value;numSeenValues++;if(seenValues!==null)safePush(seenValues,value3);yield value3}};const s=new Stream(g(this.arb,mrng.clone()));return safeObjectDefineProperties(s,{toString:{value:()=>prettyPrint(numSeenValues,seenValues!==null?seenValues.map(stringify):undefined)},[toStringMethod]:{value:()=>prettyPrint(numSeenValues,seenValues!==null?seenValues.map(stringify):undefined)},[asyncToStringMethod]:{value:async()=>prettyPrint(numSeenValues,seenValues!==null?await Promise.all(seenValues.map(asyncStringify)):undefined)},[cloneMethod]:{value:enrichedProducer,enumerable:true}})};return new Value(enrichedProducer(),undefined)}canShrinkWithoutContext(_value){return false}shrink(_value,_context){return Stream.nil()}};function infiniteStream(arb,constraints){return new StreamArbitrary(arb,constraints!==undefined&&typeof constraints==="object"&&"noHistory"in constraints?!constraints.noHistory:true)}function codePointsToStringMapper(tab){return safeJoin(tab,"")}function codePointsToStringUnmapper(value3){if(typeof value3!=="string")throw new Error("Cannot unmap the passed value");return[...value3]}function stringToBase64Mapper(s){switch(s.length%4){case 0:return s;case 3:return`${s}=`;case 2:return`${s}==`;default:return safeSubstring(s,1)}}function stringToBase64Unmapper(value3){if(typeof value3!=="string"||value3.length%4!==0)throw new Error("Invalid string received");const lastTrailingIndex=value3.indexOf("=");if(lastTrailingIndex===-1)return value3;if(value3.length-lastTrailingIndex>2)throw new Error("Cannot unmap the passed value");return safeSubstring(value3,0,lastTrailingIndex)}var safeStringFromCharCode=String.fromCharCode;function base64Mapper(v){if(v<26)return safeStringFromCharCode(v+65);if(v<52)return safeStringFromCharCode(v+97-26);if(v<62)return safeStringFromCharCode(v+48-52);return v===62?"+":"/"}function base64Unmapper(s){if(typeof s!=="string"||s.length!==1)throw new SError("Invalid entry");const v=safeCharCodeAt(s,0);if(v>=65&&v<=90)return v-65;if(v>=97&&v<=122)return v-97+26;if(v>=48&&v<=57)return v-48+52;return v===43?62:v===47?63:-1}function base64(){return integer({min:0,max:63}).map(base64Mapper,base64Unmapper)}function base64String(constraints={}){const{minLength:unscaledMinLength=0,maxLength:unscaledMaxLength=MaxLengthUpperBound,size:size6}=constraints;const minLength=unscaledMinLength+3-(unscaledMinLength+3)%4;const maxLength=unscaledMaxLength-unscaledMaxLength%4;const requestedSize=constraints.maxLength===undefined&&size6===undefined?"=":size6;if(minLength>maxLength)throw new SError("Minimal length should be inferior or equal to maximal length");if(minLength%4!==0)throw new SError("Minimal length of base64 strings must be a multiple of 4");if(maxLength%4!==0)throw new SError("Maximal length of base64 strings must be a multiple of 4");const charArbitrary=base64();return array3(charArbitrary,{minLength,maxLength,size:requestedSize,experimentalCustomSlices:createSlicesForStringLegacy(charArbitrary,codePointsToStringUnmapper)}).map(codePointsToStringMapper,codePointsToStringUnmapper).map(stringToBase64Mapper,stringToBase64Unmapper)}var safeObjectIs=Object.is;function isSubarrayOf(source,small){const countMap=new SMap$1;let countMinusZero=0;for(const sourceEntry of source)if(safeObjectIs(sourceEntry,-0))++countMinusZero;else safeMapSet(countMap,sourceEntry,(safeMapGet(countMap,sourceEntry)||0)+1);for(let index2=0;index2!==small.length;++index2){if(!(index2 in small))return false;const smallEntry=small[index2];if(safeObjectIs(smallEntry,-0)){if(countMinusZero===0)return false;--countMinusZero}else{const oldCount=safeMapGet(countMap,smallEntry)||0;if(oldCount===0)return false;safeMapSet(countMap,smallEntry,oldCount-1)}}return true}var safeMathFloor$1=Math.floor;var safeMathLog=Math.log;var safeArrayIsArray=Array.isArray;var SubarrayArbitrary=class extends Arbitrary{constructor(originalArray,isOrdered,minLength,maxLength){super();this.originalArray=originalArray;this.isOrdered=isOrdered;this.minLength=minLength;this.maxLength=maxLength;if(minLength<0||minLength>originalArray.length)throw new Error("fc.*{s|S}ubarrayOf expects the minimal length to be between 0 and the size of the original array");if(maxLength<0||maxLength>originalArray.length)throw new Error("fc.*{s|S}ubarrayOf expects the maximal length to be between 0 and the size of the original array");if(minLength>maxLength)throw new Error("fc.*{s|S}ubarrayOf expects the minimal length to be inferior or equal to the maximal length");this.lengthArb=new IntegerArbitrary(minLength,maxLength);this.biasedLengthArb=minLength!==maxLength?new IntegerArbitrary(minLength,minLength+safeMathFloor$1(safeMathLog(maxLength-minLength)/safeMathLog(2))):this.lengthArb}generate(mrng,biasFactor){const size6=(biasFactor!==undefined&&mrng.nextInt(1,biasFactor)===1?this.biasedLengthArb:this.lengthArb).generate(mrng,undefined);const sizeValue=size6.value;const remainingElements=safeMap(this.originalArray,(_v,idx)=>idx);const ids=[];for(let index2=0;index2!==sizeValue;++index2){const selectedIdIndex=mrng.nextInt(0,remainingElements.length-1);safePush(ids,remainingElements[selectedIdIndex]);safeSplice(remainingElements,selectedIdIndex,1)}if(this.isOrdered)safeSort(ids,(a,b)=>a-b);return new Value(safeMap(ids,(i)=>this.originalArray[i]),size6.context)}canShrinkWithoutContext(value3){if(!safeArrayIsArray(value3))return false;if(!this.lengthArb.canShrinkWithoutContext(value3.length))return false;return isSubarrayOf(this.originalArray,value3)}shrink(value3,context4){if(value3.length===0)return Stream.nil();return this.lengthArb.shrink(value3.length,context4).map((newSize)=>{return new Value(safeSlice(value3,value3.length-newSize.value),newSize.context)}).join(value3.length>this.minLength?makeLazy2(()=>this.shrink(safeSlice(value3,1),undefined).filter((newValue)=>this.minLength<=newValue.value.length+1).map((newValue)=>new Value([value3[0],...newValue.value],undefined))):Stream.nil())}};function subarray(originalArray,constraints={}){const{minLength=0,maxLength=originalArray.length}=constraints;return new SubarrayArbitrary(originalArray,true,minLength,maxLength)}function shuffledSubarray(originalArray,constraints={}){const{minLength=0,maxLength=originalArray.length}=constraints;return new SubarrayArbitrary(originalArray,false,minLength,maxLength)}var encodeSymbolLookupTable={10:"A",11:"B",12:"C",13:"D",14:"E",15:"F",16:"G",17:"H",18:"J",19:"K",20:"M",21:"N",22:"P",23:"Q",24:"R",25:"S",26:"T",27:"V",28:"W",29:"X",30:"Y",31:"Z"};var decodeSymbolLookupTable={"0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,A:10,B:11,C:12,D:13,E:14,F:15,G:16,H:17,J:18,K:19,M:20,N:21,P:22,Q:23,R:24,S:25,T:26,V:27,W:28,X:29,Y:30,Z:31};function encodeSymbol(symbol4){return symbol4<10?SString(symbol4):encodeSymbolLookupTable[symbol4]}function pad(value3,paddingLength){let extraPadding="";while(value3.length+extraPadding.length<paddingLength)extraPadding+="0";return extraPadding+value3}function smallUintToBase32StringMapper(num){let base32Str="";for(let remaining=num;remaining!==0;){const next=remaining>>5;base32Str=encodeSymbol(remaining-(next<<5))+base32Str;remaining=next}return base32Str}function uintToBase32StringMapper(num,paddingLength){const head=~~(num/1073741824);const tail=num&1073741823;return pad(smallUintToBase32StringMapper(head),paddingLength-6)+pad(smallUintToBase32StringMapper(tail),6)}function paddedUintToBase32StringMapper(paddingLength){return function padded(num){return uintToBase32StringMapper(num,paddingLength)}}function uintToBase32StringUnmapper(value3){if(typeof value3!=="string")throw new SError("Unsupported type");let accumulated=0;let power=1;for(let index2=value3.length-1;index2>=0;--index2){const char=value3[index2];const numericForChar=decodeSymbolLookupTable[char];if(numericForChar===undefined)throw new SError("Unsupported type");accumulated+=numericForChar*power;power*=32}return accumulated}var padded10Mapper=paddedUintToBase32StringMapper(10);var padded8Mapper=paddedUintToBase32StringMapper(8);function ulidMapper(parts){return padded10Mapper(parts[0])+padded8Mapper(parts[1])+padded8Mapper(parts[2])}function ulidUnmapper(value3){if(typeof value3!=="string"||value3.length!==26)throw new Error("Unsupported type");return[uintToBase32StringUnmapper(value3.slice(0,10)),uintToBase32StringUnmapper(value3.slice(10,18)),uintToBase32StringUnmapper(value3.slice(18))]}function ulid(){return tuple2(integer({min:0,max:281474976710655}),integer({min:0,max:1099511627775}),integer({min:0,max:1099511627775})).map(ulidMapper,ulidUnmapper)}function numberToPaddedEightMapper(n){return safePadStart(safeNumberToString(n,16),8,"0")}function numberToPaddedEightUnmapper(value3){if(typeof value3!=="string")throw new Error("Unsupported type");if(value3.length!==8)throw new Error("Unsupported value: invalid length");const n=parseInt(value3,16);if(value3!==numberToPaddedEightMapper(n))throw new Error("Unsupported value: invalid content");return n}function buildPaddedNumberArbitrary(min5,max5){return integer({min:min5,max:max5}).map(numberToPaddedEightMapper,numberToPaddedEightUnmapper)}function paddedEightsToUuidMapper(t){return`${t[0]}-${safeSubstring(t[1],4)}-${safeSubstring(t[1],0,4)}-${safeSubstring(t[2],0,4)}-${safeSubstring(t[2],4)}${t[3]}`}var UuidRegex=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/;function paddedEightsToUuidUnmapper(value3){if(typeof value3!=="string")throw new Error("Unsupported type");const m=UuidRegex.exec(value3);if(m===null)throw new Error("Unsupported type");return[m[1],m[3]+m[2],m[4]+safeSubstring(m[5],0,4),safeSubstring(m[5],4)]}var quickNumberToHexaString="0123456789abcdef";function buildVersionsAppliersForUuid(versions){const mapping={};const reversedMapping={};for(let index2=0;index2!==versions.length;++index2){const from=quickNumberToHexaString[index2];const to=quickNumberToHexaString[versions[index2]];mapping[from]=to;reversedMapping[to]=from}function versionsApplierMapper(value3){return mapping[value3[0]]+safeSubstring(value3,1)}function versionsApplierUnmapper(value3){if(typeof value3!=="string")throw new SError("Cannot produce non-string values");const rev=reversedMapping[value3[0]];if(rev===undefined)throw new SError("Cannot produce strings not starting by the version in hexa code");return rev+safeSubstring(value3,1)}return{versionsApplierMapper,versionsApplierUnmapper}}function assertValidVersions(versions){const found={};for(const version2 of versions){if(found[version2])throw new SError(`Version ${version2} has been requested at least twice for uuid`);found[version2]=true;if(version2<1||version2>15)throw new SError(`Version must be a value in [1-15] for uuid, but received ${version2}`);if(~~version2!==version2)throw new SError(`Version must be an integer value for uuid, but received ${version2}`)}if(versions.length===0)throw new SError(`Must provide at least one version for uuid`)}function uuid(constraints={}){const padded=buildPaddedNumberArbitrary(0,4294967295);const version2=constraints.version!==undefined?typeof constraints.version==="number"?[constraints.version]:constraints.version:[1,2,3,4,5,6,7,8];assertValidVersions(version2);const{versionsApplierMapper,versionsApplierUnmapper}=buildVersionsAppliersForUuid(version2);return tuple2(padded,buildPaddedNumberArbitrary(0,268435456*version2.length-1).map(versionsApplierMapper,versionsApplierUnmapper),buildPaddedNumberArbitrary(2147483648,3221225471),padded).map(paddedEightsToUuidMapper,paddedEightsToUuidUnmapper)}function hostUserInfo(size6){return string3({unit:getOrCreateAlphaNumericPercentArbitrary("-._~!$&'()*+,;=:"),size:size6})}function userHostPortMapper([u,h2,p]){return(u===null?"":`${u}@`)+h2+(p===null?"":`:${p}`)}function userHostPortUnmapper(value3){if(typeof value3!=="string")throw new Error("Unsupported");const atPosition=value3.indexOf("@");const user=atPosition!==-1?value3.substring(0,atPosition):null;const m=/:(\d+)$/.exec(value3);const port=m!==null?Number(m[1]):null;return[user,m!==null?value3.substring(atPosition+1,value3.length-m[1].length-1):value3.substring(atPosition+1),port]}function bracketedMapper(s){return`[${s}]`}function bracketedUnmapper(value3){if(typeof value3!=="string"||value3[0]!=="["||value3[value3.length-1]!=="]")throw new Error("Unsupported");return value3.substring(1,value3.length-1)}function webAuthority(constraints){const c=constraints||{};const size6=c.size;const hostnameArbs=[domain({size:size6}),...c.withIPv4===true?[ipV4()]:[],...c.withIPv6===true?[ipV6().map(bracketedMapper,bracketedUnmapper)]:[],...c.withIPv4Extended===true?[ipV4Extended()]:[]];return tuple2(c.withUserInfo===true?option3(hostUserInfo(size6)):constant2(null),oneof(...hostnameArbs),c.withPort===true?option3(nat(65535)):constant2(null)).map(userHostPortMapper,userHostPortUnmapper)}function buildUriQueryOrFragmentArbitrary(size6){return string3({unit:getOrCreateAlphaNumericPercentArbitrary("-._~!$&'()*+,;=:@/?"),size:size6})}function webFragments(constraints={}){return buildUriQueryOrFragmentArbitrary(constraints.size)}function webSegment(constraints={}){return string3({unit:getOrCreateAlphaNumericPercentArbitrary("-._~!$&'()*+,;=:@"),size:constraints.size})}function segmentsToPathMapper(segments){let path="";for(let index2=0;index2!==segments.length;++index2)path+="/"+segments[index2];return path}function segmentsToPathUnmapper(value3){if(typeof value3!=="string")throw new Error("Incompatible value received: type");if(value3.length!==0&&value3[0]!=="/")throw new Error("Incompatible value received: start");return safeSplice(safeSplit(value3,"/"),1)}function sqrtSize(size6){switch(size6){case"xsmall":return["xsmall","xsmall"];case"small":return["small","xsmall"];case"medium":return["small","small"];case"large":return["medium","small"];case"xlarge":return["medium","medium"]}}function buildUriPathArbitraryInternal(segmentSize,numSegmentSize){return array3(webSegment({size:segmentSize}),{size:numSegmentSize}).map(segmentsToPathMapper,segmentsToPathUnmapper)}function buildUriPathArbitrary(resolvedSize){const[segmentSize,numSegmentSize]=sqrtSize(resolvedSize);if(segmentSize===numSegmentSize)return buildUriPathArbitraryInternal(segmentSize,numSegmentSize);return oneof(buildUriPathArbitraryInternal(segmentSize,numSegmentSize),buildUriPathArbitraryInternal(numSegmentSize,segmentSize))}function webPath(constraints){return buildUriPathArbitrary(resolveSize((constraints||{}).size))}function webQueryParameters(constraints={}){return buildUriQueryOrFragmentArbitrary(constraints.size)}function partsToUrlMapper(data){const[scheme,authority,path]=data;return`${scheme}://${authority}${path}${data[3]===null?"":`?${data[3]}`}${data[4]===null?"":`#${data[4]}`}`}var UrlSplitRegex=/^([[A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)([^?#]*)(\?[A-Za-z0-9\-._~!$&'()*+,;=:@/?%]*)?(#[A-Za-z0-9\-._~!$&'()*+,;=:@/?%]*)?$/;function partsToUrlUnmapper(value3){if(typeof value3!=="string")throw new Error("Incompatible value received: type");const m=UrlSplitRegex.exec(value3);if(m===null)throw new Error("Incompatible value received");const scheme=m[1];const authority=m[2];const path=m[3];const query=m[4];const fragments=m[5];return[scheme,authority,path,query!==undefined?query.substring(1):null,fragments!==undefined?fragments.substring(1):null]}function webUrl(constraints){const c=constraints||{};const resolvedSize=resolveSize(c.size);const resolvedAuthoritySettingsSize=c.authoritySettings!==undefined&&c.authoritySettings.size!==undefined?relativeSizeToSize(c.authoritySettings.size,resolvedSize):resolvedSize;const resolvedAuthoritySettings={...c.authoritySettings,size:resolvedAuthoritySettingsSize};return tuple2(constantFrom(...c.validSchemes||["http","https"]),webAuthority(resolvedAuthoritySettings),webPath({size:resolvedSize}),c.withQueryParameters===true?option3(webQueryParameters({size:resolvedSize})):constant2(null),c.withFragments===true?option3(webFragments({size:resolvedSize})):constant2(null)).map(partsToUrlMapper,partsToUrlUnmapper)}var CommandsIterable=class CommandsIterable2{constructor(commands,metadataForReplay){this.commands=commands;this.metadataForReplay=metadataForReplay;this[cloneMethod]=function(){return new CommandsIterable2(this.commands.map((c)=>c.clone()),this.metadataForReplay)}}[Symbol.iterator](){return this.commands[Symbol.iterator]()}toString(){const serializedCommands=this.commands.filter((c)=>c.hasRan).map((c)=>c.toString()).join(",");const metadata=this.metadataForReplay();return metadata.length!==0?`${serializedCommands} /*${metadata}*/`:serializedCommands}};var CommandWrapper=class CommandWrapper2{constructor(cmd){this.cmd=cmd;this.hasRan=false;if(hasToStringMethod(cmd)){const method=cmd[toStringMethod];this[toStringMethod]=function toStringMethod(){return method.call(cmd)}}if(hasAsyncToStringMethod(cmd)){const method=cmd[asyncToStringMethod];this[asyncToStringMethod]=function asyncToStringMethod(){return method.call(cmd)}}}check(m){return this.cmd.check(m)}run(m,r){this.hasRan=true;return this.cmd.run(m,r)}clone(){if(hasCloneMethod(this.cmd))return new CommandWrapper2(this.cmd[cloneMethod]());return new CommandWrapper2(this.cmd)}toString(){return this.cmd.toString()}};var ReplayPath=class{static parse(replayPathStr){const[serializedCount,serializedChanges]=replayPathStr.split(":");const counts=this.parseCounts(serializedCount);const changes=this.parseChanges(serializedChanges);return this.parseOccurences(counts,changes)}static stringify(replayPath){const occurences=this.countOccurences(replayPath);return`${this.stringifyCounts(occurences)}:${this.stringifyChanges(occurences)}`}static intToB64(n){if(n<26)return String.fromCharCode(n+65);if(n<52)return String.fromCharCode(n+97-26);if(n<62)return String.fromCharCode(n+48-52);return String.fromCharCode(n===62?43:47)}static b64ToInt(c){if(c>="a")return c.charCodeAt(0)-97+26;if(c>="A")return c.charCodeAt(0)-65;if(c>="0")return c.charCodeAt(0)-48+52;return c==="+"?62:63}static countOccurences(replayPath){return replayPath.reduce((counts,cur)=>{if(counts.length===0||counts[counts.length-1].count===64||counts[counts.length-1].value!==cur)counts.push({value:cur,count:1});else counts[counts.length-1].count+=1;return counts},[])}static parseOccurences(counts,changes){const replayPath=[];for(let idx=0;idx!==counts.length;++idx){const count=counts[idx];const value3=changes[idx];for(let num=0;num!==count;++num)replayPath.push(value3)}return replayPath}static stringifyChanges(occurences){let serializedChanges="";for(let idx=0;idx<occurences.length;idx+=6){const changesInt=occurences.slice(idx,idx+6).reduceRight((prev,cur)=>(prev<<1)+(cur.value?1:0),0);serializedChanges+=this.intToB64(changesInt)}return serializedChanges}static parseChanges(serializedChanges){const changesInt=serializedChanges.split("").map((c)=>this.b64ToInt(c));const changes=[];for(let idx=0;idx!==changesInt.length;++idx){let current=changesInt[idx];for(let n=0;n!==6;++n,current>>=1)changes.push(current%2===1)}return changes}static stringifyCounts(occurences){return occurences.map(({count})=>this.intToB64(count-1)).join("")}static parseCounts(serializedCount){return serializedCount.split("").map((c)=>this.b64ToInt(c)+1)}};var CommandsArbitrary=class extends Arbitrary{constructor(commandArbs,maxGeneratedCommands,maxCommands,sourceReplayPath,disableReplayLog){super();this.sourceReplayPath=sourceReplayPath;this.disableReplayLog=disableReplayLog;this.oneCommandArb=oneof(...commandArbs).map((c)=>new CommandWrapper(c));this.lengthArb=restrictedIntegerArbitraryBuilder(0,maxGeneratedCommands,maxCommands);this.replayPath=[];this.replayPathPosition=0}metadataForReplay(){return this.disableReplayLog?"":`replayPath=${JSON.stringify(ReplayPath.stringify(this.replayPath))}`}buildValueFor(items2,shrunkOnce){const commands=items2.map((item)=>item.value_);const context4={shrunkOnce,items:items2};return new Value(new CommandsIterable(commands,()=>this.metadataForReplay()),context4)}generate(mrng){const sizeValue=this.lengthArb.generate(mrng,undefined).value;const items2=Array(sizeValue);for(let idx=0;idx!==sizeValue;++idx)items2[idx]=this.oneCommandArb.generate(mrng,undefined);this.replayPathPosition=0;return this.buildValueFor(items2,false)}canShrinkWithoutContext(_value){return false}filterOnExecution(itemsRaw){const items2=[];for(const c of itemsRaw)if(c.value_.hasRan){this.replayPath.push(true);items2.push(c)}else this.replayPath.push(false);return items2}filterOnReplay(itemsRaw){return itemsRaw.filter((c,idx)=>{const state=this.replayPath[this.replayPathPosition+idx];if(state===undefined)throw new Error(`Too short replayPath`);if(!state&&c.value_.hasRan)throw new Error(`Mismatch between replayPath and real execution`);return state})}filterForShrinkImpl(itemsRaw){if(this.replayPathPosition===0)this.replayPath=this.sourceReplayPath!==null?ReplayPath.parse(this.sourceReplayPath):[];const items2=this.replayPathPosition<this.replayPath.length?this.filterOnReplay(itemsRaw):this.filterOnExecution(itemsRaw);this.replayPathPosition+=itemsRaw.length;return items2}shrink(_value,context4){if(context4===undefined)return Stream.nil();const safeContext=context4;const shrunkOnce=safeContext.shrunkOnce;const itemsRaw=safeContext.items;const items2=this.filterForShrinkImpl(itemsRaw);if(items2.length===0)return Stream.nil();const rootShrink=shrunkOnce?Stream.nil():new Stream([[]][Symbol.iterator]());const nextShrinks=[];for(let numToKeep=0;numToKeep!==items2.length;++numToKeep)nextShrinks.push(makeLazy2(()=>{const fixedStart=items2.slice(0,numToKeep);return this.lengthArb.shrink(items2.length-1-numToKeep,undefined).map((l)=>fixedStart.concat(items2.slice(items2.length-(l.value+1))))}));for(let itemAt=0;itemAt!==items2.length;++itemAt)nextShrinks.push(makeLazy2(()=>this.oneCommandArb.shrink(items2[itemAt].value_,items2[itemAt].context).map((v)=>items2.slice(0,itemAt).concat([v],items2.slice(itemAt+1)))));return rootShrink.join(...nextShrinks).map((shrinkables)=>{return this.buildValueFor(shrinkables.map((c)=>new Value(c.value_.clone(),c.context)),true)})}};function commands(commandArbs,constraints={}){const{size:size6,maxCommands=MaxLengthUpperBound,disableReplayLog=false,replayPath=null}=constraints;return new CommandsArbitrary(commandArbs,maxGeneratedLengthFromSizeForArbitrary(size6,0,maxCommands,constraints.maxCommands!==undefined),maxCommands,replayPath,disableReplayLog)}var ScheduledCommand=class{constructor(s,cmd){this.s=s;this.cmd=cmd}async check(m){let error=null;let checkPassed=false;if((await this.s.scheduleSequence([{label:`check@${this.cmd.toString()}`,builder:async()=>{try{checkPassed=await Promise.resolve(this.cmd.check(m))}catch(err){error=err;throw err}}}]).task).faulty)throw error;return checkPassed}async run(m,r){let error=null;if((await this.s.scheduleSequence([{label:`run@${this.cmd.toString()}`,builder:async()=>{try{await this.cmd.run(m,r)}catch(err){error=err;throw err}}}]).task).faulty)throw error}};var scheduleCommands=function*(s,cmds){for(const cmd of cmds)yield new ScheduledCommand(s,cmd)};var genericModelRun=(s,cmds,initialValue,runCmd,then)=>{return s.then((o)=>{const{model,real}=o;let state=initialValue;for(const c of cmds)state=then(state,()=>{return runCmd(c,model,real)});return state})};var internalModelRun=(s,cmds)=>{const then=(_p,c)=>c();const setupProducer={then:(fun)=>{fun(s())}};const runSync3=(cmd,m,r)=>{if(cmd.check(m))cmd.run(m,r)};return genericModelRun(setupProducer,cmds,undefined,runSync3,then)};var isAsyncSetup=(s)=>{return typeof s.then==="function"};var internalAsyncModelRun=async(s,cmds,defaultPromise=Promise.resolve())=>{const then=(p,c)=>p.then(c);const setupProducer={then:(fun)=>{const out=s();if(isAsyncSetup(out))return out.then(fun);else return fun(out)}};const runAsync=async(cmd,m,r)=>{if(await cmd.check(m))await cmd.run(m,r)};return await genericModelRun(setupProducer,cmds,defaultPromise,runAsync,then)};function modelRun(s,cmds){internalModelRun(s,cmds)}async function asyncModelRun(s,cmds){await internalAsyncModelRun(s,cmds)}async function scheduledModelRun(scheduler,s,cmds){const scheduledCommands=scheduleCommands(scheduler,cmds);const out=internalAsyncModelRun(s,scheduledCommands,scheduler.schedule(Promise.resolve(),"startModel"));await scheduler.waitFor(out);await scheduler.waitAll()}var defaultSchedulerAct=(f)=>f();var SchedulerImplem=class SchedulerImplem2{constructor(act,taskSelector){this.act=act;this.taskSelector=taskSelector;this.lastTaskId=0;this.sourceTaskSelector=taskSelector.clone();this.scheduledTasks=[];this.triggeredTasks=[];this.scheduledWatchers=[];this[cloneMethod]=function(){return new SchedulerImplem2(this.act,this.sourceTaskSelector)}}static buildLog(reportItem){return`[task\${${reportItem.taskId}}] ${reportItem.label.length!==0?`${reportItem.schedulingType}::${reportItem.label}`:reportItem.schedulingType} ${reportItem.status}${reportItem.outputValue!==undefined?` with value ${escapeForTemplateString(reportItem.outputValue)}`:""}`}log(schedulingType,taskId,label,metadata,status,data){this.triggeredTasks.push({status,schedulingType,taskId,label,metadata,outputValue:data!==undefined?stringify(data):undefined})}scheduleInternal(schedulingType,label,task,metadata,customAct,thenTaskToBeAwaited){const taskId=++this.lastTaskId;let trigger=undefined;const scheduledPromise=new Promise((resolve4,reject)=>{trigger=()=>{const promise3=Promise.resolve(thenTaskToBeAwaited!==undefined?task.then(()=>thenTaskToBeAwaited()):task);promise3.then((data)=>{this.log(schedulingType,taskId,label,metadata,"resolved",data);resolve4(data)},(err)=>{this.log(schedulingType,taskId,label,metadata,"rejected",err);reject(err)});return promise3}});this.scheduledTasks.push({original:task,trigger,schedulingType,taskId,label,metadata,customAct});if(this.scheduledWatchers.length!==0)this.scheduledWatchers[0]();return scheduledPromise}schedule(task,label,metadata,customAct){return this.scheduleInternal("promise",label||"",task,metadata,customAct||defaultSchedulerAct)}scheduleFunction(asyncFunction,customAct){return(...args2)=>this.scheduleInternal("function",`${asyncFunction.name}(${args2.map(stringify).join(",")})`,asyncFunction(...args2),undefined,customAct||defaultSchedulerAct)}scheduleSequence(sequenceBuilders,customAct){const status={done:false,faulty:false};const dummyResolvedPromise={then:(f)=>f()};let resolveSequenceTask=()=>{};const sequenceTask=new Promise((resolve4)=>{resolveSequenceTask=()=>resolve4({done:status.done,faulty:status.faulty})});const onFaultyItemNoThrow=()=>{status.faulty=true;resolveSequenceTask()};const onDone=()=>{status.done=true;resolveSequenceTask()};const registerNextBuilder=(index2,previous)=>{if(index2>=sequenceBuilders.length){previous.then(onDone,onFaultyItemNoThrow);return}previous.then(()=>{const item=sequenceBuilders[index2];const[builder,label,metadata]=typeof item==="function"?[item,item.name,undefined]:[item.builder,item.label,item.metadata];const scheduled=this.scheduleInternal("sequence",label,dummyResolvedPromise,metadata,customAct||defaultSchedulerAct,()=>builder());registerNextBuilder(index2+1,scheduled)},onFaultyItemNoThrow)};registerNextBuilder(0,dummyResolvedPromise);return Object.assign(status,{task:sequenceTask})}count(){return this.scheduledTasks.length}internalWaitOne(){if(this.scheduledTasks.length===0)throw new Error("No task scheduled");const taskIndex=this.taskSelector.nextTaskIndex(this.scheduledTasks);const[scheduledTask]=this.scheduledTasks.splice(taskIndex,1);return scheduledTask.customAct(()=>{return scheduledTask.trigger().catch((_err)=>{})})}waitOne(customAct){const waitAct=customAct||defaultSchedulerAct;return this.act(()=>waitAct(()=>this.internalWaitOne()))}async waitAll(customAct){while(this.scheduledTasks.length>0)await this.waitOne(customAct)}async internalWaitFor(unscheduledTask,options){let taskResolved=false;const customAct=options.customAct;const onWaitStart=options.onWaitStart;const onWaitIdle=options.onWaitIdle;const launchAwaiterOnInit=options.launchAwaiterOnInit;let resolveFinal=undefined;let rejectFinal=undefined;let awaiterTicks=0;let awaiterPromise=null;let awaiterScheduledTaskPromise=null;const awaiter=async()=>{awaiterTicks=50;for(awaiterTicks=50;!taskResolved&&awaiterTicks>0;--awaiterTicks)await Promise.resolve();if(!taskResolved&&this.scheduledTasks.length>0){if(onWaitStart!==undefined)onWaitStart();awaiterScheduledTaskPromise=this.waitOne(customAct);return awaiterScheduledTaskPromise.then(()=>{awaiterScheduledTaskPromise=null;return awaiter()},(err)=>{awaiterScheduledTaskPromise=null;taskResolved=true;rejectFinal(err);throw err})}if(!taskResolved&&onWaitIdle!==undefined)onWaitIdle();awaiterPromise=null};const handleNotified=()=>{if(awaiterPromise!==null){awaiterTicks=51;return}awaiterPromise=awaiter().catch(()=>{})};const clearAndReplaceWatcher=()=>{const handleNotifiedIndex=this.scheduledWatchers.indexOf(handleNotified);if(handleNotifiedIndex!==-1)this.scheduledWatchers.splice(handleNotifiedIndex,1);if(handleNotifiedIndex===0&&this.scheduledWatchers.length!==0)this.scheduledWatchers[0]()};const finalTask=new Promise((resolve4,reject)=>{resolveFinal=(value3)=>{clearAndReplaceWatcher();resolve4(value3)};rejectFinal=(error)=>{clearAndReplaceWatcher();reject(error)}});unscheduledTask.then((ret)=>{taskResolved=true;if(awaiterScheduledTaskPromise===null)resolveFinal(ret);else awaiterScheduledTaskPromise.then(()=>resolveFinal(ret),(error)=>rejectFinal(error))},(err)=>{taskResolved=true;if(awaiterScheduledTaskPromise===null)rejectFinal(err);else awaiterScheduledTaskPromise.then(()=>rejectFinal(err),()=>rejectFinal(err))});if((this.scheduledTasks.length>0||launchAwaiterOnInit)&&this.scheduledWatchers.length===0)handleNotified();this.scheduledWatchers.push(handleNotified);return finalTask}waitNext(count,customAct){let resolver=undefined;let remaining=count;const awaited=remaining<=0?Promise.resolve():new Promise((r)=>{resolver=()=>{if(--remaining<=0)r()}});return this.internalWaitFor(awaited,{customAct,onWaitStart:resolver,onWaitIdle:undefined,launchAwaiterOnInit:false})}waitIdle(customAct){let resolver=undefined;const awaited=new Promise((r)=>resolver=r);return this.internalWaitFor(awaited,{customAct,onWaitStart:undefined,onWaitIdle:resolver,launchAwaiterOnInit:true})}waitFor(unscheduledTask,customAct){return this.internalWaitFor(unscheduledTask,{customAct,onWaitStart:undefined,onWaitIdle:undefined,launchAwaiterOnInit:false})}report(){return[...this.triggeredTasks,...this.scheduledTasks.map((t)=>({status:"pending",schedulingType:t.schedulingType,taskId:t.taskId,label:t.label,metadata:t.metadata}))]}toString(){return"schedulerFor()`\n"+this.report().map(SchedulerImplem2.buildLog).map((log2)=>`-> ${log2}`).join(`
|
|
221
|
+
}`}return safeObjectDefineProperties$1(f,{toString:{value:()=>prettyPrint(stringify(outs))},[toStringMethod]:{value:()=>prettyPrint(stringify(outs))},[asyncToStringMethod]:{value:async()=>prettyPrint(await asyncStringify(outs))},[cloneMethod]:{value:producer,configurable:true}})};return producer()})}var safeMinSafeInteger=Number.MIN_SAFE_INTEGER;var safeMaxSafeInteger$1=Number.MAX_SAFE_INTEGER;function maxSafeInteger(){return new IntegerArbitrary(safeMinSafeInteger,safeMaxSafeInteger$1)}var safeMaxSafeInteger=Number.MAX_SAFE_INTEGER;function maxSafeNat(){return new IntegerArbitrary(0,safeMaxSafeInteger)}var safeNumberParseInt=Number.parseInt;function natToStringifiedNatMapper(options){const[style,v]=options;switch(style){case"oct":return`0${safeNumberToString(v,8)}`;case"hex":return`0x${safeNumberToString(v,16)}`;default:return`${v}`}}function tryParseStringifiedNat(stringValue,radix){const parsedNat=safeNumberParseInt(stringValue,radix);if(safeNumberToString(parsedNat,radix)!==stringValue)throw new Error("Invalid value");return parsedNat}function natToStringifiedNatUnmapper(value3){if(typeof value3!=="string")throw new Error("Invalid type");if(value3.length>=2&&value3[0]==="0"){if(value3[1]==="x")return["hex",tryParseStringifiedNat(safeSubstring(value3,2),16)];return["oct",tryParseStringifiedNat(safeSubstring(value3,1),8)]}return["dec",tryParseStringifiedNat(value3,10)]}function dotJoinerMapper$1(data){return safeJoin(data,".")}function dotJoinerUnmapper$1(value3){if(typeof value3!=="string")throw new Error("Invalid type");return safeMap(safeSplit(value3,"."),(v)=>tryParseStringifiedNat(v,10))}function ipV4(){return tuple2(nat(255),nat(255),nat(255),nat(255)).map(dotJoinerMapper$1,dotJoinerUnmapper$1)}function buildStringifiedNatArbitrary(maxValue){return tuple2(constantFrom("dec","oct","hex"),nat(maxValue)).map(natToStringifiedNatMapper,natToStringifiedNatUnmapper)}function dotJoinerMapper(data){return safeJoin(data,".")}function dotJoinerUnmapper(value3){if(typeof value3!=="string")throw new Error("Invalid type");return safeSplit(value3,".")}function ipV4Extended(){return oneof(tuple2(buildStringifiedNatArbitrary(255),buildStringifiedNatArbitrary(255),buildStringifiedNatArbitrary(255),buildStringifiedNatArbitrary(255)).map(dotJoinerMapper,dotJoinerUnmapper),tuple2(buildStringifiedNatArbitrary(255),buildStringifiedNatArbitrary(255),buildStringifiedNatArbitrary(65535)).map(dotJoinerMapper,dotJoinerUnmapper),tuple2(buildStringifiedNatArbitrary(255),buildStringifiedNatArbitrary(16777215)).map(dotJoinerMapper,dotJoinerUnmapper),buildStringifiedNatArbitrary(4294967295))}function readBh(value3){if(value3.length===0)return[];else return safeSplit(value3,":")}function extractEhAndL(value3){const valueSplits=safeSplit(value3,":");if(valueSplits.length>=2&&valueSplits[valueSplits.length-1].length<=4)return[safeSlice(valueSplits,0,valueSplits.length-2),`${valueSplits[valueSplits.length-2]}:${valueSplits[valueSplits.length-1]}`];return[safeSlice(valueSplits,0,valueSplits.length-1),valueSplits[valueSplits.length-1]]}function fullySpecifiedMapper(data){return`${safeJoin(data[0],":")}:${data[1]}`}function fullySpecifiedUnmapper(value3){if(typeof value3!=="string")throw new Error("Invalid type");return extractEhAndL(value3)}function onlyTrailingMapper(data){return`::${safeJoin(data[0],":")}:${data[1]}`}function onlyTrailingUnmapper(value3){if(typeof value3!=="string")throw new Error("Invalid type");if(!safeStartsWith(value3,"::"))throw new Error("Invalid value");return extractEhAndL(safeSubstring(value3,2))}function multiTrailingMapper(data){return`${safeJoin(data[0],":")}::${safeJoin(data[1],":")}:${data[2]}`}function multiTrailingUnmapper(value3){if(typeof value3!=="string")throw new Error("Invalid type");const[bhString,trailingString]=safeSplit(value3,"::",2);const[eh,l]=extractEhAndL(trailingString);return[readBh(bhString),eh,l]}function multiTrailingMapperOne(data){return multiTrailingMapper([data[0],[data[1]],data[2]])}function multiTrailingUnmapperOne(value3){const out=multiTrailingUnmapper(value3);return[out[0],safeJoin(out[1],":"),out[2]]}function singleTrailingMapper(data){return`${safeJoin(data[0],":")}::${data[1]}`}function singleTrailingUnmapper(value3){if(typeof value3!=="string")throw new Error("Invalid type");const[bhString,trailing]=safeSplit(value3,"::",2);return[readBh(bhString),trailing]}function noTrailingMapper(data){return`${safeJoin(data[0],":")}::`}function noTrailingUnmapper(value3){if(typeof value3!=="string")throw new Error("Invalid type");if(!safeEndsWith(value3,"::"))throw new Error("Invalid value");return[readBh(safeSubstring(value3,0,value3.length-2))]}function h16sTol32Mapper([a,b]){return`${a}:${b}`}function h16sTol32Unmapper(value3){if(typeof value3!=="string")throw new SError("Invalid type");if(!value3.includes(":"))throw new SError("Invalid value");return value3.split(":",2)}var items="0123456789abcdef";var cachedHexa=undefined;function hexa(){if(cachedHexa===undefined)cachedHexa=integer({min:0,max:15}).map((n)=>items[n],(c)=>{if(typeof c!=="string")throw new SError("Not a string");if(c.length!==1)throw new SError("Invalid length");const code=safeCharCodeAt(c,0);if(code<=57)return code-48;if(code<97)throw new SError("Invalid character");return code-87});return cachedHexa}function ipV6(){const h16Arb=string3({unit:hexa(),minLength:1,maxLength:4,size:"max"});const ls32Arb=oneof(tuple2(h16Arb,h16Arb).map(h16sTol32Mapper,h16sTol32Unmapper),ipV4());return oneof(tuple2(array3(h16Arb,{minLength:6,maxLength:6,size:"max"}),ls32Arb).map(fullySpecifiedMapper,fullySpecifiedUnmapper),tuple2(array3(h16Arb,{minLength:5,maxLength:5,size:"max"}),ls32Arb).map(onlyTrailingMapper,onlyTrailingUnmapper),tuple2(array3(h16Arb,{minLength:0,maxLength:1,size:"max"}),array3(h16Arb,{minLength:4,maxLength:4,size:"max"}),ls32Arb).map(multiTrailingMapper,multiTrailingUnmapper),tuple2(array3(h16Arb,{minLength:0,maxLength:2,size:"max"}),array3(h16Arb,{minLength:3,maxLength:3,size:"max"}),ls32Arb).map(multiTrailingMapper,multiTrailingUnmapper),tuple2(array3(h16Arb,{minLength:0,maxLength:3,size:"max"}),array3(h16Arb,{minLength:2,maxLength:2,size:"max"}),ls32Arb).map(multiTrailingMapper,multiTrailingUnmapper),tuple2(array3(h16Arb,{minLength:0,maxLength:4,size:"max"}),h16Arb,ls32Arb).map(multiTrailingMapperOne,multiTrailingUnmapperOne),tuple2(array3(h16Arb,{minLength:0,maxLength:5,size:"max"}),ls32Arb).map(singleTrailingMapper,singleTrailingUnmapper),tuple2(array3(h16Arb,{minLength:0,maxLength:6,size:"max"}),h16Arb).map(singleTrailingMapper,singleTrailingUnmapper),tuple2(array3(h16Arb,{minLength:0,maxLength:7,size:"max"})).map(noTrailingMapper,noTrailingUnmapper))}var LazyArbitrary=class extends Arbitrary{constructor(name){super();this.name=name;this.underlying=null}generate(mrng,biasFactor){if(this.underlying===null)throw new Error(`Lazy arbitrary ${JSON.stringify(this.name)} not correctly initialized`);return this.underlying.generate(mrng,biasFactor)}canShrinkWithoutContext(value3){if(this.underlying===null)throw new Error(`Lazy arbitrary ${JSON.stringify(this.name)} not correctly initialized`);return this.underlying.canShrinkWithoutContext(value3)}shrink(value3,context4){if(this.underlying===null)throw new Error(`Lazy arbitrary ${JSON.stringify(this.name)} not correctly initialized`);return this.underlying.shrink(value3,context4)}};var safeGetOwnPropertyNames=Object.getOwnPropertyNames;function createLazyArbsPool(){const lazyArbsPool=new SMap$1;const getLazyFromPool=(key)=>{let lazyArb=safeMapGet(lazyArbsPool,key);if(lazyArb!==undefined)return lazyArb;lazyArb=new LazyArbitrary(String(key));safeMapSet(lazyArbsPool,key,lazyArb);return lazyArb};return getLazyFromPool}function letrec(builder){const getLazyFromPool=createLazyArbsPool();const strictArbs=builder(getLazyFromPool);const declaredArbitraryNames=safeGetOwnPropertyNames(strictArbs);for(const name of declaredArbitraryNames){const lazyArb=getLazyFromPool(name);lazyArb.underlying=strictArbs[name]}return strictArbs}function canHaveAtLeastOneItem(keys3,constraints){for(const key of keys3){const constraintsOnKey=constraints[key]||{};if(constraintsOnKey.maxLength===undefined||constraintsOnKey.maxLength>0)return true}return false}function initialPoolForEntityGraph(keys3,constraints){if(keys3.length===0)return constant2([]);if(!canHaveAtLeastOneItem(keys3,constraints))throw new SError("Contraints on pool must accept at least one entity, maxLength cannot sum to 0");return tuple2(...keys3.map((key)=>array3(constant2(key),constraints[key]))).map((values3)=>safeFlat(values3)).filter((names)=>names.length>0)}var safeObjectAssign$1=Object.assign;var safeObjectCreate$4=Object.create;var safeObjectDefineProperty$1=Object.defineProperty;var safeObjectGetPrototypeOf=Object.getPrototypeOf;var safeObjectPrototype=Object.prototype;function withTargetStringifiedValue(stringifiedValue){return safeObjectDefineProperty$1(safeObjectCreate$4(null),toStringMethod,{configurable:false,enumerable:false,writable:false,value:()=>stringifiedValue})}function withReferenceStringifiedValue(type,index2){return withTargetStringifiedValue(`<${SString(type)}#${index2}>`)}function unlinkedToLinkedEntitiesMapper(unlinkedEntities,producedLinks){const linkedEntities=safeObjectCreate$4(safeObjectPrototype);for(const name in unlinkedEntities){const unlinkedEntitiesForName=unlinkedEntities[name];const linkedEntitiesForName=[];for(const unlinkedEntity of unlinkedEntitiesForName){const linkedEntity=safeObjectAssign$1(safeObjectCreate$4(safeObjectGetPrototypeOf(unlinkedEntity)),unlinkedEntity);linkedEntitiesForName.push(linkedEntity)}linkedEntities[name]=linkedEntitiesForName}for(const name in producedLinks){const entityLinks=producedLinks[name];for(let entityIndex=0;entityIndex!==entityLinks.length;++entityIndex){const entityLinksForInstance=entityLinks[entityIndex];const linkedInstance=linkedEntities[name][entityIndex];for(const prop in entityLinksForInstance){const propValue=entityLinksForInstance[prop];linkedInstance[prop]=propValue.index===undefined?undefined:typeof propValue.index==="number"?linkedEntities[propValue.type][propValue.index]:safeMap(propValue.index,(index2)=>linkedEntities[propValue.type][index2])}safeObjectDefineProperty$1(linkedInstance,toStringMethod,{configurable:false,enumerable:false,writable:false,value:()=>{const unlinkedEntity=unlinkedEntities[name][entityIndex];const entity=safeObjectAssign$1(safeObjectCreate$4(safeObjectGetPrototypeOf(unlinkedEntity)),unlinkedEntity);for(const prop in entityLinksForInstance){const propValue=entityLinksForInstance[prop];entity[prop]=propValue.index===undefined?undefined:typeof propValue.index==="number"?withReferenceStringifiedValue(propValue.type,propValue.index):safeMap(propValue.index,(index2)=>withReferenceStringifiedValue(propValue.type,index2))}return stringify(entity)}})}}return linkedEntities}function buildInversedRelationsMapping(relations){let foundInversedRelations=0;const requestedInversedRelations=new SMap$1;for(const name in relations){const relationsForName=relations[name];for(const fieldName in relationsForName){const relation=relationsForName[fieldName];if(relation.arity!=="inverse")continue;let existingOnes=safeMapGet(requestedInversedRelations,relation.type);if(existingOnes===undefined){existingOnes=new SMap$1;safeMapSet(requestedInversedRelations,relation.type,existingOnes)}if(safeMapHas(existingOnes,relation.forwardRelationship))throw new SError(`Cannot declare multiple inverse relationships for the same forward relationship ${SString(relation.forwardRelationship)} on type ${SString(relation.type)}`);safeMapSet(existingOnes,relation.forwardRelationship,{type:name,property:fieldName});foundInversedRelations+=1}}const inversedRelations=new SMap$1;if(foundInversedRelations===0)return inversedRelations;for(const name in relations){const relationsForName=relations[name];const requestedInversedRelationsForName=safeMapGet(requestedInversedRelations,name);if(requestedInversedRelationsForName===undefined)continue;for(const fieldName in relationsForName){const relation=relationsForName[fieldName];if(relation.arity==="inverse")continue;const requestedIfAny=safeMapGet(requestedInversedRelationsForName,fieldName);if(requestedIfAny===undefined)continue;if(requestedIfAny.type!==relation.type)throw new SError(`Inverse relationship ${SString(requestedIfAny.property)} on type ${SString(requestedIfAny.type)} references forward relationship ${SString(fieldName)} but types do not match`);safeMapSet(inversedRelations,relation,requestedIfAny)}}if(inversedRelations.size!==foundInversedRelations)throw new SError(`Some inverse relationships could not be matched with their corresponding forward relationships`);return inversedRelations}var safeObjectAssign=Object.assign;var safeObjectCreate$3=Object.create;function produceLinkUnitaryIndexArbitrary(strategy,currentIndexIfSameType,countInTargetType){switch(strategy){case"exclusive":return constant2(countInTargetType);case"successor":return noBias(integer({min:currentIndexIfSameType!==undefined?currentIndexIfSameType+1:0,max:countInTargetType}));case"any":return noBias(integer({min:0,max:countInTargetType}))}}function buildLinkIndexArbitrary(arity,strategy,currentIndexIfSameType,countInTargetType,currentEntityDepth){const linkArbitrary=produceLinkUnitaryIndexArbitrary(strategy,currentIndexIfSameType,countInTargetType);switch(arity){case"0-1":return option3(linkArbitrary,{nil:undefined,depthIdentifier:currentEntityDepth});case"1":return linkArbitrary;case"many":{let randomUnicity=0;return option3(uniqueArray(linkArbitrary,{depthIdentifier:currentEntityDepth,selector:(v)=>v===countInTargetType?v+ ++randomUnicity:v,minLength:1}),{nil:[],depthIdentifier:currentEntityDepth}).map((values3)=>{let offset=0;return safeMap(values3,(v)=>v===countInTargetType?v+offset++:v)})}}}function createEmptyLinksInstanceFor(relations,targetType){const emptyLinksInstance=safeObjectCreate$3(null);const relationsForType=relations[targetType];for(const name in relationsForType){const relation=relationsForType[name];if(relation.arity==="inverse")emptyLinksInstance[name]={type:relation.type,index:[]}}return emptyLinksInstance}function assertAcceptableRelations(relations){const nonExclusiveEntities=new SSet;const exclusiveEntities=new SSet;for(const name in relations){const relationsForName=relations[name];for(const fieldName in relationsForName){const relation=relationsForName[fieldName];if(relation.arity==="inverse")continue;if(relation.strategy==="exclusive"){if(safeHas(nonExclusiveEntities,relation.type))throw new SError(`Cannot mix exclusive with other strategies for type ${SString(relation.type)}`);safeAdd(exclusiveEntities,relation.type)}else{if(safeHas(exclusiveEntities,relation.type))throw new SError(`Cannot mix exclusive with other strategies for type ${SString(relation.type)}`);safeAdd(nonExclusiveEntities,relation.type)}if(relation.strategy==="successor"&&relation.type!==name)throw new SError(`Cannot mix types for the strategy successor`);if(relation.strategy==="successor"&&relation.arity==="1")throw new SError(`Cannot use an arity of 1 for the strategy successor`)}}}function draftNextProductionState(state,offset){const{producedLinks,toBeProducedEntities}=state;const nextIndex=state.nextIndex+offset;const newProducedLinks=safeObjectAssign(safeObjectCreate$3(null),producedLinks);function getOrCreateProducedLinksFor(type){if(newProducedLinks[type]===producedLinks[type])newProducedLinks[type]=safeSlice(producedLinks[type]);return newProducedLinks[type]}function getOrCreateLinksFor(type,indexInType){const producedLinksForType=getOrCreateProducedLinksFor(type);if(producedLinksForType[indexInType]===producedLinks[type][indexInType])producedLinksForType[indexInType]=safeObjectAssign(safeObjectCreate$3(null),producedLinks[type][indexInType]);return producedLinksForType[indexInType]}function getOrCreateRelationFor(type,indexInType,property2){const links=getOrCreateLinksFor(type,indexInType);const originalEntity=producedLinks[type][indexInType];if(originalEntity!==undefined&&links[property2]===originalEntity[property2]){const sharedRelation=links[property2];links[property2]={type:sharedRelation.type,index:typeof sharedRelation.index==="object"?safeSlice(sharedRelation.index):sharedRelation.index}}return links[property2]}let newToBeProducedEntities=undefined;const toBeProduced=toBeProducedEntities[nextIndex];return{setOutboundLink:(name,value3)=>{const currentLinks=getOrCreateLinksFor(toBeProduced.type,toBeProduced.indexInType);currentLinks[name]=value3},enqueueNewEntity:(relations,targetType)=>{const producedLinksInTargetType=getOrCreateProducedLinksFor(targetType);const newEntityIndexInType=producedLinksInTargetType.length;if(newToBeProducedEntities===undefined)newToBeProducedEntities=safeSlice(toBeProducedEntities);safePush(newToBeProducedEntities,{type:targetType,indexInType:newEntityIndexInType,depth:toBeProduced.depth+1});safePush(producedLinksInTargetType,createEmptyLinksInstanceFor(relations,targetType));return newEntityIndexInType},appendBackReference:(targetType,indexInType,property2)=>{const knownInversedLinks=getOrCreateRelationFor(targetType,indexInType,property2).index;safePush(knownInversedLinks,toBeProduced.indexInType)},commit:()=>({producedLinks:newProducedLinks,toBeProducedEntities:newToBeProducedEntities!==undefined?newToBeProducedEntities:toBeProducedEntities,nextIndex:nextIndex+1})}}function buildInitialProductionState(relations,defaultEntities){const producedLinks=safeObjectCreate$3(null);for(const name in relations)producedLinks[name]=[];const toBeProducedEntities=[];for(const name of defaultEntities){safePush(toBeProducedEntities,{type:name,indexInType:producedLinks[name].length,depth:0});safePush(producedLinks[name],createEmptyLinksInstanceFor(relations,name))}return{producedLinks,toBeProducedEntities,nextIndex:0}}function buildEntityStepArbitrary(relations,inversedRelations,lastState,offset){const lastProducedLinks=lastState.producedLinks;const currentEntity=lastState.toBeProducedEntities[lastState.nextIndex+offset];const currentRelations=relations[currentEntity.type];const currentEntityDepth=createDepthIdentifier();currentEntityDepth.depth=currentEntity.depth;const subArbitraries=[];const linkContexts=[];for(const name in currentRelations){const relation=currentRelations[name];if(relation.arity==="inverse")continue;const targetType=relation.type;const countInTargetType=lastProducedLinks[targetType].length;safePush(subArbitraries,buildLinkIndexArbitrary(relation.arity,relation.strategy||"any",targetType===currentEntity.type?currentEntity.indexInType:undefined,countInTargetType,currentEntityDepth));safePush(linkContexts,{name,relation,sentinelLinkIndex:countInTargetType})}if(subArbitraries.length===0)return;return tuple2(...subArbitraries).map((results)=>{const state=draftNextProductionState(lastState,offset);for(let resultIndex=0;resultIndex!==results.length;++resultIndex){const linkOrLinks=results[resultIndex];const{name,relation,sentinelLinkIndex}=linkContexts[resultIndex];const effectiveLinks=[];const links=linkOrLinks===undefined?[]:typeof linkOrLinks==="number"?[linkOrLinks]:linkOrLinks;for(const link of links){let newEntityIndexInType;if(link>=sentinelLinkIndex)newEntityIndexInType=state.enqueueNewEntity(relations,relation.type);else newEntityIndexInType=link;safePush(effectiveLinks,newEntityIndexInType);const inversed=safeMapGet(inversedRelations,relation);if(inversed!==undefined)state.appendBackReference(relation.type,newEntityIndexInType,inversed.property)}state.setOutboundLink(name,{type:relation.type,index:linkOrLinks===undefined?undefined:typeof linkOrLinks==="number"?effectiveLinks[0]:effectiveLinks})}return state.commit()})}function onTheFlyLinksForEntityGraph(relations,defaultEntities){assertAcceptableRelations(relations);const inversedRelations=buildInversedRelationsMapping(relations);return chainUntil(constant2(buildInitialProductionState(relations,defaultEntities)),(state)=>{if(state.nextIndex>=state.toBeProducedEntities.length)return;let offset=0;let next=undefined;while(next===undefined&&state.nextIndex+offset<state.toBeProducedEntities.length){next=buildEntityStepArbitrary(relations,inversedRelations,state,offset);offset+=1}return next}).map((state)=>{return state.producedLinks})}var safeObjectKeys$1=Object.keys;var safeObjectGetOwnPropertySymbols$1=Object.getOwnPropertySymbols;var safeObjectGetOwnPropertyDescriptor$1=Object.getOwnPropertyDescriptor;function extractEnumerableKeys(instance){const keys3=safeObjectKeys$1(instance);const symbols=safeObjectGetOwnPropertySymbols$1(instance);for(let index2=0;index2!==symbols.length;++index2){const symbol4=symbols[index2];const descriptor=safeObjectGetOwnPropertyDescriptor$1(instance,symbol4);if(descriptor&&descriptor.enumerable)keys3.push(symbol4)}return keys3}var safeObjectCreate$2=Object.create;var safeObjectDefineProperty=Object.defineProperty;var safeObjectGetOwnPropertyDescriptor=Object.getOwnPropertyDescriptor;var safeObjectGetOwnPropertyNames=Object.getOwnPropertyNames;var safeObjectGetOwnPropertySymbols=Object.getOwnPropertySymbols;function buildValuesAndSeparateKeysToObjectMapper(keys3,noKeyValue){return function valuesAndSeparateKeysToObjectMapper(definition){const obj=definition[definition.length-1]?safeObjectCreate$2(null):{};for(let idx=0;idx!==keys3.length;++idx){const valueWrapper=definition[idx];if(valueWrapper!==noKeyValue){const key=keys3[idx];if(key==="__proto__")safeObjectDefineProperty(obj,key,{value:valueWrapper,configurable:true,enumerable:true,writable:true});else obj[key]=valueWrapper}}return obj}}function buildValuesAndSeparateKeysToObjectUnmapper(keys3,noKeyValue){return function valuesAndSeparateKeysToObjectUnmapper(value3){if(typeof value3!=="object"||value3===null)throw new Error("Incompatible instance received: should be a non-null object");const hasNullPrototype=Object.getPrototypeOf(value3)===null;const hasObjectPrototype="constructor"in value3&&value3.constructor===Object;if(!hasNullPrototype&&!hasObjectPrototype)throw new Error("Incompatible instance received: should be of exact type Object");let extractedPropertiesCount=0;const extractedValues=[];for(let idx=0;idx!==keys3.length;++idx){const descriptor=safeObjectGetOwnPropertyDescriptor(value3,keys3[idx]);if(descriptor!==undefined){if(!descriptor.configurable||!descriptor.enumerable||!descriptor.writable)throw new Error("Incompatible instance received: should contain only c/e/w properties");if(descriptor.get!==undefined||descriptor.set!==undefined)throw new Error("Incompatible instance received: should contain only no get/set properties");++extractedPropertiesCount;safePush(extractedValues,descriptor.value)}else safePush(extractedValues,noKeyValue)}const namePropertiesCount=safeObjectGetOwnPropertyNames(value3).length;const symbolPropertiesCount=safeObjectGetOwnPropertySymbols(value3).length;if(extractedPropertiesCount!==namePropertiesCount+symbolPropertiesCount)throw new Error("Incompatible instance received: should not contain extra properties");return[...extractedValues,hasNullPrototype]}}var noKeyValue=Symbol("no-key");function buildPartialRecordArbitrary(recordModel,requiredKeys,noNullPrototype){const keys3=extractEnumerableKeys(recordModel);const arbs=[];for(let index2=0;index2!==keys3.length;++index2){const k=keys3[index2];const requiredArbitrary=recordModel[k];if(requiredKeys===undefined||safeIndexOf(requiredKeys,k)!==-1)safePush(arbs,requiredArbitrary);else safePush(arbs,option3(requiredArbitrary,{nil:noKeyValue}))}return tuple2(...arbs,noNullPrototype?constant2(false):boolean2()).map(buildValuesAndSeparateKeysToObjectMapper(keys3,noKeyValue),buildValuesAndSeparateKeysToObjectUnmapper(keys3,noKeyValue))}function record2(recordModel,constraints){const noNullPrototype=constraints!==undefined&&!!constraints.noNullPrototype;if(constraints===undefined)return buildPartialRecordArbitrary(recordModel,undefined,noNullPrototype);if(!(("requiredKeys"in constraints)&&constraints.requiredKeys!==undefined))return buildPartialRecordArbitrary(recordModel,undefined,noNullPrototype);const requiredKeys=("requiredKeys"in constraints?constraints.requiredKeys:undefined)||[];for(let idx=0;idx!==requiredKeys.length;++idx){const descriptor=Object.getOwnPropertyDescriptor(recordModel,requiredKeys[idx]);if(descriptor===undefined)throw new Error(`requiredKeys cannot reference keys that have not been defined in recordModel`);if(!descriptor.enumerable)throw new Error(`requiredKeys cannot reference keys that are not enumerable in recordModel`)}return buildPartialRecordArbitrary(recordModel,requiredKeys,noNullPrototype)}var safeObjectCreate$1=Object.create;function unlinkedEntitiesForEntityGraph(arbitraries,countFor,unicityConstraintsFor,constraints){const recordModel=safeObjectCreate$1(null);for(const name in arbitraries){const entityRecordModel=arbitraries[name];const entityArbitrary=record2(entityRecordModel,constraints);const count=countFor(name);const unicityConstraints=unicityConstraintsFor(name);const arrayConstraints={minLength:count,maxLength:count};recordModel[name]=unicityConstraints!==undefined?uniqueArray(entityArbitrary,{...arrayConstraints,selector:unicityConstraints}):array3(entityArbitrary,arrayConstraints)}return record2(recordModel)}var safeObjectCreate=Object.create;var safeObjectKeys=Object.keys;function entityGraph(arbitraries,relations,constraints={}){const allKeys=safeObjectKeys(arbitraries);const initialPoolConstraints=constraints.initialPoolConstraints||safeObjectCreate(null);const unicityConstraints=constraints.unicityConstraints||safeObjectCreate(null);const unlinkedContraints={noNullPrototype:constraints.noNullPrototype};return initialPoolForEntityGraph(allKeys,initialPoolConstraints).chain((defaultEntities)=>onTheFlyLinksForEntityGraph(relations,defaultEntities).chain((producedLinks)=>unlinkedEntitiesForEntityGraph(arbitraries,(name)=>producedLinks[name].length,(name)=>unicityConstraints[name],unlinkedContraints).map((unlinkedEntities)=>unlinkedToLinkedEntitiesMapper(unlinkedEntities,producedLinks))))}function wordsToJoinedStringMapper(words){return safeJoin(safeMap(words,(w)=>w[w.length-1]===","?safeSubstring(w,0,w.length-1):w)," ")}function wordsToJoinedStringUnmapperFor(wordsArbitrary){return function wordsToJoinedStringUnmapper(value3){if(typeof value3!=="string")throw new Error("Unsupported type");const words=[];for(const candidate of safeSplit(value3," "))if(wordsArbitrary.canShrinkWithoutContext(candidate))safePush(words,candidate);else if(wordsArbitrary.canShrinkWithoutContext(candidate+","))safePush(words,candidate+",");else throw new Error("Unsupported word");return words}}function wordsToSentenceMapper(words){let sentence=safeJoin(words," ");if(sentence[sentence.length-1]===",")sentence=safeSubstring(sentence,0,sentence.length-1);return safeToUpperCase(sentence[0])+safeSubstring(sentence,1)+"."}function wordsToSentenceUnmapperFor(wordsArbitrary){return function wordsToSentenceUnmapper(value3){if(typeof value3!=="string")throw new Error("Unsupported type");if(value3.length<2||value3[value3.length-1]!=="."||value3[value3.length-2]===","||safeToUpperCase(safeToLowerCase(value3[0]))!==value3[0])throw new Error("Unsupported value");const adaptedValue=safeToLowerCase(value3[0])+safeSubstring(value3,1,value3.length-1);const words=[];const candidates=safeSplit(adaptedValue," ");for(let idx=0;idx!==candidates.length;++idx){const candidate=candidates[idx];if(wordsArbitrary.canShrinkWithoutContext(candidate))safePush(words,candidate);else if(idx===candidates.length-1&&wordsArbitrary.canShrinkWithoutContext(candidate+","))safePush(words,candidate+",");else throw new Error("Unsupported word")}return words}}function sentencesToParagraphMapper(sentences){return safeJoin(sentences," ")}function sentencesToParagraphUnmapper(value3){if(typeof value3!=="string")throw new Error("Unsupported type");const sentences=safeSplit(value3,". ");for(let idx=0;idx<sentences.length-1;++idx)sentences[idx]+=".";return sentences}var h=(v,w)=>{return{arbitrary:constant2(v),weight:w}};function loremWord(){return oneof(h("non",6),h("adipiscing",5),h("ligula",5),h("enim",5),h("pellentesque",5),h("in",5),h("augue",5),h("et",5),h("nulla",5),h("lorem",4),h("sit",4),h("sed",4),h("diam",4),h("fermentum",4),h("ut",4),h("eu",4),h("aliquam",4),h("mauris",4),h("vitae",4),h("felis",4),h("ipsum",3),h("dolor",3),h("amet,",3),h("elit",3),h("euismod",3),h("mi",3),h("orci",3),h("erat",3),h("praesent",3),h("egestas",3),h("leo",3),h("vel",3),h("sapien",3),h("integer",3),h("curabitur",3),h("convallis",3),h("purus",3),h("risus",2),h("suspendisse",2),h("lectus",2),h("nec,",2),h("ultricies",2),h("sed,",2),h("cras",2),h("elementum",2),h("ultrices",2),h("maecenas",2),h("massa,",2),h("varius",2),h("a,",2),h("semper",2),h("proin",2),h("nec",2),h("nisl",2),h("amet",2),h("duis",2),h("congue",2),h("libero",2),h("vestibulum",2),h("pede",2),h("blandit",2),h("sodales",2),h("ante",2),h("nibh",2),h("ac",2),h("aenean",2),h("massa",2),h("suscipit",2),h("sollicitudin",2),h("fusce",2),h("tempus",2),h("aliquam,",2),h("nunc",2),h("ullamcorper",2),h("rhoncus",2),h("metus",2),h("faucibus,",2),h("justo",2),h("magna",2),h("at",2),h("tincidunt",2),h("consectetur",1),h("tortor,",1),h("dignissim",1),h("congue,",1),h("non,",1),h("porttitor,",1),h("nonummy",1),h("molestie,",1),h("est",1),h("eleifend",1),h("mi,",1),h("arcu",1),h("scelerisque",1),h("vitae,",1),h("consequat",1),h("in,",1),h("pretium",1),h("volutpat",1),h("pharetra",1),h("tempor",1),h("bibendum",1),h("odio",1),h("dui",1),h("primis",1),h("faucibus",1),h("luctus",1),h("posuere",1),h("cubilia",1),h("curae,",1),h("hendrerit",1),h("velit",1),h("mauris,",1),h("gravida",1),h("ornare",1),h("ut,",1),h("pulvinar",1),h("varius,",1),h("turpis",1),h("nibh,",1),h("eros",1),h("id",1),h("aliquet",1),h("quis",1),h("lobortis",1),h("consectetuer",1),h("morbi",1),h("vehicula",1),h("tortor",1),h("tellus,",1),h("id,",1),h("eu,",1),h("quam",1),h("feugiat,",1),h("posuere,",1),h("iaculis",1),h("lectus,",1),h("tristique",1),h("mollis,",1),h("nisl,",1),h("vulputate",1),h("sem",1),h("vivamus",1),h("placerat",1),h("imperdiet",1),h("cursus",1),h("rutrum",1),h("iaculis,",1),h("augue,",1),h("lacus",1))}function lorem(constraints={}){const{maxCount,mode="words",size:size6}=constraints;if(maxCount!==undefined&&maxCount<1)throw new Error(`lorem has to produce at least one word/sentence`);const wordArbitrary=loremWord();if(mode==="sentences")return array3(array3(wordArbitrary,{minLength:1,size:"small"}).map(wordsToSentenceMapper,wordsToSentenceUnmapperFor(wordArbitrary)),{minLength:1,maxLength:maxCount,size:size6}).map(sentencesToParagraphMapper,sentencesToParagraphUnmapper);else return array3(wordArbitrary,{minLength:1,maxLength:maxCount,size:size6}).map(wordsToJoinedStringMapper,wordsToJoinedStringUnmapperFor(wordArbitrary))}function arrayToMapMapper(data){return new Map(data)}function arrayToMapUnmapper(value3){if(typeof value3!=="object"||value3===null)throw new Error("Incompatible instance received: should be a non-null object");if(!("constructor"in value3)||value3.constructor!==Map)throw new Error("Incompatible instance received: should be of exact type Map");return Array.from(value3)}function mapKeyExtractor(entry){return entry[0]}function map13(keyArb,valueArb,constraints={}){return uniqueArray(tuple2(keyArb,valueArb),{minLength:constraints.minKeys,maxLength:constraints.maxKeys,size:constraints.size,selector:mapKeyExtractor,depthIdentifier:constraints.depthIdentifier,comparator:"SameValueZero"}).map(arrayToMapMapper,arrayToMapUnmapper)}var contextRemainingDepth=10;function memo(builder){const previous={};return(maxDepth)=>{const n=maxDepth!==undefined?maxDepth:contextRemainingDepth;if(!safeHasOwnProperty(previous,n)){const prev=contextRemainingDepth;contextRemainingDepth=n-1;previous[n]=builder(n);contextRemainingDepth=prev}return previous[n]}}function countToggledBits(n){let count=0;while(n>SBigInt2(0)){if(n&SBigInt2(1))++count;n>>=SBigInt2(1)}return count}function computeNextFlags(flags,nextSize){const allowedMask=(SBigInt2(1)<<SBigInt2(nextSize))-SBigInt2(1);const preservedFlags=flags&allowedMask;let numMissingFlags=countToggledBits(flags-preservedFlags);let nFlags=preservedFlags;for(let mask2=SBigInt2(1);mask2<=allowedMask&&numMissingFlags!==0;mask2<<=SBigInt2(1))if(!(nFlags&mask2)){nFlags|=mask2;--numMissingFlags}return nFlags}function computeTogglePositions(chars,toggleCase){const positions=[];for(let idx=chars.length-1;idx!==-1;--idx)if(toggleCase(chars[idx])!==chars[idx])safePush(positions,idx);return positions}function computeFlagsFromChars(untoggledChars,toggledChars,togglePositions){let flags=SBigInt2(0);for(let idx=0,mask2=SBigInt2(1);idx!==togglePositions.length;++idx,mask2<<=SBigInt2(1))if(untoggledChars[togglePositions[idx]]!==toggledChars[togglePositions[idx]])flags|=mask2;return flags}function applyFlagsOnChars(chars,flags,togglePositions,toggleCase){for(let idx=0,mask2=SBigInt2(1);idx!==togglePositions.length;++idx,mask2<<=SBigInt2(1))if(flags&mask2)chars[togglePositions[idx]]=toggleCase(chars[togglePositions[idx]])}var MixedCaseArbitrary=class extends Arbitrary{constructor(stringArb,toggleCase,untoggleAll){super();this.stringArb=stringArb;this.toggleCase=toggleCase;this.untoggleAll=untoggleAll}buildContextFor(rawStringValue,flagsValue){return{rawString:rawStringValue.value,rawStringContext:rawStringValue.context,flags:flagsValue.value,flagsContext:flagsValue.context}}generate(mrng,biasFactor){const rawStringValue=this.stringArb.generate(mrng,biasFactor);const chars=[...rawStringValue.value];const togglePositions=computeTogglePositions(chars,this.toggleCase);const flagsValue=bigInt2(SBigInt2(0),(SBigInt2(1)<<SBigInt2(togglePositions.length))-SBigInt2(1)).generate(mrng,undefined);applyFlagsOnChars(chars,flagsValue.value,togglePositions,this.toggleCase);return new Value(safeJoin(chars,""),this.buildContextFor(rawStringValue,flagsValue))}canShrinkWithoutContext(value3){if(typeof value3!=="string")return false;return this.untoggleAll!==undefined?this.stringArb.canShrinkWithoutContext(this.untoggleAll(value3)):this.stringArb.canShrinkWithoutContext(value3)}shrink(value3,context4){let contextSafe;if(context4!==undefined)contextSafe=context4;else if(this.untoggleAll!==undefined){const untoggledValue=this.untoggleAll(value3);const valueChars=[...value3];const untoggledValueChars=[...untoggledValue];contextSafe={rawString:untoggledValue,rawStringContext:undefined,flags:computeFlagsFromChars(untoggledValueChars,valueChars,computeTogglePositions(untoggledValueChars,this.toggleCase)),flagsContext:undefined}}else contextSafe={rawString:value3,rawStringContext:undefined,flags:SBigInt2(0),flagsContext:undefined};const rawString=contextSafe.rawString;const flags=contextSafe.flags;return this.stringArb.shrink(rawString,contextSafe.rawStringContext).map((nRawStringValue)=>{const nChars=[...nRawStringValue.value];const nTogglePositions=computeTogglePositions(nChars,this.toggleCase);const nFlags=computeNextFlags(flags,nTogglePositions.length);applyFlagsOnChars(nChars,nFlags,nTogglePositions,this.toggleCase);return new Value(safeJoin(nChars,""),this.buildContextFor(nRawStringValue,new Value(nFlags,undefined)))}).join(makeLazy2(()=>{const chars=[...rawString];const togglePositions=computeTogglePositions(chars,this.toggleCase);return bigInt2(SBigInt2(0),(SBigInt2(1)<<SBigInt2(togglePositions.length))-SBigInt2(1)).shrink(flags,contextSafe.flagsContext).map((nFlagsValue)=>{const nChars=safeSlice(chars);applyFlagsOnChars(nChars,nFlagsValue.value,togglePositions,this.toggleCase);return new Value(safeJoin(nChars,""),this.buildContextFor(new Value(rawString,contextSafe.rawStringContext),nFlagsValue))})}))}};function defaultToggleCase(rawChar){const upper=safeToUpperCase(rawChar);if(upper!==rawChar)return upper;return safeToLowerCase(rawChar)}function mixedCase(stringArb,constraints){return new MixedCaseArbitrary(stringArb,constraints&&constraints.toggleCase||defaultToggleCase,constraints&&constraints.untoggleAll)}function toTypedMapper$1(data){return SFloat32Array.from(data)}function fromTypedUnmapper$1(value3){if(!(value3 instanceof SFloat32Array))throw new Error("Unexpected type");return[...value3]}function float32Array(constraints={}){return array3(float(constraints),constraints).map(toTypedMapper$1,fromTypedUnmapper$1)}function toTypedMapper(data){return SFloat64Array.from(data)}function fromTypedUnmapper(value3){if(!(value3 instanceof SFloat64Array))throw new Error("Unexpected type");return[...value3]}function float64Array(constraints={}){return array3(double(constraints),constraints).map(toTypedMapper,fromTypedUnmapper)}function typedIntArrayArbitraryArbitraryBuilder(constraints,defaultMin,defaultMax,TypedArrayClass,arbitraryBuilder){const generatorName=TypedArrayClass.name;const{min:min5=defaultMin,max:max5=defaultMax,...arrayConstraints}=constraints;if(min5>max5)throw new Error(`Invalid range passed to ${generatorName}: min must be lower than or equal to max`);if(min5<defaultMin)throw new Error(`Invalid min value passed to ${generatorName}: min must be greater than or equal to ${defaultMin}`);if(max5>defaultMax)throw new Error(`Invalid max value passed to ${generatorName}: max must be lower than or equal to ${defaultMax}`);return array3(arbitraryBuilder({min:min5,max:max5}),arrayConstraints).map((data)=>TypedArrayClass.from(data),(value3)=>{if(!(value3 instanceof TypedArrayClass))throw new Error("Invalid type");return[...value3]})}function int16Array(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,-32768,32767,SInt16Array,integer)}function int32Array(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,-2147483648,2147483647,SInt32Array,integer)}function int8Array(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,-128,127,SInt8Array,integer)}function uint16Array(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,0,65535,SUint16Array,integer)}function uint32Array(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,0,4294967295,SUint32Array,integer)}function uint8Array(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,0,255,SUint8Array,integer)}function uint8ClampedArray(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,0,255,SUint8ClampedArray,integer)}function isSafeContext(context4){return context4!==undefined}function toGeneratorValue(value3){if(value3.hasToBeCloned)return new Value(value3.value_,{generatorContext:value3.context},()=>value3.value);return new Value(value3.value_,{generatorContext:value3.context})}function toShrinkerValue(value3){if(value3.hasToBeCloned)return new Value(value3.value_,{shrinkerContext:value3.context},()=>value3.value);return new Value(value3.value_,{shrinkerContext:value3.context})}var WithShrinkFromOtherArbitrary=class extends Arbitrary{constructor(generatorArbitrary,shrinkerArbitrary){super();this.generatorArbitrary=generatorArbitrary;this.shrinkerArbitrary=shrinkerArbitrary}generate(mrng,biasFactor){return toGeneratorValue(this.generatorArbitrary.generate(mrng,biasFactor))}canShrinkWithoutContext(value3){return this.shrinkerArbitrary.canShrinkWithoutContext(value3)}shrink(value3,context4){if(!isSafeContext(context4))return this.shrinkerArbitrary.shrink(value3,undefined).map(toShrinkerValue);if("generatorContext"in context4)return this.generatorArbitrary.shrink(value3,context4.generatorContext).map(toGeneratorValue);return this.shrinkerArbitrary.shrink(value3,context4.shrinkerContext).map(toShrinkerValue)}};function restrictedIntegerArbitraryBuilder(min5,maxGenerated,max5){const generatorArbitrary=integer({min:min5,max:maxGenerated});if(maxGenerated===max5)return generatorArbitrary;return new WithShrinkFromOtherArbitrary(generatorArbitrary,integer({min:min5,max:max5}))}var safeMathMin$1=Math.min;var safeMathMax=Math.max;var safeArrayIsArray$1=SArray.isArray;var safeObjectEntries=Object.entries;function extractMaxIndex(indexesAndValues){let maxIndex=-1;for(let index2=0;index2!==indexesAndValues.length;++index2)maxIndex=safeMathMax(maxIndex,indexesAndValues[index2][0]);return maxIndex}function arrayFromItems(length,indexesAndValues){const array4=SArray(length);for(let index2=0;index2!==indexesAndValues.length;++index2){const it=indexesAndValues[index2];if(it[0]<length)array4[it[0]]=it[1]}return array4}function sparseArray(arb,constraints={}){const{size:size6,minNumElements=0,maxLength=MaxLengthUpperBound,maxNumElements=maxLength,noTrailingHole,depthIdentifier}=constraints;const maxGeneratedLength=maxGeneratedLengthFromSizeForArbitrary(size6,maxGeneratedLengthFromSizeForArbitrary(size6,minNumElements,maxNumElements,constraints.maxNumElements!==undefined),maxLength,constraints.maxLength!==undefined);if(minNumElements>maxLength)throw new Error(`The minimal number of non-hole elements cannot be higher than the maximal length of the array`);if(minNumElements>maxNumElements)throw new Error(`The minimal number of non-hole elements cannot be higher than the maximal number of non-holes`);const resultedMaxNumElements=safeMathMin$1(maxNumElements,maxLength);const resultedSizeMaxNumElements=constraints.maxNumElements!==undefined||size6!==undefined?size6:"=";const sparseArrayNoTrailingHole=uniqueArray(tuple2(restrictedIntegerArbitraryBuilder(0,safeMathMax(maxGeneratedLength-1,0),safeMathMax(maxLength-1,0)),arb),{size:resultedSizeMaxNumElements,minLength:minNumElements,maxLength:resultedMaxNumElements,selector:(item)=>item[0],depthIdentifier}).map((items2)=>{return arrayFromItems(extractMaxIndex(items2)+1,items2)},(value3)=>{if(!safeArrayIsArray$1(value3))throw new Error("Not supported entry type");if(noTrailingHole&&value3.length!==0&&!(value3.length-1 in value3))throw new Error("No trailing hole");return safeMap(safeObjectEntries(value3),(entry)=>[Number(entry[0]),entry[1]])});if(noTrailingHole||maxLength===minNumElements)return sparseArrayNoTrailingHole;return tuple2(sparseArrayNoTrailingHole,restrictedIntegerArbitraryBuilder(minNumElements,maxGeneratedLength,maxLength)).map((data)=>{const sparse=data[0];const targetLength=data[1];if(sparse.length>=targetLength)return sparse;const longerSparse=safeSlice(sparse);longerSparse.length=targetLength;return longerSparse},(value3)=>{if(!safeArrayIsArray$1(value3))throw new Error("Not supported entry type");return[value3,value3.length]})}function arrayToSetMapper(data){return new Set(data)}function arrayToSetUnmapper(value3){if(typeof value3!=="object"||value3===null)throw new Error("Incompatible instance received: should be a non-null object");if(!("constructor"in value3)||value3.constructor!==Set)throw new Error("Incompatible instance received: should be of exact type Set");return Array.from(value3)}function set3(arb,constraints={}){return uniqueArray(arb,{minLength:constraints.minLength,maxLength:constraints.maxLength,size:constraints.size,depthIdentifier:constraints.depthIdentifier,comparator:"SameValueZero"}).map(arrayToSetMapper,arrayToSetUnmapper)}function dictOf(ka,va,maxKeys,size6,depthIdentifier,withNullPrototype){return dictionary(ka,va,{maxKeys,noNullPrototype:!withNullPrototype,size:size6,depthIdentifier})}function typedArray(constraints){return oneof(int8Array(constraints),uint8Array(constraints),uint8ClampedArray(constraints),int16Array(constraints),uint16Array(constraints),int32Array(constraints),uint32Array(constraints),float32Array(constraints),float64Array(constraints))}function anyArbitraryBuilder(constraints){const arbitrariesForBase=constraints.values;const depthSize=constraints.depthSize;const depthIdentifier=createDepthIdentifier();const maxDepth=constraints.maxDepth;const maxKeys=constraints.maxKeys;const size6=constraints.size;const baseArb=oneof(...arbitrariesForBase,...constraints.withBigInt?[bigInt2()]:[],...constraints.withDate?[date()]:[]);return letrec((tie)=>({anything:oneof({maxDepth,depthSize,depthIdentifier},baseArb,tie("array"),tie("object"),...constraints.withMap?[tie("map")]:[],...constraints.withSet?[tie("set")]:[],...constraints.withObjectString?[tie("anything").map((o)=>stringify(o))]:[],...constraints.withTypedArray?[typedArray({maxLength:maxKeys,size:size6})]:[],...constraints.withSparseArray?[sparseArray(tie("anything"),{maxNumElements:maxKeys,size:size6,depthIdentifier})]:[]),keys:constraints.withObjectString?oneof({arbitrary:constraints.key,weight:10},{arbitrary:tie("anything").map((o)=>stringify(o)),weight:1}):constraints.key,array:array3(tie("anything"),{maxLength:maxKeys,size:size6,depthIdentifier}),set:set3(tie("anything"),{maxLength:maxKeys,size:size6,depthIdentifier}),map:oneof(map13(tie("keys"),tie("anything"),{maxKeys,size:size6,depthIdentifier}),map13(tie("anything"),tie("anything"),{maxKeys,size:size6,depthIdentifier})),object:dictOf(tie("keys"),tie("anything"),maxKeys,size6,depthIdentifier,constraints.withNullPrototype)})).anything}function unboxedToBoxedMapper(value3){switch(typeof value3){case"boolean":return new SBoolean(value3);case"number":return new SNumber(value3);case"string":return new SString(value3);default:return value3}}function unboxedToBoxedUnmapper(value3){if(typeof value3!=="object"||value3===null||!("constructor"in value3))return value3;return value3.constructor===SBoolean||value3.constructor===SNumber||value3.constructor===SString?value3.valueOf():value3}function boxedArbitraryBuilder(arb){return arb.map(unboxedToBoxedMapper,unboxedToBoxedUnmapper)}function defaultValues(constraints,stringArbitrary){return[boolean2(),maxSafeInteger(),double(),stringArbitrary(constraints),oneof(stringArbitrary(constraints),constant2(null),constant2(undefined))]}function boxArbitraries(arbs){return arbs.map((arb)=>boxedArbitraryBuilder(arb))}function boxArbitrariesIfNeeded(arbs,boxEnabled){return boxEnabled?boxArbitraries(arbs).concat(arbs):arbs}function toQualifiedObjectConstraints(settings={}){const valueConstraints={size:settings.size,unit:"stringUnit"in settings?settings.stringUnit:settings.withUnicodeString?"binary":undefined};return{key:settings.key!==undefined?settings.key:string3(valueConstraints),values:boxArbitrariesIfNeeded(settings.values!==undefined?settings.values:defaultValues(valueConstraints,string3),settings.withBoxedValues===true),depthSize:settings.depthSize,maxDepth:settings.maxDepth,maxKeys:settings.maxKeys,size:settings.size,withSet:settings.withSet===true,withMap:settings.withMap===true,withObjectString:settings.withObjectString===true,withNullPrototype:settings.withNullPrototype===true,withBigInt:settings.withBigInt===true,withDate:settings.withDate===true,withTypedArray:settings.withTypedArray===true,withSparseArray:settings.withSparseArray===true}}function objectInternal(constraints){return dictionary(constraints.key,anyArbitraryBuilder(constraints),{maxKeys:constraints.maxKeys,noNullPrototype:!constraints.withNullPrototype,size:constraints.size})}function object(constraints){return objectInternal(toQualifiedObjectConstraints(constraints))}function jsonConstraintsBuilder(stringArbitrary,constraints){const{depthSize,maxDepth}=constraints;return{key:stringArbitrary,values:[boolean2(),double({noDefaultInfinity:true,noNaN:true}),stringArbitrary,constant2(null)],depthSize,maxDepth}}function anything(constraints){return anyArbitraryBuilder(toQualifiedObjectConstraints(constraints))}function jsonValue(constraints={}){const noUnicodeString=constraints.noUnicodeString===undefined||constraints.noUnicodeString===true;return anything(jsonConstraintsBuilder("stringUnit"in constraints?string3({unit:constraints.stringUnit}):noUnicodeString?string3():string3({unit:"binary"}),constraints))}var safeJsonStringify=JSON.stringify;var safeJsonParse=JSON.parse;function jsonStringUnmapper(value3){if(typeof value3!=="string")throw new SError("Cannot unmap the passed value");return safeJsonParse(value3)}function json(constraints={}){return jsonValue(constraints).map(safeJsonStringify,jsonStringUnmapper)}var safeObjectDefineProperties=Object.defineProperties;function prettyPrint(numSeen,seenValuesStrings){return`Stream(${seenValuesStrings!==undefined?`${safeJoin(seenValuesStrings,",")}…`:`${numSeen} emitted`})`}var StreamArbitrary=class extends Arbitrary{constructor(arb,history){super();this.arb=arb;this.history=history}generate(mrng,biasFactor){const appliedBiasFactor=biasFactor!==undefined&&mrng.nextInt(1,biasFactor)===1?biasFactor:undefined;const enrichedProducer=()=>{const seenValues=this.history?[]:null;let numSeenValues=0;const g=function*(arb,clonedMrng){while(true){const value3=arb.generate(clonedMrng,appliedBiasFactor).value;numSeenValues++;if(seenValues!==null)safePush(seenValues,value3);yield value3}};const s=new Stream(g(this.arb,mrng.clone()));return safeObjectDefineProperties(s,{toString:{value:()=>prettyPrint(numSeenValues,seenValues!==null?seenValues.map(stringify):undefined)},[toStringMethod]:{value:()=>prettyPrint(numSeenValues,seenValues!==null?seenValues.map(stringify):undefined)},[asyncToStringMethod]:{value:async()=>prettyPrint(numSeenValues,seenValues!==null?await Promise.all(seenValues.map(asyncStringify)):undefined)},[cloneMethod]:{value:enrichedProducer,enumerable:true}})};return new Value(enrichedProducer(),undefined)}canShrinkWithoutContext(_value){return false}shrink(_value,_context){return Stream.nil()}};function infiniteStream(arb,constraints){return new StreamArbitrary(arb,constraints!==undefined&&typeof constraints==="object"&&"noHistory"in constraints?!constraints.noHistory:true)}function codePointsToStringMapper(tab){return safeJoin(tab,"")}function codePointsToStringUnmapper(value3){if(typeof value3!=="string")throw new Error("Cannot unmap the passed value");return[...value3]}function stringToBase64Mapper(s){switch(s.length%4){case 0:return s;case 3:return`${s}=`;case 2:return`${s}==`;default:return safeSubstring(s,1)}}function stringToBase64Unmapper(value3){if(typeof value3!=="string"||value3.length%4!==0)throw new Error("Invalid string received");const lastTrailingIndex=value3.indexOf("=");if(lastTrailingIndex===-1)return value3;if(value3.length-lastTrailingIndex>2)throw new Error("Cannot unmap the passed value");return safeSubstring(value3,0,lastTrailingIndex)}var safeStringFromCharCode=String.fromCharCode;function base64Mapper(v){if(v<26)return safeStringFromCharCode(v+65);if(v<52)return safeStringFromCharCode(v+97-26);if(v<62)return safeStringFromCharCode(v+48-52);return v===62?"+":"/"}function base64Unmapper(s){if(typeof s!=="string"||s.length!==1)throw new SError("Invalid entry");const v=safeCharCodeAt(s,0);if(v>=65&&v<=90)return v-65;if(v>=97&&v<=122)return v-97+26;if(v>=48&&v<=57)return v-48+52;return v===43?62:v===47?63:-1}function base64(){return integer({min:0,max:63}).map(base64Mapper,base64Unmapper)}function base64String(constraints={}){const{minLength:unscaledMinLength=0,maxLength:unscaledMaxLength=MaxLengthUpperBound,size:size6}=constraints;const minLength=unscaledMinLength+3-(unscaledMinLength+3)%4;const maxLength=unscaledMaxLength-unscaledMaxLength%4;const requestedSize=constraints.maxLength===undefined&&size6===undefined?"=":size6;if(minLength>maxLength)throw new SError("Minimal length should be inferior or equal to maximal length");if(minLength%4!==0)throw new SError("Minimal length of base64 strings must be a multiple of 4");if(maxLength%4!==0)throw new SError("Maximal length of base64 strings must be a multiple of 4");const charArbitrary=base64();return array3(charArbitrary,{minLength,maxLength,size:requestedSize,experimentalCustomSlices:createSlicesForStringLegacy(charArbitrary,codePointsToStringUnmapper)}).map(codePointsToStringMapper,codePointsToStringUnmapper).map(stringToBase64Mapper,stringToBase64Unmapper)}var safeObjectIs=Object.is;function isSubarrayOf(source,small){const countMap=new SMap$1;let countMinusZero=0;for(const sourceEntry of source)if(safeObjectIs(sourceEntry,-0))++countMinusZero;else safeMapSet(countMap,sourceEntry,(safeMapGet(countMap,sourceEntry)||0)+1);for(let index2=0;index2!==small.length;++index2){if(!(index2 in small))return false;const smallEntry=small[index2];if(safeObjectIs(smallEntry,-0)){if(countMinusZero===0)return false;--countMinusZero}else{const oldCount=safeMapGet(countMap,smallEntry)||0;if(oldCount===0)return false;safeMapSet(countMap,smallEntry,oldCount-1)}}return true}var safeMathFloor$1=Math.floor;var safeMathLog=Math.log;var safeArrayIsArray=Array.isArray;var SubarrayArbitrary=class extends Arbitrary{constructor(originalArray,isOrdered,minLength,maxLength){super();this.originalArray=originalArray;this.isOrdered=isOrdered;this.minLength=minLength;this.maxLength=maxLength;if(minLength<0||minLength>originalArray.length)throw new Error("fc.*{s|S}ubarrayOf expects the minimal length to be between 0 and the size of the original array");if(maxLength<0||maxLength>originalArray.length)throw new Error("fc.*{s|S}ubarrayOf expects the maximal length to be between 0 and the size of the original array");if(minLength>maxLength)throw new Error("fc.*{s|S}ubarrayOf expects the minimal length to be inferior or equal to the maximal length");this.lengthArb=new IntegerArbitrary(minLength,maxLength);this.biasedLengthArb=minLength!==maxLength?new IntegerArbitrary(minLength,minLength+safeMathFloor$1(safeMathLog(maxLength-minLength)/safeMathLog(2))):this.lengthArb}generate(mrng,biasFactor){const size6=(biasFactor!==undefined&&mrng.nextInt(1,biasFactor)===1?this.biasedLengthArb:this.lengthArb).generate(mrng,undefined);const sizeValue=size6.value;const remainingElements=safeMap(this.originalArray,(_v,idx)=>idx);const ids=[];for(let index2=0;index2!==sizeValue;++index2){const selectedIdIndex=mrng.nextInt(0,remainingElements.length-1);safePush(ids,remainingElements[selectedIdIndex]);safeSplice(remainingElements,selectedIdIndex,1)}if(this.isOrdered)safeSort(ids,(a,b)=>a-b);return new Value(safeMap(ids,(i)=>this.originalArray[i]),size6.context)}canShrinkWithoutContext(value3){if(!safeArrayIsArray(value3))return false;if(!this.lengthArb.canShrinkWithoutContext(value3.length))return false;return isSubarrayOf(this.originalArray,value3)}shrink(value3,context4){if(value3.length===0)return Stream.nil();return this.lengthArb.shrink(value3.length,context4).map((newSize)=>{return new Value(safeSlice(value3,value3.length-newSize.value),newSize.context)}).join(value3.length>this.minLength?makeLazy2(()=>this.shrink(safeSlice(value3,1),undefined).filter((newValue)=>this.minLength<=newValue.value.length+1).map((newValue)=>new Value([value3[0],...newValue.value],undefined))):Stream.nil())}};function subarray(originalArray,constraints={}){const{minLength=0,maxLength=originalArray.length}=constraints;return new SubarrayArbitrary(originalArray,true,minLength,maxLength)}function shuffledSubarray(originalArray,constraints={}){const{minLength=0,maxLength=originalArray.length}=constraints;return new SubarrayArbitrary(originalArray,false,minLength,maxLength)}var encodeSymbolLookupTable={10:"A",11:"B",12:"C",13:"D",14:"E",15:"F",16:"G",17:"H",18:"J",19:"K",20:"M",21:"N",22:"P",23:"Q",24:"R",25:"S",26:"T",27:"V",28:"W",29:"X",30:"Y",31:"Z"};var decodeSymbolLookupTable={"0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,A:10,B:11,C:12,D:13,E:14,F:15,G:16,H:17,J:18,K:19,M:20,N:21,P:22,Q:23,R:24,S:25,T:26,V:27,W:28,X:29,Y:30,Z:31};function encodeSymbol(symbol4){return symbol4<10?SString(symbol4):encodeSymbolLookupTable[symbol4]}function pad(value3,paddingLength){let extraPadding="";while(value3.length+extraPadding.length<paddingLength)extraPadding+="0";return extraPadding+value3}function smallUintToBase32StringMapper(num){let base32Str="";for(let remaining=num;remaining!==0;){const next=remaining>>5;base32Str=encodeSymbol(remaining-(next<<5))+base32Str;remaining=next}return base32Str}function uintToBase32StringMapper(num,paddingLength){const head=~~(num/1073741824);const tail=num&1073741823;return pad(smallUintToBase32StringMapper(head),paddingLength-6)+pad(smallUintToBase32StringMapper(tail),6)}function paddedUintToBase32StringMapper(paddingLength){return function padded(num){return uintToBase32StringMapper(num,paddingLength)}}function uintToBase32StringUnmapper(value3){if(typeof value3!=="string")throw new SError("Unsupported type");let accumulated=0;let power=1;for(let index2=value3.length-1;index2>=0;--index2){const char=value3[index2];const numericForChar=decodeSymbolLookupTable[char];if(numericForChar===undefined)throw new SError("Unsupported type");accumulated+=numericForChar*power;power*=32}return accumulated}var padded10Mapper=paddedUintToBase32StringMapper(10);var padded8Mapper=paddedUintToBase32StringMapper(8);function ulidMapper(parts){return padded10Mapper(parts[0])+padded8Mapper(parts[1])+padded8Mapper(parts[2])}function ulidUnmapper(value3){if(typeof value3!=="string"||value3.length!==26)throw new Error("Unsupported type");return[uintToBase32StringUnmapper(value3.slice(0,10)),uintToBase32StringUnmapper(value3.slice(10,18)),uintToBase32StringUnmapper(value3.slice(18))]}function ulid(){return tuple2(integer({min:0,max:281474976710655}),integer({min:0,max:1099511627775}),integer({min:0,max:1099511627775})).map(ulidMapper,ulidUnmapper)}function numberToPaddedEightMapper(n){return safePadStart(safeNumberToString(n,16),8,"0")}function numberToPaddedEightUnmapper(value3){if(typeof value3!=="string")throw new Error("Unsupported type");if(value3.length!==8)throw new Error("Unsupported value: invalid length");const n=parseInt(value3,16);if(value3!==numberToPaddedEightMapper(n))throw new Error("Unsupported value: invalid content");return n}function buildPaddedNumberArbitrary(min5,max5){return integer({min:min5,max:max5}).map(numberToPaddedEightMapper,numberToPaddedEightUnmapper)}function paddedEightsToUuidMapper(t){return`${t[0]}-${safeSubstring(t[1],4)}-${safeSubstring(t[1],0,4)}-${safeSubstring(t[2],0,4)}-${safeSubstring(t[2],4)}${t[3]}`}var UuidRegex=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/;function paddedEightsToUuidUnmapper(value3){if(typeof value3!=="string")throw new Error("Unsupported type");const m=UuidRegex.exec(value3);if(m===null)throw new Error("Unsupported type");return[m[1],m[3]+m[2],m[4]+safeSubstring(m[5],0,4),safeSubstring(m[5],4)]}var quickNumberToHexaString="0123456789abcdef";function buildVersionsAppliersForUuid(versions){const mapping={};const reversedMapping={};for(let index2=0;index2!==versions.length;++index2){const from=quickNumberToHexaString[index2];const to=quickNumberToHexaString[versions[index2]];mapping[from]=to;reversedMapping[to]=from}function versionsApplierMapper(value3){return mapping[value3[0]]+safeSubstring(value3,1)}function versionsApplierUnmapper(value3){if(typeof value3!=="string")throw new SError("Cannot produce non-string values");const rev=reversedMapping[value3[0]];if(rev===undefined)throw new SError("Cannot produce strings not starting by the version in hexa code");return rev+safeSubstring(value3,1)}return{versionsApplierMapper,versionsApplierUnmapper}}function assertValidVersions(versions){const found={};for(const version2 of versions){if(found[version2])throw new SError(`Version ${version2} has been requested at least twice for uuid`);found[version2]=true;if(version2<1||version2>15)throw new SError(`Version must be a value in [1-15] for uuid, but received ${version2}`);if(~~version2!==version2)throw new SError(`Version must be an integer value for uuid, but received ${version2}`)}if(versions.length===0)throw new SError(`Must provide at least one version for uuid`)}function uuid(constraints={}){const padded=buildPaddedNumberArbitrary(0,4294967295);const version2=constraints.version!==undefined?typeof constraints.version==="number"?[constraints.version]:constraints.version:[1,2,3,4,5,6,7,8];assertValidVersions(version2);const{versionsApplierMapper,versionsApplierUnmapper}=buildVersionsAppliersForUuid(version2);return tuple2(padded,buildPaddedNumberArbitrary(0,268435456*version2.length-1).map(versionsApplierMapper,versionsApplierUnmapper),buildPaddedNumberArbitrary(2147483648,3221225471),padded).map(paddedEightsToUuidMapper,paddedEightsToUuidUnmapper)}function hostUserInfo(size6){return string3({unit:getOrCreateAlphaNumericPercentArbitrary("-._~!$&'()*+,;=:"),size:size6})}function userHostPortMapper([u,h2,p]){return(u===null?"":`${u}@`)+h2+(p===null?"":`:${p}`)}function userHostPortUnmapper(value3){if(typeof value3!=="string")throw new Error("Unsupported");const atPosition=value3.indexOf("@");const user=atPosition!==-1?value3.substring(0,atPosition):null;const m=/:(\d+)$/.exec(value3);const port=m!==null?Number(m[1]):null;return[user,m!==null?value3.substring(atPosition+1,value3.length-m[1].length-1):value3.substring(atPosition+1),port]}function bracketedMapper(s){return`[${s}]`}function bracketedUnmapper(value3){if(typeof value3!=="string"||value3[0]!=="["||value3[value3.length-1]!=="]")throw new Error("Unsupported");return value3.substring(1,value3.length-1)}function webAuthority(constraints){const c=constraints||{};const size6=c.size;const hostnameArbs=[domain({size:size6}),...c.withIPv4===true?[ipV4()]:[],...c.withIPv6===true?[ipV6().map(bracketedMapper,bracketedUnmapper)]:[],...c.withIPv4Extended===true?[ipV4Extended()]:[]];return tuple2(c.withUserInfo===true?option3(hostUserInfo(size6)):constant2(null),oneof(...hostnameArbs),c.withPort===true?option3(nat(65535)):constant2(null)).map(userHostPortMapper,userHostPortUnmapper)}function buildUriQueryOrFragmentArbitrary(size6){return string3({unit:getOrCreateAlphaNumericPercentArbitrary("-._~!$&'()*+,;=:@/?"),size:size6})}function webFragments(constraints={}){return buildUriQueryOrFragmentArbitrary(constraints.size)}function webSegment(constraints={}){return string3({unit:getOrCreateAlphaNumericPercentArbitrary("-._~!$&'()*+,;=:@"),size:constraints.size})}function segmentsToPathMapper(segments){let path="";for(let index2=0;index2!==segments.length;++index2)path+="/"+segments[index2];return path}function segmentsToPathUnmapper(value3){if(typeof value3!=="string")throw new Error("Incompatible value received: type");if(value3.length!==0&&value3[0]!=="/")throw new Error("Incompatible value received: start");return safeSplice(safeSplit(value3,"/"),1)}function sqrtSize(size6){switch(size6){case"xsmall":return["xsmall","xsmall"];case"small":return["small","xsmall"];case"medium":return["small","small"];case"large":return["medium","small"];case"xlarge":return["medium","medium"]}}function buildUriPathArbitraryInternal(segmentSize,numSegmentSize){return array3(webSegment({size:segmentSize}),{size:numSegmentSize}).map(segmentsToPathMapper,segmentsToPathUnmapper)}function buildUriPathArbitrary(resolvedSize){const[segmentSize,numSegmentSize]=sqrtSize(resolvedSize);if(segmentSize===numSegmentSize)return buildUriPathArbitraryInternal(segmentSize,numSegmentSize);return oneof(buildUriPathArbitraryInternal(segmentSize,numSegmentSize),buildUriPathArbitraryInternal(numSegmentSize,segmentSize))}function webPath(constraints){return buildUriPathArbitrary(resolveSize((constraints||{}).size))}function webQueryParameters(constraints={}){return buildUriQueryOrFragmentArbitrary(constraints.size)}function partsToUrlMapper(data){const[scheme,authority,path]=data;return`${scheme}://${authority}${path}${data[3]===null?"":`?${data[3]}`}${data[4]===null?"":`#${data[4]}`}`}var UrlSplitRegex=/^([[A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)([^?#]*)(\?[A-Za-z0-9\-._~!$&'()*+,;=:@/?%]*)?(#[A-Za-z0-9\-._~!$&'()*+,;=:@/?%]*)?$/;function partsToUrlUnmapper(value3){if(typeof value3!=="string")throw new Error("Incompatible value received: type");const m=UrlSplitRegex.exec(value3);if(m===null)throw new Error("Incompatible value received");const scheme=m[1];const authority=m[2];const path=m[3];const query=m[4];const fragments=m[5];return[scheme,authority,path,query!==undefined?query.substring(1):null,fragments!==undefined?fragments.substring(1):null]}function webUrl(constraints){const c=constraints||{};const resolvedSize=resolveSize(c.size);const resolvedAuthoritySettingsSize=c.authoritySettings!==undefined&&c.authoritySettings.size!==undefined?relativeSizeToSize(c.authoritySettings.size,resolvedSize):resolvedSize;const resolvedAuthoritySettings={...c.authoritySettings,size:resolvedAuthoritySettingsSize};return tuple2(constantFrom(...c.validSchemes||["http","https"]),webAuthority(resolvedAuthoritySettings),webPath({size:resolvedSize}),c.withQueryParameters===true?option3(webQueryParameters({size:resolvedSize})):constant2(null),c.withFragments===true?option3(webFragments({size:resolvedSize})):constant2(null)).map(partsToUrlMapper,partsToUrlUnmapper)}var CommandsIterable=class CommandsIterable2{constructor(commands,metadataForReplay){this.commands=commands;this.metadataForReplay=metadataForReplay;this[cloneMethod]=function(){return new CommandsIterable2(this.commands.map((c)=>c.clone()),this.metadataForReplay)}}[Symbol.iterator](){return this.commands[Symbol.iterator]()}toString(){const serializedCommands=this.commands.filter((c)=>c.hasRan).map((c)=>c.toString()).join(",");const metadata=this.metadataForReplay();return metadata.length!==0?`${serializedCommands} /*${metadata}*/`:serializedCommands}};var CommandWrapper=class CommandWrapper2{constructor(cmd){this.cmd=cmd;this.hasRan=false;if(hasToStringMethod(cmd)){const method=cmd[toStringMethod];this[toStringMethod]=function toStringMethod2(){return method.call(cmd)}}if(hasAsyncToStringMethod(cmd)){const method=cmd[asyncToStringMethod];this[asyncToStringMethod]=function asyncToStringMethod2(){return method.call(cmd)}}}check(m){return this.cmd.check(m)}run(m,r){this.hasRan=true;return this.cmd.run(m,r)}clone(){if(hasCloneMethod(this.cmd))return new CommandWrapper2(this.cmd[cloneMethod]());return new CommandWrapper2(this.cmd)}toString(){return this.cmd.toString()}};var ReplayPath=class{static parse(replayPathStr){const[serializedCount,serializedChanges]=replayPathStr.split(":");const counts=this.parseCounts(serializedCount);const changes=this.parseChanges(serializedChanges);return this.parseOccurences(counts,changes)}static stringify(replayPath){const occurences=this.countOccurences(replayPath);return`${this.stringifyCounts(occurences)}:${this.stringifyChanges(occurences)}`}static intToB64(n){if(n<26)return String.fromCharCode(n+65);if(n<52)return String.fromCharCode(n+97-26);if(n<62)return String.fromCharCode(n+48-52);return String.fromCharCode(n===62?43:47)}static b64ToInt(c){if(c>="a")return c.charCodeAt(0)-97+26;if(c>="A")return c.charCodeAt(0)-65;if(c>="0")return c.charCodeAt(0)-48+52;return c==="+"?62:63}static countOccurences(replayPath){return replayPath.reduce((counts,cur)=>{if(counts.length===0||counts[counts.length-1].count===64||counts[counts.length-1].value!==cur)counts.push({value:cur,count:1});else counts[counts.length-1].count+=1;return counts},[])}static parseOccurences(counts,changes){const replayPath=[];for(let idx=0;idx!==counts.length;++idx){const count=counts[idx];const value3=changes[idx];for(let num=0;num!==count;++num)replayPath.push(value3)}return replayPath}static stringifyChanges(occurences){let serializedChanges="";for(let idx=0;idx<occurences.length;idx+=6){const changesInt=occurences.slice(idx,idx+6).reduceRight((prev,cur)=>(prev<<1)+(cur.value?1:0),0);serializedChanges+=this.intToB64(changesInt)}return serializedChanges}static parseChanges(serializedChanges){const changesInt=serializedChanges.split("").map((c)=>this.b64ToInt(c));const changes=[];for(let idx=0;idx!==changesInt.length;++idx){let current=changesInt[idx];for(let n=0;n!==6;++n,current>>=1)changes.push(current%2===1)}return changes}static stringifyCounts(occurences){return occurences.map(({count})=>this.intToB64(count-1)).join("")}static parseCounts(serializedCount){return serializedCount.split("").map((c)=>this.b64ToInt(c)+1)}};var CommandsArbitrary=class extends Arbitrary{constructor(commandArbs,maxGeneratedCommands,maxCommands,sourceReplayPath,disableReplayLog){super();this.sourceReplayPath=sourceReplayPath;this.disableReplayLog=disableReplayLog;this.oneCommandArb=oneof(...commandArbs).map((c)=>new CommandWrapper(c));this.lengthArb=restrictedIntegerArbitraryBuilder(0,maxGeneratedCommands,maxCommands);this.replayPath=[];this.replayPathPosition=0}metadataForReplay(){return this.disableReplayLog?"":`replayPath=${JSON.stringify(ReplayPath.stringify(this.replayPath))}`}buildValueFor(items2,shrunkOnce){const commands=items2.map((item)=>item.value_);const context4={shrunkOnce,items:items2};return new Value(new CommandsIterable(commands,()=>this.metadataForReplay()),context4)}generate(mrng){const sizeValue=this.lengthArb.generate(mrng,undefined).value;const items2=Array(sizeValue);for(let idx=0;idx!==sizeValue;++idx)items2[idx]=this.oneCommandArb.generate(mrng,undefined);this.replayPathPosition=0;return this.buildValueFor(items2,false)}canShrinkWithoutContext(_value){return false}filterOnExecution(itemsRaw){const items2=[];for(const c of itemsRaw)if(c.value_.hasRan){this.replayPath.push(true);items2.push(c)}else this.replayPath.push(false);return items2}filterOnReplay(itemsRaw){return itemsRaw.filter((c,idx)=>{const state=this.replayPath[this.replayPathPosition+idx];if(state===undefined)throw new Error(`Too short replayPath`);if(!state&&c.value_.hasRan)throw new Error(`Mismatch between replayPath and real execution`);return state})}filterForShrinkImpl(itemsRaw){if(this.replayPathPosition===0)this.replayPath=this.sourceReplayPath!==null?ReplayPath.parse(this.sourceReplayPath):[];const items2=this.replayPathPosition<this.replayPath.length?this.filterOnReplay(itemsRaw):this.filterOnExecution(itemsRaw);this.replayPathPosition+=itemsRaw.length;return items2}shrink(_value,context4){if(context4===undefined)return Stream.nil();const safeContext=context4;const shrunkOnce=safeContext.shrunkOnce;const itemsRaw=safeContext.items;const items2=this.filterForShrinkImpl(itemsRaw);if(items2.length===0)return Stream.nil();const rootShrink=shrunkOnce?Stream.nil():new Stream([[]][Symbol.iterator]());const nextShrinks=[];for(let numToKeep=0;numToKeep!==items2.length;++numToKeep)nextShrinks.push(makeLazy2(()=>{const fixedStart=items2.slice(0,numToKeep);return this.lengthArb.shrink(items2.length-1-numToKeep,undefined).map((l)=>fixedStart.concat(items2.slice(items2.length-(l.value+1))))}));for(let itemAt=0;itemAt!==items2.length;++itemAt)nextShrinks.push(makeLazy2(()=>this.oneCommandArb.shrink(items2[itemAt].value_,items2[itemAt].context).map((v)=>items2.slice(0,itemAt).concat([v],items2.slice(itemAt+1)))));return rootShrink.join(...nextShrinks).map((shrinkables)=>{return this.buildValueFor(shrinkables.map((c)=>new Value(c.value_.clone(),c.context)),true)})}};function commands(commandArbs,constraints={}){const{size:size6,maxCommands=MaxLengthUpperBound,disableReplayLog=false,replayPath=null}=constraints;return new CommandsArbitrary(commandArbs,maxGeneratedLengthFromSizeForArbitrary(size6,0,maxCommands,constraints.maxCommands!==undefined),maxCommands,replayPath,disableReplayLog)}var ScheduledCommand=class{constructor(s,cmd){this.s=s;this.cmd=cmd}async check(m){let error=null;let checkPassed=false;if((await this.s.scheduleSequence([{label:`check@${this.cmd.toString()}`,builder:async()=>{try{checkPassed=await Promise.resolve(this.cmd.check(m))}catch(err){error=err;throw err}}}]).task).faulty)throw error;return checkPassed}async run(m,r){let error=null;if((await this.s.scheduleSequence([{label:`run@${this.cmd.toString()}`,builder:async()=>{try{await this.cmd.run(m,r)}catch(err){error=err;throw err}}}]).task).faulty)throw error}};var scheduleCommands=function*(s,cmds){for(const cmd of cmds)yield new ScheduledCommand(s,cmd)};var genericModelRun=(s,cmds,initialValue,runCmd,then)=>{return s.then((o)=>{const{model,real}=o;let state=initialValue;for(const c of cmds)state=then(state,()=>{return runCmd(c,model,real)});return state})};var internalModelRun=(s,cmds)=>{const then=(_p,c)=>c();const setupProducer={then:(fun)=>{fun(s())}};const runSync3=(cmd,m,r)=>{if(cmd.check(m))cmd.run(m,r)};return genericModelRun(setupProducer,cmds,undefined,runSync3,then)};var isAsyncSetup=(s)=>{return typeof s.then==="function"};var internalAsyncModelRun=async(s,cmds,defaultPromise=Promise.resolve())=>{const then=(p,c)=>p.then(c);const setupProducer={then:(fun)=>{const out=s();if(isAsyncSetup(out))return out.then(fun);else return fun(out)}};const runAsync=async(cmd,m,r)=>{if(await cmd.check(m))await cmd.run(m,r)};return await genericModelRun(setupProducer,cmds,defaultPromise,runAsync,then)};function modelRun(s,cmds){internalModelRun(s,cmds)}async function asyncModelRun(s,cmds){await internalAsyncModelRun(s,cmds)}async function scheduledModelRun(scheduler,s,cmds){const scheduledCommands=scheduleCommands(scheduler,cmds);const out=internalAsyncModelRun(s,scheduledCommands,scheduler.schedule(Promise.resolve(),"startModel"));await scheduler.waitFor(out);await scheduler.waitAll()}var defaultSchedulerAct=(f)=>f();var SchedulerImplem=class SchedulerImplem2{constructor(act,taskSelector){this.act=act;this.taskSelector=taskSelector;this.lastTaskId=0;this.sourceTaskSelector=taskSelector.clone();this.scheduledTasks=[];this.triggeredTasks=[];this.scheduledWatchers=[];this[cloneMethod]=function(){return new SchedulerImplem2(this.act,this.sourceTaskSelector)}}static buildLog(reportItem){return`[task\${${reportItem.taskId}}] ${reportItem.label.length!==0?`${reportItem.schedulingType}::${reportItem.label}`:reportItem.schedulingType} ${reportItem.status}${reportItem.outputValue!==undefined?` with value ${escapeForTemplateString(reportItem.outputValue)}`:""}`}log(schedulingType,taskId,label,metadata,status,data){this.triggeredTasks.push({status,schedulingType,taskId,label,metadata,outputValue:data!==undefined?stringify(data):undefined})}scheduleInternal(schedulingType,label,task,metadata,customAct,thenTaskToBeAwaited){const taskId=++this.lastTaskId;let trigger=undefined;const scheduledPromise=new Promise((resolve4,reject)=>{trigger=()=>{const promise3=Promise.resolve(thenTaskToBeAwaited!==undefined?task.then(()=>thenTaskToBeAwaited()):task);promise3.then((data)=>{this.log(schedulingType,taskId,label,metadata,"resolved",data);resolve4(data)},(err)=>{this.log(schedulingType,taskId,label,metadata,"rejected",err);reject(err)});return promise3}});this.scheduledTasks.push({original:task,trigger,schedulingType,taskId,label,metadata,customAct});if(this.scheduledWatchers.length!==0)this.scheduledWatchers[0]();return scheduledPromise}schedule(task,label,metadata,customAct){return this.scheduleInternal("promise",label||"",task,metadata,customAct||defaultSchedulerAct)}scheduleFunction(asyncFunction,customAct){return(...args2)=>this.scheduleInternal("function",`${asyncFunction.name}(${args2.map(stringify).join(",")})`,asyncFunction(...args2),undefined,customAct||defaultSchedulerAct)}scheduleSequence(sequenceBuilders,customAct){const status={done:false,faulty:false};const dummyResolvedPromise={then:(f)=>f()};let resolveSequenceTask=()=>{};const sequenceTask=new Promise((resolve4)=>{resolveSequenceTask=()=>resolve4({done:status.done,faulty:status.faulty})});const onFaultyItemNoThrow=()=>{status.faulty=true;resolveSequenceTask()};const onDone=()=>{status.done=true;resolveSequenceTask()};const registerNextBuilder=(index2,previous)=>{if(index2>=sequenceBuilders.length){previous.then(onDone,onFaultyItemNoThrow);return}previous.then(()=>{const item=sequenceBuilders[index2];const[builder,label,metadata]=typeof item==="function"?[item,item.name,undefined]:[item.builder,item.label,item.metadata];const scheduled=this.scheduleInternal("sequence",label,dummyResolvedPromise,metadata,customAct||defaultSchedulerAct,()=>builder());registerNextBuilder(index2+1,scheduled)},onFaultyItemNoThrow)};registerNextBuilder(0,dummyResolvedPromise);return Object.assign(status,{task:sequenceTask})}count(){return this.scheduledTasks.length}internalWaitOne(){if(this.scheduledTasks.length===0)throw new Error("No task scheduled");const taskIndex=this.taskSelector.nextTaskIndex(this.scheduledTasks);const[scheduledTask]=this.scheduledTasks.splice(taskIndex,1);return scheduledTask.customAct(()=>{return scheduledTask.trigger().catch((_err)=>{})})}waitOne(customAct){const waitAct=customAct||defaultSchedulerAct;return this.act(()=>waitAct(()=>this.internalWaitOne()))}async waitAll(customAct){while(this.scheduledTasks.length>0)await this.waitOne(customAct)}async internalWaitFor(unscheduledTask,options){let taskResolved=false;const customAct=options.customAct;const onWaitStart=options.onWaitStart;const onWaitIdle=options.onWaitIdle;const launchAwaiterOnInit=options.launchAwaiterOnInit;let resolveFinal=undefined;let rejectFinal=undefined;let awaiterTicks=0;let awaiterPromise=null;let awaiterScheduledTaskPromise=null;const awaiter=async()=>{awaiterTicks=50;for(awaiterTicks=50;!taskResolved&&awaiterTicks>0;--awaiterTicks)await Promise.resolve();if(!taskResolved&&this.scheduledTasks.length>0){if(onWaitStart!==undefined)onWaitStart();awaiterScheduledTaskPromise=this.waitOne(customAct);return awaiterScheduledTaskPromise.then(()=>{awaiterScheduledTaskPromise=null;return awaiter()},(err)=>{awaiterScheduledTaskPromise=null;taskResolved=true;rejectFinal(err);throw err})}if(!taskResolved&&onWaitIdle!==undefined)onWaitIdle();awaiterPromise=null};const handleNotified=()=>{if(awaiterPromise!==null){awaiterTicks=51;return}awaiterPromise=awaiter().catch(()=>{})};const clearAndReplaceWatcher=()=>{const handleNotifiedIndex=this.scheduledWatchers.indexOf(handleNotified);if(handleNotifiedIndex!==-1)this.scheduledWatchers.splice(handleNotifiedIndex,1);if(handleNotifiedIndex===0&&this.scheduledWatchers.length!==0)this.scheduledWatchers[0]()};const finalTask=new Promise((resolve4,reject)=>{resolveFinal=(value3)=>{clearAndReplaceWatcher();resolve4(value3)};rejectFinal=(error)=>{clearAndReplaceWatcher();reject(error)}});unscheduledTask.then((ret)=>{taskResolved=true;if(awaiterScheduledTaskPromise===null)resolveFinal(ret);else awaiterScheduledTaskPromise.then(()=>resolveFinal(ret),(error)=>rejectFinal(error))},(err)=>{taskResolved=true;if(awaiterScheduledTaskPromise===null)rejectFinal(err);else awaiterScheduledTaskPromise.then(()=>rejectFinal(err),()=>rejectFinal(err))});if((this.scheduledTasks.length>0||launchAwaiterOnInit)&&this.scheduledWatchers.length===0)handleNotified();this.scheduledWatchers.push(handleNotified);return finalTask}waitNext(count,customAct){let resolver=undefined;let remaining=count;const awaited=remaining<=0?Promise.resolve():new Promise((r)=>{resolver=()=>{if(--remaining<=0)r()}});return this.internalWaitFor(awaited,{customAct,onWaitStart:resolver,onWaitIdle:undefined,launchAwaiterOnInit:false})}waitIdle(customAct){let resolver=undefined;const awaited=new Promise((r)=>resolver=r);return this.internalWaitFor(awaited,{customAct,onWaitStart:undefined,onWaitIdle:resolver,launchAwaiterOnInit:true})}waitFor(unscheduledTask,customAct){return this.internalWaitFor(unscheduledTask,{customAct,onWaitStart:undefined,onWaitIdle:undefined,launchAwaiterOnInit:false})}report(){return[...this.triggeredTasks,...this.scheduledTasks.map((t)=>({status:"pending",schedulingType:t.schedulingType,taskId:t.taskId,label:t.label,metadata:t.metadata}))]}toString(){return"schedulerFor()`\n"+this.report().map(SchedulerImplem2.buildLog).map((log2)=>`-> ${log2}`).join(`
|
|
222
222
|
`)+"`"}};function buildNextTaskIndex$1(ordering){let numTasks=0;return{clone:()=>buildNextTaskIndex$1(ordering),nextTaskIndex:(scheduledTasks)=>{if(ordering.length<=numTasks)throw new Error(`Invalid schedulerFor defined: too many tasks have been scheduled`);const taskIndex=scheduledTasks.findIndex((t)=>t.taskId===ordering[numTasks]);if(taskIndex===-1)throw new Error(`Invalid schedulerFor defined: unable to find next task`);++numTasks;return taskIndex}}}function buildSchedulerFor(act,ordering){return new SchedulerImplem(act,buildNextTaskIndex$1(ordering))}function buildNextTaskIndex(mrng){const clonedMrng=mrng.clone();return{clone:()=>buildNextTaskIndex(clonedMrng),nextTaskIndex:(scheduledTasks)=>{return mrng.nextInt(0,scheduledTasks.length-1)}}}var SchedulerArbitrary=class extends Arbitrary{constructor(act){super();this.act=act}generate(mrng,_biasFactor){return new Value(new SchedulerImplem(this.act,buildNextTaskIndex(mrng.clone())),undefined)}canShrinkWithoutContext(_value){return false}shrink(_value,_context){return Stream.nil()}};function scheduler(constraints){const{act=(f)=>f()}=constraints||{};return new SchedulerArbitrary(act)}function schedulerFor(customOrderingOrConstraints,constraintsOrUndefined){const{act=(f)=>f()}=Array.isArray(customOrderingOrConstraints)?constraintsOrUndefined||{}:customOrderingOrConstraints||{};if(Array.isArray(customOrderingOrConstraints))return buildSchedulerFor(act,customOrderingOrConstraints);return function(_strs,...ordering){return buildSchedulerFor(act,ordering)}}function bigInt64Array(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,SBigInt2("-9223372036854775808"),SBigInt2("9223372036854775807"),SBigInt64Array,bigInt2)}function bigUint64Array(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,SBigInt2(0),SBigInt2("18446744073709551615"),SBigUint64Array,bigInt2)}function noSuchValue(_value,returnedValue){return returnedValue}var safeMathFloor=Math.floor;var safeMathMin=Math.min;function clampRegexAstInternal(astNode,maxLength){switch(astNode.type){case"Char":return{astNode,minLength:1};case"Repetition":switch(astNode.quantifier.kind){case"*":{const clamped=clampRegexAstInternal(astNode.expression,maxLength);return{astNode:{type:"Repetition",quantifier:{...astNode.quantifier,kind:"Range",from:0,to:maxLength},expression:clamped.astNode},minLength:0}}case"+":{const clamped=clampRegexAstInternal(astNode.expression,maxLength);const scaledClampedMinLength=clamped.minLength>1?clamped.minLength:1;return{astNode:{type:"Repetition",quantifier:{...astNode.quantifier,kind:"Range",from:1,to:safeMathFloor(maxLength/scaledClampedMinLength)},expression:clamped.astNode},minLength:clamped.minLength}}case"?":{const clamped=clampRegexAstInternal(astNode.expression,maxLength);if(maxLength<clamped.minLength)return{astNode:{type:"Repetition",quantifier:{...astNode.quantifier,kind:"Range",from:0,to:0},expression:clamped.astNode},minLength:0};return{astNode:{...astNode,expression:clamped.astNode},minLength:0}}case"Range":{const scaledMaxLength=astNode.quantifier.from>1?safeMathFloor(maxLength/astNode.quantifier.from):maxLength;const clamped=clampRegexAstInternal(astNode.expression,scaledMaxLength);const scaledClampedMinLength=clamped.minLength>1?clamped.minLength:1;if(astNode.quantifier.to===undefined||astNode.quantifier.to*scaledClampedMinLength>maxLength)return{astNode:{type:"Repetition",quantifier:{...astNode.quantifier,kind:"Range",to:safeMathFloor(maxLength/scaledClampedMinLength)},expression:clamped.astNode},minLength:astNode.quantifier.from*clamped.minLength};return{astNode:{...astNode,expression:clamped.astNode},minLength:astNode.quantifier.from*clamped.minLength}}default:return noSuchValue(astNode.quantifier,{astNode,minLength:0})}case"Quantifier":return{astNode,minLength:0};case"Alternative":{let totalMinLength=0;const extendedClampeds=[];for(let index2=0;index2!==astNode.expressions.length;++index2){const temporaryAllowance=maxLength-totalMinLength;const clamped=clampRegexAstInternal(astNode.expressions[index2],temporaryAllowance);totalMinLength+=clamped.minLength;safePush(extendedClampeds,{value:clamped,allowance:temporaryAllowance})}const refinedExpressions=[];for(let index2=0;index2!==extendedClampeds.length;++index2){const current=extendedClampeds[index2].value;const pastAllowance=extendedClampeds[index2].allowance;const allowance=maxLength-totalMinLength+current.minLength;safePush(refinedExpressions,(allowance!==pastAllowance?clampRegexAstInternal(current.astNode,allowance):current).astNode)}return{astNode:{...astNode,expressions:refinedExpressions},minLength:totalMinLength}}case"CharacterClass":return{astNode,minLength:1};case"ClassRange":return{astNode,minLength:1};case"Group":{const clamped=clampRegexAstInternal(astNode.expression,maxLength);return{astNode:{...astNode,expression:clamped.astNode},minLength:clamped.minLength}}case"Disjunction":{if(astNode.left===null){if(astNode.right===null)return{astNode,minLength:0};const clampedRight2=clampRegexAstInternal(astNode.right,maxLength);const refinedRight=clampedRight2.minLength>maxLength?null:clampedRight2.astNode;return{astNode:{...astNode,left:null,right:refinedRight},minLength:0}}if(astNode.right===null){const clampLeft=clampRegexAstInternal(astNode.left,maxLength);const refinedLeft=clampLeft.minLength>maxLength?null:clampLeft.astNode;return{astNode:{...astNode,left:refinedLeft,right:null},minLength:0}}const clampedLeft=clampRegexAstInternal(astNode.left,maxLength);const clampedRight=clampRegexAstInternal(astNode.right,maxLength);if(clampedLeft.minLength>maxLength)return clampedRight;if(clampedRight.minLength>maxLength)return clampedLeft;return{astNode:{...astNode,left:clampedLeft.astNode,right:clampedRight.astNode},minLength:safeMathMin(clampedLeft.minLength,clampedRight.minLength)}}case"Assertion":return{astNode,minLength:0};case"Backreference":return{astNode,minLength:0};case"UnicodeProperty":return{astNode,minLength:1}}}function clampRegexAst(astNode,maxLength){return clampRegexAstInternal(astNode,maxLength).astNode}function raiseUnsupportedASTNode$1(astNode){return new Error(`Unsupported AST node! Received: ${stringify(astNode)}`)}function addMissingDotStarTraversalAddMissing(astNode,isFirst,isLast){if(!isFirst&&!isLast)return astNode;const traversalResults={hasStart:false,hasEnd:false};const revampedNode=addMissingDotStarTraversal(astNode,isFirst,isLast,traversalResults);const missingStart=isFirst&&!traversalResults.hasStart;const missingEnd=isLast&&!traversalResults.hasEnd;if(!missingStart&&!missingEnd)return revampedNode;const expressions=[];if(missingStart){expressions.push({type:"Assertion",kind:"^"});expressions.push({type:"Repetition",quantifier:{type:"Quantifier",kind:"*",greedy:true},expression:{type:"Char",kind:"meta",symbol:".",value:".",codePoint:NaN}})}expressions.push(revampedNode);if(missingEnd){expressions.push({type:"Repetition",quantifier:{type:"Quantifier",kind:"*",greedy:true},expression:{type:"Char",kind:"meta",symbol:".",value:".",codePoint:NaN}});expressions.push({type:"Assertion",kind:"$"})}return{type:"Group",capturing:false,expression:{type:"Alternative",expressions}}}function addMissingDotStarTraversal(astNode,isFirst,isLast,traversalResults){switch(astNode.type){case"Char":return astNode;case"Repetition":return astNode;case"Quantifier":throw new Error(`Wrongly defined AST tree, Quantifier nodes not supposed to be scanned!`);case"Alternative":traversalResults.hasStart=true;traversalResults.hasEnd=true;return{...astNode,expressions:astNode.expressions.map((node,index2)=>addMissingDotStarTraversalAddMissing(node,isFirst&&index2===0,isLast&&index2===astNode.expressions.length-1))};case"CharacterClass":return astNode;case"ClassRange":return astNode;case"Group":return{...astNode,expression:addMissingDotStarTraversal(astNode.expression,isFirst,isLast,traversalResults)};case"Disjunction":traversalResults.hasStart=true;traversalResults.hasEnd=true;return{...astNode,left:astNode.left!==null?addMissingDotStarTraversalAddMissing(astNode.left,isFirst,isLast):null,right:astNode.right!==null?addMissingDotStarTraversalAddMissing(astNode.right,isFirst,isLast):null};case"Assertion":if(astNode.kind==="^"||astNode.kind==="Lookahead"){traversalResults.hasStart=true;return astNode}else if(astNode.kind==="$"||astNode.kind==="Lookbehind"){traversalResults.hasEnd=true;return astNode}else throw new Error(`Assertions of kind ${astNode.kind} not implemented yet!`);case"Backreference":return astNode;case"UnicodeProperty":return astNode;default:throw raiseUnsupportedASTNode$1(astNode)}}function addMissingDotStar(astNode){return addMissingDotStarTraversalAddMissing(astNode,true,true)}function charSizeAt(text,pos){return text[pos]>="\uD800"&&text[pos]<="\uDBFF"&&text[pos+1]>="\uDC00"&&text[pos+1]<="\uDFFF"?2:1}function isHexaDigit(char){return char>="0"&&char<="9"||char>="a"&&char<="f"||char>="A"&&char<="F"}function isDigit$1(char){return char>="0"&&char<="9"}function squaredBracketBlockContentEndFrom(text,from){for(let index2=from;index2!==text.length;++index2){const char=text[index2];if(char==="\\")index2+=1;else if(char==="]")return index2}throw new Error(`Missing closing ']'`)}function parenthesisBlockContentEndFrom(text,from){let numExtraOpened=0;for(let index2=from;index2!==text.length;++index2){const char=text[index2];if(char==="\\")index2+=1;else if(char===")"){if(numExtraOpened===0)return index2;numExtraOpened-=1}else if(char==="[")index2=squaredBracketBlockContentEndFrom(text,index2);else if(char==="(")numExtraOpened+=1}throw new Error(`Missing closing ')'`)}function curlyBracketBlockContentEndFrom(text,from){let foundComma=false;for(let index2=from;index2!==text.length;++index2){const char=text[index2];if(isDigit$1(char)){}else if(from===index2)return-1;else if(char===","){if(foundComma)return-1;foundComma=true}else if(char==="}")return index2;else return-1}return-1}function blockEndFrom(text,from,unicodeMode,mode){switch(text[from]){case"[":if(mode===1)return from+1;return squaredBracketBlockContentEndFrom(text,from+1)+1;case"{":{if(mode===1)return from+1;const foundEnd=curlyBracketBlockContentEndFrom(text,from+1);if(foundEnd===-1)return from+1;return foundEnd+1}case"(":if(mode===1)return from+1;return parenthesisBlockContentEndFrom(text,from+1)+1;case"]":case"}":case")":return from+1;case"\\":{const next1=text[from+1];switch(next1){case"x":if(isHexaDigit(text[from+2])&&isHexaDigit(text[from+3]))return from+4;throw new Error(`Unexpected token '${text.substring(from,from+4)}' found`);case"u":if(text[from+2]==="{"){if(!unicodeMode)return from+2;if(text[from+4]==="}"){if(isHexaDigit(text[from+3]))return from+5;throw new Error(`Unexpected token '${text.substring(from,from+5)}' found`)}if(text[from+5]==="}"){if(isHexaDigit(text[from+3])&&isHexaDigit(text[from+4]))return from+6;throw new Error(`Unexpected token '${text.substring(from,from+6)}' found`)}if(text[from+6]==="}"){if(isHexaDigit(text[from+3])&&isHexaDigit(text[from+4])&&isHexaDigit(text[from+5]))return from+7;throw new Error(`Unexpected token '${text.substring(from,from+7)}' found`)}if(text[from+7]==="}"){if(isHexaDigit(text[from+3])&&isHexaDigit(text[from+4])&&isHexaDigit(text[from+5])&&isHexaDigit(text[from+6]))return from+8;throw new Error(`Unexpected token '${text.substring(from,from+8)}' found`)}if(text[from+8]==="}"&&isHexaDigit(text[from+3])&&isHexaDigit(text[from+4])&&isHexaDigit(text[from+5])&&isHexaDigit(text[from+6])&&isHexaDigit(text[from+7]))return from+9;throw new Error(`Unexpected token '${text.substring(from,from+9)}' found`)}if(isHexaDigit(text[from+2])&&isHexaDigit(text[from+3])&&isHexaDigit(text[from+4])&&isHexaDigit(text[from+5]))return from+6;throw new Error(`Unexpected token '${text.substring(from,from+6)}' found`);case"p":case"P":{if(!unicodeMode)return from+2;let subIndex=from+2;for(;subIndex<text.length&&text[subIndex]!=="}";subIndex+=text[subIndex]==="\\"?2:1);if(text[subIndex]!=="}")throw new Error(`Invalid \\P definition`);return subIndex+1}case"k":{let subIndex=from+2;for(;subIndex<text.length&&text[subIndex]!==">";++subIndex);if(text[subIndex]!==">"){if(!unicodeMode)return from+2;throw new Error(`Invalid \\k definition`)}return subIndex+1}default:if(isDigit$1(next1)){const maxIndex=unicodeMode?text.length:Math.min(from+4,text.length);let subIndex=from+2;for(;subIndex<maxIndex&&isDigit$1(text[subIndex]);++subIndex);return subIndex}return from+(unicodeMode?charSizeAt(text,from+1):1)+1}}default:return from+(unicodeMode?charSizeAt(text,from):1)}}function readFrom(text,from,unicodeMode,mode){const to=blockEndFrom(text,from,unicodeMode,mode);return text.substring(from,to)}var NON_BINARY_ALIASES_TO_PROP_NAMES={gc:"General_Category",sc:"Script",scx:"Script_Extensions"};var BINARY_PROP_NAMES_TO_ALIASES={ASCII:"ASCII",ASCII_Hex_Digit:"AHex",Alphabetic:"Alpha",Any:"Any",Assigned:"Assigned",Bidi_Control:"Bidi_C",Bidi_Mirrored:"Bidi_M",Case_Ignorable:"CI",Cased:"Cased",Changes_When_Casefolded:"CWCF",Changes_When_Casemapped:"CWCM",Changes_When_Lowercased:"CWL",Changes_When_NFKC_Casefolded:"CWKCF",Changes_When_Titlecased:"CWT",Changes_When_Uppercased:"CWU",Dash:"Dash",Default_Ignorable_Code_Point:"DI",Deprecated:"Dep",Diacritic:"Dia",Emoji:"Emoji",Emoji_Component:"Emoji_Component",Emoji_Modifier:"Emoji_Modifier",Emoji_Modifier_Base:"Emoji_Modifier_Base",Emoji_Presentation:"Emoji_Presentation",Extended_Pictographic:"Extended_Pictographic",Extender:"Ext",Grapheme_Base:"Gr_Base",Grapheme_Extend:"Gr_Ext",Hex_Digit:"Hex",IDS_Binary_Operator:"IDSB",IDS_Trinary_Operator:"IDST",ID_Continue:"IDC",ID_Start:"IDS",Ideographic:"Ideo",Join_Control:"Join_C",Logical_Order_Exception:"LOE",Lowercase:"Lower",Math:"Math",Noncharacter_Code_Point:"NChar",Pattern_Syntax:"Pat_Syn",Pattern_White_Space:"Pat_WS",Quotation_Mark:"QMark",Radical:"Radical",Regional_Indicator:"RI",Sentence_Terminal:"STerm",Soft_Dotted:"SD",Terminal_Punctuation:"Term",Unified_Ideograph:"UIdeo",Uppercase:"Upper",Variation_Selector:"VS",White_Space:"space",XID_Continue:"XIDC",XID_Start:"XIDS"};var BINARY_ALIASES_TO_PROP_NAMES=inverseMap(BINARY_PROP_NAMES_TO_ALIASES);var GENERAL_CATEGORY_VALUE_TO_ALIASES={Cased_Letter:"LC",Close_Punctuation:"Pe",Connector_Punctuation:"Pc",Control:["Cc","cntrl"],Currency_Symbol:"Sc",Dash_Punctuation:"Pd",Decimal_Number:["Nd","digit"],Enclosing_Mark:"Me",Final_Punctuation:"Pf",Format:"Cf",Initial_Punctuation:"Pi",Letter:"L",Letter_Number:"Nl",Line_Separator:"Zl",Lowercase_Letter:"Ll",Mark:["M","Combining_Mark"],Math_Symbol:"Sm",Modifier_Letter:"Lm",Modifier_Symbol:"Sk",Nonspacing_Mark:"Mn",Number:"N",Open_Punctuation:"Ps",Other:"C",Other_Letter:"Lo",Other_Number:"No",Other_Punctuation:"Po",Other_Symbol:"So",Paragraph_Separator:"Zp",Private_Use:"Co",Punctuation:["P","punct"],Separator:"Z",Space_Separator:"Zs",Spacing_Mark:"Mc",Surrogate:"Cs",Symbol:"S",Titlecase_Letter:"Lt",Unassigned:"Cn",Uppercase_Letter:"Lu"};var GENERAL_CATEGORY_VALUE_ALIASES_TO_VALUES=inverseMap(GENERAL_CATEGORY_VALUE_TO_ALIASES);var SCRIPT_VALUE_TO_ALIASES={Adlam:"Adlm",Ahom:"Ahom",Anatolian_Hieroglyphs:"Hluw",Arabic:"Arab",Armenian:"Armn",Avestan:"Avst",Balinese:"Bali",Bamum:"Bamu",Bassa_Vah:"Bass",Batak:"Batk",Bengali:"Beng",Bhaiksuki:"Bhks",Bopomofo:"Bopo",Brahmi:"Brah",Braille:"Brai",Buginese:"Bugi",Buhid:"Buhd",Canadian_Aboriginal:"Cans",Carian:"Cari",Caucasian_Albanian:"Aghb",Chakma:"Cakm",Cham:"Cham",Cherokee:"Cher",Common:"Zyyy",Coptic:["Copt","Qaac"],Cuneiform:"Xsux",Cypriot:"Cprt",Cyrillic:"Cyrl",Deseret:"Dsrt",Devanagari:"Deva",Dogra:"Dogr",Duployan:"Dupl",Egyptian_Hieroglyphs:"Egyp",Elbasan:"Elba",Ethiopic:"Ethi",Georgian:"Geor",Glagolitic:"Glag",Gothic:"Goth",Grantha:"Gran",Greek:"Grek",Gujarati:"Gujr",Gunjala_Gondi:"Gong",Gurmukhi:"Guru",Han:"Hani",Hangul:"Hang",Hanifi_Rohingya:"Rohg",Hanunoo:"Hano",Hatran:"Hatr",Hebrew:"Hebr",Hiragana:"Hira",Imperial_Aramaic:"Armi",Inherited:["Zinh","Qaai"],Inscriptional_Pahlavi:"Phli",Inscriptional_Parthian:"Prti",Javanese:"Java",Kaithi:"Kthi",Kannada:"Knda",Katakana:"Kana",Kayah_Li:"Kali",Kharoshthi:"Khar",Khmer:"Khmr",Khojki:"Khoj",Khudawadi:"Sind",Lao:"Laoo",Latin:"Latn",Lepcha:"Lepc",Limbu:"Limb",Linear_A:"Lina",Linear_B:"Linb",Lisu:"Lisu",Lycian:"Lyci",Lydian:"Lydi",Mahajani:"Mahj",Makasar:"Maka",Malayalam:"Mlym",Mandaic:"Mand",Manichaean:"Mani",Marchen:"Marc",Medefaidrin:"Medf",Masaram_Gondi:"Gonm",Meetei_Mayek:"Mtei",Mende_Kikakui:"Mend",Meroitic_Cursive:"Merc",Meroitic_Hieroglyphs:"Mero",Miao:"Plrd",Modi:"Modi",Mongolian:"Mong",Mro:"Mroo",Multani:"Mult",Myanmar:"Mymr",Nabataean:"Nbat",New_Tai_Lue:"Talu",Newa:"Newa",Nko:"Nkoo",Nushu:"Nshu",Ogham:"Ogam",Ol_Chiki:"Olck",Old_Hungarian:"Hung",Old_Italic:"Ital",Old_North_Arabian:"Narb",Old_Permic:"Perm",Old_Persian:"Xpeo",Old_Sogdian:"Sogo",Old_South_Arabian:"Sarb",Old_Turkic:"Orkh",Oriya:"Orya",Osage:"Osge",Osmanya:"Osma",Pahawh_Hmong:"Hmng",Palmyrene:"Palm",Pau_Cin_Hau:"Pauc",Phags_Pa:"Phag",Phoenician:"Phnx",Psalter_Pahlavi:"Phlp",Rejang:"Rjng",Runic:"Runr",Samaritan:"Samr",Saurashtra:"Saur",Sharada:"Shrd",Shavian:"Shaw",Siddham:"Sidd",SignWriting:"Sgnw",Sinhala:"Sinh",Sogdian:"Sogd",Sora_Sompeng:"Sora",Soyombo:"Soyo",Sundanese:"Sund",Syloti_Nagri:"Sylo",Syriac:"Syrc",Tagalog:"Tglg",Tagbanwa:"Tagb",Tai_Le:"Tale",Tai_Tham:"Lana",Tai_Viet:"Tavt",Takri:"Takr",Tamil:"Taml",Tangut:"Tang",Telugu:"Telu",Thaana:"Thaa",Thai:"Thai",Tibetan:"Tibt",Tifinagh:"Tfng",Tirhuta:"Tirh",Ugaritic:"Ugar",Vai:"Vaii",Warang_Citi:"Wara",Yi:"Yiii",Zanabazar_Square:"Zanb"};var SCRIPT_VALUE_ALIASES_TO_VALUES=inverseMap(SCRIPT_VALUE_TO_ALIASES);function inverseMap(data){const inverse={};for(const name of Object.keys(data)){const value3=data[name];if(Array.isArray(value3))for(let i=0;i!==value3.length;++i)inverse[value3[i]]=name;else inverse[value3]=name}return inverse}function isGeneralCategoryValue(value3){return value3 in GENERAL_CATEGORY_VALUE_TO_ALIASES||value3 in GENERAL_CATEGORY_VALUE_ALIASES_TO_VALUES}function isBinaryPropertyName(name){return name in BINARY_PROP_NAMES_TO_ALIASES||name in BINARY_ALIASES_TO_PROP_NAMES}function getCanonicalName(name){if(name in NON_BINARY_ALIASES_TO_PROP_NAMES)return NON_BINARY_ALIASES_TO_PROP_NAMES[name];if(name in BINARY_ALIASES_TO_PROP_NAMES)return BINARY_ALIASES_TO_PROP_NAMES[name];if(name in BINARY_PROP_NAMES_TO_ALIASES||name==="General_Category"||name==="Script"||name==="Script_Extensions")return name;throw new Error(`Unknown Unicode property name: ${name}`)}function getCanonicalValue(value3){if(value3 in GENERAL_CATEGORY_VALUE_ALIASES_TO_VALUES)return GENERAL_CATEGORY_VALUE_ALIASES_TO_VALUES[value3];if(value3 in SCRIPT_VALUE_ALIASES_TO_VALUES)return SCRIPT_VALUE_ALIASES_TO_VALUES[value3];if(value3 in BINARY_ALIASES_TO_PROP_NAMES)return BINARY_ALIASES_TO_PROP_NAMES[value3];if(value3 in GENERAL_CATEGORY_VALUE_TO_ALIASES||value3 in SCRIPT_VALUE_TO_ALIASES||value3 in BINARY_PROP_NAMES_TO_ALIASES)return value3;throw new Error(`Unknown Unicode property value: ${value3}`)}function resolveUnicodeProperty(propertySpec,negative){const equalIndex=propertySpec.indexOf("=");if(equalIndex!==-1){const name=propertySpec.substring(0,equalIndex);const value3=propertySpec.substring(equalIndex+1);return{type:"UnicodeProperty",name,value:value3,negative,shorthand:false,binary:false,canonicalName:getCanonicalName(name),canonicalValue:getCanonicalValue(value3)}}if(isGeneralCategoryValue(propertySpec))return{type:"UnicodeProperty",name:"General_Category",value:propertySpec,negative,shorthand:true,binary:false,canonicalName:"General_Category",canonicalValue:getCanonicalValue(propertySpec)};if(isBinaryPropertyName(propertySpec)){const canonicalName=getCanonicalName(propertySpec);return{type:"UnicodeProperty",name:propertySpec,value:propertySpec,negative,shorthand:false,binary:true,canonicalName,canonicalValue:canonicalName}}throw new Error(`Invalid Unicode property: ${propertySpec}`)}var safeStringFromCodePoint$2=String.fromCodePoint;function safePop(tokens){const previous=tokens.pop();if(previous===undefined)throw new Error("Unable to extract token preceeding the currently parsed one");return previous}function isDigit(char){return char>="0"&&char<="9"}function simpleChar(char,escaped){return{type:"Char",kind:"simple",symbol:char,value:char,codePoint:char.codePointAt(0)||-1,escaped}}function metaEscapedChar(block,symbol4){return{type:"Char",kind:"meta",symbol:symbol4,value:block,codePoint:symbol4.codePointAt(0)||-1}}function toSingleToken(tokens,allowEmpty){if(tokens.length>1)return{type:"Alternative",expressions:tokens};if(!allowEmpty&&tokens.length===0)throw new Error(`Unsupported no token`);return tokens[0]}function blockToCharToken(block){if(block[0]==="\\"){const next=block[1];switch(next){case"x":{const allDigits=block.substring(2);const codePoint=Number.parseInt(allDigits,16);return{type:"Char",kind:"hex",symbol:safeStringFromCodePoint$2(codePoint),value:block,codePoint}}case"u":{if(block==="\\u")return simpleChar("u",true);const allDigits=block[2]==="{"?block.substring(3,block.length-1):block.substring(2);const codePoint=Number.parseInt(allDigits,16);return{type:"Char",kind:"unicode",symbol:safeStringFromCodePoint$2(codePoint),value:block,codePoint}}case"0":return metaEscapedChar(block,"\x00");case"n":return metaEscapedChar(block,`
|
|
223
223
|
`);case"f":return metaEscapedChar(block,"\f");case"r":return metaEscapedChar(block,"\r");case"t":return metaEscapedChar(block,"\t");case"v":return metaEscapedChar(block,"\v");case"w":case"W":case"d":case"D":case"s":case"S":case"b":case"B":return{type:"Char",kind:"meta",symbol:undefined,value:block,codePoint:NaN};default:if(isDigit(next)){const allDigits=block.substring(1);const codePoint=Number(allDigits);return{type:"Char",kind:"decimal",symbol:safeStringFromCodePoint$2(codePoint),value:block,codePoint}}if(block.length>2&&(next==="p"||next==="P")){const negative=next==="P";return resolveUnicodeProperty(block.substring(3,block.length-1),negative)}return simpleChar(block.substring(1),true)}}return simpleChar(block)}function pushTokens(tokens,regexSource,unicodeMode,groups){let disjunctions=null;for(let index2=0,block=readFrom(regexSource,index2,unicodeMode,0);index2!==regexSource.length;index2+=block.length,block=readFrom(regexSource,index2,unicodeMode,0)){const firstInBlock=block[0];switch(firstInBlock){case"|":if(disjunctions===null)disjunctions=[];disjunctions.push(toSingleToken(tokens.splice(0),true)||null);break;case".":tokens.push({type:"Char",kind:"meta",symbol:block,value:block,codePoint:NaN});break;case"*":case"+":{const previous=safePop(tokens);tokens.push({type:"Repetition",expression:previous,quantifier:{type:"Quantifier",kind:firstInBlock,greedy:true}});break}case"?":{const previous=safePop(tokens);if(previous.type==="Repetition"){previous.quantifier.greedy=false;tokens.push(previous)}else tokens.push({type:"Repetition",expression:previous,quantifier:{type:"Quantifier",kind:firstInBlock,greedy:true}});break}case"{":{if(block==="{"){tokens.push(simpleChar(block));break}const previous=safePop(tokens);const quantifierTokens=block.substring(1,block.length-1).split(",");const from=Number(quantifierTokens[0]);const to=quantifierTokens.length===1?from:quantifierTokens[1].length!==0?Number(quantifierTokens[1]):undefined;tokens.push({type:"Repetition",expression:previous,quantifier:{type:"Quantifier",kind:"Range",greedy:true,from,to}});break}case"[":{const blockContent=block.substring(1,block.length-1);const subTokens=[];let negative=undefined;let previousWasSimpleDash=false;for(let subIndex=0,subBlock=readFrom(blockContent,subIndex,unicodeMode,1);subIndex!==blockContent.length;subIndex+=subBlock.length,subBlock=readFrom(blockContent,subIndex,unicodeMode,1)){if(subIndex===0&&subBlock==="^"){negative=true;continue}const newToken=blockToCharToken(subBlock);if(subBlock==="-"){subTokens.push(newToken);previousWasSimpleDash=true}else{const operand1Token=subTokens.length>=2?subTokens[subTokens.length-2]:undefined;if(previousWasSimpleDash&&operand1Token!==undefined&&operand1Token.type==="Char"&&newToken.type==="Char"){subTokens.pop();subTokens.pop();subTokens.push({type:"ClassRange",from:operand1Token,to:newToken})}else subTokens.push(newToken);previousWasSimpleDash=false}}tokens.push({type:"CharacterClass",expressions:subTokens,negative});break}case"(":{const blockContent=block.substring(1,block.length-1);const subTokens=[];if(blockContent[0]==="?")if(blockContent[1]===":"){pushTokens(subTokens,blockContent.substring(2),unicodeMode,groups);tokens.push({type:"Group",capturing:false,expression:toSingleToken(subTokens)})}else if(blockContent[1]==="="||blockContent[1]==="!"){pushTokens(subTokens,blockContent.substring(2),unicodeMode,groups);tokens.push({type:"Assertion",kind:"Lookahead",negative:blockContent[1]==="!"?true:undefined,assertion:toSingleToken(subTokens)})}else if(blockContent[1]==="<"&&(blockContent[2]==="="||blockContent[2]==="!")){pushTokens(subTokens,blockContent.substring(3),unicodeMode,groups);tokens.push({type:"Assertion",kind:"Lookbehind",negative:blockContent[2]==="!"?true:undefined,assertion:toSingleToken(subTokens)})}else{const chunks=blockContent.split(">");if(chunks.length<2||chunks[0][1]!=="<")throw new Error(`Unsupported regex content found at ${JSON.stringify(block)}`);const groupIndex=++groups.lastIndex;const nameRaw=chunks[0].substring(2);groups.named.set(nameRaw,groupIndex);pushTokens(subTokens,chunks.slice(1).join(">"),unicodeMode,groups);tokens.push({type:"Group",capturing:true,nameRaw,name:nameRaw,number:groupIndex,expression:toSingleToken(subTokens)})}else{const groupIndex=++groups.lastIndex;pushTokens(subTokens,blockContent,unicodeMode,groups);tokens.push({type:"Group",capturing:true,number:groupIndex,expression:toSingleToken(subTokens)})}break}default:if(block==="^")tokens.push({type:"Assertion",kind:block});else if(block==="$")tokens.push({type:"Assertion",kind:block});else if(block[0]==="\\"&&isDigit(block[1])){const reference=Number(block.substring(1));if(unicodeMode||reference<=groups.lastIndex)tokens.push({type:"Backreference",kind:"number",number:reference,reference});else tokens.push(blockToCharToken(block))}else if(block[0]==="\\"&&block[1]==="k"&&block.length!==2){const referenceRaw=block.substring(3,block.length-1);tokens.push({type:"Backreference",kind:"name",number:groups.named.get(referenceRaw)||0,referenceRaw,reference:referenceRaw})}else tokens.push(blockToCharToken(block));break}}if(disjunctions!==null){disjunctions.push(toSingleToken(tokens.splice(0),true)||null);let currentDisjunction={type:"Disjunction",left:disjunctions[0],right:disjunctions[1]};for(let index2=2;index2<disjunctions.length;++index2)currentDisjunction={type:"Disjunction",left:currentDisjunction,right:disjunctions[index2]};tokens.push(currentDisjunction)}}function tokenizeRegex(regex){const unicodeMode=safeIndexOf([...regex.flags],"u")!==-1;const regexSource=regex.source;const tokens=[];pushTokens(tokens,regexSource,unicodeMode,{lastIndex:0,named:new Map});return toSingleToken(tokens)}var safeStringFromCodePoint$1=String.fromCodePoint;function getPropertySpec(astNode){if(astNode.binary||astNode.shorthand)return astNode.canonicalValue;return`${astNode.canonicalName}=${astNode.canonicalValue}`}function appendRangesForRegex(regex,from,to,ranges){let currentRangeStart=-1;for(let cp=from;cp<=to;++cp)if(regex.test(safeStringFromCodePoint$1(cp))){if(currentRangeStart===-1)currentRangeStart=cp}else if(currentRangeStart!==-1){const rangeEnd=cp-1;ranges.push(currentRangeStart===rangeEnd?[rangeEnd]:[currentRangeStart,rangeEnd]);currentRangeStart=-1}if(currentRangeStart!==-1)ranges.push(currentRangeStart===to?[to]:[currentRangeStart,to])}function extractRangesForProperty(propertySpec,negative){const regex=new RegExp(`^\\${negative?"P":"p"}{${propertySpec}}$`,"u");const ranges=[];appendRangesForRegex(regex,0,55295,ranges);appendRangesForRegex(regex,57344,1114111,ranges);return ranges}var cache=new Map;function extractRangesForPropertyOrFromCache(propertySpec,negative){const cacheKey=`${negative?"P":"p"}:${propertySpec}`;const cachedRanges=cache.get(cacheKey);if(cachedRanges!==undefined)return cachedRanges;const ranges=extractRangesForProperty(propertySpec,negative);cache.set(cacheKey,ranges);return ranges}function unicodePropertyArbitrary(astNode){return mapToConstant(...safeMap(extractRangesForPropertyOrFromCache(getPropertySpec(astNode),astNode.negative),(range2)=>convertGraphemeRangeToMapToConstantEntry(range2)))}var safeStringFromCodePoint=String.fromCodePoint;var wordChars=[..."abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"];var digitChars=[..."0123456789"];var spaceChars=[...` \r
|
|
224
224
|
\v\f`];var newLineChars=[...`\r
|
|
@@ -287,7 +287,7 @@ ${bold2}${red2}ERRORS${reset2}`);for(const[,group]of grouped){for(const error2 o
|
|
|
287
287
|
${annotate3("Wizard cancelled.",red)}`;var renderCommandBlock=(label,commandLine,commandColor,labelColor=white)=>{const lines2=wrapCommand(commandLine);return[annotate3(label,bold,labelColor),...lines2.map((line)=>annotate3(line,commandColor)),""].join(`
|
|
288
288
|
`)};var wrapCommand=(commandLine)=>{const width=88;const firstIndent=" $ ";const continuationIndent=" ";const args2=commandLine.map(formatShellArg);const lines2=[];let current=firstIndent;for(const arg of args2){const separator=current===firstIndent||current===continuationIndent?"":" ";if(current.length+separator.length+arg.length>width&¤t!==firstIndent){lines2.push(`${current} \\`);current=`${continuationIndent}${arg}`}else{current+=`${separator}${arg}`}}if(current!==firstIndent){lines2.push(current)}return lines2};var formatShellArg=(arg)=>/^[A-Za-z0-9_./:@%+=,-]+$/.test(arg)?arg:`'${arg.replaceAll("'",`'"'"'`)}'`;var isCommand=(u)=>hasProperty(u,TypeId39);var make31=(name,config,handler)=>{const parsedConfig=parseConfig(config??{});return makeCommand({name,config:parsedConfig,...isNotUndefined(handler)?{handle:handler}:{}})};var withHandler=dual(2,(self,handler)=>makeCommand({...toImpl(self),handle:handler}));var normalizeSubcommandEntries=(entries3)=>{const flat=[];const grouped=new Map;const addToGroup=(group,command)=>{flat.push(command);const existing=grouped.get(group);if(existing){existing.push(command)}else{grouped.set(group,[command])}};for(const entry of entries3){if(isCommand(entry)){addToGroup(undefined,entry);continue}for(const command of entry.commands){addToGroup(entry.group,command)}}const groups=[];const ungroupedCommands=grouped.get(undefined);if(ungroupedCommands&&ungroupedCommands.length>0){groups.push({group:undefined,commands:ungroupedCommands})}for(const[group,commands2]of grouped){if(group===undefined){continue}groups.push({group,commands:commands2})}return{flat,groups}};var withSubcommands=dual(2,(self,subcommands)=>{const normalized=normalizeSubcommandEntries(subcommands);checkForDuplicateFlags(self,normalized.flat);const impl=toImpl(self);const byName=new Map(normalized.flat.map((s)=>[s.name,toImpl(s)]));const SubcommandStateSymbol=Symbol("effect/cli/SubcommandState");const parse3=fnUntraced2(function*(raw){if(isNone2(raw.subcommand)){return yield*impl.parse(raw)}const sub=byName.get(raw.subcommand.value.name);if(!sub){return yield*impl.parse(raw)}const context4=yield*impl.parseContext(raw);const result3=yield*sub.parse(raw.subcommand.value.parsedInput);return Object.assign({},context4,{[SubcommandStateSymbol]:{name:sub.name,result:result3}})});const handle=fnUntraced2(function*(input,path4){const internal=input;const selectedSubcommand=internal[SubcommandStateSymbol];if(selectedSubcommand){const child=byName.get(selectedSubcommand.name);if(!child){return yield*new ShowHelp({commandPath:path4,errors:[]})}return yield*child.handle(selectedSubcommand.result,[...path4,child.name]).pipe(provideService2(impl.service,input))}return yield*impl.handle(input,path4)});return makeCommand({name:impl.name,config:impl.config,contextConfig:impl.contextConfig,description:impl.description,shortDescription:impl.shortDescription,alias:impl.alias,annotations:impl.annotations,globalFlags:impl.globalFlags,examples:impl.examples,service:impl.service,subcommands:normalized.groups,parse:parse3,parseContext:impl.parseContext,handle})});var withSharedFlags=dual(2,(self,sharedFlags)=>{const impl=toImpl(self);const sharedConfig=parseConfig(sharedFlags);const mergedConfig=mergeConfig(impl.config,sharedConfig);const mergedContextConfig=mergeConfig(impl.contextConfig,sharedConfig);if(impl.subcommands.length>0){const flatSubcommands=impl.subcommands.flatMap((group)=>group.commands);checkForDuplicateFlags(self,flatSubcommands,{contextConfig:mergedContextConfig})}const parseShared=makeParser(sharedConfig);const parse3=fnUntraced2(function*(raw){const base2=yield*impl.parse(raw);const shared=yield*parseShared(raw);return Object.assign({},base2,shared)});const parseContext=fnUntraced2(function*(raw){const base2=yield*impl.parseContext(raw);const shared=yield*parseShared(raw);return Object.assign({},base2,shared)});const handle=(input,commandPath)=>impl.handle(input,commandPath);return makeCommand({name:impl.name,config:mergedConfig,contextConfig:mergedContextConfig,description:impl.description,shortDescription:impl.shortDescription,alias:impl.alias,annotations:impl.annotations,globalFlags:impl.globalFlags,examples:impl.examples,service:impl.service,subcommands:impl.subcommands,parse:parse3,parseContext,handle})});var withGlobalFlags=dual(2,(self,globalFlags)=>{const impl=toImpl(self);const next=Array.from(new Set([...impl.globalFlags,...globalFlags]));return makeCommand({...impl,globalFlags:next})});var withDescription3=dual(2,(self,description)=>makeCommand({...toImpl(self),description}));var withShortDescription=dual(2,(self,shortDescription)=>makeCommand({...toImpl(self),shortDescription}));var withAlias3=dual(2,(self,alias)=>makeCommand({...toImpl(self),alias}));var withHidden3=(self)=>makeCommand({...toImpl(self),hidden:true});var annotate4=dual(3,(self,service3,value3)=>{const impl=toImpl(self);return makeCommand({...impl,annotations:add(impl.annotations,service3,value3)})});var annotateMerge=dual(2,(self,annotations)=>{const impl=toImpl(self);return makeCommand({...impl,annotations:merge(impl.annotations,annotations)})});var withExamples=dual(2,(self,examples)=>makeCommand({...toImpl(self),examples}));var mapHandler=(self,f)=>{const impl=toImpl(self);return makeCommand({...impl,handle:(input,path4)=>f(impl.handle(input,path4),input)})};var provide6=dual((args2)=>isCommand(args2[0]),(self,layer4,options)=>mapHandler(self,(handler,input)=>provide4(handler,typeof layer4==="function"?layer4(input):layer4,options)));var provideSync=dual(3,(self,service3,implementation)=>mapHandler(self,(handler,input)=>provideService2(handler,service3,typeof implementation==="function"?implementation(input):implementation)));var provideEffect=dual(3,(self,service3,effect2)=>mapHandler(self,(handler,input)=>provideServiceEffect2(handler,service3,typeof effect2==="function"?effect2(input):effect2)));var provideEffectDiscard=dual(2,(self,effect2)=>mapHandler(self,(handler,input)=>andThen2(typeof effect2==="function"?effect2(input):effect2,handler)));var wizard=(command,options)=>run4(command,options);var getOutOfScopeGlobalFlagErrors=(allFlags,activeFlags,flagMap,commandPath)=>{const activeSet=new Set(activeFlags);const errors2=[];const seen=new Set;for(const flag of allFlags){if(activeSet.has(flag)){continue}const singles=extractSingleParams(flag.flag);for(const single of singles){const entries3=flagMap[single.name];if(!entries3||entries3.length===0){continue}const option5=`--${single.name}`;if(seen.has(option5)){continue}seen.add(option5);errors2.push(new UnrecognizedOption({option:option5,suggestions:[],command:commandPath}))}}return errors2};var showHelp=(command,error2)=>gen2(function*(){const{builtIns}=yield*CliConfig;const formatter=yield*Formatter;const helpDoc=yield*getHelpForCommandPath(command,error2.commandPath,builtIns);yield*log2(formatter.formatHelpDoc(helpDoc));if(error2.errors.length>0){yield*error(formatter.formatErrors(error2.errors))}});var run5=dual(2,(command,config)=>Stdio.use(({args:args2})=>flatMap4(args2,(args3)=>runWith2(command,config)(args3))));var runWith2=(command,config)=>{const commandImpl=toImpl(command);return fnUntraced2(function*(args2){const{builtIns}=yield*CliConfig;const{tokens,trailingOperands}=lex(args2);const allFlags=getGlobalFlagsForCommandTree(command,builtIns);const allFlagParams=allFlags.flatMap((f)=>extractSingleParams(f.flag));const globalRegistry=createFlagRegistry(allFlagParams.filter(isFlagParam));const{flagMap,remainder:remainder2,errors:globalFlagErrors}=consumeGlobalFlags(tokens,command,globalRegistry);const emptyArgs={flags:flagMap,arguments:[]};const parsedArgs=yield*parseArgs({tokens:remainder2,trailingOperands},command);const commandPath=[command.name,...getCommandPath(parsedArgs)];const handlerCtx={builtIns,command,commandPath,version:config.version};const activeFlags=getGlobalFlagsForCommandPath(command,commandPath,builtIns);const outOfScopeErrors=getOutOfScopeGlobalFlagErrors(allFlags,activeFlags,flagMap,commandPath);if(outOfScopeErrors.length>0||globalFlagErrors.length>0){const parseErrors=parsedArgs.errors??[];return yield*new ShowHelp({commandPath,errors:[...globalFlagErrors,...outOfScopeErrors,...parseErrors]})}for(const flag of activeFlags){if(flag._tag!=="Action")continue;const singles=extractSingleParams(flag.flag);const hasEntry=singles.some((s)=>{const entries3=flagMap[s.name];return entries3!==undefined&&entries3.length>0});if(!hasEntry)continue;const[,value3]=yield*flag.flag.parse(emptyArgs);if(flag===Wizard){return yield*gen2(function*(){yield*log2(renderIntroduction(command.name,config.version,command.description));const prefix=[command.name,...args2.filter((arg)=>arg!=="--wizard"&&!arg.startsWith("--wizard="))];const wizardArgs=yield*run4(command,{commandPath,prefix});yield*log2(renderCompletion(wizardArgs));const shouldRun=yield*run3(toggle({message:"Run this command?",initial:true,active:"yes",inactive:"no"}));if(shouldRun){yield*log2();yield*runWith2(command,config)(wizardArgs.slice(1))}}).pipe(catchTag2("QuitError",()=>log2(renderQuit())))}yield*flag.run(value3,handlerCtx);return}if(parsedArgs.errors&&parsedArgs.errors.length>0){return yield*new ShowHelp({commandPath,errors:parsedArgs.errors})}const parseResult=yield*result2(commandImpl.parse(parsedArgs));if(parseResult._tag==="Failure"){return yield*new ShowHelp({commandPath,errors:[parseResult.failure]})}let program=commandImpl.handle(parseResult.success,[command.name]);const logLevel2=activeFlags.includes(LogLevel2)?(yield*LogLevel2.flag.parse(emptyArgs))[1]:none2();program=provideService2(program,LogLevel2,logLevel2);for(const flag of activeFlags){if(flag._tag!=="Setting"||flag===LogLevel2)continue;const[,value3]=yield*flag.flag.parse(emptyArgs);program=provideService2(program,flag,value3)}const services=match(logLevel2,{onNone:()=>empty(),onSome:(level)=>make5(MinimumLogLevel2,level)});yield*provideContext2(program,services)},catchFilter2((error2)=>isCliError(error2)&&error2._tag==="ShowHelp"?succeed2(error2):fail2(error2),(error2)=>andThen2(showHelp(command,error2),fail6(error2))),catchFilter2((e)=>isQuitError(e)?succeed2(e):fail2(e),(_)=>interrupt3))};var runMain=makeRunMain(({fiber:fiber3,teardown})=>{let receivedSignal=false;fiber3.addObserver((exit3)=>{process.removeListener("SIGINT",onSigint);process.removeListener("SIGTERM",onSigint);teardown(exit3,(code)=>{if(receivedSignal||code!==0){process.exit(code)}})});function onSigint(){receivedSignal=true;fiber3.interruptUnsafe(fiber3.id)}process.on("SIGINT",onSigint);process.on("SIGTERM",onSigint)});var runMain2=runMain;var ExitCode=nominal();var ProcessId=nominal();var HandleTypeId="~effect/ChildProcessSpawner/ChildProcessHandle";var HandleProto={[HandleTypeId]:HandleTypeId,...BaseProto,toJSON(){return{_id:"ChildProcessHandle",pid:this.pid}}};var makeHandle=(params)=>Object.assign(Object.create(HandleProto),params);var make32=(spawn)=>{const streamString=(command,options)=>spawn(command).pipe(map7((handle)=>decodeText(options?.includeStderr===true?handle.all:handle.stdout)),unwrap3);const streamLines=(command,options)=>splitLines2(streamString(command,options));return ChildProcessSpawner.of({spawn,exitCode:(command)=>scoped2(flatMap4(spawn(command),(handle)=>handle.exitCode)),streamString,streamLines,lines:(command,options)=>runCollect(streamLines(command,options)),string:(command,options)=>mkString(streamString(command,options))})};class ChildProcessSpawner extends Service()("effect/process/ChildProcessSpawner"){}var TypeId41="~effect/unstable/process/ChildProcess";var Proto10={...Prototype2({label:"Command",evaluate(fiber3){return getUnsafe(fiber3.context,ChildProcessSpawner).spawn(this)}}),[TypeId41]:TypeId41};var makeStandardCommand=(command,args2,options)=>Object.assign(Object.create(Proto10),{_tag:"StandardCommand",command,args:args2,options});var make33=function make34(...args2){if(isTemplateString(args2[0])){const[templates,...expressions]=args2;const tokens=parseTemplates(templates,expressions);return makeStandardCommand(tokens[0]??"",tokens.slice(1),{})}if(typeof args2[0]==="object"&&!Array.isArray(args2[0])&&!isTemplateString(args2[0])){const options2=args2[0];return function(templates,...expressions){const tokens=parseTemplates(templates,expressions);return makeStandardCommand(tokens[0]??"",tokens.slice(1),options2)}}if(typeof args2[0]==="string"&&!Array.isArray(args2[1])){const[command2,options2={}]=args2;return makeStandardCommand(command2,[],options2)}const[command,cmdArgs=[],options={}]=args2;return makeStandardCommand(command,cmdArgs,options)};var isTemplateString=(u)=>Array.isArray(u)&&("raw"in u)&&Array.isArray(u.raw);var parseFdName=(name)=>{const match8=/^fd(\d+)$/.exec(name);if(match8===null)return;const fd=parseInt(match8[1],10);return fd>=3?fd:undefined};var fdName=(fd)=>`fd${fd}`;var parseTemplates=(templates,expressions)=>{let tokens=[];for(const[index2,template]of templates.entries()){tokens=parseTemplate(templates,expressions,tokens,template,index2)}return tokens};var parseTemplate=(templates,expressions,prevTokens,template,index2)=>{const rawTemplate=templates.raw[index2];if(rawTemplate===undefined){throw new Error(`Invalid backslash sequence: ${templates.raw[index2]}`)}const{hasLeadingWhitespace,hasTrailingWhitespace,tokens}=splitByWhitespaces(template,rawTemplate);const nextTokens=concatTokens(prevTokens,tokens,hasLeadingWhitespace);if(index2===expressions.length){return nextTokens}const expression=expressions[index2];const expressionTokens=Array.isArray(expression)?expression.map((expression2)=>parseExpression(expression2)):[parseExpression(expression)];return concatTokens(nextTokens,expressionTokens,hasTrailingWhitespace)};var parseExpression=(expression)=>{const type=typeof expression;if(type==="string"){return expression}return String(expression)};var DELIMITERS=new Set([" ","\t","\r",`
|
|
289
289
|
`]);var ESCAPE_LENGTH={x:3,u:5};var splitByWhitespaces=(template,rawTemplate)=>{if(rawTemplate.length===0){return{tokens:[],hasLeadingWhitespace:false,hasTrailingWhitespace:false}}const hasLeadingWhitespace=DELIMITERS.has(rawTemplate[0]);const tokens=[];let templateCursor=0;for(let templateIndex=0,rawIndex=0;templateIndex<template.length;templateIndex+=1,rawIndex+=1){const rawCharacter=rawTemplate[rawIndex];if(DELIMITERS.has(rawCharacter)){if(templateCursor!==templateIndex){tokens.push(template.slice(templateCursor,templateIndex))}templateCursor=templateIndex+1}else if(rawCharacter==="\\"){const nextRawCharacter=rawTemplate[rawIndex+1];if(nextRawCharacter===`
|
|
290
|
-
`){templateIndex-=1;rawIndex+=1}else if(nextRawCharacter==="u"&&rawTemplate[rawIndex+2]==="{"){rawIndex=rawTemplate.indexOf("}",rawIndex+3)}else{rawIndex+=ESCAPE_LENGTH[nextRawCharacter]??1}}}const hasTrailingWhitespace=templateCursor===template.length;if(!hasTrailingWhitespace){tokens.push(template.slice(templateCursor))}return{tokens,hasLeadingWhitespace,hasTrailingWhitespace}};var concatTokens=(prevTokens,nextTokens,isSeparated)=>isSeparated||prevTokens.length===0||nextTokens.length===0?[...prevTokens,...nextTokens]:[...prevTokens.slice(0,-1),`${prevTokens.at(-1)}${nextTokens.at(0)}`,...nextTokens.slice(1)];import*as NodeChildProcess from"node:child_process";import{PassThrough}from"node:stream";var handleErrnoException=(module,method)=>(err,[path4])=>{let reason="Unknown";switch(err.code){case"ENOENT":reason="NotFound";break;case"EACCES":reason="PermissionDenied";break;case"EEXIST":reason="AlreadyExists";break;case"EISDIR":reason="BadResource";break;case"ENOTDIR":reason="BadResource";break;case"EBUSY":reason="Busy";break;case"ELOOP":reason="BadResource";break}return systemError({_tag:reason,module,method,pathOrDescriptor:path4,syscall:err.syscall,cause:err})};var fromWritable=(options)=>fromChannel2(mapDone(fromWritableChannel(options),(_)=>[_]));var fromWritableChannel=(options)=>fromTransform((pull)=>{const writable=options.evaluate();return succeed6(pullIntoWritable({...options,writable,pull}))});var pullIntoWritable=(options)=>options.pull.pipe(flatMap4((chunk)=>{let i=0;return callback2(function loop(resume){for(;i<chunk.length;){const success=options.writable.write(chunk[i++],options.encoding);if(!success){options.writable.once("drain",()=>loop(resume));return}}resume(void_3)})}),forever3({disableYield:true}),raceFirst2(callback2((resume)=>{const onError4=(error2)=>resume(fail6(options.onError(error2)));options.writable.once("error",onError4);return sync2(()=>{options.writable.off("error",onError4)})})),options.endOnDone!==false?catchDone((_)=>{if("closed"in options.writable&&options.writable.closed){return done3(_)}return callback2((resume)=>{options.writable.once("finish",()=>resume(done3(_)));options.writable.end()})}):identity);var fromReadable=(options)=>fromChannel3(fromReadableChannel(options));var fromReadableChannel=(options)=>fromTransform((_,scope3)=>readableToPullUnsafe({scope:scope3,readable:options.evaluate(),onError:options.onError??defaultOnError,chunkSize:options.chunkSize,closeOnDone:options.closeOnDone}));var readableToPullUnsafe=(options)=>{const readable=options.readable;const closeOnDone=options.closeOnDone??true;const exit3=options.exit??make15(undefined);const latch=makeUnsafe5(false);function onReadable(){latch.openUnsafe()}function onError4(error2){exit3.current=fail4(options.onError(error2));latch.openUnsafe()}function onEnd2(){exit3.current=fail4(Done2());latch.openUnsafe()}readable.on("readable",onReadable);readable.once("error",onError4);readable.once("end",onEnd2);const pull=suspend2(function loop(){let item=options.readable.read(options.chunkSize);if(item===null){if(exit3.current){return exit3.current}if(readable.readableEnded){return fail6(Done2())}latch.closeUnsafe();return flatMap4(latch.await,loop)}const chunk=of(item);while(true){item=options.readable.read(options.chunkSize);if(item===null)break;chunk.push(item)}return succeed6(chunk)});return as2(addFinalizer2(options.scope,sync2(()=>{readable.off("readable",onReadable);readable.off("error",onError4);readable.off("end",onEnd2);if(closeOnDone&&"closed"in options.readable&&!options.readable.closed){options.readable.destroy()}})),pull)};var defaultOnError=(error2)=>new UnknownError2(error2);var toError=(error2)=>error2 instanceof globalThis.Error?error2:new globalThis.Error(String(error2));var toPlatformError=(method,error2,command)=>{const{commands:commands2}=flattenCommand(command);const commandStr=commands2.reduce((acc,curr)=>{const cmd=`${curr.command} ${curr.args.join(" ")}`;return acc.length===0?cmd:`${acc} | ${cmd}`},"");return handleErrnoException("ChildProcess",method)(error2,[commandStr])};var make35=gen2(function*(){const fs=yield*FileSystem;const path4=yield*Path;const resolveWorkingDirectory=fnUntraced2(function*(options){if(isUndefined(options.cwd))return;yield*fs.access(options.cwd);return path4.resolve(options.cwd)});const resolveEnvironment=(options)=>{return options.extendEnv?{...globalThis.process.env,...options.env}:options.env};const inputToStdioOption=(input)=>isStream(input)?"pipe":input;const outputToStdioOption=(input)=>isSink(input)?"pipe":input;const resolveStdinOption=(options)=>{const defaultConfig={stream:"pipe",encoding:"utf-8",endOnDone:true};if(isUndefined(options.stdin)){return defaultConfig}if(typeof options.stdin==="string"){return{...defaultConfig,stream:options.stdin}}if(isStream(options.stdin)){return{...defaultConfig,stream:options.stdin}}return{stream:options.stdin.stream,encoding:options.stdin.encoding??defaultConfig.encoding,endOnDone:options.stdin.endOnDone??defaultConfig.endOnDone}};const resolveOutputOption=(options,streamName)=>{const option5=options[streamName];if(isUndefined(option5)){return{stream:"pipe"}}if(typeof option5==="string"){return{stream:option5}}if(isSink(option5)){return{stream:option5}}return{stream:option5.stream}};const resolveAdditionalFds=(options)=>{if(isUndefined(options.additionalFds)){return[]}const result3=[];for(const[name,config]of Object.entries(options.additionalFds)){const fd=parseFdName(name);if(isNotUndefined(fd)){result3.push({fd,config})}}return result3.sort((a,b)=>a.fd-b.fd)};const buildStdioArray=(stdinConfig,stdoutConfig,stderrConfig,additionalFds)=>{const stdio=[inputToStdioOption(stdinConfig.stream),outputToStdioOption(stdoutConfig.stream),outputToStdioOption(stderrConfig.stream)];if(additionalFds.length===0){return stdio}const maxFd=additionalFds.reduce((max5,{fd})=>Math.max(max5,fd),2);for(let i=3;i<=maxFd;i++){stdio[i]="ignore"}for(const{fd}of additionalFds){stdio[fd]="pipe"}return stdio};const setupAdditionalFds=fnUntraced2(function*(command,childProcess,additionalFds){if(additionalFds.length===0){return{getInputFd:()=>drain,getOutputFd:()=>empty7}}const inputSinks=new Map;const outputStreams=new Map;for(const{config,fd}of additionalFds){const nodeStream=childProcess.stdio[fd];switch(config.type){case"input":{let sink=drain;if(nodeStream&&"write"in nodeStream){sink=fromWritable({evaluate:()=>nodeStream,onError:(error2)=>toPlatformError(`fromWritable(fd${fd})`,toError(error2),command)})}if(config.stream){yield*forkScoped2(run(config.stream,sink))}inputSinks.set(fd,sink);break}case"output":{let stream2=empty7;if(nodeStream&&"read"in nodeStream){const passThrough=new PassThrough;nodeStream.on("error",(error2)=>passThrough.destroy(error2));nodeStream.pipe(passThrough);stream2=fromReadable({evaluate:()=>passThrough,onError:(error2)=>toPlatformError(`fromReadable(fd${fd})`,toError(error2),command)})}if(config.sink){stream2=transduce(stream2,config.sink)}outputStreams.set(fd,stream2);break}}}return{getInputFd:(fd)=>inputSinks.get(fd)??drain,getOutputFd:(fd)=>outputStreams.get(fd)??empty7}});const setupChildStdin=(command,childProcess,config)=>suspend2(()=>{let sink=drain;if(isNotNull(childProcess.stdin)){sink=fromWritable({evaluate:()=>childProcess.stdin,onError:(error2)=>toPlatformError("fromWritable(stdin)",toError(error2),command),endOnDone:config.endOnDone,encoding:config.encoding})}if(isStream(config.stream)){return as2(forkScoped2(run(config.stream,sink)),sink)}return succeed6(sink)});const setupChildOutputStreams=(command,childProcess,stdoutConfig,stderrConfig)=>{let stdout=childProcess.stdout?(()=>{const passThrough=new PassThrough;childProcess.stdout.on("error",(error2)=>passThrough.destroy(error2));childProcess.stdout.pipe(passThrough);return fromReadable({evaluate:()=>passThrough,onError:(error2)=>toPlatformError("fromReadable(stdout)",toError(error2),command)})})():empty7;let stderr=childProcess.stderr?(()=>{const passThrough=new PassThrough;childProcess.stderr.on("error",(error2)=>passThrough.destroy(error2));childProcess.stderr.pipe(passThrough);return fromReadable({evaluate:()=>passThrough,onError:(error2)=>toPlatformError("fromReadable(stderr)",toError(error2),command)})})():empty7;if(isSink(stdoutConfig.stream)){stdout=transduce(stdout,stdoutConfig.stream)}if(isSink(stderrConfig.stream)){stderr=transduce(stderr,stderrConfig.stream)}const all5=merge4(stdout,stderr);return{stdout,stderr,all:all5}};const spawn2=(command,spawnOptions)=>callback2((resume)=>{const deferred=makeUnsafe2();const handle=NodeChildProcess.spawn(command.command,command.args,spawnOptions);handle.on("error",(error2)=>{resume(fail6(toPlatformError("spawn",error2,command)))});handle.on("exit",(...args2)=>{doneUnsafe(deferred,succeed4(args2))});handle.on("spawn",()=>{resume(succeed6([handle,deferred]))});return sync2(()=>{handle.kill("SIGTERM")})});const killProcessGroup=(command,childProcess,signal)=>{if(globalThis.process.platform==="win32"){return callback2((resume)=>{NodeChildProcess.exec(`taskkill /pid ${childProcess.pid} /T /F`,(error2)=>{if(error2){resume(fail6(toPlatformError("kill",toError(error2),command)))}else{resume(void_3)}})})}return try_3({try:()=>{globalThis.process.kill(-childProcess.pid,signal)},catch:(error2)=>toPlatformError("kill",toError(error2),command)})};const killProcessGroupOnExit=(childProcess,signal)=>{if(globalThis.process.platform==="win32"){NodeChildProcess.exec(`taskkill /pid ${childProcess.pid} /T /F`,()=>{});return}try{globalThis.process.kill(-childProcess.pid,signal)}catch{}};const killProcess=(command,childProcess,signal)=>suspend2(()=>{const killed=childProcess.kill(signal);if(!killed){const error2=new globalThis.Error("Failed to kill child process");return fail6(toPlatformError("kill",error2,command))}return void_3});const withTimeout=(childProcess,command,options)=>(kill)=>{const killSignal=options?.killSignal??"SIGTERM";return isUndefined(options?.forceKillAfter)?kill(command,childProcess,killSignal):timeoutOrElse2(kill(command,childProcess,killSignal),{duration:options.forceKillAfter,orElse:()=>kill(command,childProcess,"SIGKILL")})};const getSourceStream=(handle,from)=>{const fromOption4=from??"stdout";switch(fromOption4){case"stdout":return handle.stdout;case"stderr":return handle.stderr;case"all":return handle.all;default:{const fd=parseFdName(fromOption4);if(isNotUndefined(fd)){return handle.getOutputFd(fd)}return handle.stdout}}};const spawnCommand=fnUntraced2(function*(cmd){switch(cmd._tag){case"StandardCommand":{const stdinConfig=resolveStdinOption(cmd.options);const stdoutConfig=resolveOutputOption(cmd.options,"stdout");const stderrConfig=resolveOutputOption(cmd.options,"stderr");const resolvedAdditionalFds=resolveAdditionalFds(cmd.options);let isReferenced=true;const cwd=yield*resolveWorkingDirectory(cmd.options);const env=resolveEnvironment(cmd.options);const stdio=buildStdioArray(stdinConfig,stdoutConfig,stderrConfig,resolvedAdditionalFds);const[childProcess,exitSignal]=yield*acquireRelease2(spawn2(cmd,{cwd,env,stdio,detached:cmd.options.detached??process.platform!=="win32",shell:cmd.options.shell}),fnUntraced2(function*([childProcess2,exitSignal2]){const exited=yield*isDone2(exitSignal2);const killWithTimeout=withTimeout(childProcess2,cmd,cmd.options);if(exited){const[code]=yield*_await(exitSignal2);if(code!==0&&isNotNull(code)){return yield*ignore2(killWithTimeout(killProcessGroup))}return yield*void_3}if(!isReferenced){return yield*void_3}return yield*killWithTimeout((command,childProcess3,signal)=>killProcessGroup(command,childProcess3,signal).pipe(catch_2(()=>killProcess(command,childProcess3,signal)),andThen2(_await(exitSignal2)))).pipe(ignore2)}));const pid=ProcessId(childProcess.pid);childProcess.on("exit",(code)=>{if(code!==0&&isNotNull(code)){killProcessGroupOnExit(childProcess,cmd.options.killSignal??"SIGTERM")}});const reref=sync2(()=>{if(!isReferenced){childProcess.ref();isReferenced=true}});const unref=sync2(()=>{if(isReferenced){childProcess.unref();isReferenced=false}return reref});const stdin=yield*setupChildStdin(cmd,childProcess,stdinConfig);const{all:all5,stderr,stdout}=setupChildOutputStreams(cmd,childProcess,stdoutConfig,stderrConfig);const{getInputFd,getOutputFd}=yield*setupAdditionalFds(cmd,childProcess,resolvedAdditionalFds);const isRunning=map7(isDone2(exitSignal),(done4)=>!done4);const exitCode=flatMap4(_await(exitSignal),([code,signal])=>{if(isNotNull(code)){return succeed6(ExitCode(code))}const error2=new globalThis.Error(`Process interrupted due to receipt of signal: '${signal}'`);return fail6(toPlatformError("exitCode",error2,cmd))});const kill=(options)=>{const killWithTimeout=withTimeout(childProcess,cmd,options);return killWithTimeout((command,childProcess2,signal)=>killProcessGroup(command,childProcess2,signal).pipe(catch_2(()=>killProcess(command,childProcess2,signal)),andThen2(_await(exitSignal)))).pipe(asVoid2)};return makeHandle({pid,exitCode,isRunning,kill,stdin,stdout,stderr,all:all5,getInputFd,getOutputFd,unref})}case"PipedCommand":{const{commands:commands2,pipeOptions}=flattenCommand(cmd);const[root,...pipeline]=commands2;const handles=[yield*spawnCommand(root)];for(let i=0;i<pipeline.length;i++){const command=pipeline[i];const options=pipeOptions[i]??{};const stdinConfig=resolveStdinOption(command.options);const sourceStream=unwrap3(succeed6(getSourceStream(handles[handles.length-1],options.from)));const toOption=options.to??"stdin";if(toOption==="stdin"){handles.push(yield*spawnCommand(make33(command.command,command.args,{...command.options,stdin:{...stdinConfig,stream:sourceStream}})))}else{const fd=parseFdName(toOption);if(isNotUndefined(fd)){const fdName2=fdName(fd);const existingFds=command.options.additionalFds??{};handles.push(yield*spawnCommand(make33(command.command,command.args,{...command.options,additionalFds:{...existingFds,[fdName2]:{type:"input",stream:sourceStream}}})))}else{handles.push(yield*spawnCommand(make33(command.command,command.args,{...command.options,stdin:{...stdinConfig,stream:sourceStream}})))}}}const handle=handles[handles.length-1];const unref=gen2(function*(){const rerefs=[];for(const handle2 of handles){rerefs.push(yield*handle2.unref)}return forEach2([...rerefs].reverse(),(reref)=>reref,{discard:true})});return makeHandle({pid:handle.pid,exitCode:handle.exitCode,isRunning:handle.isRunning,kill:handle.kill,stdin:handle.stdin,stdout:handle.stdout,stderr:handle.stderr,all:handle.all,getInputFd:handle.getInputFd,getOutputFd:handle.getOutputFd,unref})}}});return make32(spawnCommand)});var layer4=effect(ChildProcessSpawner,make35);var flattenCommand=(command)=>{const commands2=[];const pipeOptions=[];const flatten4=(cmd)=>{switch(cmd._tag){case"StandardCommand":{commands2.push(cmd);break}case"PipedCommand":{flatten4(cmd.left);pipeOptions.push(cmd.options);flatten4(cmd.right);break}}};flatten4(command);if(commands2.length===0){throw new Error("flattenCommand produced empty commands array")}const[first,...rest]=commands2;const nonEmptyCommands=[first,...rest];return{commands:nonEmptyCommands,pipeOptions}};var TypeId42="~effect/platform/Crypto";var Crypto=Service("effect/Crypto");var make36=(impl)=>{const randomBytesUnsafe=impl.randomBytes;const randomBytes=(size6)=>map7(validateSize("randomBytes",size6),randomBytesUnsafe);const nextDoubleUnsafe=()=>{const bytes=randomBytesUnsafe(7);const value3=(bytes[0]&31)*2**48+bytes[1]*2**40+bytes[2]*2**32+bytes[3]*2**24+bytes[4]*2**16+bytes[5]*2**8+bytes[6];return value3/2**53};const nextIntUnsafe=()=>Math.floor(nextDoubleUnsafe()*(Number.MAX_SAFE_INTEGER-Number.MIN_SAFE_INTEGER+1))+Number.MIN_SAFE_INTEGER;return Crypto.of({[TypeId42]:TypeId42,randomBytes,nextDoubleUnsafe,nextIntUnsafe,digest:impl.digest,random:sync2(()=>nextDoubleUnsafe()),randomBoolean:sync2(()=>nextDoubleUnsafe()>0.5),randomInt:sync2(()=>nextIntUnsafe()),randomBetween:(min5,max5)=>sync2(()=>nextDoubleUnsafe()*(max5-min5)+min5),randomIntBetween(min5,max5,options){const extra=options?.halfOpen===true?0:1;return sync2(()=>{const minInt=Math.ceil(min5);const maxInt=Math.floor(max5);return Math.floor(nextDoubleUnsafe()*(maxInt-minInt+extra))+minInt})},randomShuffle:(elements)=>sync2(()=>{const buffer2=Array.from(elements);for(let i=buffer2.length-1;i>=1;i=i-1){const index2=Math.min(i,Math.floor(nextDoubleUnsafe()*(i+1)));const value3=buffer2[i];buffer2[i]=buffer2[index2];buffer2[index2]=value3}return buffer2}),randomUUIDv4:sync2(()=>formatUUIDv4(randomBytesUnsafe(16))),randomUUIDv7:clockWith2((clock)=>succeed6(formatUUIDv7(clock.currentTimeMillisUnsafe(),randomBytesUnsafe(16))))})};var validateSize=(method,size6)=>Number.isSafeInteger(size6)&&size6>=0?succeed6(size6):fail6(badArgument({module:"Crypto",method,description:"size must be a non-negative safe integer"}));var hex=(byte)=>byte.toString(16).padStart(2,"0");var formatUUID=(bytes)=>{const segments=[bytes.subarray(0,4),bytes.subarray(4,6),bytes.subarray(6,8),bytes.subarray(8,10),bytes.subarray(10,16)];return segments.map((segment)=>Array.from(segment,hex).join("")).join("-")};var formatUUIDv4=(bytes)=>{bytes[6]=bytes[6]&15|64;bytes[8]=bytes[8]&63|128;return formatUUID(bytes)};var maxUUIDv7Timestamp=2**48-1;var formatUUIDv7=(timestampMillis,bytes)=>{const timestamp=Math.min(Math.max(0,Math.trunc(timestampMillis)),maxUUIDv7Timestamp);bytes[0]=Math.floor(timestamp/2**40);bytes[1]=Math.floor(timestamp/2**32)&255;bytes[2]=Math.floor(timestamp/2**24)&255;bytes[3]=Math.floor(timestamp/2**16)&255;bytes[4]=Math.floor(timestamp/2**8)&255;bytes[5]=timestamp&255;bytes[6]=bytes[6]&15|112;bytes[8]=bytes[8]&63|128;return formatUUID(bytes)};import*as NodeCrypto from"node:crypto";var toHashAlgorithm=(algorithm)=>{switch(algorithm){case"SHA-1":return"sha1";case"SHA-256":return"sha256";case"SHA-384":return"sha384";case"SHA-512":return"sha512"}};var digest=(algorithm,data)=>try_3({try:()=>Uint8Array.from(NodeCrypto.createHash(toHashAlgorithm(algorithm)).update(data).digest()),catch:(cause)=>systemError({module:"Crypto",method:"digest",_tag:"Unknown",description:"Could not compute digest",cause})});var make37=make36({randomBytes:NodeCrypto.randomBytes,digest});var layer5=succeed5(Crypto,make37);var layer6=layer5;import*as Crypto2 from"node:crypto";import*as NFS from"node:fs";import*as OS from"node:os";import*as Path2 from"node:path";var handleBadArgument=(method)=>(err)=>badArgument({module:"FileSystem",method,description:err.message??String(err)});var access2=(()=>{const nodeAccess=effectify(NFS.access,handleErrnoException("FileSystem","access"),handleBadArgument("access"));return(path4,options)=>{let mode=NFS.constants.F_OK;if(options?.readable){mode|=NFS.constants.R_OK}if(options?.writable){mode|=NFS.constants.W_OK}return nodeAccess(path4,mode)}})();var copy2=(()=>{const nodeCp=effectify(NFS.cp,handleErrnoException("FileSystem","copy"),handleBadArgument("copy"));return(fromPath,toPath,options)=>nodeCp(fromPath,toPath,{force:options?.overwrite??false,preserveTimestamps:options?.preserveTimestamps??false,recursive:true})})();var copyFile2=(()=>{const nodeCopyFile=effectify(NFS.copyFile,handleErrnoException("FileSystem","copyFile"),handleBadArgument("copyFile"));return(fromPath,toPath)=>nodeCopyFile(fromPath,toPath)})();var chmod2=(()=>{const nodeChmod=effectify(NFS.chmod,handleErrnoException("FileSystem","chmod"),handleBadArgument("chmod"));return(path4,mode)=>nodeChmod(path4,mode)})();var chown2=(()=>{const nodeChown=effectify(NFS.chown,handleErrnoException("FileSystem","chown"),handleBadArgument("chown"));return(path4,uid,gid)=>nodeChown(path4,uid,gid)})();var glob2=(()=>{const nodeGlob=effectify(NFS.glob,handleErrnoException("FileSystem","glob"),handleBadArgument("glob"));return(pattern,options)=>nodeGlob(pattern,{cwd:options?.root,exclude:options?.exclude})})();var link3=(()=>{const nodeLink=effectify(NFS.link,handleErrnoException("FileSystem","link"),handleBadArgument("link"));return(existingPath,newPath)=>nodeLink(existingPath,newPath)})();var makeDirectory=(()=>{const nodeMkdir=effectify(NFS.mkdir,handleErrnoException("FileSystem","makeDirectory"),handleBadArgument("makeDirectory"));return(path4,options)=>nodeMkdir(path4,{recursive:options?.recursive??false,mode:options?.mode})})();var makeTempDirectoryFactory=(method)=>{const nodeMkdtemp=effectify(NFS.mkdtemp,handleErrnoException("FileSystem",method),handleBadArgument(method));return(options)=>suspend2(()=>{const prefix=options?.prefix??"";const directory3=typeof options?.directory==="string"?Path2.join(options.directory,"."):OS.tmpdir();return nodeMkdtemp(prefix?Path2.join(directory3,prefix):directory3+"/")})};var makeTempDirectory=makeTempDirectoryFactory("makeTempDirectory");var removeFactory=(method)=>{const nodeRm=effectify(NFS.rm,handleErrnoException("FileSystem",method),handleBadArgument(method));return(path4,options)=>nodeRm(path4,{recursive:options?.recursive??false,force:options?.force??false})};var remove4=removeFactory("remove");var makeTempDirectoryScoped=(()=>{const makeDirectory2=makeTempDirectoryFactory("makeTempDirectoryScoped");const removeDirectory=removeFactory("makeTempDirectoryScoped");return(options)=>acquireRelease2(makeDirectory2(options),(directory3)=>orDie2(removeDirectory(directory3,{recursive:true})))})();var openFactory=(method)=>{const nodeOpen=effectify(NFS.open,handleErrnoException("FileSystem",method),handleBadArgument(method));const nodeClose=effectify(NFS.close,handleErrnoException("FileSystem",method),handleBadArgument(method));return(path4,options)=>pipe(acquireRelease2(nodeOpen(path4,options?.flag??"r",options?.mode),(fd)=>orDie2(nodeClose(fd))),map7((fd)=>makeFile(FileDescriptor(fd),options?.flag?.startsWith("a")??false)))};var open2=openFactory("open");var makeFile=(()=>{const nodeReadFactory=(method)=>effectify(NFS.read,handleErrnoException("FileSystem",method),handleBadArgument(method));const nodeRead=nodeReadFactory("read");const nodeReadAlloc=nodeReadFactory("readAlloc");const nodeStat=effectify(NFS.fstat,handleErrnoException("FileSystem","stat"),handleBadArgument("stat"));const nodeTruncate=effectify(NFS.ftruncate,handleErrnoException("FileSystem","truncate"),handleBadArgument("truncate"));const nodeSync=effectify(NFS.fsync,handleErrnoException("FileSystem","sync"),handleBadArgument("sync"));const nodeWriteFactory=(method)=>effectify(NFS.write,handleErrnoException("FileSystem",method),handleBadArgument(method));const nodeWrite=nodeWriteFactory("write");const nodeWriteAll=nodeWriteFactory("writeAll");class FileImpl{[FileTypeId];fd;append;position=BigInt(0);constructor(fd,append3){this[FileTypeId]=FileTypeId;this.fd=fd;this.append=append3}get stat(){return map7(nodeStat(this.fd),makeFileInfo)}get sync(){return nodeSync(this.fd)}seek(offset,from){const offsetSize=Size(offset);return sync2(()=>{if(from==="start"){this.position=offsetSize}else if(from==="current"){this.position=this.position+offsetSize}return this.position})}read(buffer2){return suspend2(()=>{const position=this.position;return map7(nodeRead(this.fd,{buffer:buffer2,position}),(bytesRead)=>{const sizeRead=Size(bytesRead);this.position=position+sizeRead;return sizeRead})})}readAlloc(size6){const sizeNumber=Number(size6);return suspend2(()=>{const buffer2=Buffer.allocUnsafeSlow(sizeNumber);const position=this.position;return map7(nodeReadAlloc(this.fd,{buffer:buffer2,position}),(bytesRead)=>{if(bytesRead===0){return none2()}this.position=position+BigInt(bytesRead);if(bytesRead===sizeNumber){return some2(buffer2)}const dst=Buffer.allocUnsafeSlow(bytesRead);buffer2.copy(dst,0,0,bytesRead);return some2(dst)})})}truncate(length){return map7(nodeTruncate(this.fd,length?Number(length):undefined),()=>{if(!this.append){const len=BigInt(length??0);if(this.position>len){this.position=len}}})}write(buffer2){return suspend2(()=>{const position=this.position;return map7(nodeWrite(this.fd,buffer2,undefined,undefined,this.append?undefined:Number(position)),(bytesWritten)=>{const sizeWritten=Size(bytesWritten);if(!this.append){this.position=position+sizeWritten}return sizeWritten})})}writeAllChunk(buffer2){return suspend2(()=>{const position=this.position;return flatMap4(nodeWriteAll(this.fd,buffer2,undefined,undefined,this.append?undefined:Number(position)),(bytesWritten)=>{if(bytesWritten===0){return fail6(systemError({module:"FileSystem",method:"writeAll",_tag:"WriteZero",pathOrDescriptor:this.fd,description:"write returned 0 bytes written"}))}if(!this.append){this.position=position+BigInt(bytesWritten)}return bytesWritten<buffer2.length?this.writeAllChunk(buffer2.subarray(bytesWritten)):void_3})})}writeAll(buffer2){return this.writeAllChunk(buffer2)}}return(fd,append3)=>new FileImpl(fd,append3)})();var makeTempFileFactory=(method)=>{const makeDirectory2=makeTempDirectoryFactory(method);return fnUntraced2(function*(options){const directory3=yield*makeDirectory2(options);const random2=Crypto2.randomBytes(6).toString("hex");const name=Path2.join(directory3,options?.suffix?`${random2}${options.suffix}`:random2);yield*writeFile2(name,new Uint8Array(0));return name})};var makeTempFile=makeTempFileFactory("makeTempFile");var makeTempFileScoped=(()=>{const makeFile2=makeTempFileFactory("makeTempFileScoped");const removeDirectory=removeFactory("makeTempFileScoped");return(options)=>acquireRelease2(makeFile2(options),(file4)=>orDie2(removeDirectory(Path2.dirname(file4),{recursive:true})))})();var readDirectory=(path4,options)=>tryPromise2({try:()=>NFS.promises.readdir(path4,options),catch:(err)=>handleErrnoException("FileSystem","readDirectory")(err,[path4])});var readFile2=(path4)=>callback2((resume,signal)=>{try{NFS.readFile(path4,{signal},(err,data)=>{if(err){resume(fail6(handleErrnoException("FileSystem","readFile")(err,[path4])))}else{resume(succeed6(data))}})}catch(err){resume(fail6(handleBadArgument("readFile")(err)))}});var readLink=(()=>{const nodeReadLink=effectify(NFS.readlink,handleErrnoException("FileSystem","readLink"),handleBadArgument("readLink"));return(path4)=>nodeReadLink(path4)})();var realPath=(()=>{const nodeRealPath=effectify(NFS.realpath,handleErrnoException("FileSystem","realPath"),handleBadArgument("realPath"));return(path4)=>nodeRealPath(path4)})();var rename2=(()=>{const nodeRename=effectify(NFS.rename,handleErrnoException("FileSystem","rename"),handleBadArgument("rename"));return(oldPath,newPath)=>nodeRename(oldPath,newPath)})();var makeFileInfo=(stat2)=>({type:stat2.isFile()?"File":stat2.isDirectory()?"Directory":stat2.isSymbolicLink()?"SymbolicLink":stat2.isBlockDevice()?"BlockDevice":stat2.isCharacterDevice()?"CharacterDevice":stat2.isFIFO()?"FIFO":stat2.isSocket()?"Socket":"Unknown",mtime:fromNullishOr(stat2.mtime),atime:fromNullishOr(stat2.atime),birthtime:fromNullishOr(stat2.birthtime),dev:stat2.dev,rdev:fromNullishOr(stat2.rdev),ino:fromNullishOr(stat2.ino),mode:stat2.mode,nlink:fromNullishOr(stat2.nlink),uid:fromNullishOr(stat2.uid),gid:fromNullishOr(stat2.gid),size:Size(stat2.size),blksize:stat2.blksize!==undefined?some2(Size(stat2.blksize)):none2(),blocks:fromNullishOr(stat2.blocks)});var stat2=(()=>{const nodeStat=effectify(NFS.stat,handleErrnoException("FileSystem","stat"),handleBadArgument("stat"));return(path4)=>map7(nodeStat(path4),makeFileInfo)})();var symlink2=(()=>{const nodeSymlink=effectify(NFS.symlink,handleErrnoException("FileSystem","symlink"),handleBadArgument("symlink"));return(target,path4)=>nodeSymlink(target,path4)})();var truncate3=(()=>{const nodeTruncate=effectify(NFS.truncate,handleErrnoException("FileSystem","truncate"),handleBadArgument("truncate"));return(path4,length)=>nodeTruncate(path4,length!==undefined?Number(length):undefined)})();var utimes2=(()=>{const nodeUtimes=effectify(NFS.utimes,handleErrnoException("FileSystem","utime"),handleBadArgument("utime"));return(path4,atime,mtime)=>nodeUtimes(path4,atime,mtime)})();var watchNode=(path4)=>callback3((queue)=>acquireRelease2(sync2(()=>{const watcher=NFS.watch(path4,{recursive:true},(event,path5)=>{if(!path5)return;switch(event){case"rename":{runFork2(matchEffect3(stat2(path5),{onSuccess:(_)=>offer(queue,{_tag:"Create",path:path5}),onFailure:(_)=>offer(queue,{_tag:"Remove",path:path5})}));return}case"change":{offerUnsafe(queue,{_tag:"Update",path:path5});return}}});watcher.on("error",(error2)=>{failCauseUnsafe(queue,fail5(systemError({module:"FileSystem",_tag:"Unknown",method:"watch",pathOrDescriptor:path4,cause:error2})))});watcher.on("close",()=>{endUnsafe(queue)});return watcher}),(watcher)=>sync2(()=>watcher.close())));var watch2=(backend,path4)=>stat2(path4).pipe(map7((stat3)=>backend.pipe(flatMap((_)=>_.register(path4,stat3)),getOrElse(()=>watchNode(path4)))),unwrap3);var writeFile2=(path4,data,options)=>callback2((resume,signal)=>{try{NFS.writeFile(path4,data,{signal,flag:options?.flag,mode:options?.mode},(err)=>{if(err){resume(fail6(handleErrnoException("FileSystem","writeFile")(err,[path4])))}else{resume(void_3)}})}catch(err){resume(fail6(handleBadArgument("writeFile")(err)))}});var makeFileSystem=map7(serviceOption2(WatchBackend),(backend)=>make19({access:access2,chmod:chmod2,chown:chown2,copy:copy2,copyFile:copyFile2,glob:glob2,link:link3,makeDirectory,makeTempDirectory,makeTempDirectoryScoped,makeTempFile,makeTempFileScoped,open:open2,readDirectory,readFile:readFile2,readLink,realPath,remove:remove4,rename:rename2,stat:stat2,symlink:symlink2,truncate:truncate3,utimes:utimes2,watch(path4){return watch2(backend,path4)},writeFile:writeFile2}));var layer7=effect(FileSystem)(makeFileSystem);var layer8=layer7;import*as NodePath from"node:path";import*as NodeUrl from"node:url";var fromFileUrl2=(url2)=>try_3({try:()=>NodeUrl.fileURLToPath(url2),catch:(cause)=>new BadArgument({module:"Path",method:"fromFileUrl",cause})});var toFileUrl2=(path4)=>try_3({try:()=>NodeUrl.pathToFileURL(path4),catch:(cause)=>new BadArgument({module:"Path",method:"toFileUrl",cause})});var layerPosix=succeed5(Path)({[TypeId29]:TypeId29,...NodePath.posix,fromFileUrl:fromFileUrl2,toFileUrl:toFileUrl2});var layerWin32=succeed5(Path)({[TypeId29]:TypeId29,...NodePath.win32,fromFileUrl:fromFileUrl2,toFileUrl:toFileUrl2});var layer9=succeed5(Path)({[TypeId29]:TypeId29,...NodePath,fromFileUrl:fromFileUrl2,toFileUrl:toFileUrl2});var layer10=layer9;var layer11=succeed5(Stdio,make30({args:sync2(()=>process.argv.slice(2)),stdout:(options)=>fromWritable({evaluate:()=>process.stdout,onError:(cause)=>systemError({module:"Stdio",method:"stdout",_tag:"Unknown",cause}),endOnDone:options?.endOnDone??false}),stderr:(options)=>fromWritable({evaluate:()=>process.stderr,onError:(cause)=>systemError({module:"Stdio",method:"stderr",_tag:"Unknown",cause}),endOnDone:options?.endOnDone??false}),stdin:fromReadable({evaluate:()=>process.stdin,onError:(cause)=>systemError({module:"Stdio",method:"stdin",_tag:"Unknown",cause}),closeOnDone:false})}));var layer12=layer11;import*as readline from"node:readline";var make38=fnUntraced2(function*(shouldQuit=defaultShouldQuit){const stdin=process.stdin;const stdout=process.stdout;const rlRef=yield*make18({acquire:acquireRelease2(sync2(()=>{const rl=readline.createInterface({input:stdin,escapeCodeTimeout:50});readline.emitKeypressEvents(stdin,rl);if(stdin.isTTY){stdin.setRawMode(true)}return rl}),(rl)=>sync2(()=>{if(stdin.isTTY){stdin.setRawMode(false)}rl.close()}))});const columns=sync2(()=>stdout.columns??0);const rows=sync2(()=>stdout.rows??0);const readInput=gen2(function*(){yield*get3(rlRef);const queue=yield*make16();const handleKeypress=(s,k)=>{const userInput={input:fromUndefinedOr(s),key:{name:k.name??"",ctrl:!!k.ctrl,meta:!!k.meta,shift:!!k.shift}};offerUnsafe(queue,userInput);if(shouldQuit(userInput)){endUnsafe(queue)}};yield*addFinalizer3(()=>sync2(()=>stdin.off("keypress",handleKeypress)));stdin.on("keypress",handleKeypress);return queue});const readLine=scoped2(flatMap4(get3(rlRef),(readlineInterface)=>callback2((resume)=>{const onLine=(line)=>resume(succeed6(line));readlineInterface.once("line",onLine);return sync2(()=>readlineInterface.off("line",onLine))})));const display=(prompt)=>uninterruptible2(callback2((resume)=>{stdout.write(prompt,(err)=>isNullish(err)?resume(void_3):resume(fail6(badArgument({module:"Terminal",method:"display",description:"Failed to write prompt to stdout",cause:err}))))}));return make28({columns,rows,readInput,readLine,display})});var layer13=effect(Terminal,make38(defaultShouldQuit));function defaultShouldQuit(input){return input.key.ctrl&&(input.key.name==="c"||input.key.name==="d")}var layer14=layer13;var layer15=layer4.pipe(provideMerge(mergeAll2(layer8,layer6,layer10,layer12,layer14)));var decode2=(schema2)=>()=>{const decode3=decodeEffect2(NonEmptyArray(schema2));return fromTransform((upstream,_scope)=>succeed6(flatMap4(upstream,(chunk)=>decode3(chunk))))};var TypeId43="~effect/match/Match/Matcher";var TypeMatcherProto={[TypeId43]:{_input:identity,_filters:identity,_remaining:identity,_result:identity,_return:identity},_tag:"TypeMatcher",add(_case){return makeTypeMatcher([...this.cases,_case])},pipe(){return pipeArguments(this,arguments)}};function makeTypeMatcher(cases){const matcher=Object.create(TypeMatcherProto);matcher.cases=cases;return matcher}var ValueMatcherProto={[TypeId43]:{_input:identity,_filters:identity,_result:identity,_return:identity},_tag:"ValueMatcher",add(_case){if(isSuccess2(this.value)){return this}if(_case._tag==="When"&&_case.guard(this.provided)===true){return makeValueMatcher(this.provided,succeed2(_case.evaluate(this.provided)))}else if(_case._tag==="Not"&&_case.guard(this.provided)===false){return makeValueMatcher(this.provided,succeed2(_case.evaluate(this.provided)))}return this},pipe(){return pipeArguments(this,arguments)}};function makeValueMatcher(provided,value3){const matcher=Object.create(ValueMatcherProto);matcher.provided=provided;matcher.value=value3;return matcher}var makeWhen=(guard,evaluate2)=>({_tag:"When",guard,evaluate:evaluate2});var makePredicate=(pattern)=>{if(typeof pattern==="function"){return pattern}else if(Array.isArray(pattern)){const predicates=pattern.map(makePredicate);const len=predicates.length;return(u)=>{if(!Array.isArray(u)){return false}for(let i=0;i<len;i++){if(predicates[i](u[i])===false){return false}}return true}}else if(pattern!==null&&typeof pattern==="object"){const keysAndPredicates=Object.entries(pattern).map(([k,p])=>[k,makePredicate(p)]);const len=keysAndPredicates.length;return(u)=>{if(typeof u!=="object"||u===null){return false}for(let i=0;i<len;i++){const[key,predicate]=keysAndPredicates[i];if(!(key in u)||predicate(u[key])===false){return false}}return true}}return(u)=>u===pattern};var value3=(i)=>makeValueMatcher(i,fail2(i));var when3=(pattern,f)=>(self)=>self.add(makeWhen(makePredicate(pattern),f));var discriminator=(field)=>(...pattern)=>{const f=pattern[pattern.length-1];const values3=pattern.slice(0,-1);const pred=values3.length===1?(_)=>_!=null&&_[field]===values3[0]:(_)=>_!=null&&values3.includes(_[field]);return(self)=>self.add(makeWhen(pred,f))};var tag2=discriminator("_tag");var result3=(self)=>{if(self._tag==="ValueMatcher"){return self.value}const len=self.cases.length;if(len===1){const _case=self.cases[0];return(input)=>{if(_case._tag==="When"&&_case.guard(input)===true){return succeed2(_case.evaluate(input))}else if(_case._tag==="Not"&&_case.guard(input)===false){return succeed2(_case.evaluate(input))}return fail2(input)}}return(input)=>{for(let i=0;i<len;i++){const _case=self.cases[i];if(_case._tag==="When"&&_case.guard(input)===true){return succeed2(_case.evaluate(input))}else if(_case._tag==="Not"&&_case.guard(input)===false){return succeed2(_case.evaluate(input))}}return fail2(input)}};var getExhaustiveAbsurdErrorMessage="effect/match/Match/exhaustive: absurd";var exhaustive=(self)=>{const toResult=result3(self);if(isResult2(toResult)){if(isSuccess2(toResult)){return toResult.success}throw new Error(getExhaustiveAbsurdErrorMessage)}return(u)=>{const result4=toResult(u);if(isSuccess2(result4)){return result4.success}throw new Error(getExhaustiveAbsurdErrorMessage)}};var value4=value3;var when4=when3;var tag3=tag2;var exhaustive2=exhaustive;var TypeId44="~effect/Ref";var RefProto={[TypeId44]:{_A:identity},...PipeInspectableProto,toJSON(){return{_id:"Ref",ref:this.ref}}};var get6=(self)=>sync2(()=>self.ref.current);var update2=dual(2,(self,f)=>sync2(()=>{self.ref.current=f(self.ref.current)}));var toJsonAnnotationsBlacklist=new Set([...fromASTBlacklist,"expected","contentMediaType","contentSchema"]);var fromASTs2=fromASTs;var toJsonSchemaMultiDocument2=toJsonSchemaMultiDocument;var toCodeAnnotationsBlacklist=new Set([...toJsonAnnotationsBlacklist,"typeConstructor","generation","brands"]);var EnvironmentSecret=exports_Schema.Redacted(exports_Schema.NonEmptyString);class EnvironmentStartupError extends exports_Schema.TaggedErrorClass()("@punks/env/EnvironmentStartupError",{configuration:exports_Schema.NonEmptyString,message:exports_Schema.Literal("Configuration is missing or invalid")}){}var makeEnvironmentConfig=(schema2)=>exports_Config.schema(schema2);var makeEnvironmentProvider=(input)=>exports_ConfigProvider.fromEnv({env:Object.fromEntries(Object.entries(input).filter((entry)=>entry[1]!==undefined&&entry[1].length>0))});var decodeEnvironment=({config,name,provider})=>config.parse(provider).pipe(exports_Effect.catchTag("ConfigError",()=>new EnvironmentStartupError({configuration:name,message:"Configuration is missing or invalid"})));var TypeId45="~effect/http/Cookies";var CookieTypeId="~effect/http/Cookies/Cookie";var Proto11={[TypeId45]:TypeId45,...BaseProto,toJSON(){return{_id:"effect/Cookies",cookies:map3(this.cookies,(cookie)=>cookie.toJSON())}},pipe(){return pipeArguments(this,arguments)}};var fromReadonlyRecord=(cookies)=>{const self=Object.create(Proto11);self.cookies=cookies;return self};var fromIterable7=(cookies)=>{const record3={};for(const cookie of cookies){record3[cookie.name]=cookie}return fromReadonlyRecord(record3)};var fromSetCookie=(headers)=>{const arrayHeaders=typeof headers==="string"?[headers]:headers;const cookies=[];for(const header of arrayHeaders){const cookie=parseSetCookie(header.trim());if(cookie){cookies.push(cookie)}}return fromIterable7(cookies)};function parseSetCookie(header){const parts=header.split(";").map((_)=>_.trim()).filter((_)=>_!=="");if(parts.length===0){return}const firstEqual=parts[0].indexOf("=");if(firstEqual===-1){return}const name=parts[0].slice(0,firstEqual);if(!fieldContentRegExp.test(name)){return}const valueEncoded=parts[0].slice(firstEqual+1);const value5=tryDecodeURIComponent(valueEncoded);if(parts.length===1){return Object.assign(Object.create(CookieProto),{name,value:value5,valueEncoded})}const options={};for(let i=1;i<parts.length;i++){const part=parts[i];const equalIndex=part.indexOf("=");const key=equalIndex===-1?part:part.slice(0,equalIndex).trim();const value6=equalIndex===-1?undefined:part.slice(equalIndex+1).trim();switch(key.toLowerCase()){case"domain":{if(value6===undefined){break}const domain2=value6.trim().replace(/^\./,"");if(domain2){options.domain=domain2}break}case"expires":{if(value6===undefined){break}const date7=new Date(value6);if(!isNaN(date7.getTime())){options.expires=date7}break}case"max-age":{if(value6===undefined){break}const maxAge=parseInt(value6,10);if(!isNaN(maxAge)){options.maxAge=seconds(maxAge)}break}case"path":{if(value6===undefined){break}if(value6[0]==="/"){options.path=value6}break}case"priority":{if(value6===undefined){break}switch(value6.toLowerCase()){case"low":options.priority="low";break;case"medium":options.priority="medium";break;case"high":options.priority="high";break}break}case"httponly":{options.httpOnly=true;break}case"secure":{options.secure=true;break}case"partitioned":{options.partitioned=true;break}case"samesite":{if(value6===undefined){break}switch(value6.toLowerCase()){case"lax":options.sameSite="lax";break;case"strict":options.sameSite="strict";break;case"none":options.sameSite="none";break}break}}}return Object.assign(Object.create(CookieProto),{name,value:value5,valueEncoded,options:Object.keys(options).length>0?options:undefined})}var isEmpty3=(self)=>isEmptyRecord(self.cookies);var fieldContentRegExp=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;var CookieProto={[CookieTypeId]:CookieTypeId,...BaseProto,toJSON(){return{_id:"effect/Cookies/Cookie",name:this.name,value:this.value,options:this.options}}};var merge5=dual(2,(self,that)=>fromReadonlyRecord({...self.cookies,...that.cookies}));var toCookieHeader=(self)=>Object.values(self.cookies).map((cookie)=>`${cookie.name}=${cookie.valueEncoded}`).join("; ");var tryDecodeURIComponent=(str)=>{try{return decodeURIComponent(str)}catch(_){return str}};var exports_FetchHttpClient={};__export(exports_FetchHttpClient,{layer:()=>layer16,RequestInit:()=>RequestInit,Fetch:()=>Fetch});var TypeId46=Symbol.for("~effect/http/Headers");var Proto12=Object.defineProperties(Object.create(null),{[TypeId46]:{value:TypeId46},[symbolRedactable]:{value(context4){return redact4(this,get(context4,CurrentRedactedNames))}},toJSON:{value(){return redact(this)}},[symbol2]:{value(that){return Equivalence5(this,that)}},[symbol]:{value(){return structure(this)}},toString:{value:BaseProto.toString},[NodeInspectSymbol]:{value:BaseProto[NodeInspectSymbol]}});var make39=(input)=>Object.assign(Object.create(Proto12),input);var Equivalence5=makeEquivalence4(strictEqual());var empty10=Object.create(Proto12);var fromInput2=(input)=>{if(input===undefined){return empty10}else if(Symbol.iterator in input){const out2=Object.create(Proto12);for(const[k,v]of input){out2[k.toLowerCase()]=v}return out2}const out=Object.create(Proto12);for(const[k,v]of Object.entries(input)){if(Array.isArray(v)){out[k.toLowerCase()]=v.join(", ")}else if(v!==undefined){out[k.toLowerCase()]=v}}return out};var fromRecordUnsafe=(input)=>Object.setPrototypeOf(input,Proto12);var set5=dual(3,(self,key,value5)=>{const out=make39(self);out[key.toLowerCase()]=value5;return out});var setAll=dual(2,(self,headers)=>make39({...self,...fromInput2(headers)}));var merge6=dual(2,(self,headers)=>{const out=make39(self);Object.assign(out,headers);return out});var remove6=dual(2,(self,key)=>{const out=make39(self);delete out[key.toLowerCase()];return out});var redact4=dual(2,(self,key)=>{const out={...self};const modify3=(key2)=>{if(typeof key2==="string"){const k=key2.toLowerCase();if(k in self){out[k]=make9(self[k])}}else{for(const name in self){if(key2.test(name)){out[name]=make9(self[name])}}}};if(Array.isArray(key)){for(let i=0;i<key.length;i++){modify3(key[i])}}else{modify3(key)}return out});var CurrentRedactedNames=Reference("effect/Headers/CurrentRedactedNames",{defaultValue:()=>["authorization","cookie","set-cookie","x-api-key"]});var exports_HttpClient={};__export(exports_HttpClient,{withScope:()=>withScope,withRateLimiter:()=>withRateLimiter,withCookiesRef:()=>withCookiesRef,transformResponse:()=>transformResponse,transform:()=>transform5,tapRequest:()=>tapRequest,tapError:()=>tapError4,tap:()=>tap3,retryTransient:()=>retryTransient,retry:()=>retry4,put:()=>put2,post:()=>post2,patch:()=>patch2,options:()=>options2,mapRequestInputEffect:()=>mapRequestInputEffect,mapRequestInput:()=>mapRequestInput,mapRequestEffect:()=>mapRequestEffect,mapRequest:()=>mapRequest,makeWith:()=>makeWith2,make:()=>make43,layerMergedContext:()=>layerMergedContext,isHttpClient:()=>isHttpClient,head:()=>head2,get:()=>get8,followRedirects:()=>followRedirects,filterStatusOk:()=>filterStatusOk2,filterStatus:()=>filterStatus2,filterOrFail:()=>filterOrFail3,filterOrElse:()=>filterOrElse3,execute:()=>execute,del:()=>del2,catchTags:()=>catchTags3,catchTag:()=>catchTag3,catch:()=>catch_4,TracerPropagationEnabled:()=>TracerPropagationEnabled,TracerDisabledWhen:()=>TracerDisabledWhen,SpanNameGenerator:()=>SpanNameGenerator,HttpClient:()=>HttpClient});var TypeId47="~effect/http/HttpClientError";var isHttpClientError=(u)=>hasProperty(u,TypeId47);class HttpClientError extends TaggedError2("HttpClientError"){constructor(props){if("cause"in props.reason){super({...props,cause:props.reason.cause})}else{super(props)}}[TypeId47]=TypeId47;get request(){return this.reason.request}get response(){return"response"in this.reason?this.reason.response:undefined}get message(){return this.reason.message}}var formatReason=(tag4)=>tag4.endsWith("Error")?tag4.slice(0,-5):tag4;var formatMessage=(reason,description,info)=>description?`${reason}: ${description} (${info})`:`${reason} error (${info})`;class TransportError extends TaggedError2("TransportError"){get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){return formatMessage(formatReason(this._tag),this.description,this.methodAndUrl)}}class InvalidUrlError extends TaggedError2("InvalidUrlError"){get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){return formatMessage(formatReason(this._tag),this.description,this.methodAndUrl)}}class StatusCodeError extends TaggedError2("StatusCodeError"){get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){const info=`${this.response.status} ${this.methodAndUrl}`;return formatMessage(formatReason(this._tag),this.description,info)}}class DecodeError extends TaggedError2("DecodeError"){get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){const info=`${this.response.status} ${this.methodAndUrl}`;return formatMessage(formatReason(this._tag),this.description,info)}}class EmptyBodyError extends TaggedError2("EmptyBodyError"){get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){const info=`${this.response.status} ${this.methodAndUrl}`;return formatMessage(formatReason(this._tag),this.description,info)}}var exports_HttpClientRequest={};__export(exports_HttpClientRequest,{updateUrl:()=>updateUrl,trace:()=>trace,toWebResult:()=>toWebResult,toWeb:()=>toWeb,toUrl:()=>toUrl,setUrlParams:()=>setUrlParams,setUrlParam:()=>setUrlParam,setUrl:()=>setUrl,setMethod:()=>setMethod,setHeaders:()=>setHeaders,setHeader:()=>setHeader,setHash:()=>setHash,setBody:()=>setBody,schemaBodyJson:()=>schemaBodyJson,removeHash:()=>removeHash,put:()=>put,prependUrl:()=>prependUrl,post:()=>post,patch:()=>patch,options:()=>options,modify:()=>modify3,makeWith:()=>makeWith,make:()=>make42,isHttpClientRequest:()=>isHttpClientRequest,head:()=>head,get:()=>get7,fromWeb:()=>fromWeb,empty:()=>empty13,delete:()=>del,bodyUrlParams:()=>bodyUrlParams,bodyUint8Array:()=>bodyUint8Array,bodyText:()=>bodyText,bodyStream:()=>bodyStream,bodyJsonUnsafe:()=>bodyJsonUnsafe,bodyJson:()=>bodyJson,bodyFormDataRecord:()=>bodyFormDataRecord,bodyFormData:()=>bodyFormData,bodyFile:()=>bodyFile,bearerToken:()=>bearerToken,basicAuth:()=>basicAuth,appendUrlParams:()=>appendUrlParams,appendUrlParam:()=>appendUrlParam,appendUrl:()=>appendUrl,acceptJson:()=>acceptJson,accept:()=>accept});var TypeId48="~effect/http/UrlParams";var isUrlParams=(u)=>hasProperty(u,TypeId48);var Proto13={...PipeInspectableProto,[TypeId48]:TypeId48,[Symbol.iterator](){return this.params[Symbol.iterator]()},toJSON(){return{_id:"UrlParams",params:Object.fromEntries(this.params)}},[symbol2](that){return Equivalence6(this,that)},[symbol](){return array(this.params.flat())}};var make40=(params)=>{const self=Object.create(Proto13);self.params=params;return self};var fromInput3=(input)=>{if(isUrlParams(input)){return input}const parsed=fromInputNested(input);const out=[];for(let i=0;i<parsed.length;i++){if(Array.isArray(parsed[i][0])){const[keys3,value5]=parsed[i];out.push([`${keys3[0]}[${keys3.slice(1).join("][")}]`,value5])}else{out.push(parsed[i])}}return make40(out)};var fromInputNested=(input)=>{const entries3=typeof input[Symbol.iterator]==="function"?fromIterable(input):Object.entries(input);const out=[];for(const[key,value5]of entries3){if(Array.isArray(value5)){for(let i=0;i<value5.length;i++){if(value5[i]!==undefined){out.push([key,String(value5[i])])}}}else if(typeof value5==="object"){const nested3=fromInputNested(value5);for(const[k,v]of nested3){out.push([[key,...typeof k==="string"?[k]:k],v])}}else if(value5!==undefined){out.push([key,String(value5)])}}return out};var Equivalence6=make3((a,b)=>arrayEquivalence(a.params,b.params));var arrayEquivalence=makeEquivalence5(makeEquivalence3([strictEqual(),strictEqual()]));var UrlParamsSchema=declare(isUrlParams,{typeConstructor:{_tag:"effect/http/UrlParams"},generation:{runtime:`UrlParams.UrlParamsSchema`,Type:`UrlParams.UrlParams`,Encoded:`typeof UrlParams.UrlParamsSchema["Encoded"]`,importDeclaration:`import * as UrlParams from "effect/unstable/http/UrlParams"`},expected:"UrlParams",toEquivalence:()=>Equivalence6,toCodec:()=>link()(ArraySchema(Tuple2([String5,String5])),transform2({decode:make40,encode:(self)=>self.params}))});var empty11=make40([]);var set6=dual(3,(self,key,value5)=>make40(append(filter4(self.params,([k])=>k!==key),[key,String(value5)])));var transform4=dual(2,(self,f)=>make40(f(self.params)));var setAll2=dual(2,(self,input)=>{const out=fromInput3(input);const params=out.params;const keys3=new Set;for(let i=0;i<params.length;i++){keys3.add(params[i][0])}for(let i=0;i<self.params.length;i++){if(keys3.has(self.params[i][0]))continue;params.push(self.params[i])}return out});var append3=dual(3,(self,key,value5)=>make40(append(self.params,[key,String(value5)])));var appendAll3=dual(2,(self,input)=>transform4(self,appendAll(fromInput3(input).params)));var toString=(input)=>new URLSearchParams(fromInput3(input).params).toString();var toRecord=(self)=>{const out={};for(const[k,value5]of self.params){const curr=out[k];if(curr===undefined){out[k]=value5}else if(typeof curr==="string"){out[k]=[curr,value5]}else{curr.push(value5)}}return out};var toReadonlyRecord=toRecord;var schemaRecord=UrlParamsSchema.pipe(decodeTo2(Record(String5,Union2([String5,NonEmptyArray(String5)])),transform2({decode:toReadonlyRecord,encode:fromInput3})));var TypeId49="~effect/http/HttpBody";var isHttpBody=(u)=>hasProperty(u,TypeId49);var HttpBodyErrorTypeId="~effect/http/HttpBody/HttpBodyError";class HttpBodyError extends TaggedError2("HttpBodyError"){[HttpBodyErrorTypeId]=HttpBodyErrorTypeId}class Proto14{[TypeId49];constructor(){this[TypeId49]=TypeId49}[NodeInspectSymbol](){return this.toJSON()}toString(){return format(this,{ignoreToString:true})}}class Empty2 extends Proto14{_tag="Empty";toJSON(){return{_id:"effect/HttpBody",_tag:"Empty"}}}var empty12=new Empty2;class Raw extends Proto14{_tag="Raw";body;contentType;contentLength;constructor(body,contentType,contentLength){super();this.body=body;this.contentType=contentType;this.contentLength=contentLength}toJSON(){return{_id:"effect/HttpBody",_tag:"Raw",body:this.body,contentType:this.contentType,contentLength:this.contentLength}}}var raw=(body,options)=>new Raw(body,options?.contentType,options?.contentLength);class Uint8Array3 extends Proto14{_tag="Uint8Array";body;contentType;contentLength;constructor(body,contentType,contentLength){super();this.body=body;this.contentType=contentType;this.contentLength=contentLength}toJSON(){const toString2=this.contentType.startsWith("text/")||this.contentType.endsWith("json");return{_id:"effect/HttpBody",_tag:"Uint8Array",body:toString2?new TextDecoder().decode(this.body):`Uint8Array(${this.body.length})`,contentType:this.contentType,contentLength:this.contentLength}}}var uint8Array2=(body,contentType)=>new Uint8Array3(body,contentType??"application/octet-stream",body.length);var encoder2=new TextEncoder;var text2=(body,contentType)=>uint8Array2(encoder2.encode(body),contentType??"text/plain");var jsonUnsafe=(body,contentType)=>text2(JSON.stringify(body),contentType??"application/json");var json2=(body,contentType)=>try_3({try:()=>text2(JSON.stringify(body),contentType??"application/json"),catch:(cause)=>new HttpBodyError({reason:{_tag:"JsonError"},cause})});var jsonSchema=(schema2,options)=>{const encode2=encodeUnknownEffect(toCodecJson(schema2));return(body,contentType)=>encode2(body,options).pipe(mapError3((issue)=>new HttpBodyError({reason:{_tag:"SchemaError",issue},cause:issue})),flatMap4((body2)=>json2(body2,contentType)))};var urlParams=(urlParams2,contentType)=>text2(toString(fromInput3(urlParams2)),contentType??"application/x-www-form-urlencoded");class FormData3 extends Proto14{_tag="FormData";contentType=undefined;contentLength=undefined;formData;constructor(formData){super();this.formData=formData}toJSON(){return{_id:"effect/HttpBody",_tag:"FormData",formData:this.formData}}}var formData=(body)=>new FormData3(body);var appendFormDataValue=(formData2,key,value5)=>{if(value5==null){return}if(typeof value5==="object"){formData2.append(key,value5);return}formData2.append(key,String(value5))};var formDataRecord=(entries3)=>{const data=new globalThis.FormData;for(const[key,value5]of Object.entries(entries3)){if(Array.isArray(value5)){for(const item of value5){appendFormDataValue(data,key,item)}}else{appendFormDataValue(data,key,value5)}}return formData(data)};class Stream3 extends Proto14{_tag="Stream";stream;contentType;contentLength;constructor(stream2,contentType,contentLength){super();this.stream=stream2;this.contentType=contentType;this.contentLength=contentLength}toJSON(){return{_id:"effect/HttpBody",_tag:"Stream",contentType:this.contentType,contentLength:this.contentLength}}}var stream2=(body,contentType,contentLength)=>new Stream3(body,contentType??"application/octet-stream",contentLength);var file4=(path4,options)=>flatMap4(FileSystem,(fs)=>map7(fs.stat(path4),(info)=>stream2(fs.stream(path4,options),options?.contentType,Number(info.size))));var hasBody=(method)=>method!=="GET"&&method!=="HEAD"&&method!=="OPTIONS"&&method!=="TRACE";var allShort=[["GET","get"],["POST","post"],["PUT","put"],["DELETE","del"],["PATCH","patch"],["HEAD","head"],["OPTIONS","options"],["TRACE","trace"]];class UrlError extends TaggedError2("UrlError"){}var make41=(url2,params,hash3)=>try_({try:()=>{const urlInstance=new URL(url2,baseUrl());for(let i=0;i<params.params.length;i++){const[key,value5]=params.params[i];if(value5!==undefined){urlInstance.searchParams.append(key,value5)}}if(hash3!==undefined){urlInstance.hash=hash3}return urlInstance},catch:(cause)=>new UrlError({cause})});var baseUrl=()=>{if("location"in globalThis&&globalThis.location!==undefined&&globalThis.location.origin!==undefined&&globalThis.location.pathname!==undefined){return location.origin+location.pathname}return};var TypeId50="~effect/http/HttpClientRequest";var isHttpClientRequest=(u)=>hasProperty(u,TypeId50);var Proto15={[TypeId50]:TypeId50,...BaseProto,toJSON(){return{_id:"HttpClientRequest",method:this.method,url:this.url,urlParams:this.urlParams,hash:this.hash,headers:redact(this.headers),body:this.body.toJSON()}},pipe(){return pipeArguments(this,arguments)}};function makeWith(method,url2,urlParams2,hash3,headers,body){const self=Object.create(Proto15);self.method=method;self.url=url2;self.urlParams=urlParams2;self.hash=hash3;self.headers=headers;self.body=body;return self}var empty13=makeWith("GET","",empty11,none2(),empty10,empty12);var make42=(method)=>(url2,options)=>modify3(empty13,{method,url:url2,...options??undefined});var get7=make42("GET");var post=make42("POST");var patch=make42("PATCH");var put=make42("PUT");var del=make42("DELETE");var head=make42("HEAD");var options=make42("OPTIONS");var trace=make42("TRACE");var modify3=dual(2,(self,options2)=>{let result4=self;if(options2.method){result4=setMethod(result4,options2.method)}if(options2.url){result4=setUrl(result4,options2.url)}if(options2.headers){result4=setHeaders(result4,options2.headers)}if(options2.urlParams){result4=setUrlParams(result4,options2.urlParams)}if(options2.hash){result4=setHash(result4,options2.hash)}if(options2.body){result4=setBody(result4,options2.body)}if(options2.accept){result4=accept(result4,options2.accept)}if(options2.acceptJson){result4=acceptJson(result4)}return result4});var setMethod=dual(2,(self,method)=>makeWith(method,self.url,self.urlParams,self.hash,self.headers,self.body));var setHeader=dual(3,(self,key,value5)=>makeWith(self.method,self.url,self.urlParams,self.hash,set5(self.headers,key,value5),self.body));var setHeaders=dual(2,(self,input)=>makeWith(self.method,self.url,self.urlParams,self.hash,setAll(self.headers,input),self.body));var basicAuth=dual(3,(self,username,password2)=>setHeader(self,"Authorization",`Basic ${btoa(`${stringOrRedacted(username)}:${stringOrRedacted(password2)}`)}`));var bearerToken=dual(2,(self,token)=>setHeader(self,"Authorization",`Bearer ${stringOrRedacted(token)}`));var accept=dual(2,(self,mediaType)=>setHeader(self,"Accept",mediaType));var acceptJson=accept("application/json");var setUrl=dual(2,(self,url2)=>{if(typeof url2==="string"){return makeWith(self.method,url2,self.urlParams,self.hash,self.headers,self.body)}const clone2=new URL(url2.toString());const urlParams2=fromInput3(clone2.searchParams);const hash3=fromNullishOr(clone2.hash===""?undefined:clone2.hash.slice(1));clone2.search="";clone2.hash="";return makeWith(self.method,clone2.toString(),urlParams2,hash3,self.headers,self.body)});var prependUrl=dual(2,(self,path4)=>{if(path4==="")return self;return makeWith(self.method,joinSegments(path4,self.url),self.urlParams,self.hash,self.headers,self.body)});var appendUrl=dual(2,(self,path4)=>{if(path4==="")return self;return makeWith(self.method,joinSegments(self.url,path4),self.urlParams,self.hash,self.headers,self.body)});var joinSegments=(first,second)=>{const endsWithSlash=first.endsWith("/");const startsWithSlash=second.startsWith("/");const needsTrim=endsWithSlash&&startsWithSlash;const needsSlash=!endsWithSlash&&!startsWithSlash;return needsTrim?first+second.slice(1):needsSlash?first+"/"+second:first+second};var updateUrl=dual(2,(self,f)=>makeWith(self.method,f(self.url),self.urlParams,self.hash,self.headers,self.body));var setUrlParam=dual(3,(self,key,value5)=>makeWith(self.method,self.url,set6(self.urlParams,key,value5),self.hash,self.headers,self.body));var setUrlParams=dual(2,(self,input)=>makeWith(self.method,self.url,setAll2(self.urlParams,input),self.hash,self.headers,self.body));var appendUrlParam=dual(3,(self,key,value5)=>makeWith(self.method,self.url,append3(self.urlParams,key,value5),self.hash,self.headers,self.body));var appendUrlParams=dual(2,(self,input)=>makeWith(self.method,self.url,appendAll3(self.urlParams,input),self.hash,self.headers,self.body));var setHash=dual(2,(self,hash3)=>makeWith(self.method,self.url,self.urlParams,some2(hash3),self.headers,self.body));var removeHash=(self)=>makeWith(self.method,self.url,self.urlParams,none2(),self.headers,self.body);var setBody=dual(2,(self,body)=>{let headers=self.headers;if(body._tag==="Empty"||body._tag==="FormData"){headers=remove6(remove6(headers,"Content-Type"),"Content-length")}else{if(body.contentType){headers=set5(headers,"content-type",body.contentType)}if(body.contentLength!==undefined){headers=set5(headers,"content-length",body.contentLength.toString())}}return makeWith(self.method,self.url,self.urlParams,self.hash,headers,body)});var bodyUint8Array=dual((args2)=>isHttpClientRequest(args2[0]),(self,body,contentType)=>setBody(self,uint8Array2(body,contentType)));var bodyText=dual((args2)=>isHttpClientRequest(args2[0]),(self,body,contentType)=>setBody(self,text2(body,contentType)));var bodyJson=dual(2,(self,body)=>map7(json2(body),(body2)=>setBody(self,body2)));var bodyJsonUnsafe=dual(2,(self,body)=>setBody(self,jsonUnsafe(body)));var schemaBodyJson=(schema2,options2)=>{const encode2=jsonSchema(schema2,options2);return dual(2,(self,body)=>map7(encode2(body),(body2)=>setBody(self,body2)))};var bodyUrlParams=dual(2,(self,input)=>setBody(self,urlParams(fromInput3(input))));var bodyFormData=dual(2,(self,body)=>setBody(self,formData(body)));var bodyFormDataRecord=dual(2,(self,entries3)=>setBody(self,formDataRecord(entries3)));var bodyStream=dual((args2)=>isHttpClientRequest(args2[0]),(self,body,options2)=>setBody(self,stream2(body,options2?.contentType,options2?.contentLength)));var bodyFile=dual((args2)=>isHttpClientRequest(args2[0]),(self,path4,options2)=>map7(file4(path4,options2),(body)=>setBody(self,body)));function toUrl(self){const r=make41(self.url,self.urlParams,getOrUndefined(self.hash));if(isSuccess2(r)){return some2(r.success)}return none2()}var fromWeb=(request3)=>{const method=request3.method.toUpperCase();return modify3(empty13,{method,url:new URL(request3.url),headers:request3.headers,body:fromWebBody(request3,method)})};var fromWebBody=(request3,method)=>{if(!hasBody(method)||request3.body===null){return empty12}return raw(request3.body,{contentType:request3.headers.get("content-type")??undefined,contentLength:parseContentLength(request3.headers.get("content-length"))})};var parseContentLength=(contentLength)=>{if(contentLength===null){return}const parsed=Number.parseInt(contentLength,10);return Number.isNaN(parsed)?undefined:parsed};var toWebResult=(self,options2)=>{const url2=make41(self.url,self.urlParams,getOrUndefined(self.hash));if(isFailure2(url2)){return fail2(url2.failure)}const requestInit={method:self.method,headers:self.headers};if(options2?.signal){requestInit.signal=options2.signal}if(hasBody(self.method)){switch(self.body._tag){case"Empty":{break}case"Raw":{requestInit.body=self.body.body;if(isReadableStream(self.body.body)){requestInit.duplex="half"}break}case"Uint8Array":{requestInit.body=self.body.body;break}case"FormData":{requestInit.body=self.body.formData;break}case"Stream":{requestInit.body=toReadableStreamWith(self.body.stream,options2?.context??empty());requestInit.duplex="half";break}}}return try_({try:()=>new Request(url2.success,requestInit),catch:(cause)=>new UrlError({cause})})};var isReadableStream=(u)=>typeof ReadableStream!=="undefined"&&u instanceof ReadableStream;var toWeb=(self,options2)=>contextWith2((context4)=>fromResult2(toWebResult(self,{context:context4,signal:options2?.signal})));var TypeId51="~effect/http/HttpIncomingMessage";var inspect=(self,that)=>{const contentType=self.headers["content-type"]??"";let body;if(contentType.includes("application/json")){try{body=runSync2(self.json)}catch(_){}}else if(contentType.includes("text/")||contentType.includes("urlencoded")){try{body=runSync2(self.text)}catch(_){}}const obj={...that,headers:redact(self.headers),remoteAddress:self.remoteAddress};if(body!==undefined){obj.body=body}return obj};var TypeId52="~effect/http/HttpClientResponse";var fromWeb2=(request3,source)=>new WebHttpClientResponse(request3,source);var matchStatus=dual(2,(self,cases)=>{const status=self.status;if(cases[status]){return cases[status](self)}else if(status>=200&&status<300&&cases["2xx"]){return cases["2xx"](self)}else if(status>=300&&status<400&&cases["3xx"]){return cases["3xx"](self)}else if(status>=400&&status<500&&cases["4xx"]){return cases["4xx"](self)}else if(status>=500&&status<600&&cases["5xx"]){return cases["5xx"](self)}return cases.orElse(self)});var filterStatus=dual(2,(self,f)=>suspend2(()=>f(self.status)?succeed6(self):fail6(new HttpClientError({reason:new StatusCodeError({response:self,request:self.request,description:"invalid status code"})}))));var filterStatusOk=(self)=>self.status>=200&&self.status<300?succeed6(self):fail6(new HttpClientError({reason:new StatusCodeError({response:self,request:self.request,description:"non 2xx status code"})}));class WebHttpClientResponse extends Class2{[TypeId51];[TypeId52];request;source;constructor(request3,source){super();this.request=request3;this.source=source;this[TypeId51]=TypeId51;this[TypeId52]=TypeId52}toJSON(){return inspect(this,{_id:"HttpClientResponse",request:this.request.toJSON(),status:this.status})}get status(){return this.source.status}get headers(){return fromInput2(this.source.headers)}cachedCookies;get cookies(){if(this.cachedCookies){return this.cachedCookies}return this.cachedCookies=fromSetCookie(this.source.headers.getSetCookie())}get remoteAddress(){return none2()}get stream(){return this.source.body?fromReadableStream({evaluate:()=>this.source.body,onError:(cause)=>new HttpClientError({reason:new DecodeError({request:this.request,response:this,cause})})}):fail9(new HttpClientError({reason:new EmptyBodyError({request:this.request,response:this,description:"can not create stream from empty body"})}))}get json(){return flatMap4(this.text,(text3)=>try_3({try:()=>text3===""?null:JSON.parse(text3),catch:(cause)=>new HttpClientError({reason:new DecodeError({request:this.request,response:this,cause})})}))}textBody;get text(){if(this.textBody){return this.textBody}this.textBody=tryPromise2({try:()=>this.source.text(),catch:(cause)=>new HttpClientError({reason:new DecodeError({request:this.request,response:this,cause})})}).pipe(cached2,runSync2);this.arrayBufferBody=map7(this.textBody,(_)=>new TextEncoder().encode(_).buffer);return this.textBody}get urlParamsBody(){return flatMap4(this.text,(_)=>try_3({try:()=>fromInput3(new URLSearchParams(_)),catch:(cause)=>new HttpClientError({reason:new DecodeError({request:this.request,response:this,cause})})}))}formDataBody;get formData(){return this.formDataBody??=tryPromise2({try:()=>this.source.formData(),catch:(cause)=>new HttpClientError({reason:new DecodeError({request:this.request,response:this,cause})})}).pipe(cached2,runSync2)}arrayBufferBody;get arrayBuffer(){if(this.arrayBufferBody){return this.arrayBufferBody}this.arrayBufferBody=tryPromise2({try:()=>this.source.arrayBuffer(),catch:(cause)=>new HttpClientError({reason:new DecodeError({request:this.request,response:this,cause})})}).pipe(cached2,runSync2);this.textBody=map7(this.arrayBufferBody,(_)=>new TextDecoder().decode(_));return this.arrayBufferBody}pipe(){return pipeArguments(this,arguments)}}var toHeaders=(span)=>fromRecordUnsafe({b3:`${span.traceId}-${span.spanId}-${span.sampled?"1":"0"}${match(span.parent,{onNone:()=>"",onSome:(parent)=>`-${parent.spanId}`})}`,traceparent:`00-${span.traceId}-${span.spanId}-${span.sampled?"01":"00"}`});var TypeId53="~effect/http/HttpClient";var isHttpClient=(u)=>hasProperty(u,TypeId53);var HttpClient=Service("effect/HttpClient");var accessor=(method)=>(...args2)=>flatMap4(HttpClient,(client)=>client[method](...args2));var execute=accessor("execute");var get8=accessor("get");var head2=accessor("head");var post2=accessor("post");var patch2=accessor("patch");var put2=accessor("put");var del2=accessor("del");var options2=accessor("options");var transform5=dual(2,(self,f)=>makeWith2(flatMap4((request3)=>f(self.postprocess(succeed6(request3)),request3)),self.preprocess));var transformResponse=dual(2,(self,f)=>makeWith2((request3)=>f(self.postprocess(request3)),self.preprocess));var catch_4=dual(2,(self,f)=>transformResponse(self,catch_2(f)));var catchTag3=dual(3,(self,tag4,f)=>transformResponse(self,(effect2)=>catchTag2(effect2,tag4,f)));var catchTags3=dual(2,(self,cases)=>transformResponse(self,catchTags2(cases)));var filterOrElse3=dual(3,(self,f,orElse6)=>transformResponse(self,filterOrElse2(f,orElse6)));var filterOrFail3=dual(3,(self,f,orFailWith)=>transformResponse(self,filterOrFail2(f,orFailWith)));var filterStatus2=dual(2,(self,f)=>transformResponse(self,flatMap4(filterStatus(f))));var filterStatusOk2=transformResponse(flatMap4(filterStatusOk));var makeWith2=(postprocess,preprocess)=>{const self=Object.create(Proto16);self.preprocess=preprocess;self.postprocess=postprocess;self.execute=function(request3){return postprocess(preprocess(request3))};return self};var Proto16={[TypeId53]:TypeId53,pipe(){return pipeArguments(this,arguments)},...BaseProto,toJSON(){return{_id:"effect/HttpClient"}},...Object.fromEntries(allShort.map(([fullMethod,method])=>[method,function(url2,options3){return this.execute(make42(fullMethod)(url2,options3))}]))};var make43=(f)=>makeWith2((effect2)=>flatMap4(effect2,(request3)=>withFiber2((fiber3)=>{const scopedController=scopedRequests.get(request3);const controller=scopedController??new AbortController;const urlResult=make41(request3.url,request3.urlParams,getOrUndefined(request3.hash));if(isFailure2(urlResult)){return fail6(new HttpClientError({reason:new InvalidUrlError({request:request3,cause:urlResult.failure})}))}const url2=urlResult.success;const tracerDisabled=fiber3.getRef(DisablePropagation)||fiber3.getRef(TracerDisabledWhen)(request3);if(tracerDisabled){const effect3=f(request3,url2,controller.signal,fiber3);if(scopedController)return effect3;return uninterruptibleMask2((restore)=>matchCauseEffect2(restore(effect3),{onSuccess(response){responseRegistry.register(response,controller);return succeed6(new InterruptibleResponse(response,controller))},onFailure(cause){if(hasInterrupts2(cause)){controller.abort()}return failCause3(cause)}}))}return useSpan2(fiber3.getRef(SpanNameGenerator)(request3),{kind:"client"},(span)=>{span.attribute("http.request.method",request3.method);span.attribute("server.address",url2.origin);if(url2.port!==""){span.attribute("server.port",+url2.port)}span.attribute("url.full",url2.toString());span.attribute("url.path",url2.pathname);span.attribute("url.scheme",url2.protocol.slice(0,-1));const query=url2.search.slice(1);if(query!==""){span.attribute("url.query",query)}const redactedHeaderNames=fiber3.getRef(CurrentRedactedNames);const redactedHeaders=redact4(request3.headers,redactedHeaderNames);for(const name in redactedHeaders){span.attribute(`http.request.header.${name}`,String(redactedHeaders[name]))}request3=fiber3.getRef(TracerPropagationEnabled)?setHeaders(request3,toHeaders(span)):request3;return uninterruptibleMask2((restore)=>restore(f(request3,url2,controller.signal,fiber3)).pipe(withParentSpan2(span,{captureStackTrace:false}),matchCauseEffect2({onSuccess:(response)=>{span.attribute("http.response.status_code",response.status);const redactedHeaders2=redact4(response.headers,redactedHeaderNames);for(const name in redactedHeaders2){span.attribute(`http.response.header.${name}`,String(redactedHeaders2[name]))}if(scopedController)return succeed6(response);responseRegistry.register(response,controller);return succeed6(new InterruptibleResponse(response,controller))},onFailure(cause){if(!scopedController&&hasInterrupts2(cause)){controller.abort()}return failCause3(cause)}})))})})),succeed6);var mapRequest=dual(2,(self,f)=>makeWith2(self.postprocess,(request3)=>map7(self.preprocess(request3),f)));var mapRequestEffect=dual(2,(self,f)=>makeWith2(self.postprocess,(request3)=>flatMap4(self.preprocess(request3),f)));var mapRequestInput=dual(2,(self,f)=>makeWith2(self.postprocess,(request3)=>self.preprocess(f(request3))));var mapRequestInputEffect=dual(2,(self,f)=>makeWith2(self.postprocess,(request3)=>flatMap4(f(request3),self.preprocess)));var retry4=dual(2,(self,policy)=>transformResponse(self,retry2(policy)));var retryTransient=dual(2,(self,options3)=>{const isOnlySchedule=isSchedule(options3);const retryOn=isOnlySchedule?"errors-and-responses":options3.retryOn??"errors-and-responses";const schedule3=isOnlySchedule?options3:options3.schedule;const passthroughSchedule=schedule3&&passthrough(schedule3);const times=isOnlySchedule?undefined:options3.times;return transformResponse(self,flow(retryOn==="errors-only"?identity:repeat2({schedule:passthroughSchedule,times,while:isTransientResponse}),retryOn==="response-only"?identity:retry2({while:isOnlySchedule||options3.while===undefined?isTransientError:or(isTransientError,options3.while),schedule:schedule3,times})))});var withRateLimiter=dual(2,(self,options3)=>{const initialState={initial:true,limit:options3.limit,window:max2(fromInputUnsafe(options3.window),millis(1))};const states=new Map;const keyOption=options3.key;const resolveKey=typeof keyOption==="function"?keyOption:constant(keyOption);const tokensOption=options3.tokens;const resolveTokens=typeof tokensOption==="function"?tokensOption:constant(tokensOption??1);const adaptiveLearningEnabled=!options3.disableAdaptiveLearning;const getState2=(key)=>{const current=states.get(key);if(current!==undefined){return current}states.set(key,initialState);return initialState};const onResponse=options3.disableResponseInspection?undefined:(clock,key,headers,tokens)=>{const current=getState2(key);const next=parseRateLimiterState(current,clock,headers,tokens);if(next.limit!==current.limit||!equals2(next.window,current.window)){states.set(key,next)}};return transform5(self,function loop(effect2,request3){const fiber3=getCurrent();const clock=fiber3.getRef(Clock);const key=resolveKey(request3);const tokens=Math.max(resolveTokens(request3),1);const current=getState2(key);function retry5(retryAfter){if(options3.disableResponseInspection)return loop(effect2,request3);return retryAfter?flatMap4(sleep2(retryAfter),()=>loop(effect2,request3)):loop(effect2,request3)}const inspectResponse=(response,adaptive)=>{onResponse?.(clock,key,response.headers,tokens);if(options3.disableResponseInspection||response.status!==429){return succeed6(undefined)}const retryAfter=parseRetryAfter(clock,getHeader(response.headers,"retry-after"));if(retryAfter===undefined){return succeed6(undefined)}const delay3=parseRateLimitWindow(clock,response.headers)??retryAfter;if(adaptive===undefined){return succeed6(delay3)}return as2(options3.limiter.adaptiveFeedback({key,epoch:adaptive.epoch,tokens,status:response.status,retryAfter:delay3}),delay3)};return flatMap4(options3.limiter.consume({algorithm:options3.algorithm,onExceeded:"delay",key,limit:current.limit,window:current.window,tokens}),({delay:delay3})=>{const runAdaptive=()=>{const runRequest=(adaptive)=>{const request4=matchEffect3(effect2,{onSuccess(response){return flatMap4(inspectResponse(response,adaptive),(retryAfter)=>{if(response.status!==429)return succeed6(response);return retry5(retryAfter)})},onFailure(error2){if(isTooManyRequestsHttpClientError(error2)){return flatMap4(inspectResponse(error2.reason.response,adaptive),(retryAfter)=>retry5(retryAfter))}return fail6(error2)}});return adaptive===undefined||isZero(adaptive.delay)?request4:delay2(request4,adaptive.delay)};if(!adaptiveLearningEnabled){return runRequest(undefined)}return flatMap4(options3.limiter.adaptiveConsume({key,tokens,fallbackLimit:current.limit,fallbackWindow:current.window}),(adaptive)=>{if(!isZero(adaptive.delay)&&adaptive.phase==="cooldown"){return flatMap4(sleep2(adaptive.delay),runAdaptive)}return runRequest(adaptive)})};return isZero(delay3)?runAdaptive():flatMap4(sleep2(delay3),runAdaptive)})})});var parseRateLimiterState=(state,clock,headers,tokens)=>{const limit=parseRateLimitLimit(state,headers,tokens)??state.limit;const window=parseRateLimitWindow(clock,headers)??state.window;if(limit===state.limit&&equals2(window,state.window)){return state}return{limit,window,initial:false}};var parseRateLimitLimit=(state,headers,tokens)=>{const raw2=getHeader(headers,"ratelimit-limit","x-ratelimit-limit");const value5=parseNumberHeader(raw2);if(value5!==undefined&&value5>0){return value5}const remaining=parseRateLimitRemaining(headers);if(remaining===undefined){return}return state.initial?remaining+tokens:Math.max(remaining+tokens,state.limit)};var parseRateLimitRemaining=(headers)=>{const raw2=getHeader(headers,"ratelimit-remaining","x-ratelimit-remaining");const value5=parseNumberHeader(raw2);return value5!==undefined&&value5>=0?value5:undefined};var parseRateLimitWindow=(clock,headers)=>{const resetAfter=parseResetAfter(getHeader(headers,"ratelimit-reset-after","x-ratelimit-reset-after"));if(resetAfter!==undefined){return resetAfter}return parseResetHeader(clock,getHeader(headers,"ratelimit-reset","x-ratelimit-reset"))};var parseRetryAfter=(clock,value5)=>{if(value5===undefined){return}const numeric=parseNumberHeader(value5);if(numeric!==undefined){return max2(seconds(numeric),millis(1))}const parsedDate=Date.parse(value5);if(Number.isNaN(parsedDate)){return}const millis2=parsedDate-clock.currentTimeMillisUnsafe();if(millis2<=0){return millis(1)}return millis(millis2)};var parseResetAfter=(value5)=>{const numeric=parseNumberHeader(value5);if(numeric===undefined||numeric<=0){return}return max2(seconds(numeric),millis(1))};var parseResetHeader=(clock,value5)=>{const numeric=parseNumberHeader(value5);if(numeric===undefined||numeric<=0){return}const nowMillis=clock.currentTimeMillisUnsafe();if(numeric>1000000000000){return millis(Math.max(numeric-nowMillis,1))}if(numeric>1e9){return millis(Math.max(numeric*1000-nowMillis,1))}return max2(seconds(numeric),millis(1))};var parseNumberHeader=(value5)=>{if(value5===undefined){return}const match8=/-?\d+(?:\.\d+)?/.exec(value5);if(match8===null){return}const parsed=Number(match8[0]);return Number.isFinite(parsed)?parsed:undefined};var getHeader=(headers,...keys3)=>{for(let i=0;i<keys3.length;i++){const value5=headers[keys3[i]];if(value5!==undefined){return value5}}return};var tap3=dual(2,(self,f)=>transformResponse(self,tap2(f)));var tapError4=dual(2,(self,f)=>transformResponse(self,tapError2(f)));var tapRequest=dual(2,(self,f)=>makeWith2(self.postprocess,(request3)=>tap2(self.preprocess(request3),f)));var withCookiesRef=dual(2,(self,ref)=>makeWith2((request3)=>tap2(self.postprocess(request3),(response)=>update2(ref,(cookies)=>merge5(cookies,response.cookies))),(request3)=>flatMap4(self.preprocess(request3),(request4)=>map7(get6(ref),(cookies)=>isEmpty3(cookies)?request4:setHeader(request4,"cookie",toCookieHeader(cookies))))));var withScope=(self)=>transform5(self,(effect2,request3)=>{const controller=new AbortController;scopedRequests.set(request3,controller);return andThen2(addFinalizer3(()=>sync2(()=>controller.abort())),effect2)});var followRedirects=dual((args2)=>isHttpClient(args2[0]),(self,maxRedirects)=>makeWith2((request3)=>{const loop=(request4,redirects)=>flatMap4(self.postprocess(succeed6(request4)),(response)=>response.status>=300&&response.status<400&&response.headers.location&&redirects<(maxRedirects??10)?loop(setUrl(request4,new URL(response.headers.location,response.request.url)),redirects+1):succeed6(response));return flatMap4(request3,(request4)=>loop(request4,0))},self.preprocess));var TracerDisabledWhen=Reference("effect/http/HttpClient/TracerDisabledWhen",{defaultValue:()=>constFalse});var TracerPropagationEnabled=Reference("effect/HttpClient/TracerPropagationEnabled",{defaultValue:constTrue});var SpanNameGenerator=Reference("effect/http/HttpClient/SpanNameGenerator",{defaultValue:()=>(request3)=>`http.client ${request3.method}`});var layerMergedContext=(effect2)=>effect(HttpClient)(contextWith2((context4)=>map7(effect2,(client)=>transformResponse(client,updateContext2((input)=>merge(context4,input))))));var responseRegistry=(()=>{if("FinalizationRegistry"in globalThis&&globalThis.FinalizationRegistry){const registry=new FinalizationRegistry((controller)=>{controller.abort()});return{register(response,controller){registry.register(response,controller,response)},unregister(response){registry.unregister(response)}}}const timers=new Map;return{register(response,controller){timers.set(response,setTimeout(()=>controller.abort(),5000))},unregister(response){const timer=timers.get(response);if(timer===undefined)return;clearTimeout(timer);timers.delete(response)}}})();var scopedRequests=new WeakMap;class InterruptibleResponse{original;controller;constructor(original,controller){this.original=original;this.controller=controller}[TypeId52]=TypeId52;[TypeId51]=TypeId51;applyInterrupt(effect2){return suspend2(()=>{responseRegistry.unregister(this.original);return onInterrupt2(effect2,()=>sync2(()=>{this.controller.abort()}))})}get request(){return this.original.request}get status(){return this.original.status}get headers(){return this.original.headers}get cookies(){return this.original.cookies}get remoteAddress(){return this.original.remoteAddress}get formData(){return this.applyInterrupt(this.original.formData)}get text(){return this.applyInterrupt(this.original.text)}get json(){return this.applyInterrupt(this.original.json)}get urlParamsBody(){return this.applyInterrupt(this.original.urlParamsBody)}get arrayBuffer(){return this.applyInterrupt(this.original.arrayBuffer)}get stream(){return suspend4(()=>{responseRegistry.unregister(this.original);return ensuring4(this.original.stream,sync2(()=>{this.controller.abort()}))})}toJSON(){return this.original.toJSON()}[NodeInspectSymbol](){return this.original[NodeInspectSymbol]()}pipe(){return pipeArguments(this,arguments)}}var isTransientError=(error2)=>isTimeoutError2(error2)||isTransientHttpError(error2);var isTransientHttpError=(error2)=>isHttpClientError(error2)&&(error2.reason._tag==="TransportError"||error2.reason._tag==="StatusCodeError"&&isTransientResponse(error2.reason.response));var isTooManyRequestsHttpClientError=(error2)=>isHttpClientError(error2)&&error2.reason._tag==="StatusCodeError"&&error2.reason.response.status===429;var isTransientResponse=(response)=>response.status===408||response.status===429||response.status===500||response.status===502||response.status===503||response.status===504;var Fetch=Reference("effect/http/FetchHttpClient/Fetch",{defaultValue:()=>globalThis.fetch});class RequestInit extends Service()("effect/http/FetchHttpClient/RequestInit"){}var fetch2=make43((request3,url2,signal,fiber3)=>{const fetch3=fiber3.getRef(Fetch);const options3=fiber3.context.mapUnsafe.get(RequestInit.key)??{};let headers=options3.headers?merge6(fromInput2(options3.headers),request3.headers):request3.headers;if(headers["content-length"]){headers=remove6(headers,"content-length")}const send=(body)=>map7(tryPromise2({try:()=>fetch3(url2,{...options3,method:request3.method,headers,body,duplex:request3.body._tag==="Stream"?"half":undefined,signal}),catch:(cause)=>new HttpClientError({reason:new TransportError({request:request3,cause})})}),(response)=>fromWeb2(request3,response));switch(request3.body._tag){case"Raw":case"Uint8Array":return send(request3.body.body);case"FormData":return send(request3.body.formData);case"Stream":return flatMap4(toReadableStreamEffect(request3.body.stream),send)}return send(undefined)});var layer16=layerMergedContext(succeed6(fetch2));var HttpServerRequest=Service("effect/http/HttpServerRequest");var loggerDisabledRequests=new WeakSet;var withLoggerDisabled=(self)=>withFiber2((fiber3)=>{const request3=getUnsafe(fiber3.context,HttpServerRequest);loggerDisabledRequests.add(request3.source);return self});var HttpRouter=Service("effect/http/HttpRouter");var removeTrailingSlash=(path4)=>path4.endsWith("/")?path4.slice(0,-1):path4;var prefixPath=dual(2,(self,prefix)=>{prefix=removeTrailingSlash(prefix);if(self==="*")return`${prefix}/*`;else if(self==="/")return prefix;return prefix+self});var MiddlewareTypeId="~effect/http/HttpRouter/Middleware";var middleware=function(){if(arguments.length===0){return makeMiddleware}return makeMiddleware(arguments[0],arguments[1])};var makeMiddleware=(middleware2,options3)=>options3?.global?effectDiscard(gen2(function*(){const router=yield*HttpRouter;const fn3=isEffect2(middleware2)?yield*middleware2:middleware2;yield*router.addGlobalMiddleware(fn3)})):new MiddlewareImpl(isEffect2(middleware2)?effectContext(map7(middleware2,(fn3)=>makeUnsafe(new Map([[fnContextKey,fn3]])))):succeedContext(makeUnsafe(new Map([[fnContextKey,middleware2]]))));var middlewareId=0;var fnContextKey="effect/http/HttpRouter/MiddlewareFn";class MiddlewareImpl{[MiddlewareTypeId]={};layerFn;dependencies;constructor(layerFn,dependencies){this.layerFn=layerFn;this.dependencies=dependencies;const contextKey=`effect/http/HttpRouter/Middleware-${++middlewareId}`;this.layer=effectContext(gen2({self:this},function*(){const context4=yield*context2();const stack=[context4.mapUnsafe.get(fnContextKey)];if(this.dependencies){const memoMap=yield*CurrentMemoMap;const scope3=get(context4,Scope);const depsContext=yield*buildWithMemoMap(this.dependencies,memoMap,scope3);stack.push(...getMiddleware(depsContext))}return makeUnsafe(new Map([[contextKey,stack]]))})).pipe(provide2(this.layerFn))}layer;combine(other){return new MiddlewareImpl(this.layerFn,this.dependencies?provideMerge(this.dependencies,other.layer):other.layer)}}var middlewareCache=new WeakMap;var getMiddleware=(context4)=>{let arr=middlewareCache.get(context4);if(arr)return arr;const topLevel=empty3();let maxLength=0;for(const[key,value5]of context4.mapUnsafe){if(key.startsWith("effect/http/HttpRouter/Middleware-")){topLevel.push(value5);if(value5.length>maxLength){maxLength=value5.length}}}if(topLevel.length===0){arr=[]}else{const middleware2=new Set;for(let i=maxLength-1;i>=0;i--){for(const arr2 of topLevel){if(i<arr2.length){middleware2.add(arr2[i])}}}arr=fromIterable(middleware2).reverse()}middlewareCache.set(context4,arr);return arr};var disableLogger=middleware(withLoggerDisabled).layer;import path8 from"node:path";var RepositoryCheckCapabilities=Service("@punks/cli/features/repository-check/RepositoryCheckCapabilities");class RepositoryCheckOperationFailure extends TaggedErrorClass()("@punks/cli/repository-check/RepositoryCheckOperationFailure",{cause:Defect(),message:String5,operation:Literals(["assess-project-settings","check-repository-update","read-changelog"])}){}var RepositoryCheckOperations=Service("@punks/cli/features/repository-check/RepositoryCheckOperations");var isRecord=(value5)=>typeof value5==="object"&&value5!==null;var isReadOnlyAuthorityFailure=(input,failure)=>{if(input.baseline==="bundled"||!isRecord(failure.cause)){return false}const{cause:resolutionFailure}=failure;if(resolutionFailure._tag!=="@punks/cli/baseline-resolution/BaselineResolutionFailure"){return false}if(resolutionFailure.reason==="remote-access"){return true}const{cause}=resolutionFailure;return isRecord(cause)&&cause._tag==="@punks/contract/errors/BaselineIntegrityFailure"&&cause.message==="Published baseline inventory returned 404."};var unavailableCheckResult=({code,detail,rootDirectory,source})=>({availability:{detail,source,status:"unavailable"},cli:{command:null,currentVersion:null,failed:false,latestVersion:null,packageName:null,status:"unavailable",tag:null},failed:true,operation:{changes:[],degradations:[{code,subject:source}],issues:[],nextActions:[{kind:"none"}],status:"degraded",warnings:[]},releaseSummary:[],settings:{baselineVersion:null,baselineVersionDrift:false,cliVersion:null,cliVersionDrift:false,upgrade:null},update:{applied:false,baselineDrift:false,changedFiles:[],checkFailed:false,driftPrompt:null,failed:false,finalPacks:[],packDrift:false,repoShapeMode:"auto",resolvedPacks:[],rootDirectory,scaffoldManifestFile:".devpunks/scaffold-manifest.json",staleFiles:[],toolBootstrapStatuses:[]}});var normalizeCliResult=(result4)=>{const{check:check3}=result4;return{failed:result4.status!=="current"&&result4.status!=="unavailable",status:result4.status,currentVersion:check3?.currentVersion??null,latestVersion:check3?.latestVersion??null,packageName:check3?.packageName??null,tag:check3?.tag??null,command:"command"in result4?result4.command:null}};var checkSettingsPins=fn2("RepositoryCheck.checkSettingsPins")(function*checkSettingsPins2({rootDirectory,cli,baselineVersion,capabilities,currentCliVersion}){const assessment=yield*capabilities.assessSettings(rootDirectory);const settings=assessment?.settings??null;const acceptedCliVersion=settings?.cliVersion??null;const acceptedBaselineVersion=settings?.baselineVersion??null;const expectedCliVersion=cli.status==="current"&&cli.currentVersion!==null?cli.currentVersion:cli.latestVersion??cli.currentVersion??currentCliVersion;return{baselineVersion:acceptedBaselineVersion,baselineVersionDrift:acceptedBaselineVersion!==null&&baselineVersion!==null&&acceptedBaselineVersion!==baselineVersion,cliVersion:acceptedCliVersion,cliVersionDrift:acceptedCliVersion!==null&&acceptedCliVersion!==expectedCliVersion,upgrade:assessment?.upgrade??null}});var extractChangelogEntry=(changelog,heading)=>{const escapedHeading=heading.replaceAll(/[.*+?^${}()|[\]\\]/gu,"\\$&");const match8=new RegExp(`^## \\[?${escapedHeading}\\]?[^\\n]*\\n`,"mu").exec(changelog);if(match8===null){return null}const rest=changelog.slice(match8.index+match8[0].length);const nextHeading=rest.search(/^## /mu);const body=(nextHeading===-1?rest:rest.slice(0,nextHeading)).trim();return body.length>0?body:null};var findChangelogEntry=fn2("RepositoryCheck.findChangelogEntry")(function*findChangelogEntry2({rootDirectory,fileName,heading,roots,capabilities}){for(const candidateRoot of[rootDirectory,...roots]){const candidatePath=`${candidateRoot.replace(/\/$/u,"")}/${fileName}`;const changelog=yield*capabilities.readTextFile(candidatePath);if(changelog===null){continue}const entry=extractChangelogEntry(changelog,heading);if(entry!==null){return entry}}return null});var summarizeChangelogEntry=(entry)=>entry.split(`
|
|
290
|
+
`){templateIndex-=1;rawIndex+=1}else if(nextRawCharacter==="u"&&rawTemplate[rawIndex+2]==="{"){rawIndex=rawTemplate.indexOf("}",rawIndex+3)}else{rawIndex+=ESCAPE_LENGTH[nextRawCharacter]??1}}}const hasTrailingWhitespace=templateCursor===template.length;if(!hasTrailingWhitespace){tokens.push(template.slice(templateCursor))}return{tokens,hasLeadingWhitespace,hasTrailingWhitespace}};var concatTokens=(prevTokens,nextTokens,isSeparated)=>isSeparated||prevTokens.length===0||nextTokens.length===0?[...prevTokens,...nextTokens]:[...prevTokens.slice(0,-1),`${prevTokens.at(-1)}${nextTokens.at(0)}`,...nextTokens.slice(1)];import*as NodeChildProcess from"node:child_process";import{PassThrough}from"node:stream";var handleErrnoException=(module,method)=>(err,[path4])=>{let reason="Unknown";switch(err.code){case"ENOENT":reason="NotFound";break;case"EACCES":reason="PermissionDenied";break;case"EEXIST":reason="AlreadyExists";break;case"EISDIR":reason="BadResource";break;case"ENOTDIR":reason="BadResource";break;case"EBUSY":reason="Busy";break;case"ELOOP":reason="BadResource";break}return systemError({_tag:reason,module,method,pathOrDescriptor:path4,syscall:err.syscall,cause:err})};var fromWritable=(options)=>fromChannel2(mapDone(fromWritableChannel(options),(_)=>[_]));var fromWritableChannel=(options)=>fromTransform((pull)=>{const writable=options.evaluate();return succeed6(pullIntoWritable({...options,writable,pull}))});var pullIntoWritable=(options)=>options.pull.pipe(flatMap4((chunk)=>{let i=0;return callback2(function loop(resume){for(;i<chunk.length;){const success=options.writable.write(chunk[i++],options.encoding);if(!success){options.writable.once("drain",()=>loop(resume));return}}resume(void_3)})}),forever3({disableYield:true}),raceFirst2(callback2((resume)=>{const onError4=(error2)=>resume(fail6(options.onError(error2)));options.writable.once("error",onError4);return sync2(()=>{options.writable.off("error",onError4)})})),options.endOnDone!==false?catchDone((_)=>{if("closed"in options.writable&&options.writable.closed){return done3(_)}return callback2((resume)=>{options.writable.once("finish",()=>resume(done3(_)));options.writable.end()})}):identity);var fromReadable=(options)=>fromChannel3(fromReadableChannel(options));var fromReadableChannel=(options)=>fromTransform((_,scope3)=>readableToPullUnsafe({scope:scope3,readable:options.evaluate(),onError:options.onError??defaultOnError,chunkSize:options.chunkSize,closeOnDone:options.closeOnDone}));var readableToPullUnsafe=(options)=>{const readable=options.readable;const closeOnDone=options.closeOnDone??true;const exit3=options.exit??make15(undefined);const latch=makeUnsafe5(false);function onReadable(){latch.openUnsafe()}function onError4(error2){exit3.current=fail4(options.onError(error2));latch.openUnsafe()}function onEnd2(){exit3.current=fail4(Done2());latch.openUnsafe()}readable.on("readable",onReadable);readable.once("error",onError4);readable.once("end",onEnd2);const pull=suspend2(function loop(){let item=options.readable.read(options.chunkSize);if(item===null){if(exit3.current){return exit3.current}if(readable.readableEnded){return fail6(Done2())}latch.closeUnsafe();return flatMap4(latch.await,loop)}const chunk=of(item);while(true){item=options.readable.read(options.chunkSize);if(item===null)break;chunk.push(item)}return succeed6(chunk)});return as2(addFinalizer2(options.scope,sync2(()=>{readable.off("readable",onReadable);readable.off("error",onError4);readable.off("end",onEnd2);if(closeOnDone&&"closed"in options.readable&&!options.readable.closed){options.readable.destroy()}})),pull)};var defaultOnError=(error2)=>new UnknownError2(error2);var toError=(error2)=>error2 instanceof globalThis.Error?error2:new globalThis.Error(String(error2));var toPlatformError=(method,error2,command)=>{const{commands:commands2}=flattenCommand(command);const commandStr=commands2.reduce((acc,curr)=>{const cmd=`${curr.command} ${curr.args.join(" ")}`;return acc.length===0?cmd:`${acc} | ${cmd}`},"");return handleErrnoException("ChildProcess",method)(error2,[commandStr])};var make35=gen2(function*(){const fs=yield*FileSystem;const path4=yield*Path;const resolveWorkingDirectory=fnUntraced2(function*(options){if(isUndefined(options.cwd))return;yield*fs.access(options.cwd);return path4.resolve(options.cwd)});const resolveEnvironment=(options)=>{return options.extendEnv?{...globalThis.process.env,...options.env}:options.env};const inputToStdioOption=(input)=>isStream(input)?"pipe":input;const outputToStdioOption=(input)=>isSink(input)?"pipe":input;const resolveStdinOption=(options)=>{const defaultConfig={stream:"pipe",encoding:"utf-8",endOnDone:true};if(isUndefined(options.stdin)){return defaultConfig}if(typeof options.stdin==="string"){return{...defaultConfig,stream:options.stdin}}if(isStream(options.stdin)){return{...defaultConfig,stream:options.stdin}}return{stream:options.stdin.stream,encoding:options.stdin.encoding??defaultConfig.encoding,endOnDone:options.stdin.endOnDone??defaultConfig.endOnDone}};const resolveOutputOption=(options,streamName)=>{const option5=options[streamName];if(isUndefined(option5)){return{stream:"pipe"}}if(typeof option5==="string"){return{stream:option5}}if(isSink(option5)){return{stream:option5}}return{stream:option5.stream}};const resolveAdditionalFds=(options)=>{if(isUndefined(options.additionalFds)){return[]}const result3=[];for(const[name,config]of Object.entries(options.additionalFds)){const fd=parseFdName(name);if(isNotUndefined(fd)){result3.push({fd,config})}}return result3.sort((a,b)=>a.fd-b.fd)};const buildStdioArray=(stdinConfig,stdoutConfig,stderrConfig,additionalFds)=>{const stdio=[inputToStdioOption(stdinConfig.stream),outputToStdioOption(stdoutConfig.stream),outputToStdioOption(stderrConfig.stream)];if(additionalFds.length===0){return stdio}const maxFd=additionalFds.reduce((max5,{fd})=>Math.max(max5,fd),2);for(let i=3;i<=maxFd;i++){stdio[i]="ignore"}for(const{fd}of additionalFds){stdio[fd]="pipe"}return stdio};const setupAdditionalFds=fnUntraced2(function*(command,childProcess,additionalFds){if(additionalFds.length===0){return{getInputFd:()=>drain,getOutputFd:()=>empty7}}const inputSinks=new Map;const outputStreams=new Map;for(const{config,fd}of additionalFds){const nodeStream=childProcess.stdio[fd];switch(config.type){case"input":{let sink=drain;if(nodeStream&&"write"in nodeStream){sink=fromWritable({evaluate:()=>nodeStream,onError:(error2)=>toPlatformError(`fromWritable(fd${fd})`,toError(error2),command)})}if(config.stream){yield*forkScoped2(run(config.stream,sink))}inputSinks.set(fd,sink);break}case"output":{let stream2=empty7;if(nodeStream&&"read"in nodeStream){const passThrough=new PassThrough;nodeStream.on("error",(error2)=>passThrough.destroy(error2));nodeStream.pipe(passThrough);stream2=fromReadable({evaluate:()=>passThrough,onError:(error2)=>toPlatformError(`fromReadable(fd${fd})`,toError(error2),command)})}if(config.sink){stream2=transduce(stream2,config.sink)}outputStreams.set(fd,stream2);break}}}return{getInputFd:(fd)=>inputSinks.get(fd)??drain,getOutputFd:(fd)=>outputStreams.get(fd)??empty7}});const setupChildStdin=(command,childProcess,config)=>suspend2(()=>{let sink=drain;if(isNotNull(childProcess.stdin)){sink=fromWritable({evaluate:()=>childProcess.stdin,onError:(error2)=>toPlatformError("fromWritable(stdin)",toError(error2),command),endOnDone:config.endOnDone,encoding:config.encoding})}if(isStream(config.stream)){return as2(forkScoped2(run(config.stream,sink)),sink)}return succeed6(sink)});const setupChildOutputStreams=(command,childProcess,stdoutConfig,stderrConfig)=>{let stdout=childProcess.stdout?(()=>{const passThrough=new PassThrough;childProcess.stdout.on("error",(error2)=>passThrough.destroy(error2));childProcess.stdout.pipe(passThrough);return fromReadable({evaluate:()=>passThrough,onError:(error2)=>toPlatformError("fromReadable(stdout)",toError(error2),command)})})():empty7;let stderr=childProcess.stderr?(()=>{const passThrough=new PassThrough;childProcess.stderr.on("error",(error2)=>passThrough.destroy(error2));childProcess.stderr.pipe(passThrough);return fromReadable({evaluate:()=>passThrough,onError:(error2)=>toPlatformError("fromReadable(stderr)",toError(error2),command)})})():empty7;if(isSink(stdoutConfig.stream)){stdout=transduce(stdout,stdoutConfig.stream)}if(isSink(stderrConfig.stream)){stderr=transduce(stderr,stderrConfig.stream)}const all5=merge4(stdout,stderr);return{stdout,stderr,all:all5}};const spawn2=(command,spawnOptions)=>callback2((resume)=>{const deferred=makeUnsafe2();const handle=NodeChildProcess.spawn(command.command,command.args,spawnOptions);handle.on("error",(error2)=>{resume(fail6(toPlatformError("spawn",error2,command)))});handle.on("exit",(...args2)=>{doneUnsafe(deferred,succeed4(args2))});handle.on("spawn",()=>{resume(succeed6([handle,deferred]))});return sync2(()=>{handle.kill("SIGTERM")})});const killProcessGroup=(command,childProcess,signal)=>{if(globalThis.process.platform==="win32"){return callback2((resume)=>{NodeChildProcess.exec(`taskkill /pid ${childProcess.pid} /T /F`,(error2)=>{if(error2){resume(fail6(toPlatformError("kill",toError(error2),command)))}else{resume(void_3)}})})}return try_3({try:()=>{globalThis.process.kill(-childProcess.pid,signal)},catch:(error2)=>toPlatformError("kill",toError(error2),command)})};const killProcessGroupOnExit=(childProcess,signal)=>{if(globalThis.process.platform==="win32"){NodeChildProcess.exec(`taskkill /pid ${childProcess.pid} /T /F`,()=>{});return}try{globalThis.process.kill(-childProcess.pid,signal)}catch{}};const killProcess=(command,childProcess,signal)=>suspend2(()=>{const killed=childProcess.kill(signal);if(!killed){const error2=new globalThis.Error("Failed to kill child process");return fail6(toPlatformError("kill",error2,command))}return void_3});const withTimeout=(childProcess,command,options)=>(kill)=>{const killSignal=options?.killSignal??"SIGTERM";return isUndefined(options?.forceKillAfter)?kill(command,childProcess,killSignal):timeoutOrElse2(kill(command,childProcess,killSignal),{duration:options.forceKillAfter,orElse:()=>kill(command,childProcess,"SIGKILL")})};const getSourceStream=(handle,from)=>{const fromOption4=from??"stdout";switch(fromOption4){case"stdout":return handle.stdout;case"stderr":return handle.stderr;case"all":return handle.all;default:{const fd=parseFdName(fromOption4);if(isNotUndefined(fd)){return handle.getOutputFd(fd)}return handle.stdout}}};const spawnCommand=fnUntraced2(function*(cmd){switch(cmd._tag){case"StandardCommand":{const stdinConfig=resolveStdinOption(cmd.options);const stdoutConfig=resolveOutputOption(cmd.options,"stdout");const stderrConfig=resolveOutputOption(cmd.options,"stderr");const resolvedAdditionalFds=resolveAdditionalFds(cmd.options);let isReferenced=true;const cwd=yield*resolveWorkingDirectory(cmd.options);const env=resolveEnvironment(cmd.options);const stdio=buildStdioArray(stdinConfig,stdoutConfig,stderrConfig,resolvedAdditionalFds);const[childProcess,exitSignal]=yield*acquireRelease2(spawn2(cmd,{cwd,env,stdio,detached:cmd.options.detached??process.platform!=="win32",shell:cmd.options.shell}),fnUntraced2(function*([childProcess2,exitSignal2]){const exited=yield*isDone2(exitSignal2);const killWithTimeout=withTimeout(childProcess2,cmd,cmd.options);if(exited){const[code]=yield*_await(exitSignal2);if(code!==0&&isNotNull(code)){return yield*ignore2(killWithTimeout(killProcessGroup))}return yield*void_3}if(!isReferenced){return yield*void_3}return yield*killWithTimeout((command,childProcess3,signal)=>killProcessGroup(command,childProcess3,signal).pipe(catch_2(()=>killProcess(command,childProcess3,signal)),andThen2(_await(exitSignal2)))).pipe(ignore2)}));const pid=ProcessId(childProcess.pid);childProcess.on("exit",(code)=>{if(code!==0&&isNotNull(code)){killProcessGroupOnExit(childProcess,cmd.options.killSignal??"SIGTERM")}});const reref=sync2(()=>{if(!isReferenced){childProcess.ref();isReferenced=true}});const unref=sync2(()=>{if(isReferenced){childProcess.unref();isReferenced=false}return reref});const stdin=yield*setupChildStdin(cmd,childProcess,stdinConfig);const{all:all5,stderr,stdout}=setupChildOutputStreams(cmd,childProcess,stdoutConfig,stderrConfig);const{getInputFd,getOutputFd}=yield*setupAdditionalFds(cmd,childProcess,resolvedAdditionalFds);const isRunning=map7(isDone2(exitSignal),(done4)=>!done4);const exitCode=flatMap4(_await(exitSignal),([code,signal])=>{if(isNotNull(code)){return succeed6(ExitCode(code))}const error2=new globalThis.Error(`Process interrupted due to receipt of signal: '${signal}'`);return fail6(toPlatformError("exitCode",error2,cmd))});const kill=(options)=>{const killWithTimeout=withTimeout(childProcess,cmd,options);return killWithTimeout((command,childProcess2,signal)=>killProcessGroup(command,childProcess2,signal).pipe(catch_2(()=>killProcess(command,childProcess2,signal)),andThen2(_await(exitSignal)))).pipe(asVoid2)};return makeHandle({pid,exitCode,isRunning,kill,stdin,stdout,stderr,all:all5,getInputFd,getOutputFd,unref})}case"PipedCommand":{const{commands:commands2,pipeOptions}=flattenCommand(cmd);const[root,...pipeline]=commands2;const handles=[yield*spawnCommand(root)];for(let i=0;i<pipeline.length;i++){const command=pipeline[i];const options=pipeOptions[i]??{};const stdinConfig=resolveStdinOption(command.options);const sourceStream=unwrap3(succeed6(getSourceStream(handles[handles.length-1],options.from)));const toOption=options.to??"stdin";if(toOption==="stdin"){handles.push(yield*spawnCommand(make33(command.command,command.args,{...command.options,stdin:{...stdinConfig,stream:sourceStream}})))}else{const fd=parseFdName(toOption);if(isNotUndefined(fd)){const fdName2=fdName(fd);const existingFds=command.options.additionalFds??{};handles.push(yield*spawnCommand(make33(command.command,command.args,{...command.options,additionalFds:{...existingFds,[fdName2]:{type:"input",stream:sourceStream}}})))}else{handles.push(yield*spawnCommand(make33(command.command,command.args,{...command.options,stdin:{...stdinConfig,stream:sourceStream}})))}}}const handle=handles[handles.length-1];const unref=gen2(function*(){const rerefs=[];for(const handle2 of handles){rerefs.push(yield*handle2.unref)}return forEach2([...rerefs].reverse(),(reref)=>reref,{discard:true})});return makeHandle({pid:handle.pid,exitCode:handle.exitCode,isRunning:handle.isRunning,kill:handle.kill,stdin:handle.stdin,stdout:handle.stdout,stderr:handle.stderr,all:handle.all,getInputFd:handle.getInputFd,getOutputFd:handle.getOutputFd,unref})}}});return make32(spawnCommand)});var layer4=effect(ChildProcessSpawner,make35);var flattenCommand=(command)=>{const commands2=[];const pipeOptions=[];const flatten4=(cmd)=>{switch(cmd._tag){case"StandardCommand":{commands2.push(cmd);break}case"PipedCommand":{flatten4(cmd.left);pipeOptions.push(cmd.options);flatten4(cmd.right);break}}};flatten4(command);if(commands2.length===0){throw new Error("flattenCommand produced empty commands array")}const[first,...rest]=commands2;const nonEmptyCommands=[first,...rest];return{commands:nonEmptyCommands,pipeOptions}};var TypeId42="~effect/platform/Crypto";var Crypto=Service("effect/Crypto");var make36=(impl)=>{const randomBytesUnsafe=impl.randomBytes;const randomBytes=(size6)=>map7(validateSize("randomBytes",size6),randomBytesUnsafe);const nextDoubleUnsafe=()=>{const bytes=randomBytesUnsafe(7);const value3=(bytes[0]&31)*2**48+bytes[1]*2**40+bytes[2]*2**32+bytes[3]*2**24+bytes[4]*2**16+bytes[5]*2**8+bytes[6];return value3/2**53};const nextIntUnsafe=()=>Math.floor(nextDoubleUnsafe()*(Number.MAX_SAFE_INTEGER-Number.MIN_SAFE_INTEGER+1))+Number.MIN_SAFE_INTEGER;return Crypto.of({[TypeId42]:TypeId42,randomBytes,nextDoubleUnsafe,nextIntUnsafe,digest:impl.digest,random:sync2(()=>nextDoubleUnsafe()),randomBoolean:sync2(()=>nextDoubleUnsafe()>0.5),randomInt:sync2(()=>nextIntUnsafe()),randomBetween:(min5,max5)=>sync2(()=>nextDoubleUnsafe()*(max5-min5)+min5),randomIntBetween(min5,max5,options){const extra=options?.halfOpen===true?0:1;return sync2(()=>{const minInt=Math.ceil(min5);const maxInt=Math.floor(max5);return Math.floor(nextDoubleUnsafe()*(maxInt-minInt+extra))+minInt})},randomShuffle:(elements)=>sync2(()=>{const buffer2=Array.from(elements);for(let i=buffer2.length-1;i>=1;i=i-1){const index2=Math.min(i,Math.floor(nextDoubleUnsafe()*(i+1)));const value3=buffer2[i];buffer2[i]=buffer2[index2];buffer2[index2]=value3}return buffer2}),randomUUIDv4:sync2(()=>formatUUIDv4(randomBytesUnsafe(16))),randomUUIDv7:clockWith2((clock)=>succeed6(formatUUIDv7(clock.currentTimeMillisUnsafe(),randomBytesUnsafe(16))))})};var validateSize=(method,size6)=>Number.isSafeInteger(size6)&&size6>=0?succeed6(size6):fail6(badArgument({module:"Crypto",method,description:"size must be a non-negative safe integer"}));var hex=(byte)=>byte.toString(16).padStart(2,"0");var formatUUID=(bytes)=>{const segments=[bytes.subarray(0,4),bytes.subarray(4,6),bytes.subarray(6,8),bytes.subarray(8,10),bytes.subarray(10,16)];return segments.map((segment)=>Array.from(segment,hex).join("")).join("-")};var formatUUIDv4=(bytes)=>{bytes[6]=bytes[6]&15|64;bytes[8]=bytes[8]&63|128;return formatUUID(bytes)};var maxUUIDv7Timestamp=2**48-1;var formatUUIDv7=(timestampMillis,bytes)=>{const timestamp=Math.min(Math.max(0,Math.trunc(timestampMillis)),maxUUIDv7Timestamp);bytes[0]=Math.floor(timestamp/2**40);bytes[1]=Math.floor(timestamp/2**32)&255;bytes[2]=Math.floor(timestamp/2**24)&255;bytes[3]=Math.floor(timestamp/2**16)&255;bytes[4]=Math.floor(timestamp/2**8)&255;bytes[5]=timestamp&255;bytes[6]=bytes[6]&15|112;bytes[8]=bytes[8]&63|128;return formatUUID(bytes)};import*as NodeCrypto from"node:crypto";var toHashAlgorithm=(algorithm)=>{switch(algorithm){case"SHA-1":return"sha1";case"SHA-256":return"sha256";case"SHA-384":return"sha384";case"SHA-512":return"sha512"}};var digest=(algorithm,data)=>try_3({try:()=>Uint8Array.from(NodeCrypto.createHash(toHashAlgorithm(algorithm)).update(data).digest()),catch:(cause)=>systemError({module:"Crypto",method:"digest",_tag:"Unknown",description:"Could not compute digest",cause})});var make37=make36({randomBytes:NodeCrypto.randomBytes,digest});var layer5=succeed5(Crypto,make37);var layer6=layer5;import*as Crypto2 from"node:crypto";import*as NFS from"node:fs";import*as OS from"node:os";import*as Path2 from"node:path";var handleBadArgument=(method)=>(err)=>badArgument({module:"FileSystem",method,description:err.message??String(err)});var access2=(()=>{const nodeAccess=effectify(NFS.access,handleErrnoException("FileSystem","access"),handleBadArgument("access"));return(path4,options)=>{let mode=NFS.constants.F_OK;if(options?.readable){mode|=NFS.constants.R_OK}if(options?.writable){mode|=NFS.constants.W_OK}return nodeAccess(path4,mode)}})();var copy2=(()=>{const nodeCp=effectify(NFS.cp,handleErrnoException("FileSystem","copy"),handleBadArgument("copy"));return(fromPath,toPath,options)=>nodeCp(fromPath,toPath,{force:options?.overwrite??false,preserveTimestamps:options?.preserveTimestamps??false,recursive:true})})();var copyFile2=(()=>{const nodeCopyFile=effectify(NFS.copyFile,handleErrnoException("FileSystem","copyFile"),handleBadArgument("copyFile"));return(fromPath,toPath)=>nodeCopyFile(fromPath,toPath)})();var chmod2=(()=>{const nodeChmod=effectify(NFS.chmod,handleErrnoException("FileSystem","chmod"),handleBadArgument("chmod"));return(path4,mode)=>nodeChmod(path4,mode)})();var chown2=(()=>{const nodeChown=effectify(NFS.chown,handleErrnoException("FileSystem","chown"),handleBadArgument("chown"));return(path4,uid,gid)=>nodeChown(path4,uid,gid)})();var glob2=(()=>{const nodeGlob=effectify(NFS.glob,handleErrnoException("FileSystem","glob"),handleBadArgument("glob"));return(pattern,options)=>nodeGlob(pattern,{cwd:options?.root,exclude:options?.exclude})})();var link3=(()=>{const nodeLink=effectify(NFS.link,handleErrnoException("FileSystem","link"),handleBadArgument("link"));return(existingPath,newPath)=>nodeLink(existingPath,newPath)})();var makeDirectory=(()=>{const nodeMkdir=effectify(NFS.mkdir,handleErrnoException("FileSystem","makeDirectory"),handleBadArgument("makeDirectory"));return(path4,options)=>nodeMkdir(path4,{recursive:options?.recursive??false,mode:options?.mode})})();var makeTempDirectoryFactory=(method)=>{const nodeMkdtemp=effectify(NFS.mkdtemp,handleErrnoException("FileSystem",method),handleBadArgument(method));return(options)=>suspend2(()=>{const prefix=options?.prefix??"";const directory3=typeof options?.directory==="string"?Path2.join(options.directory,"."):OS.tmpdir();return nodeMkdtemp(prefix?Path2.join(directory3,prefix):directory3+"/")})};var makeTempDirectory=makeTempDirectoryFactory("makeTempDirectory");var removeFactory=(method)=>{const nodeRm=effectify(NFS.rm,handleErrnoException("FileSystem",method),handleBadArgument(method));return(path4,options)=>nodeRm(path4,{recursive:options?.recursive??false,force:options?.force??false})};var remove4=removeFactory("remove");var makeTempDirectoryScoped=(()=>{const makeDirectory2=makeTempDirectoryFactory("makeTempDirectoryScoped");const removeDirectory=removeFactory("makeTempDirectoryScoped");return(options)=>acquireRelease2(makeDirectory2(options),(directory3)=>orDie2(removeDirectory(directory3,{recursive:true})))})();var openFactory=(method)=>{const nodeOpen=effectify(NFS.open,handleErrnoException("FileSystem",method),handleBadArgument(method));const nodeClose=effectify(NFS.close,handleErrnoException("FileSystem",method),handleBadArgument(method));return(path4,options)=>pipe(acquireRelease2(nodeOpen(path4,options?.flag??"r",options?.mode),(fd)=>orDie2(nodeClose(fd))),map7((fd)=>makeFile(FileDescriptor(fd),options?.flag?.startsWith("a")??false)))};var open2=openFactory("open");var makeFile=(()=>{const nodeReadFactory=(method)=>effectify(NFS.read,handleErrnoException("FileSystem",method),handleBadArgument(method));const nodeRead=nodeReadFactory("read");const nodeReadAlloc=nodeReadFactory("readAlloc");const nodeStat=effectify(NFS.fstat,handleErrnoException("FileSystem","stat"),handleBadArgument("stat"));const nodeTruncate=effectify(NFS.ftruncate,handleErrnoException("FileSystem","truncate"),handleBadArgument("truncate"));const nodeSync=effectify(NFS.fsync,handleErrnoException("FileSystem","sync"),handleBadArgument("sync"));const nodeWriteFactory=(method)=>effectify(NFS.write,handleErrnoException("FileSystem",method),handleBadArgument(method));const nodeWrite=nodeWriteFactory("write");const nodeWriteAll=nodeWriteFactory("writeAll");class FileImpl{[FileTypeId];fd;append;position=BigInt(0);constructor(fd,append3){this[FileTypeId]=FileTypeId;this.fd=fd;this.append=append3}get stat(){return map7(nodeStat(this.fd),makeFileInfo)}get sync(){return nodeSync(this.fd)}seek(offset,from){const offsetSize=Size(offset);return sync2(()=>{if(from==="start"){this.position=offsetSize}else if(from==="current"){this.position=this.position+offsetSize}return this.position})}read(buffer2){return suspend2(()=>{const position=this.position;return map7(nodeRead(this.fd,{buffer:buffer2,position}),(bytesRead)=>{const sizeRead=Size(bytesRead);this.position=position+sizeRead;return sizeRead})})}readAlloc(size6){const sizeNumber=Number(size6);return suspend2(()=>{const buffer2=Buffer.allocUnsafeSlow(sizeNumber);const position=this.position;return map7(nodeReadAlloc(this.fd,{buffer:buffer2,position}),(bytesRead)=>{if(bytesRead===0){return none2()}this.position=position+BigInt(bytesRead);if(bytesRead===sizeNumber){return some2(buffer2)}const dst=Buffer.allocUnsafeSlow(bytesRead);buffer2.copy(dst,0,0,bytesRead);return some2(dst)})})}truncate(length){return map7(nodeTruncate(this.fd,length?Number(length):undefined),()=>{if(!this.append){const len=BigInt(length??0);if(this.position>len){this.position=len}}})}write(buffer2){return suspend2(()=>{const position=this.position;return map7(nodeWrite(this.fd,buffer2,undefined,undefined,this.append?undefined:Number(position)),(bytesWritten)=>{const sizeWritten=Size(bytesWritten);if(!this.append){this.position=position+sizeWritten}return sizeWritten})})}writeAllChunk(buffer2){return suspend2(()=>{const position=this.position;return flatMap4(nodeWriteAll(this.fd,buffer2,undefined,undefined,this.append?undefined:Number(position)),(bytesWritten)=>{if(bytesWritten===0){return fail6(systemError({module:"FileSystem",method:"writeAll",_tag:"WriteZero",pathOrDescriptor:this.fd,description:"write returned 0 bytes written"}))}if(!this.append){this.position=position+BigInt(bytesWritten)}return bytesWritten<buffer2.length?this.writeAllChunk(buffer2.subarray(bytesWritten)):void_3})})}writeAll(buffer2){return this.writeAllChunk(buffer2)}}return(fd,append3)=>new FileImpl(fd,append3)})();var makeTempFileFactory=(method)=>{const makeDirectory2=makeTempDirectoryFactory(method);return fnUntraced2(function*(options){const directory3=yield*makeDirectory2(options);const random2=Crypto2.randomBytes(6).toString("hex");const name=Path2.join(directory3,options?.suffix?`${random2}${options.suffix}`:random2);yield*writeFile2(name,new Uint8Array(0));return name})};var makeTempFile=makeTempFileFactory("makeTempFile");var makeTempFileScoped=(()=>{const makeFile2=makeTempFileFactory("makeTempFileScoped");const removeDirectory=removeFactory("makeTempFileScoped");return(options)=>acquireRelease2(makeFile2(options),(file4)=>orDie2(removeDirectory(Path2.dirname(file4),{recursive:true})))})();var readDirectory=(path4,options)=>tryPromise2({try:()=>NFS.promises.readdir(path4,options),catch:(err)=>handleErrnoException("FileSystem","readDirectory")(err,[path4])});var readFile2=(path4)=>callback2((resume,signal)=>{try{NFS.readFile(path4,{signal},(err,data)=>{if(err){resume(fail6(handleErrnoException("FileSystem","readFile")(err,[path4])))}else{resume(succeed6(data))}})}catch(err){resume(fail6(handleBadArgument("readFile")(err)))}});var readLink=(()=>{const nodeReadLink=effectify(NFS.readlink,handleErrnoException("FileSystem","readLink"),handleBadArgument("readLink"));return(path4)=>nodeReadLink(path4)})();var realPath=(()=>{const nodeRealPath=effectify(NFS.realpath,handleErrnoException("FileSystem","realPath"),handleBadArgument("realPath"));return(path4)=>nodeRealPath(path4)})();var rename2=(()=>{const nodeRename=effectify(NFS.rename,handleErrnoException("FileSystem","rename"),handleBadArgument("rename"));return(oldPath,newPath)=>nodeRename(oldPath,newPath)})();var makeFileInfo=(stat2)=>({type:stat2.isFile()?"File":stat2.isDirectory()?"Directory":stat2.isSymbolicLink()?"SymbolicLink":stat2.isBlockDevice()?"BlockDevice":stat2.isCharacterDevice()?"CharacterDevice":stat2.isFIFO()?"FIFO":stat2.isSocket()?"Socket":"Unknown",mtime:fromNullishOr(stat2.mtime),atime:fromNullishOr(stat2.atime),birthtime:fromNullishOr(stat2.birthtime),dev:stat2.dev,rdev:fromNullishOr(stat2.rdev),ino:fromNullishOr(stat2.ino),mode:stat2.mode,nlink:fromNullishOr(stat2.nlink),uid:fromNullishOr(stat2.uid),gid:fromNullishOr(stat2.gid),size:Size(stat2.size),blksize:stat2.blksize!==undefined?some2(Size(stat2.blksize)):none2(),blocks:fromNullishOr(stat2.blocks)});var stat2=(()=>{const nodeStat=effectify(NFS.stat,handleErrnoException("FileSystem","stat"),handleBadArgument("stat"));return(path4)=>map7(nodeStat(path4),makeFileInfo)})();var symlink2=(()=>{const nodeSymlink=effectify(NFS.symlink,handleErrnoException("FileSystem","symlink"),handleBadArgument("symlink"));return(target,path4)=>nodeSymlink(target,path4)})();var truncate3=(()=>{const nodeTruncate=effectify(NFS.truncate,handleErrnoException("FileSystem","truncate"),handleBadArgument("truncate"));return(path4,length)=>nodeTruncate(path4,length!==undefined?Number(length):undefined)})();var utimes2=(()=>{const nodeUtimes=effectify(NFS.utimes,handleErrnoException("FileSystem","utime"),handleBadArgument("utime"));return(path4,atime,mtime)=>nodeUtimes(path4,atime,mtime)})();var watchNode=(path4)=>callback3((queue)=>acquireRelease2(sync2(()=>{const watcher=NFS.watch(path4,{recursive:true},(event,path5)=>{if(!path5)return;switch(event){case"rename":{runFork2(matchEffect3(stat2(path5),{onSuccess:(_)=>offer(queue,{_tag:"Create",path:path5}),onFailure:(_)=>offer(queue,{_tag:"Remove",path:path5})}));return}case"change":{offerUnsafe(queue,{_tag:"Update",path:path5});return}}});watcher.on("error",(error2)=>{failCauseUnsafe(queue,fail5(systemError({module:"FileSystem",_tag:"Unknown",method:"watch",pathOrDescriptor:path4,cause:error2})))});watcher.on("close",()=>{endUnsafe(queue)});return watcher}),(watcher)=>sync2(()=>watcher.close())));var watch2=(backend,path4)=>stat2(path4).pipe(map7((stat3)=>backend.pipe(flatMap((_)=>_.register(path4,stat3)),getOrElse(()=>watchNode(path4)))),unwrap3);var writeFile2=(path4,data,options)=>callback2((resume,signal)=>{try{NFS.writeFile(path4,data,{signal,flag:options?.flag,mode:options?.mode},(err)=>{if(err){resume(fail6(handleErrnoException("FileSystem","writeFile")(err,[path4])))}else{resume(void_3)}})}catch(err){resume(fail6(handleBadArgument("writeFile")(err)))}});var makeFileSystem=map7(serviceOption2(WatchBackend),(backend)=>make19({access:access2,chmod:chmod2,chown:chown2,copy:copy2,copyFile:copyFile2,glob:glob2,link:link3,makeDirectory,makeTempDirectory,makeTempDirectoryScoped,makeTempFile,makeTempFileScoped,open:open2,readDirectory,readFile:readFile2,readLink,realPath,remove:remove4,rename:rename2,stat:stat2,symlink:symlink2,truncate:truncate3,utimes:utimes2,watch(path4){return watch2(backend,path4)},writeFile:writeFile2}));var layer7=effect(FileSystem)(makeFileSystem);var layer8=layer7;import*as NodePath from"node:path";import*as NodeUrl from"node:url";var fromFileUrl2=(url2)=>try_3({try:()=>NodeUrl.fileURLToPath(url2),catch:(cause)=>new BadArgument({module:"Path",method:"fromFileUrl",cause})});var toFileUrl2=(path4)=>try_3({try:()=>NodeUrl.pathToFileURL(path4),catch:(cause)=>new BadArgument({module:"Path",method:"toFileUrl",cause})});var layerPosix=succeed5(Path)({[TypeId29]:TypeId29,...NodePath.posix,fromFileUrl:fromFileUrl2,toFileUrl:toFileUrl2});var layerWin32=succeed5(Path)({[TypeId29]:TypeId29,...NodePath.win32,fromFileUrl:fromFileUrl2,toFileUrl:toFileUrl2});var layer9=succeed5(Path)({[TypeId29]:TypeId29,...NodePath,fromFileUrl:fromFileUrl2,toFileUrl:toFileUrl2});var layer10=layer9;var layer11=succeed5(Stdio,make30({args:sync2(()=>process.argv.slice(2)),stdout:(options)=>fromWritable({evaluate:()=>process.stdout,onError:(cause)=>systemError({module:"Stdio",method:"stdout",_tag:"Unknown",cause}),endOnDone:options?.endOnDone??false}),stderr:(options)=>fromWritable({evaluate:()=>process.stderr,onError:(cause)=>systemError({module:"Stdio",method:"stderr",_tag:"Unknown",cause}),endOnDone:options?.endOnDone??false}),stdin:fromReadable({evaluate:()=>process.stdin,onError:(cause)=>systemError({module:"Stdio",method:"stdin",_tag:"Unknown",cause}),closeOnDone:false})}));var layer12=layer11;import*as readline from"node:readline";var make38=fnUntraced2(function*(shouldQuit=defaultShouldQuit){const stdin=process.stdin;const stdout=process.stdout;const rlRef=yield*make18({acquire:acquireRelease2(sync2(()=>{const rl=readline.createInterface({input:stdin,escapeCodeTimeout:50});readline.emitKeypressEvents(stdin,rl);if(stdin.isTTY){stdin.setRawMode(true)}return rl}),(rl)=>sync2(()=>{if(stdin.isTTY){stdin.setRawMode(false)}rl.close()}))});const columns=sync2(()=>stdout.columns??0);const rows=sync2(()=>stdout.rows??0);const readInput=gen2(function*(){yield*get3(rlRef);const queue=yield*make16();const handleKeypress=(s,k)=>{const userInput={input:fromUndefinedOr(s),key:{name:k.name??"",ctrl:!!k.ctrl,meta:!!k.meta,shift:!!k.shift}};offerUnsafe(queue,userInput);if(shouldQuit(userInput)){endUnsafe(queue)}};yield*addFinalizer3(()=>sync2(()=>stdin.off("keypress",handleKeypress)));stdin.on("keypress",handleKeypress);return queue});const readLine=scoped2(flatMap4(get3(rlRef),(readlineInterface)=>callback2((resume)=>{const onLine=(line)=>resume(succeed6(line));readlineInterface.once("line",onLine);return sync2(()=>readlineInterface.off("line",onLine))})));const display=(prompt)=>uninterruptible2(callback2((resume)=>{stdout.write(prompt,(err)=>isNullish(err)?resume(void_3):resume(fail6(badArgument({module:"Terminal",method:"display",description:"Failed to write prompt to stdout",cause:err}))))}));return make28({columns,rows,readInput,readLine,display})});var layer13=effect(Terminal,make38(defaultShouldQuit));function defaultShouldQuit(input){return input.key.ctrl&&(input.key.name==="c"||input.key.name==="d")}var layer14=layer13;var layer15=layer4.pipe(provideMerge(mergeAll2(layer8,layer6,layer10,layer12,layer14)));var decode2=(schema2)=>()=>{const decode3=decodeEffect2(NonEmptyArray(schema2));return fromTransform((upstream,_scope)=>succeed6(flatMap4(upstream,(chunk)=>decode3(chunk))))};var TypeId43="~effect/match/Match/Matcher";var TypeMatcherProto={[TypeId43]:{_input:identity,_filters:identity,_remaining:identity,_result:identity,_return:identity},_tag:"TypeMatcher",add(_case){return makeTypeMatcher([...this.cases,_case])},pipe(){return pipeArguments(this,arguments)}};function makeTypeMatcher(cases){const matcher=Object.create(TypeMatcherProto);matcher.cases=cases;return matcher}var ValueMatcherProto={[TypeId43]:{_input:identity,_filters:identity,_result:identity,_return:identity},_tag:"ValueMatcher",add(_case){if(isSuccess2(this.value)){return this}if(_case._tag==="When"&&_case.guard(this.provided)===true){return makeValueMatcher(this.provided,succeed2(_case.evaluate(this.provided)))}else if(_case._tag==="Not"&&_case.guard(this.provided)===false){return makeValueMatcher(this.provided,succeed2(_case.evaluate(this.provided)))}return this},pipe(){return pipeArguments(this,arguments)}};function makeValueMatcher(provided,value3){const matcher=Object.create(ValueMatcherProto);matcher.provided=provided;matcher.value=value3;return matcher}var makeWhen=(guard,evaluate2)=>({_tag:"When",guard,evaluate:evaluate2});var makePredicate=(pattern)=>{if(typeof pattern==="function"){return pattern}else if(Array.isArray(pattern)){const predicates=pattern.map(makePredicate);const len=predicates.length;return(u)=>{if(!Array.isArray(u)){return false}for(let i=0;i<len;i++){if(predicates[i](u[i])===false){return false}}return true}}else if(pattern!==null&&typeof pattern==="object"){const keysAndPredicates=Object.entries(pattern).map(([k,p])=>[k,makePredicate(p)]);const len=keysAndPredicates.length;return(u)=>{if(typeof u!=="object"||u===null){return false}for(let i=0;i<len;i++){const[key,predicate]=keysAndPredicates[i];if(!(key in u)||predicate(u[key])===false){return false}}return true}}return(u)=>u===pattern};var value3=(i)=>makeValueMatcher(i,fail2(i));var when3=(pattern,f)=>(self)=>self.add(makeWhen(makePredicate(pattern),f));var discriminator=(field)=>(...pattern)=>{const f=pattern[pattern.length-1];const values3=pattern.slice(0,-1);const pred=values3.length===1?(_)=>_!=null&&_[field]===values3[0]:(_)=>_!=null&&values3.includes(_[field]);return(self)=>self.add(makeWhen(pred,f))};var tag2=discriminator("_tag");var result3=(self)=>{if(self._tag==="ValueMatcher"){return self.value}const len=self.cases.length;if(len===1){const _case=self.cases[0];return(input)=>{if(_case._tag==="When"&&_case.guard(input)===true){return succeed2(_case.evaluate(input))}else if(_case._tag==="Not"&&_case.guard(input)===false){return succeed2(_case.evaluate(input))}return fail2(input)}}return(input)=>{for(let i=0;i<len;i++){const _case=self.cases[i];if(_case._tag==="When"&&_case.guard(input)===true){return succeed2(_case.evaluate(input))}else if(_case._tag==="Not"&&_case.guard(input)===false){return succeed2(_case.evaluate(input))}}return fail2(input)}};var getExhaustiveAbsurdErrorMessage="effect/match/Match/exhaustive: absurd";var exhaustive=(self)=>{const toResult=result3(self);if(isResult2(toResult)){if(isSuccess2(toResult)){return toResult.success}throw new Error(getExhaustiveAbsurdErrorMessage)}return(u)=>{const result4=toResult(u);if(isSuccess2(result4)){return result4.success}throw new Error(getExhaustiveAbsurdErrorMessage)}};var value4=value3;var when4=when3;var tag3=tag2;var exhaustive2=exhaustive;var TypeId44="~effect/Ref";var RefProto={[TypeId44]:{_A:identity},...PipeInspectableProto,toJSON(){return{_id:"Ref",ref:this.ref}}};var get6=(self)=>sync2(()=>self.ref.current);var update2=dual(2,(self,f)=>sync2(()=>{self.ref.current=f(self.ref.current)}));var toJsonAnnotationsBlacklist=new Set([...fromASTBlacklist,"expected","contentMediaType","contentSchema"]);var fromASTs2=fromASTs;var toJsonSchemaMultiDocument2=toJsonSchemaMultiDocument;var toCodeAnnotationsBlacklist=new Set([...toJsonAnnotationsBlacklist,"typeConstructor","generation","brands"]);var EnvironmentSecret=exports_Schema.Redacted(exports_Schema.NonEmptyString);class EnvironmentStartupError extends exports_Schema.TaggedErrorClass()("@punks/env/EnvironmentStartupError",{configuration:exports_Schema.NonEmptyString,message:exports_Schema.Literal("Configuration is missing or invalid")}){}var makeEnvironmentConfig=(schema2)=>exports_Config.schema(schema2);var makeEnvironmentProvider=(input)=>exports_ConfigProvider.fromEnv({env:Object.fromEntries(Object.entries(input).filter((entry)=>entry[1]!==undefined&&entry[1].length>0))});var decodeEnvironment=({config,name,provider})=>config.parse(provider).pipe(exports_Effect.catchTag("ConfigError",()=>new EnvironmentStartupError({configuration:name,message:"Configuration is missing or invalid"})));var TypeId45="~effect/http/Cookies";var CookieTypeId="~effect/http/Cookies/Cookie";var Proto11={[TypeId45]:TypeId45,...BaseProto,toJSON(){return{_id:"effect/Cookies",cookies:map3(this.cookies,(cookie)=>cookie.toJSON())}},pipe(){return pipeArguments(this,arguments)}};var fromReadonlyRecord=(cookies)=>{const self=Object.create(Proto11);self.cookies=cookies;return self};var fromIterable7=(cookies)=>{const record3={};for(const cookie of cookies){record3[cookie.name]=cookie}return fromReadonlyRecord(record3)};var fromSetCookie=(headers)=>{const arrayHeaders=typeof headers==="string"?[headers]:headers;const cookies=[];for(const header of arrayHeaders){const cookie=parseSetCookie(header.trim());if(cookie){cookies.push(cookie)}}return fromIterable7(cookies)};function parseSetCookie(header){const parts=header.split(";").map((_)=>_.trim()).filter((_)=>_!=="");if(parts.length===0){return}const firstEqual=parts[0].indexOf("=");if(firstEqual===-1){return}const name=parts[0].slice(0,firstEqual);if(!fieldContentRegExp.test(name)){return}const valueEncoded=parts[0].slice(firstEqual+1);const value5=tryDecodeURIComponent(valueEncoded);if(parts.length===1){return Object.assign(Object.create(CookieProto),{name,value:value5,valueEncoded})}const options={};for(let i=1;i<parts.length;i++){const part=parts[i];const equalIndex=part.indexOf("=");const key=equalIndex===-1?part:part.slice(0,equalIndex).trim();const value6=equalIndex===-1?undefined:part.slice(equalIndex+1).trim();switch(key.toLowerCase()){case"domain":{if(value6===undefined){break}const domain2=value6.trim().replace(/^\./,"");if(domain2){options.domain=domain2}break}case"expires":{if(value6===undefined){break}const date7=new Date(value6);if(!isNaN(date7.getTime())){options.expires=date7}break}case"max-age":{if(value6===undefined){break}const maxAge=parseInt(value6,10);if(!isNaN(maxAge)){options.maxAge=seconds(maxAge)}break}case"path":{if(value6===undefined){break}if(value6[0]==="/"){options.path=value6}break}case"priority":{if(value6===undefined){break}switch(value6.toLowerCase()){case"low":options.priority="low";break;case"medium":options.priority="medium";break;case"high":options.priority="high";break}break}case"httponly":{options.httpOnly=true;break}case"secure":{options.secure=true;break}case"partitioned":{options.partitioned=true;break}case"samesite":{if(value6===undefined){break}switch(value6.toLowerCase()){case"lax":options.sameSite="lax";break;case"strict":options.sameSite="strict";break;case"none":options.sameSite="none";break}break}}}return Object.assign(Object.create(CookieProto),{name,value:value5,valueEncoded,options:Object.keys(options).length>0?options:undefined})}var isEmpty3=(self)=>isEmptyRecord(self.cookies);var fieldContentRegExp=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;var CookieProto={[CookieTypeId]:CookieTypeId,...BaseProto,toJSON(){return{_id:"effect/Cookies/Cookie",name:this.name,value:this.value,options:this.options}}};var merge5=dual(2,(self,that)=>fromReadonlyRecord({...self.cookies,...that.cookies}));var toCookieHeader=(self)=>Object.values(self.cookies).map((cookie)=>`${cookie.name}=${cookie.valueEncoded}`).join("; ");var tryDecodeURIComponent=(str)=>{try{return decodeURIComponent(str)}catch(_){return str}};var exports_FetchHttpClient={};__export(exports_FetchHttpClient,{layer:()=>layer16,RequestInit:()=>RequestInit,Fetch:()=>Fetch});var TypeId46=Symbol.for("~effect/http/Headers");var Proto12=Object.defineProperties(Object.create(null),{[TypeId46]:{value:TypeId46},[symbolRedactable]:{value(context4){return redact4(this,get(context4,CurrentRedactedNames))}},toJSON:{value(){return redact(this)}},[symbol2]:{value(that){return Equivalence5(this,that)}},[symbol]:{value(){return structure(this)}},toString:{value:BaseProto.toString},[NodeInspectSymbol]:{value:BaseProto[NodeInspectSymbol]}});var make39=(input)=>Object.assign(Object.create(Proto12),input);var Equivalence5=makeEquivalence4(strictEqual());var empty10=Object.create(Proto12);var fromInput2=(input)=>{if(input===undefined){return empty10}else if(Symbol.iterator in input){const out2=Object.create(Proto12);for(const[k,v]of input){out2[k.toLowerCase()]=v}return out2}const out=Object.create(Proto12);for(const[k,v]of Object.entries(input)){if(Array.isArray(v)){out[k.toLowerCase()]=v.join(", ")}else if(v!==undefined){out[k.toLowerCase()]=v}}return out};var fromRecordUnsafe=(input)=>Object.setPrototypeOf(input,Proto12);var set5=dual(3,(self,key,value5)=>{const out=make39(self);out[key.toLowerCase()]=value5;return out});var setAll=dual(2,(self,headers)=>make39({...self,...fromInput2(headers)}));var merge6=dual(2,(self,headers)=>{const out=make39(self);Object.assign(out,headers);return out});var remove6=dual(2,(self,key)=>{const out=make39(self);delete out[key.toLowerCase()];return out});var redact4=dual(2,(self,key)=>{const out={...self};const modify3=(key2)=>{if(typeof key2==="string"){const k=key2.toLowerCase();if(k in self){out[k]=make9(self[k])}}else{for(const name in self){if(key2.test(name)){out[name]=make9(self[name])}}}};if(Array.isArray(key)){for(let i=0;i<key.length;i++){modify3(key[i])}}else{modify3(key)}return out});var CurrentRedactedNames=Reference("effect/Headers/CurrentRedactedNames",{defaultValue:()=>["authorization","cookie","set-cookie","x-api-key"]});var exports_HttpClient={};__export(exports_HttpClient,{withScope:()=>withScope,withRateLimiter:()=>withRateLimiter,withCookiesRef:()=>withCookiesRef,transformResponse:()=>transformResponse,transform:()=>transform5,tapRequest:()=>tapRequest,tapError:()=>tapError4,tap:()=>tap3,retryTransient:()=>retryTransient,retry:()=>retry4,put:()=>put2,post:()=>post2,patch:()=>patch2,options:()=>options2,mapRequestInputEffect:()=>mapRequestInputEffect,mapRequestInput:()=>mapRequestInput,mapRequestEffect:()=>mapRequestEffect,mapRequest:()=>mapRequest,makeWith:()=>makeWith2,make:()=>make43,layerMergedContext:()=>layerMergedContext,isHttpClient:()=>isHttpClient,head:()=>head2,get:()=>get8,followRedirects:()=>followRedirects,filterStatusOk:()=>filterStatusOk2,filterStatus:()=>filterStatus2,filterOrFail:()=>filterOrFail3,filterOrElse:()=>filterOrElse3,execute:()=>execute,del:()=>del2,catchTags:()=>catchTags3,catchTag:()=>catchTag3,catch:()=>catch_4,TracerPropagationEnabled:()=>TracerPropagationEnabled,TracerDisabledWhen:()=>TracerDisabledWhen,SpanNameGenerator:()=>SpanNameGenerator,HttpClient:()=>HttpClient});var TypeId47="~effect/http/HttpClientError";var isHttpClientError=(u)=>hasProperty(u,TypeId47);class HttpClientError extends TaggedError2("HttpClientError"){constructor(props){if("cause"in props.reason){super({...props,cause:props.reason.cause})}else{super(props)}}[TypeId47]=TypeId47;get request(){return this.reason.request}get response(){return"response"in this.reason?this.reason.response:undefined}get message(){return this.reason.message}}var formatReason=(tag4)=>tag4.endsWith("Error")?tag4.slice(0,-5):tag4;var formatMessage=(reason,description,info)=>description?`${reason}: ${description} (${info})`:`${reason} error (${info})`;class TransportError extends TaggedError2("TransportError"){get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){return formatMessage(formatReason(this._tag),this.description,this.methodAndUrl)}}class InvalidUrlError extends TaggedError2("InvalidUrlError"){get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){return formatMessage(formatReason(this._tag),this.description,this.methodAndUrl)}}class StatusCodeError extends TaggedError2("StatusCodeError"){get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){const info=`${this.response.status} ${this.methodAndUrl}`;return formatMessage(formatReason(this._tag),this.description,info)}}class DecodeError extends TaggedError2("DecodeError"){get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){const info=`${this.response.status} ${this.methodAndUrl}`;return formatMessage(formatReason(this._tag),this.description,info)}}class EmptyBodyError extends TaggedError2("EmptyBodyError"){get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){const info=`${this.response.status} ${this.methodAndUrl}`;return formatMessage(formatReason(this._tag),this.description,info)}}var exports_HttpClientRequest={};__export(exports_HttpClientRequest,{updateUrl:()=>updateUrl,trace:()=>trace,toWebResult:()=>toWebResult,toWeb:()=>toWeb,toUrl:()=>toUrl,setUrlParams:()=>setUrlParams,setUrlParam:()=>setUrlParam,setUrl:()=>setUrl,setMethod:()=>setMethod,setHeaders:()=>setHeaders,setHeader:()=>setHeader,setHash:()=>setHash,setBody:()=>setBody,schemaBodyJson:()=>schemaBodyJson,removeHash:()=>removeHash,put:()=>put,prependUrl:()=>prependUrl,post:()=>post,patch:()=>patch,options:()=>options,modify:()=>modify3,makeWith:()=>makeWith,make:()=>make42,isHttpClientRequest:()=>isHttpClientRequest,head:()=>head,get:()=>get7,fromWeb:()=>fromWeb,empty:()=>empty13,delete:()=>del,bodyUrlParams:()=>bodyUrlParams,bodyUint8Array:()=>bodyUint8Array,bodyText:()=>bodyText,bodyStream:()=>bodyStream,bodyJsonUnsafe:()=>bodyJsonUnsafe,bodyJson:()=>bodyJson,bodyFormDataRecord:()=>bodyFormDataRecord,bodyFormData:()=>bodyFormData,bodyFile:()=>bodyFile,bearerToken:()=>bearerToken,basicAuth:()=>basicAuth,appendUrlParams:()=>appendUrlParams,appendUrlParam:()=>appendUrlParam,appendUrl:()=>appendUrl,acceptJson:()=>acceptJson,accept:()=>accept});var TypeId48="~effect/http/UrlParams";var isUrlParams=(u)=>hasProperty(u,TypeId48);var Proto13={...PipeInspectableProto,[TypeId48]:TypeId48,[Symbol.iterator](){return this.params[Symbol.iterator]()},toJSON(){return{_id:"UrlParams",params:Object.fromEntries(this.params)}},[symbol2](that){return Equivalence6(this,that)},[symbol](){return array(this.params.flat())}};var make40=(params)=>{const self=Object.create(Proto13);self.params=params;return self};var fromInput3=(input)=>{if(isUrlParams(input)){return input}const parsed=fromInputNested(input);const out=[];for(let i=0;i<parsed.length;i++){if(Array.isArray(parsed[i][0])){const[keys3,value5]=parsed[i];out.push([`${keys3[0]}[${keys3.slice(1).join("][")}]`,value5])}else{out.push(parsed[i])}}return make40(out)};var fromInputNested=(input)=>{const entries3=typeof input[Symbol.iterator]==="function"?fromIterable(input):Object.entries(input);const out=[];for(const[key,value5]of entries3){if(Array.isArray(value5)){for(let i=0;i<value5.length;i++){if(value5[i]!==undefined){out.push([key,String(value5[i])])}}}else if(typeof value5==="object"){const nested3=fromInputNested(value5);for(const[k,v]of nested3){out.push([[key,...typeof k==="string"?[k]:k],v])}}else if(value5!==undefined){out.push([key,String(value5)])}}return out};var Equivalence6=make3((a,b)=>arrayEquivalence(a.params,b.params));var arrayEquivalence=makeEquivalence5(makeEquivalence3([strictEqual(),strictEqual()]));var UrlParamsSchema=declare(isUrlParams,{typeConstructor:{_tag:"effect/http/UrlParams"},generation:{runtime:`UrlParams.UrlParamsSchema`,Type:`UrlParams.UrlParams`,Encoded:`typeof UrlParams.UrlParamsSchema["Encoded"]`,importDeclaration:`import * as UrlParams from "effect/unstable/http/UrlParams"`},expected:"UrlParams",toEquivalence:()=>Equivalence6,toCodec:()=>link()(ArraySchema(Tuple2([String5,String5])),transform2({decode:make40,encode:(self)=>self.params}))});var empty11=make40([]);var set6=dual(3,(self,key,value5)=>make40(append(filter4(self.params,([k])=>k!==key),[key,String(value5)])));var transform4=dual(2,(self,f)=>make40(f(self.params)));var setAll2=dual(2,(self,input)=>{const out=fromInput3(input);const params=out.params;const keys3=new Set;for(let i=0;i<params.length;i++){keys3.add(params[i][0])}for(let i=0;i<self.params.length;i++){if(keys3.has(self.params[i][0]))continue;params.push(self.params[i])}return out});var append3=dual(3,(self,key,value5)=>make40(append(self.params,[key,String(value5)])));var appendAll3=dual(2,(self,input)=>transform4(self,appendAll(fromInput3(input).params)));var toString=(input)=>new URLSearchParams(fromInput3(input).params).toString();var toRecord=(self)=>{const out={};for(const[k,value5]of self.params){const curr=out[k];if(curr===undefined){out[k]=value5}else if(typeof curr==="string"){out[k]=[curr,value5]}else{curr.push(value5)}}return out};var toReadonlyRecord=toRecord;var schemaRecord=UrlParamsSchema.pipe(decodeTo2(Record(String5,Union2([String5,NonEmptyArray(String5)])),transform2({decode:toReadonlyRecord,encode:fromInput3})));var TypeId49="~effect/http/HttpBody";var isHttpBody=(u)=>hasProperty(u,TypeId49);var HttpBodyErrorTypeId="~effect/http/HttpBody/HttpBodyError";class HttpBodyError extends TaggedError2("HttpBodyError"){[HttpBodyErrorTypeId]=HttpBodyErrorTypeId}class Proto14{[TypeId49];constructor(){this[TypeId49]=TypeId49}[NodeInspectSymbol](){return this.toJSON()}toString(){return format(this,{ignoreToString:true})}}class Empty2 extends Proto14{_tag="Empty";toJSON(){return{_id:"effect/HttpBody",_tag:"Empty"}}}var empty12=new Empty2;class Raw extends Proto14{_tag="Raw";body;contentType;contentLength;constructor(body,contentType,contentLength){super();this.body=body;this.contentType=contentType;this.contentLength=contentLength}toJSON(){return{_id:"effect/HttpBody",_tag:"Raw",body:this.body,contentType:this.contentType,contentLength:this.contentLength}}}var raw=(body,options)=>new Raw(body,options?.contentType,options?.contentLength);class Uint8Array3 extends Proto14{_tag="Uint8Array";body;contentType;contentLength;constructor(body,contentType,contentLength){super();this.body=body;this.contentType=contentType;this.contentLength=contentLength}toJSON(){const toString2=this.contentType.startsWith("text/")||this.contentType.endsWith("json");return{_id:"effect/HttpBody",_tag:"Uint8Array",body:toString2?new TextDecoder().decode(this.body):`Uint8Array(${this.body.length})`,contentType:this.contentType,contentLength:this.contentLength}}}var uint8Array2=(body,contentType)=>new Uint8Array3(body,contentType??"application/octet-stream",body.length);var encoder2=new TextEncoder;var text2=(body,contentType)=>uint8Array2(encoder2.encode(body),contentType??"text/plain");var jsonUnsafe=(body,contentType)=>text2(JSON.stringify(body),contentType??"application/json");var json2=(body,contentType)=>try_3({try:()=>text2(JSON.stringify(body),contentType??"application/json"),catch:(cause)=>new HttpBodyError({reason:{_tag:"JsonError"},cause})});var jsonSchema=(schema2,options)=>{const encode2=encodeUnknownEffect(toCodecJson(schema2));return(body,contentType)=>encode2(body,options).pipe(mapError3((issue)=>new HttpBodyError({reason:{_tag:"SchemaError",issue},cause:issue})),flatMap4((body2)=>json2(body2,contentType)))};var urlParams=(urlParams2,contentType)=>text2(toString(fromInput3(urlParams2)),contentType??"application/x-www-form-urlencoded");class FormData3 extends Proto14{_tag="FormData";contentType=undefined;contentLength=undefined;formData;constructor(formData){super();this.formData=formData}toJSON(){return{_id:"effect/HttpBody",_tag:"FormData",formData:this.formData}}}var formData=(body)=>new FormData3(body);var appendFormDataValue=(formData2,key,value5)=>{if(value5==null){return}if(typeof value5==="object"){formData2.append(key,value5);return}formData2.append(key,String(value5))};var formDataRecord=(entries3)=>{const data=new globalThis.FormData;for(const[key,value5]of Object.entries(entries3)){if(Array.isArray(value5)){for(const item of value5){appendFormDataValue(data,key,item)}}else{appendFormDataValue(data,key,value5)}}return formData(data)};class Stream3 extends Proto14{_tag="Stream";stream;contentType;contentLength;constructor(stream2,contentType,contentLength){super();this.stream=stream2;this.contentType=contentType;this.contentLength=contentLength}toJSON(){return{_id:"effect/HttpBody",_tag:"Stream",contentType:this.contentType,contentLength:this.contentLength}}}var stream2=(body,contentType,contentLength)=>new Stream3(body,contentType??"application/octet-stream",contentLength);var file4=(path4,options)=>flatMap4(FileSystem,(fs)=>map7(fs.stat(path4),(info)=>stream2(fs.stream(path4,options),options?.contentType,Number(info.size))));var hasBody=(method)=>method!=="GET"&&method!=="HEAD"&&method!=="OPTIONS"&&method!=="TRACE";var allShort=[["GET","get"],["POST","post"],["PUT","put"],["DELETE","del"],["PATCH","patch"],["HEAD","head"],["OPTIONS","options"],["TRACE","trace"]];class UrlError extends TaggedError2("UrlError"){}var make41=(url2,params,hash3)=>try_({try:()=>{const urlInstance=new URL(url2,baseUrl());for(let i=0;i<params.params.length;i++){const[key,value5]=params.params[i];if(value5!==undefined){urlInstance.searchParams.append(key,value5)}}if(hash3!==undefined){urlInstance.hash=hash3}return urlInstance},catch:(cause)=>new UrlError({cause})});var baseUrl=()=>{if("location"in globalThis&&globalThis.location!==undefined&&globalThis.location.origin!==undefined&&globalThis.location.pathname!==undefined){return location.origin+location.pathname}return};var TypeId50="~effect/http/HttpClientRequest";var isHttpClientRequest=(u)=>hasProperty(u,TypeId50);var Proto15={[TypeId50]:TypeId50,...BaseProto,toJSON(){return{_id:"HttpClientRequest",method:this.method,url:this.url,urlParams:this.urlParams,hash:this.hash,headers:redact(this.headers),body:this.body.toJSON()}},pipe(){return pipeArguments(this,arguments)}};function makeWith(method,url2,urlParams2,hash3,headers,body){const self=Object.create(Proto15);self.method=method;self.url=url2;self.urlParams=urlParams2;self.hash=hash3;self.headers=headers;self.body=body;return self}var empty13=makeWith("GET","",empty11,none2(),empty10,empty12);var make42=(method)=>(url2,options)=>modify3(empty13,{method,url:url2,...options??undefined});var get7=make42("GET");var post=make42("POST");var patch=make42("PATCH");var put=make42("PUT");var del=make42("DELETE");var head=make42("HEAD");var options=make42("OPTIONS");var trace=make42("TRACE");var modify3=dual(2,(self,options2)=>{let result4=self;if(options2.method){result4=setMethod(result4,options2.method)}if(options2.url){result4=setUrl(result4,options2.url)}if(options2.headers){result4=setHeaders(result4,options2.headers)}if(options2.urlParams){result4=setUrlParams(result4,options2.urlParams)}if(options2.hash){result4=setHash(result4,options2.hash)}if(options2.body){result4=setBody(result4,options2.body)}if(options2.accept){result4=accept(result4,options2.accept)}if(options2.acceptJson){result4=acceptJson(result4)}return result4});var setMethod=dual(2,(self,method)=>makeWith(method,self.url,self.urlParams,self.hash,self.headers,self.body));var setHeader=dual(3,(self,key,value5)=>makeWith(self.method,self.url,self.urlParams,self.hash,set5(self.headers,key,value5),self.body));var setHeaders=dual(2,(self,input)=>makeWith(self.method,self.url,self.urlParams,self.hash,setAll(self.headers,input),self.body));var basicAuth=dual(3,(self,username,password2)=>setHeader(self,"Authorization",`Basic ${btoa(`${stringOrRedacted(username)}:${stringOrRedacted(password2)}`)}`));var bearerToken=dual(2,(self,token)=>setHeader(self,"Authorization",`Bearer ${stringOrRedacted(token)}`));var accept=dual(2,(self,mediaType)=>setHeader(self,"Accept",mediaType));var acceptJson=accept("application/json");var setUrl=dual(2,(self,url2)=>{if(typeof url2==="string"){return makeWith(self.method,url2,self.urlParams,self.hash,self.headers,self.body)}const clone2=new URL(url2.toString());const urlParams2=fromInput3(clone2.searchParams);const hash3=fromNullishOr(clone2.hash===""?undefined:clone2.hash.slice(1));clone2.search="";clone2.hash="";return makeWith(self.method,clone2.toString(),urlParams2,hash3,self.headers,self.body)});var prependUrl=dual(2,(self,path4)=>{if(path4==="")return self;return makeWith(self.method,joinSegments(path4,self.url),self.urlParams,self.hash,self.headers,self.body)});var appendUrl=dual(2,(self,path4)=>{if(path4==="")return self;return makeWith(self.method,joinSegments(self.url,path4),self.urlParams,self.hash,self.headers,self.body)});var joinSegments=(first,second)=>{const endsWithSlash=first.endsWith("/");const startsWithSlash=second.startsWith("/");const needsTrim=endsWithSlash&&startsWithSlash;const needsSlash=!endsWithSlash&&!startsWithSlash;return needsTrim?first+second.slice(1):needsSlash?first+"/"+second:first+second};var updateUrl=dual(2,(self,f)=>makeWith(self.method,f(self.url),self.urlParams,self.hash,self.headers,self.body));var setUrlParam=dual(3,(self,key,value5)=>makeWith(self.method,self.url,set6(self.urlParams,key,value5),self.hash,self.headers,self.body));var setUrlParams=dual(2,(self,input)=>makeWith(self.method,self.url,setAll2(self.urlParams,input),self.hash,self.headers,self.body));var appendUrlParam=dual(3,(self,key,value5)=>makeWith(self.method,self.url,append3(self.urlParams,key,value5),self.hash,self.headers,self.body));var appendUrlParams=dual(2,(self,input)=>makeWith(self.method,self.url,appendAll3(self.urlParams,input),self.hash,self.headers,self.body));var setHash=dual(2,(self,hash3)=>makeWith(self.method,self.url,self.urlParams,some2(hash3),self.headers,self.body));var removeHash=(self)=>makeWith(self.method,self.url,self.urlParams,none2(),self.headers,self.body);var setBody=dual(2,(self,body)=>{let headers=self.headers;if(body._tag==="Empty"||body._tag==="FormData"){headers=remove6(remove6(headers,"Content-Type"),"Content-length")}else{if(body.contentType){headers=set5(headers,"content-type",body.contentType)}if(body.contentLength!==undefined){headers=set5(headers,"content-length",body.contentLength.toString())}}return makeWith(self.method,self.url,self.urlParams,self.hash,headers,body)});var bodyUint8Array=dual((args2)=>isHttpClientRequest(args2[0]),(self,body,contentType)=>setBody(self,uint8Array2(body,contentType)));var bodyText=dual((args2)=>isHttpClientRequest(args2[0]),(self,body,contentType)=>setBody(self,text2(body,contentType)));var bodyJson=dual(2,(self,body)=>map7(json2(body),(body2)=>setBody(self,body2)));var bodyJsonUnsafe=dual(2,(self,body)=>setBody(self,jsonUnsafe(body)));var schemaBodyJson=(schema2,options2)=>{const encode2=jsonSchema(schema2,options2);return dual(2,(self,body)=>map7(encode2(body),(body2)=>setBody(self,body2)))};var bodyUrlParams=dual(2,(self,input)=>setBody(self,urlParams(fromInput3(input))));var bodyFormData=dual(2,(self,body)=>setBody(self,formData(body)));var bodyFormDataRecord=dual(2,(self,entries3)=>setBody(self,formDataRecord(entries3)));var bodyStream=dual((args2)=>isHttpClientRequest(args2[0]),(self,body,options2)=>setBody(self,stream2(body,options2?.contentType,options2?.contentLength)));var bodyFile=dual((args2)=>isHttpClientRequest(args2[0]),(self,path4,options2)=>map7(file4(path4,options2),(body)=>setBody(self,body)));function toUrl(self){const r=make41(self.url,self.urlParams,getOrUndefined(self.hash));if(isSuccess2(r)){return some2(r.success)}return none2()}var fromWeb=(request3)=>{const method=request3.method.toUpperCase();return modify3(empty13,{method,url:new URL(request3.url),headers:request3.headers,body:fromWebBody(request3,method)})};var fromWebBody=(request3,method)=>{if(!hasBody(method)||request3.body===null){return empty12}return raw(request3.body,{contentType:request3.headers.get("content-type")??undefined,contentLength:parseContentLength(request3.headers.get("content-length"))})};var parseContentLength=(contentLength)=>{if(contentLength===null){return}const parsed=Number.parseInt(contentLength,10);return Number.isNaN(parsed)?undefined:parsed};var toWebResult=(self,options2)=>{const url2=make41(self.url,self.urlParams,getOrUndefined(self.hash));if(isFailure2(url2)){return fail2(url2.failure)}const requestInit={method:self.method,headers:self.headers};if(options2?.signal){requestInit.signal=options2.signal}if(hasBody(self.method)){switch(self.body._tag){case"Empty":{break}case"Raw":{requestInit.body=self.body.body;if(isReadableStream(self.body.body)){requestInit.duplex="half"}break}case"Uint8Array":{requestInit.body=self.body.body;break}case"FormData":{requestInit.body=self.body.formData;break}case"Stream":{requestInit.body=toReadableStreamWith(self.body.stream,options2?.context??empty());requestInit.duplex="half";break}}}return try_({try:()=>new Request(url2.success,requestInit),catch:(cause)=>new UrlError({cause})})};var isReadableStream=(u)=>typeof ReadableStream!=="undefined"&&u instanceof ReadableStream;var toWeb=(self,options2)=>contextWith2((context4)=>fromResult2(toWebResult(self,{context:context4,signal:options2?.signal})));var TypeId51="~effect/http/HttpIncomingMessage";var inspect=(self,that)=>{const contentType=self.headers["content-type"]??"";let body;if(contentType.includes("application/json")){try{body=runSync2(self.json)}catch(_){}}else if(contentType.includes("text/")||contentType.includes("urlencoded")){try{body=runSync2(self.text)}catch(_){}}const obj={...that,headers:redact(self.headers),remoteAddress:self.remoteAddress};if(body!==undefined){obj.body=body}return obj};var TypeId52="~effect/http/HttpClientResponse";var fromWeb2=(request3,source)=>new WebHttpClientResponse(request3,source);var matchStatus=dual(2,(self,cases)=>{const status=self.status;if(cases[status]){return cases[status](self)}else if(status>=200&&status<300&&cases["2xx"]){return cases["2xx"](self)}else if(status>=300&&status<400&&cases["3xx"]){return cases["3xx"](self)}else if(status>=400&&status<500&&cases["4xx"]){return cases["4xx"](self)}else if(status>=500&&status<600&&cases["5xx"]){return cases["5xx"](self)}return cases.orElse(self)});var filterStatus=dual(2,(self,f)=>suspend2(()=>f(self.status)?succeed6(self):fail6(new HttpClientError({reason:new StatusCodeError({response:self,request:self.request,description:"invalid status code"})}))));var filterStatusOk=(self)=>self.status>=200&&self.status<300?succeed6(self):fail6(new HttpClientError({reason:new StatusCodeError({response:self,request:self.request,description:"non 2xx status code"})}));class WebHttpClientResponse extends Class2{[TypeId51];[TypeId52];request;source;constructor(request3,source){super();this.request=request3;this.source=source;this[TypeId51]=TypeId51;this[TypeId52]=TypeId52}toJSON(){return inspect(this,{_id:"HttpClientResponse",request:this.request.toJSON(),status:this.status})}get status(){return this.source.status}get headers(){return fromInput2(this.source.headers)}cachedCookies;get cookies(){if(this.cachedCookies){return this.cachedCookies}return this.cachedCookies=fromSetCookie(this.source.headers.getSetCookie())}get remoteAddress(){return none2()}get stream(){return this.source.body?fromReadableStream({evaluate:()=>this.source.body,onError:(cause)=>new HttpClientError({reason:new DecodeError({request:this.request,response:this,cause})})}):fail9(new HttpClientError({reason:new EmptyBodyError({request:this.request,response:this,description:"can not create stream from empty body"})}))}get json(){return flatMap4(this.text,(text3)=>try_3({try:()=>text3===""?null:JSON.parse(text3),catch:(cause)=>new HttpClientError({reason:new DecodeError({request:this.request,response:this,cause})})}))}textBody;get text(){if(this.textBody){return this.textBody}this.textBody=tryPromise2({try:()=>this.source.text(),catch:(cause)=>new HttpClientError({reason:new DecodeError({request:this.request,response:this,cause})})}).pipe(cached2,runSync2);this.arrayBufferBody=map7(this.textBody,(_)=>new TextEncoder().encode(_).buffer);return this.textBody}get urlParamsBody(){return flatMap4(this.text,(_)=>try_3({try:()=>fromInput3(new URLSearchParams(_)),catch:(cause)=>new HttpClientError({reason:new DecodeError({request:this.request,response:this,cause})})}))}formDataBody;get formData(){return this.formDataBody??=tryPromise2({try:()=>this.source.formData(),catch:(cause)=>new HttpClientError({reason:new DecodeError({request:this.request,response:this,cause})})}).pipe(cached2,runSync2)}arrayBufferBody;get arrayBuffer(){if(this.arrayBufferBody){return this.arrayBufferBody}this.arrayBufferBody=tryPromise2({try:()=>this.source.arrayBuffer(),catch:(cause)=>new HttpClientError({reason:new DecodeError({request:this.request,response:this,cause})})}).pipe(cached2,runSync2);this.textBody=map7(this.arrayBufferBody,(_)=>new TextDecoder().decode(_));return this.arrayBufferBody}pipe(){return pipeArguments(this,arguments)}}var toHeaders=(span)=>fromRecordUnsafe({b3:`${span.traceId}-${span.spanId}-${span.sampled?"1":"0"}${match(span.parent,{onNone:()=>"",onSome:(parent)=>`-${parent.spanId}`})}`,traceparent:`00-${span.traceId}-${span.spanId}-${span.sampled?"01":"00"}`});var TypeId53="~effect/http/HttpClient";var isHttpClient=(u)=>hasProperty(u,TypeId53);var HttpClient=Service("effect/HttpClient");var accessor=(method)=>(...args2)=>flatMap4(HttpClient,(client)=>client[method](...args2));var execute=accessor("execute");var get8=accessor("get");var head2=accessor("head");var post2=accessor("post");var patch2=accessor("patch");var put2=accessor("put");var del2=accessor("del");var options2=accessor("options");var transform5=dual(2,(self,f)=>makeWith2(flatMap4((request3)=>f(self.postprocess(succeed6(request3)),request3)),self.preprocess));var transformResponse=dual(2,(self,f)=>makeWith2((request3)=>f(self.postprocess(request3)),self.preprocess));var catch_4=dual(2,(self,f)=>transformResponse(self,catch_2(f)));var catchTag3=dual(3,(self,tag4,f)=>transformResponse(self,(effect2)=>catchTag2(effect2,tag4,f)));var catchTags3=dual(2,(self,cases)=>transformResponse(self,catchTags2(cases)));var filterOrElse3=dual(3,(self,f,orElse6)=>transformResponse(self,filterOrElse2(f,orElse6)));var filterOrFail3=dual(3,(self,f,orFailWith)=>transformResponse(self,filterOrFail2(f,orFailWith)));var filterStatus2=dual(2,(self,f)=>transformResponse(self,flatMap4(filterStatus(f))));var filterStatusOk2=transformResponse(flatMap4(filterStatusOk));var makeWith2=(postprocess,preprocess)=>{const self=Object.create(Proto16);self.preprocess=preprocess;self.postprocess=postprocess;self.execute=function(request3){return postprocess(preprocess(request3))};return self};var Proto16={[TypeId53]:TypeId53,pipe(){return pipeArguments(this,arguments)},...BaseProto,toJSON(){return{_id:"effect/HttpClient"}},...Object.fromEntries(allShort.map(([fullMethod,method])=>[method,function(url2,options3){return this.execute(make42(fullMethod)(url2,options3))}]))};var make43=(f)=>makeWith2((effect2)=>flatMap4(effect2,(request3)=>withFiber2((fiber3)=>{const scopedController=scopedRequests.get(request3);const controller=scopedController??new AbortController;const urlResult=make41(request3.url,request3.urlParams,getOrUndefined(request3.hash));if(isFailure2(urlResult)){return fail6(new HttpClientError({reason:new InvalidUrlError({request:request3,cause:urlResult.failure})}))}const url2=urlResult.success;const tracerDisabled=fiber3.getRef(DisablePropagation)||fiber3.getRef(TracerDisabledWhen)(request3);if(tracerDisabled){const effect3=f(request3,url2,controller.signal,fiber3);if(scopedController)return effect3;return uninterruptibleMask2((restore)=>matchCauseEffect2(restore(effect3),{onSuccess(response){responseRegistry.register(response,controller);return succeed6(new InterruptibleResponse(response,controller))},onFailure(cause){if(hasInterrupts2(cause)){controller.abort()}return failCause3(cause)}}))}return useSpan2(fiber3.getRef(SpanNameGenerator)(request3),{kind:"client"},(span)=>{span.attribute("http.request.method",request3.method);span.attribute("server.address",url2.origin);if(url2.port!==""){span.attribute("server.port",+url2.port)}span.attribute("url.full",url2.toString());span.attribute("url.path",url2.pathname);span.attribute("url.scheme",url2.protocol.slice(0,-1));const query=url2.search.slice(1);if(query!==""){span.attribute("url.query",query)}const redactedHeaderNames=fiber3.getRef(CurrentRedactedNames);const redactedHeaders=redact4(request3.headers,redactedHeaderNames);for(const name in redactedHeaders){span.attribute(`http.request.header.${name}`,String(redactedHeaders[name]))}request3=fiber3.getRef(TracerPropagationEnabled)?setHeaders(request3,toHeaders(span)):request3;return uninterruptibleMask2((restore)=>restore(f(request3,url2,controller.signal,fiber3)).pipe(withParentSpan2(span,{captureStackTrace:false}),matchCauseEffect2({onSuccess:(response)=>{span.attribute("http.response.status_code",response.status);const redactedHeaders2=redact4(response.headers,redactedHeaderNames);for(const name in redactedHeaders2){span.attribute(`http.response.header.${name}`,String(redactedHeaders2[name]))}if(scopedController)return succeed6(response);responseRegistry.register(response,controller);return succeed6(new InterruptibleResponse(response,controller))},onFailure(cause){if(!scopedController&&hasInterrupts2(cause)){controller.abort()}return failCause3(cause)}})))})})),succeed6);var mapRequest=dual(2,(self,f)=>makeWith2(self.postprocess,(request3)=>map7(self.preprocess(request3),f)));var mapRequestEffect=dual(2,(self,f)=>makeWith2(self.postprocess,(request3)=>flatMap4(self.preprocess(request3),f)));var mapRequestInput=dual(2,(self,f)=>makeWith2(self.postprocess,(request3)=>self.preprocess(f(request3))));var mapRequestInputEffect=dual(2,(self,f)=>makeWith2(self.postprocess,(request3)=>flatMap4(f(request3),self.preprocess)));var retry4=dual(2,(self,policy)=>transformResponse(self,retry2(policy)));var retryTransient=dual(2,(self,options3)=>{const isOnlySchedule=isSchedule(options3);const retryOn=isOnlySchedule?"errors-and-responses":options3.retryOn??"errors-and-responses";const schedule3=isOnlySchedule?options3:options3.schedule;const passthroughSchedule=schedule3&&passthrough(schedule3);const times=isOnlySchedule?undefined:options3.times;return transformResponse(self,flow(retryOn==="errors-only"?identity:repeat2({schedule:passthroughSchedule,times,while:isTransientResponse}),retryOn==="response-only"?identity:retry2({while:isOnlySchedule||options3.while===undefined?isTransientError:or(isTransientError,options3.while),schedule:schedule3,times})))});var withRateLimiter=dual(2,(self,options3)=>{const initialState={initial:true,limit:options3.limit,window:max2(fromInputUnsafe(options3.window),millis(1))};const states=new Map;const keyOption=options3.key;const resolveKey=typeof keyOption==="function"?keyOption:constant(keyOption);const tokensOption=options3.tokens;const resolveTokens=typeof tokensOption==="function"?tokensOption:constant(tokensOption??1);const adaptiveLearningEnabled=!options3.disableAdaptiveLearning;const getState2=(key)=>{const current=states.get(key);if(current!==undefined){return current}states.set(key,initialState);return initialState};const onResponse=options3.disableResponseInspection?undefined:(clock,key,headers,tokens)=>{const current=getState2(key);const next=parseRateLimiterState(current,clock,headers,tokens);if(next.limit!==current.limit||!equals2(next.window,current.window)){states.set(key,next)}};return transform5(self,function loop(effect2,request3){const fiber3=getCurrent();const clock=fiber3.getRef(Clock);const key=resolveKey(request3);const tokens=Math.max(resolveTokens(request3),1);const current=getState2(key);function retry5(retryAfter){if(options3.disableResponseInspection)return loop(effect2,request3);return retryAfter?flatMap4(sleep2(retryAfter),()=>loop(effect2,request3)):loop(effect2,request3)}const inspectResponse=(response,adaptive)=>{onResponse?.(clock,key,response.headers,tokens);if(options3.disableResponseInspection||response.status!==429){return succeed6(undefined)}const retryAfter=parseRetryAfter(clock,getHeader(response.headers,"retry-after"));if(retryAfter===undefined){return succeed6(undefined)}const delay3=parseRateLimitWindow(clock,response.headers)??retryAfter;if(adaptive===undefined){return succeed6(delay3)}return as2(options3.limiter.adaptiveFeedback({key,epoch:adaptive.epoch,tokens,status:response.status,retryAfter:delay3}),delay3)};return flatMap4(options3.limiter.consume({algorithm:options3.algorithm,onExceeded:"delay",key,limit:current.limit,window:current.window,tokens}),({delay:delay3})=>{const runAdaptive=()=>{const runRequest=(adaptive)=>{const request4=matchEffect3(effect2,{onSuccess(response){return flatMap4(inspectResponse(response,adaptive),(retryAfter)=>{if(response.status!==429)return succeed6(response);return retry5(retryAfter)})},onFailure(error2){if(isTooManyRequestsHttpClientError(error2)){return flatMap4(inspectResponse(error2.reason.response,adaptive),(retryAfter)=>retry5(retryAfter))}return fail6(error2)}});return adaptive===undefined||isZero(adaptive.delay)?request4:delay2(request4,adaptive.delay)};if(!adaptiveLearningEnabled){return runRequest(undefined)}return flatMap4(options3.limiter.adaptiveConsume({key,tokens,fallbackLimit:current.limit,fallbackWindow:current.window}),(adaptive)=>{if(!isZero(adaptive.delay)&&adaptive.phase==="cooldown"){return flatMap4(sleep2(adaptive.delay),runAdaptive)}return runRequest(adaptive)})};return isZero(delay3)?runAdaptive():flatMap4(sleep2(delay3),runAdaptive)})})});var parseRateLimiterState=(state,clock,headers,tokens)=>{const limit=parseRateLimitLimit(state,headers,tokens)??state.limit;const window=parseRateLimitWindow(clock,headers)??state.window;if(limit===state.limit&&equals2(window,state.window)){return state}return{limit,window,initial:false}};var parseRateLimitLimit=(state,headers,tokens)=>{const raw2=getHeader(headers,"ratelimit-limit","x-ratelimit-limit");const value5=parseNumberHeader(raw2);if(value5!==undefined&&value5>0){return value5}const remaining=parseRateLimitRemaining(headers);if(remaining===undefined){return}return state.initial?remaining+tokens:Math.max(remaining+tokens,state.limit)};var parseRateLimitRemaining=(headers)=>{const raw2=getHeader(headers,"ratelimit-remaining","x-ratelimit-remaining");const value5=parseNumberHeader(raw2);return value5!==undefined&&value5>=0?value5:undefined};var parseRateLimitWindow=(clock,headers)=>{const resetAfter=parseResetAfter(getHeader(headers,"ratelimit-reset-after","x-ratelimit-reset-after"));if(resetAfter!==undefined){return resetAfter}return parseResetHeader(clock,getHeader(headers,"ratelimit-reset","x-ratelimit-reset"))};var parseRetryAfter=(clock,value5)=>{if(value5===undefined){return}const numeric=parseNumberHeader(value5);if(numeric!==undefined){return max2(seconds(numeric),millis(1))}const parsedDate=Date.parse(value5);if(Number.isNaN(parsedDate)){return}const millis2=parsedDate-clock.currentTimeMillisUnsafe();if(millis2<=0){return millis(1)}return millis(millis2)};var parseResetAfter=(value5)=>{const numeric=parseNumberHeader(value5);if(numeric===undefined||numeric<=0){return}return max2(seconds(numeric),millis(1))};var parseResetHeader=(clock,value5)=>{const numeric=parseNumberHeader(value5);if(numeric===undefined||numeric<=0){return}const nowMillis=clock.currentTimeMillisUnsafe();if(numeric>1000000000000){return millis(Math.max(numeric-nowMillis,1))}if(numeric>1e9){return millis(Math.max(numeric*1000-nowMillis,1))}return max2(seconds(numeric),millis(1))};var parseNumberHeader=(value5)=>{if(value5===undefined){return}const match8=/-?\d+(?:\.\d+)?/.exec(value5);if(match8===null){return}const parsed=Number(match8[0]);return Number.isFinite(parsed)?parsed:undefined};var getHeader=(headers,...keys3)=>{for(let i=0;i<keys3.length;i++){const value5=headers[keys3[i]];if(value5!==undefined){return value5}}return};var tap3=dual(2,(self,f)=>transformResponse(self,tap2(f)));var tapError4=dual(2,(self,f)=>transformResponse(self,tapError2(f)));var tapRequest=dual(2,(self,f)=>makeWith2(self.postprocess,(request3)=>tap2(self.preprocess(request3),f)));var withCookiesRef=dual(2,(self,ref)=>makeWith2((request3)=>tap2(self.postprocess(request3),(response)=>update2(ref,(cookies)=>merge5(cookies,response.cookies))),(request3)=>flatMap4(self.preprocess(request3),(request4)=>map7(get6(ref),(cookies)=>isEmpty3(cookies)?request4:setHeader(request4,"cookie",toCookieHeader(cookies))))));var withScope=(self)=>transform5(self,(effect2,request3)=>{const controller=new AbortController;scopedRequests.set(request3,controller);return andThen2(addFinalizer3(()=>sync2(()=>controller.abort())),effect2)});var followRedirects=dual((args2)=>isHttpClient(args2[0]),(self,maxRedirects)=>makeWith2((request3)=>{const loop=(request4,redirects)=>flatMap4(self.postprocess(succeed6(request4)),(response)=>response.status>=300&&response.status<400&&response.headers.location&&redirects<(maxRedirects??10)?loop(setUrl(request4,new URL(response.headers.location,response.request.url)),redirects+1):succeed6(response));return flatMap4(request3,(request4)=>loop(request4,0))},self.preprocess));var TracerDisabledWhen=Reference("effect/http/HttpClient/TracerDisabledWhen",{defaultValue:()=>constFalse});var TracerPropagationEnabled=Reference("effect/HttpClient/TracerPropagationEnabled",{defaultValue:constTrue});var SpanNameGenerator=Reference("effect/http/HttpClient/SpanNameGenerator",{defaultValue:()=>(request3)=>`http.client ${request3.method}`});var layerMergedContext=(effect2)=>effect(HttpClient)(contextWith2((context4)=>map7(effect2,(client)=>transformResponse(client,updateContext2((input)=>merge(context4,input))))));var responseRegistry=(()=>{if("FinalizationRegistry"in globalThis&&globalThis.FinalizationRegistry){const registry=new FinalizationRegistry((controller)=>{controller.abort()});return{register(response,controller){registry.register(response,controller,response)},unregister(response){registry.unregister(response)}}}const timers=new Map;return{register(response,controller){timers.set(response,setTimeout(()=>controller.abort(),5000))},unregister(response){const timer=timers.get(response);if(timer===undefined)return;clearTimeout(timer);timers.delete(response)}}})();var scopedRequests=new WeakMap;class InterruptibleResponse{original;controller;constructor(original,controller){this.original=original;this.controller=controller}[TypeId52]=TypeId52;[TypeId51]=TypeId51;applyInterrupt(effect2){return suspend2(()=>{responseRegistry.unregister(this.original);return onInterrupt2(effect2,()=>sync2(()=>{this.controller.abort()}))})}get request(){return this.original.request}get status(){return this.original.status}get headers(){return this.original.headers}get cookies(){return this.original.cookies}get remoteAddress(){return this.original.remoteAddress}get formData(){return this.applyInterrupt(this.original.formData)}get text(){return this.applyInterrupt(this.original.text)}get json(){return this.applyInterrupt(this.original.json)}get urlParamsBody(){return this.applyInterrupt(this.original.urlParamsBody)}get arrayBuffer(){return this.applyInterrupt(this.original.arrayBuffer)}get stream(){return suspend4(()=>{responseRegistry.unregister(this.original);return ensuring4(this.original.stream,sync2(()=>{this.controller.abort()}))})}toJSON(){return this.original.toJSON()}[NodeInspectSymbol](){return this.original[NodeInspectSymbol]()}pipe(){return pipeArguments(this,arguments)}}var isTransientError=(error2)=>isTimeoutError2(error2)||isTransientHttpError(error2);var isTransientHttpError=(error2)=>isHttpClientError(error2)&&(error2.reason._tag==="TransportError"||error2.reason._tag==="StatusCodeError"&&isTransientResponse(error2.reason.response));var isTooManyRequestsHttpClientError=(error2)=>isHttpClientError(error2)&&error2.reason._tag==="StatusCodeError"&&error2.reason.response.status===429;var isTransientResponse=(response)=>response.status===408||response.status===429||response.status===500||response.status===502||response.status===503||response.status===504;var Fetch=Reference("effect/http/FetchHttpClient/Fetch",{defaultValue:()=>globalThis.fetch});class RequestInit extends Service()("effect/http/FetchHttpClient/RequestInit"){}var fetch2=make43((request3,url2,signal,fiber3)=>{const fetch3=fiber3.getRef(Fetch);const options3=fiber3.context.mapUnsafe.get(RequestInit.key)??{};let headers=options3.headers?merge6(fromInput2(options3.headers),request3.headers):request3.headers;if(headers["content-length"]){headers=remove6(headers,"content-length")}const send=(body)=>map7(tryPromise2({try:()=>fetch3(url2,{...options3,method:request3.method,headers,body,duplex:request3.body._tag==="Stream"?"half":undefined,signal}),catch:(cause)=>new HttpClientError({reason:new TransportError({request:request3,cause})})}),(response)=>fromWeb2(request3,response));switch(request3.body._tag){case"Raw":case"Uint8Array":return send(request3.body.body);case"FormData":return send(request3.body.formData);case"Stream":return flatMap4(toReadableStreamEffect(request3.body.stream),send)}return send(undefined)});var layer16=layerMergedContext(succeed6(fetch2));var HttpServerRequest=Service("effect/http/HttpServerRequest");var loggerDisabledRequests=new WeakSet;var withLoggerDisabled=(self)=>withFiber2((fiber3)=>{const request3=getUnsafe(fiber3.context,HttpServerRequest);loggerDisabledRequests.add(request3.source);return self});var HttpRouter=Service("effect/http/HttpRouter");var removeTrailingSlash=(path4)=>path4.endsWith("/")?path4.slice(0,-1):path4;var prefixPath=dual(2,(self,prefix)=>{prefix=removeTrailingSlash(prefix);if(self==="*")return`${prefix}/*`;else if(self==="/")return prefix;return prefix+self});var MiddlewareTypeId="~effect/http/HttpRouter/Middleware";var middleware=function(){if(arguments.length===0){return makeMiddleware}return makeMiddleware(arguments[0],arguments[1])};var makeMiddleware=(middleware2,options3)=>options3?.global?effectDiscard(gen2(function*(){const router=yield*HttpRouter;const fn3=isEffect2(middleware2)?yield*middleware2:middleware2;yield*router.addGlobalMiddleware(fn3)})):new MiddlewareImpl(isEffect2(middleware2)?effectContext(map7(middleware2,(fn3)=>makeUnsafe(new Map([[fnContextKey,fn3]])))):succeedContext(makeUnsafe(new Map([[fnContextKey,middleware2]]))));var middlewareId=0;var fnContextKey="effect/http/HttpRouter/MiddlewareFn";class MiddlewareImpl{[MiddlewareTypeId]={};layerFn;dependencies;constructor(layerFn,dependencies){this.layerFn=layerFn;this.dependencies=dependencies;const contextKey=`effect/http/HttpRouter/Middleware-${++middlewareId}`;this.layer=effectContext(gen2({self:this},function*(){const context4=yield*context2();const stack=[context4.mapUnsafe.get(fnContextKey)];if(this.dependencies){const memoMap=yield*CurrentMemoMap;const scope3=get(context4,Scope);const depsContext=yield*buildWithMemoMap(this.dependencies,memoMap,scope3);stack.push(...getMiddleware(depsContext))}return makeUnsafe(new Map([[contextKey,stack]]))})).pipe(provide2(this.layerFn))}layer;combine(other){return new MiddlewareImpl(this.layerFn,this.dependencies?provideMerge(this.dependencies,other.layer):other.layer)}}var middlewareCache=new WeakMap;var getMiddleware=(context4)=>{let arr=middlewareCache.get(context4);if(arr)return arr;const topLevel=empty3();let maxLength=0;for(const[key,value5]of context4.mapUnsafe){if(key.startsWith("effect/http/HttpRouter/Middleware-")){topLevel.push(value5);if(value5.length>maxLength){maxLength=value5.length}}}if(topLevel.length===0){arr=[]}else{const middleware2=new Set;for(let i=maxLength-1;i>=0;i--){for(const arr2 of topLevel){if(i<arr2.length){middleware2.add(arr2[i])}}}arr=fromIterable(middleware2).reverse()}middlewareCache.set(context4,arr);return arr};var disableLogger=middleware(withLoggerDisabled).layer;import path8 from"node:path";var RepositoryCheckCapabilities=Service("@punks/cli/features/repository-check/RepositoryCheckCapabilities");class RepositoryCheckOperationFailure extends TaggedErrorClass()("@punks/cli/repository-check/RepositoryCheckOperationFailure",{cause:Defect(),message:String5,operation:Literals(["assess-project-settings","check-repository-update","read-changelog"])}){}var RepositoryCheckOperations=Service("@punks/cli/features/repository-check/RepositoryCheckOperations");var isRecord=(value5)=>typeof value5==="object"&&value5!==null;var isReadOnlyAuthorityFailure=(input,failure)=>{if(input.baseline==="bundled"||!isRecord(failure.cause)){return false}const{cause:resolutionFailure}=failure;if(resolutionFailure._tag!=="@punks/cli/baseline-resolution/BaselineResolutionFailure"){return false}const{cause}=resolutionFailure;if(isRecord(cause)&&cause._tag==="@punks/contract/errors/BaselineAuthorityFailure"){return false}if(resolutionFailure.reason==="remote-access"){return true}return isRecord(cause)&&cause._tag==="@punks/contract/errors/BaselineIntegrityFailure"&&cause.message==="Published baseline inventory returned 404."};var unavailableCheckResult=({code,detail,rootDirectory,source})=>({availability:{detail,source,status:"unavailable"},cli:{command:null,currentVersion:null,failed:false,latestVersion:null,packageName:null,status:"unavailable",tag:null},failed:true,operation:{changes:[],degradations:[{code,subject:source}],issues:[],nextActions:[{kind:"none"}],status:"degraded",warnings:[]},releaseSummary:[],settings:{baselineVersion:null,baselineVersionDrift:false,cliVersion:null,cliVersionDrift:false,upgrade:null},update:{applied:false,baselineDrift:false,changedFiles:[],checkFailed:false,driftPrompt:null,failed:false,finalPacks:[],packDrift:false,repoShapeMode:"auto",resolvedPacks:[],rootDirectory,scaffoldManifestFile:".devpunks/scaffold-manifest.json",staleFiles:[],toolBootstrapStatuses:[]}});var normalizeCliResult=(result4)=>{const{check:check3}=result4;return{failed:result4.status!=="current"&&result4.status!=="unavailable",status:result4.status,currentVersion:check3?.currentVersion??null,latestVersion:check3?.latestVersion??null,packageName:check3?.packageName??null,tag:check3?.tag??null,command:"command"in result4?result4.command:null}};var checkSettingsPins=fn2("RepositoryCheck.checkSettingsPins")(function*checkSettingsPins2({rootDirectory,cli,baselineVersion,capabilities,currentCliVersion}){const assessment=yield*capabilities.assessSettings(rootDirectory);const settings=assessment?.settings??null;const acceptedCliVersion=settings?.cliVersion??null;const acceptedBaselineVersion=settings?.baselineVersion??null;const expectedCliVersion=cli.status==="current"&&cli.currentVersion!==null?cli.currentVersion:cli.latestVersion??cli.currentVersion??currentCliVersion;return{baselineVersion:acceptedBaselineVersion,baselineVersionDrift:acceptedBaselineVersion!==null&&baselineVersion!==null&&acceptedBaselineVersion!==baselineVersion,cliVersion:acceptedCliVersion,cliVersionDrift:acceptedCliVersion!==null&&acceptedCliVersion!==expectedCliVersion,upgrade:assessment?.upgrade??null}});var extractChangelogEntry=(changelog,heading)=>{const escapedHeading=heading.replaceAll(/[.*+?^${}()|[\]\\]/gu,"\\$&");const match8=new RegExp(`^## \\[?${escapedHeading}\\]?[^\\n]*\\n`,"mu").exec(changelog);if(match8===null){return null}const rest=changelog.slice(match8.index+match8[0].length);const nextHeading=rest.search(/^## /mu);const body=(nextHeading===-1?rest:rest.slice(0,nextHeading)).trim();return body.length>0?body:null};var findChangelogEntry=fn2("RepositoryCheck.findChangelogEntry")(function*findChangelogEntry2({rootDirectory,fileName,heading,roots,capabilities}){for(const candidateRoot of[rootDirectory,...roots]){const candidatePath=`${candidateRoot.replace(/\/$/u,"")}/${fileName}`;const changelog=yield*capabilities.readTextFile(candidatePath);if(changelog===null){continue}const entry=extractChangelogEntry(changelog,heading);if(entry!==null){return entry}}return null});var summarizeChangelogEntry=(entry)=>entry.split(`
|
|
291
291
|
`).map((line)=>line.trim()).filter((line)=>line.startsWith("- ")).slice(0,3).map((line)=>line.slice(2)).join(" ");var changelogSummaryFor=fn2("RepositoryCheck.changelogSummaryFor")(function*changelogSummaryFor2({rootDirectory,fileName,heading,label,roots,capabilities}){const entry=yield*findChangelogEntry({capabilities,fileName,heading,rootDirectory,roots});const summary=entry===null?"":summarizeChangelogEntry(entry);return summary.length>0?`${label} ${heading}: ${summary}`:`${label} ${heading}: changelog entry not available locally; inspect ${fileName}.`});var releaseSummaryFor=fn2("RepositoryCheck.releaseSummaryFor")(function*releaseSummaryFor2({rootDirectory,cli,update:update3,baselineVersion,roots,capabilities}){const lines2=[];if(cli.failed&&cli.latestVersion!==null){lines2.push(yield*changelogSummaryFor({capabilities,fileName:"CHANGELOG.md",heading:cli.latestVersion,label:"CLI",rootDirectory,roots}))}if(update3.baselineDrift&&baselineVersion!==null){lines2.push(yield*changelogSummaryFor({capabilities,fileName:"BASELINE_CHANGELOG.md",heading:baselineVersion,label:"Baseline",rootDirectory,roots}))}return lines2});var toOperationResult=({failed,cli,releaseSummary,settings,update:update3})=>{const changes=[...update3.changedFiles.map((change)=>({action:change.status,state:"planned",subject:change.path})),...update3.staleFiles.map((subject)=>({action:"remove",state:"planned",subject}))];const warnings=[...cli.status==="unavailable"?[{code:"cli-metadata-unavailable",subject:"cli"}]:[],...settings.cliVersionDrift?[{code:"cli-version-drift",subject:settings.cliVersion??"unset"}]:[],...settings.baselineVersionDrift?[{code:"baseline-version-drift",subject:settings.baselineVersion??"unset"}]:[],...releaseSummary.map((subject)=>({code:"release-summary",subject}))];const issues=failed?[{action:"check",code:"drift-detected",kind:"handled-failure",subject:"repository"}]:[];const status=failed?"failed":"success";return{changes,degradations:[],facts:{cli:{command:cli.command,currentVersion:cli.currentVersion,latestVersion:cli.latestVersion,packageName:cli.packageName,status:cli.status},kind:"repository-check",releaseSummary,settings:{baselineVersion:settings.baselineVersion,baselineVersionDrift:settings.baselineVersionDrift,cliVersion:settings.cliVersion,cliVersionDrift:settings.cliVersionDrift},updateFailed:update3.failed},issues,nextActions:status==="success"?[{kind:"none"}]:[{kind:"review",subject:"repository"}],status,warnings}};var runCheck=({rootDirectory,changelogRoots=[],baselineVersion,update:update3,updateTag="latest",currentCliVersion="unknown"})=>gen2(function*checkRepository(){const capabilities=yield*RepositoryCheckCapabilities;const cliStatus=yield*capabilities.checkCli(updateTag);if(cliStatus.status==="unavailable"){return unavailableCheckResult({code:"cli-metadata-unavailable",detail:"CLI release metadata is unavailable.",rootDirectory,source:"npm-registry"})}const cli=normalizeCliResult(cliStatus);const updateResult={...update3,failed:update3.checkFailed};const settings=yield*checkSettingsPins({baselineVersion,capabilities,cli,currentCliVersion,rootDirectory});const releaseSummary=yield*releaseSummaryFor({baselineVersion,capabilities,cli,rootDirectory,roots:changelogRoots,update:updateResult});const resultWithoutOperation={failed:updateResult.failed||cli.failed||settings.cliVersionDrift||settings.baselineVersionDrift,cli,releaseSummary,settings,update:updateResult};return{...resultWithoutOperation,operation:toOperationResult(resultWithoutOperation)}});var runRepositoryCheckApplication=fn2("RepositoryCheck.run")(function*runRepositoryCheckApplication2(input){const operations=yield*RepositoryCheckOperations;const baseline=input.baseline??operations.configuredBaseline??"stable";const checkInput={...input,baseline,refreshBaseline:baseline==="bundled"?input.refreshBaseline:true};const resolution=yield*operations.checkUpdate(checkInput).pipe(map7((resolved2)=>({_tag:"Available",resolved:resolved2})),catchTag2("@punks/cli/repository-check/RepositoryCheckOperationFailure",(failure)=>isReadOnlyAuthorityFailure(checkInput,failure)?succeed6({_tag:"Unavailable",failure}):fail6(failure)));if(resolution._tag==="Unavailable"){return unavailableCheckResult({code:"baseline-authority-unavailable",detail:resolution.failure.message,rootDirectory:input.rootDirectory,source:"control-plane"})}const{resolved}=resolution;return yield*runCheck({baselineVersion:resolved.baselineVersion,changelogRoots:input.changelogRoots,currentCliVersion:operations.cliVersion,rootDirectory:input.rootDirectory,update:resolved.update,updateTag:operations.updateTag})});var SelectedOutputMode=Service("@punks/cli/presentation/SelectedOutputMode");var jsonOptionDescriptor={canonicalOption:"--json",takesValue:false};var jsonOptionEntry=["--json",jsonOptionDescriptor];var optionName=(argument)=>{const equalsIndex=argument.indexOf("=");return equalsIndex===-1?argument:argument.slice(0,equalsIndex)};var commandArgumentsFromRootOptions=(args2,rootOptions)=>{const commandArguments=[];const optionDescriptors=new Map([...rootOptions,jsonOptionEntry]);for(let index2=0;index2<args2.length;index2+=1){const argument=args2[index2];if(argument==="--"){break}if(!argument.startsWith("-")||argument==="-"){commandArguments.push(argument);continue}if(argument.startsWith("--")){const descriptor=optionDescriptors.get(optionName(argument));if(descriptor?.takesValue===true&&argument.includes("=")===false&&args2[index2+1]!==undefined&&args2[index2+1]!=="--"){index2+=1}continue}for(let aliasIndex=1;aliasIndex<argument.length;aliasIndex+=1){const descriptor=optionDescriptors.get(`-${argument[aliasIndex]}`);if(descriptor?.takesValue!==true){continue}if(aliasIndex+1===argument.length&&args2[index2+1]!==undefined&&args2[index2+1]!=="--"){index2+=1}break}}return commandArguments};var selectOutputMode=({jsonSelected,stdinIsTTY,stdoutIsTTY})=>{if(jsonSelected){return"json"}return stdinIsTTY&&stdoutIsTTY?"interactive":"plain"};var processLongArgument=(argument,index2,args2,optionDescriptors,state)=>{const option6=optionName(argument);const descriptor=optionDescriptors.get(option6);const equalsIndex=argument.indexOf("=");if(option6==="--json"){const value6=equalsIndex===-1?"true":argument.slice(equalsIndex+1);if(value6==="true"){state.jsonSelected=true;return index2}}if(descriptor?.nativeAction===true&&state.nativeAction===undefined){state.nativeAction=option6}if(descriptor?.takesValue!==true){state.normalizedArguments.push(argument);return index2}if(equalsIndex!==-1){if(argument.slice(equalsIndex+1).length===0&&state.missingOption===undefined){state.missingOption=option6}state.normalizedArguments.push(argument);return index2}const value5=args2[index2+1];if(value5===undefined||value5==="--"){state.missingOption??=option6;state.normalizedArguments.push(argument);return index2}state.normalizedArguments.push(`${descriptor.canonicalOption}=${value5}`);return index2+1};var processShortArgument=(argument,index2,args2,optionDescriptors,state)=>{for(let aliasIndex=1;aliasIndex<argument.length;aliasIndex+=1){const option6=`-${argument[aliasIndex]}`;const descriptor=optionDescriptors.get(option6);if(descriptor?.nativeAction===true&&state.nativeAction===undefined){state.nativeAction=option6}if(descriptor?.takesValue!==true){continue}if(aliasIndex+1<argument.length){state.normalizedArguments.push(`${descriptor.canonicalOption}=${argument.slice(aliasIndex+1)}`);return index2}const value5=args2[index2+1];if(value5===undefined||value5==="--"){state.missingOption??=option6;return index2}state.normalizedArguments.push(`${descriptor.canonicalOption}=${value5}`);return index2+1}state.normalizedArguments.push(argument);return index2};var analyzeCliArguments=({args:args2,commandOptionsForArguments,rootOptions,stdinIsTTY,stdoutIsTTY})=>{const commandArguments=commandArgumentsFromRootOptions(args2,rootOptions);const optionDescriptors=new Map([...rootOptions,...commandOptionsForArguments(commandArguments),jsonOptionEntry]);const state={jsonSelected:false,missingOption:undefined,nativeAction:undefined,normalizedArguments:[]};for(let index2=0;index2<args2.length;index2+=1){const argument=args2[index2];if(argument==="--"){state.normalizedArguments.push(...args2.slice(index2));break}if(!argument.startsWith("-")||argument==="-"){state.normalizedArguments.push(argument);continue}if(argument.startsWith("--")){index2=processLongArgument(argument,index2,args2,optionDescriptors,state);continue}index2=processShortArgument(argument,index2,args2,optionDescriptors,state)}return{arguments:state.normalizedArguments,commandArguments,...state.missingOption===undefined?{}:{missingOption:state.missingOption},mode:selectOutputMode({jsonSelected:state.jsonSelected,stdinIsTTY,stdoutIsTTY}),...state.nativeAction===undefined?{}:{nativeAction:state.nativeAction}}};class CliUpgradeFacts extends Class4("CliUpgradeFacts")({kind:Literal2("cli-upgrade"),command:NullOr(ArraySchema(String5)),currentVersion:String5,environment:Record(String5,String5),latestVersion:String5,packageManager:NullOr(Literals(["bun","pnpm","npm","yarn"])),packageName:String5,status:Literals(["current","upgraded"]),tag:String5}){}class NoNextAction extends Class4("NoNextAction")({kind:Literal2("none")}){}class OperationChange extends Class4("OperationChange")({action:String5,state:Literals(["planned","completed"]),subject:String5}){}class OperationConflict extends Class4("OperationConflict")({kind:Literal2("conflict"),action:String5,code:String5,subject:String5}){}class OperationHandledFailure extends Class4("OperationHandledFailure")({kind:Literal2("handled-failure"),action:String5,code:String5,errorMessage:optional(String5),subject:String5}){}class OperationNotice extends Class4("OperationNotice")({code:String5,subject:String5}){}class ReportSubmissionFacts extends Class4("ReportSubmissionFacts")({kind:Literal2("report-submission"),deduplicated:Boolean4,githubUrl:optionalKey2(String5),reportId:String5,status:String5,title:NullOr(String5)}){}var repositoryCheckCliFacts=Struct({command:NullOr(ArraySchema(String5)),currentVersion:NullOr(String5),latestVersion:NullOr(String5),packageName:NullOr(String5),status:Literals(["available","current","failed","manager-not-detected","unavailable"])});var repositoryCheckSettingsFacts=Struct({baselineVersion:NullOr(String5),baselineVersionDrift:Boolean4,cliVersion:NullOr(String5),cliVersionDrift:Boolean4});class RepositoryCheckFacts extends Class4("RepositoryCheckFacts")({kind:Literal2("repository-check"),cli:repositoryCheckCliFacts,releaseSummary:ArraySchema(String5),settings:repositoryCheckSettingsFacts,updateFailed:Boolean4}){}class SubjectNextAction extends Class4("SubjectNextAction")({kind:Literals(["run","review","retry","resolve"]),subject:String5}){}var OperationIssue=Union2([OperationConflict,OperationHandledFailure]);var OperationNextAction=Union2([NoNextAction,SubjectNextAction]);var OperationFacts=Union2([ReportSubmissionFacts,CliUpgradeFacts,RepositoryCheckFacts]);var operationFields={changes:ArraySchema(OperationChange),warnings:ArraySchema(OperationNotice),degradations:ArraySchema(OperationNotice),issues:ArraySchema(OperationIssue),nextActions:ArraySchema(OperationNextAction),facts:optional(OperationFacts)};class ConflictOperationResult extends Class4("ConflictOperationResult")({status:Literal2("conflict"),...operationFields}){}class DegradedOperationResult extends Class4("DegradedOperationResult")({status:Literal2("degraded"),...operationFields}){}class FailedOperationResult extends Class4("FailedOperationResult")({status:Literal2("failed"),...operationFields}){}class NoOpOperationResult extends Class4("NoOpOperationResult")({status:Literal2("no-op"),...operationFields}){}class PartialOperationResult extends Class4("PartialOperationResult")({status:Literal2("partial"),...operationFields}){}class PlannedOperationResult extends Class4("PlannedOperationResult")({status:Literal2("planned"),...operationFields}){}class SuccessOperationResult extends Class4("SuccessOperationResult")({status:Literal2("success"),...operationFields}){}var validSuccess=SuccessOperationResult.pipe(check2(makeFilter2((result4)=>result4.issues.length===0&&result4.degradations.length===0,{message:"success results cannot contain issues or degradations"})));var validNoOp=NoOpOperationResult.pipe(check2(makeFilter2((result4)=>result4.changes.length===0&&result4.degradations.length===0&&result4.issues.length===0,{message:"no-op results cannot contain changes, degradations, or issues"})));var validPlanned=PlannedOperationResult.pipe(check2(makeFilter2((result4)=>result4.changes.length>0,{message:"planned results must describe at least one change"})));var validPartial=PartialOperationResult.pipe(check2(makeFilter2((result4)=>result4.changes.length>0,{message:"partial results must describe at least one change"})));var validDegraded=DegradedOperationResult.pipe(check2(makeFilter2((result4)=>result4.degradations.length>0,{message:"degraded results must describe at least one degradation"})));var validConflict=ConflictOperationResult.pipe(check2(makeFilter2((result4)=>result4.issues.some((issue)=>issue.kind==="conflict"),{message:"conflict results must describe a conflict"})));var validFailed=FailedOperationResult.pipe(check2(makeFilter2((result4)=>result4.issues.some((issue)=>issue.kind==="handled-failure"),{message:"failed results must describe a handled failure"})));var OperationResult=Union2([validSuccess,validNoOp,validPlanned,validPartial,validDegraded,validConflict,validFailed]).annotate({parseOptions:{onExcessProperty:"error"}});class CommandExpectedFailureSchema extends Class4("CommandExpectedFailureSchema")({code:String5,subject:String5,detail:String5,recoverable:Boolean4,recoveryCommand:optional(String5)}){}var CommandExpectedFailure=CommandExpectedFailureSchema.annotate({identifier:"CommandExpectedFailure",parseOptions:{onExcessProperty:"error"}});var decodeOperationResult=decodeUnknownSync2(OperationResult);var decodeCommandExpectedFailure=decodeUnknownSync2(CommandExpectedFailure);var renderJsonResult=(result4)=>`${JSON.stringify(result4,null,2)}
|
|
292
292
|
`;var renderJsonFailure=(failure)=>`${JSON.stringify({error:failure},null,2)}
|
|
293
293
|
`;var minimumWidth=32;var terminalWidth=(width)=>Math.max(minimumWidth,Math.floor(width));var wrapLine=(line,width)=>{if(line.length<=width){return[line]}const leading=line.match(/^\s*/u)?.[0]??"";const continuation=`${leading} `;const wrapped=[];let current=leading;for(const word of line.trimStart().split(/\s+/u)){const candidate=current.trim().length===0?`${current}${word}`:`${current} ${word}`;if(candidate.length<=width){current=candidate;continue}if(current.trim().length>0){wrapped.push(current)}let prefix=current.trim().length>0?continuation:current;let remainder2=word;while(prefix.length+remainder2.length>width){const chunkWidth=Math.max(1,width-prefix.length);wrapped.push(`${prefix}${remainder2.slice(0,chunkWidth)}`);remainder2=remainder2.slice(chunkWidth);prefix=continuation}current=`${prefix}${remainder2}`}if(current.trim().length>0){wrapped.push(current)}return wrapped};var renderRail=({rows,title,width})=>{const contentWidth=terminalWidth(width)-3;const fragments=rows.flatMap((row,rowIndex)=>wrapLine(row,contentWidth).map((text3,fragmentIndex,wrapped)=>({final:rowIndex===rows.length-1&&fragmentIndex===wrapped.length-1,text:text3})));return[`◇ ${title}`,...fragments.length===0?["└"]:fragments.map(({final,text:text3})=>`${final?"└":"│"} ${text3}`)].join(`
|
|
@@ -322,7 +322,7 @@ ${colorRail2({environment,headingTone:"accent",rail:reflowRail(guide,environment
|
|
|
322
322
|
`){++position}discardTrailingNewline=false}let lineLength=-1;let fieldLength=startingFieldLength;let character;for(let index2=startingPosition;lineLength<0&&index2<length;++index2){character=buffer2[index2];if(character===":"&&fieldLength<0){fieldLength=index2-position}else if(character==="\r"){discardTrailingNewline=true;lineLength=index2-position}else if(character===`
|
|
323
323
|
`){lineLength=index2-position}}if(lineLength<0){startingPosition=length-position;startingFieldLength=fieldLength;break}else{startingPosition=0;startingFieldLength=-1}parseEventStreamLine(buffer2,position,fieldLength,lineLength);position+=lineLength+1}if(position===length){buffer2=""}else if(position>0){buffer2=buffer2.slice(position)}}function parseEventStreamLine(lineBuffer,index2,fieldLength,lineLength){if(lineLength===0){if(data.length>0){onParse({_tag:"Event",id:eventId,event:eventName??"message",data:data.slice(0,-1)});data="";eventId=undefined}eventName=undefined;return}const noValue=fieldLength<0;const field=lineBuffer.slice(index2,index2+(noValue?lineLength:fieldLength));let step=0;if(noValue){step=lineLength}else if(lineBuffer[index2+fieldLength+1]===" "){step=fieldLength+2}else{step=fieldLength+1}const position=index2+step;const valueLength=lineLength-step;const value5=lineBuffer.slice(position,position+valueLength).toString();if(field==="data"){data+=value5?`${value5}
|
|
324
324
|
`:`
|
|
325
|
-
`}else if(field==="event"){eventName=value5}else if(field==="id"&&!value5.includes("\x00")){eventId=value5;lastEventId=value5}else if(field==="retry"){const retry5=parseInt(value5,10);if(!Number.isNaN(retry5)){onParse(new Retry({duration:millis(retry5),lastEventId}))}}}}var BOM=[239,187,191];function hasBom(buffer2){return BOM.every((charCode,index2)=>buffer2.charCodeAt(index2)===charCode)}var EventEncoded=Struct({id:optional(String5),event:String5,data:String5});var RetryTypeId="~effect/encoding/Sse/Retry";class Retry extends TaggedClass("Retry"){[RetryTypeId]=RetryTypeId;static is(u){return hasProperty(u,RetryTypeId)}static filter(u){return Retry.is(u)?succeed2(u):fail2(u)}}var SecurityTypeId="~effect/httpapi/HttpApiMiddleware/Security";var isSecurity=(u)=>hasProperty(u,SecurityTypeId);var exports_OpenApi={};__export(exports_OpenApi,{fromApi:()=>fromApi,annotations:()=>annotations,Version:()=>Version2,Transform:()=>Transform,Title:()=>Title,Summary:()=>Summary,Servers:()=>Servers,Override:()=>Override,License:()=>License,Identifier:()=>Identifier,Format:()=>Format,ExternalDocs:()=>ExternalDocs,Exclude:()=>Exclude,Description:()=>Description,Deprecated:()=>Deprecated});class Identifier extends Service()("effect/httpapi/OpenApi/Identifier"){}class Title extends Service()("effect/httpapi/OpenApi/Title"){}class Version2 extends Service()("effect/httpapi/OpenApi/Version"){}class Description extends Service()("effect/httpapi/OpenApi/Description"){}class License extends Service()("effect/httpapi/OpenApi/License"){}class ExternalDocs extends Service()("effect/httpapi/OpenApi/ExternalDocs"){}class Servers extends Service()("effect/httpapi/OpenApi/Servers"){}class Format extends Service()("effect/httpapi/OpenApi/Format"){}class Summary extends Service()("effect/httpapi/OpenApi/Summary"){}class Deprecated extends Service()("effect/httpapi/OpenApi/Deprecated"){}class Override extends Service()("effect/httpapi/OpenApi/Override"){}var Exclude=Reference("effect/httpapi/OpenApi/Exclude",{defaultValue:constFalse});class Transform extends Service()("effect/httpapi/OpenApi/Transform"){}var servicesPartial=(tags2)=>{const entries3=Object.entries(tags2);return(options4)=>{let context4=empty();for(const[key,tag4]of entries3){if(options4[key]!==undefined){context4=add(context4,tag4,options4[key])}}return context4}};var annotations=servicesPartial({identifier:Identifier,title:Title,version:Version2,description:Description,license:License,summary:Summary,deprecated:Deprecated,externalDocs:ExternalDocs,servers:Servers,format:Format,override:Override,exclude:Exclude,transform:Transform});var apiCache=new WeakMap;function processAnnotation(ctx,annotation,f){const o=getOption(ctx,annotation);if(isSome2(o)){f(o.value)}}function fromApi(api){const cached3=apiCache.get(api);if(cached3!==undefined){return cached3}let spec={openapi:"3.1.0",info:{title:"Api",version:"0.0.1"},paths:{},components:{schemas:{},securitySchemes:{}},security:[],tags:[]};const pathOps=[];const pathOperations=new Set;const operationIds=new Set;processAnnotation(api.annotations,Title,(title)=>{spec.info.title=title});processAnnotation(api.annotations,Version2,(version2)=>{spec.info.version=version2});processAnnotation(api.annotations,Description,(description)=>{spec.info.description=description});processAnnotation(api.annotations,License,(license)=>{spec.info.license=license});processAnnotation(api.annotations,Summary,(summary)=>{spec.info.summary=summary});processAnnotation(api.annotations,Servers,(servers)=>{spec.servers=[...servers]});reflect(api,{onGroup({group}){if(get(group.annotations,Exclude)){return}let tag4={name:getOrElse2(group.annotations,Title,()=>group.identifier)};processAnnotation(group.annotations,Description,(description)=>{tag4.description=description});processAnnotation(group.annotations,ExternalDocs,(externalDocs)=>{tag4.externalDocs=externalDocs});processAnnotation(group.annotations,Override,(override)=>{Object.assign(tag4,override)});processAnnotation(group.annotations,Transform,(transformFn)=>{tag4=transformFn(tag4)});spec.tags.push(tag4)},onEndpoint({endpoint,group,mergedAnnotations,middleware:middleware2}){if(get(mergedAnnotations,Exclude)){return}let op={tags:[getOrElse2(group.annotations,Title,()=>group.identifier)],operationId:getOrElse2(endpoint.annotations,Identifier,()=>group.topLevel?endpoint.identifier:`${group.identifier}.${endpoint.identifier}`),parameters:[],security:[],responses:{}};const path4=endpoint.path.replace(/:(\w+)\??/g,"{$1}");const method=endpoint.method.toLowerCase();function processResponseBodies(bodies,defaultDescription){for(const[status2,{content,descriptions,streamContent}]of bodies){const description=descriptions.size>0?Array.from(descriptions).join(" | "):defaultDescription();op.responses[status2]={description};if(content!==undefined){content.forEach((map18,encoding)=>{map18.forEach((schemas,contentType)=>{const asts=Array.from(schemas,getAST);const ast=asts.length===1?asts[0]:new Union(asts,"anyOf");pathOps.push({_tag:"schema",ast:toEncodingAST(ast,encoding),path:["paths",path4,method,"responses",String(status2),"content",contentType,"schema"]});op.responses[status2].content??={};op.responses[status2].content[contentType]={schema:{}}})})}if(streamContent!==undefined){streamContent.forEach((stream3,contentType)=>{op.responses[status2].content??={};if(isStreamSse(stream3)){pathOps.push({_tag:"schema",ast:getAST(stream3.events),path:["paths",path4,method,"responses",String(status2),"content",contentType,"schema"]});pathOps.push({_tag:"schema",ast:getAST(toCodecJson(Cause(stream3.error,Defect()))),path:["paths",path4,method,"responses",String(status2),"content",contentType,"x-effect-stream","causeSchema"]});pathOps.push({_tag:"schema",ast:getAST(stream3.error),path:["paths",path4,method,"responses",String(status2),"content",contentType,"x-effect-stream","errorSchema"]});op.responses[status2].content[contentType]={schema:{},"x-effect-stream":{encoding:"sse",causeSchema:{},errorSchema:{},failureEvent:reservedStreamFailureEvent2}}}else{op.responses[status2].content[contentType]={schema:{type:"string",format:"binary"},"x-effect-stream":{encoding:"uint8array"}}}})}}}function processParameters(schema2,i){if(schema2){const ast=getLastEncoding(schema2.ast);if(isObjects(ast)){for(const ps of ast.propertySignatures){op.parameters.push({name:String(ps.name),in:i,schema:{},required:i==="path"||!isOptional(ps.type)});pathOps.push({_tag:"parameter",ast:ps.type,path:["paths",path4,method,"parameters",String(op.parameters.length-1),"schema"]})}}}}processAnnotation(endpoint.annotations,Description,(description)=>{op.description=description});processAnnotation(endpoint.annotations,Summary,(summary)=>{op.summary=summary});processAnnotation(endpoint.annotations,Deprecated,(deprecated)=>{op.deprecated=deprecated});processAnnotation(endpoint.annotations,ExternalDocs,(externalDocs)=>{op.externalDocs=externalDocs});middleware2.forEach((middleware3)=>{if(!isSecurity(middleware3)){return}for(const[name,security]of Object.entries(middleware3.security)){processHttpApiSecurity(name,security);op.security.push({[name]:[]})}});function processHttpApiSecurity(name,security){const scheme=makeSecurityScheme(security);if(!Object.hasOwn(spec.components.securitySchemes,name)){set(spec.components.securitySchemes,name,scheme);return}if(!equals(securitySchemeForComparison(spec.components.securitySchemes[name]),securitySchemeForComparison(scheme))){throw new globalThis.Error(`Conflicting OpenAPI security scheme: ${name}`)}}const hasBody2=hasBody(endpoint.method);if(hasBody2){const schemasByContentType=new Map;for(const schema2 of getPayloadSchemas(endpoint)){if(isNoContent(schema2.ast))continue;const encoding=getPayloadEncoding(schema2.ast,endpoint.method);const existing=schemasByContentType.get(encoding.contentType);if(existing===undefined){schemasByContentType.set(encoding.contentType,{encoding,schemas:[schema2]})}else{existing.schemas.push(schema2)}}if(schemasByContentType.size>0){const content={};for(const[contentType,{encoding,schemas}]of schemasByContentType){const asts=schemas.map(getAST);const ast=asts.length===1?asts[0]:new Union(asts,"anyOf");pathOps.push({_tag:"schema",ast:toEncodingAST(ast,encoding._tag),path:["paths",path4,method,"requestBody","content",contentType,"schema"]});content[contentType]={schema:{}}}op.requestBody={content,required:true}}}processParameters(endpoint.params,"path");if(!hasBody2&&endpoint.payload.size===1){const entry=endpoint.payload.values().next().value;processParameters(entry.schemas[0],"query")}processParameters(endpoint.headers,"header");processParameters(endpoint.query,"query");processResponseBodies(extractSuccessResponseBodies(endpoint),()=>"Success");processResponseBodies(extractResponseBodies(getErrorSchemas(endpoint),getStatusError,resolveDescriptionOrIdentifier),()=>"Error");processAnnotation(endpoint.annotations,Override,(override)=>{Object.assign(op,override)});processAnnotation(endpoint.annotations,Transform,(transformFn)=>{op=transformFn(op)});const pathOperation=`${method} ${path4.replace(/\{[^}]+\}/g,"{}")}`;if(pathOperations.has(pathOperation)){throw new globalThis.Error(`Duplicate OpenAPI operation for ${endpoint.method} ${path4}`)}const operationId=op.operationId;if(operationId!==undefined){if(operationIds.has(operationId)){throw new globalThis.Error(`Duplicate OpenAPI operationId: ${operationId}`)}operationIds.add(operationId)}pathOperations.add(pathOperation);if(!spec.paths[path4]){spec.paths[path4]={}}spec.paths[path4][method]=op}});processAnnotation(api.annotations,AdditionalSchemas,(componentSchemas)=>{componentSchemas.forEach((componentSchema)=>{const identifier2=resolveIdentifier2(componentSchema.ast);if(identifier2!==undefined){if(identifier2 in spec.components.schemas){throw new globalThis.Error(`Duplicate component schema identifier: ${identifier2}`)}spec.components.schemas[identifier2]={};pathOps.push({_tag:"schema",ast:componentSchema.ast,path:["components","schemas",identifier2]})}})});function escapePath(path4){return"/"+path4.map(escapeToken).join("/")}if(isArrayNonEmpty2(pathOps)){const multiDocument=fromASTs2(map4(pathOps,(op)=>op.ast));const jsonSchemaMultiDocument=toMultiDocumentOpenApi3_1(toJsonSchemaMultiDocument2(multiDocument));const patchOps=pathOps.map((op,i)=>{const oppath=escapePath(op.path);const value5=jsonSchemaMultiDocument.schemas[i];return{op:"replace",path:oppath,value:value5}});Object.entries(jsonSchemaMultiDocument.definitions).forEach(([name,definition])=>{patchOps.push({op:"add",path:escapePath(["components","schemas",name]),value:definition})});spec=apply(patchOps,spec)}Object.keys(spec.components.schemas).forEach((key)=>{if(!VALID_OPEN_API_COMPONENTS_SCHEMAS_KEY_REGEXP.test(key)){throw new globalThis.Error(`Invalid component schema key: ${key}`)}});processAnnotation(api.annotations,Override,(override)=>{Object.assign(spec,override)});processAnnotation(api.annotations,Transform,(transformFn)=>{spec=transformFn(spec)});apiCache.set(api,spec);return spec}var reservedStreamFailureEvent2="effect/httpapi/stream/failure";function extractSuccessResponseBodies(endpoint){return extractResponseBodies(getSuccessSchemas(endpoint),getStatusSuccess,resolveDescriptionOrIdentifier)}function extractResponseBodies(schemas,getStatus,getDescription){const map18=new Map;schemas.forEach(process2);return map18;function process2(schema2){if(isStreamSchema(schema2)){addStreamContent(schema2);return}const ast=schema2.ast;const status2=getStatus(ast);if(isNoContent(ast)){addNoContent(status2,getDescription(schema2.ast)??"<No Content>")}else{addContent(schema2,status2,getResponseEncoding(ast))}}function addNoContent(status2,description){const statusMap=map18.get(status2);if(statusMap===undefined){map18.set(status2,{descriptions:new Set([description]),content:undefined,streamContent:undefined})}else{if(description!==undefined){statusMap.descriptions.add(description)}}}function addContent(schema2,status2,encoding){const description=getDescription(schema2.ast);const statusMap=map18.get(status2);const{_tag,contentType}=encoding;if(statusMap===undefined){map18.set(status2,{descriptions:new Set(description!==undefined?[description]:[]),content:new Map([[_tag,new Map([[contentType,new Set([schema2])]])]]),streamContent:undefined})}else{if(description!==undefined){statusMap.descriptions.add(description)}if(statusMap.content===undefined){statusMap.content=new Map([[_tag,new Map([[contentType,new Set([schema2])]])]])}else{const schemasByContentType=statusMap.content.get(_tag);if(schemasByContentType===undefined){statusMap.content.set(_tag,new Map([[contentType,new Set([schema2])]]))}else{const set7=schemasByContentType.get(contentType);if(set7===undefined){schemasByContentType.set(contentType,new Set([schema2]))}else{set7.add(schema2)}}}}}function addStreamContent(stream3){const status2=getStatusStream(stream3);const statusMap=map18.get(status2);if(statusMap===undefined){map18.set(status2,{descriptions:new Set,content:undefined,streamContent:new Map([[stream3.contentType,stream3]])})}else if(statusMap.streamContent===undefined){statusMap.streamContent=new Map([[stream3.contentType,stream3]])}else{statusMap.streamContent.set(stream3.contentType,stream3)}}}function resolveDescriptionOrIdentifier(ast){return resolveDescription2(ast)??resolveIdentifier2(ast)}var Uint8ArrayEncoding=String5.annotate({format:"binary"});function toEncodingAST(ast,_tag){switch(_tag){case"Uint8Array":return Uint8ArrayEncoding.ast;case"Text":return String5.ast;case"FormUrlEncoded":case"Json":return ast;case"Multipart":return persistedFileToBinaryEncoding(ast)}}function persistedFileToBinaryEncoding(ast){if(isDeclaration(ast)&&ast.annotations?.typeConstructor?._tag==="effect/http/PersistedFile"){return Uint8ArrayEncoding.ast}if(typeof ast?.recur==="function"){return ast.recur(persistedFileToBinaryEncoding)}return ast}var makeSecurityScheme=(security)=>{const meta={};processAnnotation(security.annotations,Description,(description)=>{meta.description=description});switch(security._tag){case"Basic":{return{...meta,type:"http",scheme:"basic"}}case"Http":{const format5=getOption(security.annotations,Format).pipe(map((format6)=>({bearerFormat:format6})),getOrUndefined);return{...meta,type:"http",scheme:security.scheme,...format5}}case"ApiKey":{return{...meta,type:"apiKey",name:security.key,in:security.in}}}};var securitySchemeForComparison=(scheme)=>{if(scheme.type==="http"){return{...scheme,scheme:scheme.scheme.toLowerCase()}}if(scheme.in==="header"){return{...scheme,name:scheme.name.toLowerCase()}}return scheme};var exports_HttpApiClient={};__export(exports_HttpApiClient,{urlBuilder:()=>urlBuilder,makeWith:()=>makeWith3,makeClient:()=>makeClient,make:()=>make46,group:()=>group,endpoint:()=>endpoint});var makeClient=(api,options4)=>gen2(function*(){const services=yield*context2();const httpClient=options4.httpClient.pipe(options4?.baseUrl===undefined?identity:mapRequest(prependUrl(options4.baseUrl.toString())));function executeMiddleware(group,endpoint,request3,middlewareKeys,index2){if(index2===-1){return httpClient.execute(request3)}const middleware2=services.mapUnsafe.get(middlewareKeys[index2]);if(middleware2===undefined){return executeMiddleware(group,endpoint,request3,middlewareKeys,index2-1)}return middleware2({endpoint,group,request:request3,next(request4){return executeMiddleware(group,endpoint,request4,middlewareKeys,index2-1)}})}reflect(api,{predicate:options4?.predicate,onGroup(onGroupOptions){options4.onGroup?.(onGroupOptions)},onEndpoint(onEndpointOptions){const{group,endpoint,errors:errors2,successes}=onEndpointOptions;const makeUrl=compilePath(endpoint.path);const decodeMap={orElse:statusOrElse};const decodeResponse=matchStatus(decodeMap);const errorAlternatives=new Map;for(const[status2,schemas]of errors2.entries()){const grouped=groupSchemasByContentType(schemas);for(const[contentType,schemas2]of grouped.entries()){addResponseAlternative(errorAlternatives,status2,contentType,schemasToResponse(schemas2))}}for(const[status2,alternatives]of errorAlternatives.entries()){const decode4=makeResponseDecoder(alternatives);decodeMap[status2]=(response)=>flatMap4(catchCause2(decode4(response),(cause)=>failCause3(combine2(fail5(new HttpClientError({reason:new StatusCodeError({request:response.request,response})})),cause))),fail6)}const successAlternatives=new Map;for(const[status2,schemas]of successes.entries()){const grouped=groupSchemasByContentType(schemas);for(const[contentType,schemas2]of grouped.entries()){addResponseAlternative(successAlternatives,status2,contentType,schemasToResponse(schemas2))}}for(const streamSuccess of getStreamSuccessSchemas(endpoint)){addResponseAlternative(successAlternatives,getStatusStream(streamSuccess),streamSuccess.contentType,streamToResponse(streamSuccess))}for(const[status2,alternatives]of successAlternatives.entries()){decodeMap[status2]=makeResponseDecoder(alternatives)}const encodeParams=map12(endpoint.params,encodeUnknownEffect2);const payloadSchemas=getPayloadSchemas(endpoint);const encodePayload=isArrayNonEmpty2(payloadSchemas)?hasBody(endpoint.method)?encodeUnknownEffect2(getEncodePayloadSchema(payloadSchemas,endpoint.method)):encodeUnknownEffect2(Union2(payloadSchemas)):undefined;const encodeHeaders=map12(endpoint.headers,encodeUnknownEffect2);const encodeQuery=map12(endpoint.query,encodeUnknownEffect2);const middlewareKeys=Array.from(onEndpointOptions.middleware,(tag4)=>`${tag4.key}/Client`);const endpointFn=fnUntraced2(function*(request3){let httpRequest=make42(endpoint.method)(endpoint.path);if(request3!==undefined){if(encodeParams!==undefined){const params=yield*encodeParams(request3.params);httpRequest=setUrl(httpRequest,makeUrl(params))}if(encodePayload!==undefined){if(hasBody(endpoint.method)){if(request3.payload instanceof FormData){httpRequest=bodyFormData(httpRequest,request3.payload)}else{const body=yield*encodePayload(request3.payload);httpRequest=setBody(httpRequest,body)}}else{const urlParams2=yield*encodePayload(request3.payload);httpRequest=appendUrlParams(httpRequest,urlParams2)}}if(encodeHeaders!==undefined){const headers=yield*encodeHeaders(request3.headers);httpRequest=setHeaders(httpRequest,headers)}if(encodeQuery!==undefined){const query=yield*encodeQuery(request3.query);httpRequest=appendUrlParams(httpRequest,query)}}const response=yield*executeMiddleware(group,endpoint,httpRequest,middlewareKeys,middlewareKeys.length-1);if(request3?.responseMode==="response-only"){return response}const value5=yield*options4.transformResponse===undefined?decodeResponse(response):options4.transformResponse(decodeResponse(response));return request3?.responseMode==="decoded-and-response"?[value5,response]:value5});options4.onEndpoint({...onEndpointOptions,endpointFn})}})});var make46=(api,options4)=>flatMap4(HttpClient,(httpClient)=>makeWith3(api,{...options4,httpClient:options4?.transformClient?options4.transformClient(httpClient):httpClient}));var makeWith3=(api,options4)=>{const client={};return makeClient(api,{...options4,onGroup({group}){if(group.topLevel)return;set(client,group.identifier,{})},onEndpoint({endpoint,endpointFn,group}){set(group.topLevel?client:client[group.identifier],endpoint.identifier,endpointFn)}}).pipe(as2(client))};var group=(api,options4)=>{const client={};return makeClient(api,{...options4,predicate:({group:group2})=>group2.identifier===options4.group,onEndpoint({endpoint,endpointFn}){set(client,endpoint.identifier,endpointFn)}}).pipe(map7(()=>client))};var endpoint=(api,options4)=>{let client=undefined;return makeClient(api,{...options4,httpClient:options4.transformClient?options4.transformClient(options4.httpClient):options4.httpClient,predicate:({endpoint:endpoint2,group:group2})=>group2.identifier===options4.group&&endpoint2.identifier===options4.endpoint,onEndpoint({endpointFn}){client=endpointFn}}).pipe(map7(()=>client))};var urlBuilder=(api,options4)=>{const builder={};reflect(api,{onGroup({group:group2}){if(group2.topLevel)return;set(builder,group2.identifier,{})},onEndpoint({group:group2,endpoint:endpoint2}){const makeUrl=compilePath(endpoint2.path);const encodeParams=endpoint2.params===undefined?undefined:encodeSync2(endpoint2.params);const encodeQuery=endpoint2.query===undefined?undefined:encodeSync2(endpoint2.query);const endpointBuilder=(request3)=>{const params=request3?.params;const path4=params===undefined?endpoint2.path:makeUrl(encodeParams===undefined?params:encodeParams(params));const queryInput=request3?.query===undefined?undefined:encodeQuery===undefined?request3.query:encodeQuery(request3.query);const query=queryInput===undefined?"":toString(fromInput3(queryInput));const url2=query===""?path4:`${path4}?${query}`;return options4?.baseUrl===undefined?url2:new URL(url2,options4.baseUrl.toString()).toString()};set(group2.topLevel?builder:builder[group2.identifier],endpoint2.identifier,endpointBuilder)}});return builder};var paramsRegExp=/(\/?):(\w+)(\?)?/g;var compilePath=(path4)=>{if(!paramsRegExp.test(path4)){return(_)=>path4}paramsRegExp.lastIndex=0;return(params)=>{paramsRegExp.lastIndex=0;return path4.replace(paramsRegExp,(_,slash,key,optional4)=>{const value5=params[key];if(value5===undefined){if(optional4!==undefined){return""}throw new Error(`Missing path parameter: ${key}`)}return`${slash}${encodeURIComponent(value5)}`})}};function schemasToResponse(schemas){const codec=toCodecArrayBuffer(schemas);const decode4=decodeEffect2(codec);return(response)=>flatMap4(response.arrayBuffer,decode4)}function addResponseAlternative(map18,status2,contentType,decode4){const normalizedContentType=normalize2(contentType);const alternatives=map18.get(status2);if(alternatives===undefined){map18.set(status2,[{contentType:normalizedContentType,decode:decode4}])}else{alternatives.push({contentType:normalizedContentType,decode:decode4})}}function makeResponseDecoder(alternatives){const first=alternatives[0];if(alternatives.length===1&&first!==undefined){return first.decode}return(response)=>{const contentType=normalize2(response.headers["content-type"]??"");const alternative=alternatives.find((alternative2)=>alternative2.contentType===contentType);return alternative===undefined?failUnsupportedContentType(response,contentType,alternatives):alternative.decode(response)}}function groupSchemasByContentType(schemas){const grouped=new Map;for(const schema2 of schemas){const contentType=isNoContent(schema2.ast)?"":normalize2(getResponseEncoding(schema2.ast).contentType);const existing=grouped.get(contentType);if(existing===undefined){grouped.set(contentType,[schema2])}else{existing.push(schema2)}}return grouped}function failUnsupportedContentType(response,contentType,alternatives){const expected=Array.from(new Set(alternatives.map((alternative)=>alternative.contentType))).join(", ");return fail6(new HttpClientError({reason:new DecodeError({request:response.request,response,description:`Unsupported response content-type for status ${response.status}: ${contentType||"<missing>"}. Expected one of: ${expected}`})}))}var reservedStreamFailureEvent3="effect/httpapi/stream/failure";function getStreamSuccessSchemas(endpoint2){const schemas=[];for(const schema2 of endpoint2.success){if(isStreamSchema(schema2)){schemas.push(schema2)}}return schemas}function streamToResponse(streamSchema2){const sse=isStreamUint8Array(streamSchema2)?undefined:{declaration:streamSchema2,decoder:makeSseDecoder(streamSchema2)};return(response)=>map7(context2(),(context4)=>provideContext4(sse===undefined?response.stream:decodeSseStream(response.stream,sse.declaration,sse.decoder),context4))}function makeSseDecoder(declaration){const Event=Union2([Struct({event:Literal2(reservedStreamFailureEvent3),data:fromJsonString2(toCodecJson(Cause(declaration.error,Defect())))}),declaration.events]);return decodeSchema(Event)}function decodeSseStream(stream3,declaration,decoder2){const events=transformPull2(stream3.pipe(decodeText,pipeThroughChannel(decoder2)),(pull)=>sync2(()=>{let pendingFailureCause=undefined;return suspend2(()=>{if(pendingFailureCause!==undefined){return failCause3(pendingFailureCause)}return flatMap4(pull,(events2)=>{for(let i=0;i<events2.length;i++){const event=events2[i];if(event.event===reservedStreamFailureEvent3&&isCause2(event.data)){if(i===0){return failCause3(event.data)}pendingFailureCause=event.data;events2=events2.slice(0,i);break}}return succeed6(events2)})})}));if(declaration.sseMode==="data"){return map9(events,(event)=>event.data)}return events}var ArrayBuffer2=instanceOf(globalThis.ArrayBuffer,{expected:"ArrayBuffer"});var Uint8ArrayFromArrayBuffer=ArrayBuffer2.pipe(decodeTo2(Uint8Array2,transform2({decode(fromA){return new Uint8Array(fromA)},encode(arr){return arr.byteLength===arr.buffer.byteLength?arr.buffer:arr.buffer.slice(arr.byteOffset,arr.byteOffset+arr.byteLength)}})));var StringFromArrayBuffer=ArrayBuffer2.pipe(decodeTo2(String5,transform2({decode(fromA){return new TextDecoder().decode(fromA)},encode(toI){const arr=new TextEncoder().encode(toI);return arr.byteLength===arr.buffer.byteLength?arr.buffer:arr.buffer.slice(arr.byteOffset,arr.byteOffset+arr.byteLength)}})));var UnknownFromArrayBuffer=StringFromArrayBuffer.pipe(decodeTo2(Union2([Literal2("").pipe(decodeTo2(Undefined2,transform2({decode:()=>{return},encode:()=>""}))),UnknownFromJsonString])));function toCodecArrayBuffer(schemas){return Union2(schemas.map(onSchema));function onSchema(schema2){const encoding=getResponseEncoding(schema2.ast);switch(encoding._tag){case"Json":{const encodedIsNull=isNull(toEncoded(schema2.ast));return UnknownFromArrayBuffer.pipe(decodeTo2(schema2,encodedIsNull?transform2({decode:(a)=>a===undefined?null:a,encode:(a)=>a===null?undefined:a}):undefined))}case"FormUrlEncoded":return StringFromArrayBuffer.pipe(decodeTo2(schemaRecord),decodeTo2(schema2));case"Uint8Array":return Uint8ArrayFromArrayBuffer.pipe(decodeTo2(schema2));case"Text":return StringFromArrayBuffer.pipe(decodeTo2(schema2))}}}var statusOrElse=(response)=>fail6(new HttpClientError({reason:new DecodeError({request:response.request,response})}));var $HttpBody=declare(isHttpBody);function getEncodePayloadSchema(schemas,method){return Union2(schemas.map((s)=>getEncodePayloadSchemaFromBody(s,method)))}var bodyFromPayloadCache=new WeakMap;function getEncodePayloadSchemaFromBody(schema2,method){const ast=schema2.ast;const cached3=bodyFromPayloadCache.get(ast);if(cached3!==undefined){return cached3}const encoding=getPayloadEncoding(ast,method);const out=$HttpBody.pipe(decodeTo2(schema2,transformOrFail2({decode(httpBody){return fail6(new Forbidden(some2(httpBody),{message:"Encode only schema"}))},encode(t){switch(encoding._tag){case"Multipart":return fail6(new Forbidden(some2(t),{message:"Payload must be a FormData"}));case"Json":{try{const body=JSON.stringify(t);return succeed6(text2(body,encoding.contentType))}catch(error2){return fail6(new InvalidValue(some2(t),{message:globalThis.String(error2)}))}}case"Text":{if(typeof t!=="string"){return fail6(new InvalidValue(some2(t),{message:"Expected a string"}))}return succeed6(text2(t,encoding.contentType))}case"FormUrlEncoded":{if(!isObject(t)){return fail6(new InvalidValue(some2(t),{message:"Expected a record"}))}return succeed6(urlParams(fromInput3(t),encoding.contentType))}case"Uint8Array":{if(!(t instanceof Uint8Array)){return fail6(new InvalidValue(some2(t),{message:"Expected a Uint8Array"}))}return succeed6(uint8Array2(t,encoding.contentType))}}}})));bodyFromPayloadCache.set(ast,out);return out}var exports_HttpApiGroup={};__export(exports_HttpApiGroup,{make:()=>make47,isHttpApiGroup:()=>isHttpApiGroup});var TypeId56="~effect/httpapi/HttpApiGroup";var isHttpApiGroup=(u)=>hasProperty(u,TypeId56);var Proto19={[TypeId56]:TypeId56,add(...toAdd){const endpoints={...this.endpoints};for(const endpoint2 of toAdd){set(endpoints,endpoint2.identifier,endpoint2)}return makeProto4({...optionsFromGroup(this),endpoints})},prefix(prefix){return makeProto4({...optionsFromGroup(this),endpoints:map3(this.endpoints,(endpoint2)=>endpoint2.prefix(prefix))})},middleware(middleware2){return makeProto4({...optionsFromGroup(this),endpoints:map3(this.endpoints,(endpoint2)=>endpoint2.middleware(middleware2))})},annotateMerge(annotations2){return makeProto4({...optionsFromGroup(this),annotations:merge(this.annotations,annotations2)})},annotate(annotation,value5){return makeProto4({...optionsFromGroup(this),annotations:add(this.annotations,annotation,value5)})},annotateEndpointsMerge(annotations2){return makeProto4({...optionsFromGroup(this),endpoints:map3(this.endpoints,(endpoint2)=>endpoint2.annotateMerge(annotations2))})},annotateEndpoints(annotation,value5){return makeProto4({...optionsFromGroup(this),endpoints:map3(this.endpoints,(endpoint2)=>endpoint2.annotate(annotation,value5))})},pipe(){return pipeArguments(this,arguments)}};var optionsFromGroup=(group2)=>({identifier:group2.identifier,topLevel:group2.topLevel,endpoints:group2.endpoints,annotations:group2.annotations});var makeProto4=(options4)=>{function HttpApiGroup(){}Object.setPrototypeOf(HttpApiGroup,Proto19);HttpApiGroup.key=`effect/httpapi/HttpApiGroup/${options4.identifier}`;return Object.assign(HttpApiGroup,options4)};var make47=(identifier2,options4)=>makeProto4({identifier:identifier2,topLevel:options4?.topLevel??false,endpoints:{},annotations:empty()});var defaultMessage=(message)=>String5.pipe(optionalKey2,withConstructorDefault2(succeed6(message)));var BaselineChannel=Literals(["stable","bundled"]);var HarnessReportStatus=Literals(["new","triaged","accepted","wontfix","resolved"]);var OperatorIdentity=Struct({operatorId:String5,email:optionalKey2(String5),emailVerified:optionalKey2(Boolean4)}).annotate({identifier:"OperatorIdentity"});var isoDateTimePattern=/^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})T(?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2})(?:\.(?<fraction>\d{1,9}))?(?:Z|[+-]\d{2}:\d{2})$/u;var isValidIsoDateTime=(value5)=>{const groups=isoDateTimePattern.exec(value5)?.groups;if(groups===undefined){return false}const year=Number(groups.year);const month=Number(groups.month);const day=Number(groups.day);const hour=Number(groups.hour);const minute=Number(groups.minute);const second=Number(groups.second);const millisecond=Number((groups.fraction??"").slice(0,3).padEnd(3,"0"));const date7=new Date(Date.UTC(year,month-1,day,hour,minute,second,millisecond));return Number.isFinite(Date.parse(value5))&&date7.getUTCFullYear()===year&&date7.getUTCMonth()===month-1&&date7.getUTCDate()===day&&date7.getUTCHours()===hour&&date7.getUTCMinutes()===minute&&date7.getUTCSeconds()===second};var IsoDateTimeString=String5.pipe(refine((value5)=>isValidIsoDateTime(value5),{identifier:"IsoDateTimeString",description:"an ISO 8601 datetime string with timezone"}));var GitIdentity=Struct({name:optionalKey2(String5),email:optionalKey2(String5)}).annotate({identifier:"GitIdentity"});var ObservedRepositoryInput=Struct({remoteUrl:optionalKey2(String5),remoteHost:optionalKey2(String5),remotePath:optionalKey2(String5),branch:optionalKey2(String5),commitSha:optionalKey2(String5),dirty:optionalKey2(Boolean4),gitIdentity:optionalKey2(GitIdentity)}).annotate({identifier:"ObservedRepositoryInput"});var SymbolPropertyKey=Struct({_tag:Literal2("symbol"),key:String5}).annotate({description:"an object to be decoded into a globally shared symbol"});var PropertyKey2=Union2([String5,Finite,SymbolPropertyKey]).annotate({identifier:"PropertyKey"});var DecodeIssue=Struct({_tag:Literals(["Pointer","Unexpected","Missing","Composite","Refinement","Transformation","Type","Forbidden"]),path:ArraySchema(PropertyKey2),message:String5}).annotate({identifier:"Issue"});class HttpApiDecodeError extends TaggedErrorClass()("HttpApiDecodeError",{issues:ArraySchema(DecodeIssue),message:String5},{httpApiStatus:400,description:"The request did not match the expected schema"}){}class Forbidden2 extends TaggedErrorClass()("@punks/contract/errors/Forbidden",{message:defaultMessage("The supplied credentials cannot access this resource.")},{httpApiStatus:403,title:"Forbidden"}){}var defaultMessage2=(message)=>String5.pipe(optionalKey2,withConstructorDefault2(succeed6(message)));var ArtifactKind=Literals(["manifest","archive"]);var BaselineVersion=NonEmptyString.annotate({identifier:"BaselineVersion"});var BaselineRequest=Struct({channel:BaselineChannel,version:optionalKey2(BaselineVersion)}).annotate({identifier:"BaselineRequest"});var BaselineVersionRequest=Struct({version:optionalKey2(BaselineVersion)}).annotate({identifier:"BaselineVersionRequest"});var BaselineSource=Literals(["control-plane","published-release","cache","bundled"]);var BaselineCompatibility=Struct({cliVersionRange:String5}).annotate({identifier:"BaselineCompatibility"});var BaselineRetrievalStatus=Literals(["available","retrieved","cached","fallback"]);var ArtifactMetadata=Struct({kind:ArtifactKind,fileName:String5,contentType:String5,url:String5,sha256:String5,sizeBytes:optionalKey2(Finite)}).annotate({identifier:"ArtifactMetadata"});var BaselineIdentity={requested:BaselineRequest,resolvedVersion:BaselineVersion,digest:String5,source:BaselineSource,provenance:String5,compatibility:BaselineCompatibility,retrieval:BaselineRetrievalStatus};var BaselineResolution=Struct({...BaselineIdentity,manifest:ArtifactMetadata,archive:ArtifactMetadata}).pipe(check2(makeFilter2(({requested,resolvedVersion})=>requested.version===undefined||requested.version===resolvedVersion,{message:"An exact baseline request must resolve to the requested version."})),check2(makeFilter2(({digest:digest2,archive})=>digest2===archive.sha256,{message:"The baseline digest must match the archive digest."}))).annotate({identifier:"BaselineResolution"});var BaselineArtifact=Struct({...BaselineIdentity,artifact:ArtifactMetadata}).pipe(check2(makeFilter2(({requested,resolvedVersion})=>requested.version===undefined||requested.version===resolvedVersion,{message:"Artifact metadata must match the exact requested baseline version."})),check2(makeFilter2(({artifact,digest:digest2})=>artifact.kind!=="archive"||artifact.sha256===digest2,{message:"The baseline artifact digest must match the verified baseline digest."}))).annotate({identifier:"BaselineArtifact"});class BaselineNotFound extends TaggedErrorClass()("@punks/contract/errors/BaselineNotFound",{channel:String5,message:defaultMessage2("No baseline exists for the requested channel.")},{httpApiStatus:404,title:"Baseline Not Found"}){}class ControlPlaneUnavailable extends TaggedErrorClass()("@punks/contract/errors/ControlPlaneUnavailable",{message:defaultMessage2("The control plane cannot resolve this resource yet.")},{httpApiStatus:503,title:"Control Plane Unavailable"}){}class BaselineAuthorityFailure extends TaggedErrorClass()("@punks/contract/errors/BaselineAuthorityFailure",{request:BaselineRequest,resolvedVersion:optionalKey2(BaselineVersion),message:String5},{httpApiStatus:409,title:"Baseline Authority Failure"}){}class BaselineIntegrityFailure extends TaggedErrorClass()("@punks/contract/errors/BaselineIntegrityFailure",{request:BaselineRequest,resolvedVersion:optionalKey2(BaselineVersion),expectedDigest:optionalKey2(String5),actualDigest:optionalKey2(String5),message:defaultMessage2("Baseline identity or artifact integrity verification failed.")},{httpApiStatus:422,title:"Baseline Integrity Failure"}){}var BaselineAvailability=Literals(["authority-unconfigured","network","unavailable-status"]);class BaselineUnavailable extends TaggedErrorClass()("@punks/contract/errors/BaselineUnavailable",{availability:BaselineAvailability,request:BaselineRequest,message:defaultMessage2("The requested baseline is unavailable.")},{httpApiStatus:503,title:"Baseline Unavailable"}){}var errors2=[HttpApiDecodeError,Forbidden2,BaselineNotFound,BaselineAuthorityFailure,BaselineIntegrityFailure,BaselineUnavailable];var BaselineApi=exports_HttpApiGroup.make("baseline").add(exports_HttpApiEndpoint.get("resolve","/:channel",{params:{channel:BaselineChannel},query:BaselineVersionRequest,success:BaselineResolution,error:errors2}),exports_HttpApiEndpoint.get("artifact","/:channel/artifacts/:kind",{params:{channel:BaselineChannel,kind:ArtifactKind},query:BaselineVersionRequest,success:BaselineArtifact,error:errors2})).prefix("/baselines").annotateMerge(exports_OpenApi.annotations({title:"Baseline control plane"}));import{createHash as createHash2}from"node:crypto";import{lstatSync,readFileSync,readdirSync,readlinkSync}from"node:fs";import path4 from"node:path";var digestContentRoots=(roots)=>{const entries3=[];for(const{root,prefix,include=()=>true,logicalPath=(value5)=>value5}of roots){const visit2=(directory3)=>{for(const entry of readdirSync(directory3,{withFileTypes:true})){const absolutePath=path4.join(directory3,entry.name);if(entry.isDirectory()){visit2(absolutePath);continue}const relativePath=path4.relative(root,absolutePath).split(path4.sep).join("/");if(include(relativePath)){entries3.push({absolutePath,identity:`${prefix}/${logicalPath(relativePath)}`})}}};visit2(root)}const hash3=createHash2("sha256");for(const{absolutePath,identity:identity3}of entries3.toSorted((left,right)=>left.identity.localeCompare(right.identity))){const stat3=lstatSync(absolutePath);hash3.update(identity3);hash3.update("\x00");if(stat3.isSymbolicLink()){hash3.update("symlink\x00");hash3.update(readlinkSync(absolutePath))}else{hash3.update("file\x00");hash3.update(readFileSync(absolutePath))}hash3.update("\x00")}return hash3.digest("hex")};import{existsSync,mkdirSync,readFileSync as readFileSync2,statSync,writeFileSync}from"node:fs";import{tmpdir as tmpdir2}from"node:os";import path5 from"node:path";var embeddedAssets=[];var name="@punks/cli";var version2="3.1.0";var findFirst6=(candidates)=>candidates.find((candidate)=>existsSync(candidate));var executableSignature=()=>{try{return String(Math.trunc(statSync(process.execPath).mtimeMs))}catch{return"unknown"}};var extractEmbeddedAssets=()=>{if(embeddedAssets.length===0){return}const root=path5.join(tmpdir2(),"punks-cli-assets",`${version2}-${executableSignature()}`);for(const asset of embeddedAssets){const targetPath=path5.join(root,asset.relativePath);if(existsSync(targetPath)){continue}mkdirSync(path5.dirname(targetPath),{recursive:true});writeFileSync(targetPath,readFileSync2(asset.path))}return root};var findBundledPackageRoot=()=>{let currentDirectory=path5.resolve(import.meta.dirname,"../..");while(true){if(existsSync(path5.join(currentDirectory,"package.json"))){return currentDirectory}const parentDirectory=path5.dirname(currentDirectory);if(parentDirectory===currentDirectory){break}currentDirectory=parentDirectory}return path5.resolve(import.meta.dirname,"../..")};var packageRoot=findBundledPackageRoot();var runtimeRoot=import.meta.dirname;var embeddedAssetsRoot=extractEmbeddedAssets();var executableRoots=[process.argv[1],process.execPath].filter((candidate)=>candidate!==undefined&&candidate.length>0).map((candidate)=>path5.dirname(path5.resolve(candidate)));var dataCandidates=[path5.join(runtimeRoot,"data"),...embeddedAssetsRoot===undefined?[]:[path5.join(embeddedAssetsRoot,"data")],...executableRoots.map((root)=>path5.join(root,"data")),path5.resolve(import.meta.dirname,"../data"),path5.join(packageRoot,"src/data"),path5.resolve(import.meta.dirname,"../../src/data")];var skillCandidates=[path5.join(runtimeRoot,"skills"),...embeddedAssetsRoot===undefined?[]:[path5.join(embeddedAssetsRoot,"skills")],...executableRoots.map((root)=>path5.join(root,"skills")),path5.join(packageRoot,"skills"),path5.resolve(import.meta.dirname,"../../skills"),path5.resolve(import.meta.dirname,"../skills")];var resolvedDataRoot=findFirst6(dataCandidates);var resolvedSkillsRoot=findFirst6(skillCandidates);if(resolvedDataRoot===undefined){throw new Error("Could not locate bundled data directory.")}if(resolvedSkillsRoot===undefined){throw new Error("Could not locate bundled skills directory.")}var dataRoot=resolvedDataRoot;var skillsRoot=resolvedSkillsRoot;var dataPath=(...segments)=>path5.join(dataRoot,...segments);var readDataFile=(...segments)=>readFileSync2(dataPath(...segments),"utf-8");var readBaselineDataFile=(baselineDataRoot,...segments)=>readFileSync2(path5.join(baselineDataRoot,...segments),"utf-8");var resolveBaselinePath=({baselineRoot,baselineSkillsRoot,relativePath})=>{const resolvedPath=relativePath.startsWith("skills/")?findFirst6([path5.join(baselineSkillsRoot,relativePath.slice("skills/".length)),path5.join(baselineRoot,relativePath)]):findFirst6([path5.join(baselineRoot,relativePath)]);if(resolvedPath!==undefined){return resolvedPath}throw new Error(`Could not locate baseline asset: ${relativePath}`)};var bundledBaselineDigest="09c98193f19bd32231fc47644f7ee0bb16aa8e9486d68bc6e9b1b56199cbe3be";var hookCatalog=[{description:"Shared session-start hook that reports whether managed Harness scaffold output is current.",harness:"shared",id:"scaffold-update-check",outputPath:".agents/hooks/scaffold-update-check.mjs",sourcePath:"hooks/scaffold-update-check.mjs"},{description:"Shared hook that auto-formats edited JS/TS/JSON files and lint-checks product files after tool use.",harness:"shared",id:"format-edited-file",outputPath:".agents/hooks/format-edited-file.mjs",sourcePath:"hooks/format-edited-file.mjs"}];var sharedReactPlacement={placementNotes:"Add as an override for detected React-rendered code. Keep backend packages outside this override unless they render React.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-react-workspace>/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected React workspaces"]};var webOnlyPlacement={placementNotes:"Place this in the Next.js app override. If the repo uses a different frontend app path, retarget the file globs to that workspace before composing the final Oxlint config.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-nextjs-workspace>/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected Next.js workspaces"]};var effectPlacement={placementNotes:"Apply this only where Effect code lives. If the target repo renames or splits backend workspaces, move the override with those code paths instead of broadening it repo-wide.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-effect-workspace>/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected Effect workspaces"]};var vitestPlacement={placementNotes:"Attach this to test-only globs. Expand or narrow the file patterns to match the repo's actual Vitest test layout instead of treating it as a global default.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-test-workspace>/**/*.{test,spec}.{js,jsx,ts,tsx}","<detected-test-workspace>/src/test/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected JavaScript/TypeScript test workspaces"]};var lintCatalog=[{description:"Ultracite React preset for rendered app and shared UI code.",id:"react-core",jsPlugins:[],oxlintPresets:["react"],placement:sharedReactPlacement,plugins:[],requiredDevDependencies:[],rules:{},settings:{}},{description:"React Hooks lint rules via the JS plugin bridge for Oxlint.",id:"react-hooks",jsPlugins:[{name:"react-hooks-js",specifier:"eslint-plugin-react-hooks"}],oxlintPresets:[],placement:sharedReactPlacement,plugins:[],requiredDevDependencies:["eslint-plugin-react-hooks"],rules:Object.fromEntries([["react-hooks-js/exhaustive-deps","error"],["react-hooks-js/component-hook-factories","error"],["react-hooks-js/config","error"],["react-hooks-js/error-boundaries","error"],["react-hooks-js/gating","error"],["react-hooks-js/globals","error"],["react-hooks-js/immutability","error"],["react-hooks-js/incompatible-library","error"],["react-hooks-js/preserve-manual-memoization","error"],["react-hooks-js/purity","error"],["react-hooks-js/refs","error"],["react-hooks-js/rules-of-hooks","error"],["react-hooks-js/set-state-in-effect","error"],["react-hooks-js/set-state-in-render","error"],["react-hooks-js/static-components","error"],["react-hooks-js/unsupported-syntax","error"],["react-hooks-js/use-memo","error"]]),settings:{}},{description:"Guidance rules that push React code away from unnecessary effects.",id:"react-you-might-not-need-an-effect",jsPlugins:[{name:"react-you-might-not-need-an-effect-js",specifier:"eslint-plugin-react-you-might-not-need-an-effect"}],oxlintPresets:[],placement:sharedReactPlacement,plugins:[],requiredDevDependencies:["eslint-plugin-react-you-might-not-need-an-effect"],rules:{"react-you-might-not-need-an-effect-js/no-adjust-state-on-prop-change":"error","react-you-might-not-need-an-effect-js/no-chain-state-updates":"error","react-you-might-not-need-an-effect-js/no-derived-state":"error","react-you-might-not-need-an-effect-js/no-event-handler":"error","react-you-might-not-need-an-effect-js/no-initialize-state":"error","react-you-might-not-need-an-effect-js/no-pass-data-to-parent":"error","react-you-might-not-need-an-effect-js/no-pass-live-state-to-parent":"error","react-you-might-not-need-an-effect-js/no-reset-all-state-on-prop-change":"error"},settings:{}},{description:"Ultracite Next.js preset for the main web application.",id:"next-core",jsPlugins:[],oxlintPresets:["next"],placement:{...webOnlyPlacement,placementNotes:"Place this beside the React app override and set `settings.next.rootDir` to the repo's actual Next workspace roots if the final config needs that plugin setting."},plugins:[],requiredDevDependencies:[],rules:{},settings:{}},{description:"Ultracite TanStack preset for query/router/start framework linting.",id:"tanstack-query-core",jsPlugins:[],oxlintPresets:["tanstack"],placement:{...webOnlyPlacement,placementNotes:"Scope this to client code that owns TanStack Query usage. Keep it out of server-only or shared non-query packages unless those paths actually create queries or mutations."},plugins:[],requiredDevDependencies:[],rules:{},settings:{}},{description:"Effect architectural rule that blocks barrel-package imports.",id:"effect-no-barrel-imports",jsPlugins:[{name:"effect-js",specifier:"@effect/eslint-plugin"}],oxlintPresets:[],placement:effectPlacement,plugins:[],requiredDevDependencies:["@effect/eslint-plugin"],rules:{"effect-js/no-import-from-barrel-package":["error",{packageNames:["effect"]}]},settings:{}},{description:"Ultracite Vitest preset for repo-owned test globs.",id:"vitest-core",jsPlugins:[],oxlintPresets:["vitest"],placement:vitestPlacement,plugins:[],requiredDevDependencies:[],rules:{},settings:{}}];var stableJson=(value5)=>JSON.stringify(value5);var placementKeyOf=(placement)=>[placement.recommendedConfigFile,...placement.recommendedFiles].join("::");var validateLintCatalog=(catalog)=>{const seenIds=new Set;const seenRules=new Map;const seenSettings=new Map;const seenJsPlugins=new Map;for(const asset of catalog){if(seenIds.has(asset.id)){throw new Error(`Duplicate lint asset id: ${asset.id}`)}seenIds.add(asset.id);const placementKey=placementKeyOf(asset.placement);for(const[ruleName,ruleValue]of Object.entries(asset.rules)){const key=`${placementKey}::rule::${ruleName}`;const value5=stableJson(ruleValue);const previous=seenRules.get(key);if(previous!==undefined&&previous.value!==value5){throw new Error(`Conflicting lint rule \`${ruleName}\` for placement \`${placementKey}\`: ${previous.assetId} vs ${asset.id}`)}if(previous===undefined){seenRules.set(key,{assetId:asset.id,value:value5})}}for(const[settingName,settingValue]of Object.entries(asset.settings)){const key=`${placementKey}::setting::${settingName}`;const value5=stableJson(settingValue);const previous=seenSettings.get(key);if(previous!==undefined&&previous.value!==value5){throw new Error(`Conflicting lint setting \`${settingName}\` for placement \`${placementKey}\`: ${previous.assetId} vs ${asset.id}`)}if(previous===undefined){seenSettings.set(key,{assetId:asset.id,value:value5})}}for(const plugin of asset.jsPlugins){const key=`${placementKey}::js-plugin::${plugin.name}`;const previous=seenJsPlugins.get(key);if(previous!==undefined&&previous.specifier!==plugin.specifier){throw new Error(`Conflicting JS plugin alias \`${plugin.name}\` for placement \`${placementKey}\`: ${previous.assetId} vs ${asset.id}`)}if(previous===undefined){seenJsPlugins.set(key,{assetId:asset.id,specifier:plugin.specifier})}}}return catalog};var skillCatalog=[{framework:"browser-automation",id:"agent-browser",language:null,requiresTools:["agent-browser"],sourceDirectory:"skills/agnostic/frontend/agent-browser",tier:"framework"},{framework:null,id:"backend-domain-structure",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/backend/backend-domain-structure",tier:"agnostic"},{framework:null,id:"backend-recoverable-actions",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/backend/backend-recoverable-actions",tier:"agnostic"},{framework:null,id:"logging-best-practices",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/backend/logging-best-practices",tier:"agnostic"},{framework:null,id:"audit-cicd-security",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/security/audit-cicd-security",tier:"agnostic"},{framework:null,id:"security-best-practices",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/security/security-best-practices",tier:"agnostic"},{framework:"better-auth",id:"better-auth-best-practices",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/better-auth/better-auth-best-practices",tier:"framework"},{framework:"better-auth",id:"better-auth-security-best-practices",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/better-auth/better-auth-security-best-practices",tier:"framework"},{framework:null,id:"create-plan",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/planning/create-plan",tier:"agnostic"},{framework:null,id:"create-spec",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/planning/create-spec",tier:"agnostic"},{framework:null,id:"delivery-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/delivery-phase",tier:"agnostic"},{framework:null,id:"design-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/design-phase",tier:"agnostic"},{framework:null,id:"debug-agent",language:null,requiresTools:["debug-agent"],sourceDirectory:"skills/agnostic/debug/debug-agent",tier:"agnostic"},{framework:null,id:"debugging-phase",language:null,requiresTools:["debug-agent"],sourceDirectory:"skills/phases/debugging-phase",tier:"agnostic"},{framework:null,id:"bug-discovery-phase",language:null,requiresTools:["clawpatch"],sourceDirectory:"skills/phases/bug-discovery-phase",tier:"agnostic"},{framework:null,id:"bug-resolution-phase",language:null,requiresTools:["clawpatch"],sourceDirectory:"skills/phases/bug-resolution-phase",tier:"agnostic"},{framework:null,id:"docs-ingest-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/docs-ingest-phase",tier:"agnostic"},{framework:null,id:"docs-onboarding",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/docs-onboarding",tier:"agnostic"},{framework:null,id:"writing-fragments",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/writing-fragments",tier:"agnostic"},{framework:null,id:"writing-beats",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/writing-beats",tier:"agnostic"},{framework:null,id:"writing-shape",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/writing-shape",tier:"agnostic"},{framework:"effect",id:"effect-backend-structure",language:"typescript",requiresTools:["opensrc"],sourceDirectory:"skills/frameworks/effect/effect-backend-structure",tier:"framework"},{framework:"effect",id:"effect",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/effect/effect",tier:"framework"},{framework:"effect",id:"effect-recoverable-actions",language:"typescript",requiresTools:["opensrc"],sourceDirectory:"skills/frameworks/effect/effect-recoverable-actions",tier:"framework"},{framework:"elysiajs",id:"elysiajs",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/elysia/elysiajs",tier:"framework"},{framework:"expo",id:"add-app-clip",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/add-app-clip",tier:"framework"},{framework:"expo",id:"building-native-ui",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/building-native-ui",tier:"framework"},{framework:"expo",id:"eas-simulator",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/eas-simulator",tier:"framework"},{framework:"expo",id:"eas-update-insights",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/eas-update-insights",tier:"framework"},{framework:"expo",id:"expo-api-routes",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-api-routes",tier:"framework"},{framework:"expo",id:"expo-brownfield",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-brownfield",tier:"framework"},{framework:"expo",id:"expo-cicd-workflows",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-cicd-workflows",tier:"framework"},{framework:"expo",id:"expo-deployment",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-deployment",tier:"framework"},{framework:"expo",id:"expo-dev-client",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-dev-client",tier:"framework"},{framework:"expo",id:"expo-examples",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-examples",tier:"framework"},{framework:"expo",id:"expo-module",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-module",tier:"framework"},{framework:"expo",id:"expo-observe",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-observe",tier:"framework"},{framework:"expo",id:"expo-skill-eval",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-skill-eval",tier:"framework"},{framework:"expo",id:"expo-tailwind-setup",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-tailwind-setup",tier:"framework"},{framework:"expo",id:"expo-ui",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-ui",tier:"framework"},{framework:"expo",id:"native-data-fetching",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/native-data-fetching",tier:"framework"},{framework:"expo",id:"upgrading-expo",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/upgrading-expo",tier:"framework"},{framework:"expo",id:"use-dom",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/use-dom",tier:"framework"},{framework:"expo",id:"web-to-native",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/web-to-native",tier:"framework"},{framework:"pulumi",id:"pulumi-overview",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/pulumi-overview",tier:"framework"},{framework:"pulumi",id:"pulumi-best-practices",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/pulumi-best-practices",tier:"framework"},{framework:"pulumi",id:"pulumi-component",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/pulumi-component",tier:"framework"},{framework:"pulumi",id:"pulumi-automation-api",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/pulumi-automation-api",tier:"framework"},{framework:"pulumi",id:"pulumi-esc",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/pulumi-esc",tier:"framework"},{framework:"pulumi",id:"provider-upgrade",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/provider-upgrade",tier:"framework"},{framework:"pulumi",id:"package-usage",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/package-usage",tier:"framework"},{framework:null,id:"design-taste-frontend",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/frontend/design-taste-frontend",tier:"agnostic"},{framework:null,id:"imagegen-frontend-mobile",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/frontend/imagegen-frontend-mobile",tier:"agnostic"},{framework:null,id:"imagegen-frontend-web",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/frontend/imagegen-frontend-web",tier:"agnostic"},{framework:null,id:"frontend-domain-structure",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/frontend/frontend-domain-structure",tier:"agnostic"},{framework:null,id:"finder-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/finder-phase",tier:"agnostic"},{framework:null,id:"goalify",language:null,requiresTools:[],sourceDirectory:"skills/phases/goalify",tier:"agnostic"},{framework:null,id:"grilling",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/requirements/grilling",tier:"agnostic"},{framework:null,id:"handoff",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/generic/handoff",tier:"agnostic"},{framework:null,id:"improve-codebase-architecture",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/research/improve-codebase-architecture",tier:"agnostic"},{framework:null,id:"implement-spec",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/planning/implement-spec",tier:"agnostic"},{framework:null,id:"repo-asset-management",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/repo-asset-management",tier:"agnostic"},{framework:null,id:"stack",language:null,requiresTools:["stack"],sourceDirectory:"skills/agnostic/planning/stack",tier:"agnostic"},{framework:null,id:"wayfinder",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/planning/wayfinder",tier:"agnostic"},{framework:"nextjs",id:"next-best-practices",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/nextjs/next-best-practices",tier:"framework"},{framework:"nextjs",id:"next-cache-components",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/nextjs/next-cache-components",tier:"framework"},{framework:null,id:"parallel-research",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/research/parallel-research",tier:"agnostic"},{framework:null,id:"prototype",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/research/prototype",tier:"agnostic"},{framework:null,id:"async-python-patterns",language:"python",requiresTools:[],sourceDirectory:"skills/languages/python/async-python-patterns",tier:"language"},{framework:null,id:"python-code-style",language:"python",requiresTools:[],sourceDirectory:"skills/languages/python/python-code-style",tier:"language"},{framework:null,id:"python-design-patterns",language:"python",requiresTools:[],sourceDirectory:"skills/languages/python/python-design-patterns",tier:"language"},{framework:null,id:"python-project-structure",language:"python",requiresTools:[],sourceDirectory:"skills/languages/python/python-project-structure",tier:"language"},{framework:null,id:"python-testing-patterns",language:"python",requiresTools:[],sourceDirectory:"skills/languages/python/python-testing-patterns",tier:"language"},{framework:null,id:"quality-types",language:"typescript",requiresTools:[],sourceDirectory:"skills/languages/typescript/quality-types",tier:"language"},{framework:null,id:"codebase-design",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/codebase-design",tier:"agnostic"},{framework:"react",id:"async-react-patterns",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/react/async-react-patterns",tier:"framework"},{framework:"react",id:"react-doctor",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/react/react-doctor",tier:"framework"},{framework:null,id:"requirements-grill",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/requirements/requirements-grill",tier:"agnostic"},{framework:null,id:"requirements-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/requirements-phase",tier:"agnostic"},{framework:null,id:"resolve-debt-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/resolve-debt-phase",tier:"agnostic"},{framework:null,id:"review-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/review-phase",tier:"agnostic"},{framework:null,id:"review",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/review",tier:"agnostic"},{framework:null,id:"autoreview",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/autoreview",tier:"agnostic"},{framework:null,id:"simplify",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/simplify",tier:"agnostic"},{framework:null,id:"swarm-planner",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/subagents/swarm-planner",tier:"agnostic"},{framework:"tanstack-query",id:"tanstack-query",language:"typescript",requiresTools:["opensrc"],sourceDirectory:"skills/frameworks/tanstack-query/tanstack-query",tier:"framework"},{framework:null,id:"tdd",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/tdd",tier:"agnostic"},{framework:null,id:"writing-great-skills",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/writing-great-skills",tier:"agnostic"},{framework:"turborepo",id:"turborepo",language:null,requiresTools:[],sourceDirectory:"skills/frameworks/turborepo/turborepo",tier:"framework"},{framework:"react",id:"vercel-composition-patterns",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/react/vercel-composition-patterns",tier:"framework"},{framework:"react",id:"vercel-react-best-practices",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/react/vercel-react-best-practices",tier:"framework"},{framework:null,id:"write-backlog",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/requirements/write-backlog",tier:"agnostic"}];var toolCatalog=[{ensureCommands:[["agent-browser","install"]],id:"agent-browser",latestInstallTarget:"agent-browser@latest",packageName:"agent-browser",requiredBins:["node"],skipEnsureCommandsIfAnyCommandExists:[{env:"AGENT_BROWSER_EXECUTABLE_PATH"},"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium","/Applications/Brave Browser.app/Contents/MacOS/Brave Browser","google-chrome","google-chrome-stable","chromium","chromium-browser","brave-browser","brave-browser-stable","C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe","C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"]},{ensureCommands:[],id:"debug-agent",latestInstallTarget:"debug-agent@latest",packageName:"debug-agent",requiredBins:["node"]},{ensureCommands:[],id:"clawpatch",latestInstallTarget:"clawpatch@latest",packageName:"clawpatch",requiredBins:["node"]},{ensureCommands:[],id:"opensrc",latestInstallTarget:"opensrc@latest",minimumVersion:"0.7.2",packageName:"opensrc@^0.7.2",requiredBins:["node"],versionCommand:["opensrc","--version"]},{ensureCommands:[],id:"portless",latestInstallTarget:"portless@latest",packageName:"portless",requiredBins:["node"]},{ensureCommands:[],id:"skills",latestInstallTarget:"skills@latest",packageName:"skills",requiredBins:["node"]},{ensureCommands:[],id:"stack",latestInstallTarget:"@kitlangton/stack@latest",packageName:"@kitlangton/stack",requiredBins:["node"]}];var bundledNpmInstallAliasManifest=[{expectedSha256:"d1a3b15bb12948cfbd82acdd54889efc5d1263809550cb4d379863bbc1cc2f82",logicalRelativePath:"frameworks/nestjs/nestjs-best-practices/.gitignore",physicalRelativePath:"frameworks/nestjs/nestjs-best-practices/.npmignore"}];var fileSha256=(filePath)=>createHash3("sha256").update(readFileSync3(filePath)).digest("hex");var npmIgnoreFiles=(root)=>{const files=[];const visit2=(directory3)=>{for(const entry of readdirSync2(directory3,{withFileTypes:true})){const absolutePath=path6.join(directory3,entry.name);if(entry.isDirectory()){visit2(absolutePath)}else if(entry.isFile()&&entry.name===".npmignore"){files.push(path6.relative(root,absolutePath).split(path6.sep).join("/"))}}};visit2(root);return files};var resolveBundledSkillAliases=(root)=>{const aliases=new Map;const expectedPhysicalPaths=new Set(bundledNpmInstallAliasManifest.map(({physicalRelativePath})=>physicalRelativePath));for(const relativePath of npmIgnoreFiles(root)){if(!expectedPhysicalPaths.has(relativePath)){throw new Error(`Bundled baseline contains an unexpected npm alias: ${relativePath}`)}}for(const alias of bundledNpmInstallAliasManifest){const logicalPath=path6.join(root,alias.logicalRelativePath);const physicalPath=path6.join(root,alias.physicalRelativePath);const hasLogical=existsSync2(logicalPath);const hasPhysical=existsSync2(physicalPath);if(hasLogical&&hasPhysical){throw new Error(`Bundled baseline npm alias is ambiguous: ${alias.logicalRelativePath}`)}let resolvedPath=null;if(hasLogical){resolvedPath=logicalPath}else if(hasPhysical){resolvedPath=physicalPath}if(resolvedPath===null){throw new Error(`Bundled baseline asset is missing: ${alias.logicalRelativePath}`)}if(fileSha256(resolvedPath)!==alias.expectedSha256){throw new Error(`Bundled baseline npm alias hash mismatch: ${alias.logicalRelativePath}`)}if(hasPhysical){aliases.set(alias.physicalRelativePath,alias.logicalRelativePath)}}return aliases};var logicalBundledSkillRelativePath=(relativePath)=>bundledNpmInstallAliasManifest.find(({physicalRelativePath})=>physicalRelativePath===relativePath)?.logicalRelativePath??relativePath;var materializeBundledSkillDirectoryAliases=({sourceDirectory,sourceSkillsRoot,targetDirectory})=>{for(const alias of bundledNpmInstallAliasManifest){const sourcePhysicalPath=path6.join(sourceSkillsRoot,alias.physicalRelativePath);if(!existsSync2(sourcePhysicalPath)){continue}const relativePhysicalPath=path6.relative(sourceDirectory,sourcePhysicalPath);if(relativePhysicalPath===".."||relativePhysicalPath.startsWith(`..${path6.sep}`)){continue}const physicalPath=path6.join(targetDirectory,relativePhysicalPath);if(!existsSync2(physicalPath)){continue}const logicalPath=path6.join(targetDirectory,path6.relative(sourceDirectory,path6.join(sourceSkillsRoot,alias.logicalRelativePath)));if(existsSync2(logicalPath)){throw new Error(`Bundled baseline npm alias is ambiguous: ${alias.logicalRelativePath}`)}renameSync(physicalPath,logicalPath)}};var bundledBaseline={dataRoot,hooks:hookCatalog,lintAssets:validateLintCatalog(lintCatalog),packs:packCatalog,root:path6.dirname(dataRoot),skills:skillCatalog,skillsRoot,summary:{authoritySource:"bundled",channel:"bundled",commit:null,compatibility:{cliVersionRange:`=${version2}`},digest:bundledBaselineDigest,provenance:"packaged-cli",requested:{channel:"bundled"},resolvedVersion:version2,retrieval:"available",sha256:bundledBaselineDigest,source:"bundled",tag:null,version:version2},tools:toolCatalog};var resolveVerifiedBundledBaseline=(requested=bundledBaseline.summary.requested,retrieval="available")=>{const aliases=resolveBundledSkillAliases(skillsRoot);const actualDigest=digestContentRoots([{include:(relativePath)=>!relativePath.endsWith(".ts"),prefix:"data",root:dataRoot},{logicalPath:(relativePath)=>aliases.get(relativePath)??relativePath,prefix:"skills",root:skillsRoot}]);if(actualDigest!==bundledBaselineDigest){throw new BaselineIntegrityFailure({actualDigest,expectedDigest:bundledBaselineDigest,message:"Packaged baseline content no longer matches its verified identity.",request:requested,resolvedVersion:bundledBaseline.summary.resolvedVersion})}return{...bundledBaseline,summary:{...bundledBaseline.summary,channel:requested.channel,requested,retrieval}}};var packContents=packCatalog;var packContentsForBaseline=(baseline=bundledBaseline)=>baseline.packs;var packContentsByIdForBaseline=(baseline=bundledBaseline)=>{const contents={};for(const pack of packContentsForBaseline(baseline)){contents[pack.id]=pack}return contents};var packContentsById=packContentsByIdForBaseline();var defaultPackIds=packContents.filter((pack)=>pack.category==="default").map((pack)=>pack.id).toSorted();var languagePackIds=packContents.filter((pack)=>pack.category==="language").map((pack)=>pack.id).toSorted();var detectedPackIds=packContents.filter((pack)=>pack.category==="detected").map((pack)=>pack.id).toSorted();var surfacePackIds=packContents.filter((pack)=>pack.category==="surface").map((pack)=>pack.id).toSorted();var knownPackIds=packContents.map((pack)=>pack.id).toSorted();var defaultPackIdsForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).filter((pack)=>pack.category==="default").map((pack)=>pack.id).toSorted();var languagePackIdsForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).filter((pack)=>pack.category==="language").map((pack)=>pack.id).toSorted();var detectedPackIdsForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).filter((pack)=>pack.category==="detected").map((pack)=>pack.id).toSorted();var surfacePackIdsForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).filter((pack)=>pack.category==="surface").map((pack)=>pack.id).toSorted();var knownPackIdsForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).map((pack)=>pack.id).toSorted();var skillsForPack=(packId,baseline=bundledBaseline)=>packContentsByIdForBaseline(baseline)[packId]?.skills??[];var lintAssetsForPack=(packId,baseline=bundledBaseline)=>packContentsByIdForBaseline(baseline)[packId]?.lintAssets??[];var hooksForPack=(packId,baseline=bundledBaseline)=>packContentsByIdForBaseline(baseline)[packId]?.hooks??[];var promptDetailsForPack=(packId,baseline=bundledBaseline)=>packContentsByIdForBaseline(baseline)[packId]?.promptDetails??[];var exampleRepositoriesForPack=(packId,baseline=bundledBaseline)=>packContentsByIdForBaseline(baseline)[packId]?.exampleRepositories??[];var formatToolBootstrapStatus=(entry)=>{switch(entry.status){case"already-present":{return"already present"}case"installed":{return"installed during scaffold"}case"failed":{return"bootstrap failed"}default:{return entry.status}}};var formatToolBootstrapFailureDetails=(statuses)=>{const failures=statuses.filter((entry)=>entry.status==="failed");if(failures.length===0){return null}return["Required tool bootstrap failed, but scaffold/update output can still be written.","","Agent recovery prompt:","Read `.devpunks/settings.json`, verify each listed required tool manually, then fix the failed install before deeper repo work. If `agent-browser` failed while installing Chromium, install or repair that browser dependency outside the scaffold command, then rerun `agent-browser install` or the documented tool check.","","Failure stack traces:",...failures.flatMap((failure)=>["",`--- ${failure.toolId} ---`,failure.errorStack??failure.errorMessage??"Unknown tool bootstrap failure."])].join(`
|
|
325
|
+
`}else if(field==="event"){eventName=value5}else if(field==="id"&&!value5.includes("\x00")){eventId=value5;lastEventId=value5}else if(field==="retry"){const retry5=parseInt(value5,10);if(!Number.isNaN(retry5)){onParse(new Retry({duration:millis(retry5),lastEventId}))}}}}var BOM=[239,187,191];function hasBom(buffer2){return BOM.every((charCode,index2)=>buffer2.charCodeAt(index2)===charCode)}var EventEncoded=Struct({id:optional(String5),event:String5,data:String5});var RetryTypeId="~effect/encoding/Sse/Retry";class Retry extends TaggedClass("Retry"){[RetryTypeId]=RetryTypeId;static is(u){return hasProperty(u,RetryTypeId)}static filter(u){return Retry.is(u)?succeed2(u):fail2(u)}}var SecurityTypeId="~effect/httpapi/HttpApiMiddleware/Security";var isSecurity=(u)=>hasProperty(u,SecurityTypeId);var exports_OpenApi={};__export(exports_OpenApi,{fromApi:()=>fromApi,annotations:()=>annotations,Version:()=>Version2,Transform:()=>Transform,Title:()=>Title,Summary:()=>Summary,Servers:()=>Servers,Override:()=>Override,License:()=>License,Identifier:()=>Identifier,Format:()=>Format,ExternalDocs:()=>ExternalDocs,Exclude:()=>Exclude,Description:()=>Description,Deprecated:()=>Deprecated});class Identifier extends Service()("effect/httpapi/OpenApi/Identifier"){}class Title extends Service()("effect/httpapi/OpenApi/Title"){}class Version2 extends Service()("effect/httpapi/OpenApi/Version"){}class Description extends Service()("effect/httpapi/OpenApi/Description"){}class License extends Service()("effect/httpapi/OpenApi/License"){}class ExternalDocs extends Service()("effect/httpapi/OpenApi/ExternalDocs"){}class Servers extends Service()("effect/httpapi/OpenApi/Servers"){}class Format extends Service()("effect/httpapi/OpenApi/Format"){}class Summary extends Service()("effect/httpapi/OpenApi/Summary"){}class Deprecated extends Service()("effect/httpapi/OpenApi/Deprecated"){}class Override extends Service()("effect/httpapi/OpenApi/Override"){}var Exclude=Reference("effect/httpapi/OpenApi/Exclude",{defaultValue:constFalse});class Transform extends Service()("effect/httpapi/OpenApi/Transform"){}var servicesPartial=(tags2)=>{const entries3=Object.entries(tags2);return(options4)=>{let context4=empty();for(const[key,tag4]of entries3){if(options4[key]!==undefined){context4=add(context4,tag4,options4[key])}}return context4}};var annotations=servicesPartial({identifier:Identifier,title:Title,version:Version2,description:Description,license:License,summary:Summary,deprecated:Deprecated,externalDocs:ExternalDocs,servers:Servers,format:Format,override:Override,exclude:Exclude,transform:Transform});var apiCache=new WeakMap;function processAnnotation(ctx,annotation,f){const o=getOption(ctx,annotation);if(isSome2(o)){f(o.value)}}function fromApi(api){const cached3=apiCache.get(api);if(cached3!==undefined){return cached3}let spec={openapi:"3.1.0",info:{title:"Api",version:"0.0.1"},paths:{},components:{schemas:{},securitySchemes:{}},security:[],tags:[]};const pathOps=[];const pathOperations=new Set;const operationIds=new Set;processAnnotation(api.annotations,Title,(title)=>{spec.info.title=title});processAnnotation(api.annotations,Version2,(version2)=>{spec.info.version=version2});processAnnotation(api.annotations,Description,(description)=>{spec.info.description=description});processAnnotation(api.annotations,License,(license)=>{spec.info.license=license});processAnnotation(api.annotations,Summary,(summary)=>{spec.info.summary=summary});processAnnotation(api.annotations,Servers,(servers)=>{spec.servers=[...servers]});reflect(api,{onGroup({group}){if(get(group.annotations,Exclude)){return}let tag4={name:getOrElse2(group.annotations,Title,()=>group.identifier)};processAnnotation(group.annotations,Description,(description)=>{tag4.description=description});processAnnotation(group.annotations,ExternalDocs,(externalDocs)=>{tag4.externalDocs=externalDocs});processAnnotation(group.annotations,Override,(override)=>{Object.assign(tag4,override)});processAnnotation(group.annotations,Transform,(transformFn)=>{tag4=transformFn(tag4)});spec.tags.push(tag4)},onEndpoint({endpoint,group,mergedAnnotations,middleware:middleware2}){if(get(mergedAnnotations,Exclude)){return}let op={tags:[getOrElse2(group.annotations,Title,()=>group.identifier)],operationId:getOrElse2(endpoint.annotations,Identifier,()=>group.topLevel?endpoint.identifier:`${group.identifier}.${endpoint.identifier}`),parameters:[],security:[],responses:{}};const path4=endpoint.path.replace(/:(\w+)\??/g,"{$1}");const method=endpoint.method.toLowerCase();function processResponseBodies(bodies,defaultDescription){for(const[status2,{content,descriptions,streamContent}]of bodies){const description=descriptions.size>0?Array.from(descriptions).join(" | "):defaultDescription();op.responses[status2]={description};if(content!==undefined){content.forEach((map18,encoding)=>{map18.forEach((schemas,contentType)=>{const asts=Array.from(schemas,getAST);const ast=asts.length===1?asts[0]:new Union(asts,"anyOf");pathOps.push({_tag:"schema",ast:toEncodingAST(ast,encoding),path:["paths",path4,method,"responses",String(status2),"content",contentType,"schema"]});op.responses[status2].content??={};op.responses[status2].content[contentType]={schema:{}}})})}if(streamContent!==undefined){streamContent.forEach((stream3,contentType)=>{op.responses[status2].content??={};if(isStreamSse(stream3)){pathOps.push({_tag:"schema",ast:getAST(stream3.events),path:["paths",path4,method,"responses",String(status2),"content",contentType,"schema"]});pathOps.push({_tag:"schema",ast:getAST(toCodecJson(Cause(stream3.error,Defect()))),path:["paths",path4,method,"responses",String(status2),"content",contentType,"x-effect-stream","causeSchema"]});pathOps.push({_tag:"schema",ast:getAST(stream3.error),path:["paths",path4,method,"responses",String(status2),"content",contentType,"x-effect-stream","errorSchema"]});op.responses[status2].content[contentType]={schema:{},"x-effect-stream":{encoding:"sse",causeSchema:{},errorSchema:{},failureEvent:reservedStreamFailureEvent2}}}else{op.responses[status2].content[contentType]={schema:{type:"string",format:"binary"},"x-effect-stream":{encoding:"uint8array"}}}})}}}function processParameters(schema2,i){if(schema2){const ast=getLastEncoding(schema2.ast);if(isObjects(ast)){for(const ps of ast.propertySignatures){op.parameters.push({name:String(ps.name),in:i,schema:{},required:i==="path"||!isOptional(ps.type)});pathOps.push({_tag:"parameter",ast:ps.type,path:["paths",path4,method,"parameters",String(op.parameters.length-1),"schema"]})}}}}processAnnotation(endpoint.annotations,Description,(description)=>{op.description=description});processAnnotation(endpoint.annotations,Summary,(summary)=>{op.summary=summary});processAnnotation(endpoint.annotations,Deprecated,(deprecated)=>{op.deprecated=deprecated});processAnnotation(endpoint.annotations,ExternalDocs,(externalDocs)=>{op.externalDocs=externalDocs});middleware2.forEach((middleware3)=>{if(!isSecurity(middleware3)){return}for(const[name,security]of Object.entries(middleware3.security)){processHttpApiSecurity(name,security);op.security.push({[name]:[]})}});function processHttpApiSecurity(name,security){const scheme=makeSecurityScheme(security);if(!Object.hasOwn(spec.components.securitySchemes,name)){set(spec.components.securitySchemes,name,scheme);return}if(!equals(securitySchemeForComparison(spec.components.securitySchemes[name]),securitySchemeForComparison(scheme))){throw new globalThis.Error(`Conflicting OpenAPI security scheme: ${name}`)}}const hasBody2=hasBody(endpoint.method);if(hasBody2){const schemasByContentType=new Map;for(const schema2 of getPayloadSchemas(endpoint)){if(isNoContent(schema2.ast))continue;const encoding=getPayloadEncoding(schema2.ast,endpoint.method);const existing=schemasByContentType.get(encoding.contentType);if(existing===undefined){schemasByContentType.set(encoding.contentType,{encoding,schemas:[schema2]})}else{existing.schemas.push(schema2)}}if(schemasByContentType.size>0){const content={};for(const[contentType,{encoding,schemas}]of schemasByContentType){const asts=schemas.map(getAST);const ast=asts.length===1?asts[0]:new Union(asts,"anyOf");pathOps.push({_tag:"schema",ast:toEncodingAST(ast,encoding._tag),path:["paths",path4,method,"requestBody","content",contentType,"schema"]});content[contentType]={schema:{}}}op.requestBody={content,required:true}}}processParameters(endpoint.params,"path");if(!hasBody2&&endpoint.payload.size===1){const entry=endpoint.payload.values().next().value;processParameters(entry.schemas[0],"query")}processParameters(endpoint.headers,"header");processParameters(endpoint.query,"query");processResponseBodies(extractSuccessResponseBodies(endpoint),()=>"Success");processResponseBodies(extractResponseBodies(getErrorSchemas(endpoint),getStatusError,resolveDescriptionOrIdentifier),()=>"Error");processAnnotation(endpoint.annotations,Override,(override)=>{Object.assign(op,override)});processAnnotation(endpoint.annotations,Transform,(transformFn)=>{op=transformFn(op)});const pathOperation=`${method} ${path4.replace(/\{[^}]+\}/g,"{}")}`;if(pathOperations.has(pathOperation)){throw new globalThis.Error(`Duplicate OpenAPI operation for ${endpoint.method} ${path4}`)}const operationId=op.operationId;if(operationId!==undefined){if(operationIds.has(operationId)){throw new globalThis.Error(`Duplicate OpenAPI operationId: ${operationId}`)}operationIds.add(operationId)}pathOperations.add(pathOperation);if(!spec.paths[path4]){spec.paths[path4]={}}spec.paths[path4][method]=op}});processAnnotation(api.annotations,AdditionalSchemas,(componentSchemas)=>{componentSchemas.forEach((componentSchema)=>{const identifier2=resolveIdentifier2(componentSchema.ast);if(identifier2!==undefined){if(identifier2 in spec.components.schemas){throw new globalThis.Error(`Duplicate component schema identifier: ${identifier2}`)}spec.components.schemas[identifier2]={};pathOps.push({_tag:"schema",ast:componentSchema.ast,path:["components","schemas",identifier2]})}})});function escapePath(path4){return"/"+path4.map(escapeToken).join("/")}if(isArrayNonEmpty2(pathOps)){const multiDocument=fromASTs2(map4(pathOps,(op)=>op.ast));const jsonSchemaMultiDocument=toMultiDocumentOpenApi3_1(toJsonSchemaMultiDocument2(multiDocument));const patchOps=pathOps.map((op,i)=>{const oppath=escapePath(op.path);const value5=jsonSchemaMultiDocument.schemas[i];return{op:"replace",path:oppath,value:value5}});Object.entries(jsonSchemaMultiDocument.definitions).forEach(([name,definition])=>{patchOps.push({op:"add",path:escapePath(["components","schemas",name]),value:definition})});spec=apply(patchOps,spec)}Object.keys(spec.components.schemas).forEach((key)=>{if(!VALID_OPEN_API_COMPONENTS_SCHEMAS_KEY_REGEXP.test(key)){throw new globalThis.Error(`Invalid component schema key: ${key}`)}});processAnnotation(api.annotations,Override,(override)=>{Object.assign(spec,override)});processAnnotation(api.annotations,Transform,(transformFn)=>{spec=transformFn(spec)});apiCache.set(api,spec);return spec}var reservedStreamFailureEvent2="effect/httpapi/stream/failure";function extractSuccessResponseBodies(endpoint){return extractResponseBodies(getSuccessSchemas(endpoint),getStatusSuccess,resolveDescriptionOrIdentifier)}function extractResponseBodies(schemas,getStatus,getDescription){const map18=new Map;schemas.forEach(process2);return map18;function process2(schema2){if(isStreamSchema(schema2)){addStreamContent(schema2);return}const ast=schema2.ast;const status2=getStatus(ast);if(isNoContent(ast)){addNoContent(status2,getDescription(schema2.ast)??"<No Content>")}else{addContent(schema2,status2,getResponseEncoding(ast))}}function addNoContent(status2,description){const statusMap=map18.get(status2);if(statusMap===undefined){map18.set(status2,{descriptions:new Set([description]),content:undefined,streamContent:undefined})}else{if(description!==undefined){statusMap.descriptions.add(description)}}}function addContent(schema2,status2,encoding){const description=getDescription(schema2.ast);const statusMap=map18.get(status2);const{_tag,contentType}=encoding;if(statusMap===undefined){map18.set(status2,{descriptions:new Set(description!==undefined?[description]:[]),content:new Map([[_tag,new Map([[contentType,new Set([schema2])]])]]),streamContent:undefined})}else{if(description!==undefined){statusMap.descriptions.add(description)}if(statusMap.content===undefined){statusMap.content=new Map([[_tag,new Map([[contentType,new Set([schema2])]])]])}else{const schemasByContentType=statusMap.content.get(_tag);if(schemasByContentType===undefined){statusMap.content.set(_tag,new Map([[contentType,new Set([schema2])]]))}else{const set7=schemasByContentType.get(contentType);if(set7===undefined){schemasByContentType.set(contentType,new Set([schema2]))}else{set7.add(schema2)}}}}}function addStreamContent(stream3){const status2=getStatusStream(stream3);const statusMap=map18.get(status2);if(statusMap===undefined){map18.set(status2,{descriptions:new Set,content:undefined,streamContent:new Map([[stream3.contentType,stream3]])})}else if(statusMap.streamContent===undefined){statusMap.streamContent=new Map([[stream3.contentType,stream3]])}else{statusMap.streamContent.set(stream3.contentType,stream3)}}}function resolveDescriptionOrIdentifier(ast){return resolveDescription2(ast)??resolveIdentifier2(ast)}var Uint8ArrayEncoding=String5.annotate({format:"binary"});function toEncodingAST(ast,_tag){switch(_tag){case"Uint8Array":return Uint8ArrayEncoding.ast;case"Text":return String5.ast;case"FormUrlEncoded":case"Json":return ast;case"Multipart":return persistedFileToBinaryEncoding(ast)}}function persistedFileToBinaryEncoding(ast){if(isDeclaration(ast)&&ast.annotations?.typeConstructor?._tag==="effect/http/PersistedFile"){return Uint8ArrayEncoding.ast}if(typeof ast?.recur==="function"){return ast.recur(persistedFileToBinaryEncoding)}return ast}var makeSecurityScheme=(security)=>{const meta={};processAnnotation(security.annotations,Description,(description)=>{meta.description=description});switch(security._tag){case"Basic":{return{...meta,type:"http",scheme:"basic"}}case"Http":{const format5=getOption(security.annotations,Format).pipe(map((format6)=>({bearerFormat:format6})),getOrUndefined);return{...meta,type:"http",scheme:security.scheme,...format5}}case"ApiKey":{return{...meta,type:"apiKey",name:security.key,in:security.in}}}};var securitySchemeForComparison=(scheme)=>{if(scheme.type==="http"){return{...scheme,scheme:scheme.scheme.toLowerCase()}}if(scheme.in==="header"){return{...scheme,name:scheme.name.toLowerCase()}}return scheme};var exports_HttpApiClient={};__export(exports_HttpApiClient,{urlBuilder:()=>urlBuilder,makeWith:()=>makeWith3,makeClient:()=>makeClient,make:()=>make46,group:()=>group,endpoint:()=>endpoint});var makeClient=(api,options4)=>gen2(function*(){const services=yield*context2();const httpClient=options4.httpClient.pipe(options4?.baseUrl===undefined?identity:mapRequest(prependUrl(options4.baseUrl.toString())));function executeMiddleware(group,endpoint,request3,middlewareKeys,index2){if(index2===-1){return httpClient.execute(request3)}const middleware2=services.mapUnsafe.get(middlewareKeys[index2]);if(middleware2===undefined){return executeMiddleware(group,endpoint,request3,middlewareKeys,index2-1)}return middleware2({endpoint,group,request:request3,next(request4){return executeMiddleware(group,endpoint,request4,middlewareKeys,index2-1)}})}reflect(api,{predicate:options4?.predicate,onGroup(onGroupOptions){options4.onGroup?.(onGroupOptions)},onEndpoint(onEndpointOptions){const{group,endpoint,errors:errors2,successes}=onEndpointOptions;const makeUrl=compilePath(endpoint.path);const decodeMap={orElse:statusOrElse};const decodeResponse=matchStatus(decodeMap);const errorAlternatives=new Map;for(const[status2,schemas]of errors2.entries()){const grouped=groupSchemasByContentType(schemas);for(const[contentType,schemas2]of grouped.entries()){addResponseAlternative(errorAlternatives,status2,contentType,schemasToResponse(schemas2))}}for(const[status2,alternatives]of errorAlternatives.entries()){const decode4=makeResponseDecoder(alternatives);decodeMap[status2]=(response)=>flatMap4(catchCause2(decode4(response),(cause)=>failCause3(combine2(fail5(new HttpClientError({reason:new StatusCodeError({request:response.request,response})})),cause))),fail6)}const successAlternatives=new Map;for(const[status2,schemas]of successes.entries()){const grouped=groupSchemasByContentType(schemas);for(const[contentType,schemas2]of grouped.entries()){addResponseAlternative(successAlternatives,status2,contentType,schemasToResponse(schemas2))}}for(const streamSuccess of getStreamSuccessSchemas(endpoint)){addResponseAlternative(successAlternatives,getStatusStream(streamSuccess),streamSuccess.contentType,streamToResponse(streamSuccess))}for(const[status2,alternatives]of successAlternatives.entries()){decodeMap[status2]=makeResponseDecoder(alternatives)}const encodeParams=map12(endpoint.params,encodeUnknownEffect2);const payloadSchemas=getPayloadSchemas(endpoint);const encodePayload=isArrayNonEmpty2(payloadSchemas)?hasBody(endpoint.method)?encodeUnknownEffect2(getEncodePayloadSchema(payloadSchemas,endpoint.method)):encodeUnknownEffect2(Union2(payloadSchemas)):undefined;const encodeHeaders=map12(endpoint.headers,encodeUnknownEffect2);const encodeQuery=map12(endpoint.query,encodeUnknownEffect2);const middlewareKeys=Array.from(onEndpointOptions.middleware,(tag4)=>`${tag4.key}/Client`);const endpointFn=fnUntraced2(function*(request3){let httpRequest=make42(endpoint.method)(endpoint.path);if(request3!==undefined){if(encodeParams!==undefined){const params=yield*encodeParams(request3.params);httpRequest=setUrl(httpRequest,makeUrl(params))}if(encodePayload!==undefined){if(hasBody(endpoint.method)){if(request3.payload instanceof FormData){httpRequest=bodyFormData(httpRequest,request3.payload)}else{const body=yield*encodePayload(request3.payload);httpRequest=setBody(httpRequest,body)}}else{const urlParams2=yield*encodePayload(request3.payload);httpRequest=appendUrlParams(httpRequest,urlParams2)}}if(encodeHeaders!==undefined){const headers=yield*encodeHeaders(request3.headers);httpRequest=setHeaders(httpRequest,headers)}if(encodeQuery!==undefined){const query=yield*encodeQuery(request3.query);httpRequest=appendUrlParams(httpRequest,query)}}const response=yield*executeMiddleware(group,endpoint,httpRequest,middlewareKeys,middlewareKeys.length-1);if(request3?.responseMode==="response-only"){return response}const value5=yield*options4.transformResponse===undefined?decodeResponse(response):options4.transformResponse(decodeResponse(response));return request3?.responseMode==="decoded-and-response"?[value5,response]:value5});options4.onEndpoint({...onEndpointOptions,endpointFn})}})});var make46=(api,options4)=>flatMap4(HttpClient,(httpClient)=>makeWith3(api,{...options4,httpClient:options4?.transformClient?options4.transformClient(httpClient):httpClient}));var makeWith3=(api,options4)=>{const client={};return makeClient(api,{...options4,onGroup({group}){if(group.topLevel)return;set(client,group.identifier,{})},onEndpoint({endpoint,endpointFn,group}){set(group.topLevel?client:client[group.identifier],endpoint.identifier,endpointFn)}}).pipe(as2(client))};var group=(api,options4)=>{const client={};return makeClient(api,{...options4,predicate:({group:group2})=>group2.identifier===options4.group,onEndpoint({endpoint,endpointFn}){set(client,endpoint.identifier,endpointFn)}}).pipe(map7(()=>client))};var endpoint=(api,options4)=>{let client=undefined;return makeClient(api,{...options4,httpClient:options4.transformClient?options4.transformClient(options4.httpClient):options4.httpClient,predicate:({endpoint:endpoint2,group:group2})=>group2.identifier===options4.group&&endpoint2.identifier===options4.endpoint,onEndpoint({endpointFn}){client=endpointFn}}).pipe(map7(()=>client))};var urlBuilder=(api,options4)=>{const builder={};reflect(api,{onGroup({group:group2}){if(group2.topLevel)return;set(builder,group2.identifier,{})},onEndpoint({group:group2,endpoint:endpoint2}){const makeUrl=compilePath(endpoint2.path);const encodeParams=endpoint2.params===undefined?undefined:encodeSync2(endpoint2.params);const encodeQuery=endpoint2.query===undefined?undefined:encodeSync2(endpoint2.query);const endpointBuilder=(request3)=>{const params=request3?.params;const path4=params===undefined?endpoint2.path:makeUrl(encodeParams===undefined?params:encodeParams(params));const queryInput=request3?.query===undefined?undefined:encodeQuery===undefined?request3.query:encodeQuery(request3.query);const query=queryInput===undefined?"":toString(fromInput3(queryInput));const url2=query===""?path4:`${path4}?${query}`;return options4?.baseUrl===undefined?url2:new URL(url2,options4.baseUrl.toString()).toString()};set(group2.topLevel?builder:builder[group2.identifier],endpoint2.identifier,endpointBuilder)}});return builder};var paramsRegExp=/(\/?):(\w+)(\?)?/g;var compilePath=(path4)=>{if(!paramsRegExp.test(path4)){return(_)=>path4}paramsRegExp.lastIndex=0;return(params)=>{paramsRegExp.lastIndex=0;return path4.replace(paramsRegExp,(_,slash,key,optional4)=>{const value5=params[key];if(value5===undefined){if(optional4!==undefined){return""}throw new Error(`Missing path parameter: ${key}`)}return`${slash}${encodeURIComponent(value5)}`})}};function schemasToResponse(schemas){const codec=toCodecArrayBuffer(schemas);const decode4=decodeEffect2(codec);return(response)=>flatMap4(response.arrayBuffer,decode4)}function addResponseAlternative(map18,status2,contentType,decode4){const normalizedContentType=normalize2(contentType);const alternatives=map18.get(status2);if(alternatives===undefined){map18.set(status2,[{contentType:normalizedContentType,decode:decode4}])}else{alternatives.push({contentType:normalizedContentType,decode:decode4})}}function makeResponseDecoder(alternatives){const first=alternatives[0];if(alternatives.length===1&&first!==undefined){return first.decode}return(response)=>{const contentType=normalize2(response.headers["content-type"]??"");const alternative=alternatives.find((alternative2)=>alternative2.contentType===contentType);return alternative===undefined?failUnsupportedContentType(response,contentType,alternatives):alternative.decode(response)}}function groupSchemasByContentType(schemas){const grouped=new Map;for(const schema2 of schemas){const contentType=isNoContent(schema2.ast)?"":normalize2(getResponseEncoding(schema2.ast).contentType);const existing=grouped.get(contentType);if(existing===undefined){grouped.set(contentType,[schema2])}else{existing.push(schema2)}}return grouped}function failUnsupportedContentType(response,contentType,alternatives){const expected=Array.from(new Set(alternatives.map((alternative)=>alternative.contentType))).join(", ");return fail6(new HttpClientError({reason:new DecodeError({request:response.request,response,description:`Unsupported response content-type for status ${response.status}: ${contentType||"<missing>"}. Expected one of: ${expected}`})}))}var reservedStreamFailureEvent3="effect/httpapi/stream/failure";function getStreamSuccessSchemas(endpoint2){const schemas=[];for(const schema2 of endpoint2.success){if(isStreamSchema(schema2)){schemas.push(schema2)}}return schemas}function streamToResponse(streamSchema2){const sse=isStreamUint8Array(streamSchema2)?undefined:{declaration:streamSchema2,decoder:makeSseDecoder(streamSchema2)};return(response)=>map7(context2(),(context4)=>provideContext4(sse===undefined?response.stream:decodeSseStream(response.stream,sse.declaration,sse.decoder),context4))}function makeSseDecoder(declaration){const Event=Union2([Struct({event:Literal2(reservedStreamFailureEvent3),data:fromJsonString2(toCodecJson(Cause(declaration.error,Defect())))}),declaration.events]);return decodeSchema(Event)}function decodeSseStream(stream3,declaration,decoder2){const events=transformPull2(stream3.pipe(decodeText,pipeThroughChannel(decoder2)),(pull)=>sync2(()=>{let pendingFailureCause=undefined;return suspend2(()=>{if(pendingFailureCause!==undefined){return failCause3(pendingFailureCause)}return flatMap4(pull,(events2)=>{for(let i=0;i<events2.length;i++){const event=events2[i];if(event.event===reservedStreamFailureEvent3&&isCause2(event.data)){if(i===0){return failCause3(event.data)}pendingFailureCause=event.data;events2=events2.slice(0,i);break}}return succeed6(events2)})})}));if(declaration.sseMode==="data"){return map9(events,(event)=>event.data)}return events}var ArrayBuffer2=instanceOf(globalThis.ArrayBuffer,{expected:"ArrayBuffer"});var Uint8ArrayFromArrayBuffer=ArrayBuffer2.pipe(decodeTo2(Uint8Array2,transform2({decode(fromA){return new Uint8Array(fromA)},encode(arr){return arr.byteLength===arr.buffer.byteLength?arr.buffer:arr.buffer.slice(arr.byteOffset,arr.byteOffset+arr.byteLength)}})));var StringFromArrayBuffer=ArrayBuffer2.pipe(decodeTo2(String5,transform2({decode(fromA){return new TextDecoder().decode(fromA)},encode(toI){const arr=new TextEncoder().encode(toI);return arr.byteLength===arr.buffer.byteLength?arr.buffer:arr.buffer.slice(arr.byteOffset,arr.byteOffset+arr.byteLength)}})));var UnknownFromArrayBuffer=StringFromArrayBuffer.pipe(decodeTo2(Union2([Literal2("").pipe(decodeTo2(Undefined2,transform2({decode:()=>{return},encode:()=>""}))),UnknownFromJsonString])));function toCodecArrayBuffer(schemas){return Union2(schemas.map(onSchema));function onSchema(schema2){const encoding=getResponseEncoding(schema2.ast);switch(encoding._tag){case"Json":{const encodedIsNull=isNull(toEncoded(schema2.ast));return UnknownFromArrayBuffer.pipe(decodeTo2(schema2,encodedIsNull?transform2({decode:(a)=>a===undefined?null:a,encode:(a)=>a===null?undefined:a}):undefined))}case"FormUrlEncoded":return StringFromArrayBuffer.pipe(decodeTo2(schemaRecord),decodeTo2(schema2));case"Uint8Array":return Uint8ArrayFromArrayBuffer.pipe(decodeTo2(schema2));case"Text":return StringFromArrayBuffer.pipe(decodeTo2(schema2))}}}var statusOrElse=(response)=>fail6(new HttpClientError({reason:new DecodeError({request:response.request,response})}));var $HttpBody=declare(isHttpBody);function getEncodePayloadSchema(schemas,method){return Union2(schemas.map((s)=>getEncodePayloadSchemaFromBody(s,method)))}var bodyFromPayloadCache=new WeakMap;function getEncodePayloadSchemaFromBody(schema2,method){const ast=schema2.ast;const cached3=bodyFromPayloadCache.get(ast);if(cached3!==undefined){return cached3}const encoding=getPayloadEncoding(ast,method);const out=$HttpBody.pipe(decodeTo2(schema2,transformOrFail2({decode(httpBody){return fail6(new Forbidden(some2(httpBody),{message:"Encode only schema"}))},encode(t){switch(encoding._tag){case"Multipart":return fail6(new Forbidden(some2(t),{message:"Payload must be a FormData"}));case"Json":{try{const body=JSON.stringify(t);return succeed6(text2(body,encoding.contentType))}catch(error2){return fail6(new InvalidValue(some2(t),{message:globalThis.String(error2)}))}}case"Text":{if(typeof t!=="string"){return fail6(new InvalidValue(some2(t),{message:"Expected a string"}))}return succeed6(text2(t,encoding.contentType))}case"FormUrlEncoded":{if(!isObject(t)){return fail6(new InvalidValue(some2(t),{message:"Expected a record"}))}return succeed6(urlParams(fromInput3(t),encoding.contentType))}case"Uint8Array":{if(!(t instanceof Uint8Array)){return fail6(new InvalidValue(some2(t),{message:"Expected a Uint8Array"}))}return succeed6(uint8Array2(t,encoding.contentType))}}}})));bodyFromPayloadCache.set(ast,out);return out}var exports_HttpApiGroup={};__export(exports_HttpApiGroup,{make:()=>make47,isHttpApiGroup:()=>isHttpApiGroup});var TypeId56="~effect/httpapi/HttpApiGroup";var isHttpApiGroup=(u)=>hasProperty(u,TypeId56);var Proto19={[TypeId56]:TypeId56,add(...toAdd){const endpoints={...this.endpoints};for(const endpoint2 of toAdd){set(endpoints,endpoint2.identifier,endpoint2)}return makeProto4({...optionsFromGroup(this),endpoints})},prefix(prefix){return makeProto4({...optionsFromGroup(this),endpoints:map3(this.endpoints,(endpoint2)=>endpoint2.prefix(prefix))})},middleware(middleware2){return makeProto4({...optionsFromGroup(this),endpoints:map3(this.endpoints,(endpoint2)=>endpoint2.middleware(middleware2))})},annotateMerge(annotations2){return makeProto4({...optionsFromGroup(this),annotations:merge(this.annotations,annotations2)})},annotate(annotation,value5){return makeProto4({...optionsFromGroup(this),annotations:add(this.annotations,annotation,value5)})},annotateEndpointsMerge(annotations2){return makeProto4({...optionsFromGroup(this),endpoints:map3(this.endpoints,(endpoint2)=>endpoint2.annotateMerge(annotations2))})},annotateEndpoints(annotation,value5){return makeProto4({...optionsFromGroup(this),endpoints:map3(this.endpoints,(endpoint2)=>endpoint2.annotate(annotation,value5))})},pipe(){return pipeArguments(this,arguments)}};var optionsFromGroup=(group2)=>({identifier:group2.identifier,topLevel:group2.topLevel,endpoints:group2.endpoints,annotations:group2.annotations});var makeProto4=(options4)=>{function HttpApiGroup(){}Object.setPrototypeOf(HttpApiGroup,Proto19);HttpApiGroup.key=`effect/httpapi/HttpApiGroup/${options4.identifier}`;return Object.assign(HttpApiGroup,options4)};var make47=(identifier2,options4)=>makeProto4({identifier:identifier2,topLevel:options4?.topLevel??false,endpoints:{},annotations:empty()});var defaultMessage=(message)=>String5.pipe(optionalKey2,withConstructorDefault2(succeed6(message)));var BaselineChannel=Literals(["stable","bundled"]);var HarnessReportStatus=Literals(["new","triaged","accepted","wontfix","resolved"]);var OperatorIdentity=Struct({operatorId:String5,email:optionalKey2(String5),emailVerified:optionalKey2(Boolean4)}).annotate({identifier:"OperatorIdentity"});var isoDateTimePattern=/^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})T(?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2})(?:\.(?<fraction>\d{1,9}))?(?:Z|[+-]\d{2}:\d{2})$/u;var isValidIsoDateTime=(value5)=>{const groups=isoDateTimePattern.exec(value5)?.groups;if(groups===undefined){return false}const year=Number(groups.year);const month=Number(groups.month);const day=Number(groups.day);const hour=Number(groups.hour);const minute=Number(groups.minute);const second=Number(groups.second);const millisecond=Number((groups.fraction??"").slice(0,3).padEnd(3,"0"));const date7=new Date(Date.UTC(year,month-1,day,hour,minute,second,millisecond));return Number.isFinite(Date.parse(value5))&&date7.getUTCFullYear()===year&&date7.getUTCMonth()===month-1&&date7.getUTCDate()===day&&date7.getUTCHours()===hour&&date7.getUTCMinutes()===minute&&date7.getUTCSeconds()===second};var IsoDateTimeString=String5.pipe(refine((value5)=>isValidIsoDateTime(value5),{identifier:"IsoDateTimeString",description:"an ISO 8601 datetime string with timezone"}));var GitIdentity=Struct({name:optionalKey2(String5),email:optionalKey2(String5)}).annotate({identifier:"GitIdentity"});var ObservedRepositoryInput=Struct({remoteUrl:optionalKey2(String5),remoteHost:optionalKey2(String5),remotePath:optionalKey2(String5),branch:optionalKey2(String5),commitSha:optionalKey2(String5),dirty:optionalKey2(Boolean4),gitIdentity:optionalKey2(GitIdentity)}).annotate({identifier:"ObservedRepositoryInput"});var SymbolPropertyKey=Struct({_tag:Literal2("symbol"),key:String5}).annotate({description:"an object to be decoded into a globally shared symbol"});var PropertyKey2=Union2([String5,Finite,SymbolPropertyKey]).annotate({identifier:"PropertyKey"});var DecodeIssue=Struct({_tag:Literals(["Pointer","Unexpected","Missing","Composite","Refinement","Transformation","Type","Forbidden"]),path:ArraySchema(PropertyKey2),message:String5}).annotate({identifier:"Issue"});class HttpApiDecodeError extends TaggedErrorClass()("HttpApiDecodeError",{issues:ArraySchema(DecodeIssue),message:String5},{httpApiStatus:400,description:"The request did not match the expected schema"}){}class Forbidden2 extends TaggedErrorClass()("@punks/contract/errors/Forbidden",{message:defaultMessage("The supplied credentials cannot access this resource.")},{httpApiStatus:403,title:"Forbidden"}){}var defaultMessage2=(message)=>String5.pipe(optionalKey2,withConstructorDefault2(succeed6(message)));var ArtifactKind=Literals(["manifest","archive"]);var BaselineVersion=NonEmptyString.annotate({identifier:"BaselineVersion"});var NonBlankString=String5.check(isTrimmed(),isNonEmpty());var BaselineRevision=String5.check(isPattern2(/^[1-9][0-9]*$/u)).annotate({identifier:"BaselineRevision"});var BaselineSha256=String5.check(isPattern2(/^[0-9a-f]{64}$/u)).annotate({identifier:"BaselineSha256"});var BaselinePromotionArtifact=Struct({url:NonBlankString,sha256:BaselineSha256}).annotate({identifier:"BaselinePromotionArtifact"});var BaselinePromotionCandidate=Struct({releaseId:NonBlankString,version:BaselineVersion,tag:NonBlankString,publishedAt:IsoDateTimeString,commitSha:NonBlankString,provenance:NonBlankString,cliVersionRange:NonBlankString,manifest:BaselinePromotionArtifact,archive:BaselinePromotionArtifact}).annotate({identifier:"BaselinePromotionCandidate"});var BaselinePublishRequest=Struct({mode:Literal2("publish"),candidate:BaselinePromotionCandidate,publicationIdentity:NonBlankString,expectedRevision:optionalKey2(BaselineRevision),reason:optionalKey2(Never2)});var BaselineRollbackRequest=Struct({mode:Literal2("rollback"),candidate:BaselinePromotionCandidate,publicationIdentity:NonBlankString,expectedRevision:BaselineRevision,reason:NonBlankString});var BaselinePromotionRequest=Union2([BaselinePublishRequest,BaselineRollbackRequest]).annotate({identifier:"BaselinePromotionRequest"});var BaselinePromotionResult=Struct({outcome:Literals(["committed","already-committed"]),revision:BaselineRevision,mode:Literals(["publish","rollback"]),candidate:BaselinePromotionCandidate,publicationIdentity:NonBlankString,previousRevision:optionalKey2(BaselineRevision),previousReleaseId:optionalKey2(NonBlankString),committedAt:IsoDateTimeString}).annotate({identifier:"BaselinePromotionResult"});var BaselineRequest=Struct({channel:BaselineChannel,version:optionalKey2(BaselineVersion)}).annotate({identifier:"BaselineRequest"});var BaselineVersionRequest=Struct({version:optionalKey2(BaselineVersion)}).annotate({identifier:"BaselineVersionRequest"});var BaselineSource=Literals(["control-plane","published-release","cache","bundled"]);var BaselineCompatibility=Struct({cliVersionRange:String5}).annotate({identifier:"BaselineCompatibility"});var BaselineRetrievalStatus=Literals(["available","retrieved","cached","fallback"]);var ArtifactMetadata=Struct({kind:ArtifactKind,fileName:String5,contentType:String5,url:String5,sha256:String5,sizeBytes:optionalKey2(Finite)}).annotate({identifier:"ArtifactMetadata"});var BaselineIdentity={requested:BaselineRequest,resolvedVersion:BaselineVersion,digest:String5,source:BaselineSource,provenance:String5,compatibility:BaselineCompatibility,retrieval:BaselineRetrievalStatus};var BaselineResolution=Struct({...BaselineIdentity,manifest:ArtifactMetadata,archive:ArtifactMetadata}).pipe(check2(makeFilter2(({requested,resolvedVersion})=>requested.version===undefined||requested.version===resolvedVersion,{message:"An exact baseline request must resolve to the requested version."})),check2(makeFilter2(({digest:digest2,archive})=>digest2===archive.sha256,{message:"The baseline digest must match the archive digest."}))).annotate({identifier:"BaselineResolution"});var BaselineArtifact=Struct({...BaselineIdentity,artifact:ArtifactMetadata}).pipe(check2(makeFilter2(({requested,resolvedVersion})=>requested.version===undefined||requested.version===resolvedVersion,{message:"Artifact metadata must match the exact requested baseline version."})),check2(makeFilter2(({artifact,digest:digest2})=>artifact.kind!=="archive"||artifact.sha256===digest2,{message:"The baseline artifact digest must match the verified baseline digest."}))).annotate({identifier:"BaselineArtifact"});class BaselineNotFound extends TaggedErrorClass()("@punks/contract/errors/BaselineNotFound",{channel:String5,message:defaultMessage2("No baseline exists for the requested channel.")},{httpApiStatus:404,title:"Baseline Not Found"}){}class ControlPlaneUnavailable extends TaggedErrorClass()("@punks/contract/errors/ControlPlaneUnavailable",{message:defaultMessage2("The control plane cannot resolve this resource yet.")},{httpApiStatus:503,title:"Control Plane Unavailable"}){}class BaselineAuthorityFailure extends TaggedErrorClass()("@punks/contract/errors/BaselineAuthorityFailure",{request:BaselineRequest,resolvedVersion:optionalKey2(BaselineVersion),message:String5},{httpApiStatus:409,title:"Baseline Authority Failure"}){}class BaselineIntegrityFailure extends TaggedErrorClass()("@punks/contract/errors/BaselineIntegrityFailure",{request:BaselineRequest,resolvedVersion:optionalKey2(BaselineVersion),expectedDigest:optionalKey2(String5),actualDigest:optionalKey2(String5),message:defaultMessage2("Baseline identity or artifact integrity verification failed.")},{httpApiStatus:422,title:"Baseline Integrity Failure"}){}var BaselineAvailability=Literals(["authority-unconfigured","network","unavailable-status"]);class BaselineUnavailable extends TaggedErrorClass()("@punks/contract/errors/BaselineUnavailable",{availability:BaselineAvailability,request:BaselineRequest,message:defaultMessage2("The requested baseline is unavailable.")},{httpApiStatus:503,title:"Baseline Unavailable"}){}class BaselinePublisherUnauthorized extends TaggedErrorClass()("@punks/contract/errors/BaselinePublisherUnauthorized",{message:defaultMessage2("Baseline publisher authentication is required.")},{httpApiStatus:401,title:"Baseline Publisher Unauthorized"}){}class BaselinePromotionConflict extends TaggedErrorClass()("@punks/contract/errors/BaselinePromotionConflict",{publicationIdentity:NonBlankString,expectedRevision:optionalKey2(BaselineRevision),actualRevision:optionalKey2(BaselineRevision),message:String5},{httpApiStatus:409,title:"Baseline Promotion Conflict"}){}class BaselinePromotionIntegrityFailure extends TaggedErrorClass()("@punks/contract/errors/BaselinePromotionIntegrityFailure",{publicationIdentity:NonBlankString,releaseId:optionalKey2(NonBlankString),expectedDigest:optionalKey2(BaselineSha256),actualDigest:optionalKey2(BaselineSha256),message:defaultMessage2("Baseline promotion evidence failed integrity verification.")},{httpApiStatus:422,title:"Baseline Promotion Integrity Failure"}){}class BaselinePromotionUnavailable extends TaggedErrorClass()("@punks/contract/errors/BaselinePromotionUnavailable",{publicationIdentity:NonBlankString,outcome:Literals(["not-committed","indeterminate"]),message:defaultMessage2("Baseline promotion is unavailable.")},{httpApiStatus:503,title:"Baseline Promotion Unavailable"}){}var errors2=[HttpApiDecodeError,Forbidden2,BaselineNotFound,BaselineAuthorityFailure,BaselineIntegrityFailure,BaselineUnavailable];var promotionErrors=[HttpApiDecodeError,Forbidden2,BaselinePublisherUnauthorized,BaselinePromotionConflict,BaselinePromotionIntegrityFailure,BaselinePromotionUnavailable];var BaselineApi=exports_HttpApiGroup.make("baseline").add(exports_HttpApiEndpoint.get("resolve","/:channel",{params:{channel:BaselineChannel},query:BaselineVersionRequest,success:BaselineResolution,error:errors2}),exports_HttpApiEndpoint.get("artifact","/:channel/artifacts/:kind",{params:{channel:BaselineChannel,kind:ArtifactKind},query:BaselineVersionRequest,success:BaselineArtifact,error:errors2}),exports_HttpApiEndpoint.post("promote","/stable/promotions",{payload:BaselinePromotionRequest,success:BaselinePromotionResult,error:promotionErrors})).prefix("/baselines").annotateMerge(exports_OpenApi.annotations({title:"Baseline control plane"}));import{createHash as createHash2}from"node:crypto";import{lstatSync,readFileSync,readdirSync,readlinkSync}from"node:fs";import path4 from"node:path";var digestContentRoots=(roots)=>{const entries3=[];for(const{root,prefix,include=()=>true,logicalPath=(value5)=>value5}of roots){const visit2=(directory3)=>{for(const entry of readdirSync(directory3,{withFileTypes:true})){const absolutePath=path4.join(directory3,entry.name);if(entry.isDirectory()){visit2(absolutePath);continue}const relativePath=path4.relative(root,absolutePath).split(path4.sep).join("/");if(include(relativePath)){entries3.push({absolutePath,identity:`${prefix}/${logicalPath(relativePath)}`})}}};visit2(root)}const hash3=createHash2("sha256");for(const{absolutePath,identity:identity3}of entries3.toSorted((left,right)=>left.identity.localeCompare(right.identity))){const stat3=lstatSync(absolutePath);hash3.update(identity3);hash3.update("\x00");if(stat3.isSymbolicLink()){hash3.update("symlink\x00");hash3.update(readlinkSync(absolutePath))}else{hash3.update("file\x00");hash3.update(readFileSync(absolutePath))}hash3.update("\x00")}return hash3.digest("hex")};import{existsSync,mkdirSync,readFileSync as readFileSync2,statSync,writeFileSync}from"node:fs";import{tmpdir as tmpdir2}from"node:os";import path5 from"node:path";var embeddedAssets=[];var name="@punks/cli";var version2="3.1.1-beta.0";var findFirst6=(candidates)=>candidates.find((candidate)=>existsSync(candidate));var executableSignature=()=>{try{return String(Math.trunc(statSync(process.execPath).mtimeMs))}catch{return"unknown"}};var extractEmbeddedAssets=()=>{if(embeddedAssets.length===0){return}const root=path5.join(tmpdir2(),"punks-cli-assets",`${version2}-${executableSignature()}`);for(const asset of embeddedAssets){const targetPath=path5.join(root,asset.relativePath);if(existsSync(targetPath)){continue}mkdirSync(path5.dirname(targetPath),{recursive:true});writeFileSync(targetPath,readFileSync2(asset.path))}return root};var findBundledPackageRoot=()=>{let currentDirectory=path5.resolve(import.meta.dirname,"../..");while(true){if(existsSync(path5.join(currentDirectory,"package.json"))){return currentDirectory}const parentDirectory=path5.dirname(currentDirectory);if(parentDirectory===currentDirectory){break}currentDirectory=parentDirectory}return path5.resolve(import.meta.dirname,"../..")};var packageRoot=findBundledPackageRoot();var runtimeRoot=import.meta.dirname;var embeddedAssetsRoot=extractEmbeddedAssets();var executableRoots=[process.argv[1],process.execPath].filter((candidate)=>candidate!==undefined&&candidate.length>0).map((candidate)=>path5.dirname(path5.resolve(candidate)));var dataCandidates=[path5.join(runtimeRoot,"data"),...embeddedAssetsRoot===undefined?[]:[path5.join(embeddedAssetsRoot,"data")],...executableRoots.map((root)=>path5.join(root,"data")),path5.resolve(import.meta.dirname,"../data"),path5.join(packageRoot,"src/data"),path5.resolve(import.meta.dirname,"../../src/data")];var skillCandidates=[path5.join(runtimeRoot,"skills"),...embeddedAssetsRoot===undefined?[]:[path5.join(embeddedAssetsRoot,"skills")],...executableRoots.map((root)=>path5.join(root,"skills")),path5.join(packageRoot,"skills"),path5.resolve(import.meta.dirname,"../../skills"),path5.resolve(import.meta.dirname,"../skills")];var resolvedDataRoot=findFirst6(dataCandidates);var resolvedSkillsRoot=findFirst6(skillCandidates);if(resolvedDataRoot===undefined){throw new Error("Could not locate bundled data directory.")}if(resolvedSkillsRoot===undefined){throw new Error("Could not locate bundled skills directory.")}var dataRoot=resolvedDataRoot;var skillsRoot=resolvedSkillsRoot;var dataPath=(...segments)=>path5.join(dataRoot,...segments);var readDataFile=(...segments)=>readFileSync2(dataPath(...segments),"utf-8");var readBaselineDataFile=(baselineDataRoot,...segments)=>readFileSync2(path5.join(baselineDataRoot,...segments),"utf-8");var resolveBaselinePath=({baselineRoot,baselineSkillsRoot,relativePath})=>{const resolvedPath=relativePath.startsWith("skills/")?findFirst6([path5.join(baselineSkillsRoot,relativePath.slice("skills/".length)),path5.join(baselineRoot,relativePath)]):findFirst6([path5.join(baselineRoot,relativePath)]);if(resolvedPath!==undefined){return resolvedPath}throw new Error(`Could not locate baseline asset: ${relativePath}`)};var bundledBaselineDigest="09c98193f19bd32231fc47644f7ee0bb16aa8e9486d68bc6e9b1b56199cbe3be";var hookCatalog=[{description:"Shared session-start hook that reports whether managed Harness scaffold output is current.",harness:"shared",id:"scaffold-update-check",outputPath:".agents/hooks/scaffold-update-check.mjs",sourcePath:"hooks/scaffold-update-check.mjs"},{description:"Shared hook that auto-formats edited JS/TS/JSON files and lint-checks product files after tool use.",harness:"shared",id:"format-edited-file",outputPath:".agents/hooks/format-edited-file.mjs",sourcePath:"hooks/format-edited-file.mjs"}];var sharedReactPlacement={placementNotes:"Add as an override for detected React-rendered code. Keep backend packages outside this override unless they render React.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-react-workspace>/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected React workspaces"]};var webOnlyPlacement={placementNotes:"Place this in the Next.js app override. If the repo uses a different frontend app path, retarget the file globs to that workspace before composing the final Oxlint config.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-nextjs-workspace>/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected Next.js workspaces"]};var effectPlacement={placementNotes:"Apply this only where Effect code lives. If the target repo renames or splits backend workspaces, move the override with those code paths instead of broadening it repo-wide.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-effect-workspace>/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected Effect workspaces"]};var vitestPlacement={placementNotes:"Attach this to test-only globs. Expand or narrow the file patterns to match the repo's actual Vitest test layout instead of treating it as a global default.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-test-workspace>/**/*.{test,spec}.{js,jsx,ts,tsx}","<detected-test-workspace>/src/test/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected JavaScript/TypeScript test workspaces"]};var lintCatalog=[{description:"Ultracite React preset for rendered app and shared UI code.",id:"react-core",jsPlugins:[],oxlintPresets:["react"],placement:sharedReactPlacement,plugins:[],requiredDevDependencies:[],rules:{},settings:{}},{description:"React Hooks lint rules via the JS plugin bridge for Oxlint.",id:"react-hooks",jsPlugins:[{name:"react-hooks-js",specifier:"eslint-plugin-react-hooks"}],oxlintPresets:[],placement:sharedReactPlacement,plugins:[],requiredDevDependencies:["eslint-plugin-react-hooks"],rules:Object.fromEntries([["react-hooks-js/exhaustive-deps","error"],["react-hooks-js/component-hook-factories","error"],["react-hooks-js/config","error"],["react-hooks-js/error-boundaries","error"],["react-hooks-js/gating","error"],["react-hooks-js/globals","error"],["react-hooks-js/immutability","error"],["react-hooks-js/incompatible-library","error"],["react-hooks-js/preserve-manual-memoization","error"],["react-hooks-js/purity","error"],["react-hooks-js/refs","error"],["react-hooks-js/rules-of-hooks","error"],["react-hooks-js/set-state-in-effect","error"],["react-hooks-js/set-state-in-render","error"],["react-hooks-js/static-components","error"],["react-hooks-js/unsupported-syntax","error"],["react-hooks-js/use-memo","error"]]),settings:{}},{description:"Guidance rules that push React code away from unnecessary effects.",id:"react-you-might-not-need-an-effect",jsPlugins:[{name:"react-you-might-not-need-an-effect-js",specifier:"eslint-plugin-react-you-might-not-need-an-effect"}],oxlintPresets:[],placement:sharedReactPlacement,plugins:[],requiredDevDependencies:["eslint-plugin-react-you-might-not-need-an-effect"],rules:{"react-you-might-not-need-an-effect-js/no-adjust-state-on-prop-change":"error","react-you-might-not-need-an-effect-js/no-chain-state-updates":"error","react-you-might-not-need-an-effect-js/no-derived-state":"error","react-you-might-not-need-an-effect-js/no-event-handler":"error","react-you-might-not-need-an-effect-js/no-initialize-state":"error","react-you-might-not-need-an-effect-js/no-pass-data-to-parent":"error","react-you-might-not-need-an-effect-js/no-pass-live-state-to-parent":"error","react-you-might-not-need-an-effect-js/no-reset-all-state-on-prop-change":"error"},settings:{}},{description:"Ultracite Next.js preset for the main web application.",id:"next-core",jsPlugins:[],oxlintPresets:["next"],placement:{...webOnlyPlacement,placementNotes:"Place this beside the React app override and set `settings.next.rootDir` to the repo's actual Next workspace roots if the final config needs that plugin setting."},plugins:[],requiredDevDependencies:[],rules:{},settings:{}},{description:"Ultracite TanStack preset for query/router/start framework linting.",id:"tanstack-query-core",jsPlugins:[],oxlintPresets:["tanstack"],placement:{...webOnlyPlacement,placementNotes:"Scope this to client code that owns TanStack Query usage. Keep it out of server-only or shared non-query packages unless those paths actually create queries or mutations."},plugins:[],requiredDevDependencies:[],rules:{},settings:{}},{description:"Effect architectural rule that blocks barrel-package imports.",id:"effect-no-barrel-imports",jsPlugins:[{name:"effect-js",specifier:"@effect/eslint-plugin"}],oxlintPresets:[],placement:effectPlacement,plugins:[],requiredDevDependencies:["@effect/eslint-plugin"],rules:{"effect-js/no-import-from-barrel-package":["error",{packageNames:["effect"]}]},settings:{}},{description:"Ultracite Vitest preset for repo-owned test globs.",id:"vitest-core",jsPlugins:[],oxlintPresets:["vitest"],placement:vitestPlacement,plugins:[],requiredDevDependencies:[],rules:{},settings:{}}];var stableJson=(value5)=>JSON.stringify(value5);var placementKeyOf=(placement)=>[placement.recommendedConfigFile,...placement.recommendedFiles].join("::");var validateLintCatalog=(catalog)=>{const seenIds=new Set;const seenRules=new Map;const seenSettings=new Map;const seenJsPlugins=new Map;for(const asset of catalog){if(seenIds.has(asset.id)){throw new Error(`Duplicate lint asset id: ${asset.id}`)}seenIds.add(asset.id);const placementKey=placementKeyOf(asset.placement);for(const[ruleName,ruleValue]of Object.entries(asset.rules)){const key=`${placementKey}::rule::${ruleName}`;const value5=stableJson(ruleValue);const previous=seenRules.get(key);if(previous!==undefined&&previous.value!==value5){throw new Error(`Conflicting lint rule \`${ruleName}\` for placement \`${placementKey}\`: ${previous.assetId} vs ${asset.id}`)}if(previous===undefined){seenRules.set(key,{assetId:asset.id,value:value5})}}for(const[settingName,settingValue]of Object.entries(asset.settings)){const key=`${placementKey}::setting::${settingName}`;const value5=stableJson(settingValue);const previous=seenSettings.get(key);if(previous!==undefined&&previous.value!==value5){throw new Error(`Conflicting lint setting \`${settingName}\` for placement \`${placementKey}\`: ${previous.assetId} vs ${asset.id}`)}if(previous===undefined){seenSettings.set(key,{assetId:asset.id,value:value5})}}for(const plugin of asset.jsPlugins){const key=`${placementKey}::js-plugin::${plugin.name}`;const previous=seenJsPlugins.get(key);if(previous!==undefined&&previous.specifier!==plugin.specifier){throw new Error(`Conflicting JS plugin alias \`${plugin.name}\` for placement \`${placementKey}\`: ${previous.assetId} vs ${asset.id}`)}if(previous===undefined){seenJsPlugins.set(key,{assetId:asset.id,specifier:plugin.specifier})}}}return catalog};var skillCatalog=[{framework:"browser-automation",id:"agent-browser",language:null,requiresTools:["agent-browser"],sourceDirectory:"skills/agnostic/frontend/agent-browser",tier:"framework"},{framework:null,id:"backend-domain-structure",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/backend/backend-domain-structure",tier:"agnostic"},{framework:null,id:"backend-recoverable-actions",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/backend/backend-recoverable-actions",tier:"agnostic"},{framework:null,id:"logging-best-practices",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/backend/logging-best-practices",tier:"agnostic"},{framework:null,id:"audit-cicd-security",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/security/audit-cicd-security",tier:"agnostic"},{framework:null,id:"security-best-practices",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/security/security-best-practices",tier:"agnostic"},{framework:"better-auth",id:"better-auth-best-practices",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/better-auth/better-auth-best-practices",tier:"framework"},{framework:"better-auth",id:"better-auth-security-best-practices",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/better-auth/better-auth-security-best-practices",tier:"framework"},{framework:null,id:"create-plan",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/planning/create-plan",tier:"agnostic"},{framework:null,id:"create-spec",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/planning/create-spec",tier:"agnostic"},{framework:null,id:"delivery-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/delivery-phase",tier:"agnostic"},{framework:null,id:"design-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/design-phase",tier:"agnostic"},{framework:null,id:"debug-agent",language:null,requiresTools:["debug-agent"],sourceDirectory:"skills/agnostic/debug/debug-agent",tier:"agnostic"},{framework:null,id:"debugging-phase",language:null,requiresTools:["debug-agent"],sourceDirectory:"skills/phases/debugging-phase",tier:"agnostic"},{framework:null,id:"bug-discovery-phase",language:null,requiresTools:["clawpatch"],sourceDirectory:"skills/phases/bug-discovery-phase",tier:"agnostic"},{framework:null,id:"bug-resolution-phase",language:null,requiresTools:["clawpatch"],sourceDirectory:"skills/phases/bug-resolution-phase",tier:"agnostic"},{framework:null,id:"docs-ingest-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/docs-ingest-phase",tier:"agnostic"},{framework:null,id:"docs-onboarding",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/docs-onboarding",tier:"agnostic"},{framework:null,id:"writing-fragments",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/writing-fragments",tier:"agnostic"},{framework:null,id:"writing-beats",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/writing-beats",tier:"agnostic"},{framework:null,id:"writing-shape",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/writing-shape",tier:"agnostic"},{framework:"effect",id:"effect-backend-structure",language:"typescript",requiresTools:["opensrc"],sourceDirectory:"skills/frameworks/effect/effect-backend-structure",tier:"framework"},{framework:"effect",id:"effect",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/effect/effect",tier:"framework"},{framework:"effect",id:"effect-recoverable-actions",language:"typescript",requiresTools:["opensrc"],sourceDirectory:"skills/frameworks/effect/effect-recoverable-actions",tier:"framework"},{framework:"elysiajs",id:"elysiajs",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/elysia/elysiajs",tier:"framework"},{framework:"expo",id:"add-app-clip",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/add-app-clip",tier:"framework"},{framework:"expo",id:"building-native-ui",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/building-native-ui",tier:"framework"},{framework:"expo",id:"eas-simulator",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/eas-simulator",tier:"framework"},{framework:"expo",id:"eas-update-insights",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/eas-update-insights",tier:"framework"},{framework:"expo",id:"expo-api-routes",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-api-routes",tier:"framework"},{framework:"expo",id:"expo-brownfield",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-brownfield",tier:"framework"},{framework:"expo",id:"expo-cicd-workflows",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-cicd-workflows",tier:"framework"},{framework:"expo",id:"expo-deployment",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-deployment",tier:"framework"},{framework:"expo",id:"expo-dev-client",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-dev-client",tier:"framework"},{framework:"expo",id:"expo-examples",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-examples",tier:"framework"},{framework:"expo",id:"expo-module",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-module",tier:"framework"},{framework:"expo",id:"expo-observe",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-observe",tier:"framework"},{framework:"expo",id:"expo-skill-eval",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-skill-eval",tier:"framework"},{framework:"expo",id:"expo-tailwind-setup",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-tailwind-setup",tier:"framework"},{framework:"expo",id:"expo-ui",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-ui",tier:"framework"},{framework:"expo",id:"native-data-fetching",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/native-data-fetching",tier:"framework"},{framework:"expo",id:"upgrading-expo",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/upgrading-expo",tier:"framework"},{framework:"expo",id:"use-dom",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/use-dom",tier:"framework"},{framework:"expo",id:"web-to-native",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/web-to-native",tier:"framework"},{framework:"pulumi",id:"pulumi-overview",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/pulumi-overview",tier:"framework"},{framework:"pulumi",id:"pulumi-best-practices",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/pulumi-best-practices",tier:"framework"},{framework:"pulumi",id:"pulumi-component",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/pulumi-component",tier:"framework"},{framework:"pulumi",id:"pulumi-automation-api",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/pulumi-automation-api",tier:"framework"},{framework:"pulumi",id:"pulumi-esc",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/pulumi-esc",tier:"framework"},{framework:"pulumi",id:"provider-upgrade",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/provider-upgrade",tier:"framework"},{framework:"pulumi",id:"package-usage",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/package-usage",tier:"framework"},{framework:null,id:"design-taste-frontend",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/frontend/design-taste-frontend",tier:"agnostic"},{framework:null,id:"imagegen-frontend-mobile",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/frontend/imagegen-frontend-mobile",tier:"agnostic"},{framework:null,id:"imagegen-frontend-web",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/frontend/imagegen-frontend-web",tier:"agnostic"},{framework:null,id:"frontend-domain-structure",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/frontend/frontend-domain-structure",tier:"agnostic"},{framework:null,id:"finder-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/finder-phase",tier:"agnostic"},{framework:null,id:"goalify",language:null,requiresTools:[],sourceDirectory:"skills/phases/goalify",tier:"agnostic"},{framework:null,id:"grilling",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/requirements/grilling",tier:"agnostic"},{framework:null,id:"handoff",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/generic/handoff",tier:"agnostic"},{framework:null,id:"improve-codebase-architecture",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/research/improve-codebase-architecture",tier:"agnostic"},{framework:null,id:"implement-spec",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/planning/implement-spec",tier:"agnostic"},{framework:null,id:"repo-asset-management",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/repo-asset-management",tier:"agnostic"},{framework:null,id:"stack",language:null,requiresTools:["stack"],sourceDirectory:"skills/agnostic/planning/stack",tier:"agnostic"},{framework:null,id:"wayfinder",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/planning/wayfinder",tier:"agnostic"},{framework:"nextjs",id:"next-best-practices",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/nextjs/next-best-practices",tier:"framework"},{framework:"nextjs",id:"next-cache-components",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/nextjs/next-cache-components",tier:"framework"},{framework:null,id:"parallel-research",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/research/parallel-research",tier:"agnostic"},{framework:null,id:"prototype",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/research/prototype",tier:"agnostic"},{framework:null,id:"async-python-patterns",language:"python",requiresTools:[],sourceDirectory:"skills/languages/python/async-python-patterns",tier:"language"},{framework:null,id:"python-code-style",language:"python",requiresTools:[],sourceDirectory:"skills/languages/python/python-code-style",tier:"language"},{framework:null,id:"python-design-patterns",language:"python",requiresTools:[],sourceDirectory:"skills/languages/python/python-design-patterns",tier:"language"},{framework:null,id:"python-project-structure",language:"python",requiresTools:[],sourceDirectory:"skills/languages/python/python-project-structure",tier:"language"},{framework:null,id:"python-testing-patterns",language:"python",requiresTools:[],sourceDirectory:"skills/languages/python/python-testing-patterns",tier:"language"},{framework:null,id:"quality-types",language:"typescript",requiresTools:[],sourceDirectory:"skills/languages/typescript/quality-types",tier:"language"},{framework:null,id:"codebase-design",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/codebase-design",tier:"agnostic"},{framework:"react",id:"async-react-patterns",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/react/async-react-patterns",tier:"framework"},{framework:"react",id:"react-doctor",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/react/react-doctor",tier:"framework"},{framework:null,id:"requirements-grill",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/requirements/requirements-grill",tier:"agnostic"},{framework:null,id:"requirements-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/requirements-phase",tier:"agnostic"},{framework:null,id:"resolve-debt-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/resolve-debt-phase",tier:"agnostic"},{framework:null,id:"review-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/review-phase",tier:"agnostic"},{framework:null,id:"review",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/review",tier:"agnostic"},{framework:null,id:"autoreview",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/autoreview",tier:"agnostic"},{framework:null,id:"simplify",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/simplify",tier:"agnostic"},{framework:null,id:"swarm-planner",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/subagents/swarm-planner",tier:"agnostic"},{framework:"tanstack-query",id:"tanstack-query",language:"typescript",requiresTools:["opensrc"],sourceDirectory:"skills/frameworks/tanstack-query/tanstack-query",tier:"framework"},{framework:null,id:"tdd",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/tdd",tier:"agnostic"},{framework:null,id:"writing-great-skills",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/writing-great-skills",tier:"agnostic"},{framework:"turborepo",id:"turborepo",language:null,requiresTools:[],sourceDirectory:"skills/frameworks/turborepo/turborepo",tier:"framework"},{framework:"react",id:"vercel-composition-patterns",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/react/vercel-composition-patterns",tier:"framework"},{framework:"react",id:"vercel-react-best-practices",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/react/vercel-react-best-practices",tier:"framework"},{framework:null,id:"write-backlog",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/requirements/write-backlog",tier:"agnostic"}];var toolCatalog=[{ensureCommands:[["agent-browser","install"]],id:"agent-browser",latestInstallTarget:"agent-browser@latest",packageName:"agent-browser",requiredBins:["node"],skipEnsureCommandsIfAnyCommandExists:[{env:"AGENT_BROWSER_EXECUTABLE_PATH"},"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium","/Applications/Brave Browser.app/Contents/MacOS/Brave Browser","google-chrome","google-chrome-stable","chromium","chromium-browser","brave-browser","brave-browser-stable","C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe","C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"]},{ensureCommands:[],id:"debug-agent",latestInstallTarget:"debug-agent@latest",packageName:"debug-agent",requiredBins:["node"]},{ensureCommands:[],id:"clawpatch",latestInstallTarget:"clawpatch@latest",packageName:"clawpatch",requiredBins:["node"]},{ensureCommands:[],id:"opensrc",latestInstallTarget:"opensrc@latest",minimumVersion:"0.7.2",packageName:"opensrc@^0.7.2",requiredBins:["node"],versionCommand:["opensrc","--version"]},{ensureCommands:[],id:"portless",latestInstallTarget:"portless@latest",packageName:"portless",requiredBins:["node"]},{ensureCommands:[],id:"skills",latestInstallTarget:"skills@latest",packageName:"skills",requiredBins:["node"]},{ensureCommands:[],id:"stack",latestInstallTarget:"@kitlangton/stack@latest",packageName:"@kitlangton/stack",requiredBins:["node"]}];var bundledNpmInstallAliasManifest=[{expectedSha256:"d1a3b15bb12948cfbd82acdd54889efc5d1263809550cb4d379863bbc1cc2f82",logicalRelativePath:"frameworks/nestjs/nestjs-best-practices/.gitignore",physicalRelativePath:"frameworks/nestjs/nestjs-best-practices/.npmignore"}];var fileSha256=(filePath)=>createHash3("sha256").update(readFileSync3(filePath)).digest("hex");var npmIgnoreFiles=(root)=>{const files=[];const visit2=(directory3)=>{for(const entry of readdirSync2(directory3,{withFileTypes:true})){const absolutePath=path6.join(directory3,entry.name);if(entry.isDirectory()){visit2(absolutePath)}else if(entry.isFile()&&entry.name===".npmignore"){files.push(path6.relative(root,absolutePath).split(path6.sep).join("/"))}}};visit2(root);return files};var resolveBundledSkillAliases=(root)=>{const aliases=new Map;const expectedPhysicalPaths=new Set(bundledNpmInstallAliasManifest.map(({physicalRelativePath})=>physicalRelativePath));for(const relativePath of npmIgnoreFiles(root)){if(!expectedPhysicalPaths.has(relativePath)){throw new Error(`Bundled baseline contains an unexpected npm alias: ${relativePath}`)}}for(const alias of bundledNpmInstallAliasManifest){const logicalPath=path6.join(root,alias.logicalRelativePath);const physicalPath=path6.join(root,alias.physicalRelativePath);const hasLogical=existsSync2(logicalPath);const hasPhysical=existsSync2(physicalPath);if(hasLogical&&hasPhysical){throw new Error(`Bundled baseline npm alias is ambiguous: ${alias.logicalRelativePath}`)}let resolvedPath=null;if(hasLogical){resolvedPath=logicalPath}else if(hasPhysical){resolvedPath=physicalPath}if(resolvedPath===null){throw new Error(`Bundled baseline asset is missing: ${alias.logicalRelativePath}`)}if(fileSha256(resolvedPath)!==alias.expectedSha256){throw new Error(`Bundled baseline npm alias hash mismatch: ${alias.logicalRelativePath}`)}if(hasPhysical){aliases.set(alias.physicalRelativePath,alias.logicalRelativePath)}}return aliases};var logicalBundledSkillRelativePath=(relativePath)=>bundledNpmInstallAliasManifest.find(({physicalRelativePath})=>physicalRelativePath===relativePath)?.logicalRelativePath??relativePath;var materializeBundledSkillDirectoryAliases=({sourceDirectory,sourceSkillsRoot,targetDirectory})=>{for(const alias of bundledNpmInstallAliasManifest){const sourcePhysicalPath=path6.join(sourceSkillsRoot,alias.physicalRelativePath);if(!existsSync2(sourcePhysicalPath)){continue}const relativePhysicalPath=path6.relative(sourceDirectory,sourcePhysicalPath);if(relativePhysicalPath===".."||relativePhysicalPath.startsWith(`..${path6.sep}`)){continue}const physicalPath=path6.join(targetDirectory,relativePhysicalPath);if(!existsSync2(physicalPath)){continue}const logicalPath=path6.join(targetDirectory,path6.relative(sourceDirectory,path6.join(sourceSkillsRoot,alias.logicalRelativePath)));if(existsSync2(logicalPath)){throw new Error(`Bundled baseline npm alias is ambiguous: ${alias.logicalRelativePath}`)}renameSync(physicalPath,logicalPath)}};var bundledBaseline={dataRoot,hooks:hookCatalog,lintAssets:validateLintCatalog(lintCatalog),packs:packCatalog,root:path6.dirname(dataRoot),skills:skillCatalog,skillsRoot,summary:{authoritySource:"bundled",channel:"bundled",commit:null,compatibility:{cliVersionRange:`=${version2}`},digest:bundledBaselineDigest,provenance:"packaged-cli",requested:{channel:"bundled"},resolvedVersion:version2,retrieval:"available",sha256:bundledBaselineDigest,source:"bundled",tag:null,version:version2},tools:toolCatalog};var resolveVerifiedBundledBaseline=(requested=bundledBaseline.summary.requested,retrieval="available")=>{const aliases=resolveBundledSkillAliases(skillsRoot);const actualDigest=digestContentRoots([{include:(relativePath)=>!relativePath.endsWith(".ts"),prefix:"data",root:dataRoot},{logicalPath:(relativePath)=>aliases.get(relativePath)??relativePath,prefix:"skills",root:skillsRoot}]);if(actualDigest!==bundledBaselineDigest){throw new BaselineIntegrityFailure({actualDigest,expectedDigest:bundledBaselineDigest,message:"Packaged baseline content no longer matches its verified identity.",request:requested,resolvedVersion:bundledBaseline.summary.resolvedVersion})}return{...bundledBaseline,summary:{...bundledBaseline.summary,channel:requested.channel,requested,retrieval}}};var packContents=packCatalog;var packContentsForBaseline=(baseline=bundledBaseline)=>baseline.packs;var packContentsByIdForBaseline=(baseline=bundledBaseline)=>{const contents={};for(const pack of packContentsForBaseline(baseline)){contents[pack.id]=pack}return contents};var packContentsById=packContentsByIdForBaseline();var defaultPackIds=packContents.filter((pack)=>pack.category==="default").map((pack)=>pack.id).toSorted();var languagePackIds=packContents.filter((pack)=>pack.category==="language").map((pack)=>pack.id).toSorted();var detectedPackIds=packContents.filter((pack)=>pack.category==="detected").map((pack)=>pack.id).toSorted();var surfacePackIds=packContents.filter((pack)=>pack.category==="surface").map((pack)=>pack.id).toSorted();var knownPackIds=packContents.map((pack)=>pack.id).toSorted();var defaultPackIdsForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).filter((pack)=>pack.category==="default").map((pack)=>pack.id).toSorted();var languagePackIdsForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).filter((pack)=>pack.category==="language").map((pack)=>pack.id).toSorted();var detectedPackIdsForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).filter((pack)=>pack.category==="detected").map((pack)=>pack.id).toSorted();var surfacePackIdsForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).filter((pack)=>pack.category==="surface").map((pack)=>pack.id).toSorted();var knownPackIdsForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).map((pack)=>pack.id).toSorted();var skillsForPack=(packId,baseline=bundledBaseline)=>packContentsByIdForBaseline(baseline)[packId]?.skills??[];var lintAssetsForPack=(packId,baseline=bundledBaseline)=>packContentsByIdForBaseline(baseline)[packId]?.lintAssets??[];var hooksForPack=(packId,baseline=bundledBaseline)=>packContentsByIdForBaseline(baseline)[packId]?.hooks??[];var promptDetailsForPack=(packId,baseline=bundledBaseline)=>packContentsByIdForBaseline(baseline)[packId]?.promptDetails??[];var exampleRepositoriesForPack=(packId,baseline=bundledBaseline)=>packContentsByIdForBaseline(baseline)[packId]?.exampleRepositories??[];var formatToolBootstrapStatus=(entry)=>{switch(entry.status){case"already-present":{return"already present"}case"installed":{return"installed during scaffold"}case"failed":{return"bootstrap failed"}default:{return entry.status}}};var formatToolBootstrapFailureDetails=(statuses)=>{const failures=statuses.filter((entry)=>entry.status==="failed");if(failures.length===0){return null}return["Required tool bootstrap failed, but scaffold/update output can still be written.","","Agent recovery prompt:","Read `.devpunks/settings.json`, verify each listed required tool manually, then fix the failed install before deeper repo work. If `agent-browser` failed while installing Chromium, install or repair that browser dependency outside the scaffold command, then rerun `agent-browser install` or the documented tool check.","","Failure stack traces:",...failures.flatMap((failure)=>["",`--- ${failure.toolId} ---`,failure.errorStack??failure.errorMessage??"Unknown tool bootstrap failure."])].join(`
|
|
326
326
|
`)};var formatList=(values3)=>values3.length===0?[" ∅"]:values3.map((value5)=>` • ${value5}`);var wrapInlineValues=({values:values3,firstPrefix,continuationPrefix,maxLineLength=88})=>{if(values3.length===0){return[`${firstPrefix}∅`]}const lines2=[];let currentLine=firstPrefix;for(const value5 of values3){const candidate=currentLine===firstPrefix?`${currentLine}${value5}`:`${currentLine}, ${value5}`;if(candidate.length<=maxLineLength||currentLine===firstPrefix){currentLine=candidate;continue}lines2.push(currentLine);currentLine=`${continuationPrefix}${value5}`}lines2.push(currentLine);return lines2};var formatPackRows=({label,values:values3,isLast})=>wrapInlineValues({continuationPrefix:`${isLast?" ":" │ "}${" ".repeat(`${label}: `.length)}`,firstPrefix:` ${isLast?"└":"├"} ${label}: `,values:values3});var formatPackList=(values3,baseline=bundledBaseline)=>values3.length===0?[" ∅"]:values3.flatMap((packId)=>{const skills=skillsForPack(packId,baseline);const lintAssets=lintAssetsForPack(packId,baseline);const hooks=hooksForPack(packId,baseline);const detailRows=[...skills.length===0?[]:[{label:"skills",values:skills}],...lintAssets.length===0?[]:[{label:"lint",values:lintAssets}],...hooks.length===0?[]:[{label:"hooks",values:hooks}],...(()=>{const promptLabels=promptDetailsForPack(packId,baseline);return promptLabels.length===0?[]:[{label:"prompts",values:promptLabels}]})()];return[` • ${packId}`,...detailRows.flatMap((row,index2)=>formatPackRows({isLast:index2===detailRows.length-1,label:row.label,values:row.values}))]});var formatCompactPackList=(values3)=>values3.length===0?[" ∅"]:wrapInlineValues({continuationPrefix:" ",firstPrefix:" • ",values:values3});var section=(title,lines2)=>[title,...lines2];var maybeSection=(title,lines2)=>lines2.length===1&&lines2[0]===" ∅"?[]:section(title,lines2);var formatDetectionSummary=(detection)=>["Scaffold detection summary",`cwd: ${detection.cwd}`,...section("detected languages:",formatList(detection.detectedLanguages)),...section("detected technologies:",formatList(detection.detectedTechnologies)),...section("manifest files:",formatList(detection.manifests.map((manifest)=>path7.relative(detection.cwd,manifest.path)||"package.json"))),...section("monorepo signals:",formatList(detection.monorepoSignals.map((signal)=>`${signal.type} (${path7.relative(detection.cwd,signal.path)||"."})`)))].join(`
|
|
327
327
|
`);var formatConfirmationSummary=(result4,baseline=bundledBaseline)=>["Confirmed scaffold selection",`baseline: ${result4.baseline.source}/${result4.baseline.channel} ${result4.baseline.version}`,`cwd: ${result4.cwd}`,`repo shape mode: ${result4.repoShapeMode}`,`effective repo shape: ${result4.monorepo?"monorepo":"single"}`,...section("detected languages:",formatList(result4.detectedLanguages)),...section("detected technologies:",formatList(result4.detectedTechnologies)),...section("default packs:",formatPackList(result4.defaultPacks,baseline)),...section("language packs:",formatPackList(result4.languagePacks,baseline)),...section("detected packs:",formatPackList(result4.detectedPacks,baseline)),...section("surface packs:",formatPackList(result4.surfacePacks,baseline)),...maybeSection("added packs:",formatPackList(result4.addedPacks,baseline)),...maybeSection("removed packs:",formatPackList(result4.removedPacks,baseline)),...section("final packs:",formatCompactPackList(result4.finalPacks)),`output directory: ${result4.outputDirectory}`,...section("shared core files:",formatList(result4.promptOutputs)),...section("lint spec files:",formatList(result4.lintSpecFiles)),...section("source guide files:",formatList(result4.sourceGuideFiles)),...section("skill files:",formatList(result4.skillFiles)),...section("prompt spec files:",formatList(result4.promptSpecFiles)),...section("subagent scaffold files:",formatList(result4.subagentFiles)),...section("script files:",formatList(result4.scriptFiles)),...section("hook files:",formatList(result4.hookFiles)),...section("harness files:",formatList(result4.harnessFiles)),...maybeSection("hidden output directories:",formatList(result4.hiddenOutputDirectories)),...section("agent handoff file:",formatList([result4.agentHandoffFile])),...section("required tools source:",formatList([".devpunks/settings.json"])),...maybeSection("tool bootstrap:",formatList(result4.toolBootstrapStatuses.map((entry)=>`${entry.toolId}: ${formatToolBootstrapStatus(entry)}`))),...section("scaffold manifest:",formatList([result4.scaffoldManifestFile]))].join(`
|
|
328
328
|
`);var formatAgentHandoffSummary=(result4)=>["Give this to the next agent","","You are continuing a `hi scaffold` run.","","Read first:",` • \`${result4.scaffoldManifestFile}\``,` • \`${result4.agentHandoffFile}\``," • `.devpunks/settings.json`","",...result4.toolBootstrapStatuses.length===0?[]:["Tool bootstrap status:",...result4.toolBootstrapStatuses.map((entry)=>` • \`${entry.toolId}\`: ${formatToolBootstrapStatus(entry)}`),""],...result4.toolBootstrapStatuses.some((entry)=>entry.status==="failed")?["Tool bootstrap recovery:"," • Read `.devpunks/settings.json` and manually verify every listed required tool before deeper repo work."," • Repair failed installs outside the scaffold command. For `agent-browser` Chromium failures, rerun `agent-browser install` after fixing the local browser dependency.",""]:[],"What was scaffolded:"," • final scoped/root prompt files were not written yet",...formatList([...result4.promptOutputs,...result4.lintSpecFiles,...result4.sourceGuideFiles,...result4.skillFiles,...result4.promptSpecFiles,...result4.subagentFiles,...result4.scriptFiles,...result4.hookFiles,...result4.harnessFiles]),"","What you must do:"," 1. Treat the prompt spec markdown files as instructions, not final prompt bodies.",result4.monorepo?" 2. Repo is in monorepo mode. Generate final prompt files for root, docs, and each relevant app/package scope.":" 2. Repo is in single-repo mode. Stitch scoped guidance into one root prompt, plus docs guidance when present."," 3. Read `.devpunks/settings.json` and verify listed required tools such as `skills`, `portless`, `opensrc`, and `agent-browser` are actually available. If any are missing, install/fix that first."," 4. Use the root prompt spec criteria to author root `AGENTS.md` from real repo evidence: surface map, workflow routing, cross-surface contract rules, validation routing, then short source/URL/docs rules. Do not add a root `Primary skills here` line."," 4a. Author scoped `AGENTS.md` files with `Primary skills here` lines for local defaults only. Never put phase skills in scoped primary-skill lines; keep them as global orchestration entrypoints."," 5. Treat every authored root/docs/workspace `AGENTS.md` file as the neutral scoped prompt source and create a sibling `CLAUDE.md` symlink mirror beside each one."," 6. Keep `.agents/AGENTS.md` as the shared global prompt source behind the scoped prompt tree; `.claude/CLAUDE.md` should mirror that neutral file."," 7. Before relying on subagents, verify the active harness global/project settings enable subagent execution, then verify `.agents/subagents/manifest.mjs` and selected specialist path/guidance/skill coverage. Repair settings/setup or execute locally if the guard fails."," 8. Keep `.agents/hooks/` as the neutral hook source, `.agents/skills/` as the main skill directory, and `.agents/scripts/sync-subagents.mjs` as the harness sync entrypoint. Only `.claude/skills` should mirror `.agents/skills`."," 9. Reconcile `.agents/subagents/manifest.mjs` with both `.agents/subagents/manifest.prompt.md` and `.devpunks/specs/subagents/manifest-spec.json`."," 10. Update owned paths / guidance file references in the subagent manifest to match the real repo shape."," 11. Use `portless` as the local-dev URL baseline. Prefer stable subdomains over raw `localhost:<port>` values in env examples, endpoint defaults, callback URLs, allowed origins, CORS, and app-to-app proxies."," 12. If adopting Oxlint or Oxfmt, replace existing lint/format setup deliberately: package scripts, task pipelines, CI, editor/docs references, and hooks should agree on the new tools."," 13. Before authoring final prompts or implementation plans, identify the core detected libraries whose source behavior matters."," 14. If an `opensrc/<package>.md` guide exists for a package, read that card first, then run its `opensrc path --cwd . <package>` command or fallback repository lookup."," 15. Inspect the returned checkout paths. Clone the major framework/runtime libraries you will reason about; do not clone every dependency mechanically."].join(`
|
|
@@ -340,9 +340,9 @@ ${colorRail2({environment,headingTone:"accent",rail:reflowRail(guide,environment
|
|
|
340
340
|
`))]}case"Json":{return[encodePrettyJson(publicUpdateResult(event.result))]}}};var makeUpdateInteraction=(prompt)=>({confirmApply:()=>map7(prompt.readLine(renderQuestion("Apply managed scaffold updates? [Y/n]: ")),(answer)=>{const normalized=answer.trim().toLowerCase();return normalized===""||normalized==="y"||normalized==="yes"}),emit:(event)=>forEach2(renderUpdateEvent(event),prompt.writeLine,{discard:true})});var updateInteractionLayer=effect(UpdateInteraction,map7(CliPrompt,makeUpdateInteraction));var publicCheckResult=(result4)=>{const{facts:_facts,...operation}=result4.operation;return{...result4,operation,update:publicUpdateResult(result4.update)}};var commandOutputModes=["interactive","plain","json"];var commandInteractionRequirements=["none","optional","required"];var metadataKeys=new Set(["path","name","group","summary","options","examples","interaction","outputModes"]);var optionKeys=new Set(["name","summary"]);var exampleKeys=new Set(["command","summary"]);class CommandMetadataError extends Error{_tag="CommandMetadataError";constructor(message){super(message);this.name="CommandMetadataError"}}var isRecord3=(value5)=>typeof value5==="object"&&value5!==null&&!Array.isArray(value5);var assertString=(value5,label)=>{if(typeof value5!=="string"||value5.trim()===""){throw new CommandMetadataError(`${label} must be a non-empty string.`)}};var assertAllowedKeys=(value5,keys3,label)=>{for(const key of Object.keys(value5)){if(!keys3.has(key)){throw new CommandMetadataError(`${label} contains unsupported behavior or metadata key '${key}'.`)}}};var validateOption=(value5,index2)=>{if(!isRecord3(value5)){throw new CommandMetadataError(`Command option ${index2} must be an object.`)}assertAllowedKeys(value5,optionKeys,`Command option ${index2}`);assertString(value5.name,`Command option ${index2}.name`);assertString(value5.summary,`Command option ${index2}.summary`);return{name:value5.name,summary:value5.summary}};var validateExample=(value5,index2)=>{if(!isRecord3(value5)){throw new CommandMetadataError(`Command example ${index2} must be an object.`)}assertAllowedKeys(value5,exampleKeys,`Command example ${index2}`);assertString(value5.command,`Command example ${index2}.command`);assertString(value5.summary,`Command example ${index2}.summary`);return{command:value5.command,summary:value5.summary}};var validateEntry=(value5,index2)=>{if(!isRecord3(value5)){throw new CommandMetadataError(`Command metadata entry ${index2} must be an object.`)}assertAllowedKeys(value5,metadataKeys,`Command metadata entry ${index2}`);if(!Array.isArray(value5.path)||value5.path.length===0){throw new CommandMetadataError(`Command metadata entry ${index2}.path must not be empty.`)}for(const[segmentIndex,segment]of value5.path.entries()){assertString(segment,`Command metadata entry ${index2}.path[${segmentIndex}]`);if(/^[-_]/u.test(segment)||/\s/u.test(segment)){throw new CommandMetadataError(`Command metadata entry ${index2}.path contains an invalid segment.`)}}assertString(value5.name,`Command metadata entry ${index2}.name`);if(value5.name!==value5.path.at(-1)){throw new CommandMetadataError(`Command metadata entry ${index2}.name must match the final path segment.`)}assertString(value5.group,`Command metadata entry ${index2}.group`);assertString(value5.summary,`Command metadata entry ${index2}.summary`);if(!Array.isArray(value5.options)){throw new CommandMetadataError(`Command metadata entry ${index2}.options must be an array.`)}if(!Array.isArray(value5.examples)){throw new CommandMetadataError(`Command metadata entry ${index2}.examples must be an array.`)}if(!commandInteractionRequirements.includes(value5.interaction)){throw new CommandMetadataError(`Command metadata entry ${index2}.interaction is invalid.`)}if(!Array.isArray(value5.outputModes)||value5.outputModes.length===0){throw new CommandMetadataError(`Command metadata entry ${index2}.outputModes must not be empty.`)}const outputModes=value5.outputModes.map((mode,modeIndex)=>{if(!commandOutputModes.includes(mode)){throw new CommandMetadataError(`Command metadata entry ${index2}.outputModes[${modeIndex}] is invalid.`)}return mode});if(new Set(outputModes).size!==outputModes.length){throw new CommandMetadataError(`Command metadata entry ${index2} has duplicate output modes.`)}const options4=value5.options.map(validateOption);if(new Set(options4.map((option6)=>option6.name)).size!==options4.length){throw new CommandMetadataError(`Command metadata entry ${index2} has duplicate option names.`)}return{examples:value5.examples.map(validateExample),group:value5.group,interaction:value5.interaction,name:value5.name,options:options4,outputModes,path:[...value5.path],summary:value5.summary}};var createCommandMetadataRegistry=(entries3)=>{const validated=entries3.map(validateEntry);const paths=new Set;for(const entry of validated){const key=entry.path.join(" ");if(paths.has(key)){throw new CommandMetadataError(`Duplicate command path '${key}'.`)}paths.add(key)}for(const entry of validated){for(let depth=1;depth<entry.path.length;depth+=1){const parent=entry.path.slice(0,depth).join(" ");if(!paths.has(parent)){throw new CommandMetadataError(`Command '${entry.path.join(" ")}' has missing parent '${parent}'.`)}}}return validated.toSorted((left,right)=>left.path.join(" ").localeCompare(right.path.join(" "),"en",{numeric:false}))};var declareCommandMetadata=(declaration)=>declaration;var commandMetadataFromDeclaration=(path8,declaration)=>({...declaration,path:path8});var optionMetadata=(declaration,name2)=>{const option6=declaration.options.find((candidate)=>candidate.name===name2);if(option6===undefined){throw new Error(`Command metadata for '${declaration.name}' does not declare '--${name2}'.`)}return option6};var metadataOptionName=(declaration,name2)=>optionMetadata(declaration,name2).name;var withOptionMetadata=(declaration,name2)=>(flag)=>exports_Flag.withDescription(flag,optionMetadata(declaration,name2).summary);var withCommandMetadata=(declaration)=>(command)=>command.pipe(exports_Command.withDescription(declaration.summary),exports_Command.withExamples(declaration.examples.map(({command:exampleCommand,summary})=>({command:exampleCommand,description:summary}))));var checkCommandMetadata=declareCommandMetadata({examples:[{command:"hi check",summary:"Check the current repository."}],group:"commands",interaction:"none",name:"check",options:[{name:"input",summary:"Scaffolded repository root check. Defaults current working directory."},{name:"json",summary:"Print machine-readable check result."},{name:"baseline",summary:"Scaffold baseline to use: stable, bundled, or an exact version. Defaults to stable."},{name:"refresh-baseline",summary:"Retained for compatibility; check already refreshes remote baseline metadata and bytes."}],outputModes:["interactive","plain","json"],summary:"Check managed scaffold, baseline, and CLI drift without writing files."});var inputOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(checkCommandMetadata,"input")).pipe(exports_Flag.withAlias("i"),withOptionMetadata(checkCommandMetadata,"input")));var jsonOption=exports_Flag.boolean(metadataOptionName(checkCommandMetadata,"json")).pipe(exports_Flag.withDefault(false),withOptionMetadata(checkCommandMetadata,"json"));var baselineOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(checkCommandMetadata,"baseline")).pipe(withOptionMetadata(checkCommandMetadata,"baseline")));var refreshBaselineOption=exports_Flag.boolean(metadataOptionName(checkCommandMetadata,"refresh-baseline")).pipe(exports_Flag.withDefault(false),withOptionMetadata(checkCommandMetadata,"refresh-baseline"));var executeCheckCommand=(input2,operation=runRepositoryCheckApplication)=>scoped2(gen2(function*executeCheck(){const result4=yield*operation(input2);return input2.json?{jsonPayload:publicCheckResult(result4),operation:result4.operation}:{operation:result4.operation}}));var makeCheckCommand=(operation=runRepositoryCheckApplication)=>exports_Command.make(checkCommandMetadata.name,{baseline:baselineOption,input:inputOption,json:jsonOption,refreshBaseline:refreshBaselineOption},({input:input2,json:json3,baseline,refreshBaseline})=>gen2(function*runCheckCommand(){const selectedOutputMode=yield*SelectedOutputMode;return yield*captureCommandResult(executeCheckCommand({baseline:getOrUndefined(baseline),changelogRoots:[process.cwd(),path8.resolve(import.meta.dirname,".."),path8.resolve(import.meta.dirname,"../.."),path8.resolve(import.meta.dirname,"../../.."),path8.resolve(import.meta.dirname,"../../../..")],json:json3||selectedOutputMode==="json",refreshBaseline,rootDirectory:path8.resolve(process.cwd(),getOrElse(input2,()=>"."))},operation))})).pipe(withCommandMetadata(checkCommandMetadata));var checkCommand=makeCheckCommand();class ProjectSettingsAccessFailure extends TaggedErrorClass()("@punks/cli/project-settings/ProjectSettingsAccessFailure",{cause:Defect(),message:String5,operation:Literals(["read","write"]),path:String5}){}class ProjectSettingsAlreadyExists extends TaggedErrorClass()("ProjectSettingsAlreadyExists",{message:String5,path:String5}){}var RepositoryManager=Literals(["azure-devops","bitbucket","github","gitlab"]);var BacklogProvider=Literals(["azure-devops","github","linear","monday"]);var AssetProvider=Union2([BacklogProvider,RepositoryManager]);var ProjectSettingsDocument=Struct({assetProviderSlug:optional(AssetProvider),backlogProjectUrl:optional(String5),backlogProvider:optional(BacklogProvider),baselineVersion:optional(String5),cliVersion:optional(String5),repositoryManager:optional(RepositoryManager),requiredTools:optional(ArraySchema(String5))});var repositoryManagerTools={"azure-devops":["az"],bitbucket:[],github:["gh"],gitlab:["glab"]};var requiredToolsForRepositoryManager=(repositoryManager)=>repositoryManagerTools[repositoryManager];var deriveRequiredTools=({repositoryManager,requiredTools})=>[...new Set([...requiredTools,...requiredToolsForRepositoryManager(repositoryManager)])].toSorted();class AmbiguousSettingsUpgrade extends TaggedErrorClass()("AmbiguousSettingsUpgrade",{message:String5,path:String5,providers:ArraySchema(AssetProvider)}){}class InvalidProjectSettings extends TaggedErrorClass()("InvalidProjectSettings",{cause:optional(Unknown2),message:String5,path:String5}){}class ProjectSettingsMissing extends TaggedErrorClass()("ProjectSettingsMissing",{message:String5,path:String5}){}var projectSettingsFile=".devpunks/settings.json";var ProjectSettingsFileSystem=Service("@punks/cli/ProjectSettingsFileSystem");var wikiRoots=["apps/wiki","app/wiki","wiki","."];var backlogProviders=BacklogProvider.literals;var repositoryManagers=RepositoryManager.literals;var parseSettings=fn2("ProjectSettings.parseSettings")(function*parseSettings2(settingsPath,content){const parsed=yield*try_3({catch:(cause)=>new InvalidProjectSettings({cause,message:`Invalid JSON in ${settingsPath}.`,path:settingsPath}),try:()=>JSON.parse(content)});const decoded=decodeUnknownResult2(ProjectSettingsDocument)(parsed);if(isFailure2(decoded)){return yield*new InvalidProjectSettings({cause:decoded.failure,message:`Invalid project settings in ${settingsPath}.`,path:settingsPath})}return{document:decoded.success,raw:parsed}});var providerHints=fn2("ProjectSettings.providerHints")(function*providerHints2(fileSystem,rootDirectory){const contents=yield*all2(wikiRoots.map((wikiRoot)=>fileSystem.readTextFile(fileSystem.joinPath(rootDirectory,wikiRoot,"backlog-provider.md"))));return[...new Set(contents.flatMap((content)=>match(content,{onNone:()=>[],onSome:(value5)=>backlogProviders.filter((provider)=>value5.includes(`\`${provider}\``))})))].toSorted()});var repositoryManagerHintsFromGitConfig=fn2("ProjectSettings.repositoryManagerHintsFromGitConfig")(function*repositoryManagerHintsFromGitConfig2(fileSystem,rootDirectory){const config=yield*fileSystem.readRepositoryGitConfig(rootDirectory);return match(config,{onNone:()=>[],onSome:(content)=>repositoryManagers.filter((repositoryManager)=>value4(repositoryManager).pipe(when4("azure-devops",()=>["dev.azure.com","visualstudio.com"].some((host)=>content.includes(host))),when4("bitbucket",()=>content.includes("bitbucket.org")),when4("github",()=>content.includes("github.com")),when4("gitlab",()=>content.includes("gitlab.com")),exhaustive2)).toSorted()})});var readProjectSettings=fn2("ProjectSettings.read")(function*readProjectSettings2(fileSystem,rootDirectory){const settingsPath=fileSystem.joinPath(rootDirectory,projectSettingsFile);const content=yield*fileSystem.readTextFile(settingsPath);if(isNone2(content)){return yield*new ProjectSettingsMissing({message:`Project settings are missing at ${settingsPath}.`,path:settingsPath})}const{document}=yield*parseSettings(settingsPath,content.value);const backlogProviderOption=fromNullishOr(document.backlogProvider);const repositoryManagerOption=fromNullishOr(document.repositoryManager);const hints=isNone2(backlogProviderOption)?yield*providerHints(fileSystem,rootDirectory):[];if(hints.length>1){return yield*new AmbiguousSettingsUpgrade({message:`Conflicting legacy backlog provider hints found: ${hints.join(", ")}.`,path:settingsPath,providers:hints})}const backlogProvider=getOrElse(backlogProviderOption,()=>hints[0]);if(backlogProvider===undefined){return yield*new InvalidProjectSettings({message:`Project settings do not identify a backlog provider.`,path:settingsPath})}const repositoryManagerHints=isNone2(repositoryManagerOption)?yield*repositoryManagerHintsFromGitConfig(fileSystem,rootDirectory):[];if(repositoryManagerHints.length>1){return yield*new AmbiguousSettingsUpgrade({message:`Conflicting legacy repository manager hints found: ${repositoryManagerHints.join(", ")}.`,path:settingsPath,providers:repositoryManagerHints})}const repositoryManager=getOrElse(repositoryManagerOption,()=>repositoryManagerHints[0]);if(repositoryManager===undefined){return yield*new AmbiguousSettingsUpgrade({message:`Legacy project settings do not identify a repository manager for ${backlogProvider}.`,path:settingsPath,providers:[]})}const settings={assetProviderSlug:document.assetProviderSlug??backlogProvider,backlogProvider,...document.backlogProjectUrl===undefined?{}:{backlogProjectUrl:document.backlogProjectUrl},...document.baselineVersion===undefined?{}:{baselineVersion:document.baselineVersion},...document.cliVersion===undefined?{}:{cliVersion:document.cliVersion},repositoryManager,requiredTools:deriveRequiredTools({repositoryManager,requiredTools:document.requiredTools??[]})};const upgradedFields=["assetProviderSlug","backlogProvider","repositoryManager"].filter((field)=>document[field]===undefined);const requiredToolsNeedUpgrade=document.requiredTools===undefined||document.requiredTools.length!==settings.requiredTools.length||document.requiredTools.some((tool,index2)=>tool!==settings.requiredTools[index2]);const safeUpgradeFields=requiredToolsNeedUpgrade?[...upgradedFields,"requiredTools"]:upgradedFields;return{settings,upgrade:safeUpgradeFields.length===0?{_tag:"CurrentSettings"}:{_tag:"SafeSettingsUpgrade",fields:safeUpgradeFields}}});var inferProjectSettings=fn2("ProjectSettings.infer")(function*inferProjectSettings2(fileSystem,rootDirectory){const settingsPath=fileSystem.joinPath(rootDirectory,projectSettingsFile);const backlogProviderHints=yield*providerHints(fileSystem,rootDirectory);if(backlogProviderHints.length>1){return yield*new AmbiguousSettingsUpgrade({message:`Conflicting legacy backlog provider hints found: ${backlogProviderHints.join(", ")}.`,path:settingsPath,providers:backlogProviderHints})}const[backlogProvider]=backlogProviderHints;if(backlogProvider===undefined){return none2()}const repositoryManagerHints=yield*repositoryManagerHintsFromGitConfig(fileSystem,rootDirectory);if(repositoryManagerHints.length>1){return yield*new AmbiguousSettingsUpgrade({message:`Conflicting legacy repository manager hints found: ${repositoryManagerHints.join(", ")}.`,path:settingsPath,providers:repositoryManagerHints})}const repositoryManager=repositoryManagerHints[0]??(backlogProvider==="github"||backlogProvider==="azure-devops"?backlogProvider:undefined);if(repositoryManager===undefined){return none2()}return some2({assetProviderSlug:backlogProvider,backlogProvider,repositoryManager,requiredTools:deriveRequiredTools({repositoryManager,requiredTools:[]})})});var writeProjectSettings=fn2("ProjectSettings.write")(function*writeProjectSettings2(fileSystem,rootDirectory,change){const settingsPath=fileSystem.joinPath(rootDirectory,projectSettingsFile);const content=yield*fileSystem.readTextFile(settingsPath);if(isNone2(content)){return yield*new ProjectSettingsMissing({message:`Project settings are missing at ${settingsPath}.`,path:settingsPath})}const{document,raw:raw2}=yield*parseSettings(settingsPath,content.value);const next={...raw2};if(change._tag==="ReconfigurationChange"){const requiredTools=deriveRequiredTools({repositoryManager:change.repositoryManager,requiredTools:change.requiredTools});next.assetProviderSlug=change.assetProviderSlug;next.backlogProvider=change.backlogProvider;next.repositoryManager=change.repositoryManager;next.requiredTools=requiredTools;if(change.backlogProjectUrl===undefined){delete next.backlogProjectUrl}else{next.backlogProjectUrl=change.backlogProjectUrl}yield*fileSystem.writeTextFile(settingsPath,`${JSON.stringify(next,null,2)}
|
|
341
341
|
`);return{settings:{assetProviderSlug:change.assetProviderSlug,backlogProvider:change.backlogProvider,...change.backlogProjectUrl===undefined?{}:{backlogProjectUrl:change.backlogProjectUrl},...document.baselineVersion===undefined?{}:{baselineVersion:document.baselineVersion},...document.cliVersion===undefined?{}:{cliVersion:document.cliVersion},repositoryManager:change.repositoryManager,requiredTools},upgrade:{_tag:"CurrentSettings"}}}yield*value4(change).pipe(tag3("UserChoicesChange",(choices)=>sync2(()=>{next.assetProviderSlug=choices.assetProviderSlug;next.backlogProvider=choices.backlogProvider;next.repositoryManager=choices.repositoryManager;if(choices.backlogProjectUrl===undefined){delete next.backlogProjectUrl}else{next.backlogProjectUrl=choices.backlogProjectUrl}})),tag3("CalculatedToolsChange",({requiredTools})=>gen2(function*applyCalculatedToolsChange(){const current=yield*readProjectSettings(fileSystem,rootDirectory);next.requiredTools=deriveRequiredTools({repositoryManager:current.settings.repositoryManager,requiredTools})})),tag3("ManagedVersionsChange",({baselineVersion,cliVersion})=>gen2(function*applyManagedVersionsChange(){yield*readProjectSettings(fileSystem,rootDirectory);next.baselineVersion=baselineVersion;next.cliVersion=cliVersion})),tag3("ScaffoldChange",({baselineVersion,cliVersion,requiredTools})=>gen2(function*applyScaffoldChange(){const current=yield*readProjectSettings(fileSystem,rootDirectory);next.baselineVersion=baselineVersion;next.cliVersion=cliVersion;next.requiredTools=deriveRequiredTools({repositoryManager:current.settings.repositoryManager,requiredTools})})),exhaustive2);yield*fileSystem.writeTextFile(settingsPath,`${JSON.stringify(next,null,2)}
|
|
342
342
|
`);return yield*readProjectSettings(fileSystem,rootDirectory)});var projectSettingsInitializationContent=(initialization)=>{const{calculatedTools,managedVersions,userChoices}=initialization;const settings={...userChoices,...managedVersions,requiredTools:deriveRequiredTools({repositoryManager:userChoices.repositoryManager,requiredTools:calculatedTools.requiredTools})};return`${JSON.stringify(settings,null,2)}
|
|
343
|
-
`};var initializeProjectSettings=fn2("ProjectSettings.initialize")(function*initializeProjectSettings2(fileSystem,rootDirectory,initialization){const settingsPath=fileSystem.joinPath(rootDirectory,projectSettingsFile);const settingsDirectory=fileSystem.joinPath(rootDirectory,".devpunks");const settingsDirectoryExisted=yield*fileSystem.directoryExists(settingsDirectory);const expectedContent=projectSettingsInitializationContent(initialization);const created=yield*fileSystem.createTextFile(settingsPath,expectedContent);if(!created){return yield*new ProjectSettingsAlreadyExists({message:`Project settings already exist at ${settingsPath}.`,path:settingsPath})}const read3=yield*readProjectSettings(fileSystem,rootDirectory).pipe(result2);if(isSuccess2(read3)){return read3.success}yield*gen2(function*rollbackProjectSettingsInitialization(){yield*fileSystem.removeTextFileIfContent(settingsPath,expectedContent);if(!settingsDirectoryExisted){yield*fileSystem.removeEmptyDirectory(settingsDirectory)}}).pipe(result2);return yield*read3.failure});var rollbackProjectSettingsInitialization=fn2("ProjectSettings.rollbackInitialization")(function*rollbackProjectSettingsInitialization2(fileSystem,rootDirectory,rollback){const settingsPath=fileSystem.joinPath(rootDirectory,projectSettingsFile);const settingsDirectory=fileSystem.joinPath(rootDirectory,".devpunks");const removed=yield*fileSystem.removeTextFileIfContent(settingsPath,projectSettingsInitializationContent(rollback.initialization));if(rollback.removeSettingsDirectory){yield*fileSystem.removeEmptyDirectory(settingsDirectory)}return removed});var ProjectSettings=Service("@punks/cli/ProjectSettings");var ProjectSettingsDefault=effect(ProjectSettings,gen2(function*ProjectSettingsDefault2(){const fileSystem=yield*ProjectSettingsFileSystem;return{infer:(rootDirectory)=>inferProjectSettings(fileSystem,rootDirectory),initialize:(rootDirectory,initialization)=>initializeProjectSettings(fileSystem,rootDirectory,initialization),read:(rootDirectory)=>readProjectSettings(fileSystem,rootDirectory),rollbackInitialization:(rootDirectory,rollback)=>rollbackProjectSettingsInitialization(fileSystem,rootDirectory,rollback),write:(rootDirectory,change)=>writeProjectSettings(fileSystem,rootDirectory,change)}}));import{execFileSync}from"node:child_process";import{accessSync,constants as constants2,existsSync as existsSync3,mkdirSync as mkdirSync2,readFileSync as readFileSync4,writeFileSync as writeFileSync2}from"node:fs";import{homedir}from"node:os";import path9 from"node:path";class ToolManagementFailure extends TaggedErrorClass()("@punks/cli/integrations/tool-management/ToolManagementFailure",{cause:Defect(),message:String5,operation:Literals(["ensure-required-tool","infer-repo-settings"])}){}var toolManagementFailure=(operation,message)=>new ToolManagementFailure({cause:new Error(message),message,operation});var repoSettingsFile=".devpunks/settings.json";var repositoryManagerTools2={"azure-devops":["az"],bitbucket:[],github:["gh"],gitlab:["glab"]};var repositoryManagers2=new Set(Object.keys(repositoryManagerTools2));var backlogProviders2=new Set(["azure-devops","github","linear","monday"]);var assetProviders=new Set([...backlogProviders2,...repositoryManagers2]);var requiredToolsForRepositoryManager2=(repositoryManager)=>repositoryManagerTools2[repositoryManager];var reconcileRepositoryManagerTools=({previousRepositoryManager,requiredTools,repositoryManager})=>{const previousManagerTools=new Set(requiredToolsForRepositoryManager2(previousRepositoryManager));return[...new Set([...requiredTools.filter((tool)=>!previousManagerTools.has(tool)),...requiredToolsForRepositoryManager2(repositoryManager)])].toSorted()};var isRepositoryManager=(value5)=>typeof value5==="string"&&repositoryManagers2.has(value5);var isBacklogProvider=(value5)=>typeof value5==="string"&&backlogProviders2.has(value5);var isAssetProvider=(value5)=>typeof value5==="string"&&assetProviders.has(value5);var isStringArray=(value5)=>Array.isArray(value5)&&value5.every((tool)=>typeof tool==="string");var normalizeRepoSettings=(value5)=>{if(typeof value5!=="object"||value5===null){return null}const record3=value5;if(!isBacklogProvider(record3.backlogProvider)||!isAssetProvider(record3.assetProviderSlug)||!isRepositoryManager(record3.repositoryManager)||!isStringArray(record3.requiredTools)){return null}return Object.fromEntries([["backlogProvider",record3.backlogProvider],["assetProviderSlug",record3.assetProviderSlug],...typeof record3.backlogProjectUrl==="string"?[["backlogProjectUrl",record3.backlogProjectUrl]]:[],...typeof record3.baselineVersion==="string"?[["baselineVersion",record3.baselineVersion]]:[],...typeof record3.cliVersion==="string"?[["cliVersion",record3.cliVersion]]:[],["repositoryManager",record3.repositoryManager],["requiredTools",[...new Set([...record3.requiredTools,...requiredToolsForRepositoryManager2(record3.repositoryManager)])].toSorted()]])};var readRepoSettings=(rootDirectory)=>{const settingsPath=path9.join(rootDirectory,repoSettingsFile);if(!existsSync3(settingsPath)){return null}return normalizeRepoSettings(JSON.parse(readFileSync4(settingsPath,"utf-8")))};var commandExistsOnPath=(command,env={},platform=process.platform)=>{const pathValue=env.PATH??env.Path;if(pathValue===undefined||pathValue.length===0){return false}const isWindows=platform==="win32";const pathSeparator=isWindows?";":":";const pathEntries=pathValue.split(pathSeparator).filter((entry)=>entry.length>0);const pathExtensions=isWindows?(env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter((extension)=>extension.length>0):[""];const commandExtensions=isWindows&&path9.extname(command).length===0?pathExtensions:[""];const hasPathSegment=command.includes("/")||command.includes("\\");const candidates=(hasPathSegment?[""]:pathEntries).flatMap((entry)=>commandExtensions.map((extension)=>hasPathSegment?`${command}${extension}`:path9.join(entry,`${command}${extension}`)));return candidates.some((candidate)=>{try{accessSync(candidate,isWindows?constants2.F_OK:constants2.X_OK);return true}catch{return false}})};var makeToolCommandRuntime=(environment)=>({commandExists:(command)=>commandExistsOnPath(command,environment),cwd:homedir(),env:environment,execFile:(command,args2,options4)=>{execFileSync(command,[...args2],{cwd:options4?.cwd,env:environment,stdio:options4?.stdio==="inherit"?["ignore","inherit","inherit"]:"ignore"})},execFileOutput:(command,args2,options4)=>execFileSync(command,[...args2],{cwd:options4?.cwd,encoding:"utf-8",env:environment})});var defaultRuntime=makeToolCommandRuntime({});var defaultToolBootstrapOptions={mode:"repair",stdio:"inherit"};var detectGlobalPackageManager=(runtime)=>{if(runtime.commandExists("bun")){return"bun"}if(runtime.commandExists("pnpm")){return"pnpm"}if(runtime.commandExists("npm")){return"npm"}return null};var globalInstallCommandFor=(packageManager,packageName)=>{switch(packageManager){case"bun":{return["bun","add","-g",packageName]}case"pnpm":{return["pnpm","add","-g",packageName]}case"npm":{return["npm","install","-g",packageName]}default:{return packageManager}}};var parseVersionParts=(value5)=>{const match8=value5.match(/\d+(?:\.\d+){0,2}/u);if(match8===null){return null}const[matchedVersion]=match8;return matchedVersion===undefined?null:matchedVersion.split(".").map((part)=>Number.parseInt(part,10))};var compareVersions=(actual,minimum)=>{const length=Math.max(actual.length,minimum.length);for(let index2=0;index2<length;index2+=1){const actualPart=actual[index2]??0;const minimumPart=minimum[index2]??0;if(actualPart>minimumPart){return 1}if(actualPart<minimumPart){return-1}}return 0};var isMinimumVersionSatisfied=(tool,runtime,cwd)=>{if(tool.minimumVersion===undefined||tool.versionCommand===undefined){return true}const[command,...args2]=tool.versionCommand;if(command===undefined||runtime.execFileOutput===undefined){return true}const actual=parseVersionParts(runtime.execFileOutput(command,args2,{cwd}));const minimum=parseVersionParts(tool.minimumVersion);if(actual===null||minimum===null){throw toolManagementFailure("ensure-required-tool",`Cannot verify required tool version from \`${tool.versionCommand.join(" ")}\`.`)}return compareVersions(actual,minimum)>=0};var commandCandidateValue=(candidate,env)=>{if(typeof candidate==="string"){return candidate}const value5=env[candidate.env];return value5===undefined||value5.length===0?null:value5};var shouldSkipEnsureCommands=(tool,runtime)=>tool.skipEnsureCommandsIfAnyCommandExists?.some((candidate)=>{const command=commandCandidateValue(candidate,runtime.env??{});return command!==null&&runtime.commandExists(command)})??false;var manualProviderCliTools=Object.fromEntries([...new Set(Object.values(repositoryManagerTools2).flat())].map((toolId)=>[toolId,{ensureCommands:[],manual:true,requiredBins:[]}]));var installTool=({cwd,installTarget,runtime,stdio,toolId,versionContract})=>{const packageManager=detectGlobalPackageManager(runtime);if(packageManager===null){throw toolManagementFailure("ensure-required-tool","Cannot install required tools because no supported global package manager was found on PATH. Install Bun, pnpm, or npm first.")}if(installTarget===undefined){throw toolManagementFailure("ensure-required-tool",`Required tool \`${toolId}\` cannot be installed automatically.`)}const[command,...args2]=globalInstallCommandFor(packageManager,installTarget);runtime.execFile(command,args2,{cwd,stdio});if(!runtime.commandExists(toolId)){throw toolManagementFailure("ensure-required-tool",`Tried to install required tool \`${toolId}\`, but the binary is still not available on PATH afterwards.`)}if(!isMinimumVersionSatisfied(versionContract,runtime,cwd)){throw toolManagementFailure("ensure-required-tool",`Tried to install required tool \`${toolId}\`, but the installed version does not satisfy ${versionContract.minimumVersion}.`)}};var ensureToolsInstalled=(toolIds,baseline=bundledBaseline,runtime=defaultRuntime,options4=defaultToolBootstrapOptions)=>{const statuses=[];const toolCatalogById=Object.fromEntries(baseline.tools.map((tool)=>[tool.id,tool]));const cwd=runtime.cwd??homedir();for(const toolId of toolIds){const tool=toolCatalogById[toolId]===undefined?manualProviderCliTools[toolId]:{...toolCatalogById[toolId],manual:false};if(tool===undefined){throw toolManagementFailure("ensure-required-tool",`Unknown required tool \`${toolId}\` in baseline.`)}const missingPrerequisites=tool.requiredBins.filter((command)=>!runtime.commandExists(command));if(missingPrerequisites.length>0){throw toolManagementFailure("ensure-required-tool",`Cannot install required tool \`${toolId}\` because ${missingPrerequisites.join(", ")} is not available on PATH.`)}const versionContract=tool;const alreadyPresent=runtime.commandExists(toolId)&&isMinimumVersionSatisfied(versionContract,runtime,cwd);const refreshLatest=options4.mode==="refresh-latest"&&!tool.manual;if(!alreadyPresent&&tool.manual){throw toolManagementFailure("ensure-required-tool",`Required external tool \`${toolId}\` is not available on PATH. Install it before running scaffold/update workflows.`)}if(!alreadyPresent||refreshLatest){const installTarget=refreshLatest?tool.latestInstallTarget:tool.packageName;installTool({cwd,installTarget,runtime,stdio:options4.stdio,toolId,versionContract})}const ensureCommandContract=tool;if(!shouldSkipEnsureCommands(ensureCommandContract,runtime)){for(const[command,...args2]of tool.ensureCommands){runtime.execFile(command,args2,{cwd,stdio:options4.stdio})}}statuses.push({status:alreadyPresent&&!refreshLatest?"already-present":"installed",toolId})}return statuses};var errorMessage=(cause)=>cause instanceof Error?cause.message:String(cause);var errorStack=(cause)=>cause instanceof Error?cause.stack??cause.message:String(cause);var ensureToolsInstalledBestEffort=(toolIds,baseline=bundledBaseline,runtime=defaultRuntime,options4=defaultToolBootstrapOptions)=>toolIds.flatMap((toolId)=>{try{return ensureToolsInstalled([toolId],baseline,runtime,options4)}catch(error2){return[Object.fromEntries([["toolId",toolId],["status","failed"],["errorMessage",errorMessage(error2)],["errorStack",errorStack(error2)]])]}});var providerChoices=[{title:"GitHub Projects and Issues",value:"github"},{title:"Linear",value:"linear"},{title:"Azure DevOps",value:"azure-devops"},{title:"monday.com",value:"monday"}];var assetChoices=[...providerChoices,{title:"GitLab",value:"gitlab"},{title:"Bitbucket",value:"bitbucket"}];var repositoryChoices=[{title:"GitHub",value:"github"},{title:"GitLab",value:"gitlab"},{title:"Azure DevOps",value:"azure-devops"},{title:"Bitbucket",value:"bitbucket"}];var validProjectUrl=(input2)=>{const value5=input2.trim();try{const url2=new URL(value5);return url2.protocol==="http:"||url2.protocol==="https:"?value5:null}catch{return null}};var selectRepoSettings=({prompt,defaults:defaults2,retryCommand})=>gen2(function*selectSettings(){const backlogProvider=yield*prompt.singleSelect({choices:providerChoices,defaultValue:defaults2?.backlogProvider??"github",message:"Select backlog provider"});const assetProviderSlug=yield*prompt.singleSelect({choices:assetChoices,defaultValue:defaults2?.assetProviderSlug??backlogProvider,message:"Select asset provider"});const repositoryManager=yield*prompt.singleSelect({choices:repositoryChoices,defaultValue:defaults2?.repositoryManager??"github",message:"Select repository manager"});const input2=yield*prompt.readLine(`Backlog project URL${defaults2?.backlogProjectUrl?` [${defaults2.backlogProjectUrl}]`:""}: `);const backlogProjectUrl=validProjectUrl(input2||defaults2?.backlogProjectUrl||"");if(backlogProjectUrl===null){return yield*fail6(new CliPromptError({message:`Backlog project URL must be an absolute HTTP(S) URL. Rerun \`${retryCommand}\`.`}))}return{assetProviderSlug,backlogProjectUrl,backlogProvider,repositoryManager}});var ensureCommandMetadata=declareCommandMetadata({examples:[{command:"hi ensure",summary:"Reconfigure current project settings."}],group:"commands",interaction:"required",name:"ensure",options:[],outputModes:["interactive","plain"],summary:"Reconfigure backlog, asset, repository, and backlog project URL settings only."});var mapSettingsError=(error2)=>new CliPromptError({message:error2._tag==="ProjectSettingsMissing"?`${projectSettingsFile} was not found. Run \`hi init\` first.`:error2.message});var runEnsure=({rootDirectory,prompt})=>gen2(function*ensureSettings(){const projectSettings=yield*ProjectSettings;const current=(yield*projectSettings.read(rootDirectory).pipe(mapError3(mapSettingsError))).settings;const selected=yield*selectRepoSettings({defaults:current,prompt,retryCommand:"hi ensure"});const requiredTools=reconcileRepositoryManagerTools({previousRepositoryManager:current.repositoryManager,repositoryManager:selected.repositoryManager,requiredTools:current.requiredTools});yield*projectSettings.write(rootDirectory,{_tag:"ReconfigurationChange",assetProviderSlug:selected.assetProviderSlug,...selected.backlogProjectUrl===undefined?{}:{backlogProjectUrl:selected.backlogProjectUrl},backlogProvider:selected.backlogProvider,repositoryManager:selected.repositoryManager,requiredTools}).pipe(mapError3(mapSettingsError));return{changes:[{action:"configure",state:"completed",subject:projectSettingsFile}],degradations:[],issues:[],nextActions:[{kind:"none"}],status:"success",warnings:[]}});var executeEnsureCommand=(input2)=>captureCommandResult(runEnsure(input2));var ensureCommand=exports_Command.make(ensureCommandMetadata.name,{},()=>scoped2(gen2(function*runEnsureCommand(){const outputMode=yield*SelectedOutputMode;if(outputMode!=="interactive"){return yield*new CliValidationError({message:outputMode==="json"?"`hi ensure` requires interactive input and is unavailable in JSON mode.":"`hi ensure` requires interactive input and is unavailable when output is redirected.",recoveryCommand:"hi ensure"})}const prompt=yield*PromptLive;return yield*executeEnsureCommand({prompt,rootDirectory:process.cwd()})}))).pipe(withCommandMetadata(ensureCommandMetadata));class InvalidMigrationRetry extends TaggedErrorClass()("InvalidMigrationRetry",{message:String5}){}class InvalidMutationRetry extends TaggedErrorClass()("InvalidMutationRetry",{message:String5}){}class InvalidOperatorContext extends TaggedErrorClass()("InvalidOperatorContext",{message:String5}){}var SkillsCliScope=Literals(["project","global"]);var skillsCliFailureFields={agent:String5,message:String5,operation:Literals(["list","install","remove"]),scope:SkillsCliScope};var verifiedInstalledSkillSchema=Struct({agents:ArraySchema(String5),cliCompatibility:Struct({maximumExclusive:String5,minimum:String5}),name:String5,path:String5,revision:String5,scope:SkillsCliScope,source:String5,version:String5});var SkillsCliVerificationFailureReason=Literals(["unsafe-path","missing","unreadable","malformed","identity-mismatch"]);class SkillsCliVerificationFailure extends TaggedErrorClass()("SkillsCliVerificationFailure",{...skillsCliFailureFields,reason:SkillsCliVerificationFailureReason,skillName:String5,skillPath:String5,verifiedSkills:ArraySchema(verifiedInstalledSkillSchema)}){}class SkillsCliBindingFailure extends TaggedErrorClass()("SkillsCliBindingFailure",{...skillsCliFailureFields,reportedAgents:ArraySchema(String5),skillName:String5,verifiedSkills:ArraySchema(verifiedInstalledSkillSchema)}){}class SkillsCliExit extends TaggedErrorClass()("SkillsCliExit",{...skillsCliFailureFields,exitCode:Number6,stderr:String5}){}class SkillsCliMalformedOutput extends TaggedErrorClass()("SkillsCliMalformedOutput",{...skillsCliFailureFields,stdout:String5}){}class SkillsCliTimeout extends TaggedErrorClass()("SkillsCliTimeout",{...skillsCliFailureFields,timeoutMs:Number6}){}class SkillsCliUnavailable extends TaggedErrorClass()("SkillsCliUnavailable",{...skillsCliFailureFields,executable:String5}){}class SkillsCliUnsupportedVersion extends TaggedErrorClass()("SkillsCliUnsupportedVersion",{...skillsCliFailureFields,minimumVersion:String5,version:String5}){}var SkillsCli=Service("@punks/cli/features/operator-skill/SkillsCli");var OperatorSkillOperations=Service("@punks/cli/features/operator-skill/OperatorSkillOperations");var runOperatorSkillApplication=fn2("OperatorSkill.run")(function*runOperatorSkillApplication2(action2){const operations=yield*OperatorSkillOperations;return yield*operations.run(action2)});var isWithinCanonicalPath=(candidate,root)=>candidate===root||candidate.startsWith(root.endsWith("/")?root:`${root}/`)||candidate.startsWith(root.endsWith("\\")?root:`${root}\\`);var installedOperatorSkillCopyIdentity=(copy3)=>JSON.stringify([copy3.scope,copy3.scope==="project-local"?copy3.projectRoot:"",copy3.version,copy3.source,copy3.revision,copy3.compatibility,[...copy3.boundAgents].toSorted()]);var compareText=(left,right)=>left<right?-1:Number(left>right);var compareCopyIdentity=(left,right)=>{const leftIdentity=installedOperatorSkillCopyIdentity(left);const rightIdentity=installedOperatorSkillCopyIdentity(right);return compareText(leftIdentity,rightIdentity)};var sortCopies=(copies)=>copies.toSorted(compareCopyIdentity);var failureIdentity=(failure)=>JSON.stringify([failure.scope,failure.scope==="project-local"?failure.projectRoot:"",failure.reason,failure.message]);var resolveInstalledOperatorSkillState=(input2)=>{const failures=[];const copies=[];for(const inspection of input2.inspections){if(inspection._tag==="DetectionFailed"){failures.push(inspection);continue}if(inspection.scope==="global"){copies.push(...inspection.copies.map((copy3)=>({...copy3,boundAgents:[...copy3.boundAgents].toSorted()})));continue}for(const copy3 of inspection.copies){if(copy3.projectRoot!==inspection.projectRoot){failures.push({_tag:"DetectionFailed",message:`Project-local copy root ${copy3.projectRoot} does not match inspection root ${inspection.projectRoot}`,projectRoot:inspection.projectRoot,reason:"ProjectRootMismatch",scope:"project-local"});continue}copies.push({...copy3,boundAgents:[...copy3.boundAgents].toSorted(),projectRoot:inspection.projectRoot})}}const detected=sortCopies(copies);const incompatible=sortCopies(copies.filter((copy3)=>copy3.compatibility==="incompatible"));if(failures.length>0){return{_tag:"DetectionFailed",detected,failures:failures.toSorted((left,right)=>compareText(failureIdentity(left),failureIdentity(right))),incompatible}}const candidates=detected.filter((copy3)=>copy3.boundAgents.includes(input2.activeAgent)&&(copy3.scope==="global"||isWithinCanonicalPath(input2.cwd,copy3.projectRoot))).toSorted((left,right)=>Number(left.scope==="global")-Number(right.scope==="global"));const[effective]=candidates;if(effective===undefined){return{_tag:"Absent",detected,incompatible}}const topCandidates=candidates.filter((copy3)=>copy3.scope===effective.scope);if(topCandidates.some((copy3)=>installedOperatorSkillCopyIdentity(copy3)!==installedOperatorSkillCopyIdentity(effective))){return{_tag:"Ambiguous",candidates:topCandidates.toSorted(compareCopyIdentity),incompatible,shadowed:sortCopies(candidates.slice(topCandidates.length))}}return{_tag:"Resolved",effective,incompatible,shadowed:sortCopies(candidates.slice(1))}};var operatorSkillScopeCwd=(scope3,input2)=>scope3==="global"?input2.cwd:input2.projectRoot;var parseSemanticVersion=(value5)=>{const match8=/^(?<major>0|[1-9]\d*)\.(?<minor>0|[1-9]\d*)\.(?<patch>0|[1-9]\d*)(?:-(?<prerelease>[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u.exec(value5);const groups=match8?.groups;const prerelease=groups?.prerelease?.split(".");if(groups===undefined||prerelease?.some((identifier2)=>/^\d+$/u.test(identifier2)&&!/^(?:0|[1-9]\d*)$/u.test(identifier2))){return}return{core:[groups.major,groups.minor,groups.patch],prerelease}};var compareIdentifiers=(left,right)=>{if(left===right){return 0}return left<right?-1:1};var compareNumericIdentifiers=(left,right)=>left.length-right.length||compareIdentifiers(left,right);var comparePrerelease=(left,right)=>{if(left===undefined||right===undefined){if(left===right){return 0}return left===undefined?1:-1}const length=Math.max(left.length,right.length);for(let index2=0;index2<length;index2+=1){const leftIdentifier=left[index2];const rightIdentifier=right[index2];if(leftIdentifier===undefined||rightIdentifier===undefined){if(leftIdentifier===rightIdentifier){return 0}return leftIdentifier===undefined?-1:1}if(leftIdentifier===rightIdentifier){continue}const leftIsNumeric=/^\d+$/u.test(leftIdentifier);const rightIsNumeric=/^\d+$/u.test(rightIdentifier);if(leftIsNumeric&&rightIsNumeric){return compareNumericIdentifiers(leftIdentifier,rightIdentifier)}if(leftIsNumeric!==rightIsNumeric){return leftIsNumeric?-1:1}return compareIdentifiers(leftIdentifier,rightIdentifier)}return 0};var compareSemanticVersions=(left,right)=>{const parsedLeft=parseSemanticVersion(left);const parsedRight=parseSemanticVersion(right);if(parsedLeft===undefined||parsedRight===undefined){return}for(let index2=0;index2<parsedLeft.core.length;index2+=1){const compared=compareNumericIdentifiers(parsedLeft.core[index2],parsedRight.core[index2]);if(compared!==0){return compared}}return comparePrerelease(parsedLeft.prerelease,parsedRight.prerelease)};var satisfiesSemanticVersionRange=(version3,minimum,maximumExclusive)=>{const comparedToMinimum=compareSemanticVersions(version3,minimum);const comparedToMaximum=compareSemanticVersions(version3,maximumExclusive);return comparedToMinimum!==undefined&&comparedToMaximum!==undefined&&comparedToMinimum>=0&&comparedToMaximum<0};var authoritativeContentManifest=Object.freeze([Object.freeze({path:"SKILL.md",sha256:"aee7ff55492ba810ca75bfbc8bbf5d4a14695828634c3fb1c6aea0a895589b98"}),Object.freeze({path:"references/commands.md",sha256:"62e07c52acd6add81a8feccbe39eb99521d6a2c9682d97e940bcc39a5e705e1a"}),Object.freeze({path:"references/post-command-flow.md",sha256:"0975f458b8636de0ef0d26e1dbc3c353208acc439fa47ebe2f261181e94815a8"})]);var authoritativeOperatorSkillTarget=Object.freeze({cliCompatibility:Object.freeze({maximumExclusive:"4.0.0",minimum:"3.0.0-beta.0"}),contentManifest:authoritativeContentManifest,revision:"09a6f3c6f9a7ed62a7e4abf0411f8a0f4f993e1d",source:"https://github.com/wearedevpunks/skills/tree/09a6f3c6f9a7ed62a7e4abf0411f8a0f4f993e1d/skills/agnostic/cli/hi-cli",version:"1.1.0"});var immutableRevisionPattern=/^[0-9a-f]{40}$/u;var authoritativeSourceRoot="https://github.com/wearedevpunks/skills";var operatorSkillPath="skills/agnostic/cli/hi-cli";var targetIsIncomplete=(target)=>target.source.trim()===""||target.version.trim()===""||target.revision.trim()===""||target.cliCompatibility.minimum.trim()===""||target.cliCompatibility.maximumExclusive.trim()===""||target.contentManifest.length===0||target.contentManifest.some((entry)=>entry.path.trim()===""||entry.sha256.trim()==="");var validateTarget=(target)=>{if(targetIsIncomplete(target)){return"IncompleteIdentity"}if(!immutableRevisionPattern.test(target.revision)){return"MovingRevision"}const immutableSource=`${authoritativeSourceRoot}/tree/${target.revision}/${operatorSkillPath}`;if(target.source!==immutableSource){return target.source.startsWith(authoritativeSourceRoot)?"SourceRevisionMismatch":"NonAuthoritativeSource"}const version3=compareSemanticVersions(target.version,target.version);const rangeOrder=compareSemanticVersions(target.cliCompatibility.minimum,target.cliCompatibility.maximumExclusive);if(version3===undefined||rangeOrder===undefined||rangeOrder>=0){return"InvalidVersion"}if(target.source!==authoritativeOperatorSkillTarget.source||target.version!==authoritativeOperatorSkillTarget.version||target.revision!==authoritativeOperatorSkillTarget.revision||target.cliCompatibility.minimum!==authoritativeOperatorSkillTarget.cliCompatibility.minimum||target.cliCompatibility.maximumExclusive!==authoritativeOperatorSkillTarget.cliCompatibility.maximumExclusive||JSON.stringify(target.contentManifest)!==JSON.stringify(authoritativeOperatorSkillTarget.contentManifest)){return"NonAuthoritativeIdentity"}return};var resolveOperatorSkillTarget=(input2)=>{if(compareSemanticVersions(input2.activeCliVersion,input2.activeCliVersion)===undefined){return{_tag:"NoCompatibleTarget",activeCliVersion:input2.activeCliVersion}}const compatibleIndexes=[];for(const[candidateIndex,candidate]of input2.candidates.entries()){const invalidReason=validateTarget(candidate);if(invalidReason!==undefined){return{_tag:"InvalidTarget",candidateIndex,reason:invalidReason}}if(satisfiesSemanticVersionRange(input2.activeCliVersion,candidate.cliCompatibility.minimum,candidate.cliCompatibility.maximumExclusive)){compatibleIndexes.push(candidateIndex)}}if(compatibleIndexes.length===0){return{_tag:"NoCompatibleTarget",activeCliVersion:input2.activeCliVersion}}if(compatibleIndexes.length>1){return{_tag:"AmbiguousCompatibleTargets",activeCliVersion:input2.activeCliVersion,candidateIndexes:compatibleIndexes}}return{_tag:"Resolved",target:authoritativeOperatorSkillTarget}};var compatibilityFor=(activeCliVersion,skill)=>satisfiesSemanticVersionRange(activeCliVersion,skill.cliCompatibility.minimum,skill.cliCompatibility.maximumExclusive)?"compatible":"incompatible";var isVerified=(skill)=>("version"in skill);var mapGlobalCopy=(activeCliVersion,skill)=>({boundAgents:[...skill.agents].toSorted(),compatibility:compatibilityFor(activeCliVersion,skill),revision:skill.revision,scope:"global",source:skill.source,version:skill.version});var mapProjectCopy=(activeCliVersion,projectRoot,skill)=>({boundAgents:[...skill.agents].toSorted(),compatibility:compatibilityFor(activeCliVersion,skill),projectRoot,revision:skill.revision,scope:"project-local",source:skill.source,version:skill.version});var inspectListedSkills=(scope3,input2,skills)=>{const operatorSkills=skills.filter((skill)=>skill.name==="hi-cli"&&isVerified(skill));const legacySkills=skills.filter((skill)=>skill.name==="dp-cli");if(scope3==="global"){return{_tag:"Inspected",copies:operatorSkills.map((skill)=>mapGlobalCopy(input2.activeCliVersion,skill)),legacy:legacySkills.map((skill)=>({boundAgents:[...skill.agents].toSorted(),path:skill.path,scope:scope3})),scope:scope3}}return{_tag:"Inspected",copies:operatorSkills.map((skill)=>mapProjectCopy(input2.activeCliVersion,input2.projectRoot,skill)),legacy:legacySkills.map((skill)=>({boundAgents:[...skill.agents].toSorted(),path:skill.path,projectRoot:input2.projectRoot,scope:scope3})),projectRoot:input2.projectRoot,scope:scope3}};var failedInspection=(scope3,input2,failure)=>{const verifiedSkills=failure._tag==="SkillsCliVerificationFailure"||failure._tag==="SkillsCliBindingFailure"?failure.verifiedSkills:[];if(scope3==="global"){return{_tag:"InspectionFailed",copies:verifiedSkills.map((skill)=>mapGlobalCopy(input2.activeCliVersion,skill)),failure,legacy:[],scope:scope3}}return{_tag:"InspectionFailed",copies:verifiedSkills.map((skill)=>mapProjectCopy(input2.activeCliVersion,input2.projectRoot,skill)),failure,legacy:[],projectRoot:input2.projectRoot,scope:scope3}};var installedInspections=(inspections)=>inspections.flatMap((inspection)=>{const detected=inspection.scope==="global"?{_tag:"Detected",copies:inspection.copies,scope:"global"}:{_tag:"Detected",copies:inspection.copies,projectRoot:inspection.projectRoot,scope:"project-local"};if(inspection._tag==="Inspected"){return[detected]}const failure=inspection.scope==="global"?{_tag:"DetectionFailed",message:inspection.failure.message,reason:"ListingFailed",scope:"global"}:{_tag:"DetectionFailed",message:inspection.failure.message,projectRoot:inspection.projectRoot,reason:"ListingFailed",scope:"project-local"};return inspection.copies.length===0?[failure]:[detected,failure]});var collectLegacyCopies=(inspections)=>{const copies=[];for(const inspection of inspections){copies.push(...inspection.legacy)}return copies};var inspectOperatorSkillLifecycle=fn2("OperatorSkillLifecycle.status")(function*inspectOperatorSkillLifecycle2(input2){const resolution=resolveOperatorSkillTarget({activeCliVersion:input2.activeCliVersion,candidates:[authoritativeOperatorSkillTarget]});if(resolution._tag!=="Resolved"){return{_tag:"TargetResolutionFailed",resolution}}const skillsCli=yield*SkillsCli;const[globalResult,projectResult]=yield*all2([result2(skillsCli.list({agent:input2.activeAgent,cwd:operatorSkillScopeCwd("global",input2),scope:"global",target:resolution.target})),result2(skillsCli.list({agent:input2.activeAgent,cwd:operatorSkillScopeCwd("project-local",input2),scope:"project",target:resolution.target}))],{concurrency:"unbounded"});const inspections=[isFailure2(globalResult)?failedInspection("global",input2,globalResult.failure):inspectListedSkills("global",input2,globalResult.success),isFailure2(projectResult)?failedInspection("project-local",input2,projectResult.failure):inspectListedSkills("project-local",input2,projectResult.success)];const installed=resolveInstalledOperatorSkillState({activeAgent:input2.activeAgent,cwd:input2.cwd,inspections:installedInspections(inspections)});return{_tag:"Inspected",inspections,installed,legacy:collectLegacyCopies(inspections),target:resolution.target}});var retryFor=(operation,scope3,input2,target)=>Object.freeze({input:Object.freeze({...input2}),operation,scope:scope3,target});var inspectionFor=(status2,scope3)=>status2.inspections.find((inspection)=>inspection.scope===scope3);var copyMatchesTarget=(copy3,target)=>copy3.version===target.version&©3.source===target.source&©3.revision===target.revision&©3.compatibility==="compatible";var copyAppliesToScope=(copy3,input2)=>copy3.boundAgents.includes(input2.activeAgent)&&(copy3.scope==="global"||copy3.projectRoot===input2.projectRoot);var targetCopy=(inspection,input2,target)=>inspection.copies.find((copy3)=>copyMatchesTarget(copy3,target)&©AppliesToScope(copy3,input2));var hasCompetingCopyIdentity=(inspection,copy3,input2)=>inspection.copies.some((candidate)=>copyAppliesToScope(candidate,input2)&&installedOperatorSkillCopyIdentity(candidate)!==installedOperatorSkillCopyIdentity(copy3));var verifyOperatorSkillScope=(scope3,input2,target,verification)=>{if(verification._tag==="TargetResolutionFailed"){return{_tag:"Unverified",reason:"TargetResolutionFailed",scope:scope3,verification}}const inspection=inspectionFor(verification,scope3);if(inspection?._tag==="InspectionFailed"){return{_tag:"Unverified",failure:inspection.failure,reason:"InspectionFailed",scope:scope3,verification}}if(inspection!==undefined){const copy3=targetCopy(inspection,input2,target);if(copy3!==undefined){if(hasCompetingCopyIdentity(inspection,copy3,input2)){return{_tag:"Unverified",reason:"CompetingCopyObserved",scope:scope3,verification}}return{_tag:"Verified",copy:copy3,scope:scope3,verification}}}return{_tag:"Unverified",reason:"TargetNotObserved",scope:scope3,verification}};var ensureAndVerifyOperatorSkillScope=fn2("OperatorSkillLifecycle.ensureAndVerifyScope")(function*ensureAndVerifyOperatorSkillScope2(scope3,input2,target){const skillsCli=yield*SkillsCli;const write2=yield*result2(skillsCli.install({agent:input2.activeAgent,cwd:operatorSkillScopeCwd(scope3,input2),scope:scope3==="global"?"global":"project",target}));if(isFailure2(write2)){return{_tag:"Failed",failure:write2.failure,scope:scope3}}const verification=yield*inspectOperatorSkillLifecycle(input2);return verifyOperatorSkillScope(scope3,input2,target,verification)});var mutationActionFor=(operation,input2,target,result4)=>{const retry5=retryFor(operation,result4.scope,input2,target);if(result4._tag==="Failed"){return{_tag:"Failed",failure:result4.failure,operation,phase:"write",retry:retry5,scope:result4.scope}}if(result4._tag==="Unverified"){return{...result4,operation,retry:retry5}}return{...result4,operation}};var inspectionDetectedOperatorSkill=(inspection)=>inspection.copies.length>0||inspection._tag==="InspectionFailed"&&(inspection.failure._tag==="SkillsCliVerificationFailure"||inspection.failure._tag==="SkillsCliBindingFailure")&&inspection.failure.skillName==="hi-cli";var inspectionScopeIsUnknown=(inspection)=>inspection._tag==="InspectionFailed"&&!inspectionDetectedOperatorSkill(inspection);var alreadyVerifiedGlobal=(before,input2)=>{const inspection=inspectionFor(before,"global");if(inspection?._tag!=="Inspected"){return}const copy3=targetCopy(inspection,input2,before.target);if(copy3===undefined||hasCompetingCopyIdentity(inspection,copy3,input2)){return}return{_tag:"AlreadyVerified",copy:copy3,operation:"install",scope:"global",verification:before}};var unknownScopeFailures=(operation,before,input2)=>before.inspections.flatMap((inspection)=>inspectionScopeIsUnknown(inspection)&&(operation==="update"||inspection.scope==="global")?[{_tag:"Failed",failure:inspection.failure,operation,phase:"inspection",retry:retryFor(operation,inspection.scope,input2,before.target),scope:inspection.scope}]:[]);var scopesToMutate=(operation,before)=>{if(operation==="install"){const globalIsUnknown=before.inspections.some((inspection)=>inspection.scope==="global"&&inspectionScopeIsUnknown(inspection));return globalIsUnknown?[]:["global"]}return before.inspections.filter(inspectionDetectedOperatorSkill).map((inspection)=>inspection.scope)};var mutateOperatorSkill=fn2("OperatorSkillLifecycle.mutate")(function*mutateOperatorSkill2(operation,input2){const before=yield*inspectOperatorSkillLifecycle(input2);if(before._tag==="TargetResolutionFailed"){return{_tag:"TargetResolutionFailed",actions:[],before,operation,reload:{_tag:"NotRequired"}}}const existingGlobal=operation==="install"?alreadyVerifiedGlobal(before,input2):undefined;const actions=[...unknownScopeFailures(operation,before,input2),...existingGlobal===undefined?[]:[existingGlobal]];let wrote=false;const scopes=existingGlobal===undefined?scopesToMutate(operation,before):[];for(const scope3 of scopes){const ensured=yield*ensureAndVerifyOperatorSkillScope(scope3,input2,before.target);wrote||=ensured._tag!=="Failed";actions.push(mutationActionFor(operation,input2,before.target,ensured))}return{_tag:"Completed",actions,before,operation,reload:wrote?{_tag:"ReloadRequired",skill:"hi-cli"}:{_tag:"NotRequired"},target:before.target}});var installOperatorSkill=fn2("OperatorSkillLifecycle.install")(function*installOperatorSkill2(input2){return yield*mutateOperatorSkill("install",input2)});var updateOperatorSkill=fn2("OperatorSkillLifecycle.update")(function*updateOperatorSkill2(input2){return yield*mutateOperatorSkill("update",input2)});var migrationRetry=(scope3,input2,target,phase,affectedScopes)=>Object.freeze({affectedScopes:Object.freeze([...affectedScopes]),input:Object.freeze({...input2}),operation:"migrate",phase,scope:scope3,target});var affectedScopes=(before,input2)=>["global","project-local"].filter((scope3)=>(scope3==="global"||isWithinCanonicalPath(input2.cwd,input2.projectRoot))&&before.inspections.some((inspection)=>inspection.scope===scope3&&inspection.legacy.some((copy3)=>copy3.boundAgents.includes(input2.activeAgent))));var scopeApplies=(scope3,input2)=>scope3==="global"||isWithinCanonicalPath(input2.cwd,input2.projectRoot);var recoverableScopes=(input2,scopes)=>["global","project-local"].filter((scope3)=>scopes.includes(scope3)&&scopeApplies(scope3,input2));var targetIdentity=(target)=>JSON.stringify([target.source,target.version,target.revision,target.cliCompatibility,target.contentManifest]);var legacyIdentity=(copy3)=>JSON.stringify([copy3.scope,copy3.scope==="project-local"?copy3.projectRoot:"",copy3.path,[...copy3.boundAgents].toSorted()]);var inspectedLegacyCopiesFor=(status2,scope3)=>{if(status2._tag!=="Inspected"){return}const inspection=status2.inspections.find((candidate)=>candidate.scope===scope3);return inspection?._tag==="Inspected"?inspection.legacy:undefined};var legacyCopiesFor=(status2,scope3)=>inspectedLegacyCopiesFor(status2,scope3)??[];var legacyCopiesMatch=(left,right)=>JSON.stringify(left.map(legacyIdentity).toSorted())===JSON.stringify(right.map(legacyIdentity).toSorted());var unrelatedLegacyResiduals=(copies,activeAgent)=>copies.flatMap((copy3)=>{const boundAgents=copy3.boundAgents.filter((agent)=>agent!==activeAgent);return boundAgents.length===0?[]:[{...copy3,boundAgents}]});var replacementAction=(result4,input2,target,scopes,wrote=true)=>{const retry5=migrationRetry(result4.scope,input2,target,"replacement",scopes);if(result4._tag==="Failed"){return{_tag:"ReplacementFailed",failure:result4.failure,retry:retry5,scope:result4.scope}}if(result4._tag==="Unverified"){return{_tag:"ReplacementUnverified",...result4.failure===undefined?{}:{failure:result4.failure},reason:result4.reason,retry:retry5,scope:result4.scope,verification:result4.verification}}return{_tag:"ReplacementVerified",copy:result4.copy,scope:result4.scope,verification:result4.verification,wrote}};var reloadGuidance=(wrote)=>wrote?{_tag:"ReloadRequired",skill:"hi-cli"}:{_tag:"NotRequired"};var verifyBarrierCopy=(scope3,input2,target,verification,expected)=>{const observed=verifyOperatorSkillScope(scope3,input2,target,verification);if(observed._tag!=="Verified"){return observed}if(expected===undefined||installedOperatorSkillCopyIdentity(observed.copy)!==installedOperatorSkillCopyIdentity(expected)){return{_tag:"Unverified",reason:"ReplacementChanged",scope:scope3,verification}}return observed};var legacyRemovalReason=(reason)=>{if(reason==="InspectionFailed"){return"InspectionFailed"}return reason==="ReplacementChanged"?"ReplacementChanged":"ReplacementNotVerified"};var validateAffectedBarriers=(input2)=>(()=>{let blockingLoss;return input2.scopes.flatMap((scope3,scopeIndex)=>{const pending=scopeIndex>input2.afterIndex;const checked=verifyBarrierCopy(scope3,input2.migrationInput,input2.target,input2.verification,input2.barrierCopies.get(scope3));if(checked._tag==="Verified"){if(!pending||blockingLoss===undefined||input2.refusedScopes.has(scope3)){return[]}input2.refusedScopes.add(scope3);return[{_tag:"LegacyRemovalRefused",barrierReason:blockingLoss.reason,barrierScope:blockingLoss.scope,...blockingLoss.failure===undefined?{}:{failure:blockingLoss.failure},reason:"BarrierLost",retry:migrationRetry(scope3,input2.migrationInput,input2.target,"removal",input2.scopes),scope:scope3,verification:input2.verification}]}if(pending&&input2.refusedScopes.has(scope3)){return[]}const failure="failure"in checked&&checked.failure!==undefined?{failure:checked.failure}:{};if(pending){input2.refusedScopes.add(scope3);return[{_tag:"LegacyRemovalRefused",barrierReason:checked.reason,barrierScope:scope3,...failure,reason:"BarrierLost",retry:migrationRetry(scope3,input2.migrationInput,input2.target,"removal",input2.scopes),scope:scope3,verification:input2.verification}]}blockingLoss={reason:checked.reason,scope:scope3,...failure};if(input2.lostBarrierScopes.has(scope3)){return[]}input2.lostBarrierScopes.add(scope3);return[{_tag:"RemovalBarrierLost",afterScope:input2.afterScope,barrierReason:checked.reason,...failure,phase:input2.phase,position:scopeIndex===input2.afterIndex?"current":"prior",retry:migrationRetry(scope3,input2.migrationInput,input2.target,"removal",input2.scopes),scope:scope3,verification:input2.verification}]})})();var validatePeerLegacySnapshots=(input2)=>input2.scopes.flatMap((scope3,scopeIndex)=>{if(scopeIndex===input2.afterIndex){return[]}const observed=inspectedLegacyCopiesFor(input2.verification,scope3);if(observed===undefined){return[]}const activeChanged=!legacyCopiesMatch(input2.activeSnapshots.get(scope3)??[],observed.filter((copy3)=>copy3.boundAgents.includes(input2.migrationInput.activeAgent)));const unrelatedChanged=!legacyCopiesMatch(input2.unrelatedSnapshots.get(scope3)??[],unrelatedLegacyResiduals(observed,input2.migrationInput.activeAgent));if(!activeChanged&&!unrelatedChanged){return[]}const legacyReason=unrelatedChanged?"UnrelatedLegacyChanged":"ActiveLegacyChanged";const retry5=migrationRetry(scope3,input2.migrationInput,input2.target,"removal",input2.scopes);if(scopeIndex>input2.afterIndex){if(input2.refusedScopes.has(scope3)){return[]}input2.refusedScopes.add(scope3);return[{_tag:"LegacyRemovalRefused",legacyReason,reason:"LegacyChanged",retry:retry5,scope:scope3,verification:input2.verification}]}if(input2.reportedScopes.has(scope3)){return[]}input2.reportedScopes.add(scope3);return[{_tag:"LegacyRemovalUnverified",reason:activeChanged?"LegacyChangedAfterRemoval":"UnrelatedLegacyChanged",retry:retry5,scope:scope3,verification:input2.verification}]});var handleFailedLegacyRemoval=fn2("OperatorSkillLifecycle.handleFailedLegacyRemoval")(function*handleFailedLegacyRemoval2(context4,failure){const{activeLegacyCopies,barrierCopies,input:input2,lostBarrierScopes,refusedScopes,reportedLegacyScopes,retry:retry5,scope:scope3,scopeIndex,scopes,target,unrelatedLegacyCopies}=context4;const actions=[{_tag:"LegacyRemovalFailed",failure,retry:retry5,scope:scope3}];let wrote=false;const verification=yield*inspectOperatorSkillLifecycle(input2);const observedLegacy=inspectedLegacyCopiesFor(verification,scope3);const activeLegacyChanged=observedLegacy!==undefined&&!legacyCopiesMatch(activeLegacyCopies.get(scope3)??[],observedLegacy.filter((copy3)=>copy3.boundAgents.includes(input2.activeAgent)));const unrelatedLegacyChanged=observedLegacy!==undefined&&!legacyCopiesMatch(unrelatedLegacyCopies.get(scope3)??[],unrelatedLegacyResiduals(observedLegacy,input2.activeAgent));if(activeLegacyChanged||unrelatedLegacyChanged){wrote=true;actions.push({_tag:"LegacyRemovalUnverified",reason:activeLegacyChanged?"LegacyChangedAfterFailure":"UnrelatedLegacyChanged",retry:retry5,scope:scope3,verification})}const peerLegacyActions=validatePeerLegacySnapshots({activeSnapshots:activeLegacyCopies,afterIndex:scopeIndex,migrationInput:input2,refusedScopes,reportedScopes:reportedLegacyScopes,scopes,target,unrelatedSnapshots:unrelatedLegacyCopies,verification});wrote||=peerLegacyActions.length>0;actions.push(...peerLegacyActions);const barrierActions=validateAffectedBarriers({afterIndex:scopeIndex,afterScope:scope3,barrierCopies,lostBarrierScopes,migrationInput:input2,phase:"remove-failed",refusedScopes,scopes,target,verification});wrote||=barrierActions.some((action2)=>action2.barrierReason!=="InspectionFailed"&&action2.barrierReason!=="TargetResolutionFailed");actions.push(...barrierActions);if(observedLegacy!==undefined){activeLegacyCopies.set(scope3,observedLegacy.filter((copy3)=>copy3.boundAgents.includes(input2.activeAgent)));unrelatedLegacyCopies.set(scope3,unrelatedLegacyResiduals(observedLegacy,input2.activeAgent))}return{actions,wrote}});var handleSuccessfulLegacyRemoval=fn2("OperatorSkillLifecycle.handleSuccessfulLegacyRemoval")(function*handleSuccessfulLegacyRemoval2(context4){const{activeLegacyCopies,barrierCopies,input:input2,lostBarrierScopes,refusedScopes,reportedLegacyScopes,retry:retry5,scope:scope3,scopeIndex,scopes,target,unrelatedLegacyCopies}=context4;const verification=yield*inspectOperatorSkillLifecycle(input2);let currentAction;if(verification._tag==="TargetResolutionFailed"){currentAction={_tag:"LegacyRemovalUnverified",reason:"ReplacementNotVerified",retry:retry5,scope:scope3,verification}}else{const inspection=verification.inspections.find((candidate)=>candidate.scope===scope3);const observedLegacy=inspectedLegacyCopiesFor(verification,scope3);const unrelatedLegacyChanged=observedLegacy!==undefined&&!legacyCopiesMatch(unrelatedLegacyCopies.get(scope3)??[],unrelatedLegacyResiduals(observedLegacy,input2.activeAgent));if(unrelatedLegacyChanged){currentAction={_tag:"LegacyRemovalUnverified",reason:"UnrelatedLegacyChanged",retry:retry5,scope:scope3,verification}}else if(inspection!==undefined&&inspection.legacy.some((copy3)=>copy3.boundAgents.includes(input2.activeAgent))){currentAction={_tag:"LegacyRemovalUnverified",reason:"LegacyStillPresent",retry:retry5,scope:scope3,verification}}else{const replacementCheck=verifyBarrierCopy(scope3,input2,target,verification,barrierCopies.get(scope3));currentAction=replacementCheck._tag==="Verified"?{_tag:"LegacyRemoved",scope:scope3,verification}:{_tag:"LegacyRemovalUnverified",..."failure"in replacementCheck&&replacementCheck.failure!==undefined?{failure:replacementCheck.failure}:{},reason:legacyRemovalReason(replacementCheck.reason),retry:retry5,scope:scope3,verification}}}const actions=[currentAction,...validatePeerLegacySnapshots({activeSnapshots:activeLegacyCopies,afterIndex:scopeIndex,migrationInput:input2,refusedScopes,reportedScopes:reportedLegacyScopes,scopes,target,unrelatedSnapshots:unrelatedLegacyCopies,verification})];const observedCurrentLegacy=inspectedLegacyCopiesFor(verification,scope3);if(observedCurrentLegacy!==undefined){activeLegacyCopies.set(scope3,observedCurrentLegacy.filter((copy3)=>copy3.boundAgents.includes(input2.activeAgent)))}actions.push(...validateAffectedBarriers({afterIndex:scopeIndex,afterScope:scope3,barrierCopies,lostBarrierScopes,migrationInput:input2,phase:"remove-succeeded",refusedScopes,scopes,target,verification}));return actions});var prepareMigration=(before,input2,recoveryScopes,recoveryPhase)=>{const observedScopes=affectedScopes(before,input2);const recoveryScopeLimit=recoveryScopes===undefined?undefined:recoverableScopes(input2,recoveryScopes);let scopes=observedScopes;if(recoveryScopeLimit!==undefined){scopes=recoveryPhase==="preflight"?observedScopes.filter((scope3)=>recoveryScopeLimit.includes(scope3)):recoveryScopeLimit}const retryScopes=recoveryScopeLimit===undefined?recoverableScopes(input2,[...scopes,...before.inspections.flatMap((inspection)=>inspection._tag==="InspectionFailed"?[inspection.scope]:[])]):recoveryScopeLimit;const preflightFailures=before.inspections.flatMap((inspection)=>inspection._tag==="InspectionFailed"&&scopeApplies(inspection.scope,input2)&&(recoveryScopeLimit===undefined||recoveryScopeLimit.includes(inspection.scope))?[{_tag:"PreflightFailed",failure:inspection.failure,retry:migrationRetry(inspection.scope,input2,before.target,"preflight",retryScopes),scope:inspection.scope}]:[]);return{preflightFailures,scopes}};var ensureReplacementBarriers=fn2("OperatorSkillLifecycle.ensureReplacementBarriers")(function*ensureReplacementBarriers2(scopes,input2,before){const actions=[];let wrote=false;let barrierFailed=false;for(const scope3 of scopes){const existing=verifyOperatorSkillScope(scope3,input2,before.target,before);if(existing._tag==="Verified"){actions.push({_tag:"ReplacementVerified",copy:existing.copy,scope:scope3,verification:existing.verification,wrote:false});continue}const replacement=yield*ensureAndVerifyOperatorSkillScope(scope3,input2,before.target);wrote||=replacement._tag!=="Failed";barrierFailed||=replacement._tag!=="Verified";actions.push(replacementAction(replacement,input2,before.target,scopes))}return{actions,barrierFailed,wrote}});var inspectReplacementBarrier=fn2("OperatorSkillLifecycle.inspectReplacementBarrier")(function*inspectReplacementBarrier2(scopes,input2,target,recoveryScopes){const status2=yield*inspectOperatorSkillLifecycle(input2);const failedInspections=status2._tag==="Inspected"?status2.inspections.filter((inspection)=>inspection._tag==="InspectionFailed"&&scopeApplies(inspection.scope,input2)&&(recoveryScopes===undefined||scopes.includes(inspection.scope))):[];const failedScopes=new Set(failedInspections.map((inspection)=>inspection.scope));const verifications=scopes.flatMap((scope3)=>{if(failedScopes.has(scope3)){return[]}const verification=verifyOperatorSkillScope(scope3,input2,target,status2);return[{scope:scope3,verification}]});const actions=[...failedInspections.map((inspection)=>({_tag:"BarrierInspectionFailed",failure:inspection.failure,retry:migrationRetry(inspection.scope,input2,target,"barrier",scopes),scope:inspection.scope})),...verifications.flatMap(({scope:scope3,verification})=>verification._tag==="Unverified"?[{_tag:"BarrierUnverified",...verification.failure===undefined?{}:{failure:verification.failure},reason:verification.reason,retry:migrationRetry(scope3,input2,target,"barrier",scopes),scope:scope3,verification:verification.verification}]:[])];return{actions,status:status2,verifications}});var migrateLegacyOperatorSkillPolicy=fn2("OperatorSkillLifecycle.migratePolicy")(function*migrateLegacyOperatorSkillPolicy2(input2,recoveryScopes,expectedTarget,recoveryPhase){const before=yield*inspectOperatorSkillLifecycle(input2);if(before._tag==="TargetResolutionFailed"){return{_tag:"TargetResolutionFailed",actions:[],before,reload:{_tag:"NotRequired"}}}if(expectedTarget!==undefined&&targetIdentity(expectedTarget)!==targetIdentity(before.target)){return{_tag:"RetryTargetChanged",actions:[],expected:expectedTarget,observed:before.target,reload:{_tag:"NotRequired"}}}const{preflightFailures,scopes}=prepareMigration(before,input2,recoveryScopes,recoveryPhase);if(preflightFailures.length>0){return{_tag:"Refused",actions:preflightFailures,before,reason:"PreflightUnknown",reload:{_tag:"NotRequired"},target:before.target}}if(scopes.length===0){return{_tag:"Completed",actions:[],before,reload:{_tag:"NotRequired"},target:before.target}}const replacement=yield*ensureReplacementBarriers(scopes,input2,before);const actions=[...replacement.actions];let{wrote}=replacement;if(replacement.barrierFailed){return{_tag:"Refused",actions,before,reason:"ReplacementBarrierFailed",reload:reloadGuidance(wrote),target:before.target}}const barrier=yield*inspectReplacementBarrier(scopes,input2,before.target,recoveryScopes);const finalBarrier=barrier.status;const finalVerifications=barrier.verifications;actions.push(...barrier.actions);if(barrier.actions.length>0){return{_tag:"Refused",actions,before,reason:"ReplacementBarrierFailed",reload:reloadGuidance(wrote),target:before.target}}const barrierCopies=new Map(finalVerifications.flatMap(({scope:scope3,verification})=>verification._tag==="Verified"?[[scope3,verification.copy]]:[]));const activeLegacyCopies=new Map(scopes.map((scope3)=>[scope3,legacyCopiesFor(finalBarrier,scope3).filter((copy3)=>copy3.boundAgents.includes(input2.activeAgent))]));const unrelatedLegacyCopies=new Map(scopes.map((scope3)=>[scope3,unrelatedLegacyResiduals(legacyCopiesFor(finalBarrier,scope3),input2.activeAgent)]));const skillsCli=yield*SkillsCli;const refusedScopes=new Set;const lostBarrierScopes=new Set;const reportedLegacyScopes=new Set;for(const scope3 of scopes){if(!(activeLegacyCopies.get(scope3)??[]).some((copy3)=>copy3.boundAgents.some((agent)=>agent!==input2.activeAgent))){continue}refusedScopes.add(scope3);actions.push({_tag:"LegacyRemovalRefused",legacyReason:"SharedResidualUnverifiable",reason:"ResidualBindingsUnverifiable",retry:migrationRetry(scope3,input2,before.target,"removal",scopes),scope:scope3,verification:finalBarrier})}const removalScopes=scopes.filter((scope3)=>(activeLegacyCopies.get(scope3)??[]).length>0);for(const scope3 of removalScopes){const scopeIndex=scopes.indexOf(scope3);if(refusedScopes.has(scope3)){continue}const remove7=yield*result2(skillsCli.remove({agent:input2.activeAgent,cwd:operatorSkillScopeCwd(scope3,input2),name:"dp-cli",scope:scope3==="global"?"global":"project"}));const retry5=migrationRetry(scope3,input2,before.target,"removal",scopes);const context4={activeLegacyCopies,barrierCopies,input:input2,lostBarrierScopes,refusedScopes,reportedLegacyScopes,retry:retry5,scope:scope3,scopeIndex,scopes,target:before.target,unrelatedLegacyCopies};if(isFailure2(remove7)){const failureResult=yield*handleFailedLegacyRemoval(context4,remove7.failure);wrote||=failureResult.wrote;actions.push(...failureResult.actions);continue}wrote=true;actions.push(...yield*handleSuccessfulLegacyRemoval(context4))}return{_tag:"Completed",actions,before,reload:reloadGuidance(wrote),target:before.target}});var migrateLegacyOperatorSkill=fn2("OperatorSkillLifecycle.migrate")(function*migrateLegacyOperatorSkill2(input2){return yield*migrateLegacyOperatorSkillPolicy(input2)});var retryLegacyOperatorSkillMigration=fn2("OperatorSkillLifecycle.retryMigration")(function*retryLegacyOperatorSkillMigration2(retry5,currentInput){return yield*migrateLegacyOperatorSkillPolicy({...retry5.input,activeCliVersion:currentInput.activeCliVersion},retry5.affectedScopes,retry5.target,retry5.phase)});var migrationRetrySchema=Struct({affectedScopes:ArraySchema(Literals(["global","project-local"])),input:Struct({activeAgent:String5,activeCliVersion:String5,cwd:String5,projectRoot:String5}),operation:Literal2("migrate"),phase:Literals(["barrier","preflight","removal","replacement"]),scope:Literals(["global","project-local"]),target:Struct({cliCompatibility:Struct({maximumExclusive:String5,minimum:String5}),contentManifest:ArraySchema(Struct({path:String5,sha256:String5})),revision:String5,source:String5,version:String5})});var mutationRetrySchema=Struct({input:Struct({activeAgent:String5,activeCliVersion:String5,cwd:String5,projectRoot:String5}),operation:Literals(["install","update"]),scope:Literals(["global","project-local"]),target:migrationRetrySchema.fields.target});var encodeMigrationRetry=(retry5)=>Buffer.from(JSON.stringify(retry5),"utf-8").toString("base64url");var decodeMigrationRetry=(token)=>try_3({catch:()=>new InvalidMigrationRetry({message:"Migration retry token is invalid or stale."}),try:()=>decodeUnknownSync2(migrationRetrySchema)(JSON.parse(Buffer.from(token,"base64url").toString("utf-8")))});var encodeMutationRetry=(retry5)=>Buffer.from(JSON.stringify(retry5),"utf-8").toString("base64url");var decodeMutationRetry=(token)=>try_3({catch:()=>new InvalidMutationRetry({message:"Operator mutation retry token is invalid or stale."}),try:()=>decodeUnknownSync2(mutationRetrySchema)(JSON.parse(Buffer.from(token,"base64url").toString("utf-8")))});var targetIdentity2=(target)=>JSON.stringify([target.source,target.version,target.revision,target.cliCompatibility,target.contentManifest]);var retryOperatorSkillMutation=(retry5,action2,currentInput)=>gen2(function*executeMutationRetry(){if(retry5.operation!==action2){return yield*new InvalidMutationRetry({message:`Operator mutation retry is for ${retry5.operation}, not ${action2}.`})}const retryInput={...retry5.input,activeCliVersion:currentInput.activeCliVersion};const before=yield*inspectOperatorSkillLifecycle(retryInput);if(before._tag==="TargetResolutionFailed"){return{_tag:"TargetResolutionFailed",actions:[],before,operation:retry5.operation,reload:{_tag:"NotRequired"}}}if(targetIdentity2(before.target)!==targetIdentity2(retry5.target)){return yield*new InvalidMutationRetry({message:"Operator mutation retry target changed; rerun the operator command."})}if(retry5.operation==="install"&&retry5.scope!=="global"){return yield*new InvalidMutationRetry({message:"Operator install retry scope changed; rerun the operator command."})}const inspection=inspectionFor(before,retry5.scope);if(inspection===undefined){return yield*new InvalidMutationRetry({message:"Operator mutation retry scope changed; rerun the operator command."})}if(inspectionScopeIsUnknown(inspection)){return{_tag:"Completed",actions:[{_tag:"Failed",failure:inspection.failure,operation:retry5.operation,phase:"inspection",retry:retry5,scope:retry5.scope}],before,operation:retry5.operation,reload:{_tag:"NotRequired"},target:retry5.target}}const updateIsAuthorized=retry5.operation==="update"&&inspectionDetectedOperatorSkill(inspection);const installIsAuthorized=retry5.operation==="install";if(!updateIsAuthorized&&!installIsAuthorized){return yield*new InvalidMutationRetry({message:"Operator mutation retry state changed; rerun the operator command."})}const result4=yield*ensureAndVerifyOperatorSkillScope(retry5.scope,retryInput,retry5.target);let mutationAction;if(result4._tag==="Failed"){mutationAction={...result4,operation:retry5.operation,phase:"write",retry:retry5}}else if(result4._tag==="Unverified"){mutationAction={...result4,operation:retry5.operation,retry:retry5}}else{mutationAction={...result4,operation:retry5.operation}}return{_tag:"Completed",actions:[mutationAction],before,operation:retry5.operation,reload:result4._tag==="Failed"?{_tag:"NotRequired"}:{_tag:"ReloadRequired",skill:"hi-cli"},target:retry5.target}});var executeOperatorAction=fn2("OperatorSkill.execute")(function*executeOperatorAction2(request3){const{action:action2,input:input2}=request3;if(action2==="status"){const lifecycle2=yield*inspectOperatorSkillLifecycle(input2);return{action:action2,lifecycle:lifecycle2}}if(action2==="install"||action2==="update"){const lifecycle2=request3.mutationRetryToken===undefined?yield*action2==="install"?installOperatorSkill(input2):updateOperatorSkill(input2):yield*decodeMutationRetry(request3.mutationRetryToken).pipe(flatMap4((retry5)=>retryOperatorSkillMutation(retry5,action2,input2)));return{action:action2,lifecycle:lifecycle2}}const lifecycle=request3.migrationRetryToken===undefined?yield*migrateLegacyOperatorSkill(input2):yield*decodeMigrationRetry(request3.migrationRetryToken).pipe(flatMap4((retry5)=>retryLegacyOperatorSkillMigration(retry5,input2)));return{action:action2,lifecycle}});var operatorCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator status",summary:"Inspect effective operator skill state."}],group:"commands",interaction:"none",name:"operator",options:[],outputModes:["interactive","plain","json"],summary:"Manage the Harness operator skill."});var operatorStatusCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator status",summary:"Run operator status."}],group:"operator",interaction:"none",name:"status",options:[],outputModes:["interactive","plain","json"],summary:"Show immutable hi-cli identity and effective installed state."});var operatorInstallCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator install",summary:"Run operator install."}],group:"operator",interaction:"none",name:"install",options:[],outputModes:["interactive","plain","json"],summary:"Ensure and verify the global hi-cli operator skill."});var operatorUpdateCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator update",summary:"Run operator update."}],group:"operator",interaction:"none",name:"update",options:[],outputModes:["interactive","plain","json"],summary:"Update and verify every detected hi-cli scope."});var operatorMigrateCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator migrate",summary:"Run operator migrate."}],group:"operator",interaction:"none",name:"migrate",options:[],outputModes:["interactive","plain","json"],summary:"Verify replacements before removing legacy dp-cli copies."});var operatorActionMetadata=(action2)=>{switch(action2){case"status":{return operatorStatusCommandMetadata}case"install":{return operatorInstallCommandMetadata}case"update":{return operatorUpdateCommandMetadata}case"migrate":{return operatorMigrateCommandMetadata}default:{return action2}}};var publicOperatorFailure=(value5)=>{if(typeof value5!=="object"||value5===null){return value5}const failure=value5;return Object.fromEntries(["_tag","agent","exitCode","message","operation","reason","reportedAgents","scope","skillName"].filter((key)=>failure[key]!==undefined).map((key)=>[key,failure[key]]))};var operatorFact=(value5)=>JSON.stringify(value5,(key,nestedValue)=>{if(key==="stderr"||key==="stack"||key==="cause"){return}return key==="failure"?publicOperatorFailure(nestedValue):nestedValue});var quoteShellArgument=(value5)=>`'${value5.replaceAll("'",`'"'"'`)}'`;var quotePowerShellLiteral=(value5)=>`'${value5.replaceAll("'","''")}'`;var windowsPowerShellCommand=(statements)=>`powershell.exe -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(statements.join("; "),"utf16le").toString("base64")}`;var mutationRetryCommand=(action2,platform)=>{const retry5=encodeMutationRetry(action2.retry);if(platform==="win32"){return windowsPowerShellCommand([`Set-Location -LiteralPath ${quotePowerShellLiteral(action2.retry.input.cwd)}`,`$env:HI_OPERATOR_MUTATION_RETRY = ${quotePowerShellLiteral(retry5)}`,`$env:HI_OPERATOR_AGENT = ${quotePowerShellLiteral(action2.retry.input.activeAgent)}`,`& hi operator ${action2.retry.operation}`])}return`cd -- ${quoteShellArgument(action2.retry.input.cwd)} && HI_OPERATOR_MUTATION_RETRY=${retry5} HI_OPERATOR_AGENT=${quoteShellArgument(action2.retry.input.activeAgent)} hi operator ${action2.retry.operation}`};var migrationRetryCommand=(action2,platform)=>{const retry5=encodeMigrationRetry(action2.retry);if(platform==="win32"){return windowsPowerShellCommand([`Set-Location -LiteralPath ${quotePowerShellLiteral(action2.retry.input.cwd)}`,`$env:HI_OPERATOR_MIGRATION_RETRY = ${quotePowerShellLiteral(retry5)}`,`$env:HI_OPERATOR_AGENT = ${quotePowerShellLiteral(action2.retry.input.activeAgent)}`,"& hi operator migrate"])}return`cd -- ${quoteShellArgument(action2.retry.input.cwd)} && HI_OPERATOR_MIGRATION_RETRY=${retry5} HI_OPERATOR_AGENT=${quoteShellArgument(action2.retry.input.activeAgent)} hi operator migrate`};var publicTarget=(target)=>({cliCompatibility:target.cliCompatibility,revision:target.revision,source:target.source,version:target.version});var statusFromChangesAndIssues=(changeCount,issueCount)=>{if(issueCount>0){return changeCount>0?"partial":"failed"}return changeCount>0?"success":"no-op"};var operatorStatusOperationResult=(lifecycle)=>{if(lifecycle._tag==="TargetResolutionFailed"){return{changes:[],degradations:[],issues:[{action:"status",code:`operator-target-${lifecycle.resolution._tag}`,kind:"handled-failure",subject:operatorFact(lifecycle.resolution)}],nextActions:[{kind:"retry",subject:"operator:status"}],status:"failed",warnings:[]}}const changes=[{action:"operator-target",state:"completed",subject:operatorFact(publicTarget(lifecycle.target))},...lifecycle.inspections.map((inspection)=>({action:"operator-inspection",state:"completed",subject:operatorFact(inspection)})),{action:"operator-installed-state",state:"completed",subject:operatorFact(lifecycle.installed)},{action:"operator-legacy-copies",state:"completed",subject:operatorFact(lifecycle.legacy)}];let issues=[];if(lifecycle.installed._tag==="DetectionFailed"){issues=lifecycle.installed.failures.map((failure)=>({action:"status",code:"operator-detection-failed",errorMessage:failure.message,kind:"handled-failure",subject:operatorFact(failure)}))}else if(lifecycle.installed._tag==="Ambiguous"){issues=[{action:"status",code:"operator-installed-ambiguous",kind:"conflict",subject:operatorFact(lifecycle.installed.candidates)}]}let status2="success";if(lifecycle.installed._tag==="Ambiguous"){status2="conflict"}else if(lifecycle.installed._tag==="DetectionFailed"){status2="failed"}return{changes,degradations:[],issues,nextActions:issues.length===0?[{kind:"none"}]:[lifecycle.installed._tag==="Ambiguous"?{kind:"resolve",subject:"operator:status"}:{kind:"retry",subject:"operator:status"}],status:status2,warnings:[]}};var publicVerifiedMutationAction=(action2)=>({_tag:action2._tag,copy:action2.copy,operation:action2.operation,scope:action2.scope});var publicFailedMutationAction=(action2)=>({_tag:action2._tag,operation:action2.operation,phase:action2.phase,retry:action2.retry,scope:action2.scope});var publicAlreadyVerifiedMutationAction=(action2)=>({_tag:action2._tag,copy:action2.copy,operation:action2.operation,scope:action2.scope});var publicUnverifiedMutationAction=(action2)=>({_tag:action2._tag,operation:action2.operation,reason:action2.reason,retry:action2.retry,scope:action2.scope});var operatorMutationOperationResult=(lifecycle,platform=process.platform)=>{if(lifecycle._tag==="TargetResolutionFailed"){return{changes:[],degradations:[],issues:[{action:lifecycle.operation,code:`operator-target-${lifecycle.before.resolution._tag}`,kind:"handled-failure",subject:operatorFact(lifecycle.before.resolution)}],nextActions:[{kind:"retry",subject:`operator:${lifecycle.operation}`}],status:"failed",warnings:[]}}const completed=lifecycle.actions.filter((action2)=>action2._tag==="Verified");const failed=lifecycle.actions.filter((action2)=>action2._tag==="Failed");const alreadyVerified=lifecycle.actions.filter((action2)=>action2._tag==="AlreadyVerified");const unverified=lifecycle.actions.filter((action2)=>action2._tag==="Unverified");const retryActions=[...failed,...unverified];const changes=completed.map((action2)=>({action:action2.operation,state:"completed",subject:operatorFact(publicVerifiedMutationAction(action2))}));const noInstalledUpdate=lifecycle.operation==="update"&&lifecycle.actions.length===0;const issues=[...failed.map((action2)=>({action:action2.operation,code:`operator-${action2.operation}-${action2._tag}`,errorMessage:action2.failure.message,kind:"handled-failure",subject:operatorFact(publicFailedMutationAction(action2))})),...unverified.map((action2)=>({action:action2.operation,code:`operator-${action2.operation}-${action2._tag}`,errorMessage:action2.failure?.message,kind:"handled-failure",subject:operatorFact(publicUnverifiedMutationAction(action2))})),...noInstalledUpdate?[{action:"update",code:"operator-update-no-installed-scope",kind:"handled-failure",subject:operatorFact({before:lifecycle.before,target:publicTarget(lifecycle.target)})}]:[]];let nextActions=[{kind:"none"}];if(noInstalledUpdate){nextActions=[{kind:"run",subject:"hi operator install"}]}else if(retryActions.length>0){nextActions=retryActions.map((action2)=>({kind:"run",subject:mutationRetryCommand(action2,platform)}))}return{changes,degradations:[],issues,nextActions,status:statusFromChangesAndIssues(changes.length,issues.length),warnings:[...alreadyVerified.map((action2)=>({code:`operator-${action2.operation}-${action2._tag}`,subject:operatorFact(publicAlreadyVerifiedMutationAction(action2))})),...lifecycle.reload._tag==="ReloadRequired"?[{code:"reload-required",subject:lifecycle.reload.skill}]:[]]}};var migrationContext=(lifecycle)=>{if(lifecycle._tag==="RetryTargetChanged"){return{expected:publicTarget(lifecycle.expected),observed:publicTarget(lifecycle.observed),result:{_tag:lifecycle._tag}}}if(lifecycle._tag==="TargetResolutionFailed"){return{resolution:lifecycle.before.resolution,result:{_tag:lifecycle._tag}}}return{before:{inspections:lifecycle.before.inspections,installed:lifecycle.before.installed,legacy:lifecycle.before.legacy},result:{_tag:lifecycle._tag,...lifecycle._tag==="Refused"?{reason:lifecycle.reason}:{}},target:publicTarget(lifecycle.target)}};var migrationFailure=(action2)=>("failure"in action2)?action2.failure:undefined;var operatorMigrationOperationResult=(lifecycle,platform=process.platform)=>{if(lifecycle._tag==="RetryTargetChanged"){return{changes:[],degradations:[],issues:[{action:"migrate",code:"operator-migrate-RetryTargetChanged",kind:"conflict",subject:operatorFact(migrationContext(lifecycle))}],nextActions:[{kind:"retry",subject:"operator:migrate"}],status:"conflict",warnings:[]}}if(lifecycle._tag==="TargetResolutionFailed"){return{changes:[],degradations:[],issues:[{action:"migrate",code:`operator-target-${lifecycle.before.resolution._tag}`,kind:"handled-failure",subject:operatorFact(migrationContext(lifecycle))}],nextActions:[{kind:"retry",subject:"operator:migrate"}],status:"failed",warnings:[]}}const completed=lifecycle.actions.filter((action2)=>action2._tag==="LegacyRemoved"||action2._tag==="ReplacementVerified"&&action2.wrote);const noOp=lifecycle.actions.filter((action2)=>action2._tag==="ReplacementVerified"&&!action2.wrote);const failed=lifecycle.actions.filter((action2)=>action2._tag!=="LegacyRemoved"&&action2._tag!=="ReplacementVerified");const context4=migrationContext(lifecycle);const changes=completed.map((action2)=>({action:"migrate",state:"completed",subject:operatorFact(action2)}));const issues=failed.map((action2)=>{const failure=migrationFailure(action2);return{action:"migrate",code:`operator-migrate-${action2._tag}`,...failure===undefined?{}:{errorMessage:failure.message},kind:"handled-failure",subject:operatorFact({action:action2,...context4})}});if(lifecycle._tag==="Refused"&&issues.length===0){issues.push({action:"migrate",code:"operator-migrate-Refused",kind:"handled-failure",subject:operatorFact(context4)})}let nextActions=[{kind:"none"}];if(failed.length>0){nextActions=failed.map((action2)=>({kind:"run",subject:migrationRetryCommand(action2,platform)}))}else if(issues.length>0){nextActions=[{kind:"retry",subject:"operator:migrate"}]}return{changes,degradations:[],issues,nextActions,status:statusFromChangesAndIssues(changes.length,issues.length),warnings:[{code:"operator-migrate-context",subject:operatorFact(context4)},...noOp.map((action2)=>({code:"operator-migrate-ReplacementVerified",subject:operatorFact(action2)})),...lifecycle.reload._tag==="ReloadRequired"?[{code:"reload-required",subject:lifecycle.reload.skill}]:[]]}};var executeOperatorCommand=(action2,operation=runOperatorSkillApplication)=>gen2(function*runOperatorCommand(){const result4=yield*operation(action2);if(result4.action==="status"){return operatorStatusOperationResult(result4.lifecycle)}if(result4.action==="migrate"){return operatorMigrationOperationResult(result4.lifecycle)}return operatorMutationOperationResult(result4.lifecycle)}).pipe(catchTag2("InvalidMigrationRetry",(failure)=>fail6(new CliValidationError({message:failure.message,recoveryCommand:"unset HI_OPERATOR_MIGRATION_RETRY; hi operator migrate"}))),catchTag2("InvalidOperatorContext",(failure)=>fail6(new CliValidationError({message:failure.message}))),catchTag2("InvalidMutationRetry",(failure)=>fail6(new CliValidationError({message:failure.message,recoveryCommand:`unset HI_OPERATOR_MUTATION_RETRY; hi operator ${action2}`}))));var makeOperatorAction=(action2,operation=runOperatorSkillApplication)=>{const metadata=operatorActionMetadata(action2);return exports_Command.make(metadata.name,{},()=>captureCommandResult(executeOperatorCommand(action2,operation))).pipe(withCommandMetadata(metadata))};var operatorRootOperationResult={changes:[],degradations:[],issues:[],nextActions:[{kind:"run",subject:"hi operator status"},{kind:"run",subject:"hi operator install"},{kind:"run",subject:"hi operator update"},{kind:"run",subject:"hi operator migrate"}],status:"no-op",warnings:[{code:"operator-command-summary",subject:"Manage the Harness operator skill."}]};var operatorRootOperation=succeed6(operatorRootOperationResult);var operatorSubcommands=[makeOperatorAction("status"),makeOperatorAction("install"),makeOperatorAction("update"),makeOperatorAction("migrate")];var operatorCommandRoot=exports_Command.make(operatorCommandMetadata.name,{},()=>captureCommandResult(operatorRootOperation)).pipe(withCommandMetadata(operatorCommandMetadata));var operatorCommand=operatorCommandRoot.pipe(exports_Command.withSubcommands(operatorSubcommands));class ReportConfigurationUnavailable extends TaggedErrorClass()("@punks/cli/report-submission/ReportConfigurationUnavailable",{cause:Defect(),message:String5,operation:Literal2("resolve-control-plane-url")}){}class ReportSubmissionResponseInvalid extends TaggedErrorClass()("@punks/cli/report-submission/ReportSubmissionResponseInvalid",{cause:Defect(),message:String5,operation:Literal2("validate-submission-response")}){}class ReportInputInvalid extends TaggedErrorClass()("@punks/cli/report-submission/ReportInputInvalid",{cause:Defect(),field:Literal2("body"),message:String5,operation:Literal2("validate-report-input")}){}class ReportSubmissionOperationFailure extends TaggedErrorClass()("@punks/cli/report-submission/ReportSubmissionOperationFailure",{cause:Defect(),message:String5,operation:Literals(["record-submitted","submit-report"])}){}var ReportSubmissionOperations=Service("@punks/cli/features/report-submission/ReportSubmissionOperations");var nonEmpty=(value5)=>{const trimmed=value5.trim();if(trimmed.length===0){const cause=new Error("Missing body. Pass a non-empty value.");return fail6(new ReportInputInvalid({cause,field:"body",message:cause.message,operation:"validate-report-input"}))}return succeed6(trimmed)};var csvLabels=(value5)=>value5===undefined?[]:value5.split(",").map((label)=>label.trim()).filter((label)=>label.length>0);var buildHarnessReport=fn2("ReportSubmission.build")(function*buildReport({title,body,message,type:type2,severity,area,repoRoot,skillPack,command,expected,actual,steps,labels}){const operations=yield*ReportSubmissionOperations;const validBody=yield*nonEmpty(body??message??[actual,expected,steps].filter(Boolean).join(`
|
|
343
|
+
`};var initializeProjectSettings=fn2("ProjectSettings.initialize")(function*initializeProjectSettings2(fileSystem,rootDirectory,initialization){const settingsPath=fileSystem.joinPath(rootDirectory,projectSettingsFile);const settingsDirectory=fileSystem.joinPath(rootDirectory,".devpunks");const settingsDirectoryExisted=yield*fileSystem.directoryExists(settingsDirectory);const expectedContent=projectSettingsInitializationContent(initialization);const created=yield*fileSystem.createTextFile(settingsPath,expectedContent);if(!created){return yield*new ProjectSettingsAlreadyExists({message:`Project settings already exist at ${settingsPath}.`,path:settingsPath})}const read3=yield*readProjectSettings(fileSystem,rootDirectory).pipe(result2);if(isSuccess2(read3)){return read3.success}yield*gen2(function*rollbackProjectSettingsInitialization(){yield*fileSystem.removeTextFileIfContent(settingsPath,expectedContent);if(!settingsDirectoryExisted){yield*fileSystem.removeEmptyDirectory(settingsDirectory)}}).pipe(result2);return yield*read3.failure});var rollbackProjectSettingsInitialization=fn2("ProjectSettings.rollbackInitialization")(function*rollbackProjectSettingsInitialization2(fileSystem,rootDirectory,rollback){const settingsPath=fileSystem.joinPath(rootDirectory,projectSettingsFile);const settingsDirectory=fileSystem.joinPath(rootDirectory,".devpunks");const removed=yield*fileSystem.removeTextFileIfContent(settingsPath,projectSettingsInitializationContent(rollback.initialization));if(rollback.removeSettingsDirectory){yield*fileSystem.removeEmptyDirectory(settingsDirectory)}return removed});var ProjectSettings=Service("@punks/cli/ProjectSettings");var ProjectSettingsDefault=effect(ProjectSettings,gen2(function*ProjectSettingsDefault2(){const fileSystem=yield*ProjectSettingsFileSystem;return{infer:(rootDirectory)=>inferProjectSettings(fileSystem,rootDirectory),initialize:(rootDirectory,initialization)=>initializeProjectSettings(fileSystem,rootDirectory,initialization),read:(rootDirectory)=>readProjectSettings(fileSystem,rootDirectory),rollbackInitialization:(rootDirectory,rollback)=>rollbackProjectSettingsInitialization(fileSystem,rootDirectory,rollback),write:(rootDirectory,change)=>writeProjectSettings(fileSystem,rootDirectory,change)}}));import{execFileSync}from"node:child_process";import{accessSync,constants as constants2,existsSync as existsSync3,mkdirSync as mkdirSync2,readFileSync as readFileSync4,writeFileSync as writeFileSync2}from"node:fs";import{homedir}from"node:os";import path9 from"node:path";class ToolManagementFailure extends TaggedErrorClass()("@punks/cli/integrations/tool-management/ToolManagementFailure",{cause:Defect(),message:String5,operation:Literals(["ensure-required-tool","infer-repo-settings"])}){}var toolManagementFailure=(operation,message)=>new ToolManagementFailure({cause:new Error(message),message,operation});var repoSettingsFile=".devpunks/settings.json";var repositoryManagerTools2={"azure-devops":["az"],bitbucket:[],github:["gh"],gitlab:["glab"]};var repositoryManagers2=new Set(Object.keys(repositoryManagerTools2));var backlogProviders2=new Set(["azure-devops","github","linear","monday"]);var assetProviders=new Set([...backlogProviders2,...repositoryManagers2]);var requiredToolsForRepositoryManager2=(repositoryManager)=>repositoryManagerTools2[repositoryManager];var reconcileRepositoryManagerTools=({previousRepositoryManager,requiredTools,repositoryManager})=>{const previousManagerTools=new Set(requiredToolsForRepositoryManager2(previousRepositoryManager));return[...new Set([...requiredTools.filter((tool)=>!previousManagerTools.has(tool)),...requiredToolsForRepositoryManager2(repositoryManager)])].toSorted()};var isRepositoryManager=(value5)=>typeof value5==="string"&&repositoryManagers2.has(value5);var isBacklogProvider=(value5)=>typeof value5==="string"&&backlogProviders2.has(value5);var isAssetProvider=(value5)=>typeof value5==="string"&&assetProviders.has(value5);var isStringArray=(value5)=>Array.isArray(value5)&&value5.every((tool)=>typeof tool==="string");var normalizeRepoSettings=(value5)=>{if(typeof value5!=="object"||value5===null){return null}const record3=value5;if(!isBacklogProvider(record3.backlogProvider)||!isAssetProvider(record3.assetProviderSlug)||!isRepositoryManager(record3.repositoryManager)||!isStringArray(record3.requiredTools)){return null}return Object.fromEntries([["backlogProvider",record3.backlogProvider],["assetProviderSlug",record3.assetProviderSlug],...typeof record3.backlogProjectUrl==="string"?[["backlogProjectUrl",record3.backlogProjectUrl]]:[],...typeof record3.baselineVersion==="string"?[["baselineVersion",record3.baselineVersion]]:[],...typeof record3.cliVersion==="string"?[["cliVersion",record3.cliVersion]]:[],["repositoryManager",record3.repositoryManager],["requiredTools",[...new Set([...record3.requiredTools,...requiredToolsForRepositoryManager2(record3.repositoryManager)])].toSorted()]])};var readRepoSettings=(rootDirectory)=>{const settingsPath=path9.join(rootDirectory,repoSettingsFile);if(!existsSync3(settingsPath)){return null}return normalizeRepoSettings(JSON.parse(readFileSync4(settingsPath,"utf-8")))};var commandExistsOnPath=(command,env={},platform=process.platform)=>{const pathValue=env.PATH??env.Path;if(pathValue===undefined||pathValue.length===0){return false}const isWindows=platform==="win32";const pathSeparator=isWindows?";":":";const pathEntries=pathValue.split(pathSeparator).filter((entry)=>entry.length>0);const pathExtensions=isWindows?(env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter((extension)=>extension.length>0):[""];const commandExtensions=isWindows&&path9.extname(command).length===0?pathExtensions:[""];const hasPathSegment=command.includes("/")||command.includes("\\");const candidates=(hasPathSegment?[""]:pathEntries).flatMap((entry)=>commandExtensions.map((extension)=>hasPathSegment?`${command}${extension}`:path9.join(entry,`${command}${extension}`)));return candidates.some((candidate)=>{try{accessSync(candidate,isWindows?constants2.F_OK:constants2.X_OK);return true}catch{return false}})};var makeToolCommandRuntime=(environment)=>({commandExists:(command)=>commandExistsOnPath(command,environment),cwd:homedir(),env:environment,execFile:(command,args2,options4)=>{execFileSync(command,[...args2],{cwd:options4?.cwd,env:environment,stdio:options4?.stdio==="inherit"?["ignore","inherit","inherit"]:"ignore"})},execFileOutput:(command,args2,options4)=>execFileSync(command,[...args2],{cwd:options4?.cwd,encoding:"utf-8",env:environment})});var defaultRuntime=makeToolCommandRuntime({});var defaultToolBootstrapOptions={mode:"repair",stdio:"inherit"};var detectGlobalPackageManager=(runtime)=>{if(runtime.commandExists("bun")){return"bun"}if(runtime.commandExists("pnpm")){return"pnpm"}if(runtime.commandExists("npm")){return"npm"}return null};var globalInstallCommandFor=(packageManager,packageName)=>{switch(packageManager){case"bun":{return["bun","add","-g",packageName]}case"pnpm":{return["pnpm","add","-g",packageName]}case"npm":{return["npm","install","-g",packageName]}default:{return packageManager}}};var parseVersionParts=(value5)=>{const match8=value5.match(/\d+(?:\.\d+){0,2}/u);if(match8===null){return null}const[matchedVersion]=match8;return matchedVersion===undefined?null:matchedVersion.split(".").map((part)=>Number.parseInt(part,10))};var compareVersions=(actual,minimum)=>{const length=Math.max(actual.length,minimum.length);for(let index2=0;index2<length;index2+=1){const actualPart=actual[index2]??0;const minimumPart=minimum[index2]??0;if(actualPart>minimumPart){return 1}if(actualPart<minimumPart){return-1}}return 0};var isMinimumVersionSatisfied=(tool,runtime,cwd)=>{if(tool.minimumVersion===undefined||tool.versionCommand===undefined){return true}const[command,...args2]=tool.versionCommand;if(command===undefined||runtime.execFileOutput===undefined){return true}const actual=parseVersionParts(runtime.execFileOutput(command,args2,{cwd}));const minimum=parseVersionParts(tool.minimumVersion);if(actual===null||minimum===null){throw toolManagementFailure("ensure-required-tool",`Cannot verify required tool version from \`${tool.versionCommand.join(" ")}\`.`)}return compareVersions(actual,minimum)>=0};var commandCandidateValue=(candidate,env)=>{if(typeof candidate==="string"){return candidate}const value5=env[candidate.env];return value5===undefined||value5.length===0?null:value5};var shouldSkipEnsureCommands=(tool,runtime)=>tool.skipEnsureCommandsIfAnyCommandExists?.some((candidate)=>{const command=commandCandidateValue(candidate,runtime.env??{});return command!==null&&runtime.commandExists(command)})??false;var manualProviderCliTools=Object.fromEntries([...new Set(Object.values(repositoryManagerTools2).flat())].map((toolId)=>[toolId,{ensureCommands:[],manual:true,requiredBins:[]}]));var installTool=({cwd,installTarget,runtime,stdio,toolId,versionContract})=>{const packageManager=detectGlobalPackageManager(runtime);if(packageManager===null){throw toolManagementFailure("ensure-required-tool","Cannot install required tools because no supported global package manager was found on PATH. Install Bun, pnpm, or npm first.")}if(installTarget===undefined){throw toolManagementFailure("ensure-required-tool",`Required tool \`${toolId}\` cannot be installed automatically.`)}const[command,...args2]=globalInstallCommandFor(packageManager,installTarget);runtime.execFile(command,args2,{cwd,stdio});if(!runtime.commandExists(toolId)){throw toolManagementFailure("ensure-required-tool",`Tried to install required tool \`${toolId}\`, but the binary is still not available on PATH afterwards.`)}if(!isMinimumVersionSatisfied(versionContract,runtime,cwd)){throw toolManagementFailure("ensure-required-tool",`Tried to install required tool \`${toolId}\`, but the installed version does not satisfy ${versionContract.minimumVersion}.`)}};var ensureToolsInstalled=(toolIds,baseline=bundledBaseline,runtime=defaultRuntime,options4=defaultToolBootstrapOptions)=>{const statuses=[];const toolCatalogById=Object.fromEntries(baseline.tools.map((tool)=>[tool.id,tool]));const cwd=runtime.cwd??homedir();for(const toolId of toolIds){const tool=toolCatalogById[toolId]===undefined?manualProviderCliTools[toolId]:{...toolCatalogById[toolId],manual:false};if(tool===undefined){throw toolManagementFailure("ensure-required-tool",`Unknown required tool \`${toolId}\` in baseline.`)}const missingPrerequisites=tool.requiredBins.filter((command)=>!runtime.commandExists(command));if(missingPrerequisites.length>0){throw toolManagementFailure("ensure-required-tool",`Cannot install required tool \`${toolId}\` because ${missingPrerequisites.join(", ")} is not available on PATH.`)}const versionContract=tool;const alreadyPresent=runtime.commandExists(toolId)&&isMinimumVersionSatisfied(versionContract,runtime,cwd);const refreshLatest=options4.mode==="refresh-latest"&&!tool.manual;if(!alreadyPresent&&tool.manual){throw toolManagementFailure("ensure-required-tool",`Required external tool \`${toolId}\` is not available on PATH. Install it before running scaffold/update workflows.`)}if(!alreadyPresent||refreshLatest){const installTarget=refreshLatest?tool.latestInstallTarget:tool.packageName;installTool({cwd,installTarget,runtime,stdio:options4.stdio,toolId,versionContract})}const ensureCommandContract=tool;if(!shouldSkipEnsureCommands(ensureCommandContract,runtime)){for(const[command,...args2]of tool.ensureCommands){runtime.execFile(command,args2,{cwd,stdio:options4.stdio})}}statuses.push({status:alreadyPresent&&!refreshLatest?"already-present":"installed",toolId})}return statuses};var errorMessage=(cause)=>cause instanceof Error?cause.message:String(cause);var errorStack=(cause)=>cause instanceof Error?cause.stack??cause.message:String(cause);var ensureToolsInstalledBestEffort=(toolIds,baseline=bundledBaseline,runtime=defaultRuntime,options4=defaultToolBootstrapOptions)=>toolIds.flatMap((toolId)=>{try{return ensureToolsInstalled([toolId],baseline,runtime,options4)}catch(error2){return[Object.fromEntries([["toolId",toolId],["status","failed"],["errorMessage",errorMessage(error2)],["errorStack",errorStack(error2)]])]}});var providerChoices=[{title:"GitHub Projects and Issues",value:"github"},{title:"Linear",value:"linear"},{title:"Azure DevOps",value:"azure-devops"},{title:"monday.com",value:"monday"}];var assetChoices=[...providerChoices,{title:"GitLab",value:"gitlab"},{title:"Bitbucket",value:"bitbucket"}];var repositoryChoices=[{title:"GitHub",value:"github"},{title:"GitLab",value:"gitlab"},{title:"Azure DevOps",value:"azure-devops"},{title:"Bitbucket",value:"bitbucket"}];var validProjectUrl=(input2)=>{const value5=input2.trim();try{const url2=new URL(value5);return url2.protocol==="http:"||url2.protocol==="https:"?value5:null}catch{return null}};var selectRepoSettings=({prompt,defaults:defaults2,retryCommand})=>gen2(function*selectSettings(){const backlogProvider=yield*prompt.singleSelect({choices:providerChoices,defaultValue:defaults2?.backlogProvider??"github",message:"Select backlog provider"});const assetProviderSlug=yield*prompt.singleSelect({choices:assetChoices,defaultValue:defaults2?.assetProviderSlug??backlogProvider,message:"Select asset provider"});const repositoryManager=yield*prompt.singleSelect({choices:repositoryChoices,defaultValue:defaults2?.repositoryManager??"github",message:"Select repository manager"});const input2=yield*prompt.readLine(`Backlog project URL${defaults2?.backlogProjectUrl?` [${defaults2.backlogProjectUrl}]`:""}: `);const backlogProjectUrl=validProjectUrl(input2||defaults2?.backlogProjectUrl||"");if(backlogProjectUrl===null){return yield*fail6(new CliPromptError({message:`Backlog project URL must be an absolute HTTP(S) URL. Rerun \`${retryCommand}\`.`}))}return{assetProviderSlug,backlogProjectUrl,backlogProvider,repositoryManager}});var ensureCommandMetadata=declareCommandMetadata({examples:[{command:"hi ensure",summary:"Reconfigure current project settings."}],group:"commands",interaction:"required",name:"ensure",options:[],outputModes:["interactive","plain"],summary:"Reconfigure backlog, asset, repository, and backlog project URL settings only."});var mapSettingsError=(error2)=>new CliPromptError({message:error2._tag==="ProjectSettingsMissing"?`${projectSettingsFile} was not found. Run \`hi init\` first.`:error2.message});var runEnsure=({rootDirectory,prompt})=>gen2(function*ensureSettings(){const projectSettings=yield*ProjectSettings;const current=(yield*projectSettings.read(rootDirectory).pipe(mapError3(mapSettingsError))).settings;const selected=yield*selectRepoSettings({defaults:current,prompt,retryCommand:"hi ensure"});const requiredTools=reconcileRepositoryManagerTools({previousRepositoryManager:current.repositoryManager,repositoryManager:selected.repositoryManager,requiredTools:current.requiredTools});yield*projectSettings.write(rootDirectory,{_tag:"ReconfigurationChange",assetProviderSlug:selected.assetProviderSlug,...selected.backlogProjectUrl===undefined?{}:{backlogProjectUrl:selected.backlogProjectUrl},backlogProvider:selected.backlogProvider,repositoryManager:selected.repositoryManager,requiredTools}).pipe(mapError3(mapSettingsError));return{changes:[{action:"configure",state:"completed",subject:projectSettingsFile}],degradations:[],issues:[],nextActions:[{kind:"none"}],status:"success",warnings:[]}});var executeEnsureCommand=(input2)=>captureCommandResult(runEnsure(input2));var ensureCommand=exports_Command.make(ensureCommandMetadata.name,{},()=>scoped2(gen2(function*runEnsureCommand(){const outputMode=yield*SelectedOutputMode;if(outputMode!=="interactive"){return yield*new CliValidationError({message:outputMode==="json"?"`hi ensure` requires interactive input and is unavailable in JSON mode.":"`hi ensure` requires interactive input and is unavailable when output is redirected.",recoveryCommand:"hi ensure"})}const prompt=yield*PromptLive;return yield*executeEnsureCommand({prompt,rootDirectory:process.cwd()})}))).pipe(withCommandMetadata(ensureCommandMetadata));class InvalidMigrationRetry extends TaggedErrorClass()("InvalidMigrationRetry",{message:String5}){}class InvalidMutationRetry extends TaggedErrorClass()("InvalidMutationRetry",{message:String5}){}class InvalidOperatorContext extends TaggedErrorClass()("InvalidOperatorContext",{message:String5}){}var SkillsCliScope=Literals(["project","global"]);var skillsCliFailureFields={agent:String5,message:String5,operation:Literals(["list","install","remove"]),scope:SkillsCliScope};var verifiedInstalledSkillSchema=Struct({agents:ArraySchema(String5),cliCompatibility:Struct({maximumExclusive:String5,minimum:String5}),name:String5,path:String5,revision:String5,scope:SkillsCliScope,source:String5,version:String5});var SkillsCliVerificationFailureReason=Literals(["unsafe-path","missing","unreadable","malformed","identity-mismatch"]);class SkillsCliVerificationFailure extends TaggedErrorClass()("SkillsCliVerificationFailure",{...skillsCliFailureFields,reason:SkillsCliVerificationFailureReason,skillName:String5,skillPath:String5,verifiedSkills:ArraySchema(verifiedInstalledSkillSchema)}){}class SkillsCliBindingFailure extends TaggedErrorClass()("SkillsCliBindingFailure",{...skillsCliFailureFields,reportedAgents:ArraySchema(String5),skillName:String5,verifiedSkills:ArraySchema(verifiedInstalledSkillSchema)}){}class SkillsCliExit extends TaggedErrorClass()("SkillsCliExit",{...skillsCliFailureFields,exitCode:Number6,stderr:String5}){}class SkillsCliMalformedOutput extends TaggedErrorClass()("SkillsCliMalformedOutput",{...skillsCliFailureFields,stdout:String5}){}class SkillsCliTimeout extends TaggedErrorClass()("SkillsCliTimeout",{...skillsCliFailureFields,timeoutMs:Number6}){}class SkillsCliUnavailable extends TaggedErrorClass()("SkillsCliUnavailable",{...skillsCliFailureFields,executable:String5}){}class SkillsCliUnsupportedVersion extends TaggedErrorClass()("SkillsCliUnsupportedVersion",{...skillsCliFailureFields,minimumVersion:String5,version:String5}){}var SkillsCli=Service("@punks/cli/features/operator-skill/SkillsCli");var OperatorSkillOperations=Service("@punks/cli/features/operator-skill/OperatorSkillOperations");var runOperatorSkillApplication=fn2("OperatorSkill.run")(function*runOperatorSkillApplication2(action2,selectAgent){const operations=yield*OperatorSkillOperations;return yield*operations.run(action2,selectAgent)});var isWithinCanonicalPath=(candidate,root)=>candidate===root||candidate.startsWith(root.endsWith("/")?root:`${root}/`)||candidate.startsWith(root.endsWith("\\")?root:`${root}\\`);var installedOperatorSkillCopyIdentity=(copy3)=>JSON.stringify([copy3.scope,copy3.scope==="project-local"?copy3.projectRoot:"",copy3.version,copy3.source,copy3.revision,copy3.compatibility,[...copy3.boundAgents].toSorted()]);var compareText=(left,right)=>left<right?-1:Number(left>right);var compareCopyIdentity=(left,right)=>{const leftIdentity=installedOperatorSkillCopyIdentity(left);const rightIdentity=installedOperatorSkillCopyIdentity(right);return compareText(leftIdentity,rightIdentity)};var sortCopies=(copies)=>copies.toSorted(compareCopyIdentity);var failureIdentity=(failure)=>JSON.stringify([failure.scope,failure.scope==="project-local"?failure.projectRoot:"",failure.reason,failure.message]);var resolveInstalledOperatorSkillState=(input2)=>{const failures=[];const copies=[];for(const inspection of input2.inspections){if(inspection._tag==="DetectionFailed"){failures.push(inspection);continue}if(inspection.scope==="global"){copies.push(...inspection.copies.map((copy3)=>({...copy3,boundAgents:[...copy3.boundAgents].toSorted()})));continue}for(const copy3 of inspection.copies){if(copy3.projectRoot!==inspection.projectRoot){failures.push({_tag:"DetectionFailed",message:`Project-local copy root ${copy3.projectRoot} does not match inspection root ${inspection.projectRoot}`,projectRoot:inspection.projectRoot,reason:"ProjectRootMismatch",scope:"project-local"});continue}copies.push({...copy3,boundAgents:[...copy3.boundAgents].toSorted(),projectRoot:inspection.projectRoot})}}const detected=sortCopies(copies);const incompatible=sortCopies(copies.filter((copy3)=>copy3.compatibility==="incompatible"));if(failures.length>0){return{_tag:"DetectionFailed",detected,failures:failures.toSorted((left,right)=>compareText(failureIdentity(left),failureIdentity(right))),incompatible}}const candidates=detected.filter((copy3)=>copy3.boundAgents.includes(input2.activeAgent)&&(copy3.scope==="global"||isWithinCanonicalPath(input2.cwd,copy3.projectRoot))).toSorted((left,right)=>Number(left.scope==="global")-Number(right.scope==="global"));const[effective]=candidates;if(effective===undefined){return{_tag:"Absent",detected,incompatible}}const topCandidates=candidates.filter((copy3)=>copy3.scope===effective.scope);if(topCandidates.some((copy3)=>installedOperatorSkillCopyIdentity(copy3)!==installedOperatorSkillCopyIdentity(effective))){return{_tag:"Ambiguous",candidates:topCandidates.toSorted(compareCopyIdentity),incompatible,shadowed:sortCopies(candidates.slice(topCandidates.length))}}return{_tag:"Resolved",effective,incompatible,shadowed:sortCopies(candidates.slice(1))}};var operatorSkillScopeCwd=(scope3,input2)=>scope3==="global"?input2.cwd:input2.projectRoot;var parseSemanticVersion=(value5)=>{const match8=/^(?<major>0|[1-9]\d*)\.(?<minor>0|[1-9]\d*)\.(?<patch>0|[1-9]\d*)(?:-(?<prerelease>[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u.exec(value5);const groups=match8?.groups;const prerelease=groups?.prerelease?.split(".");if(groups===undefined||prerelease?.some((identifier2)=>/^\d+$/u.test(identifier2)&&!/^(?:0|[1-9]\d*)$/u.test(identifier2))){return}return{core:[groups.major,groups.minor,groups.patch],prerelease}};var compareIdentifiers=(left,right)=>{if(left===right){return 0}return left<right?-1:1};var compareNumericIdentifiers=(left,right)=>left.length-right.length||compareIdentifiers(left,right);var comparePrerelease=(left,right)=>{if(left===undefined||right===undefined){if(left===right){return 0}return left===undefined?1:-1}const length=Math.max(left.length,right.length);for(let index2=0;index2<length;index2+=1){const leftIdentifier=left[index2];const rightIdentifier=right[index2];if(leftIdentifier===undefined||rightIdentifier===undefined){if(leftIdentifier===rightIdentifier){return 0}return leftIdentifier===undefined?-1:1}if(leftIdentifier===rightIdentifier){continue}const leftIsNumeric=/^\d+$/u.test(leftIdentifier);const rightIsNumeric=/^\d+$/u.test(rightIdentifier);if(leftIsNumeric&&rightIsNumeric){return compareNumericIdentifiers(leftIdentifier,rightIdentifier)}if(leftIsNumeric!==rightIsNumeric){return leftIsNumeric?-1:1}return compareIdentifiers(leftIdentifier,rightIdentifier)}return 0};var compareSemanticVersions=(left,right)=>{const parsedLeft=parseSemanticVersion(left);const parsedRight=parseSemanticVersion(right);if(parsedLeft===undefined||parsedRight===undefined){return}for(let index2=0;index2<parsedLeft.core.length;index2+=1){const compared=compareNumericIdentifiers(parsedLeft.core[index2],parsedRight.core[index2]);if(compared!==0){return compared}}return comparePrerelease(parsedLeft.prerelease,parsedRight.prerelease)};var satisfiesSemanticVersionRange=(version3,minimum,maximumExclusive)=>{const comparedToMinimum=compareSemanticVersions(version3,minimum);const comparedToMaximum=compareSemanticVersions(version3,maximumExclusive);return comparedToMinimum!==undefined&&comparedToMaximum!==undefined&&comparedToMinimum>=0&&comparedToMaximum<0};var authoritativeContentManifest=Object.freeze([Object.freeze({path:"SKILL.md",sha256:"aee7ff55492ba810ca75bfbc8bbf5d4a14695828634c3fb1c6aea0a895589b98"}),Object.freeze({path:"references/commands.md",sha256:"62e07c52acd6add81a8feccbe39eb99521d6a2c9682d97e940bcc39a5e705e1a"}),Object.freeze({path:"references/post-command-flow.md",sha256:"0975f458b8636de0ef0d26e1dbc3c353208acc439fa47ebe2f261181e94815a8"})]);var authoritativeOperatorSkillTarget=Object.freeze({cliCompatibility:Object.freeze({maximumExclusive:"4.0.0",minimum:"3.0.0-beta.0"}),contentManifest:authoritativeContentManifest,revision:"09a6f3c6f9a7ed62a7e4abf0411f8a0f4f993e1d",source:"https://github.com/wearedevpunks/skills/tree/09a6f3c6f9a7ed62a7e4abf0411f8a0f4f993e1d/skills/agnostic/cli/hi-cli",version:"1.1.0"});var immutableRevisionPattern=/^[0-9a-f]{40}$/u;var authoritativeSourceRoot="https://github.com/wearedevpunks/skills";var operatorSkillPath="skills/agnostic/cli/hi-cli";var targetIsIncomplete=(target)=>target.source.trim()===""||target.version.trim()===""||target.revision.trim()===""||target.cliCompatibility.minimum.trim()===""||target.cliCompatibility.maximumExclusive.trim()===""||target.contentManifest.length===0||target.contentManifest.some((entry)=>entry.path.trim()===""||entry.sha256.trim()==="");var validateTarget=(target)=>{if(targetIsIncomplete(target)){return"IncompleteIdentity"}if(!immutableRevisionPattern.test(target.revision)){return"MovingRevision"}const immutableSource=`${authoritativeSourceRoot}/tree/${target.revision}/${operatorSkillPath}`;if(target.source!==immutableSource){return target.source.startsWith(authoritativeSourceRoot)?"SourceRevisionMismatch":"NonAuthoritativeSource"}const version3=compareSemanticVersions(target.version,target.version);const rangeOrder=compareSemanticVersions(target.cliCompatibility.minimum,target.cliCompatibility.maximumExclusive);if(version3===undefined||rangeOrder===undefined||rangeOrder>=0){return"InvalidVersion"}if(target.source!==authoritativeOperatorSkillTarget.source||target.version!==authoritativeOperatorSkillTarget.version||target.revision!==authoritativeOperatorSkillTarget.revision||target.cliCompatibility.minimum!==authoritativeOperatorSkillTarget.cliCompatibility.minimum||target.cliCompatibility.maximumExclusive!==authoritativeOperatorSkillTarget.cliCompatibility.maximumExclusive||JSON.stringify(target.contentManifest)!==JSON.stringify(authoritativeOperatorSkillTarget.contentManifest)){return"NonAuthoritativeIdentity"}return};var resolveOperatorSkillTarget=(input2)=>{if(compareSemanticVersions(input2.activeCliVersion,input2.activeCliVersion)===undefined){return{_tag:"NoCompatibleTarget",activeCliVersion:input2.activeCliVersion}}const compatibleIndexes=[];for(const[candidateIndex,candidate]of input2.candidates.entries()){const invalidReason=validateTarget(candidate);if(invalidReason!==undefined){return{_tag:"InvalidTarget",candidateIndex,reason:invalidReason}}if(satisfiesSemanticVersionRange(input2.activeCliVersion,candidate.cliCompatibility.minimum,candidate.cliCompatibility.maximumExclusive)){compatibleIndexes.push(candidateIndex)}}if(compatibleIndexes.length===0){return{_tag:"NoCompatibleTarget",activeCliVersion:input2.activeCliVersion}}if(compatibleIndexes.length>1){return{_tag:"AmbiguousCompatibleTargets",activeCliVersion:input2.activeCliVersion,candidateIndexes:compatibleIndexes}}return{_tag:"Resolved",target:authoritativeOperatorSkillTarget}};var compatibilityFor=(activeCliVersion,skill)=>satisfiesSemanticVersionRange(activeCliVersion,skill.cliCompatibility.minimum,skill.cliCompatibility.maximumExclusive)?"compatible":"incompatible";var isVerified=(skill)=>("version"in skill);var mapGlobalCopy=(activeCliVersion,skill)=>({boundAgents:[...skill.agents].toSorted(),compatibility:compatibilityFor(activeCliVersion,skill),revision:skill.revision,scope:"global",source:skill.source,version:skill.version});var mapProjectCopy=(activeCliVersion,projectRoot,skill)=>({boundAgents:[...skill.agents].toSorted(),compatibility:compatibilityFor(activeCliVersion,skill),projectRoot,revision:skill.revision,scope:"project-local",source:skill.source,version:skill.version});var inspectListedSkills=(scope3,input2,skills)=>{const operatorSkills=skills.filter((skill)=>skill.name==="hi-cli"&&isVerified(skill));const legacySkills=skills.filter((skill)=>skill.name==="dp-cli");if(scope3==="global"){return{_tag:"Inspected",copies:operatorSkills.map((skill)=>mapGlobalCopy(input2.activeCliVersion,skill)),legacy:legacySkills.map((skill)=>({boundAgents:[...skill.agents].toSorted(),path:skill.path,scope:scope3})),scope:scope3}}return{_tag:"Inspected",copies:operatorSkills.map((skill)=>mapProjectCopy(input2.activeCliVersion,input2.projectRoot,skill)),legacy:legacySkills.map((skill)=>({boundAgents:[...skill.agents].toSorted(),path:skill.path,projectRoot:input2.projectRoot,scope:scope3})),projectRoot:input2.projectRoot,scope:scope3}};var failedInspection=(scope3,input2,failure)=>{const verifiedSkills=failure._tag==="SkillsCliVerificationFailure"||failure._tag==="SkillsCliBindingFailure"?failure.verifiedSkills:[];if(scope3==="global"){return{_tag:"InspectionFailed",copies:verifiedSkills.map((skill)=>mapGlobalCopy(input2.activeCliVersion,skill)),failure,legacy:[],scope:scope3}}return{_tag:"InspectionFailed",copies:verifiedSkills.map((skill)=>mapProjectCopy(input2.activeCliVersion,input2.projectRoot,skill)),failure,legacy:[],projectRoot:input2.projectRoot,scope:scope3}};var installedInspections=(inspections)=>inspections.flatMap((inspection)=>{const detected=inspection.scope==="global"?{_tag:"Detected",copies:inspection.copies,scope:"global"}:{_tag:"Detected",copies:inspection.copies,projectRoot:inspection.projectRoot,scope:"project-local"};if(inspection._tag==="Inspected"){return[detected]}const failure=inspection.scope==="global"?{_tag:"DetectionFailed",message:inspection.failure.message,reason:"ListingFailed",scope:"global"}:{_tag:"DetectionFailed",message:inspection.failure.message,projectRoot:inspection.projectRoot,reason:"ListingFailed",scope:"project-local"};return inspection.copies.length===0?[failure]:[detected,failure]});var collectLegacyCopies=(inspections)=>{const copies=[];for(const inspection of inspections){copies.push(...inspection.legacy)}return copies};var inspectOperatorSkillLifecycle=fn2("OperatorSkillLifecycle.status")(function*inspectOperatorSkillLifecycle2(input2){const resolution=resolveOperatorSkillTarget({activeCliVersion:input2.activeCliVersion,candidates:[authoritativeOperatorSkillTarget]});if(resolution._tag!=="Resolved"){return{_tag:"TargetResolutionFailed",resolution}}const skillsCli=yield*SkillsCli;const[globalResult,projectResult]=yield*all2([result2(skillsCli.list({agent:input2.activeAgent,cwd:operatorSkillScopeCwd("global",input2),scope:"global",target:resolution.target})),result2(skillsCli.list({agent:input2.activeAgent,cwd:operatorSkillScopeCwd("project-local",input2),scope:"project",target:resolution.target}))],{concurrency:"unbounded"});const inspections=[isFailure2(globalResult)?failedInspection("global",input2,globalResult.failure):inspectListedSkills("global",input2,globalResult.success),isFailure2(projectResult)?failedInspection("project-local",input2,projectResult.failure):inspectListedSkills("project-local",input2,projectResult.success)];const installed=resolveInstalledOperatorSkillState({activeAgent:input2.activeAgent,cwd:input2.cwd,inspections:installedInspections(inspections)});return{_tag:"Inspected",inspections,installed,legacy:collectLegacyCopies(inspections),target:resolution.target}});var retryFor=(operation,scope3,input2,target)=>Object.freeze({input:Object.freeze({...input2}),operation,scope:scope3,target});var inspectionFor=(status2,scope3)=>status2.inspections.find((inspection)=>inspection.scope===scope3);var copyMatchesTarget=(copy3,target)=>copy3.version===target.version&©3.source===target.source&©3.revision===target.revision&©3.compatibility==="compatible";var copyAppliesToScope=(copy3,input2)=>copy3.boundAgents.includes(input2.activeAgent)&&(copy3.scope==="global"||copy3.projectRoot===input2.projectRoot);var targetCopy=(inspection,input2,target)=>inspection.copies.find((copy3)=>copyMatchesTarget(copy3,target)&©AppliesToScope(copy3,input2));var hasCompetingCopyIdentity=(inspection,copy3,input2)=>inspection.copies.some((candidate)=>copyAppliesToScope(candidate,input2)&&installedOperatorSkillCopyIdentity(candidate)!==installedOperatorSkillCopyIdentity(copy3));var verifyOperatorSkillScope=(scope3,input2,target,verification)=>{if(verification._tag==="TargetResolutionFailed"){return{_tag:"Unverified",reason:"TargetResolutionFailed",scope:scope3,verification}}const inspection=inspectionFor(verification,scope3);if(inspection?._tag==="InspectionFailed"){return{_tag:"Unverified",failure:inspection.failure,reason:"InspectionFailed",scope:scope3,verification}}if(inspection!==undefined){const copy3=targetCopy(inspection,input2,target);if(copy3!==undefined){if(hasCompetingCopyIdentity(inspection,copy3,input2)){return{_tag:"Unverified",reason:"CompetingCopyObserved",scope:scope3,verification}}return{_tag:"Verified",copy:copy3,scope:scope3,verification}}}return{_tag:"Unverified",reason:"TargetNotObserved",scope:scope3,verification}};var ensureAndVerifyOperatorSkillScope=fn2("OperatorSkillLifecycle.ensureAndVerifyScope")(function*ensureAndVerifyOperatorSkillScope2(scope3,input2,target){const skillsCli=yield*SkillsCli;const write2=yield*result2(skillsCli.install({agent:input2.activeAgent,cwd:operatorSkillScopeCwd(scope3,input2),scope:scope3==="global"?"global":"project",target}));if(isFailure2(write2)){return{_tag:"Failed",failure:write2.failure,scope:scope3}}const verification=yield*inspectOperatorSkillLifecycle(input2);return verifyOperatorSkillScope(scope3,input2,target,verification)});var mutationActionFor=(operation,input2,target,result4)=>{const retry5=retryFor(operation,result4.scope,input2,target);if(result4._tag==="Failed"){return{_tag:"Failed",failure:result4.failure,operation,phase:"write",retry:retry5,scope:result4.scope}}if(result4._tag==="Unverified"){return{...result4,operation,retry:retry5}}return{...result4,operation}};var inspectionDetectedOperatorSkill=(inspection)=>inspection.copies.length>0||inspection._tag==="InspectionFailed"&&(inspection.failure._tag==="SkillsCliVerificationFailure"||inspection.failure._tag==="SkillsCliBindingFailure")&&inspection.failure.skillName==="hi-cli";var inspectionScopeIsUnknown=(inspection)=>inspection._tag==="InspectionFailed"&&!inspectionDetectedOperatorSkill(inspection);var alreadyVerifiedGlobal=(before,input2)=>{const inspection=inspectionFor(before,"global");if(inspection?._tag!=="Inspected"){return}const copy3=targetCopy(inspection,input2,before.target);if(copy3===undefined||hasCompetingCopyIdentity(inspection,copy3,input2)){return}return{_tag:"AlreadyVerified",copy:copy3,operation:"install",scope:"global",verification:before}};var unknownScopeFailures=(operation,before,input2)=>before.inspections.flatMap((inspection)=>inspectionScopeIsUnknown(inspection)&&(operation==="update"||inspection.scope==="global")?[{_tag:"Failed",failure:inspection.failure,operation,phase:"inspection",retry:retryFor(operation,inspection.scope,input2,before.target),scope:inspection.scope}]:[]);var scopesToMutate=(operation,before)=>{if(operation==="install"){const globalIsUnknown=before.inspections.some((inspection)=>inspection.scope==="global"&&inspectionScopeIsUnknown(inspection));return globalIsUnknown?[]:["global"]}return before.inspections.filter(inspectionDetectedOperatorSkill).map((inspection)=>inspection.scope)};var mutateOperatorSkill=fn2("OperatorSkillLifecycle.mutate")(function*mutateOperatorSkill2(operation,input2){const before=yield*inspectOperatorSkillLifecycle(input2);if(before._tag==="TargetResolutionFailed"){return{_tag:"TargetResolutionFailed",actions:[],before,operation,reload:{_tag:"NotRequired"}}}const existingGlobal=operation==="install"?alreadyVerifiedGlobal(before,input2):undefined;const actions=[...unknownScopeFailures(operation,before,input2),...existingGlobal===undefined?[]:[existingGlobal]];let wrote=false;const scopes=existingGlobal===undefined?scopesToMutate(operation,before):[];for(const scope3 of scopes){const ensured=yield*ensureAndVerifyOperatorSkillScope(scope3,input2,before.target);wrote||=ensured._tag!=="Failed";actions.push(mutationActionFor(operation,input2,before.target,ensured))}return{_tag:"Completed",actions,before,operation,reload:wrote?{_tag:"ReloadRequired",skill:"hi-cli"}:{_tag:"NotRequired"},target:before.target}});var installOperatorSkill=fn2("OperatorSkillLifecycle.install")(function*installOperatorSkill2(input2){return yield*mutateOperatorSkill("install",input2)});var updateOperatorSkill=fn2("OperatorSkillLifecycle.update")(function*updateOperatorSkill2(input2){return yield*mutateOperatorSkill("update",input2)});var migrationRetry=(scope3,input2,target,phase,affectedScopes)=>Object.freeze({affectedScopes:Object.freeze([...affectedScopes]),input:Object.freeze({...input2}),operation:"migrate",phase,scope:scope3,target});var affectedScopes=(before,input2)=>["global","project-local"].filter((scope3)=>(scope3==="global"||isWithinCanonicalPath(input2.cwd,input2.projectRoot))&&before.inspections.some((inspection)=>inspection.scope===scope3&&inspection.legacy.some((copy3)=>copy3.boundAgents.includes(input2.activeAgent))));var scopeApplies=(scope3,input2)=>scope3==="global"||isWithinCanonicalPath(input2.cwd,input2.projectRoot);var recoverableScopes=(input2,scopes)=>["global","project-local"].filter((scope3)=>scopes.includes(scope3)&&scopeApplies(scope3,input2));var targetIdentity=(target)=>JSON.stringify([target.source,target.version,target.revision,target.cliCompatibility,target.contentManifest]);var legacyIdentity=(copy3)=>JSON.stringify([copy3.scope,copy3.scope==="project-local"?copy3.projectRoot:"",copy3.path,[...copy3.boundAgents].toSorted()]);var inspectedLegacyCopiesFor=(status2,scope3)=>{if(status2._tag!=="Inspected"){return}const inspection=status2.inspections.find((candidate)=>candidate.scope===scope3);return inspection?._tag==="Inspected"?inspection.legacy:undefined};var legacyCopiesFor=(status2,scope3)=>inspectedLegacyCopiesFor(status2,scope3)??[];var legacyCopiesMatch=(left,right)=>JSON.stringify(left.map(legacyIdentity).toSorted())===JSON.stringify(right.map(legacyIdentity).toSorted());var unrelatedLegacyResiduals=(copies,activeAgent)=>copies.flatMap((copy3)=>{const boundAgents=copy3.boundAgents.filter((agent)=>agent!==activeAgent);return boundAgents.length===0?[]:[{...copy3,boundAgents}]});var replacementAction=(result4,input2,target,scopes,wrote=true)=>{const retry5=migrationRetry(result4.scope,input2,target,"replacement",scopes);if(result4._tag==="Failed"){return{_tag:"ReplacementFailed",failure:result4.failure,retry:retry5,scope:result4.scope}}if(result4._tag==="Unverified"){return{_tag:"ReplacementUnverified",...result4.failure===undefined?{}:{failure:result4.failure},reason:result4.reason,retry:retry5,scope:result4.scope,verification:result4.verification}}return{_tag:"ReplacementVerified",copy:result4.copy,scope:result4.scope,verification:result4.verification,wrote}};var reloadGuidance=(wrote)=>wrote?{_tag:"ReloadRequired",skill:"hi-cli"}:{_tag:"NotRequired"};var verifyBarrierCopy=(scope3,input2,target,verification,expected)=>{const observed=verifyOperatorSkillScope(scope3,input2,target,verification);if(observed._tag!=="Verified"){return observed}if(expected===undefined||installedOperatorSkillCopyIdentity(observed.copy)!==installedOperatorSkillCopyIdentity(expected)){return{_tag:"Unverified",reason:"ReplacementChanged",scope:scope3,verification}}return observed};var legacyRemovalReason=(reason)=>{if(reason==="InspectionFailed"){return"InspectionFailed"}return reason==="ReplacementChanged"?"ReplacementChanged":"ReplacementNotVerified"};var validateAffectedBarriers=(input2)=>(()=>{let blockingLoss;return input2.scopes.flatMap((scope3,scopeIndex)=>{const pending=scopeIndex>input2.afterIndex;const checked=verifyBarrierCopy(scope3,input2.migrationInput,input2.target,input2.verification,input2.barrierCopies.get(scope3));if(checked._tag==="Verified"){if(!pending||blockingLoss===undefined||input2.refusedScopes.has(scope3)){return[]}input2.refusedScopes.add(scope3);return[{_tag:"LegacyRemovalRefused",barrierReason:blockingLoss.reason,barrierScope:blockingLoss.scope,...blockingLoss.failure===undefined?{}:{failure:blockingLoss.failure},reason:"BarrierLost",retry:migrationRetry(scope3,input2.migrationInput,input2.target,"removal",input2.scopes),scope:scope3,verification:input2.verification}]}if(pending&&input2.refusedScopes.has(scope3)){return[]}const failure="failure"in checked&&checked.failure!==undefined?{failure:checked.failure}:{};if(pending){input2.refusedScopes.add(scope3);return[{_tag:"LegacyRemovalRefused",barrierReason:checked.reason,barrierScope:scope3,...failure,reason:"BarrierLost",retry:migrationRetry(scope3,input2.migrationInput,input2.target,"removal",input2.scopes),scope:scope3,verification:input2.verification}]}blockingLoss={reason:checked.reason,scope:scope3,...failure};if(input2.lostBarrierScopes.has(scope3)){return[]}input2.lostBarrierScopes.add(scope3);return[{_tag:"RemovalBarrierLost",afterScope:input2.afterScope,barrierReason:checked.reason,...failure,phase:input2.phase,position:scopeIndex===input2.afterIndex?"current":"prior",retry:migrationRetry(scope3,input2.migrationInput,input2.target,"removal",input2.scopes),scope:scope3,verification:input2.verification}]})})();var validatePeerLegacySnapshots=(input2)=>input2.scopes.flatMap((scope3,scopeIndex)=>{if(scopeIndex===input2.afterIndex){return[]}const observed=inspectedLegacyCopiesFor(input2.verification,scope3);if(observed===undefined){return[]}const activeChanged=!legacyCopiesMatch(input2.activeSnapshots.get(scope3)??[],observed.filter((copy3)=>copy3.boundAgents.includes(input2.migrationInput.activeAgent)));const unrelatedChanged=!legacyCopiesMatch(input2.unrelatedSnapshots.get(scope3)??[],unrelatedLegacyResiduals(observed,input2.migrationInput.activeAgent));if(!activeChanged&&!unrelatedChanged){return[]}const legacyReason=unrelatedChanged?"UnrelatedLegacyChanged":"ActiveLegacyChanged";const retry5=migrationRetry(scope3,input2.migrationInput,input2.target,"removal",input2.scopes);if(scopeIndex>input2.afterIndex){if(input2.refusedScopes.has(scope3)){return[]}input2.refusedScopes.add(scope3);return[{_tag:"LegacyRemovalRefused",legacyReason,reason:"LegacyChanged",retry:retry5,scope:scope3,verification:input2.verification}]}if(input2.reportedScopes.has(scope3)){return[]}input2.reportedScopes.add(scope3);return[{_tag:"LegacyRemovalUnverified",reason:activeChanged?"LegacyChangedAfterRemoval":"UnrelatedLegacyChanged",retry:retry5,scope:scope3,verification:input2.verification}]});var handleFailedLegacyRemoval=fn2("OperatorSkillLifecycle.handleFailedLegacyRemoval")(function*handleFailedLegacyRemoval2(context4,failure){const{activeLegacyCopies,barrierCopies,input:input2,lostBarrierScopes,refusedScopes,reportedLegacyScopes,retry:retry5,scope:scope3,scopeIndex,scopes,target,unrelatedLegacyCopies}=context4;const actions=[{_tag:"LegacyRemovalFailed",failure,retry:retry5,scope:scope3}];let wrote=false;const verification=yield*inspectOperatorSkillLifecycle(input2);const observedLegacy=inspectedLegacyCopiesFor(verification,scope3);const activeLegacyChanged=observedLegacy!==undefined&&!legacyCopiesMatch(activeLegacyCopies.get(scope3)??[],observedLegacy.filter((copy3)=>copy3.boundAgents.includes(input2.activeAgent)));const unrelatedLegacyChanged=observedLegacy!==undefined&&!legacyCopiesMatch(unrelatedLegacyCopies.get(scope3)??[],unrelatedLegacyResiduals(observedLegacy,input2.activeAgent));if(activeLegacyChanged||unrelatedLegacyChanged){wrote=true;actions.push({_tag:"LegacyRemovalUnverified",reason:activeLegacyChanged?"LegacyChangedAfterFailure":"UnrelatedLegacyChanged",retry:retry5,scope:scope3,verification})}const peerLegacyActions=validatePeerLegacySnapshots({activeSnapshots:activeLegacyCopies,afterIndex:scopeIndex,migrationInput:input2,refusedScopes,reportedScopes:reportedLegacyScopes,scopes,target,unrelatedSnapshots:unrelatedLegacyCopies,verification});wrote||=peerLegacyActions.length>0;actions.push(...peerLegacyActions);const barrierActions=validateAffectedBarriers({afterIndex:scopeIndex,afterScope:scope3,barrierCopies,lostBarrierScopes,migrationInput:input2,phase:"remove-failed",refusedScopes,scopes,target,verification});wrote||=barrierActions.some((action2)=>action2.barrierReason!=="InspectionFailed"&&action2.barrierReason!=="TargetResolutionFailed");actions.push(...barrierActions);if(observedLegacy!==undefined){activeLegacyCopies.set(scope3,observedLegacy.filter((copy3)=>copy3.boundAgents.includes(input2.activeAgent)));unrelatedLegacyCopies.set(scope3,unrelatedLegacyResiduals(observedLegacy,input2.activeAgent))}return{actions,wrote}});var handleSuccessfulLegacyRemoval=fn2("OperatorSkillLifecycle.handleSuccessfulLegacyRemoval")(function*handleSuccessfulLegacyRemoval2(context4){const{activeLegacyCopies,barrierCopies,input:input2,lostBarrierScopes,refusedScopes,reportedLegacyScopes,retry:retry5,scope:scope3,scopeIndex,scopes,target,unrelatedLegacyCopies}=context4;const verification=yield*inspectOperatorSkillLifecycle(input2);let currentAction;if(verification._tag==="TargetResolutionFailed"){currentAction={_tag:"LegacyRemovalUnverified",reason:"ReplacementNotVerified",retry:retry5,scope:scope3,verification}}else{const inspection=verification.inspections.find((candidate)=>candidate.scope===scope3);const observedLegacy=inspectedLegacyCopiesFor(verification,scope3);const unrelatedLegacyChanged=observedLegacy!==undefined&&!legacyCopiesMatch(unrelatedLegacyCopies.get(scope3)??[],unrelatedLegacyResiduals(observedLegacy,input2.activeAgent));if(unrelatedLegacyChanged){currentAction={_tag:"LegacyRemovalUnverified",reason:"UnrelatedLegacyChanged",retry:retry5,scope:scope3,verification}}else if(inspection!==undefined&&inspection.legacy.some((copy3)=>copy3.boundAgents.includes(input2.activeAgent))){currentAction={_tag:"LegacyRemovalUnverified",reason:"LegacyStillPresent",retry:retry5,scope:scope3,verification}}else{const replacementCheck=verifyBarrierCopy(scope3,input2,target,verification,barrierCopies.get(scope3));currentAction=replacementCheck._tag==="Verified"?{_tag:"LegacyRemoved",scope:scope3,verification}:{_tag:"LegacyRemovalUnverified",..."failure"in replacementCheck&&replacementCheck.failure!==undefined?{failure:replacementCheck.failure}:{},reason:legacyRemovalReason(replacementCheck.reason),retry:retry5,scope:scope3,verification}}}const actions=[currentAction,...validatePeerLegacySnapshots({activeSnapshots:activeLegacyCopies,afterIndex:scopeIndex,migrationInput:input2,refusedScopes,reportedScopes:reportedLegacyScopes,scopes,target,unrelatedSnapshots:unrelatedLegacyCopies,verification})];const observedCurrentLegacy=inspectedLegacyCopiesFor(verification,scope3);if(observedCurrentLegacy!==undefined){activeLegacyCopies.set(scope3,observedCurrentLegacy.filter((copy3)=>copy3.boundAgents.includes(input2.activeAgent)))}actions.push(...validateAffectedBarriers({afterIndex:scopeIndex,afterScope:scope3,barrierCopies,lostBarrierScopes,migrationInput:input2,phase:"remove-succeeded",refusedScopes,scopes,target,verification}));return actions});var prepareMigration=(before,input2,recoveryScopes,recoveryPhase)=>{const observedScopes=affectedScopes(before,input2);const recoveryScopeLimit=recoveryScopes===undefined?undefined:recoverableScopes(input2,recoveryScopes);let scopes=observedScopes;if(recoveryScopeLimit!==undefined){scopes=recoveryPhase==="preflight"?observedScopes.filter((scope3)=>recoveryScopeLimit.includes(scope3)):recoveryScopeLimit}const retryScopes=recoveryScopeLimit===undefined?recoverableScopes(input2,[...scopes,...before.inspections.flatMap((inspection)=>inspection._tag==="InspectionFailed"?[inspection.scope]:[])]):recoveryScopeLimit;const preflightFailures=before.inspections.flatMap((inspection)=>inspection._tag==="InspectionFailed"&&scopeApplies(inspection.scope,input2)&&(recoveryScopeLimit===undefined||recoveryScopeLimit.includes(inspection.scope))?[{_tag:"PreflightFailed",failure:inspection.failure,retry:migrationRetry(inspection.scope,input2,before.target,"preflight",retryScopes),scope:inspection.scope}]:[]);return{preflightFailures,scopes}};var ensureReplacementBarriers=fn2("OperatorSkillLifecycle.ensureReplacementBarriers")(function*ensureReplacementBarriers2(scopes,input2,before){const actions=[];let wrote=false;let barrierFailed=false;for(const scope3 of scopes){const existing=verifyOperatorSkillScope(scope3,input2,before.target,before);if(existing._tag==="Verified"){actions.push({_tag:"ReplacementVerified",copy:existing.copy,scope:scope3,verification:existing.verification,wrote:false});continue}const replacement=yield*ensureAndVerifyOperatorSkillScope(scope3,input2,before.target);wrote||=replacement._tag!=="Failed";barrierFailed||=replacement._tag!=="Verified";actions.push(replacementAction(replacement,input2,before.target,scopes))}return{actions,barrierFailed,wrote}});var inspectReplacementBarrier=fn2("OperatorSkillLifecycle.inspectReplacementBarrier")(function*inspectReplacementBarrier2(scopes,input2,target,recoveryScopes){const status2=yield*inspectOperatorSkillLifecycle(input2);const failedInspections=status2._tag==="Inspected"?status2.inspections.filter((inspection)=>inspection._tag==="InspectionFailed"&&scopeApplies(inspection.scope,input2)&&(recoveryScopes===undefined||scopes.includes(inspection.scope))):[];const failedScopes=new Set(failedInspections.map((inspection)=>inspection.scope));const verifications=scopes.flatMap((scope3)=>{if(failedScopes.has(scope3)){return[]}const verification=verifyOperatorSkillScope(scope3,input2,target,status2);return[{scope:scope3,verification}]});const actions=[...failedInspections.map((inspection)=>({_tag:"BarrierInspectionFailed",failure:inspection.failure,retry:migrationRetry(inspection.scope,input2,target,"barrier",scopes),scope:inspection.scope})),...verifications.flatMap(({scope:scope3,verification})=>verification._tag==="Unverified"?[{_tag:"BarrierUnverified",...verification.failure===undefined?{}:{failure:verification.failure},reason:verification.reason,retry:migrationRetry(scope3,input2,target,"barrier",scopes),scope:scope3,verification:verification.verification}]:[])];return{actions,status:status2,verifications}});var migrateLegacyOperatorSkillPolicy=fn2("OperatorSkillLifecycle.migratePolicy")(function*migrateLegacyOperatorSkillPolicy2(input2,recoveryScopes,expectedTarget,recoveryPhase){const before=yield*inspectOperatorSkillLifecycle(input2);if(before._tag==="TargetResolutionFailed"){return{_tag:"TargetResolutionFailed",actions:[],before,reload:{_tag:"NotRequired"}}}if(expectedTarget!==undefined&&targetIdentity(expectedTarget)!==targetIdentity(before.target)){return{_tag:"RetryTargetChanged",actions:[],expected:expectedTarget,observed:before.target,reload:{_tag:"NotRequired"}}}const{preflightFailures,scopes}=prepareMigration(before,input2,recoveryScopes,recoveryPhase);if(preflightFailures.length>0){return{_tag:"Refused",actions:preflightFailures,before,reason:"PreflightUnknown",reload:{_tag:"NotRequired"},target:before.target}}if(scopes.length===0){return{_tag:"Completed",actions:[],before,reload:{_tag:"NotRequired"},target:before.target}}const replacement=yield*ensureReplacementBarriers(scopes,input2,before);const actions=[...replacement.actions];let{wrote}=replacement;if(replacement.barrierFailed){return{_tag:"Refused",actions,before,reason:"ReplacementBarrierFailed",reload:reloadGuidance(wrote),target:before.target}}const barrier=yield*inspectReplacementBarrier(scopes,input2,before.target,recoveryScopes);const finalBarrier=barrier.status;const finalVerifications=barrier.verifications;actions.push(...barrier.actions);if(barrier.actions.length>0){return{_tag:"Refused",actions,before,reason:"ReplacementBarrierFailed",reload:reloadGuidance(wrote),target:before.target}}const barrierCopies=new Map(finalVerifications.flatMap(({scope:scope3,verification})=>verification._tag==="Verified"?[[scope3,verification.copy]]:[]));const activeLegacyCopies=new Map(scopes.map((scope3)=>[scope3,legacyCopiesFor(finalBarrier,scope3).filter((copy3)=>copy3.boundAgents.includes(input2.activeAgent))]));const unrelatedLegacyCopies=new Map(scopes.map((scope3)=>[scope3,unrelatedLegacyResiduals(legacyCopiesFor(finalBarrier,scope3),input2.activeAgent)]));const skillsCli=yield*SkillsCli;const refusedScopes=new Set;const lostBarrierScopes=new Set;const reportedLegacyScopes=new Set;for(const scope3 of scopes){if(!(activeLegacyCopies.get(scope3)??[]).some((copy3)=>copy3.boundAgents.some((agent)=>agent!==input2.activeAgent))){continue}refusedScopes.add(scope3);actions.push({_tag:"LegacyRemovalRefused",legacyReason:"SharedResidualUnverifiable",reason:"ResidualBindingsUnverifiable",retry:migrationRetry(scope3,input2,before.target,"removal",scopes),scope:scope3,verification:finalBarrier})}const removalScopes=scopes.filter((scope3)=>(activeLegacyCopies.get(scope3)??[]).length>0);for(const scope3 of removalScopes){const scopeIndex=scopes.indexOf(scope3);if(refusedScopes.has(scope3)){continue}const remove7=yield*result2(skillsCli.remove({agent:input2.activeAgent,cwd:operatorSkillScopeCwd(scope3,input2),name:"dp-cli",scope:scope3==="global"?"global":"project"}));const retry5=migrationRetry(scope3,input2,before.target,"removal",scopes);const context4={activeLegacyCopies,barrierCopies,input:input2,lostBarrierScopes,refusedScopes,reportedLegacyScopes,retry:retry5,scope:scope3,scopeIndex,scopes,target:before.target,unrelatedLegacyCopies};if(isFailure2(remove7)){const failureResult=yield*handleFailedLegacyRemoval(context4,remove7.failure);wrote||=failureResult.wrote;actions.push(...failureResult.actions);continue}wrote=true;actions.push(...yield*handleSuccessfulLegacyRemoval(context4))}return{_tag:"Completed",actions,before,reload:reloadGuidance(wrote),target:before.target}});var migrateLegacyOperatorSkill=fn2("OperatorSkillLifecycle.migrate")(function*migrateLegacyOperatorSkill2(input2){return yield*migrateLegacyOperatorSkillPolicy(input2)});var retryLegacyOperatorSkillMigration=fn2("OperatorSkillLifecycle.retryMigration")(function*retryLegacyOperatorSkillMigration2(retry5,currentInput){return yield*migrateLegacyOperatorSkillPolicy({...retry5.input,activeCliVersion:currentInput.activeCliVersion},retry5.affectedScopes,retry5.target,retry5.phase)});var migrationRetrySchema=Struct({affectedScopes:ArraySchema(Literals(["global","project-local"])),input:Struct({activeAgent:String5,activeCliVersion:String5,cwd:String5,projectRoot:String5}),operation:Literal2("migrate"),phase:Literals(["barrier","preflight","removal","replacement"]),scope:Literals(["global","project-local"]),target:Struct({cliCompatibility:Struct({maximumExclusive:String5,minimum:String5}),contentManifest:ArraySchema(Struct({path:String5,sha256:String5})),revision:String5,source:String5,version:String5})});var mutationRetrySchema=Struct({input:Struct({activeAgent:String5,activeCliVersion:String5,cwd:String5,projectRoot:String5}),operation:Literals(["install","update"]),scope:Literals(["global","project-local"]),target:migrationRetrySchema.fields.target});var encodeMigrationRetry=(retry5)=>Buffer.from(JSON.stringify(retry5),"utf-8").toString("base64url");var decodeMigrationRetry=(token)=>try_3({catch:()=>new InvalidMigrationRetry({message:"Migration retry token is invalid or stale."}),try:()=>decodeUnknownSync2(migrationRetrySchema)(JSON.parse(Buffer.from(token,"base64url").toString("utf-8")))});var encodeMutationRetry=(retry5)=>Buffer.from(JSON.stringify(retry5),"utf-8").toString("base64url");var decodeMutationRetry=(token)=>try_3({catch:()=>new InvalidMutationRetry({message:"Operator mutation retry token is invalid or stale."}),try:()=>decodeUnknownSync2(mutationRetrySchema)(JSON.parse(Buffer.from(token,"base64url").toString("utf-8")))});var targetIdentity2=(target)=>JSON.stringify([target.source,target.version,target.revision,target.cliCompatibility,target.contentManifest]);var retryOperatorSkillMutation=(retry5,action2,currentInput)=>gen2(function*executeMutationRetry(){if(retry5.operation!==action2){return yield*new InvalidMutationRetry({message:`Operator mutation retry is for ${retry5.operation}, not ${action2}.`})}const retryInput={...retry5.input,activeCliVersion:currentInput.activeCliVersion};const before=yield*inspectOperatorSkillLifecycle(retryInput);if(before._tag==="TargetResolutionFailed"){return{_tag:"TargetResolutionFailed",actions:[],before,operation:retry5.operation,reload:{_tag:"NotRequired"}}}if(targetIdentity2(before.target)!==targetIdentity2(retry5.target)){return yield*new InvalidMutationRetry({message:"Operator mutation retry target changed; rerun the operator command."})}if(retry5.operation==="install"&&retry5.scope!=="global"){return yield*new InvalidMutationRetry({message:"Operator install retry scope changed; rerun the operator command."})}const inspection=inspectionFor(before,retry5.scope);if(inspection===undefined){return yield*new InvalidMutationRetry({message:"Operator mutation retry scope changed; rerun the operator command."})}if(inspectionScopeIsUnknown(inspection)){return{_tag:"Completed",actions:[{_tag:"Failed",failure:inspection.failure,operation:retry5.operation,phase:"inspection",retry:retry5,scope:retry5.scope}],before,operation:retry5.operation,reload:{_tag:"NotRequired"},target:retry5.target}}const updateIsAuthorized=retry5.operation==="update"&&inspectionDetectedOperatorSkill(inspection);const installIsAuthorized=retry5.operation==="install";if(!updateIsAuthorized&&!installIsAuthorized){return yield*new InvalidMutationRetry({message:"Operator mutation retry state changed; rerun the operator command."})}const result4=yield*ensureAndVerifyOperatorSkillScope(retry5.scope,retryInput,retry5.target);let mutationAction;if(result4._tag==="Failed"){mutationAction={...result4,operation:retry5.operation,phase:"write",retry:retry5}}else if(result4._tag==="Unverified"){mutationAction={...result4,operation:retry5.operation,retry:retry5}}else{mutationAction={...result4,operation:retry5.operation}}return{_tag:"Completed",actions:[mutationAction],before,operation:retry5.operation,reload:result4._tag==="Failed"?{_tag:"NotRequired"}:{_tag:"ReloadRequired",skill:"hi-cli"},target:retry5.target}});var executeOperatorAction=fn2("OperatorSkill.execute")(function*executeOperatorAction2(request3){const{action:action2,input:input2}=request3;if(action2==="status"){const lifecycle2=yield*inspectOperatorSkillLifecycle(input2);return{action:action2,lifecycle:lifecycle2}}if(action2==="install"||action2==="update"){const lifecycle2=request3.mutationRetryToken===undefined?yield*action2==="install"?installOperatorSkill(input2):updateOperatorSkill(input2):yield*decodeMutationRetry(request3.mutationRetryToken).pipe(flatMap4((retry5)=>retryOperatorSkillMutation(retry5,action2,input2)));return{action:action2,lifecycle:lifecycle2}}const lifecycle=request3.migrationRetryToken===undefined?yield*migrateLegacyOperatorSkill(input2):yield*decodeMigrationRetry(request3.migrationRetryToken).pipe(flatMap4((retry5)=>retryLegacyOperatorSkillMigration(retry5,input2)));return{action:action2,lifecycle}});var operatorCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator status",summary:"Inspect effective operator skill state."}],group:"commands",interaction:"none",name:"operator",options:[],outputModes:["interactive","plain","json"],summary:"Manage the Harness operator skill."});var operatorStatusCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator status",summary:"Run operator status."}],group:"operator",interaction:"optional",name:"status",options:[],outputModes:["interactive","plain","json"],summary:"Show immutable hi-cli identity and effective installed state."});var operatorInstallCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator install",summary:"Run operator install."}],group:"operator",interaction:"optional",name:"install",options:[],outputModes:["interactive","plain","json"],summary:"Ensure and verify the global hi-cli operator skill."});var operatorUpdateCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator update",summary:"Run operator update."}],group:"operator",interaction:"optional",name:"update",options:[],outputModes:["interactive","plain","json"],summary:"Update and verify every detected hi-cli scope."});var operatorMigrateCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator migrate",summary:"Run operator migrate."}],group:"operator",interaction:"optional",name:"migrate",options:[],outputModes:["interactive","plain","json"],summary:"Verify replacements before removing legacy dp-cli copies."});var operatorActionMetadata=(action2)=>{switch(action2){case"status":{return operatorStatusCommandMetadata}case"install":{return operatorInstallCommandMetadata}case"update":{return operatorUpdateCommandMetadata}case"migrate":{return operatorMigrateCommandMetadata}default:{return action2}}};var publicOperatorFailure=(value5)=>{if(typeof value5!=="object"||value5===null){return value5}const failure=value5;return Object.fromEntries(["_tag","agent","exitCode","message","operation","reason","reportedAgents","scope","skillName"].filter((key)=>failure[key]!==undefined).map((key)=>[key,failure[key]]))};var operatorFact=(value5)=>JSON.stringify(value5,(key,nestedValue)=>{if(key==="stderr"||key==="stack"||key==="cause"){return}return key==="failure"?publicOperatorFailure(nestedValue):nestedValue});var quoteShellArgument=(value5)=>`'${value5.replaceAll("'",`'"'"'`)}'`;var quotePowerShellLiteral=(value5)=>`'${value5.replaceAll("'","''")}'`;var windowsPowerShellCommand=(statements)=>`powershell.exe -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(statements.join("; "),"utf16le").toString("base64")}`;var mutationRetryCommand=(action2,platform)=>{const retry5=encodeMutationRetry(action2.retry);if(platform==="win32"){return windowsPowerShellCommand([`Set-Location -LiteralPath ${quotePowerShellLiteral(action2.retry.input.cwd)}`,`$env:HI_OPERATOR_MUTATION_RETRY = ${quotePowerShellLiteral(retry5)}`,`$env:HI_OPERATOR_AGENT = ${quotePowerShellLiteral(action2.retry.input.activeAgent)}`,`& hi operator ${action2.retry.operation}`])}return`cd -- ${quoteShellArgument(action2.retry.input.cwd)} && HI_OPERATOR_MUTATION_RETRY=${retry5} HI_OPERATOR_AGENT=${quoteShellArgument(action2.retry.input.activeAgent)} hi operator ${action2.retry.operation}`};var migrationRetryCommand=(action2,platform)=>{const retry5=encodeMigrationRetry(action2.retry);if(platform==="win32"){return windowsPowerShellCommand([`Set-Location -LiteralPath ${quotePowerShellLiteral(action2.retry.input.cwd)}`,`$env:HI_OPERATOR_MIGRATION_RETRY = ${quotePowerShellLiteral(retry5)}`,`$env:HI_OPERATOR_AGENT = ${quotePowerShellLiteral(action2.retry.input.activeAgent)}`,"& hi operator migrate"])}return`cd -- ${quoteShellArgument(action2.retry.input.cwd)} && HI_OPERATOR_MIGRATION_RETRY=${retry5} HI_OPERATOR_AGENT=${quoteShellArgument(action2.retry.input.activeAgent)} hi operator migrate`};var publicTarget=(target)=>({cliCompatibility:target.cliCompatibility,revision:target.revision,source:target.source,version:target.version});var statusFromChangesAndIssues=(changeCount,issueCount)=>{if(issueCount>0){return changeCount>0?"partial":"failed"}return changeCount>0?"success":"no-op"};var operatorStatusOperationResult=(lifecycle)=>{if(lifecycle._tag==="TargetResolutionFailed"){return{changes:[],degradations:[],issues:[{action:"status",code:`operator-target-${lifecycle.resolution._tag}`,kind:"handled-failure",subject:operatorFact(lifecycle.resolution)}],nextActions:[{kind:"retry",subject:"operator:status"}],status:"failed",warnings:[]}}const changes=[{action:"operator-target",state:"completed",subject:operatorFact(publicTarget(lifecycle.target))},...lifecycle.inspections.map((inspection)=>({action:"operator-inspection",state:"completed",subject:operatorFact(inspection)})),{action:"operator-installed-state",state:"completed",subject:operatorFact(lifecycle.installed)},{action:"operator-legacy-copies",state:"completed",subject:operatorFact(lifecycle.legacy)}];let issues=[];if(lifecycle.installed._tag==="DetectionFailed"){issues=lifecycle.installed.failures.map((failure)=>({action:"status",code:"operator-detection-failed",errorMessage:failure.message,kind:"handled-failure",subject:operatorFact(failure)}))}else if(lifecycle.installed._tag==="Ambiguous"){issues=[{action:"status",code:"operator-installed-ambiguous",kind:"conflict",subject:operatorFact(lifecycle.installed.candidates)}]}let status2="success";if(lifecycle.installed._tag==="Ambiguous"){status2="conflict"}else if(lifecycle.installed._tag==="DetectionFailed"){status2="failed"}return{changes,degradations:[],issues,nextActions:issues.length===0?[{kind:"none"}]:[lifecycle.installed._tag==="Ambiguous"?{kind:"resolve",subject:"operator:status"}:{kind:"retry",subject:"operator:status"}],status:status2,warnings:[]}};var publicVerifiedMutationAction=(action2)=>({_tag:action2._tag,copy:action2.copy,operation:action2.operation,scope:action2.scope});var publicFailedMutationAction=(action2)=>({_tag:action2._tag,operation:action2.operation,phase:action2.phase,retry:action2.retry,scope:action2.scope});var publicAlreadyVerifiedMutationAction=(action2)=>({_tag:action2._tag,copy:action2.copy,operation:action2.operation,scope:action2.scope});var publicUnverifiedMutationAction=(action2)=>({_tag:action2._tag,operation:action2.operation,reason:action2.reason,retry:action2.retry,scope:action2.scope});var operatorMutationOperationResult=(lifecycle,platform=process.platform)=>{if(lifecycle._tag==="TargetResolutionFailed"){return{changes:[],degradations:[],issues:[{action:lifecycle.operation,code:`operator-target-${lifecycle.before.resolution._tag}`,kind:"handled-failure",subject:operatorFact(lifecycle.before.resolution)}],nextActions:[{kind:"retry",subject:`operator:${lifecycle.operation}`}],status:"failed",warnings:[]}}const completed=lifecycle.actions.filter((action2)=>action2._tag==="Verified");const failed=lifecycle.actions.filter((action2)=>action2._tag==="Failed");const alreadyVerified=lifecycle.actions.filter((action2)=>action2._tag==="AlreadyVerified");const unverified=lifecycle.actions.filter((action2)=>action2._tag==="Unverified");const retryActions=[...failed,...unverified];const changes=completed.map((action2)=>({action:action2.operation,state:"completed",subject:operatorFact(publicVerifiedMutationAction(action2))}));const noInstalledUpdate=lifecycle.operation==="update"&&lifecycle.actions.length===0;const issues=[...failed.map((action2)=>({action:action2.operation,code:`operator-${action2.operation}-${action2._tag}`,errorMessage:action2.failure.message,kind:"handled-failure",subject:operatorFact(publicFailedMutationAction(action2))})),...unverified.map((action2)=>({action:action2.operation,code:`operator-${action2.operation}-${action2._tag}`,errorMessage:action2.failure?.message,kind:"handled-failure",subject:operatorFact(publicUnverifiedMutationAction(action2))})),...noInstalledUpdate?[{action:"update",code:"operator-update-no-installed-scope",kind:"handled-failure",subject:operatorFact({before:lifecycle.before,target:publicTarget(lifecycle.target)})}]:[]];let nextActions=[{kind:"none"}];if(noInstalledUpdate){nextActions=[{kind:"run",subject:"hi operator install"}]}else if(retryActions.length>0){nextActions=retryActions.map((action2)=>({kind:"run",subject:mutationRetryCommand(action2,platform)}))}return{changes,degradations:[],issues,nextActions,status:statusFromChangesAndIssues(changes.length,issues.length),warnings:[...alreadyVerified.map((action2)=>({code:`operator-${action2.operation}-${action2._tag}`,subject:operatorFact(publicAlreadyVerifiedMutationAction(action2))})),...lifecycle.reload._tag==="ReloadRequired"?[{code:"reload-required",subject:lifecycle.reload.skill}]:[]]}};var migrationContext=(lifecycle)=>{if(lifecycle._tag==="RetryTargetChanged"){return{expected:publicTarget(lifecycle.expected),observed:publicTarget(lifecycle.observed),result:{_tag:lifecycle._tag}}}if(lifecycle._tag==="TargetResolutionFailed"){return{resolution:lifecycle.before.resolution,result:{_tag:lifecycle._tag}}}return{before:{inspections:lifecycle.before.inspections,installed:lifecycle.before.installed,legacy:lifecycle.before.legacy},result:{_tag:lifecycle._tag,...lifecycle._tag==="Refused"?{reason:lifecycle.reason}:{}},target:publicTarget(lifecycle.target)}};var migrationFailure=(action2)=>("failure"in action2)?action2.failure:undefined;var operatorMigrationOperationResult=(lifecycle,platform=process.platform)=>{if(lifecycle._tag==="RetryTargetChanged"){return{changes:[],degradations:[],issues:[{action:"migrate",code:"operator-migrate-RetryTargetChanged",kind:"conflict",subject:operatorFact(migrationContext(lifecycle))}],nextActions:[{kind:"retry",subject:"operator:migrate"}],status:"conflict",warnings:[]}}if(lifecycle._tag==="TargetResolutionFailed"){return{changes:[],degradations:[],issues:[{action:"migrate",code:`operator-target-${lifecycle.before.resolution._tag}`,kind:"handled-failure",subject:operatorFact(migrationContext(lifecycle))}],nextActions:[{kind:"retry",subject:"operator:migrate"}],status:"failed",warnings:[]}}const completed=lifecycle.actions.filter((action2)=>action2._tag==="LegacyRemoved"||action2._tag==="ReplacementVerified"&&action2.wrote);const noOp=lifecycle.actions.filter((action2)=>action2._tag==="ReplacementVerified"&&!action2.wrote);const failed=lifecycle.actions.filter((action2)=>action2._tag!=="LegacyRemoved"&&action2._tag!=="ReplacementVerified");const context4=migrationContext(lifecycle);const changes=completed.map((action2)=>({action:"migrate",state:"completed",subject:operatorFact(action2)}));const issues=failed.map((action2)=>{const failure=migrationFailure(action2);return{action:"migrate",code:`operator-migrate-${action2._tag}`,...failure===undefined?{}:{errorMessage:failure.message},kind:"handled-failure",subject:operatorFact({action:action2,...context4})}});if(lifecycle._tag==="Refused"&&issues.length===0){issues.push({action:"migrate",code:"operator-migrate-Refused",kind:"handled-failure",subject:operatorFact(context4)})}let nextActions=[{kind:"none"}];if(failed.length>0){nextActions=failed.map((action2)=>({kind:"run",subject:migrationRetryCommand(action2,platform)}))}else if(issues.length>0){nextActions=[{kind:"retry",subject:"operator:migrate"}]}return{changes,degradations:[],issues,nextActions,status:statusFromChangesAndIssues(changes.length,issues.length),warnings:[{code:"operator-migrate-context",subject:operatorFact(context4)},...noOp.map((action2)=>({code:"operator-migrate-ReplacementVerified",subject:operatorFact(action2)})),...lifecycle.reload._tag==="ReloadRequired"?[{code:"reload-required",subject:lifecycle.reload.skill}]:[]]}};var executeOperatorCommand=(action2,operation=runOperatorSkillApplication,interaction)=>gen2(function*runOperatorCommand(){const selectAgent=interaction?.mode==="interactive"?interaction.prompt.readLine("Enter the Skills CLI agent name: "):undefined;const result4=yield*operation(action2,selectAgent);if(result4.action==="status"){return operatorStatusOperationResult(result4.lifecycle)}if(result4.action==="migrate"){return operatorMigrationOperationResult(result4.lifecycle)}return operatorMutationOperationResult(result4.lifecycle)}).pipe(catchTag2("InvalidMigrationRetry",(failure)=>fail6(new CliValidationError({message:failure.message,recoveryCommand:"unset HI_OPERATOR_MIGRATION_RETRY; hi operator migrate"}))),catchTag2("InvalidOperatorContext",(failure)=>fail6(new CliValidationError({message:failure.message}))),catchTag2("InvalidMutationRetry",(failure)=>fail6(new CliValidationError({message:failure.message,recoveryCommand:`unset HI_OPERATOR_MUTATION_RETRY; hi operator ${action2}`}))));var makeOperatorAction=(action2,operation=runOperatorSkillApplication)=>{const metadata=operatorActionMetadata(action2);return exports_Command.make(metadata.name,{},()=>gen2(function*runOperatorAction(){const mode=yield*SelectedOutputMode;const prompt=yield*CliPrompt;return yield*captureCommandResult(executeOperatorCommand(action2,operation,{mode,prompt}))})).pipe(withCommandMetadata(metadata))};var operatorRootOperationResult={changes:[],degradations:[],issues:[],nextActions:[{kind:"run",subject:"hi operator status"},{kind:"run",subject:"hi operator install"},{kind:"run",subject:"hi operator update"},{kind:"run",subject:"hi operator migrate"}],status:"no-op",warnings:[{code:"operator-command-summary",subject:"Manage the Harness operator skill."}]};var operatorRootOperation=succeed6(operatorRootOperationResult);var operatorSubcommands=[makeOperatorAction("status"),makeOperatorAction("install"),makeOperatorAction("update"),makeOperatorAction("migrate")];var operatorCommandRoot=exports_Command.make(operatorCommandMetadata.name,{},()=>captureCommandResult(operatorRootOperation)).pipe(withCommandMetadata(operatorCommandMetadata));var operatorCommand=operatorCommandRoot.pipe(exports_Command.withSubcommands(operatorSubcommands));class ReportConfigurationUnavailable extends TaggedErrorClass()("@punks/cli/report-submission/ReportConfigurationUnavailable",{cause:Defect(),message:String5,operation:Literal2("resolve-control-plane-url")}){}class ReportSubmissionResponseInvalid extends TaggedErrorClass()("@punks/cli/report-submission/ReportSubmissionResponseInvalid",{cause:Defect(),message:String5,operation:Literal2("validate-submission-response")}){}class ReportInputInvalid extends TaggedErrorClass()("@punks/cli/report-submission/ReportInputInvalid",{cause:Defect(),field:Literal2("body"),message:String5,operation:Literal2("validate-report-input")}){}class ReportSubmissionOperationFailure extends TaggedErrorClass()("@punks/cli/report-submission/ReportSubmissionOperationFailure",{cause:Defect(),message:String5,operation:Literals(["record-submitted","submit-report"])}){}var ReportSubmissionOperations=Service("@punks/cli/features/report-submission/ReportSubmissionOperations");var nonEmpty=(value5)=>{const trimmed=value5.trim();if(trimmed.length===0){const cause=new Error("Missing body. Pass a non-empty value.");return fail6(new ReportInputInvalid({cause,field:"body",message:cause.message,operation:"validate-report-input"}))}return succeed6(trimmed)};var csvLabels=(value5)=>value5===undefined?[]:value5.split(",").map((label)=>label.trim()).filter((label)=>label.length>0);var buildHarnessReport=fn2("ReportSubmission.build")(function*buildReport({title,body,message,type:type2,severity,area,repoRoot,skillPack,command,expected,actual,steps,labels}){const operations=yield*ReportSubmissionOperations;const validBody=yield*nonEmpty(body??message??[actual,expected,steps].filter(Boolean).join(`
|
|
344
344
|
|
|
345
|
-
`));const repository=operations.observeRepository(repoRoot);return{...title===undefined?{}:{title},body:validBody,type:type2,severity,createdAt:new Date().toISOString(),cliVersion:operations.cliVersion,area,...skillPack===undefined?{}:{skillPack},...command===undefined?{}:{command},...expected===undefined?{}:{expected},...actual===undefined?{}:{actual},...steps===undefined?{}:{steps},...labels===undefined?{}:{labels},...repository===undefined?{}:{repository}}});var runReportSubmissionApplication=fn2("ReportSubmission.run")(function*runReportSubmissionApplication2(input2){const operations=yield*ReportSubmissionOperations;const report=yield*buildHarnessReport({...input2,labels:csvLabels(input2.extraLabels)});const baseUrl2=yield*operations.resolveControlPlaneUrl();if(baseUrl2===undefined){const cause=new Error("Harness report API URL is not configured.");return yield*new ReportConfigurationUnavailable({cause,message:cause.message,operation:"resolve-control-plane-url"})}const submitted=yield*operations.submit(baseUrl2,report);yield*operations.recordSubmitted(input2.repoRoot);return submitted});var reportCommandMetadata=declareCommandMetadata({examples:[{command:"hi report --message '...'",summary:"Submit a Harness report."}],group:"commands",interaction:"none",name:"report",options:[{name:"message",summary:"Raw report text for Harness triage."},{name:"title",summary:"Deprecated: optional title hint. The API generates the final title."},{name:"body",summary:"Deprecated: optional body hint. The API generates the final body."},{name:"type",summary:"Report type."},{name:"severity",summary:"Report severity."},{name:"area",summary:"Harness area."},{name:"repo-root",summary:"Repository root used for safe git context."},{name:"skill-pack",summary:"Affected skill pack, for example `hi-cli` or `docs-ingest-phase`."},{name:"command",summary:"Affected CLI command, for example `hi report` or `hi init`."},{name:"expected",summary:"Expected behavior."},{name:"actual",summary:"Actual behavior."},{name:"steps",summary:"Reproduction steps or evidence summary."},{name:"labels",summary:"Comma-separated extra GitHub labels."},{name:"json",summary:"Print JSON output."}],outputModes:["interactive","plain","json"],summary:"Submit reusable Harness friction to GitHub-backed maintainer triage."});var messageOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"message")).pipe(withOptionMetadata(reportCommandMetadata,"message")));var titleOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"title")).pipe(withOptionMetadata(reportCommandMetadata,"title")));var bodyOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"body")).pipe(withOptionMetadata(reportCommandMetadata,"body")));var typeOption=exports_Flag.choice(metadataOptionName(reportCommandMetadata,"type"),["bug","docs","workflow","tooling","other"]).pipe(exports_Flag.withDefault("other"),withOptionMetadata(reportCommandMetadata,"type"));var severityOption=exports_Flag.choice(metadataOptionName(reportCommandMetadata,"severity"),["low","medium","high"]).pipe(exports_Flag.withDefault("medium"),withOptionMetadata(reportCommandMetadata,"severity"));var areaOption=exports_Flag.choice(metadataOptionName(reportCommandMetadata,"area"),["cli","wiki","skill","docs","workflow","backoffice","other"]).pipe(exports_Flag.withDefault("other"),withOptionMetadata(reportCommandMetadata,"area"));var repoRootOption=exports_Flag.string(metadataOptionName(reportCommandMetadata,"repo-root")).pipe(exports_Flag.withDefault(process.cwd()),withOptionMetadata(reportCommandMetadata,"repo-root"));var skillPackOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"skill-pack")).pipe(withOptionMetadata(reportCommandMetadata,"skill-pack")));var commandOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"command")).pipe(withOptionMetadata(reportCommandMetadata,"command")));var expectedOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"expected")).pipe(withOptionMetadata(reportCommandMetadata,"expected")));var actualOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"actual")).pipe(withOptionMetadata(reportCommandMetadata,"actual")));var stepsOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"steps")).pipe(withOptionMetadata(reportCommandMetadata,"steps")));var labelsOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"labels")).pipe(withOptionMetadata(reportCommandMetadata,"labels")));var jsonOption2=exports_Flag.boolean(metadataOptionName(reportCommandMetadata,"json")).pipe(withOptionMetadata(reportCommandMetadata,"json"));var optionalValue=(value5)=>isNone2(value5)||value5.value.trim().length===0?undefined:value5.value.trim();var reportExpectedFailure=(failure)=>{if(failure._tag==="@punks/cli/report-submission/ReportInputInvalid"){return new CliValidationError({message:"Report content is required.",recoveryCommand:"hi report --help"})}if(failure._tag==="@punks/cli/report-submission/ReportConfigurationUnavailable"){return new CliValidationError({message:"Harness report API URL is not configured.",recoveryCommand:"hi report"})}if(failure._tag==="@punks/cli/report-submission/ReportSubmissionResponseInvalid"){return new CliValidationError({message:"Harness report submission did not return a GitHub issue URL.",recoveryCommand:"hi report"})}return new CliValidationError({message:failure.operation==="record-submitted"?"Harness report submission could not be recorded locally.":"Harness report submission failed.",recoveryCommand:"hi report"})};var reportOperationResult=(submitted)=>{const{githubUrl}=submitted;const subject=githubUrl??submitted.reportId;return{changes:submitted.deduplicated===true?[]:[{action:`submit:${submitted.status}`,state:"completed",subject}],degradations:[],facts:{deduplicated:submitted.deduplicated===true,...githubUrl===undefined?{}:{githubUrl},kind:"report-submission",reportId:submitted.reportId,status:submitted.status,title:submitted.title??null},issues:[],nextActions:githubUrl===undefined?[]:[{kind:"review",subject:githubUrl}],status:submitted.deduplicated===true?"no-op":"success",warnings:submitted.deduplicated===true?[{code:"report-deduplicated",subject},{code:"report-status",subject:submitted.status}]:[]}};var executeReportCommand=(input2,operation=runReportSubmissionApplication)=>gen2(function*submitReport(){const submitted=yield*operation(input2).pipe(mapError3(reportExpectedFailure));return{...submitted,operation:reportOperationResult(submitted)}});var makeReportCommand=(operation=runReportSubmissionApplication)=>exports_Command.make(reportCommandMetadata.name,{actual:actualOption,area:areaOption,body:bodyOption,command:commandOption,expected:expectedOption,json:jsonOption2,labels:labelsOption,message:messageOption,repoRoot:repoRootOption,severity:severityOption,skillPack:skillPackOption,steps:stepsOption,title:titleOption,type:typeOption},({message,title,body,type:type2,severity,area,repoRoot,skillPack,command,expected,actual,steps,labels})=>captureCommandResult(executeReportCommand({actual:optionalValue(actual),area,body:optionalValue(body),command:optionalValue(command),expected:optionalValue(expected),extraLabels:optionalValue(labels),message:optionalValue(message),repoRoot,severity,skillPack:optionalValue(skillPack),steps:optionalValue(steps),title:optionalValue(title),type:type2},operation))).pipe(withCommandMetadata(reportCommandMetadata));var reportCommand=makeReportCommand();import path10 from"node:path";var RepositoryScaffoldingInteraction=Service("@punks/cli/features/repository-scaffolding/RepositoryScaffoldingInteraction");class RepositoryScaffoldingOperationFailure extends TaggedErrorClass()("@punks/cli/repository-scaffolding/RepositoryScaffoldingOperationFailure",{cause:Defect(),message:String5,operation:Literals(["initialize-repository","setup-repository"])}){}var RepositoryScaffoldingOperations=Service("@punks/cli/features/repository-scaffolding/RepositoryScaffoldingOperations");var runRepositoryScaffoldingApplication=fn2("RepositoryScaffolding.run")(function*runRepositoryScaffoldingApplication2(input2){const interaction=yield*RepositoryScaffoldingInteraction;const operations=yield*RepositoryScaffoldingOperations;return yield*operations.run(input2,interaction)});var outputSummary="Output directory for scaffolded files. Defaults to the current working directory.";var baselineSummary="Scaffold baseline to use: stable, bundled, or an exact version. Defaults to stable.";var refreshBaselineSummary="Refetch the stable baseline instead of reusing the local cache.";var initCommandMetadata=declareCommandMetadata({examples:[{command:"hi init",summary:"Initialize the current repository."}],group:"commands",interaction:"required",name:"init",options:[{name:"output",summary:outputSummary},{name:"baseline",summary:baselineSummary},{name:"refresh-baseline",summary:refreshBaselineSummary}],outputModes:["interactive","plain"],summary:"Seed docs onboarding, requirements/backlog/spec skills, and wiki structure. Agents: activate $hi-cli, then $docs-onboarding."});var scaffoldCommandMetadata=declareCommandMetadata({examples:[{command:"hi scaffold",summary:"Scaffold the current repository."}],group:"commands",interaction:"optional",name:"scaffold",options:[{name:"input",summary:"Repository root to scan. Defaults to the current working directory."},{name:"output",summary:outputSummary},{name:"json",summary:"Print the full machine-readable scaffold payload to stdout after completion."},{name:"repo-shape",summary:"Override repo shape detection. Use 'monorepo' or 'single' when auto-detection is not the desired scaffold mode."},{name:"baseline",summary:baselineSummary},{name:"refresh-baseline",summary:refreshBaselineSummary},{name:"yes",summary:"Run non-interactively and accept the resolved default scaffold selection."}],outputModes:["interactive","plain","json"],summary:"Repo-aware AI setup. Agents: activate $hi-cli, then reconcile .devpunks output with the real repo layout."});var silentNonInteractiveScaffoldingInteraction={confirmSelection:()=>die3("Non-interactive scaffold mode cannot confirm interactively"),emit:()=>void_3,keepPrefilledSelection:()=>die3("Non-interactive scaffold mode cannot edit the prefilled selection interactively"),selectPacks:()=>die3("Non-interactive scaffold mode cannot select packs interactively"),selectRepoSettings:()=>die3("Non-interactive scaffold mode cannot select repository settings interactively"),selectWikiFramework:()=>die3("Non-interactive scaffold mode cannot select a wiki framework interactively")};var outputOption=(metadata)=>exports_Flag.optional(exports_Flag.string(metadataOptionName(metadata,"output")).pipe(exports_Flag.withAlias("o"),withOptionMetadata(metadata,"output")));var inputOption2=exports_Flag.optional(exports_Flag.string(metadataOptionName(scaffoldCommandMetadata,"input")).pipe(exports_Flag.withAlias("i"),withOptionMetadata(scaffoldCommandMetadata,"input")));var jsonOption3=exports_Flag.boolean(metadataOptionName(scaffoldCommandMetadata,"json")).pipe(withOptionMetadata(scaffoldCommandMetadata,"json"));var repoShapeOption=exports_Flag.optional(exports_Flag.choice(metadataOptionName(scaffoldCommandMetadata,"repo-shape"),["auto","monorepo","single"]).pipe(withOptionMetadata(scaffoldCommandMetadata,"repo-shape")));var baselineOption2=(metadata)=>exports_Flag.optional(exports_Flag.string(metadataOptionName(metadata,"baseline")).pipe(withOptionMetadata(metadata,"baseline")));var refreshBaselineOption2=(metadata)=>exports_Flag.boolean(metadataOptionName(metadata,"refresh-baseline")).pipe(withOptionMetadata(metadata,"refresh-baseline"));var yesOption=exports_Flag.boolean(metadataOptionName(scaffoldCommandMetadata,"yes")).pipe(withOptionMetadata(scaffoldCommandMetadata,"yes"));var scaffoldOperationResult=(input2,result4)=>{const failedTools=result4.toolBootstrapStatuses.filter((tool)=>tool.status==="failed");const projectionPartial=result4.projectionStatus==="partial";const issues=[...projectionPartial?[{action:"project",code:"scaffold-projection-partial",errorMessage:"Scaffold projection completed partially.",kind:"handled-failure",subject:result4.outputDirectory}]:[],...failedTools.map((tool)=>({action:"bootstrap-required-tool",code:`scaffold-required-tool-${tool.toolId}-failed`,errorMessage:tool.errorMessage,kind:"handled-failure",subject:tool.toolId}))];return{changes:[{action:input2.kind==="init"?"initialize":"setup",state:"completed",subject:result4.outputDirectory},...result4.toolBootstrapStatuses.filter((tool)=>tool.status!=="failed").map((tool)=>({action:tool.status==="installed"?"install-required-tool":"verify-required-tool",state:"completed",subject:tool.toolId}))],degradations:[],issues,nextActions:issues.length===0?[{kind:"none"}]:[...failedTools.length===0?[]:[{kind:"run",subject:"hi tools ensure"}],...projectionPartial?[{kind:"review",subject:result4.outputDirectory}]:[]],status:issues.length===0?"success":"partial",warnings:[]}};var executeScaffoldCommand=(input2,operation=runRepositoryScaffoldingApplication)=>scoped2(gen2(function*executeScaffold(){const result4=yield*operation(input2);const operationResult=scaffoldOperationResult(input2,result4);return input2.kind==="setup"&&input2.emitJson?{jsonPayload:result4.machinePayload,operation:operationResult}:operationResult}));var makeInitCommand=(operation=runRepositoryScaffoldingApplication)=>exports_Command.make(initCommandMetadata.name,{baseline:baselineOption2(initCommandMetadata),output:outputOption(initCommandMetadata),refreshBaseline:refreshBaselineOption2(initCommandMetadata)},({output:output2,baseline,refreshBaseline})=>gen2(function*runInitCommand(){const outputMode=yield*SelectedOutputMode;if(outputMode!=="interactive"){return yield*new CliValidationError({message:outputMode==="json"?"`hi init` requires interactive input and is unavailable in JSON mode.":"`hi init` requires interactive input and is unavailable when output is redirected.",recoveryCommand:"hi init"})}return yield*captureCommandResult(executeScaffoldCommand({baseline:getOrUndefined(baseline),kind:"init",outputDirectory:path10.resolve(process.cwd(),getOrElse(output2,()=>".")),refreshBaseline},operation))})).pipe(withCommandMetadata(initCommandMetadata));var makeScaffoldCommand=(operation=runRepositoryScaffoldingApplication)=>exports_Command.make(scaffoldCommandMetadata.name,{baseline:baselineOption2(scaffoldCommandMetadata),input:inputOption2,json:jsonOption3,output:outputOption(scaffoldCommandMetadata),refreshBaseline:refreshBaselineOption2(scaffoldCommandMetadata),repoShape:repoShapeOption,yes:yesOption},({input:input2,output:output2,json:json3,repoShape,baseline,refreshBaseline,yes})=>gen2(function*runScaffoldCommand(){const selectedOutputMode=yield*SelectedOutputMode;const emitJson=json3||selectedOutputMode==="json";return yield*captureCommandResult(executeScaffoldCommand({assumeYes:yes||selectedOutputMode!=="interactive",baseline:getOrUndefined(baseline),emitJson,kind:"setup",...isSome2(output2)?{outputDirectory:path10.resolve(process.cwd(),output2.value)}:{},refreshBaseline,repoShape:getOrElse(repoShape,()=>"auto"),scanDirectory:path10.resolve(process.cwd(),getOrElse(input2,()=>".")),toolStdio:selectedOutputMode==="interactive"?"inherit":"ignore"},operation).pipe(selectedOutputMode==="interactive"?(effect2)=>effect2:provideService2(RepositoryScaffoldingInteraction,silentNonInteractiveScaffoldingInteraction)))})).pipe(withCommandMetadata(scaffoldCommandMetadata));var initCommand=makeInitCommand();var scaffoldCommand=makeScaffoldCommand();var skillsCommandMetadata=declareCommandMetadata({examples:[{command:"hi skills rename",summary:"Migrate legacy operator skills."}],group:"commands",interaction:"none",name:"skills",options:[],outputModes:["interactive","plain","json"],summary:"Deprecated operator-skill compatibility commands."});var skillsRenameCommandMetadata=declareCommandMetadata({examples:[{command:"hi skills rename",summary:"Delegate to operator migration."}],group:"skills",interaction:"none",name:"rename",options:[],outputModes:["interactive","plain","json"],summary:"Deprecated alias for `hi operator migrate`."});var skillsRenameOperationResult=(operation)=>({...operation,warnings:[...operation.warnings,{code:"skills-rename-deprecated",subject:"hi operator migrate"}]});var skillsRenameCommand=exports_Command.make(skillsRenameCommandMetadata.name,{},()=>captureCommandResult(executeOperatorCommand("migrate").pipe(map7(skillsRenameOperationResult)))).pipe(withCommandMetadata(skillsRenameCommandMetadata));var skillsCommandRoot=exports_Command.make(skillsCommandMetadata.name,{},()=>captureCommandResult(succeed6({changes:[],degradations:[],issues:[],nextActions:[{kind:"none"}],status:"no-op",warnings:[{code:"skills-command-deprecated",subject:"hi operator"}]}))).pipe(withCommandMetadata(skillsCommandMetadata));var skillsCommand=skillsCommandRoot.pipe(exports_Command.withSubcommands([skillsRenameCommand]));import path11 from"node:path";class ToolEnsureOperationFailure extends TaggedErrorClass()("@punks/cli/tool-ensure/ToolEnsureOperationFailure",{cause:Defect(),message:String5,operation:Literal2("ensure-tools")}){}var ToolEnsureOperations=Service("@punks/cli/features/tool-ensure/ToolEnsureOperations");var baselineToolIds=["agent-browser","opensrc","portless","skills"];var requiredToolsForSkills=(skillIds,baseline)=>[...new Set([...baselineToolIds,...baseline.skills.filter((skill)=>skillIds.includes(skill.id)).flatMap((skill)=>skill.requiresTools)])].toSorted();var ensureTools=({baseline,rootDirectory,capabilities,runtime,stdio="inherit"})=>{const settings=capabilities.readSettings(rootDirectory);const toolIds=settings?.requiredTools??requiredToolsForSkills([],baseline);const statuses=capabilities.ensureTools(toolIds,baseline,runtime,{mode:"refresh-latest",stdio});return{hasFailures:statuses.some((status2)=>status2.status==="failed"),rootDirectory,statuses,toolIds}};var runToolEnsureApplication=fn2("ToolEnsure.run")(function*runToolEnsureApplication2(input2){const operations=yield*ToolEnsureOperations;return yield*operations.run(input2)});var toolsCommandMetadata=declareCommandMetadata({examples:[{command:"hi tools ensure",summary:"Ensure required tools are installed."}],group:"commands",interaction:"none",name:"tools",options:[],outputModes:["interactive","plain","json"],summary:"Manage external Harness tool requirements."});var toolsEnsureCommandMetadata=declareCommandMetadata({examples:[{command:"hi tools ensure",summary:"Refresh the selected managed toolchain."}],group:"tools",interaction:"none",name:"ensure",options:[{name:"input",summary:"Scaffolded repository root to inspect. Defaults to the current working directory."},{name:"baseline",summary:"Trusted scaffold baseline: stable, bundled, or an exact version. Defaults to stable."},{name:"refresh-baseline",summary:"Refetch the stable baseline instead of reusing the local cache."}],outputModes:["interactive","plain","json"],summary:"Refresh auto-managed required tools to trusted latest targets; validate manual platform tools without upgrading them."});var toolsRootOperation=succeed6({changes:[],degradations:[],issues:[],nextActions:[{kind:"none"}],status:"no-op",warnings:[]});var toolEnsureStatus=(changeCount,issueCount)=>{if(issueCount>0){return changeCount>0?"partial":"failed"}return changeCount>0?"success":"no-op"};var inputOption3=exports_Flag.optional(exports_Flag.string(metadataOptionName(toolsEnsureCommandMetadata,"input")).pipe(exports_Flag.withAlias("i"),withOptionMetadata(toolsEnsureCommandMetadata,"input")));var baselineOption3=exports_Flag.optional(exports_Flag.string(metadataOptionName(toolsEnsureCommandMetadata,"baseline")).pipe(withOptionMetadata(toolsEnsureCommandMetadata,"baseline")));var refreshBaselineOption3=exports_Flag.boolean(metadataOptionName(toolsEnsureCommandMetadata,"refresh-baseline")).pipe(withOptionMetadata(toolsEnsureCommandMetadata,"refresh-baseline"));var toolEnsureOperationResult=(result4)=>{const changes=result4.statuses.filter((status2)=>status2.status==="installed").map((status2)=>({action:"install",state:"completed",subject:status2.toolId}));const issues=result4.statuses.filter((status2)=>status2.status==="failed").map((status2)=>({action:"install",code:"tool-install-failed",errorMessage:status2.errorMessage,kind:"handled-failure",subject:status2.toolId}));return{changes,degradations:[],issues,nextActions:issues.length>0?[{kind:"retry",subject:"required-tools"}]:[{kind:"none"}],status:toolEnsureStatus(changes.length,issues.length),warnings:[]}};var executeToolsEnsureCommand=(input2,operation=runToolEnsureApplication)=>gen2(function*ensureRequiredTools(){const result4=yield*operation(input2);return toolEnsureOperationResult(result4)});var toolsEnsureCommand=exports_Command.make(toolsEnsureCommandMetadata.name,{baseline:baselineOption3,input:inputOption3,refreshBaseline:refreshBaselineOption3},({input:input2,baseline,refreshBaseline})=>gen2(function*ensureTools(){const outputMode=yield*SelectedOutputMode;return yield*captureCommandResult(executeToolsEnsureCommand({baseline:getOrUndefined(baseline),refreshBaseline,rootDirectory:path11.resolve(process.cwd(),getOrElse(input2,()=>".")),stdio:outputMode==="interactive"?"inherit":"ignore"}))})).pipe(withCommandMetadata(toolsEnsureCommandMetadata));var toolsCommandRoot=exports_Command.make(toolsCommandMetadata.name,{},()=>captureCommandResult(toolsRootOperation)).pipe(withCommandMetadata(toolsCommandMetadata));var toolsCommand=toolsCommandRoot.pipe(exports_Command.withSubcommands([toolsEnsureCommand]));import path12 from"node:path";var updateCommandMetadata=declareCommandMetadata({examples:[{command:"hi update --check",summary:"Preview managed scaffold updates."}],group:"commands",interaction:"optional",name:"update",options:[{name:"input",summary:"Scaffolded repository root to update. Defaults to the current working directory."},{name:"check",summary:"Preview managed scaffold updates, write nothing, and exit nonzero when updates are available."},{name:"write",summary:"Apply managed scaffold updates without asking for confirmation."},{name:"yes",summary:"Apply managed scaffold updates without asking for confirmation."},{name:"json",summary:"Print the machine-readable update payload to stdout."},{name:"baseline",summary:"Scaffold baseline to use: stable, bundled, or an exact version. Defaults to stable."},{name:"refresh-baseline",summary:"Refetch the stable baseline instead of reusing the local cache."}],outputModes:["interactive","plain","json"],summary:"Refresh managed scaffold assets from the recorded .devpunks scaffold manifest."});var inputOption4=exports_Flag.optional(exports_Flag.string(metadataOptionName(updateCommandMetadata,"input")).pipe(exports_Flag.withAlias("i"),withOptionMetadata(updateCommandMetadata,"input")));var checkOption=exports_Flag.boolean(metadataOptionName(updateCommandMetadata,"check")).pipe(withOptionMetadata(updateCommandMetadata,"check"));var writeOption=exports_Flag.boolean(metadataOptionName(updateCommandMetadata,"write")).pipe(withOptionMetadata(updateCommandMetadata,"write"));var yesOption2=exports_Flag.boolean(metadataOptionName(updateCommandMetadata,"yes")).pipe(withOptionMetadata(updateCommandMetadata,"yes"));var jsonOption4=exports_Flag.boolean(metadataOptionName(updateCommandMetadata,"json")).pipe(withOptionMetadata(updateCommandMetadata,"json"));var baselineOption4=exports_Flag.optional(exports_Flag.string(metadataOptionName(updateCommandMetadata,"baseline")).pipe(withOptionMetadata(updateCommandMetadata,"baseline")));var refreshBaselineOption4=exports_Flag.boolean(metadataOptionName(updateCommandMetadata,"refresh-baseline")).pipe(withOptionMetadata(updateCommandMetadata,"refresh-baseline"));var silentNonInteractiveUpdateInteraction={confirmApply:()=>succeed6(false),emit:()=>void_3};var executeUpdateCommand=(input2,operation=runScaffoldUpdateApplication)=>scoped2(gen2(function*executeUpdate(){const result4=yield*operation(input2);return input2.emitJson?{jsonPayload:publicUpdateResult(result4),operation:result4.operation}:result4}));var makeUpdateCommand=(operation=runScaffoldUpdateApplication)=>exports_Command.make(updateCommandMetadata.name,{baseline:baselineOption4,check:checkOption,input:inputOption4,json:jsonOption4,refreshBaseline:refreshBaselineOption4,write:writeOption,yes:yesOption2},({input:input2,check:check3,write:write2,yes,json:json3,baseline,refreshBaseline})=>gen2(function*runUpdateCommand(){const selectedOutputMode=yield*SelectedOutputMode;return yield*captureCommandResult(executeUpdateCommand({baseline:getOrUndefined(baseline),check:check3,emitJson:json3||selectedOutputMode==="json",refreshBaseline,rootDirectory:path12.resolve(process.cwd(),getOrElse(input2,()=>".")),toolStdio:selectedOutputMode==="interactive"?"inherit":"ignore",write:write2,yes},operation).pipe(selectedOutputMode==="interactive"?(effect2)=>effect2:provideService2(UpdateInteraction,silentNonInteractiveUpdateInteraction)))})).pipe(withCommandMetadata(updateCommandMetadata));var updateCommand=makeUpdateCommand();import{spawnSync}from"node:child_process";import{existsSync as existsSync4,realpathSync}from"node:fs";var parseSemver=(value5)=>{const match8=value5.match(/^v?(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)(?:-(?<prerelease>[0-9A-Za-z.-]+))?$/u);if(match8===null){return null}return{major:Number.parseInt(match8[1],10),minor:Number.parseInt(match8[2],10),patch:Number.parseInt(match8[3],10),prerelease:match8[4]??null}};var isNumericPrereleaseIdentifier=(value5)=>/^(?<zero>0|[1-9]\d*)$/u.test(value5);var comparePrerelease2=(candidate,current)=>{const candidateParts=candidate.split(".");const currentParts=current.split(".");const maxLength=Math.max(candidateParts.length,currentParts.length);for(let index2=0;index2<maxLength;index2+=1){const candidatePart=candidateParts[index2];const currentPart=currentParts[index2];if(candidatePart===undefined){return-1}if(currentPart===undefined){return 1}if(candidatePart===currentPart){continue}const candidateIsNumeric=isNumericPrereleaseIdentifier(candidatePart);const currentIsNumeric=isNumericPrereleaseIdentifier(currentPart);if(candidateIsNumeric&¤tIsNumeric){return Number.parseInt(candidatePart,10)>Number.parseInt(currentPart,10)?1:-1}if(candidateIsNumeric!==currentIsNumeric){return candidateIsNumeric?-1:1}return candidatePart>currentPart?1:-1}return 0};var isNewerVersion=(candidate,current)=>{const parsedCandidate=parseSemver(candidate);const parsedCurrent=parseSemver(current);if(parsedCandidate===null||parsedCurrent===null){return false}if(parsedCandidate.major!==parsedCurrent.major){return parsedCandidate.major>parsedCurrent.major}if(parsedCandidate.minor!==parsedCurrent.minor){return parsedCandidate.minor>parsedCurrent.minor}if(parsedCandidate.patch!==parsedCurrent.patch){return parsedCandidate.patch>parsedCurrent.patch}if(parsedCandidate.prerelease!==null&&parsedCurrent.prerelease!==null){return comparePrerelease2(parsedCandidate.prerelease,parsedCurrent.prerelease)>0}return parsedCurrent.prerelease!==null&&parsedCandidate.prerelease===null};var readTaggedVersion=async({packageName,registry="https://registry.npmjs.org",tag:tag4,timeoutMs})=>{if(typeof fetch!=="function"){return null}const controller=new AbortController;const timeout3=setTimeout(()=>controller.abort(),timeoutMs);try{const response=await fetch(`${registry.replace(/\/+$/u,"")}/${encodeURIComponent(packageName)}/${encodeURIComponent(tag4)}`,{headers:{accept:"application/json"},signal:controller.signal});if(!response.ok){return null}const payload=await response.json();return typeof payload.version==="string"?payload.version:null}catch{return null}finally{clearTimeout(timeout3)}};var checkSelfUpdate=async({currentVersion,packageName,registry,tag:tag4="latest",timeoutMs=750})=>{const latestVersion=await readTaggedVersion({packageName,...registry===undefined?{}:{registry},tag:tag4,timeoutMs});if(latestVersion===null){return null}return{currentVersion,latestVersion,packageName,tag:tag4,updateAvailable:isNewerVersion(latestVersion,currentVersion)}};var looksLikePath=(value5)=>value5.includes("/")||value5.includes("\\")||existsSync4(value5);var defaultEntrypointCandidates=()=>[process.argv[1]??"",process.execPath].filter((value5)=>value5.length>0);var packageManagerForRuntimePath=(runtimePath)=>{const normalizedEntrypoint=runtimePath.toLowerCase();if(normalizedEntrypoint.includes("/.bun/")||normalizedEntrypoint.includes("\\.bun\\")||normalizedEntrypoint.includes("/install/global/node_modules/@punks/cli/")||normalizedEntrypoint.includes("\\install\\global\\node_modules\\@punks\\cli\\")){return"bun"}if(normalizedEntrypoint.includes("/pnpm/")||normalizedEntrypoint.includes("\\pnpm\\")||normalizedEntrypoint.includes("/.pnpm/")){return"pnpm"}if(normalizedEntrypoint.includes("/yarn/")||normalizedEntrypoint.includes("\\yarn\\")||normalizedEntrypoint.includes("/.yarn/")){return"yarn"}if(normalizedEntrypoint.includes("/node_modules/@punks/cli/")||normalizedEntrypoint.includes("\\node_modules\\@punks\\cli\\")){return"npm"}return null};var detectCliInstallPackageManager=({entrypoint,userAgent}={})=>{const entrypointCandidates=entrypoint===undefined?defaultEntrypointCandidates():[entrypoint];const runtimePaths=entrypointCandidates.flatMap((candidate)=>{if(candidate.length===0||!looksLikePath(candidate)){return[]}try{return[candidate,realpathSync(candidate)]}catch{return[candidate]}});for(const runtimePath of runtimePaths){const packageManager=packageManagerForRuntimePath(runtimePath);if(packageManager!==null){return packageManager}}if(runtimePaths.length>0){return null}if(userAgent?.startsWith("bun/")===true){return"bun"}if(userAgent?.startsWith("pnpm/")===true){return"pnpm"}if(userAgent?.startsWith("yarn/")===true){return"yarn"}if(userAgent?.startsWith("npm/")===true){return"npm"}return null};var globalInstallCommandForPackageManager=({packageManager,packageName,tag:tag4})=>{const specifier=`${packageName}@${tag4}`;switch(packageManager){case"bun":{return["bun","add","-g",specifier,"--minimum-release-age=0"]}case"pnpm":{return["pnpm","add","-g",specifier]}case"npm":{return["npm","install","-g",specifier,"--min-release-age=0"]}case"yarn":{return["yarn","global","add",specifier]}default:{return packageManager}}};var minimumReleaseAgeEnvironmentForPackageManager=(packageManager)=>{switch(packageManager){case"pnpm":{return{npm_config_minimum_release_age:"0"}}case"yarn":{return{YARN_NPM_MINIMAL_AGE_GATE:"0"}}case"bun":case"npm":{return{}}default:{return packageManager}}};var runCliInstallCommand=({baseEnvironment={},command,environment})=>{const result4=spawnSync(command[0],command.slice(1),{env:{...baseEnvironment,...environment},stdio:"inherit"});return result4.status===0};var autoUpdateCliIfStale=async({currentVersion,packageName,tag:tag4="latest",timeoutMs=750,entrypoint,runtime={}})=>{const check3=await checkSelfUpdate({currentVersion,packageName,...runtime.npmRegistry===undefined?{}:{registry:runtime.npmRegistry},tag:tag4,timeoutMs});if(check3===null){return{check:check3,status:"unavailable"}}if(!check3.updateAvailable){return{check:check3,status:"current"}}const packageManager=detectCliInstallPackageManager({...entrypoint===undefined?{}:{entrypoint},...runtime.npmUserAgent===undefined?{}:{userAgent:runtime.npmUserAgent}});if(packageManager===null){return{check:check3,command:null,packageManager,status:"manager-not-detected"}}const command=globalInstallCommandForPackageManager({packageManager,packageName,tag:tag4});const environment=minimumReleaseAgeEnvironmentForPackageManager(packageManager);return{check:check3,command,environment,packageManager,status:"available"}};var upgradeCli=async({currentVersion,packageName,tag:tag4="latest",timeoutMs=5000,entrypoint,force=false,runtime={}})=>{const check3=await checkSelfUpdate({currentVersion,packageName,...runtime.npmRegistry===undefined?{}:{registry:runtime.npmRegistry},tag:tag4,timeoutMs});if(check3===null){return{check:check3,status:"unavailable"}}if(!check3.updateAvailable&&!force){return{check:check3,status:"current"}}const packageManager=detectCliInstallPackageManager({...entrypoint===undefined?{}:{entrypoint},...runtime.npmUserAgent===undefined?{}:{userAgent:runtime.npmUserAgent}});if(packageManager===null){return{check:check3,command:null,packageManager,status:"manager-not-detected"}}const command=globalInstallCommandForPackageManager({packageManager,packageName,tag:tag4});const environment=minimumReleaseAgeEnvironmentForPackageManager(packageManager);if(runCliInstallCommand({...runtime.commandEnvironment===undefined?{}:{baseEnvironment:runtime.commandEnvironment},command,environment})){return{check:check3,command,environment,packageManager,status:"upgraded"}}return{check:check3,command,packageManager,status:"failed"}};import{tmpdir as tmpdir3}from"node:os";import path13 from"node:path";var CliControlPlaneConfig=Service("@punks/cli/CliControlPlaneConfig");var CliReleaseConfig=Service("@punks/cli/CliReleaseConfig");var CliRuntimeConfig=Service("@punks/cli/CliRuntimeConfig");var controlPlaneEnvironment=makeEnvironmentConfig(Struct({CI:optional(String5),DP_CONTROL_PLANE_URL:optional(URLFromString),DP_DISABLE_BUNDLED_CONTROL_PLANE_URL:optional(Literals(["0","1"])),DP_TELEMETRY_SOURCE:optional(String5),NODE_ENV:optional(String5),VITEST:optional(String5)}));var releaseEnvironment=makeEnvironmentConfig(Struct({DP_BASELINE:optional(NonEmptyString),DP_BASELINE_REFRESH:optional(Literals(["0","1"])),DP_BASELINE_URL:optional(URLFromString),DP_UPDATE_TAG:optional(NonEmptyString),GH_TOKEN:optional(EnvironmentSecret),GITHUB_TOKEN:optional(EnvironmentSecret),HOME:optional(NonEmptyString),XDG_CACHE_HOME:optional(NonEmptyString)}));var runtimeEnvironment=makeEnvironmentConfig(Struct({CI:optional(String5),COLORFGBG:optional(String5),DP_SCRIPT_RUNTIME:optional(NonEmptyString),FORCE_COLOR:optional(String5),HI_NO_SKILL_UPDATE_CHECK:optional(Literals(["0","1"])),HI_NO_UPDATE_CHECK:optional(Literals(["0","1"])),HI_STARTUP_CHECK_CLI:optional(Literals(["0","1"])),HI_STARTUP_CHECK_INTERVAL_MS:optional(NumberFromString.check(isInt(),isGreaterThanOrEqualTo3(0))),HI_STARTUP_CHECK_SKILL:optional(Literals(["0","1"])),HI_STARTUP_CHECK_WORKER:optional(Literals(["0","1"])),HI_THEME:optional(Literals(["dark","light"])),HI_UPDATE_TAG:optional(NonEmptyString),NO_COLOR:optional(String5),NPM_CONFIG_REGISTRY:optional(URLFromString),npm_config_registry:optional(URLFromString),npm_config_user_agent:optional(String5)}));var stripTrailingSlashes=(value5)=>value5.toString().replace(/\/+$/u,"");var commandEnvironmentKeys=["AGENT_BROWSER_EXECUTABLE_PATH","ALL_PROXY","APPDATA","BUN_INSTALL","CI","COLORTERM","COMSPEC","CLAUDE_CODE","CLAUDE_PROJECT_DIR","CODEX_HOME","CODEX_THREAD_ID","DISPLAY","DP_SCRIPT_RUNTIME","DP_NO_CLIPBOARD","FORCE_COLOR","GH_CONFIG_DIR","HI_NO_SKILL_UPDATE_CHECK","HI_NO_UPDATE_CHECK","HI_OPERATOR_AGENT","HI_OPERATOR_MIGRATION_RETRY","HI_OPERATOR_MUTATION_RETRY","HI_STARTUP_CHECK_CLI","HI_STARTUP_CHECK_INTERVAL_MS","HI_STARTUP_CHECK_SKILL","HI_STARTUP_CHECK_WORKER","HI_THEME","HI_UPDATE_TAG","HOME","HTTP_PROXY","HTTPS_PROXY","LANG","LC_ALL","LOCALAPPDATA","NODE_EXTRA_CA_CERTS","NODE_OPTIONS","NODE_ENV","NO_COLOR","NO_PROXY","NPM_CONFIG_REGISTRY","PATH","PATHEXT","Path","SHELL","SSL_CERT_DIR","SSL_CERT_FILE","SYSTEMROOT","TEMP","TERM","TMP","TMPDIR","USERPROFILE","VITEST","WAYLAND_DISPLAY","WINDIR","XAUTHORITY","XDG_CACHE_HOME","XDG_CONFIG_HOME","XDG_RUNTIME_DIR","all_proxy","http_proxy","https_proxy","no_proxy","npm_config_registry","npm_config_user_agent"];var commandEnvironment=(input2)=>Object.fromEntries(commandEnvironmentKeys.flatMap((key)=>input2[key]===undefined?[]:[[key,input2[key]]]));var loadCliRuntimeConfiguration=(provider,input2)=>decodeEnvironment({config:runtimeEnvironment,name:"CLI runtime",provider}).pipe(map7((environment)=>{const ciPresent=input2.CI!==undefined||environment.CI!==undefined;const forceColor=input2.FORCE_COLOR??environment.FORCE_COLOR;const noColorPresent=input2.NO_COLOR!==undefined||environment.NO_COLOR!==undefined;return{commandEnvironment:commandEnvironment(input2),forceColor:forceColor!==undefined&&forceColor!=="0",noColor:noColorPresent,npmRegistry:(environment.npm_config_registry?.toString()??environment.NPM_CONFIG_REGISTRY?.toString()??"https://registry.npmjs.org").replace(/\/+$/u,""),...environment.npm_config_user_agent===undefined?{}:{npmUserAgent:environment.npm_config_user_agent},scriptRuntimePath:environment.DP_SCRIPT_RUNTIME??"node",skillUpdateChecksEnabled:environment.HI_NO_SKILL_UPDATE_CHECK!=="1"&&!ciPresent,startupCheckCli:environment.HI_STARTUP_CHECK_CLI==="1",startupCheckIntervalMs:environment.HI_STARTUP_CHECK_INTERVAL_MS??12*60*60*1000,startupCheckSkill:environment.HI_STARTUP_CHECK_SKILL==="1",startupWorker:environment.HI_STARTUP_CHECK_WORKER==="1",updateChecksEnabled:environment.HI_NO_UPDATE_CHECK!=="1"&&!ciPresent,updateTag:environment.HI_UPDATE_TAG??"latest",...environment.HI_THEME===undefined?{}:{terminalTheme:environment.HI_THEME},...environment.COLORFGBG===undefined?{}:{colorForegroundBackground:environment.COLORFGBG}}}));var makeCliConfigLayer=(provider,input2={})=>mergeAll2(effect(CliControlPlaneConfig,decodeEnvironment({config:controlPlaneEnvironment,name:"CLI control plane",provider}).pipe(map7((environment)=>{let telemetrySource;const ciPresent=input2.CI!==undefined||environment.CI!==undefined;const vitestPresent=input2.VITEST!==undefined||environment.VITEST!==undefined;if(ciPresent){telemetrySource="ci"}else if(environment.DP_TELEMETRY_SOURCE==="debug"){telemetrySource="debug"}else if(environment.NODE_ENV==="test"||vitestPresent){telemetrySource="test"}return{disableBundledUrl:environment.DP_DISABLE_BUNDLED_CONTROL_PLANE_URL==="1",...environment.DP_CONTROL_PLANE_URL===undefined?{}:{baseUrl:stripTrailingSlashes(environment.DP_CONTROL_PLANE_URL)},...telemetrySource===undefined?{}:{telemetrySource}}}))),effect(CliReleaseConfig,decodeEnvironment({config:releaseEnvironment,name:"CLI release",provider}).pipe(map7((environment)=>{const githubToken=environment.GH_TOKEN??environment.GITHUB_TOKEN;return{cacheDirectory:environment.XDG_CACHE_HOME??path13.join(environment.HOME??tmpdir3(),".cache"),refreshBaseline:environment.DP_BASELINE_REFRESH==="1",updateTag:environment.DP_UPDATE_TAG??"latest",...environment.DP_BASELINE===undefined?{}:{baseline:environment.DP_BASELINE},...environment.DP_BASELINE_URL===undefined?{}:{baselineUrl:stripTrailingSlashes(environment.DP_BASELINE_URL)},...githubToken===undefined?{}:{githubToken}}}))),effect(CliRuntimeConfig,loadCliRuntimeConfiguration(provider,input2)));var upgradeCommandMetadata=declareCommandMetadata({examples:[{command:"hi upgrade",summary:"Upgrade the installed CLI."}],group:"commands",interaction:"none",name:"upgrade",options:[{name:"tag",summary:"npm dist-tag to install, for example `latest`, `next`, or `beta`."},{name:"force",summary:"Reinstall the selected dist-tag even when the current version is fresh."},{name:"json",summary:"Print JSON output."}],outputModes:["interactive","plain","json"],summary:"Upgrade this CLI through the package manager used for its global install."});var tagOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(upgradeCommandMetadata,"tag")).pipe(withOptionMetadata(upgradeCommandMetadata,"tag")));var forceOption=exports_Flag.boolean(metadataOptionName(upgradeCommandMetadata,"force")).pipe(withOptionMetadata(upgradeCommandMetadata,"force"));var jsonOption5=exports_Flag.boolean(metadataOptionName(upgradeCommandMetadata,"json")).pipe(withOptionMetadata(upgradeCommandMetadata,"json"));var posixSafeComponent=/^[A-Za-z0-9_@%+=:,./-]+$/u;var windowsUnsafeComponent=/[\r\n"%]/u;var quotePosixComponent=(value5)=>posixSafeComponent.test(value5)?value5:`'${value5.replaceAll("'",`'"'"'`)}'`;var quoteWindowsComponent=(value5)=>{if(windowsUnsafeComponent.test(value5)){return}const trailingBackslashes=value5.match(/\\+$/u)?.[0]??"";return`"${value5}${trailingBackslashes}"`};var formatUpgradeRecoveryCommand=({command,environment,platform})=>{if(command.length===0||command.some((component)=>component.includes("\x00"))){return}const environmentEntries=Object.entries(environment);if(environmentEntries.some(([key,value5])=>key.length===0||key.includes("=")||value5.includes("\x00"))){return}if(platform==="win32"){const commandComponents=command.map(quoteWindowsComponent);const assignments=[];for(const[key,value5]of environmentEntries){if(windowsUnsafeComponent.test(key)||windowsUnsafeComponent.test(value5)){return}assignments.push(`set "${key}=${value5}"&&`)}if(commandComponents.some((component)=>component===undefined)){return}return`cmd.exe /d /v:off /s /c "${[...assignments,...commandComponents].join(" ")}"`}return[...environmentEntries.length===0?[]:["env"],...environmentEntries.map(([key,value5])=>quotePosixComponent(`${key}=${value5}`)),...command.map(quotePosixComponent)].join(" ")};var upgradeOperationResult=(result4)=>{switch(result4.status){case"upgraded":{return{changes:[{action:"upgrade",state:"completed",subject:result4.check.packageName}],degradations:[],facts:{command:result4.command,currentVersion:result4.check.currentVersion,environment:result4.environment,kind:"cli-upgrade",latestVersion:result4.check.latestVersion,packageManager:result4.packageManager,packageName:result4.check.packageName,status:result4.status,tag:result4.check.tag},issues:[],nextActions:[{kind:"none"}],status:"success",warnings:[]}}case"current":{return result4.check===null?undefined:{changes:[],degradations:[],facts:{command:null,currentVersion:result4.check.currentVersion,environment:{},kind:"cli-upgrade",latestVersion:result4.check.latestVersion,packageManager:null,packageName:result4.check.packageName,status:result4.status,tag:result4.check.tag},issues:[],nextActions:[{kind:"none"}],status:"no-op",warnings:[]}}default:{return}}};var upgradeExpectedFailure=(result4,platform=process.platform)=>{const recoveryCommand=(()=>{if(!("command"in result4)||result4.command===null){return result4.check===null?undefined:formatUpgradeRecoveryCommand({command:["npm","install","-g",`${result4.check.packageName}@${result4.check.tag}`],environment:{},platform})}return formatUpgradeRecoveryCommand({command:result4.command,environment:"environment"in result4?result4.environment:{},platform})})();switch(result4.status){case"current":{return result4.check===null?new CliValidationError({message:"Could not read the npm registry version for this CLI."}):undefined}case"unavailable":{return new CliValidationError({message:"Could not read the npm registry version for this CLI."})}case"manager-not-detected":{return new CliValidationError({message:"Could not detect how this CLI was installed.",...recoveryCommand===undefined?{}:{recoveryCommand}})}case"available":{return new CliValidationError({message:"Upgrade command was not executed.",...recoveryCommand===undefined?{}:{recoveryCommand}})}case"failed":{return new CliValidationError({message:"CLI upgrade failed.",...recoveryCommand===undefined?{}:{recoveryCommand}})}case"upgraded":{return}default:{return result4}}};var makeUpgradeCommand=(operation=upgradeCli)=>exports_Command.make(upgradeCommandMetadata.name,{force:forceOption,json:jsonOption5,tag:tagOption},({tag:tag4,force,json:_json})=>captureCommandResult(gen2(function*executeUpgradeCommand(){const release=yield*CliReleaseConfig;const runtime=yield*CliRuntimeConfig;const result4=yield*tryPromise2({catch:()=>new CliValidationError({message:"CLI upgrade failed."}),try:()=>operation({currentVersion:version2,force,packageName:name,runtime:{commandEnvironment:runtime.commandEnvironment,npmRegistry:runtime.npmRegistry,...runtime.npmUserAgent===undefined?{}:{npmUserAgent:runtime.npmUserAgent}},tag:getOrElse(tag4,()=>release.updateTag)})});const failure=upgradeExpectedFailure(result4);if(failure!==undefined){return yield*fail6(failure)}return upgradeOperationResult(result4)}))).pipe(withCommandMetadata(upgradeCommandMetadata));var upgradeCommand=makeUpgradeCommand();var registration=(command,commandMetadata,children=[])=>({children,command,metadata:commandMetadata});var operatorChildren=[registration(operatorSubcommands[0],operatorStatusCommandMetadata),registration(operatorSubcommands[1],operatorInstallCommandMetadata),registration(operatorSubcommands[2],operatorUpdateCommandMetadata),registration(operatorSubcommands[3],operatorMigrateCommandMetadata)];var rootRegistrations=[registration(checkCommand,checkCommandMetadata),registration(ensureCommand,ensureCommandMetadata),registration(initCommand,initCommandMetadata),registration(operatorCommandRoot,operatorCommandMetadata,operatorChildren),registration(reportCommand,reportCommandMetadata),registration(scaffoldCommand,scaffoldCommandMetadata),registration(skillsCommandRoot,skillsCommandMetadata,[registration(skillsRenameCommand,skillsRenameCommandMetadata)]),registration(toolsCommandRoot,toolsCommandMetadata,[registration(toolsEnsureCommand,toolsEnsureCommandMetadata)]),registration(updateCommand,updateCommandMetadata),registration(upgradeCommand,upgradeCommandMetadata)];var flatten4=(registrations)=>registrations.flatMap(({children,metadata:commandMetadata})=>[commandMetadata,...flatten4(children)]);var resolveRegistrations=(nodes,parentPath=[])=>nodes.map((node)=>{if(node.command.name!==node.metadata.name){throw new CommandMetadataError(`Executable command '${node.command.name}' does not match metadata name '${node.metadata.name}'.`)}const[first,...rest]=parentPath;const path14=first===undefined?[node.metadata.name]:[first,...rest,node.metadata.name];return{children:resolveRegistrations(node.children,path14),command:node.command,metadata:commandMetadataFromDeclaration(path14,node.metadata)}});var buildRegisteredCommand=(node)=>{const children=node.children.map((child)=>buildRegisteredCommand(child));return children.length===0?node.command:exports_Command.withSubcommands(node.command,children)};var buildCommandRegistry=(rootCommand,registrations)=>{const executableCommands=registrations.map((node)=>buildRegisteredCommand(node));const resolvedRegistrations=resolveRegistrations(registrations);const reference=createCommandMetadataRegistry(flatten4(resolvedRegistrations));const discovery=reference.map(({path:commandPath,summary})=>({path:[...commandPath],summary}));return{command:exports_Command.withSubcommands(rootCommand,executableCommands),commands:reference,discovery,reference,registrations:resolvedRegistrations}};var rootCommand=exports_Command.make("hi",{},()=>void_3).pipe(exports_Command.withDescription("Harness Intelligence CLI. Agents: activate $hi-cli before acting on generated output."));var commandRegistry=buildCommandRegistry(rootCommand,rootRegistrations);import{execFileSync as execFileSync2}from"node:child_process";import{homedir as homedir2}from"node:os";import path19 from"node:path";import{existsSync as existsSync5,readFileSync as readFileSync5,readdirSync as readdirSync3}from"node:fs";import path14 from"node:path";class CliDetectionError extends TaggedErrorClass()("CliDetectionError",{cause:optional(Defect()),message:String5}){}var ignoredDirectoryNames=new Set([".git",".agents",".claude",".codex",".cursor",".devpunks",".devpunks-cache",".next",".opencode",".source",".turbo","coverage","dist","docs","examples","build","node_modules","opensrc","scripts","skills","test-fixtures","tmp","worktrees",".venv","venv","__pycache__"]);var detectionOrder=["nextjs","react","tanstack-query","elysia","trpc","drizzle","better-auth","effect","turborepo"];var languageDetectionOrder=["python","typescript"];var sourceLanguageExtensions=[{language:"python",pattern:/\.py$/u},{language:"typescript",pattern:/\.(?:ts|tsx)$/u}];var conventionalWorkspaceRoots=["apps","packages","services","libs"];var wikiRootPaths=new Set(["app/wiki","apps/wiki","wiki"]);var isRecord4=(value5)=>typeof value5==="object"&&value5!==null;var dependencyRecordSchema=Record(String5,String5);var packageJsonSchema=fromJsonString2(Struct({dependencies:optional(dependencyRecordSchema),devDependencies:optional(dependencyRecordSchema),name:optional(String5),optionalDependencies:optional(dependencyRecordSchema),peerDependencies:optional(dependencyRecordSchema),workspaces:optional(Unknown2)}));var parsePackageJsonRecord=decodeUnknownSync2(packageJsonSchema);var decodeWorkspacePackages=decodeUnknownSync2(ArraySchema(String5));var collectPackageNames=(pkg)=>{const names=new Set;const addEntries=(record3)=>{if(!record3){return}for(const name2 of Object.keys(record3)){names.add(name2)}};addEntries(pkg.dependencies);addEntries(pkg.devDependencies);addEntries(pkg.peerDependencies);addEntries(pkg.optionalDependencies);return[...names].toSorted()};var normalizeRelativePath=(relativePath)=>relativePath.split(path14.sep).join("/");var isWikiRelativePath=(relativePath)=>{const normalized=normalizeRelativePath(relativePath);return[...wikiRootPaths].some((wikiRoot)=>normalized===wikiRoot||normalized.startsWith(`${wikiRoot}/`))};var isWikiManifest=(manifest)=>isWikiRelativePath(manifest.relativePath);var packDetectionManifests=(manifests)=>manifests.filter((manifest)=>!isWikiManifest(manifest));var recursiveFindFiles=(cwd,filename)=>{const results=[];const visit2=(directory3)=>{for(const entry of readdirSync3(directory3,{withFileTypes:true})){if(ignoredDirectoryNames.has(entry.name)){continue}const absolutePath=path14.join(directory3,entry.name);if(entry.isDirectory()){visit2(absolutePath);continue}if(entry.isFile()&&entry.name===filename){results.push(absolutePath)}}};if(existsSync5(cwd)){visit2(cwd)}return results.toSorted()};var discoverConventionalWorkspacePackageJsonPaths=(cwd)=>conventionalWorkspaceRoots.flatMap((rootDirectoryName)=>{const rootDirectory=path14.join(cwd,rootDirectoryName);if(!existsSync5(rootDirectory)){return[]}return readdirSync3(rootDirectory,{withFileTypes:true}).filter((entry)=>entry.isDirectory()&&!ignoredDirectoryNames.has(entry.name)).map((entry)=>path14.join(rootDirectory,entry.name,"package.json")).filter((manifestPath)=>existsSync5(manifestPath))});var discoverTopLevelPackageJsonPaths=(cwd)=>readdirSync3(cwd,{withFileTypes:true}).filter((entry)=>entry.isDirectory()&&!ignoredDirectoryNames.has(entry.name)).map((entry)=>path14.join(cwd,entry.name,"package.json")).filter((manifestPath)=>existsSync5(manifestPath));var readPackageJsonWorkspacePatterns=(pkg)=>{const{workspaces}=pkg;if(isArray(workspaces)){return decodeWorkspacePackages(workspaces)}if(isRecord4(workspaces)&&isArray(workspaces.packages)){return decodeWorkspacePackages(workspaces.packages)}return[]};var readPnpmWorkspacePatterns=(cwd)=>{const workspacePath=path14.join(cwd,"pnpm-workspace.yaml");if(!existsSync5(workspacePath)){return[]}const patterns=[];let inPackagesSection=false;for(const rawLine of readFileSync5(workspacePath,"utf-8").split(/\r?\n/u)){const line=rawLine.trim();if(line==="packages:"){inPackagesSection=true;continue}if(!inPackagesSection){continue}if(line.startsWith("- ")){const pattern=line.slice(2).trim().replaceAll(/^['"]|['"]$/gu,"");if(pattern.length>0){patterns.push(pattern)}continue}if(line.length>0&&!line.startsWith("#")){break}}return patterns};var expandWorkspacePattern=(cwd,pattern)=>{if(pattern.endsWith("/*")){const baseDirectory=path14.join(cwd,pattern.slice(0,-2));if(!existsSync5(baseDirectory)){return[]}return readdirSync3(baseDirectory,{withFileTypes:true}).filter((entry)=>entry.isDirectory()&&!ignoredDirectoryNames.has(entry.name)).map((entry)=>path14.join(baseDirectory,entry.name,"package.json")).filter((manifestPath2)=>existsSync5(manifestPath2)).toSorted()}if(pattern.includes("*")){return[]}const manifestPath=path14.join(cwd,pattern,"package.json");return existsSync5(manifestPath)?[manifestPath]:[]};var discoverPackageJsonPaths=(cwd)=>{const rootPackageJsonPath=path14.join(cwd,"package.json");const recursivePackageJsonPaths=recursiveFindFiles(cwd,"package.json");if(!existsSync5(rootPackageJsonPath)){return recursivePackageJsonPaths}const rootPackageJson=parsePackageJsonRecord(readFileSync5(rootPackageJsonPath,"utf-8"));const workspacePatterns=new Set([...readPackageJsonWorkspacePatterns(rootPackageJson),...readPnpmWorkspacePatterns(cwd)]);const workspacePackageJsonPaths=[...workspacePatterns].flatMap((pattern)=>expandWorkspacePattern(cwd,pattern));const conventionalWorkspacePackageJsonPaths=discoverConventionalWorkspacePackageJsonPaths(cwd);const topLevelPackageJsonPaths=discoverTopLevelPackageJsonPaths(cwd);return[...recursivePackageJsonPaths,...workspacePackageJsonPaths,...conventionalWorkspacePackageJsonPaths,...topLevelPackageJsonPaths].filter((value5,index2,values3)=>values3.indexOf(value5)===index2).toSorted()};var detectTechnologies=(manifests)=>{const packageNames=new Set(packDetectionManifests(manifests).flatMap((manifest)=>manifest.dependencies));const detected=new Set;const hasPackage=(packageName)=>packageNames.has(packageName);const hasPackagePrefix=(prefix)=>[...packageNames].some((packageName)=>packageName.startsWith(prefix));if(hasPackage("next")){detected.add("nextjs");detected.add("react")}if(hasPackage("react")||hasPackage("react-dom")){detected.add("react")}if(hasPackage("@tanstack/react-query")||hasPackage("@tanstack/query-core")||hasPackage("@tanstack/react-query-devtools")||hasPackage("@tanstack/react-query-persist-client")||hasPackage("@tanstack/query-persist-client-core")){detected.add("tanstack-query")}if(hasPackage("elysia")){detected.add("elysia")}if(hasPackagePrefix("@trpc/")){detected.add("trpc")}if(hasPackage("drizzle-orm")||hasPackage("drizzle-kit")){detected.add("drizzle")}if(hasPackage("better-auth")){detected.add("better-auth")}if(hasPackage("effect")||hasPackagePrefix("@effect/")){detected.add("effect")}if(hasPackage("turbo")){detected.add("turborepo")}return detectionOrder.filter((technology)=>detected.has(technology))};var hasPackageTrigger=(packageNames,trigger)=>trigger.endsWith("/")?[...packageNames].some((packageName)=>packageName.startsWith(trigger)):packageNames.has(trigger);var isSourceDirectoryPath=(cwd,directory3)=>path14.relative(cwd,directory3)!=="";var detectSourceLanguages=(cwd)=>{const detected=new Set;const visit2=(directory3)=>{for(const entry of readdirSync3(directory3,{withFileTypes:true})){if(ignoredDirectoryNames.has(entry.name)){continue}const absolutePath=path14.join(directory3,entry.name);if(entry.isDirectory()){visit2(absolutePath);continue}const relativePath=path14.relative(cwd,absolutePath);if(entry.isFile()&&isSourceDirectoryPath(cwd,directory3)&&!isWikiRelativePath(relativePath)){for(const{language,pattern}of sourceLanguageExtensions){if(pattern.test(entry.name)&&!entry.name.endsWith(".d.ts")){detected.add(language)}}}}};if(existsSync5(cwd)){visit2(cwd)}return languageDetectionOrder.filter((language)=>detected.has(language))};var detectLanguages=(cwd,manifests)=>{const packageNames=new Set(packDetectionManifests(manifests).flatMap((manifest)=>manifest.dependencies));const detected=new Set(detectSourceLanguages(cwd));if(hasPackageTrigger(packageNames,"typescript")){detected.add("typescript")}return languageDetectionOrder.filter((language)=>detected.has(language))};var detectMonorepoSignals=(cwd,manifests)=>{const signals=[];for(const workspacePath of recursiveFindFiles(cwd,"pnpm-workspace.yaml")){signals.push({path:workspacePath,type:"pnpm-workspace"})}for(const turboConfigPath of recursiveFindFiles(cwd,"turbo.json")){signals.push({path:turboConfigPath,type:"turbo-config"})}for(const manifest of manifests){const pkg=parsePackageJsonRecord(readFileSync5(manifest.path,"utf-8"));const{workspaces}=pkg;const hasWorkspaces=isArray(workspaces)||isRecord4(workspaces)&&isArray(workspaces.packages);if(hasWorkspaces){signals.push({path:manifest.path,type:"package-json-workspaces"})}}const workspaceManifests=manifests.filter((manifest)=>{const pkg=parsePackageJsonRecord(readFileSync5(manifest.path,"utf-8"));const{workspaces}=pkg;return!(isArray(workspaces)||isRecord4(workspaces)&&isArray(workspaces.packages))});if(workspaceManifests.length>1){signals.push({path:cwd,type:"workspace-packages"})}return signals.filter((signal,index2,allSignals)=>allSignals.findIndex((candidate)=>candidate.type===signal.type&&candidate.path===signal.path)===index2)};var detectRepository=(cwd)=>try_3({catch:(cause)=>new CliDetectionError({cause,message:"Failed to detect repository shape."}),try:()=>{const manifestPaths=discoverPackageJsonPaths(cwd);const manifests=manifestPaths.map((manifestPath)=>{const pkg=parsePackageJsonRecord(readFileSync5(manifestPath,"utf-8"));return{dependencies:collectPackageNames(pkg),packageName:pkg.name??null,path:manifestPath,relativePath:path14.relative(cwd,manifestPath)||"package.json"}});const detectedLanguages=detectLanguages(cwd,manifests);const detectedTechnologies=detectTechnologies(manifests);const monorepoSignals=detectMonorepoSignals(cwd,manifests);return{cwd,detectedLanguages,detectedTechnologies,manifests,monorepo:monorepoSignals.length>0,monorepoSignals}}});var manifestPaths=(result4)=>result4.manifests.map((manifest)=>path14.relative(result4.cwd,manifest.path)||"package.json");var applyRepoShapeMode=(result4,repoShapeMode)=>repoShapeMode==="auto"?result4:{...result4,monorepo:repoShapeMode==="monorepo"};var shouldUseClipboard=(environment)=>environment.VITEST!=="true"&&environment.NODE_ENV!=="test"&&environment.DP_NO_CLIPBOARD!=="1";import{existsSync as existsSync6,mkdirSync as mkdirSync3,readFileSync as readFileSync6,rmSync,writeFileSync as writeFileSync3}from"node:fs";import path15 from"node:path";var nodeFilesystem={exists:existsSync6,read:(filePath)=>readFileSync6(filePath,"utf-8"),remove:(filePath,options4)=>rmSync(filePath,{force:true,recursive:options4?.recursive??false}),write:(filePath,content)=>{mkdirSync3(path15.dirname(filePath),{recursive:true});writeFileSync3(filePath,content,"utf-8")}};var ScaffoldCapabilities=Service("@punks/cli/scaffold/ScaffoldCapabilities");import{existsSync as existsSync7,readFileSync as readFileSync7,writeFileSync as writeFileSync4}from"node:fs";import path16 from"node:path";var harnessDirectories=new Set([".agents",".claude",".codex",".cursor",".opencode"]);var normalizeGitignorePattern=(line)=>{const trimmed=line.trim();if(trimmed===""||trimmed.startsWith("#")||trimmed.startsWith("!")){return null}return trimmed.replace(/^\//u,"").replace(/\/\*\*?$/u,"").replace(/\/$/u,"")};var isHarnessDirectoryIgnore=(line)=>{const normalized=normalizeGitignorePattern(line);return normalized!==null&&harnessDirectories.has(normalized)};var removeHarnessDirectoriesFromGitignore=(rootDirectory)=>{const gitignorePath=path16.join(rootDirectory,".gitignore");if(!existsSync7(gitignorePath)){return{gitignorePath,removedPatterns:[]}}const original=readFileSync7(gitignorePath,"utf-8");const hadFinalNewline=original.endsWith(`
|
|
345
|
+
`));const repository=operations.observeRepository(repoRoot);return{...title===undefined?{}:{title},body:validBody,type:type2,severity,createdAt:new Date().toISOString(),cliVersion:operations.cliVersion,area,...skillPack===undefined?{}:{skillPack},...command===undefined?{}:{command},...expected===undefined?{}:{expected},...actual===undefined?{}:{actual},...steps===undefined?{}:{steps},...labels===undefined?{}:{labels},...repository===undefined?{}:{repository}}});var runReportSubmissionApplication=fn2("ReportSubmission.run")(function*runReportSubmissionApplication2(input2){const operations=yield*ReportSubmissionOperations;const report=yield*buildHarnessReport({...input2,labels:csvLabels(input2.extraLabels)});const baseUrl2=yield*operations.resolveControlPlaneUrl();if(baseUrl2===undefined){const cause=new Error("Harness report API URL is not configured.");return yield*new ReportConfigurationUnavailable({cause,message:cause.message,operation:"resolve-control-plane-url"})}const submitted=yield*operations.submit(baseUrl2,report);yield*operations.recordSubmitted(input2.repoRoot);return submitted});var reportCommandMetadata=declareCommandMetadata({examples:[{command:"hi report --message '...'",summary:"Submit a Harness report."}],group:"commands",interaction:"none",name:"report",options:[{name:"message",summary:"Raw report text for Harness triage."},{name:"title",summary:"Deprecated: optional title hint. The API generates the final title."},{name:"body",summary:"Deprecated: optional body hint. The API generates the final body."},{name:"type",summary:"Report type."},{name:"severity",summary:"Report severity."},{name:"area",summary:"Harness area."},{name:"repo-root",summary:"Repository root used for safe git context."},{name:"skill-pack",summary:"Affected skill pack, for example `hi-cli` or `docs-ingest-phase`."},{name:"command",summary:"Affected CLI command, for example `hi report` or `hi init`."},{name:"expected",summary:"Expected behavior."},{name:"actual",summary:"Actual behavior."},{name:"steps",summary:"Reproduction steps or evidence summary."},{name:"labels",summary:"Comma-separated extra GitHub labels."},{name:"json",summary:"Print JSON output."}],outputModes:["interactive","plain","json"],summary:"Submit reusable Harness friction to GitHub-backed maintainer triage."});var messageOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"message")).pipe(withOptionMetadata(reportCommandMetadata,"message")));var titleOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"title")).pipe(withOptionMetadata(reportCommandMetadata,"title")));var bodyOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"body")).pipe(withOptionMetadata(reportCommandMetadata,"body")));var typeOption=exports_Flag.choice(metadataOptionName(reportCommandMetadata,"type"),["bug","docs","workflow","tooling","other"]).pipe(exports_Flag.withDefault("other"),withOptionMetadata(reportCommandMetadata,"type"));var severityOption=exports_Flag.choice(metadataOptionName(reportCommandMetadata,"severity"),["low","medium","high"]).pipe(exports_Flag.withDefault("medium"),withOptionMetadata(reportCommandMetadata,"severity"));var areaOption=exports_Flag.choice(metadataOptionName(reportCommandMetadata,"area"),["cli","wiki","skill","docs","workflow","backoffice","other"]).pipe(exports_Flag.withDefault("other"),withOptionMetadata(reportCommandMetadata,"area"));var repoRootOption=exports_Flag.string(metadataOptionName(reportCommandMetadata,"repo-root")).pipe(exports_Flag.withDefault(process.cwd()),withOptionMetadata(reportCommandMetadata,"repo-root"));var skillPackOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"skill-pack")).pipe(withOptionMetadata(reportCommandMetadata,"skill-pack")));var commandOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"command")).pipe(withOptionMetadata(reportCommandMetadata,"command")));var expectedOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"expected")).pipe(withOptionMetadata(reportCommandMetadata,"expected")));var actualOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"actual")).pipe(withOptionMetadata(reportCommandMetadata,"actual")));var stepsOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"steps")).pipe(withOptionMetadata(reportCommandMetadata,"steps")));var labelsOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"labels")).pipe(withOptionMetadata(reportCommandMetadata,"labels")));var jsonOption2=exports_Flag.boolean(metadataOptionName(reportCommandMetadata,"json")).pipe(withOptionMetadata(reportCommandMetadata,"json"));var optionalValue=(value5)=>isNone2(value5)||value5.value.trim().length===0?undefined:value5.value.trim();var reportExpectedFailure=(failure)=>{if(failure._tag==="@punks/cli/report-submission/ReportInputInvalid"){return new CliValidationError({message:"Report content is required.",recoveryCommand:"hi report --help"})}if(failure._tag==="@punks/cli/report-submission/ReportConfigurationUnavailable"){return new CliValidationError({message:"Harness report API URL is not configured.",recoveryCommand:"hi report"})}if(failure._tag==="@punks/cli/report-submission/ReportSubmissionResponseInvalid"){return new CliValidationError({message:"Harness report submission did not return a GitHub issue URL.",recoveryCommand:"hi report"})}return new CliValidationError({message:failure.operation==="record-submitted"?"Harness report submission could not be recorded locally.":"Harness report submission failed.",recoveryCommand:"hi report"})};var reportOperationResult=(submitted)=>{const{githubUrl}=submitted;const subject=githubUrl??submitted.reportId;return{changes:submitted.deduplicated===true?[]:[{action:`submit:${submitted.status}`,state:"completed",subject}],degradations:[],facts:{deduplicated:submitted.deduplicated===true,...githubUrl===undefined?{}:{githubUrl},kind:"report-submission",reportId:submitted.reportId,status:submitted.status,title:submitted.title??null},issues:[],nextActions:githubUrl===undefined?[]:[{kind:"review",subject:githubUrl}],status:submitted.deduplicated===true?"no-op":"success",warnings:submitted.deduplicated===true?[{code:"report-deduplicated",subject},{code:"report-status",subject:submitted.status}]:[]}};var executeReportCommand=(input2,operation=runReportSubmissionApplication)=>gen2(function*submitReport(){const submitted=yield*operation(input2).pipe(mapError3(reportExpectedFailure));return{...submitted,operation:reportOperationResult(submitted)}});var makeReportCommand=(operation=runReportSubmissionApplication)=>exports_Command.make(reportCommandMetadata.name,{actual:actualOption,area:areaOption,body:bodyOption,command:commandOption,expected:expectedOption,json:jsonOption2,labels:labelsOption,message:messageOption,repoRoot:repoRootOption,severity:severityOption,skillPack:skillPackOption,steps:stepsOption,title:titleOption,type:typeOption},({message,title,body,type:type2,severity,area,repoRoot,skillPack,command,expected,actual,steps,labels})=>captureCommandResult(executeReportCommand({actual:optionalValue(actual),area,body:optionalValue(body),command:optionalValue(command),expected:optionalValue(expected),extraLabels:optionalValue(labels),message:optionalValue(message),repoRoot,severity,skillPack:optionalValue(skillPack),steps:optionalValue(steps),title:optionalValue(title),type:type2},operation))).pipe(withCommandMetadata(reportCommandMetadata));var reportCommand=makeReportCommand();import path10 from"node:path";var RepositoryScaffoldingInteraction=Service("@punks/cli/features/repository-scaffolding/RepositoryScaffoldingInteraction");class RepositoryScaffoldingOperationFailure extends TaggedErrorClass()("@punks/cli/repository-scaffolding/RepositoryScaffoldingOperationFailure",{cause:Defect(),message:String5,operation:Literals(["initialize-repository","setup-repository"])}){}var RepositoryScaffoldingOperations=Service("@punks/cli/features/repository-scaffolding/RepositoryScaffoldingOperations");var runRepositoryScaffoldingApplication=fn2("RepositoryScaffolding.run")(function*runRepositoryScaffoldingApplication2(input2){const interaction=yield*RepositoryScaffoldingInteraction;const operations=yield*RepositoryScaffoldingOperations;return yield*operations.run(input2,interaction)});var outputSummary="Output directory for scaffolded files. Defaults to the current working directory.";var baselineSummary="Scaffold baseline to use: stable, bundled, or an exact version. Defaults to stable.";var refreshBaselineSummary="Refetch the stable baseline instead of reusing the local cache.";var initCommandMetadata=declareCommandMetadata({examples:[{command:"hi init",summary:"Initialize the current repository."}],group:"commands",interaction:"required",name:"init",options:[{name:"output",summary:outputSummary},{name:"baseline",summary:baselineSummary},{name:"refresh-baseline",summary:refreshBaselineSummary}],outputModes:["interactive","plain"],summary:"Seed docs onboarding, requirements/backlog/spec skills, and wiki structure. Agents: activate $hi-cli, then $docs-onboarding."});var scaffoldCommandMetadata=declareCommandMetadata({examples:[{command:"hi scaffold",summary:"Scaffold the current repository."}],group:"commands",interaction:"optional",name:"scaffold",options:[{name:"input",summary:"Repository root to scan. Defaults to the current working directory."},{name:"output",summary:outputSummary},{name:"json",summary:"Print the full machine-readable scaffold payload to stdout after completion."},{name:"repo-shape",summary:"Override repo shape detection. Use 'monorepo' or 'single' when auto-detection is not the desired scaffold mode."},{name:"baseline",summary:baselineSummary},{name:"refresh-baseline",summary:refreshBaselineSummary},{name:"yes",summary:"Run non-interactively and accept the resolved default scaffold selection."}],outputModes:["interactive","plain","json"],summary:"Repo-aware AI setup. Agents: activate $hi-cli, then reconcile .devpunks output with the real repo layout."});var silentNonInteractiveScaffoldingInteraction={confirmSelection:()=>die3("Non-interactive scaffold mode cannot confirm interactively"),emit:()=>void_3,keepPrefilledSelection:()=>die3("Non-interactive scaffold mode cannot edit the prefilled selection interactively"),selectPacks:()=>die3("Non-interactive scaffold mode cannot select packs interactively"),selectRepoSettings:()=>die3("Non-interactive scaffold mode cannot select repository settings interactively"),selectWikiFramework:()=>die3("Non-interactive scaffold mode cannot select a wiki framework interactively")};var outputOption=(metadata)=>exports_Flag.optional(exports_Flag.string(metadataOptionName(metadata,"output")).pipe(exports_Flag.withAlias("o"),withOptionMetadata(metadata,"output")));var inputOption2=exports_Flag.optional(exports_Flag.string(metadataOptionName(scaffoldCommandMetadata,"input")).pipe(exports_Flag.withAlias("i"),withOptionMetadata(scaffoldCommandMetadata,"input")));var jsonOption3=exports_Flag.boolean(metadataOptionName(scaffoldCommandMetadata,"json")).pipe(withOptionMetadata(scaffoldCommandMetadata,"json"));var repoShapeOption=exports_Flag.optional(exports_Flag.choice(metadataOptionName(scaffoldCommandMetadata,"repo-shape"),["auto","monorepo","single"]).pipe(withOptionMetadata(scaffoldCommandMetadata,"repo-shape")));var baselineOption2=(metadata)=>exports_Flag.optional(exports_Flag.string(metadataOptionName(metadata,"baseline")).pipe(withOptionMetadata(metadata,"baseline")));var refreshBaselineOption2=(metadata)=>exports_Flag.boolean(metadataOptionName(metadata,"refresh-baseline")).pipe(withOptionMetadata(metadata,"refresh-baseline"));var yesOption=exports_Flag.boolean(metadataOptionName(scaffoldCommandMetadata,"yes")).pipe(withOptionMetadata(scaffoldCommandMetadata,"yes"));var scaffoldOperationResult=(input2,result4)=>{const failedTools=result4.toolBootstrapStatuses.filter((tool)=>tool.status==="failed");const projectionPartial=result4.projectionStatus==="partial";const issues=[...projectionPartial?[{action:"project",code:"scaffold-projection-partial",errorMessage:"Scaffold projection completed partially.",kind:"handled-failure",subject:result4.outputDirectory}]:[],...failedTools.map((tool)=>({action:"bootstrap-required-tool",code:`scaffold-required-tool-${tool.toolId}-failed`,errorMessage:tool.errorMessage,kind:"handled-failure",subject:tool.toolId}))];return{changes:[{action:input2.kind==="init"?"initialize":"setup",state:"completed",subject:result4.outputDirectory},...result4.toolBootstrapStatuses.filter((tool)=>tool.status!=="failed").map((tool)=>({action:tool.status==="installed"?"install-required-tool":"verify-required-tool",state:"completed",subject:tool.toolId}))],degradations:[],issues,nextActions:issues.length===0?[{kind:"none"}]:[...failedTools.length===0?[]:[{kind:"run",subject:"hi tools ensure"}],...projectionPartial?[{kind:"review",subject:result4.outputDirectory}]:[]],status:issues.length===0?"success":"partial",warnings:[]}};var executeScaffoldCommand=(input2,operation=runRepositoryScaffoldingApplication)=>scoped2(gen2(function*executeScaffold(){const result4=yield*operation(input2);const operationResult=scaffoldOperationResult(input2,result4);return input2.kind==="setup"&&input2.emitJson?{jsonPayload:result4.machinePayload,operation:operationResult}:operationResult}));var makeInitCommand=(operation=runRepositoryScaffoldingApplication)=>exports_Command.make(initCommandMetadata.name,{baseline:baselineOption2(initCommandMetadata),output:outputOption(initCommandMetadata),refreshBaseline:refreshBaselineOption2(initCommandMetadata)},({output:output2,baseline,refreshBaseline})=>gen2(function*runInitCommand(){const outputMode=yield*SelectedOutputMode;if(outputMode!=="interactive"){return yield*new CliValidationError({message:outputMode==="json"?"`hi init` requires interactive input and is unavailable in JSON mode.":"`hi init` requires interactive input and is unavailable when output is redirected.",recoveryCommand:"hi init"})}return yield*captureCommandResult(executeScaffoldCommand({baseline:getOrUndefined(baseline),kind:"init",outputDirectory:path10.resolve(process.cwd(),getOrElse(output2,()=>".")),refreshBaseline},operation))})).pipe(withCommandMetadata(initCommandMetadata));var makeScaffoldCommand=(operation=runRepositoryScaffoldingApplication)=>exports_Command.make(scaffoldCommandMetadata.name,{baseline:baselineOption2(scaffoldCommandMetadata),input:inputOption2,json:jsonOption3,output:outputOption(scaffoldCommandMetadata),refreshBaseline:refreshBaselineOption2(scaffoldCommandMetadata),repoShape:repoShapeOption,yes:yesOption},({input:input2,output:output2,json:json3,repoShape,baseline,refreshBaseline,yes})=>gen2(function*runScaffoldCommand(){const selectedOutputMode=yield*SelectedOutputMode;const emitJson=json3||selectedOutputMode==="json";return yield*captureCommandResult(executeScaffoldCommand({assumeYes:yes||selectedOutputMode!=="interactive",baseline:getOrUndefined(baseline),emitJson,kind:"setup",...isSome2(output2)?{outputDirectory:path10.resolve(process.cwd(),output2.value)}:{},refreshBaseline,repoShape:getOrElse(repoShape,()=>"auto"),scanDirectory:path10.resolve(process.cwd(),getOrElse(input2,()=>".")),toolStdio:selectedOutputMode==="interactive"?"inherit":"ignore"},operation).pipe(selectedOutputMode==="interactive"?(effect2)=>effect2:provideService2(RepositoryScaffoldingInteraction,silentNonInteractiveScaffoldingInteraction)))})).pipe(withCommandMetadata(scaffoldCommandMetadata));var initCommand=makeInitCommand();var scaffoldCommand=makeScaffoldCommand();var skillsCommandMetadata=declareCommandMetadata({examples:[{command:"hi skills rename",summary:"Migrate legacy operator skills."}],group:"commands",interaction:"none",name:"skills",options:[],outputModes:["interactive","plain","json"],summary:"Deprecated operator-skill compatibility commands."});var skillsRenameCommandMetadata=declareCommandMetadata({examples:[{command:"hi skills rename",summary:"Delegate to operator migration."}],group:"skills",interaction:"none",name:"rename",options:[],outputModes:["interactive","plain","json"],summary:"Deprecated alias for `hi operator migrate`."});var skillsRenameOperationResult=(operation)=>({...operation,warnings:[...operation.warnings,{code:"skills-rename-deprecated",subject:"hi operator migrate"}]});var skillsRenameCommand=exports_Command.make(skillsRenameCommandMetadata.name,{},()=>captureCommandResult(executeOperatorCommand("migrate").pipe(map7(skillsRenameOperationResult)))).pipe(withCommandMetadata(skillsRenameCommandMetadata));var skillsCommandRoot=exports_Command.make(skillsCommandMetadata.name,{},()=>captureCommandResult(succeed6({changes:[],degradations:[],issues:[],nextActions:[{kind:"none"}],status:"no-op",warnings:[{code:"skills-command-deprecated",subject:"hi operator"}]}))).pipe(withCommandMetadata(skillsCommandMetadata));var skillsCommand=skillsCommandRoot.pipe(exports_Command.withSubcommands([skillsRenameCommand]));import path11 from"node:path";class ToolEnsureOperationFailure extends TaggedErrorClass()("@punks/cli/tool-ensure/ToolEnsureOperationFailure",{cause:Defect(),message:String5,operation:Literal2("ensure-tools")}){}var ToolEnsureOperations=Service("@punks/cli/features/tool-ensure/ToolEnsureOperations");var baselineToolIds=["agent-browser","opensrc","portless","skills"];var requiredToolsForSkills=(skillIds,baseline)=>[...new Set([...baselineToolIds,...baseline.skills.filter((skill)=>skillIds.includes(skill.id)).flatMap((skill)=>skill.requiresTools)])].toSorted();var ensureTools=({baseline,rootDirectory,capabilities,runtime,stdio="inherit"})=>{const settings=capabilities.readSettings(rootDirectory);const toolIds=settings?.requiredTools??requiredToolsForSkills([],baseline);const statuses=capabilities.ensureTools(toolIds,baseline,runtime,{mode:"refresh-latest",stdio});return{hasFailures:statuses.some((status2)=>status2.status==="failed"),rootDirectory,statuses,toolIds}};var runToolEnsureApplication=fn2("ToolEnsure.run")(function*runToolEnsureApplication2(input2){const operations=yield*ToolEnsureOperations;return yield*operations.run(input2)});var toolsCommandMetadata=declareCommandMetadata({examples:[{command:"hi tools ensure",summary:"Ensure required tools are installed."}],group:"commands",interaction:"none",name:"tools",options:[],outputModes:["interactive","plain","json"],summary:"Manage external Harness tool requirements."});var toolsEnsureCommandMetadata=declareCommandMetadata({examples:[{command:"hi tools ensure",summary:"Refresh the selected managed toolchain."}],group:"tools",interaction:"none",name:"ensure",options:[{name:"input",summary:"Scaffolded repository root to inspect. Defaults to the current working directory."},{name:"baseline",summary:"Trusted scaffold baseline: stable, bundled, or an exact version. Defaults to stable."},{name:"refresh-baseline",summary:"Refetch the stable baseline instead of reusing the local cache."}],outputModes:["interactive","plain","json"],summary:"Refresh auto-managed required tools to trusted latest targets; validate manual platform tools without upgrading them."});var toolsRootOperation=succeed6({changes:[],degradations:[],issues:[],nextActions:[{kind:"none"}],status:"no-op",warnings:[]});var toolEnsureStatus=(changeCount,issueCount)=>{if(issueCount>0){return changeCount>0?"partial":"failed"}return changeCount>0?"success":"no-op"};var inputOption3=exports_Flag.optional(exports_Flag.string(metadataOptionName(toolsEnsureCommandMetadata,"input")).pipe(exports_Flag.withAlias("i"),withOptionMetadata(toolsEnsureCommandMetadata,"input")));var baselineOption3=exports_Flag.optional(exports_Flag.string(metadataOptionName(toolsEnsureCommandMetadata,"baseline")).pipe(withOptionMetadata(toolsEnsureCommandMetadata,"baseline")));var refreshBaselineOption3=exports_Flag.boolean(metadataOptionName(toolsEnsureCommandMetadata,"refresh-baseline")).pipe(withOptionMetadata(toolsEnsureCommandMetadata,"refresh-baseline"));var toolEnsureOperationResult=(result4)=>{const changes=result4.statuses.filter((status2)=>status2.status==="installed").map((status2)=>({action:"install",state:"completed",subject:status2.toolId}));const issues=result4.statuses.filter((status2)=>status2.status==="failed").map((status2)=>({action:"install",code:"tool-install-failed",errorMessage:status2.errorMessage,kind:"handled-failure",subject:status2.toolId}));return{changes,degradations:[],issues,nextActions:issues.length>0?[{kind:"retry",subject:"required-tools"}]:[{kind:"none"}],status:toolEnsureStatus(changes.length,issues.length),warnings:[]}};var executeToolsEnsureCommand=(input2,operation=runToolEnsureApplication)=>gen2(function*ensureRequiredTools(){const result4=yield*operation(input2);return toolEnsureOperationResult(result4)});var toolsEnsureCommand=exports_Command.make(toolsEnsureCommandMetadata.name,{baseline:baselineOption3,input:inputOption3,refreshBaseline:refreshBaselineOption3},({input:input2,baseline,refreshBaseline})=>gen2(function*ensureTools2(){const outputMode=yield*SelectedOutputMode;return yield*captureCommandResult(executeToolsEnsureCommand({baseline:getOrUndefined(baseline),refreshBaseline,rootDirectory:path11.resolve(process.cwd(),getOrElse(input2,()=>".")),stdio:outputMode==="interactive"?"inherit":"ignore"}))})).pipe(withCommandMetadata(toolsEnsureCommandMetadata));var toolsCommandRoot=exports_Command.make(toolsCommandMetadata.name,{},()=>captureCommandResult(toolsRootOperation)).pipe(withCommandMetadata(toolsCommandMetadata));var toolsCommand=toolsCommandRoot.pipe(exports_Command.withSubcommands([toolsEnsureCommand]));import path12 from"node:path";var updateCommandMetadata=declareCommandMetadata({examples:[{command:"hi update --check",summary:"Preview managed scaffold updates."}],group:"commands",interaction:"optional",name:"update",options:[{name:"input",summary:"Scaffolded repository root to update. Defaults to the current working directory."},{name:"check",summary:"Preview managed scaffold updates, write nothing, and exit nonzero when updates are available."},{name:"write",summary:"Apply managed scaffold updates without asking for confirmation."},{name:"yes",summary:"Apply managed scaffold updates without asking for confirmation."},{name:"json",summary:"Print the machine-readable update payload to stdout."},{name:"baseline",summary:"Scaffold baseline to use: stable, bundled, or an exact version. Defaults to stable."},{name:"refresh-baseline",summary:"Refetch the stable baseline instead of reusing the local cache."}],outputModes:["interactive","plain","json"],summary:"Refresh managed scaffold assets from the recorded .devpunks scaffold manifest."});var inputOption4=exports_Flag.optional(exports_Flag.string(metadataOptionName(updateCommandMetadata,"input")).pipe(exports_Flag.withAlias("i"),withOptionMetadata(updateCommandMetadata,"input")));var checkOption=exports_Flag.boolean(metadataOptionName(updateCommandMetadata,"check")).pipe(withOptionMetadata(updateCommandMetadata,"check"));var writeOption=exports_Flag.boolean(metadataOptionName(updateCommandMetadata,"write")).pipe(withOptionMetadata(updateCommandMetadata,"write"));var yesOption2=exports_Flag.boolean(metadataOptionName(updateCommandMetadata,"yes")).pipe(withOptionMetadata(updateCommandMetadata,"yes"));var jsonOption4=exports_Flag.boolean(metadataOptionName(updateCommandMetadata,"json")).pipe(withOptionMetadata(updateCommandMetadata,"json"));var baselineOption4=exports_Flag.optional(exports_Flag.string(metadataOptionName(updateCommandMetadata,"baseline")).pipe(withOptionMetadata(updateCommandMetadata,"baseline")));var refreshBaselineOption4=exports_Flag.boolean(metadataOptionName(updateCommandMetadata,"refresh-baseline")).pipe(withOptionMetadata(updateCommandMetadata,"refresh-baseline"));var silentNonInteractiveUpdateInteraction={confirmApply:()=>succeed6(false),emit:()=>void_3};var executeUpdateCommand=(input2,operation=runScaffoldUpdateApplication)=>scoped2(gen2(function*executeUpdate(){const result4=yield*operation(input2);return input2.emitJson?{jsonPayload:publicUpdateResult(result4),operation:result4.operation}:result4}));var makeUpdateCommand=(operation=runScaffoldUpdateApplication)=>exports_Command.make(updateCommandMetadata.name,{baseline:baselineOption4,check:checkOption,input:inputOption4,json:jsonOption4,refreshBaseline:refreshBaselineOption4,write:writeOption,yes:yesOption2},({input:input2,check:check3,write:write2,yes,json:json3,baseline,refreshBaseline})=>gen2(function*runUpdateCommand(){const selectedOutputMode=yield*SelectedOutputMode;return yield*captureCommandResult(executeUpdateCommand({baseline:getOrUndefined(baseline),check:check3,emitJson:json3||selectedOutputMode==="json",refreshBaseline,rootDirectory:path12.resolve(process.cwd(),getOrElse(input2,()=>".")),toolStdio:selectedOutputMode==="interactive"?"inherit":"ignore",write:write2,yes},operation).pipe(selectedOutputMode==="interactive"?(effect2)=>effect2:provideService2(UpdateInteraction,silentNonInteractiveUpdateInteraction)))})).pipe(withCommandMetadata(updateCommandMetadata));var updateCommand=makeUpdateCommand();import{spawnSync}from"node:child_process";import{existsSync as existsSync4,realpathSync}from"node:fs";var parseSemver=(value5)=>{const match8=value5.match(/^v?(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)(?:-(?<prerelease>[0-9A-Za-z.-]+))?$/u);if(match8===null){return null}return{major:Number.parseInt(match8[1],10),minor:Number.parseInt(match8[2],10),patch:Number.parseInt(match8[3],10),prerelease:match8[4]??null}};var isNumericPrereleaseIdentifier=(value5)=>/^(?<zero>0|[1-9]\d*)$/u.test(value5);var comparePrerelease2=(candidate,current)=>{const candidateParts=candidate.split(".");const currentParts=current.split(".");const maxLength=Math.max(candidateParts.length,currentParts.length);for(let index2=0;index2<maxLength;index2+=1){const candidatePart=candidateParts[index2];const currentPart=currentParts[index2];if(candidatePart===undefined){return-1}if(currentPart===undefined){return 1}if(candidatePart===currentPart){continue}const candidateIsNumeric=isNumericPrereleaseIdentifier(candidatePart);const currentIsNumeric=isNumericPrereleaseIdentifier(currentPart);if(candidateIsNumeric&¤tIsNumeric){return Number.parseInt(candidatePart,10)>Number.parseInt(currentPart,10)?1:-1}if(candidateIsNumeric!==currentIsNumeric){return candidateIsNumeric?-1:1}return candidatePart>currentPart?1:-1}return 0};var isNewerVersion=(candidate,current)=>{const parsedCandidate=parseSemver(candidate);const parsedCurrent=parseSemver(current);if(parsedCandidate===null||parsedCurrent===null){return false}if(parsedCandidate.major!==parsedCurrent.major){return parsedCandidate.major>parsedCurrent.major}if(parsedCandidate.minor!==parsedCurrent.minor){return parsedCandidate.minor>parsedCurrent.minor}if(parsedCandidate.patch!==parsedCurrent.patch){return parsedCandidate.patch>parsedCurrent.patch}if(parsedCandidate.prerelease!==null&&parsedCurrent.prerelease!==null){return comparePrerelease2(parsedCandidate.prerelease,parsedCurrent.prerelease)>0}return parsedCurrent.prerelease!==null&&parsedCandidate.prerelease===null};var readTaggedVersion=async({packageName,registry="https://registry.npmjs.org",tag:tag4,timeoutMs})=>{if(typeof fetch!=="function"){return null}const controller=new AbortController;const timeout3=setTimeout(()=>controller.abort(),timeoutMs);try{const response=await fetch(`${registry.replace(/\/+$/u,"")}/${encodeURIComponent(packageName)}/${encodeURIComponent(tag4)}`,{headers:{accept:"application/json"},signal:controller.signal});if(!response.ok){return null}const payload=await response.json();return typeof payload.version==="string"?payload.version:null}catch{return null}finally{clearTimeout(timeout3)}};var checkSelfUpdate=async({currentVersion,packageName,registry,tag:tag4="latest",timeoutMs=750})=>{const latestVersion=await readTaggedVersion({packageName,...registry===undefined?{}:{registry},tag:tag4,timeoutMs});if(latestVersion===null){return null}return{currentVersion,latestVersion,packageName,tag:tag4,updateAvailable:isNewerVersion(latestVersion,currentVersion)}};var looksLikePath=(value5)=>value5.includes("/")||value5.includes("\\")||existsSync4(value5);var defaultEntrypointCandidates=()=>[process.argv[1]??"",process.execPath].filter((value5)=>value5.length>0);var packageManagerForRuntimePath=(runtimePath)=>{const normalizedEntrypoint=runtimePath.toLowerCase();if(normalizedEntrypoint.includes("/.bun/")||normalizedEntrypoint.includes("\\.bun\\")||normalizedEntrypoint.includes("/install/global/node_modules/@punks/cli/")||normalizedEntrypoint.includes("\\install\\global\\node_modules\\@punks\\cli\\")){return"bun"}if(normalizedEntrypoint.includes("/pnpm/")||normalizedEntrypoint.includes("\\pnpm\\")||normalizedEntrypoint.includes("/.pnpm/")){return"pnpm"}if(normalizedEntrypoint.includes("/yarn/")||normalizedEntrypoint.includes("\\yarn\\")||normalizedEntrypoint.includes("/.yarn/")){return"yarn"}if(normalizedEntrypoint.includes("/node_modules/@punks/cli/")||normalizedEntrypoint.includes("\\node_modules\\@punks\\cli\\")){return"npm"}return null};var detectCliInstallPackageManager=({entrypoint,userAgent}={})=>{const entrypointCandidates=entrypoint===undefined?defaultEntrypointCandidates():[entrypoint];const runtimePaths=entrypointCandidates.flatMap((candidate)=>{if(candidate.length===0||!looksLikePath(candidate)){return[]}try{return[candidate,realpathSync(candidate)]}catch{return[candidate]}});for(const runtimePath of runtimePaths){const packageManager=packageManagerForRuntimePath(runtimePath);if(packageManager!==null){return packageManager}}if(runtimePaths.length>0){return null}if(userAgent?.startsWith("bun/")===true){return"bun"}if(userAgent?.startsWith("pnpm/")===true){return"pnpm"}if(userAgent?.startsWith("yarn/")===true){return"yarn"}if(userAgent?.startsWith("npm/")===true){return"npm"}return null};var globalInstallCommandForPackageManager=({packageManager,packageName,tag:tag4})=>{const specifier=`${packageName}@${tag4}`;switch(packageManager){case"bun":{return["bun","add","-g",specifier,"--minimum-release-age=0"]}case"pnpm":{return["pnpm","add","-g",specifier]}case"npm":{return["npm","install","-g",specifier,"--min-release-age=0"]}case"yarn":{return["yarn","global","add",specifier]}default:{return packageManager}}};var minimumReleaseAgeEnvironmentForPackageManager=(packageManager)=>{switch(packageManager){case"pnpm":{return{npm_config_minimum_release_age:"0"}}case"yarn":{return{YARN_NPM_MINIMAL_AGE_GATE:"0"}}case"bun":case"npm":{return{}}default:{return packageManager}}};var runCliInstallCommand=({baseEnvironment={},command,environment})=>{const result4=spawnSync(command[0],command.slice(1),{env:{...baseEnvironment,...environment},stdio:"inherit"});return result4.status===0};var autoUpdateCliIfStale=async({currentVersion,packageName,tag:tag4="latest",timeoutMs=750,entrypoint,runtime={}})=>{const check3=await checkSelfUpdate({currentVersion,packageName,...runtime.npmRegistry===undefined?{}:{registry:runtime.npmRegistry},tag:tag4,timeoutMs});if(check3===null){return{check:check3,status:"unavailable"}}if(!check3.updateAvailable){return{check:check3,status:"current"}}const packageManager=detectCliInstallPackageManager({...entrypoint===undefined?{}:{entrypoint},...runtime.npmUserAgent===undefined?{}:{userAgent:runtime.npmUserAgent}});if(packageManager===null){return{check:check3,command:null,packageManager,status:"manager-not-detected"}}const command=globalInstallCommandForPackageManager({packageManager,packageName,tag:tag4});const environment=minimumReleaseAgeEnvironmentForPackageManager(packageManager);return{check:check3,command,environment,packageManager,status:"available"}};var upgradeCli=async({currentVersion,packageName,tag:tag4="latest",timeoutMs=5000,entrypoint,force=false,runtime={}})=>{const check3=await checkSelfUpdate({currentVersion,packageName,...runtime.npmRegistry===undefined?{}:{registry:runtime.npmRegistry},tag:tag4,timeoutMs});if(check3===null){return{check:check3,status:"unavailable"}}if(!check3.updateAvailable&&!force){return{check:check3,status:"current"}}const packageManager=detectCliInstallPackageManager({...entrypoint===undefined?{}:{entrypoint},...runtime.npmUserAgent===undefined?{}:{userAgent:runtime.npmUserAgent}});if(packageManager===null){return{check:check3,command:null,packageManager,status:"manager-not-detected"}}const command=globalInstallCommandForPackageManager({packageManager,packageName,tag:tag4});const environment=minimumReleaseAgeEnvironmentForPackageManager(packageManager);if(runCliInstallCommand({...runtime.commandEnvironment===undefined?{}:{baseEnvironment:runtime.commandEnvironment},command,environment})){return{check:check3,command,environment,packageManager,status:"upgraded"}}return{check:check3,command,packageManager,status:"failed"}};import{tmpdir as tmpdir3}from"node:os";import path13 from"node:path";var CliControlPlaneConfig=Service("@punks/cli/CliControlPlaneConfig");var CliReleaseConfig=Service("@punks/cli/CliReleaseConfig");var CliRuntimeConfig=Service("@punks/cli/CliRuntimeConfig");var controlPlaneEnvironment=makeEnvironmentConfig(Struct({CI:optional(String5),DP_CONTROL_PLANE_URL:optional(URLFromString),DP_DISABLE_BUNDLED_CONTROL_PLANE_URL:optional(Literals(["0","1"])),DP_TELEMETRY_SOURCE:optional(String5),NODE_ENV:optional(String5),VITEST:optional(String5)}));var releaseEnvironment=makeEnvironmentConfig(Struct({DP_BASELINE:optional(NonEmptyString),DP_BASELINE_REFRESH:optional(Literals(["0","1"])),DP_BASELINE_URL:optional(URLFromString),DP_UPDATE_TAG:optional(NonEmptyString),GH_TOKEN:optional(EnvironmentSecret),GITHUB_TOKEN:optional(EnvironmentSecret),HOME:optional(NonEmptyString),XDG_CACHE_HOME:optional(NonEmptyString)}));var runtimeEnvironment=makeEnvironmentConfig(Struct({CI:optional(String5),COLORFGBG:optional(String5),DP_SCRIPT_RUNTIME:optional(NonEmptyString),FORCE_COLOR:optional(String5),HI_NO_SKILL_UPDATE_CHECK:optional(Literals(["0","1"])),HI_NO_UPDATE_CHECK:optional(Literals(["0","1"])),HI_STARTUP_CHECK_CLI:optional(Literals(["0","1"])),HI_STARTUP_CHECK_INTERVAL_MS:optional(NumberFromString.check(isInt(),isGreaterThanOrEqualTo3(0))),HI_STARTUP_CHECK_SKILL:optional(Literals(["0","1"])),HI_STARTUP_CHECK_WORKER:optional(Literals(["0","1"])),HI_THEME:optional(Literals(["dark","light"])),HI_UPDATE_TAG:optional(NonEmptyString),NO_COLOR:optional(String5),NPM_CONFIG_REGISTRY:optional(URLFromString),npm_config_registry:optional(URLFromString),npm_config_user_agent:optional(String5)}));var stripTrailingSlashes=(value5)=>value5.toString().replace(/\/+$/u,"");var commandEnvironmentKeys=["AGENT_BROWSER_EXECUTABLE_PATH","ALL_PROXY","APPDATA","BUN_INSTALL","CI","COLORTERM","COMSPEC","CLAUDE_CODE","CLAUDE_PROJECT_DIR","CODEX_HOME","CODEX_THREAD_ID","DISPLAY","DP_SCRIPT_RUNTIME","DP_NO_CLIPBOARD","FORCE_COLOR","GH_CONFIG_DIR","HI_NO_SKILL_UPDATE_CHECK","HI_NO_UPDATE_CHECK","HI_OPERATOR_AGENT","HI_OPERATOR_MIGRATION_RETRY","HI_OPERATOR_MUTATION_RETRY","HI_STARTUP_CHECK_CLI","HI_STARTUP_CHECK_INTERVAL_MS","HI_STARTUP_CHECK_SKILL","HI_STARTUP_CHECK_WORKER","HI_THEME","HI_UPDATE_TAG","HOME","HTTP_PROXY","HTTPS_PROXY","LANG","LC_ALL","LOCALAPPDATA","NODE_EXTRA_CA_CERTS","NODE_OPTIONS","NODE_ENV","NO_COLOR","NO_PROXY","NPM_CONFIG_REGISTRY","PATH","PATHEXT","Path","SHELL","SSL_CERT_DIR","SSL_CERT_FILE","SYSTEMROOT","TEMP","TERM","TMP","TMPDIR","USERPROFILE","VITEST","WAYLAND_DISPLAY","WINDIR","XAUTHORITY","XDG_CACHE_HOME","XDG_CONFIG_HOME","XDG_RUNTIME_DIR","all_proxy","http_proxy","https_proxy","no_proxy","npm_config_registry","npm_config_user_agent"];var commandEnvironment=(input2)=>Object.fromEntries(commandEnvironmentKeys.flatMap((key)=>input2[key]===undefined?[]:[[key,input2[key]]]));var loadCliRuntimeConfiguration=(provider,input2)=>decodeEnvironment({config:runtimeEnvironment,name:"CLI runtime",provider}).pipe(map7((environment)=>{const ciPresent=input2.CI!==undefined||environment.CI!==undefined;const forceColor=input2.FORCE_COLOR??environment.FORCE_COLOR;const noColorPresent=input2.NO_COLOR!==undefined||environment.NO_COLOR!==undefined;return{commandEnvironment:commandEnvironment(input2),forceColor:forceColor!==undefined&&forceColor!=="0",noColor:noColorPresent,npmRegistry:(environment.npm_config_registry?.toString()??environment.NPM_CONFIG_REGISTRY?.toString()??"https://registry.npmjs.org").replace(/\/+$/u,""),...environment.npm_config_user_agent===undefined?{}:{npmUserAgent:environment.npm_config_user_agent},scriptRuntimePath:environment.DP_SCRIPT_RUNTIME??"node",skillUpdateChecksEnabled:environment.HI_NO_SKILL_UPDATE_CHECK!=="1"&&!ciPresent,startupCheckCli:environment.HI_STARTUP_CHECK_CLI==="1",startupCheckIntervalMs:environment.HI_STARTUP_CHECK_INTERVAL_MS??12*60*60*1000,startupCheckSkill:environment.HI_STARTUP_CHECK_SKILL==="1",startupWorker:environment.HI_STARTUP_CHECK_WORKER==="1",updateChecksEnabled:environment.HI_NO_UPDATE_CHECK!=="1"&&!ciPresent,updateTag:environment.HI_UPDATE_TAG??"latest",...environment.HI_THEME===undefined?{}:{terminalTheme:environment.HI_THEME},...environment.COLORFGBG===undefined?{}:{colorForegroundBackground:environment.COLORFGBG}}}));var makeCliConfigLayer=(provider,input2={})=>mergeAll2(effect(CliControlPlaneConfig,decodeEnvironment({config:controlPlaneEnvironment,name:"CLI control plane",provider}).pipe(map7((environment)=>{let telemetrySource;const ciPresent=input2.CI!==undefined||environment.CI!==undefined;const vitestPresent=input2.VITEST!==undefined||environment.VITEST!==undefined;if(ciPresent){telemetrySource="ci"}else if(environment.DP_TELEMETRY_SOURCE==="debug"){telemetrySource="debug"}else if(environment.NODE_ENV==="test"||vitestPresent){telemetrySource="test"}return{disableBundledUrl:environment.DP_DISABLE_BUNDLED_CONTROL_PLANE_URL==="1",...environment.DP_CONTROL_PLANE_URL===undefined?{}:{baseUrl:stripTrailingSlashes(environment.DP_CONTROL_PLANE_URL)},...telemetrySource===undefined?{}:{telemetrySource}}}))),effect(CliReleaseConfig,decodeEnvironment({config:releaseEnvironment,name:"CLI release",provider}).pipe(map7((environment)=>{const githubToken=environment.GH_TOKEN??environment.GITHUB_TOKEN;return{cacheDirectory:environment.XDG_CACHE_HOME??path13.join(environment.HOME??tmpdir3(),".cache"),refreshBaseline:environment.DP_BASELINE_REFRESH==="1",updateTag:environment.DP_UPDATE_TAG??"latest",...environment.DP_BASELINE===undefined?{}:{baseline:environment.DP_BASELINE},...environment.DP_BASELINE_URL===undefined?{}:{baselineUrl:stripTrailingSlashes(environment.DP_BASELINE_URL)},...githubToken===undefined?{}:{githubToken}}}))),effect(CliRuntimeConfig,loadCliRuntimeConfiguration(provider,input2)));var upgradeCommandMetadata=declareCommandMetadata({examples:[{command:"hi upgrade",summary:"Upgrade the installed CLI."}],group:"commands",interaction:"none",name:"upgrade",options:[{name:"tag",summary:"npm dist-tag to install, for example `latest`, `next`, or `beta`."},{name:"force",summary:"Reinstall the selected dist-tag even when the current version is fresh."},{name:"json",summary:"Print JSON output."}],outputModes:["interactive","plain","json"],summary:"Upgrade this CLI through the package manager used for its global install."});var tagOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(upgradeCommandMetadata,"tag")).pipe(withOptionMetadata(upgradeCommandMetadata,"tag")));var forceOption=exports_Flag.boolean(metadataOptionName(upgradeCommandMetadata,"force")).pipe(withOptionMetadata(upgradeCommandMetadata,"force"));var jsonOption5=exports_Flag.boolean(metadataOptionName(upgradeCommandMetadata,"json")).pipe(withOptionMetadata(upgradeCommandMetadata,"json"));var posixSafeComponent=/^[A-Za-z0-9_@%+=:,./-]+$/u;var windowsUnsafeComponent=/[\r\n"%]/u;var quotePosixComponent=(value5)=>posixSafeComponent.test(value5)?value5:`'${value5.replaceAll("'",`'"'"'`)}'`;var quoteWindowsComponent=(value5)=>{if(windowsUnsafeComponent.test(value5)){return}const trailingBackslashes=value5.match(/\\+$/u)?.[0]??"";return`"${value5}${trailingBackslashes}"`};var formatUpgradeRecoveryCommand=({command,environment,platform})=>{if(command.length===0||command.some((component)=>component.includes("\x00"))){return}const environmentEntries=Object.entries(environment);if(environmentEntries.some(([key,value5])=>key.length===0||key.includes("=")||value5.includes("\x00"))){return}if(platform==="win32"){const commandComponents=command.map(quoteWindowsComponent);const assignments=[];for(const[key,value5]of environmentEntries){if(windowsUnsafeComponent.test(key)||windowsUnsafeComponent.test(value5)){return}assignments.push(`set "${key}=${value5}"&&`)}if(commandComponents.some((component)=>component===undefined)){return}return`cmd.exe /d /v:off /s /c "${[...assignments,...commandComponents].join(" ")}"`}return[...environmentEntries.length===0?[]:["env"],...environmentEntries.map(([key,value5])=>quotePosixComponent(`${key}=${value5}`)),...command.map(quotePosixComponent)].join(" ")};var upgradeOperationResult=(result4)=>{switch(result4.status){case"upgraded":{return{changes:[{action:"upgrade",state:"completed",subject:result4.check.packageName}],degradations:[],facts:{command:result4.command,currentVersion:result4.check.currentVersion,environment:result4.environment,kind:"cli-upgrade",latestVersion:result4.check.latestVersion,packageManager:result4.packageManager,packageName:result4.check.packageName,status:result4.status,tag:result4.check.tag},issues:[],nextActions:[{kind:"none"}],status:"success",warnings:[]}}case"current":{return result4.check===null?undefined:{changes:[],degradations:[],facts:{command:null,currentVersion:result4.check.currentVersion,environment:{},kind:"cli-upgrade",latestVersion:result4.check.latestVersion,packageManager:null,packageName:result4.check.packageName,status:result4.status,tag:result4.check.tag},issues:[],nextActions:[{kind:"none"}],status:"no-op",warnings:[]}}default:{return}}};var upgradeExpectedFailure=(result4,platform=process.platform)=>{const recoveryCommand=(()=>{if(!("command"in result4)||result4.command===null){return result4.check===null?undefined:formatUpgradeRecoveryCommand({command:["npm","install","-g",`${result4.check.packageName}@${result4.check.tag}`],environment:{},platform})}return formatUpgradeRecoveryCommand({command:result4.command,environment:"environment"in result4?result4.environment:{},platform})})();switch(result4.status){case"current":{return result4.check===null?new CliValidationError({message:"Could not read the npm registry version for this CLI."}):undefined}case"unavailable":{return new CliValidationError({message:"Could not read the npm registry version for this CLI."})}case"manager-not-detected":{return new CliValidationError({message:"Could not detect how this CLI was installed.",...recoveryCommand===undefined?{}:{recoveryCommand}})}case"available":{return new CliValidationError({message:"Upgrade command was not executed.",...recoveryCommand===undefined?{}:{recoveryCommand}})}case"failed":{return new CliValidationError({message:"CLI upgrade failed.",...recoveryCommand===undefined?{}:{recoveryCommand}})}case"upgraded":{return}default:{return result4}}};var makeUpgradeCommand=(operation=upgradeCli)=>exports_Command.make(upgradeCommandMetadata.name,{force:forceOption,json:jsonOption5,tag:tagOption},({tag:tag4,force,json:_json})=>captureCommandResult(gen2(function*executeUpgradeCommand(){const release=yield*CliReleaseConfig;const runtime=yield*CliRuntimeConfig;const result4=yield*tryPromise2({catch:()=>new CliValidationError({message:"CLI upgrade failed."}),try:()=>operation({currentVersion:version2,force,packageName:name,runtime:{commandEnvironment:runtime.commandEnvironment,npmRegistry:runtime.npmRegistry,...runtime.npmUserAgent===undefined?{}:{npmUserAgent:runtime.npmUserAgent}},tag:getOrElse(tag4,()=>release.updateTag)})});const failure=upgradeExpectedFailure(result4);if(failure!==undefined){return yield*fail6(failure)}return upgradeOperationResult(result4)}))).pipe(withCommandMetadata(upgradeCommandMetadata));var upgradeCommand=makeUpgradeCommand();var registration=(command,commandMetadata,children=[])=>({children,command,metadata:commandMetadata});var operatorChildren=[registration(operatorSubcommands[0],operatorStatusCommandMetadata),registration(operatorSubcommands[1],operatorInstallCommandMetadata),registration(operatorSubcommands[2],operatorUpdateCommandMetadata),registration(operatorSubcommands[3],operatorMigrateCommandMetadata)];var rootRegistrations=[registration(checkCommand,checkCommandMetadata),registration(ensureCommand,ensureCommandMetadata),registration(initCommand,initCommandMetadata),registration(operatorCommandRoot,operatorCommandMetadata,operatorChildren),registration(reportCommand,reportCommandMetadata),registration(scaffoldCommand,scaffoldCommandMetadata),registration(skillsCommandRoot,skillsCommandMetadata,[registration(skillsRenameCommand,skillsRenameCommandMetadata)]),registration(toolsCommandRoot,toolsCommandMetadata,[registration(toolsEnsureCommand,toolsEnsureCommandMetadata)]),registration(updateCommand,updateCommandMetadata),registration(upgradeCommand,upgradeCommandMetadata)];var flatten4=(registrations)=>registrations.flatMap(({children,metadata:commandMetadata})=>[commandMetadata,...flatten4(children)]);var resolveRegistrations=(nodes,parentPath=[])=>nodes.map((node)=>{if(node.command.name!==node.metadata.name){throw new CommandMetadataError(`Executable command '${node.command.name}' does not match metadata name '${node.metadata.name}'.`)}const[first,...rest]=parentPath;const path14=first===undefined?[node.metadata.name]:[first,...rest,node.metadata.name];return{children:resolveRegistrations(node.children,path14),command:node.command,metadata:commandMetadataFromDeclaration(path14,node.metadata)}});var buildRegisteredCommand=(node)=>{const children=node.children.map((child)=>buildRegisteredCommand(child));return children.length===0?node.command:exports_Command.withSubcommands(node.command,children)};var buildCommandRegistry=(rootCommand,registrations)=>{const executableCommands=registrations.map((node)=>buildRegisteredCommand(node));const resolvedRegistrations=resolveRegistrations(registrations);const reference=createCommandMetadataRegistry(flatten4(resolvedRegistrations));const discovery=reference.map(({path:commandPath,summary})=>({path:[...commandPath],summary}));return{command:exports_Command.withSubcommands(rootCommand,executableCommands),commands:reference,discovery,reference,registrations:resolvedRegistrations}};var rootCommand=exports_Command.make("hi",{},()=>void_3).pipe(exports_Command.withDescription("Harness Intelligence CLI. Agents: activate $hi-cli before acting on generated output."));var commandRegistry=buildCommandRegistry(rootCommand,rootRegistrations);import{execFileSync as execFileSync2}from"node:child_process";import{homedir as homedir2}from"node:os";import path19 from"node:path";import{existsSync as existsSync5,readFileSync as readFileSync5,readdirSync as readdirSync3}from"node:fs";import path14 from"node:path";class CliDetectionError extends TaggedErrorClass()("CliDetectionError",{cause:optional(Defect()),message:String5}){}var ignoredDirectoryNames=new Set([".git",".agents",".claude",".codex",".cursor",".devpunks",".devpunks-cache",".next",".opencode",".source",".turbo","coverage","dist","docs","examples","build","node_modules","opensrc","scripts","skills","test-fixtures","tmp","worktrees",".venv","venv","__pycache__"]);var detectionOrder=["nextjs","react","tanstack-query","elysia","trpc","drizzle","better-auth","effect","turborepo"];var languageDetectionOrder=["python","typescript"];var sourceLanguageExtensions=[{language:"python",pattern:/\.py$/u},{language:"typescript",pattern:/\.(?:ts|tsx)$/u}];var conventionalWorkspaceRoots=["apps","packages","services","libs"];var wikiRootPaths=new Set(["app/wiki","apps/wiki","wiki"]);var isRecord4=(value5)=>typeof value5==="object"&&value5!==null;var dependencyRecordSchema=Record(String5,String5);var packageJsonSchema=fromJsonString2(Struct({dependencies:optional(dependencyRecordSchema),devDependencies:optional(dependencyRecordSchema),name:optional(String5),optionalDependencies:optional(dependencyRecordSchema),peerDependencies:optional(dependencyRecordSchema),workspaces:optional(Unknown2)}));var parsePackageJsonRecord=decodeUnknownSync2(packageJsonSchema);var decodeWorkspacePackages=decodeUnknownSync2(ArraySchema(String5));var collectPackageNames=(pkg)=>{const names=new Set;const addEntries=(record3)=>{if(!record3){return}for(const name2 of Object.keys(record3)){names.add(name2)}};addEntries(pkg.dependencies);addEntries(pkg.devDependencies);addEntries(pkg.peerDependencies);addEntries(pkg.optionalDependencies);return[...names].toSorted()};var normalizeRelativePath=(relativePath)=>relativePath.split(path14.sep).join("/");var isWikiRelativePath=(relativePath)=>{const normalized=normalizeRelativePath(relativePath);return[...wikiRootPaths].some((wikiRoot)=>normalized===wikiRoot||normalized.startsWith(`${wikiRoot}/`))};var isWikiManifest=(manifest)=>isWikiRelativePath(manifest.relativePath);var packDetectionManifests=(manifests)=>manifests.filter((manifest)=>!isWikiManifest(manifest));var recursiveFindFiles=(cwd,filename)=>{const results=[];const visit2=(directory3)=>{for(const entry of readdirSync3(directory3,{withFileTypes:true})){if(ignoredDirectoryNames.has(entry.name)){continue}const absolutePath=path14.join(directory3,entry.name);if(entry.isDirectory()){visit2(absolutePath);continue}if(entry.isFile()&&entry.name===filename){results.push(absolutePath)}}};if(existsSync5(cwd)){visit2(cwd)}return results.toSorted()};var discoverConventionalWorkspacePackageJsonPaths=(cwd)=>conventionalWorkspaceRoots.flatMap((rootDirectoryName)=>{const rootDirectory=path14.join(cwd,rootDirectoryName);if(!existsSync5(rootDirectory)){return[]}return readdirSync3(rootDirectory,{withFileTypes:true}).filter((entry)=>entry.isDirectory()&&!ignoredDirectoryNames.has(entry.name)).map((entry)=>path14.join(rootDirectory,entry.name,"package.json")).filter((manifestPath)=>existsSync5(manifestPath))});var discoverTopLevelPackageJsonPaths=(cwd)=>readdirSync3(cwd,{withFileTypes:true}).filter((entry)=>entry.isDirectory()&&!ignoredDirectoryNames.has(entry.name)).map((entry)=>path14.join(cwd,entry.name,"package.json")).filter((manifestPath)=>existsSync5(manifestPath));var readPackageJsonWorkspacePatterns=(pkg)=>{const{workspaces}=pkg;if(isArray(workspaces)){return decodeWorkspacePackages(workspaces)}if(isRecord4(workspaces)&&isArray(workspaces.packages)){return decodeWorkspacePackages(workspaces.packages)}return[]};var readPnpmWorkspacePatterns=(cwd)=>{const workspacePath=path14.join(cwd,"pnpm-workspace.yaml");if(!existsSync5(workspacePath)){return[]}const patterns=[];let inPackagesSection=false;for(const rawLine of readFileSync5(workspacePath,"utf-8").split(/\r?\n/u)){const line=rawLine.trim();if(line==="packages:"){inPackagesSection=true;continue}if(!inPackagesSection){continue}if(line.startsWith("- ")){const pattern=line.slice(2).trim().replaceAll(/^['"]|['"]$/gu,"");if(pattern.length>0){patterns.push(pattern)}continue}if(line.length>0&&!line.startsWith("#")){break}}return patterns};var expandWorkspacePattern=(cwd,pattern)=>{if(pattern.endsWith("/*")){const baseDirectory=path14.join(cwd,pattern.slice(0,-2));if(!existsSync5(baseDirectory)){return[]}return readdirSync3(baseDirectory,{withFileTypes:true}).filter((entry)=>entry.isDirectory()&&!ignoredDirectoryNames.has(entry.name)).map((entry)=>path14.join(baseDirectory,entry.name,"package.json")).filter((manifestPath2)=>existsSync5(manifestPath2)).toSorted()}if(pattern.includes("*")){return[]}const manifestPath=path14.join(cwd,pattern,"package.json");return existsSync5(manifestPath)?[manifestPath]:[]};var discoverPackageJsonPaths=(cwd)=>{const rootPackageJsonPath=path14.join(cwd,"package.json");const recursivePackageJsonPaths=recursiveFindFiles(cwd,"package.json");if(!existsSync5(rootPackageJsonPath)){return recursivePackageJsonPaths}const rootPackageJson=parsePackageJsonRecord(readFileSync5(rootPackageJsonPath,"utf-8"));const workspacePatterns=new Set([...readPackageJsonWorkspacePatterns(rootPackageJson),...readPnpmWorkspacePatterns(cwd)]);const workspacePackageJsonPaths=[...workspacePatterns].flatMap((pattern)=>expandWorkspacePattern(cwd,pattern));const conventionalWorkspacePackageJsonPaths=discoverConventionalWorkspacePackageJsonPaths(cwd);const topLevelPackageJsonPaths=discoverTopLevelPackageJsonPaths(cwd);return[...recursivePackageJsonPaths,...workspacePackageJsonPaths,...conventionalWorkspacePackageJsonPaths,...topLevelPackageJsonPaths].filter((value5,index2,values3)=>values3.indexOf(value5)===index2).toSorted()};var detectTechnologies=(manifests)=>{const packageNames=new Set(packDetectionManifests(manifests).flatMap((manifest)=>manifest.dependencies));const detected=new Set;const hasPackage=(packageName)=>packageNames.has(packageName);const hasPackagePrefix=(prefix)=>[...packageNames].some((packageName)=>packageName.startsWith(prefix));if(hasPackage("next")){detected.add("nextjs");detected.add("react")}if(hasPackage("react")||hasPackage("react-dom")){detected.add("react")}if(hasPackage("@tanstack/react-query")||hasPackage("@tanstack/query-core")||hasPackage("@tanstack/react-query-devtools")||hasPackage("@tanstack/react-query-persist-client")||hasPackage("@tanstack/query-persist-client-core")){detected.add("tanstack-query")}if(hasPackage("elysia")){detected.add("elysia")}if(hasPackagePrefix("@trpc/")){detected.add("trpc")}if(hasPackage("drizzle-orm")||hasPackage("drizzle-kit")){detected.add("drizzle")}if(hasPackage("better-auth")){detected.add("better-auth")}if(hasPackage("effect")||hasPackagePrefix("@effect/")){detected.add("effect")}if(hasPackage("turbo")){detected.add("turborepo")}return detectionOrder.filter((technology)=>detected.has(technology))};var hasPackageTrigger=(packageNames,trigger)=>trigger.endsWith("/")?[...packageNames].some((packageName)=>packageName.startsWith(trigger)):packageNames.has(trigger);var isSourceDirectoryPath=(cwd,directory3)=>path14.relative(cwd,directory3)!=="";var detectSourceLanguages=(cwd)=>{const detected=new Set;const visit2=(directory3)=>{for(const entry of readdirSync3(directory3,{withFileTypes:true})){if(ignoredDirectoryNames.has(entry.name)){continue}const absolutePath=path14.join(directory3,entry.name);if(entry.isDirectory()){visit2(absolutePath);continue}const relativePath=path14.relative(cwd,absolutePath);if(entry.isFile()&&isSourceDirectoryPath(cwd,directory3)&&!isWikiRelativePath(relativePath)){for(const{language,pattern}of sourceLanguageExtensions){if(pattern.test(entry.name)&&!entry.name.endsWith(".d.ts")){detected.add(language)}}}}};if(existsSync5(cwd)){visit2(cwd)}return languageDetectionOrder.filter((language)=>detected.has(language))};var detectLanguages=(cwd,manifests)=>{const packageNames=new Set(packDetectionManifests(manifests).flatMap((manifest)=>manifest.dependencies));const detected=new Set(detectSourceLanguages(cwd));if(hasPackageTrigger(packageNames,"typescript")){detected.add("typescript")}return languageDetectionOrder.filter((language)=>detected.has(language))};var detectMonorepoSignals=(cwd,manifests)=>{const signals=[];for(const workspacePath of recursiveFindFiles(cwd,"pnpm-workspace.yaml")){signals.push({path:workspacePath,type:"pnpm-workspace"})}for(const turboConfigPath of recursiveFindFiles(cwd,"turbo.json")){signals.push({path:turboConfigPath,type:"turbo-config"})}for(const manifest of manifests){const pkg=parsePackageJsonRecord(readFileSync5(manifest.path,"utf-8"));const{workspaces}=pkg;const hasWorkspaces=isArray(workspaces)||isRecord4(workspaces)&&isArray(workspaces.packages);if(hasWorkspaces){signals.push({path:manifest.path,type:"package-json-workspaces"})}}const workspaceManifests=manifests.filter((manifest)=>{const pkg=parsePackageJsonRecord(readFileSync5(manifest.path,"utf-8"));const{workspaces}=pkg;return!(isArray(workspaces)||isRecord4(workspaces)&&isArray(workspaces.packages))});if(workspaceManifests.length>1){signals.push({path:cwd,type:"workspace-packages"})}return signals.filter((signal,index2,allSignals)=>allSignals.findIndex((candidate)=>candidate.type===signal.type&&candidate.path===signal.path)===index2)};var detectRepository=(cwd)=>try_3({catch:(cause)=>new CliDetectionError({cause,message:"Failed to detect repository shape."}),try:()=>{const manifestPaths=discoverPackageJsonPaths(cwd);const manifests=manifestPaths.map((manifestPath)=>{const pkg=parsePackageJsonRecord(readFileSync5(manifestPath,"utf-8"));return{dependencies:collectPackageNames(pkg),packageName:pkg.name??null,path:manifestPath,relativePath:path14.relative(cwd,manifestPath)||"package.json"}});const detectedLanguages=detectLanguages(cwd,manifests);const detectedTechnologies=detectTechnologies(manifests);const monorepoSignals=detectMonorepoSignals(cwd,manifests);return{cwd,detectedLanguages,detectedTechnologies,manifests,monorepo:monorepoSignals.length>0,monorepoSignals}}});var manifestPaths=(result4)=>result4.manifests.map((manifest)=>path14.relative(result4.cwd,manifest.path)||"package.json");var applyRepoShapeMode=(result4,repoShapeMode)=>repoShapeMode==="auto"?result4:{...result4,monorepo:repoShapeMode==="monorepo"};var shouldUseClipboard=(environment)=>environment.VITEST!=="true"&&environment.NODE_ENV!=="test"&&environment.DP_NO_CLIPBOARD!=="1";import{existsSync as existsSync6,mkdirSync as mkdirSync3,readFileSync as readFileSync6,rmSync,writeFileSync as writeFileSync3}from"node:fs";import path15 from"node:path";var nodeFilesystem={exists:existsSync6,read:(filePath)=>readFileSync6(filePath,"utf-8"),remove:(filePath,options4)=>rmSync(filePath,{force:true,recursive:options4?.recursive??false}),write:(filePath,content)=>{mkdirSync3(path15.dirname(filePath),{recursive:true});writeFileSync3(filePath,content,"utf-8")}};var ScaffoldCapabilities=Service("@punks/cli/scaffold/ScaffoldCapabilities");import{existsSync as existsSync7,readFileSync as readFileSync7,writeFileSync as writeFileSync4}from"node:fs";import path16 from"node:path";var harnessDirectories=new Set([".agents",".claude",".codex",".cursor",".opencode"]);var normalizeGitignorePattern=(line)=>{const trimmed=line.trim();if(trimmed===""||trimmed.startsWith("#")||trimmed.startsWith("!")){return null}return trimmed.replace(/^\//u,"").replace(/\/\*\*?$/u,"").replace(/\/$/u,"")};var isHarnessDirectoryIgnore=(line)=>{const normalized=normalizeGitignorePattern(line);return normalized!==null&&harnessDirectories.has(normalized)};var removeHarnessDirectoriesFromGitignore=(rootDirectory)=>{const gitignorePath=path16.join(rootDirectory,".gitignore");if(!existsSync7(gitignorePath)){return{gitignorePath,removedPatterns:[]}}const original=readFileSync7(gitignorePath,"utf-8");const hadFinalNewline=original.endsWith(`
|
|
346
346
|
`);const removedPatterns=[];const keptLines=original.split(/\r?\n/u).filter((line,index2,lines2)=>{if(index2===lines2.length-1&&line===""){return false}if(!isHarnessDirectoryIgnore(line)){return true}removedPatterns.push(line.trim());return false});if(removedPatterns.length===0){return{gitignorePath,removedPatterns}}writeFileSync4(gitignorePath,`${keptLines.join(`
|
|
347
347
|
`)}${hadFinalNewline?`
|
|
348
348
|
`:""}`,"utf-8");return{gitignorePath,removedPatterns}};import{createHash as createHash4}from"node:crypto";import{chmodSync,existsSync as existsSync9,lstatSync as lstatSync3,mkdtempSync,mkdirSync as mkdirSync5,readdirSync as readdirSync4,readFileSync as readFileSync8,readlinkSync as readlinkSync2,realpathSync as realpathSync2,rmSync as rmSync3,symlinkSync,writeFileSync as writeFileSync5}from"node:fs";import{tmpdir as tmpdir4}from"node:os";import path18 from"node:path";import{runInNewContext}from"node:vm";var orderedSchemaFields=(...entries3)=>Object.fromEntries(entries3);var ContextPlanVersion=Literal2("1");var ContributionKind=Literals(["skill","scoped-prompt","lifecycle-hook","tool-configuration","subagent-template"]);var ContributionIdentity=Struct({id:NonEmptyString,version:NonEmptyString});var ContributionProvenance=Struct(orderedSchemaFields(["source",NonEmptyString],["revision",NonEmptyString]));var ContributionCompatibility=Struct({id:NonEmptyString,versionRange:NonEmptyString});var ContributionReferenceClosure=ArraySchema(NonEmptyString);var ContributionOrder=Number6.pipe(check2(isInt(),isGreaterThanOrEqualTo3(0)));var contributionFields=orderedSchemaFields(["identity",ContributionIdentity],["provenance",ContributionProvenance],["compatibility",ArraySchema(ContributionCompatibility)],["references",ContributionReferenceClosure],["order",ContributionOrder]);var ContextContribution=Union2([Struct({kind:Literal2("skill"),...contributionFields}),Struct({kind:Literal2("scoped-prompt"),...contributionFields}),Struct({kind:Literal2("lifecycle-hook"),...contributionFields}),Struct({kind:Literal2("tool-configuration"),...contributionFields}),Struct({kind:Literal2("subagent-template"),...contributionFields})]);var SelectedPack=Struct({id:NonEmptyString,order:ContributionOrder});var RepositoryScope=Struct(orderedSchemaFields(["id",NonEmptyString],["packs",ArraySchema(SelectedPack)],["contributions",ArraySchema(ContextContribution)]));var ContextPlan=Struct(orderedSchemaFields(["version",ContextPlanVersion],["scopes",ArraySchema(RepositoryScope)])).annotate({parseOptions:{onExcessProperty:"error"}});var phaseSkillIds=["bug-discovery-phase","bug-resolution-phase","debugging-phase","delivery-phase","design-phase","docs-ingest-phase","finder-phase","requirements-phase","resolve-debt-phase","review-phase"];var phaseSkillSet=new Set(phaseSkillIds);var scopedPrimarySkills=(skills)=>skills.filter((skill)=>!phaseSkillSet.has(skill));var renderPrimarySkills=(skills)=>(scopedPrimarySkills(skills).length===0?["simplify"]:scopedPrimarySkills(skills)).map((skill)=>`\`${skill}\``).join(", ");var titleFromSegment=(value5)=>value5.split(/[-_]/u).filter((segment)=>segment.length>0).map((segment)=>segment.charAt(0).toUpperCase()+segment.slice(1)).join(" ");var sharedAgentsPromptTemplate=readDataFile("AGENTS.md");var rootPromptTemplate=`## Root Prompt Scaffold
|
|
@@ -386,7 +386,7 @@ Keep agent workflow in prompt files, not in the docs themselves.`;var includesPa
|
|
|
386
386
|
`)};var rootPackageJsonRecord=({scanDirectory,outputDirectory})=>{const rootPackageJsonPath=sourceOrOutputPath({outputDirectory,relativePath:"package.json",scanDirectory});return rootPackageJsonPath===null?null:readJsonRecord(rootPackageJsonPath)};var dependencyVersionFor=({rootPackageJson,packageName,isRootWorkspace})=>{const dependencySections=[rootPackageJson?.devDependencies,rootPackageJson?.dependencies,rootPackageJson?.peerDependencies,rootPackageJson?.optionalDependencies];for(const section2 of dependencySections){if(isRecord5(section2)&&typeof section2[packageName]==="string"){return section2[packageName]}}const workspaces=rootPackageJson?.workspaces;const catalog=isRecord5(workspaces)?workspaces.catalog:undefined;if(!isRootWorkspace&&isRecord5(catalog)&&typeof catalog[packageName]==="string"){return"catalog:"}return defaultDevDependencyVersion};var packageHasDependency=(packageJson,packageName)=>[packageJson.dependencies,packageJson.devDependencies,packageJson.peerDependencies,packageJson.optionalDependencies].filter(isRecord5).some((section2)=>typeof section2[packageName]==="string");var patchPackageJsonDependencies=({packageJson,packageNames,rootPackageJson,isRootWorkspace})=>{const nextPackageJson={...packageJson};const devDependencies=isRecord5(nextPackageJson.devDependencies)?{...nextPackageJson.devDependencies}:{};for(const packageName of packageNames){if(packageHasDependency(nextPackageJson,packageName)){continue}devDependencies[packageName]=dependencyVersionFor({isRootWorkspace,packageName,rootPackageJson})}nextPackageJson.devDependencies=Object.fromEntries(Object.entries(devDependencies).toSorted(([left],[right])=>left.localeCompare(right)));return nextPackageJson};var lintTargetManifests=(detection)=>{if(!detection.monorepo){return detection.manifests}return detection.manifests.filter((manifest)=>path18.posix.dirname(toPosixPath(manifest.relativePath))!==".")};var existingJsonOxlintConfigPath=({scanDirectory,outputDirectory,workspacePath})=>{const candidates=[".oxlintrc.json",".oxlintrc.jsonc"].map((fileName)=>workspacePath==="."?fileName:path18.posix.join(workspacePath,fileName));for(const candidate of candidates){const configPath=sourceOrOutputPath({outputDirectory,relativePath:candidate,scanDirectory});if(configPath!==null){return configPath}}return null};var hasRootDocsContent=(scanDirectory)=>{const docsDirectory=path18.join(scanDirectory,"docs");if(!existsSync9(docsDirectory)){return false}return readdirSync4(docsDirectory).some((entry)=>entry!=="AGENTS.md")};var ignoredPromptTargetDirectories=new Set([".git",".agents",".claude",".codex",".cursor",".devpunks",".devpunks-cache",".next",".opencode",".source",".turbo","build","coverage","dist","node_modules","opensrc","skills","tmp","worktrees"]);var discoverAuthoredAgentPromptTargets=(scanDirectory)=>{const targets=[];const visit2=(directory3)=>{for(const entry of readdirSync4(directory3,{withFileTypes:true})){if(entry.isDirectory()){if(!ignoredPromptTargetDirectories.has(entry.name)){visit2(path18.join(directory3,entry.name))}continue}if(entry.isFile()&&entry.name==="AGENTS.md"){targets.push(relativePosixPath(scanDirectory,path18.join(directory3,entry.name)))}}};if(existsSync9(scanDirectory)){visit2(scanDirectory)}return targets.toSorted()};var hasJavaScriptWorkspaceDependency=(manifest)=>manifest.dependencies.some((dependency)=>dependency==="next"||dependency==="react"||dependency==="react-dom"||dependency==="typescript"||dependency==="vite"||dependency.startsWith("@effect/")||dependency.startsWith("@tanstack/")||dependency.startsWith("@trpc/"));var isPythonUvWorkspace=({scanDirectory,outputDirectory,workspacePath,manifest})=>{const prefix=workspacePath==="."?"":`${workspacePath}/`;const hasPythonProject=sourceOrOutputPath({outputDirectory,relativePath:`${prefix}pyproject.toml`,scanDirectory})!==null||sourceOrOutputPath({outputDirectory,relativePath:`${prefix}uv.lock`,scanDirectory})!==null;return hasPythonProject&&!hasJavaScriptWorkspaceDependency(manifest)};var scopeIdForWorkspacePath=(workspacePath)=>{if(workspacePath===".agents"){return"shared"}return workspacePath==="."?"root":workspacePath};var scopeForWorkspacePath=(contextPlan,relativeWorkspacePath)=>{const scope3=contextPlan.scopes.find(({id:id2})=>id2===scopeIdForWorkspacePath(relativeWorkspacePath));if(scope3===undefined){throw new Error(`Missing compiled context scope: ${relativeWorkspacePath}`)}return scope3};var packsForWorkspace=(contextPlan,relativeWorkspacePath)=>scopeForWorkspacePath(contextPlan,relativeWorkspacePath).packs.map(({id:id2})=>id2);var writeAppliedLintConfigs=({scanDirectory,outputDirectory,detection,contextPlan,baseline,planArtifact,plannedDependencies,planOnly})=>{const rootPackageJson=planOnly?null:rootPackageJsonRecord({outputDirectory,scanDirectory});const applied=[];for(const manifest of lintTargetManifests(detection)){const manifestRelativePath=toPosixPath(manifest.relativePath);const workspacePath=path18.posix.dirname(manifestRelativePath);const normalizedWorkspacePath=workspacePath==="."?".":workspacePath;if(planOnly?detection.detectedLanguages.includes("python")&&!hasJavaScriptWorkspaceDependency(manifest):isPythonUvWorkspace({manifest,outputDirectory,scanDirectory,workspacePath:normalizedWorkspacePath})){continue}const workspacePacks=packsForWorkspace(contextPlan,normalizedWorkspacePath);const assets=resolveLintAssetsForPacks(workspacePacks,baseline);if(assets.length===0){continue}const configFile=normalizedWorkspacePath==="."?oxlintConfigFileName:path18.posix.join(normalizedWorkspacePath,oxlintConfigFileName);const existingConfigPath=planOnly?null:existingJsonOxlintConfigPath({outputDirectory,scanDirectory,workspacePath:normalizedWorkspacePath});const existingConfig=planOnly||existingConfigPath===null?{}:readJsonRecord(existingConfigPath);if(!wikiWorkspacePaths.has(normalizedWorkspacePath)){planArtifact({content:encodeOxlintConfigTs({assets,existingConfig}),kind:"harness",path:configFile,source:"lint"})}const packageJsonFile=manifestRelativePath;const requiredDevDependencies=uniqueSorted2(["oxlint","ultracite",...assets.flatMap((asset)=>asset.requiredDevDependencies)]);if(!planOnly){const packageJsonPath=sourceOrOutputPath({outputDirectory,relativePath:packageJsonFile,scanDirectory});const packageJson=packageJsonPath===null?{}:readJsonRecord(packageJsonPath);planArtifact({content:encodePrettyJson2(patchPackageJsonDependencies({isRootWorkspace:normalizedWorkspacePath===".",packageJson,packageNames:requiredDevDependencies,rootPackageJson})),kind:"harness",path:packageJsonFile,source:"lint"})}plannedDependencies.push(...requiredDevDependencies.map((name2)=>({name:name2,section:"devDependencies",source:"lint",version:dependencyVersionFor({isRootWorkspace:normalizedWorkspacePath===".",packageName:name2,rootPackageJson}),workspace:normalizedWorkspacePath})));applied.push(Object.fromEntries([["workspace",normalizedWorkspacePath],["configFile",configFile],["packageJsonFile",packageJsonFile],["assets",assets.map((asset)=>asset.id)],["requiredDevDependencies",requiredDevDependencies]]))}return applied.toSorted((left,right)=>left.workspace.localeCompare(right.workspace))};var detectedWorkspaces=(scanDirectory,detection)=>detection.manifests.map((manifest)=>path18.posix.dirname(relativePosixPath(scanDirectory,manifest.path))).filter((workspace)=>workspace!==""&&workspace!==".").toSorted();var primarySkillsForWorkspace=(contextPlan,relativeWorkspacePath)=>{const skills=scopeForWorkspacePath(contextPlan,relativeWorkspacePath).contributions.filter(({kind})=>kind==="skill").map(({identity:identity3})=>identity3.id);return uniqueSorted2(relativeWorkspacePath===".agents"?skills:scopedPrimarySkills(skills))};var skillIdsForContextPlan=(contextPlan)=>uniqueSorted2(contextPlan.scopes.flatMap(({contributions})=>contributions.filter(({kind})=>kind==="skill").map(({identity:identity3})=>identity3.id)));var workspacePathForPromptTarget=(relativePath)=>{if(relativePath===".agents/AGENTS.md"){return".agents"}if(relativePath==="AGENTS.md"){return"."}if(relativePath==="docs/AGENTS.md"){return"docs"}return path18.posix.dirname(relativePath)};var promptScope=(relativePath)=>{if(relativePath===".agents/AGENTS.md"){return"shared"}if(relativePath==="AGENTS.md"){return"root"}return relativePath==="docs/AGENTS.md"?"docs":"workspace"};var ownedPathsForPromptSpec=(spec)=>{if(spec.workspacePath==="docs"){return["docs"]}if(spec.workspacePath===null||spec.workspacePath==="."){return["."]}return[spec.workspacePath]};var buildPromptSpec=({forceGenerated=false,scanDirectory,relativePath,packs,primarySkills})=>{const sourcePath=path18.join(scanDirectory,relativePath);const source=!forceGenerated&&existsSync9(sourcePath)?"copied":"generated";const workspacePath=workspacePathForPromptTarget(relativePath);return{opensrcReferences:opensrcReferencesForPacks(packs),packs,primarySkills,scope:promptScope(relativePath),source,specFile:specPathForPromptTarget(relativePath),targetFile:relativePath,workspacePath}};var buildSubagentManifestSpec=({detection,finalPacks,promptSpecs,workspaces=detectedWorkspaces(detection.cwd,detection)})=>{const specialists=promptSpecs.filter((spec)=>spec.scope==="docs"||spec.scope==="workspace").map((spec)=>Object.fromEntries([["id",(spec.workspacePath??spec.targetFile).replaceAll(/[^a-z0-9]+/giu,"-").replaceAll(/^-|-$/gu,"")],["ownedPaths",ownedPathsForPromptSpec(spec)],["guidanceFiles",[spec.targetFile]],["packs",spec.packs],["skills",spec.primarySkills.length===0?["simplify"]:spec.primarySkills],["notes",subagentSpecialistNote(spec)]]));return sortSubagentSpecialists(Object.fromEntries([["targetFile",".agents/subagents/manifest.mjs"],["specFile",".devpunks/specs/subagents/manifest-spec.json"],["finalPacks",finalPacks],["workspaces",workspaces],["specialists",specialists]]))};var decodeSubagentManifestModule=(source)=>{const namedExport=/export\s*\{\s*(?:agents\s*,\s*capabilityPacks|capabilityPacks\s*,\s*agents)\s*\};?\s*$/u;const exportsAgentsDeclaration=/^export\s+const\s+agents\s*=/mu.test(source);const exportsCapabilityPacksDeclaration=/^export\s+const\s+capabilityPacks\s*=/mu.test(source);if(!namedExport.test(source)&&!(exportsAgentsDeclaration&&exportsCapabilityPacksDeclaration)){throw new Error("Subagent manifest does not export agents and capabilityPacks")}const sandbox3={};runInNewContext(`${source.replaceAll(/^export\s+const\s+agents\s*=/gmu,"const agents =").replaceAll(/^export\s+const\s+capabilityPacks\s*=/gmu,"const capabilityPacks =").replace(namedExport,"")}
|
|
387
387
|
globalThis.__manifest = { agents, capabilityPacks };`,sandbox3);if(sandbox3.__manifest===undefined){throw new Error("Subagent manifest does not export agents and capabilityPacks")}return sandbox3.__manifest};var subagentManifestSource=({scanDirectory,detection,finalPacks,promptSpecs,baseline,preserveExisting=true,workspaces})=>{const sourceManifestPath=path18.join(scanDirectory,".agents/subagents/manifest.mjs");if(preserveExisting&&existsSync9(sourceManifestPath)){return readFileSync8(sourceManifestPath,"utf-8")}const spec=buildSubagentManifestSpec({detection,finalPacks,promptSpecs,...workspaces===undefined?{}:{workspaces}});const authoredManifest=readBaselineDataFile(baseline.dataRoot,"subagents","manifest.mjs");return spec.specialists.length===0?authoredManifest:renderSubagentManifestModule({baseline,fallback:"",spec})};var subagentSkills=(manifest,agent)=>uniqueSorted2(agent.skills??(agent.packs??[]).flatMap((packId)=>{const pack=manifest.capabilityPacks[packId];if(pack===undefined){throw new Error(`Unknown subagent capability pack: ${packId}`)}return pack.skills}));var subagentContextInputs=(manifest)=>({capabilityGroups:manifest.agents.map((agent)=>({id:`agent:${agent.name}`,skills:subagentSkills(manifest,agent)})),templates:manifest.agents.map(({name:name2})=>({capabilityGroups:[`agent:${name2}`],id:name2,scopeId:"root"}))});var assertSubagentManifestMatchesContext=(contextPlan,manifest)=>{const planned=contextPlan.scopes.flatMap(({contributions})=>contributions).filter(({kind})=>kind==="subagent-template").map(({identity:identity3,references})=>({id:identity3.id,references:uniqueSorted2(references)})).toSorted((left,right)=>left.id.localeCompare(right.id));const rendered=manifest.agents.map((agent)=>({id:agent.name,references:subagentSkills(manifest,agent)})).toSorted((left,right)=>left.id.localeCompare(right.id));if(JSON.stringify(planned)!==JSON.stringify(rendered)){throw new Error("Rendered subagent manifest does not match compiled context plan")}};var renderWorkspacePrompt=({relativeWorkspacePath,primarySkills,packs})=>{const seededPrompt=resolveSeededWorkspacePrompt({packs,primarySkills,relativeWorkspacePath});if(seededPrompt!==undefined){return seededPrompt}return resolveGenericWorkspacePrompt({packs,primarySkills,relativeWorkspacePath})};var writeArtifact=({outputDirectory,relativePath,content})=>{const absolutePath=path18.join(outputDirectory,relativePath);mkdirSync5(path18.dirname(absolutePath),{recursive:true});writeFileSync5(absolutePath,content,"utf-8");return relativePath};var applyDesiredArtifact=({outputDirectory,relativePath,content,encoding="utf-8",mode})=>{const absolutePath=path18.join(outputDirectory,relativePath);mkdirSync5(path18.dirname(absolutePath),{recursive:true});rmSync3(absolutePath,{force:true,recursive:true});if(encoding==="symlink"){symlinkSync(content,absolutePath);return relativePath}writeFileSync5(absolutePath,Buffer.from(content,encoding==="base64"?"base64":"utf-8"));if(mode!==undefined){chmodSync(absolutePath,mode%512)}return relativePath};var writeEvidenceArtifact=writeArtifact;var resolvePromptContent=({scanDirectory,relativePath,promptSpec,preserveExistingManagedFiles,seedContent})=>{const sourcePath=path18.join(scanDirectory,relativePath);if(preserveExistingManagedFiles&&existsSync9(sourcePath)){return readFileSync8(sourcePath,"utf-8")}if(seedContent!==undefined){return seedContent}if(relativePath===".agents/AGENTS.md"){return sharedAgentsPromptTemplate}if(relativePath==="AGENTS.md"){return rootPromptTemplate}if(relativePath==="docs/AGENTS.md"){return docsPromptTemplate}if(promptSpec.scope==="workspace"){const relativeWorkspacePath=path18.dirname(relativePath);return renderWorkspacePrompt({packs:promptSpec.packs,primarySkills:promptSpec.primarySkills,relativeWorkspacePath})}return""};var collectRelativeFiles=(outputDirectory,relativeDirectory)=>{const absoluteDirectory=path18.join(outputDirectory,relativeDirectory);if(!existsSync9(absoluteDirectory)){return[]}const files=[];const visit2=(currentDirectory)=>{for(const entry of readdirSync4(currentDirectory,{withFileTypes:true})){const absolutePath=path18.join(currentDirectory,entry.name);const relativePath=path18.relative(outputDirectory,absolutePath).split(path18.sep).join("/");const stat3=lstatSync3(absolutePath);if(stat3.isSymbolicLink()){files.push(relativePath);continue}if(entry.isDirectory()){visit2(absolutePath);continue}if(entry.isFile()){files.push(relativePath)}}};visit2(absoluteDirectory);return files.toSorted()};var hashContent=(content)=>createHash4("sha256").update(content).digest("hex");var managedKindForPath=(relativePath)=>{if(relativePath===".agents/AGENTS.md"){return"agent-prompt"}if(relativePath===".devpunks/AGENT-HANDOFF.md"||relativePath===".devpunks/AGENT-SYSTEM-PROMPT.md"){return"handoff"}if(relativePath===".devpunks/scaffold-manifest.json"){return"manifest"}if(relativePath===".devpunks/context-plan.json"){return"context-plan"}if(relativePath===".devpunks/harness-projection-receipt.json"){return"projection-receipt"}if(relativePath.startsWith(".devpunks/specs/prompts/")){return"prompt-spec"}if(relativePath.startsWith(".devpunks/specs/lint/")){return"lint-spec"}if(relativePath.startsWith("opensrc/")){return"source-guide"}if(relativePath.startsWith(".agents/skills/")){return"skill"}if(relativePath.startsWith(".agents/subagents/")||relativePath.startsWith(".devpunks/specs/subagents/")){return"subagent"}if(relativePath.startsWith(".agents/scripts/")){return"script"}if(relativePath.includes("/hooks/")){return"hook"}return"harness"};var expandManagedFiles=(outputDirectory,relativePaths)=>{const files=new Set;for(const relativePath of relativePaths){const absolutePath=path18.join(outputDirectory,relativePath);if(!existsSync9(absolutePath)){continue}const stat3=lstatSync3(absolutePath);if(stat3.isDirectory()){for(const file5 of collectRelativeFiles(outputDirectory,relativePath)){files.add(file5)}continue}if(stat3.isFile()||stat3.isSymbolicLink()){files.add(relativePath)}}return[...files].toSorted().map((relativePath)=>{const absolutePath=path18.join(outputDirectory,relativePath);const stat3=lstatSync3(absolutePath);const content=stat3.isSymbolicLink()?`symlink:${readlinkSync2(absolutePath)}`:readFileSync8(absolutePath);return{kind:managedKindForPath(relativePath),path:relativePath,sha256:hashContent(content)}})};var promptTargetsForDetection=(scanDirectory,detection,additionalPromptTargets=[],discoverAuthored=true)=>{const targets=new Map;const setTarget=(target)=>{const existing=targets.get(target.relativePath);if(existing===undefined||existing.manifest===null&&target.manifest!==null){targets.set(target.relativePath,target)}};setTarget({manifest:null,relativePath:".agents/AGENTS.md"});setTarget({manifest:null,relativePath:"AGENTS.md"});for(const{relativePath}of additionalPromptTargets){setTarget({manifest:null,relativePath})}if(discoverAuthored&&(hasRootDocsContent(scanDirectory)||existsSync9(path18.join(scanDirectory,"docs/AGENTS.md")))){setTarget({manifest:null,relativePath:"docs/AGENTS.md"})}if(discoverAuthored){for(const relativePath of discoverAuthoredAgentPromptTargets(scanDirectory)){setTarget({manifest:null,relativePath})}}if(detection.monorepo){for(const manifest of detection.manifests){const relativeManifestPath=relativePosixPath(scanDirectory,manifest.path);if(relativeManifestPath==="package.json"){continue}setTarget({manifest,relativePath:path18.posix.join(path18.posix.dirname(relativeManifestPath),"AGENTS.md")})}}return[...targets.values()].toSorted((left,right)=>left.relativePath.localeCompare(right.relativePath))};var promptFileForScopeId=(scopeId)=>{if(scopeId==="root"){return"AGENTS.md"}return scopeId==="shared"?".agents/AGENTS.md":`${scopeId}/AGENTS.md`};var promptTargetsForContextPlan=(contextPlan)=>contextPlan.scopes.filter(({contributions})=>contributions.some(({kind})=>kind==="scoped-prompt")).map(({id:id2})=>({manifest:null,relativePath:promptFileForScopeId(id2)})).toSorted((left,right)=>left.relativePath.localeCompare(right.relativePath));var contextScopeKind=(relativeWorkspacePath)=>{if(relativeWorkspacePath===".agents"){return"shared"}if(relativeWorkspacePath==="."){return"root"}if(relativeWorkspacePath==="docs"||wikiWorkspacePaths.has(relativeWorkspacePath)){return"docs"}return"workspace"};var skillReferenceClosure=({baseline,sourceDirectory})=>{const root=resolveBaselinePath({baselineRoot:baseline.root,baselineSkillsRoot:baseline.skillsRoot,relativePath:sourceDirectory});const references=[];const visit2=(directory3)=>{for(const entry of readdirSync4(directory3,{withFileTypes:true})){const absolutePath=path18.join(directory3,entry.name);if(entry.isDirectory()){visit2(absolutePath)}else if(entry.isFile()&&absolutePath!==path18.join(root,"SKILL.md")){references.push(relativePosixPath(root,absolutePath))}}};visit2(root);return references.toSorted()};var projectLocalSkillMetadata=({scanDirectory,skillIds,baseline})=>{const baselineSkillIds=new Set(baseline.skills.map(({id:id2})=>id2));const localSkillsRoot=path18.join(scanDirectory,".agents/skills");if(existsSync9(localSkillsRoot)&&lstatSync3(localSkillsRoot).isSymbolicLink()){throw new Error("Project-local skills root must not be a symlink")}const resolvedLocalSkillsRoot=existsSync9(localSkillsRoot)?realpathSync2(localSkillsRoot):null;if(resolvedLocalSkillsRoot!==null){const agentsBoundary=path18.join(realpathSync2(scanDirectory),".agents");const relativeSkillsRoot=path18.relative(agentsBoundary,resolvedLocalSkillsRoot);if(relativeSkillsRoot===".."||relativeSkillsRoot.startsWith(`..${path18.sep}`)||path18.isAbsolute(relativeSkillsRoot)){throw new Error("Project-local skills root escapes repository .agents boundary")}}return skillIds.filter((skillId)=>!baselineSkillIds.has(skillId)).map((skillId)=>{if(!/^[a-z0-9][a-z0-9._-]*$/u.test(skillId)||resolvedLocalSkillsRoot===null){throw new Error(`Missing project-local skill metadata: ${skillId}`)}const root=path18.join(localSkillsRoot,skillId);if(existsSync9(root)&&!lstatSync3(root).isDirectory()){throw new Error(`Project-local skill root must be an ordinary directory: ${skillId}`)}const skillFile=path18.join(root,"SKILL.md");if(!existsSync9(skillFile)){throw new Error(`Missing project-local skill metadata: ${skillId}`)}const skillFileStat=lstatSync3(skillFile);if(!skillFileStat.isFile()&&!skillFileStat.isSymbolicLink()){throw new Error(`Project-local SKILL.md must be a regular file: ${skillId}`)}const resolvedRoot=realpathSync2(root);const relativeRoot=path18.relative(resolvedLocalSkillsRoot,resolvedRoot);if(relativeRoot===".."||relativeRoot.startsWith(`..${path18.sep}`)||path18.isAbsolute(relativeRoot)){throw new Error(`Project-local skill escapes .agents/skills: ${skillId}`)}const references=[];const visit2=(directory3)=>{for(const entry of readdirSync4(directory3,{withFileTypes:true})){const absolutePath=path18.join(directory3,entry.name);if(entry.isSymbolicLink()){throw new Error(`Project-local skill contains symlink: ${skillId}/${relativePosixPath(root,absolutePath)}`)}if(entry.isDirectory()){visit2(absolutePath)}else if(entry.isFile()&&absolutePath!==path18.join(root,"SKILL.md")){references.push(relativePosixPath(root,absolutePath))}else if(!entry.isFile()){throw new Error(`Project-local skill contains unsupported entry: ${skillId}/${relativePosixPath(root,absolutePath)}`)}}};visit2(root);return{compatibility:[],id:skillId,references:references.toSorted()}})};var compileScaffoldContextPlan=({scanDirectory,detection,finalPacks,additionalPromptTargets=[],additionalScopes=[],preserveExistingSubagentManifest=true,baseline=bundledBaseline})=>gen2(function*compileContextPlanForScaffold(){const targets=promptTargetsForDetection(scanDirectory,detection,additionalPromptTargets);const scopesById=new Map(targets.map((target)=>{const relativeWorkspacePath=workspacePathForPromptTarget(target.relativePath);return[scopeIdForWorkspacePath(relativeWorkspacePath),{id:scopeIdForWorkspacePath(relativeWorkspacePath),kind:contextScopeKind(relativeWorkspacePath),manifest:target.manifest,relativeWorkspacePath}]}));for(const manifest of detection.manifests){const relativeWorkspacePath=path18.posix.dirname(toPosixPath(manifest.relativePath));const id2=scopeIdForWorkspacePath(relativeWorkspacePath);if(!scopesById.has(id2)){scopesById.set(id2,{id:id2,kind:contextScopeKind(relativeWorkspacePath),manifest,relativeWorkspacePath})}}for(const scope3 of additionalScopes){scopesById.set(scope3.id,scope3)}const promptSpecs=yield*all2(targets.map((target)=>gen2(function*compilePromptSpec(){const relativeWorkspacePath=workspacePathForPromptTarget(target.relativePath);const scope3=scopesById.get(scopeIdForWorkspacePath(relativeWorkspacePath));if(scope3===undefined){const message=`Missing context scope for prompt target: ${target.relativePath}`;return yield*new ContextPlanCompilationFailure({cause:new Error(message),message,operation:"compile-context-plan"})}const selection=yield*resolveContextScopeSelection({baseline,finalPacks,scope:scope3});return buildPromptSpec({packs:selection.packs,primarySkills:relativeWorkspacePath===".agents"?selection.skillIds:scopedPrimarySkills(selection.skillIds),relativePath:target.relativePath,scanDirectory})})));const manifestSource=subagentManifestSource({baseline,detection,finalPacks,preserveExisting:preserveExistingSubagentManifest,promptSpecs,scanDirectory});const subagentInputs=subagentContextInputs(decodeSubagentManifestModule(manifestSource));const compilerInput={baseline,detection,finalPacks,resolvedSkills:[...baseline.skills.map((skill)=>({compatibility:[],id:skill.id,references:skillReferenceClosure({baseline,sourceDirectory:skill.sourceDirectory})})),...projectLocalSkillMetadata({baseline,scanDirectory,skillIds:uniqueSorted2(subagentInputs.capabilityGroups.flatMap(({skills})=>skills))})],scopes:[...scopesById.values()]};return yield*compileContextPlan({...compilerInput,capabilityGroups:subagentInputs.capabilityGroups,subagentTemplates:subagentInputs.templates})});var runScaffoldOutputPipeline=({scanDirectory,detection,additionalPromptTargets=[],contextPlan:suppliedContextPlan,finalPacks:suppliedFinalPacks,outputDirectory,repoShapeMode,toolBootstrapStatuses=[],preserveExistingManagedFiles,displayOutputDirectory,baseline=bundledBaseline,compileDesiredOutput=compileDesiredScaffoldOutput,desiredState:suppliedDesiredState,settings,scriptEnvironment,scriptRuntimePath:scriptRuntimePath2,planOnly=false})=>gen2(function*executeScaffoldOutputPipeline(){if(suppliedContextPlan===undefined&&suppliedFinalPacks===undefined){const message="Scaffold output requires a compiled context plan or legacy pack selection";return yield*new ContextPlanCompilationFailure({cause:new Error(message),message,operation:"compile-context-plan"})}const compiledContextPlan=suppliedContextPlan??(yield*compileScaffoldContextPlan({additionalPromptTargets,baseline,detection,finalPacks:suppliedFinalPacks??[],preserveExistingSubagentManifest:preserveExistingManagedFiles??true,scanDirectory}));return yield*sync2(()=>{const contextPlan=compiledContextPlan;const persistContextPlan=suppliedContextPlan!==undefined;const finalPacks=packsForWorkspace(contextPlan,".");const shouldPreserveExistingManagedFiles=preserveExistingManagedFiles??true;const renderedOutputDirectory=displayOutputDirectory??outputDirectory;const generatedFiles=[];const promptOutputs=[];const promptSpecFiles=[];const lintSpecFiles=[];const sourceGuideFiles=[];const skillFiles=[];const subagentFiles=[];const scriptFiles=[];const hookFiles=[];const harnessFiles=[];const plannedFiles=[];const plannedDependencies=[];const plannedDirectoriesToReset=[];const planArtifact=(file5)=>{plannedFiles.push(file5);return file5.path};const planDirectory=({sourceDirectory,targetDirectory,source})=>{const visit2=(directory3)=>{for(const entry of readdirSync4(directory3,{withFileTypes:true})){const absolutePath=path18.join(directory3,entry.name);if(entry.isDirectory()){visit2(absolutePath);continue}const sourceRelativePath=relativePosixPath(sourceDirectory,absolutePath);const baselineRelativePath=relativePosixPath(baseline.skillsRoot,absolutePath);const logicalBaselineRelativePath=baseline===bundledBaseline?logicalBundledSkillRelativePath(baselineRelativePath):baselineRelativePath;const logicalSourceRelativePath=logicalBaselineRelativePath===baselineRelativePath?sourceRelativePath:path18.posix.relative(relativePosixPath(baseline.skillsRoot,sourceDirectory),logicalBaselineRelativePath);const relativePath=path18.posix.join(targetDirectory,logicalSourceRelativePath);if(entry.isSymbolicLink()){planArtifact({content:readlinkSync2(absolutePath),encoding:"symlink",kind:"skill",path:relativePath,source});continue}if(!entry.isFile()){continue}const bytes=readFileSync8(absolutePath);let content;try{content=bytes.includes(0)?undefined:new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{content=undefined}planArtifact({content:content??bytes.toString("base64"),encoding:content===undefined?"base64":"utf-8",kind:"skill",mode:fileMode(lstatSync3(absolutePath).mode),path:relativePath,source})}};visit2(sourceDirectory)};const selectedSkillIds=skillIdsForContextPlan(contextPlan);const baselineSkillIds=new Set(baseline.skills.map(({id:id2})=>id2));const referencedProjectLocalSkillIds=uniqueSorted2(contextPlan.scopes.flatMap(({contributions})=>contributions.flatMap((contribution2)=>contribution2.kind==="subagent-template"?contribution2.references.filter((skillId)=>!baselineSkillIds.has(skillId)):[])));const projectLocalSkillIds=new Set(planOnly?[]:projectLocalSkillMetadata({baseline,scanDirectory,skillIds:referencedProjectLocalSkillIds}).map(({id:id2})=>id2));const finalSkills=uniqueSorted2(planOnly?selectedSkillIds.filter((skillId)=>baselineSkillIds.has(skillId)):[...selectedSkillIds,...projectLocalSkillIds]);const hasOxfmt=detectionHasPackage(detection,"oxfmt");const hasPython=detection.detectedLanguages.includes("python");const finalHookIds=new Set(scopeForWorkspacePath(contextPlan,".").contributions.filter(({kind})=>kind==="lifecycle-hook").map(({identity:identity3})=>identity3.id).filter((hookId)=>hookId!=="format-edited-file"||hasOxfmt||hasPython));const lintAssets=resolveLintAssetsForPacks(finalPacks,baseline);const appliedLintConfigs=writeAppliedLintConfigs({baseline,contextPlan,detection,outputDirectory,planArtifact,planOnly,plannedDependencies,scanDirectory});const rootOxlintConfigFiles=uniqueSorted2([...planOnly?[]:existingOxlintConfigFiles(scanDirectory),...scanDirectory===outputDirectory?plannedFiles.map(({path:filePath})=>filePath).filter((filePath)=>oxlintConfigCandidates.some((candidate)=>candidate===filePath)):[]]);const lintAssetIdsByPack=Object.fromEntries(finalPacks.map((packId)=>[packId,lintAssets.filter((asset)=>asset.sourcePacks.includes(packId)).map((asset)=>asset.id)]).filter(([,assetIds])=>assetIds.length>0));const hasExistingRootOxlintConfig=rootOxlintConfigFiles.length>0;const lintStarterConfigFile=hasExistingRootOxlintConfig?null:".devpunks/specs/lint/oxlint-starter.json";const promptTargets=suppliedContextPlan===undefined?promptTargetsForDetection(scanDirectory,detection,additionalPromptTargets,!planOnly):promptTargetsForContextPlan(contextPlan);const promptSpecs=promptTargets.map((target)=>buildPromptSpec({forceGenerated:planOnly,packs:packsForWorkspace(contextPlan,workspacePathForPromptTarget(target.relativePath)),primarySkills:primarySkillsForWorkspace(contextPlan,workspacePathForPromptTarget(target.relativePath)),relativePath:target.relativePath,scanDirectory}));const opensrcReferences=collectOpensrcReferences(promptSpecs);const sourceGuides=sourceGuidesForSelection({detectedTechnologies:detection.detectedTechnologies,finalPacks});const sourceGuideSummaries=sourceGuides.map(summarizeSourceGuide);const contextPlanFile=".devpunks/context-plan.json";const planPromptAndLintArtifacts=()=>{if(persistContextPlan){generatedFiles.push(planArtifact(Object.fromEntries([["path",contextPlanFile],["content",encodeJson3(encodeContextPlan2(contextPlan))],["kind","context-plan"],["source","context-plan"]])))}generatedFiles.push(planArtifact(Object.fromEntries([["path",".agents/AGENTS.md"],["content",resolvePromptContent({preserveExistingManagedFiles:shouldPreserveExistingManagedFiles,promptSpec:expectedPromptSpec(promptSpecs,".agents/AGENTS.md"),relativePath:".agents/AGENTS.md",scanDirectory})],["kind","agent-prompt"],["source","prompt"]])));promptOutputs.push(".agents/AGENTS.md");const additionalPromptTargetByPath=new Map(additionalPromptTargets.map((target)=>[target.relativePath,target]));additionalPromptTargetByPath.delete(".agents/AGENTS.md");for(const[promptTarget,{seedContent}]of[...additionalPromptTargetByPath].toSorted(([left],[right])=>left.localeCompare(right))){const promptSpec=promptSpecs.find(({targetFile})=>targetFile===promptTarget);if(promptSpec===undefined){continue}generatedFiles.push(planArtifact(Object.fromEntries([["path",promptTarget],["content",resolvePromptContent({preserveExistingManagedFiles:shouldPreserveExistingManagedFiles,promptSpec,relativePath:promptTarget,scanDirectory,...seedContent===undefined?{}:{seedContent}})],["kind","agent-prompt"],["source","prompt"]])));promptOutputs.push(promptTarget)}for(const promptSpec of promptSpecs){generatedFiles.push(planArtifact(Object.fromEntries([["path",promptSpec.specFile],["content",renderPromptSpecMarkdown(promptSpec)],["kind","prompt-spec"],["source","prompt"]])));promptSpecFiles.push(promptSpec.specFile)}if(sourceGuides.length>0){const readmeFile="opensrc/README.md";generatedFiles.push(planArtifact(Object.fromEntries([["path",readmeFile],["content",renderSourceGuideReadme(sourceGuides)],["kind","source-guide"],["source","source-guide"]])));sourceGuideFiles.push(readmeFile);for(const guide of sourceGuides){const guideFile=sourceGuideFile(guide);generatedFiles.push(planArtifact(Object.fromEntries([["path",guideFile],["content",renderSourceGuide(guide)],["kind","source-guide"],["source","source-guide"]])));sourceGuideFiles.push(guideFile)}}if(lintAssets.length>0){const lintAssetsFile=".devpunks/specs/lint/assets.json";generatedFiles.push(planArtifact(Object.fromEntries([["path",lintAssetsFile],["content",encodeJson3(lintAssets)],["kind","lint-spec"],["source","lint"]])));lintSpecFiles.push(lintAssetsFile);const lintSelectionFile=".devpunks/specs/lint/selection.json";generatedFiles.push(planArtifact(Object.fromEntries([["path",lintSelectionFile],["content",encodeJson3(Object.fromEntries([["finalPacks",finalPacks],["selectedAssetIds",lintAssets.map((asset)=>asset.id)],["selectedAssetsByPack",lintAssetIdsByPack],["requiredDevDependencies",uniqueSorted2(["oxlint","ultracite",...lintAssets.flatMap((asset)=>asset.requiredDevDependencies)])],["existingRootOxlintConfigFiles",rootOxlintConfigFiles],["starterConfigFile",lintStarterConfigFile],["ultraciteCorePreset","ultracite/oxlint/core"],["appliedLintConfigs",appliedLintConfigs]]))],["kind","lint-spec"],["source","lint"]])));lintSpecFiles.push(lintSelectionFile);const lintReadmeFile=".devpunks/specs/lint/README.md";generatedFiles.push(planArtifact(Object.fromEntries([["path",lintReadmeFile],["content",renderLintSpecMarkdown({hasExistingOxlintConfig:hasExistingRootOxlintConfig,lintAssets,starterConfigFile:lintStarterConfigFile})],["kind","lint-spec"],["source","lint"]])));lintSpecFiles.push(lintReadmeFile);if(lintStarterConfigFile!==null){generatedFiles.push(planArtifact(Object.fromEntries([["path",lintStarterConfigFile],["content",encodeJson3(oxlintStarterConfig)],["kind","lint-spec"],["source","lint"]])));lintSpecFiles.push(lintStarterConfigFile)}}};planPromptAndLintArtifacts();const planSkillArtifacts=()=>{for(const skillId of finalSkills){const baselineSourceDirectory=baseline.skills.find(({id:id2})=>id2===skillId)?.sourceDirectory;if(baselineSourceDirectory===undefined&&!projectLocalSkillIds.has(skillId)){throw new Error(`Unknown scaffold skill: ${skillId}`)}const targetDirectory=path18.posix.join(".agents/skills",skillId);const absoluteTargetDirectory=path18.join(outputDirectory,targetDirectory);const absoluteSourceDirectory=baselineSourceDirectory===undefined?path18.join(scanDirectory,targetDirectory):resolveBaselinePath({baselineRoot:baseline.root,baselineSkillsRoot:baseline.skillsRoot,relativePath:baselineSourceDirectory});const materializesSkill=path18.resolve(absoluteSourceDirectory)!==path18.resolve(absoluteTargetDirectory);if(materializesSkill){plannedDirectoriesToReset.push(targetDirectory)}planDirectory({source:baselineSourceDirectory===undefined?"project-local-skill":"baseline",sourceDirectory:absoluteSourceDirectory,targetDirectory});if(baselineSourceDirectory!==undefined){generatedFiles.push(targetDirectory)}skillFiles.push(targetDirectory)}};planSkillArtifacts();const projectionScriptFiles=["sync-subagents.mjs","harness-projection/core.mjs","harness-projection/apply.mjs","harness-projection/adapters/claude.mjs","harness-projection/adapters/codex.mjs","harness-projection/adapters/cursor.mjs","harness-projection/adapters/opencode.mjs"].map((relativePath)=>`.agents/scripts/${relativePath}`);for(const scriptFile of projectionScriptFiles){const sourcePath=scriptFile.slice(".agents/scripts/".length);const content=readBaselineDataFile(baseline.dataRoot,"scripts",...sourcePath.split("/"));generatedFiles.push(planArtifact({content,kind:"script",path:scriptFile,source:"baseline"}));scriptFiles.push(scriptFile)}const syncScriptFile=".agents/scripts/sync-subagents.mjs";const planSubagentArtifacts=()=>{const useCompiledSubagentAuthority=planOnly||suppliedDesiredState!==undefined;const compiledSubagentTemplates=useCompiledSubagentAuthority?contextPlan.scopes.flatMap(({contributions})=>contributions.filter(({kind})=>kind==="subagent-template")):[];const compiledSubagentScopes=useCompiledSubagentAuthority?contextPlan.scopes.flatMap((scope3)=>{if(scope3.id==="root"||scope3.id==="shared"||scope3.id===".agents"){return[]}const specialistId=scope3.id.replaceAll(/[^a-z0-9]+/giu,"-").replaceAll(/^-|-$/gu,"");const template=compiledSubagentTemplates.find(({identity:identity3})=>identity3.id===specialistId);return template===undefined?[]:[{scope:scope3,template}]}):[];const subagentWorkspaces=useCompiledSubagentAuthority?compiledSubagentScopes.map(({scope:scope3})=>scope3.id):detectedWorkspaces(scanDirectory,detection);const manifestPromptPath=".agents/subagents/manifest.prompt.md";generatedFiles.push(planArtifact(Object.fromEntries([["path",manifestPromptPath],["content",renderSubagentManifestPrompt({finalPacks,workspaces:subagentWorkspaces})],["kind","subagent"],["source","subagent"]])));subagentFiles.push(manifestPromptPath);const subagentPromptSpecs=useCompiledSubagentAuthority?compiledSubagentScopes.map(({scope:scope3,template})=>buildPromptSpec({forceGenerated:true,packs:scope3.packs.map(({id:id2})=>id2),primarySkills:template.references,relativePath:path18.posix.join(scope3.id,"AGENTS.md"),scanDirectory})):promptSpecs;const manifestSpec=buildSubagentManifestSpec({detection,finalPacks,promptSpecs:subagentPromptSpecs,...useCompiledSubagentAuthority?{workspaces:subagentWorkspaces}:{}});generatedFiles.push(planArtifact(Object.fromEntries([["path",manifestSpec.specFile],["content",encodeJson3(manifestSpec)],["kind","subagent"],["source","subagent"]])));subagentFiles.push(manifestSpec.specFile);const renderedSubagentManifest=subagentManifestSource({baseline,detection,finalPacks,preserveExisting:!useCompiledSubagentAuthority&&shouldPreserveExistingManagedFiles,promptSpecs:subagentPromptSpecs,scanDirectory,...useCompiledSubagentAuthority?{workspaces:subagentWorkspaces}:{}});assertSubagentManifestMatchesContext(contextPlan,decodeSubagentManifestModule(renderedSubagentManifest));generatedFiles.push(planArtifact(Object.fromEntries([["path",".agents/subagents/manifest.mjs"],["content",renderedSubagentManifest],["kind","subagent"],["source","subagent"]])));subagentFiles.push(".agents/subagents/manifest.mjs");return manifestSpec};const subagentManifestSpec=planSubagentArtifacts();for(const hook of hookRegistryForBaseline(baseline).filter((entry)=>finalHookIds.has(entry.id))){generatedFiles.push(planArtifact({content:readBaselineDataFile(baseline.dataRoot,...hook.sourcePath.split("/")),kind:"hook",path:hook.outputPath,source:"baseline"}));hookFiles.push(hook.outputPath)}const buildDesiredOutputInput=()=>({baseline:{catalogRevision:baseline.summary.version,provenance:baseline.summary},contextPlan,dependencies:plannedDependencies,files:plannedFiles,projections:[claudeAdapter,codexAdapter,cursorAdapter,openCodeAdapter].map((adapter2)=>({matrix:adapter2.matrix,result:project({adapter:adapter2,contextPlan})})),...settings===undefined?{}:{settings},structuredEntries:settings===undefined?[]:[{file:".devpunks/settings.json",kind:"field",path:["requiredTools"],source:"project-settings",value:[...settings.requiredTools]}]});const desiredOutputInput=buildDesiredOutputInput();if(planOnly){return desiredOutputInput}const desiredReceiptState=(()=>{if(suppliedDesiredState!==undefined){return suppliedDesiredState}const desiredOutput=compileDesiredOutput(desiredOutputInput);if(desiredOutput._tag==="DesiredScaffoldStateCompilationFailure"){throw new Error(desiredOutput.errors.map(({message})=>message).join(`
|
|
388
388
|
`))}return desiredOutput._tag==="DesiredScaffoldOutputCompiled"?desiredOutput.catalog:desiredOutput.state})();const materializeDesiredOutput=()=>{mkdirSync5(outputDirectory,{recursive:true});snapshotPreExistingSkillHomes(outputDirectory);for(const relativeDirectory of plannedDirectoriesToReset){rmSync3(path18.join(outputDirectory,relativeDirectory),{force:true,recursive:true})}for(const file5 of desiredReceiptState.files){applyDesiredArtifact({content:file5.content,...file5.encoding===undefined?{}:{encoding:file5.encoding},...file5.mode===undefined?{}:{mode:file5.mode},outputDirectory,relativePath:file5.path})}const projectionPlanDirectory=suppliedDesiredState===undefined?null:mkdtempSync(path18.join(tmpdir4(),"hi-projection-plan-"));try{const projectionPlanPath=projectionPlanDirectory===null?null:path18.join(projectionPlanDirectory,"plan.json");if(suppliedDesiredState!==undefined&&projectionPlanPath!==null){const appliedContextPlan=decodeUnknownSync2(ContextPlan)(JSON.parse(readFileSync8(path18.join(outputDirectory,contextPlanFile),"utf-8")));const refreshedProjections=[claudeAdapter,codexAdapter,cursorAdapter,openCodeAdapter].map((adapter2)=>normalizeHarnessProjection({matrix:adapter2.matrix,result:project({adapter:adapter2,contextPlan:appliedContextPlan})})).toSorted((left,right)=>{if(left.matrix.adapter.id===right.matrix.adapter.id){return 0}return left.matrix.adapter.id<right.matrix.adapter.id?-1:1});writeFileSync5(projectionPlanPath,encodeJson3({contextPlanVersion:appliedContextPlan.version,projections:refreshedProjections,version:"1"}))}runJavaScriptFileSync({cwd:outputDirectory,...scriptEnvironment===undefined?{}:{environment:scriptEnvironment},environmentOverrides:{DP_HARNESS_PROJECTION_PLAN:projectionPlanPath??undefined},file:path18.join(outputDirectory,syncScriptFile),...scriptRuntimePath2===undefined?{}:{runtimePath:scriptRuntimePath2}})}finally{if(projectionPlanDirectory!==null){rmSync3(projectionPlanDirectory,{force:true,recursive:true})}}};materializeDesiredOutput();const collectHarnessProjectionFiles=()=>{const projectionReceiptFile2=persistContextPlan?".devpunks/harness-projection-receipt.json":null;const projectionReceipt2=projectionReceiptFile2===null?null:JSON.parse(readFileSync8(path18.join(outputDirectory,projectionReceiptFile2),"utf-8"));if(projectionReceipt2?.status==="failure"){throw new Error(`Harness projection failed; inspect ${projectionReceiptFile2}`)}if(projectionReceiptFile2!==null){generatedFiles.push(projectionReceiptFile2)}harnessFiles.push(...scanDirectory===outputDirectory||projectionReceipt2!==null?[]:collectRelativeFiles(outputDirectory,".").filter((relativePath)=>path18.posix.basename(relativePath)==="CLAUDE.md"),...collectRelativeFiles(outputDirectory,".claude").filter((relativePath)=>projectionReceipt2===null&&scanDirectory!==outputDirectory||path18.posix.basename(relativePath)!=="CLAUDE.md"),...collectRelativeFiles(outputDirectory,".codex"),...collectRelativeFiles(outputDirectory,".cursor"),...collectRelativeFiles(outputDirectory,".opencode"));const claudeProjection=projectionReceipt2?.projections.find(({adapter:adapter2})=>adapter2.id==="claude");const failedClaudeActions=new Set(claudeProjection?.failures.flatMap(({action:action2})=>action2===undefined?[]:[action2]));harnessFiles.push(...claudeProjection?.actions.flatMap((action2)=>{if(action2.operation!=="mirror"||!action2.id.includes(":scoped-prompt:")||action2.target===undefined||failedClaudeActions.has(action2.id)){return[]}const targetPath=path18.resolve(outputDirectory,action2.target);const relativeTarget=path18.relative(outputDirectory,targetPath);if(relativeTarget.startsWith(`..${path18.sep}`)||path18.isAbsolute(relativeTarget)||!existsSync9(targetPath)){return[]}const targetStat=lstatSync3(targetPath);if(!targetStat.isSymbolicLink()){if(action2.source===undefined||!targetStat.isFile()){return[]}const sourcePath=path18.resolve(outputDirectory,action2.source);const relativeSource=path18.relative(outputDirectory,sourcePath);if(relativeSource.startsWith(`..${path18.sep}`)||path18.isAbsolute(relativeSource)||!existsSync9(sourcePath)||!lstatSync3(sourcePath).isFile()||hashContent(readFileSync8(targetPath))!==hashContent(readFileSync8(sourcePath))){return[]}}return[toPosixPath(relativeTarget)]})??[]);const uniqueHarnessFiles=uniqueSorted2([...harnessFiles,...existsSync9(path18.join(outputDirectory,"opencode.json"))?["opencode.json"]:[]]);harnessFiles.splice(0,harnessFiles.length,...uniqueHarnessFiles);generatedFiles.push(...harnessFiles);return[projectionReceiptFile2,projectionReceipt2]};const[projectionReceiptFile,projectionReceipt]=collectHarnessProjectionFiles();const agentHandoffFile=".devpunks/AGENT-HANDOFF.md";generatedFiles.push(writeEvidenceArtifact({content:renderAgentHandoffMarkdown({detectedTechnologies:detection.detectedTechnologies,finalPacks,harnessFiles:harnessFiles.toSorted(),hookFiles:hookFiles.toSorted(),lintSpecFiles:lintSpecFiles.toSorted(),monorepo:detection.monorepo,opensrcReferences,outputDirectory:renderedOutputDirectory,promptOutputs:promptOutputs.toSorted(),promptSpecFiles:promptSpecFiles.toSorted(),repoShapeMode,scaffoldManifestFile:".devpunks/scaffold-manifest.json",scriptFiles:scriptFiles.toSorted(),skillFiles:skillFiles.toSorted(),sourceGuideFiles:sourceGuideFiles.toSorted(),subagentFiles:subagentFiles.toSorted(),toolBootstrapStatuses}),outputDirectory,relativePath:agentHandoffFile}));const scaffoldManifestFile=".devpunks/scaffold-manifest.json";const manifestGeneratedFiles=[...generatedFiles,scaffoldManifestFile].toSorted();const managedFiles=expandManagedFiles(outputDirectory,generatedFiles);const managedFileTypes=Object.fromEntries(managedFiles.map(({path:relativePath})=>[relativePath,lstatSync3(path18.join(outputDirectory,relativePath)).isSymbolicLink()?"symlink":"file"]));const managedFileModes=Object.fromEntries(managedFiles.map(({path:relativePath})=>{const stat3=lstatSync3(path18.join(outputDirectory,relativePath));return[relativePath,stat3.isSymbolicLink()?null:fileMode(stat3.mode)]}));const managedDependencies=desiredReceiptState.dependencies.filter((dependency)=>{const packageFile=dependency.workspace==="."?"package.json":path18.posix.join(dependency.workspace,"package.json");const absolutePath=path18.join(outputDirectory,packageFile);if(!existsSync9(absolutePath)){return false}const document=readJsonRecord(absolutePath);const section2=document[dependency.section];return typeof section2==="object"&§ion2!==null&&!Array.isArray(section2)&§ion2[dependency.name]===dependency.version});const managedStructuredEntries=desiredReceiptState.structuredEntries.filter((entry)=>{const absolutePath=path18.join(outputDirectory,entry.file);if(!existsSync9(absolutePath)){return false}let value5=readJsonRecord(absolutePath);for(const segment of entry.path){if(typeof value5!=="object"||value5===null||Array.isArray(value5)){return false}value5=value5[segment]}return JSON.stringify(value5)===JSON.stringify(entry.value)});generatedFiles.push(writeEvidenceArtifact({content:encodeJson3(Object.fromEntries([["cwd",scanDirectory],["outputDirectory",renderedOutputDirectory],["repoShapeMode",repoShapeMode],["monorepo",detection.monorepo],["manifests",detection.manifests.map((manifest)=>relativePosixPath(scanDirectory,manifest.path)||"package.json")],["detectedLanguages",detection.detectedLanguages],["detectedTechnologies",detection.detectedTechnologies],["monorepoSignals",detection.monorepoSignals.map((signal)=>Object.fromEntries([["type",signal.type],["path",relativePosixPath(scanDirectory,signal.path)||"."]]))],["finalPacks",finalPacks],...persistContextPlan?[["contextPlanFile",contextPlanFile]]:[],...projectionReceiptFile===null?[]:[["projectionReceiptFile",projectionReceiptFile],["projectionStatus",projectionReceipt?.status]],["promptOutputs",promptOutputs],["promptSpecFiles",promptSpecFiles],["lintSpecFiles",lintSpecFiles],["sourceGuideFiles",sourceGuideFiles],["skillFiles",skillFiles],["subagentFiles",subagentFiles],["scriptFiles",scriptFiles],["hookFiles",hookFiles],["harnessFiles",harnessFiles],["agentHandoffFile",agentHandoffFile],["promptSpecs",promptSpecs],["opensrcReferences",opensrcReferences],["sourceGuides",sourceGuideSummaries],["lintAssets",lintAssets],["appliedLintConfigs",appliedLintConfigs],["subagentManifestSpec",subagentManifestSpec],["baseline",baseline.summary],["version",version2],["managedFiles",managedFiles],["managedFileTypes",managedFileTypes],["managedFileModes",managedFileModes],["managedDependencies",managedDependencies],["managedStructuredEntries",managedStructuredEntries],["generatedFiles",manifestGeneratedFiles]])),outputDirectory,relativePath:scaffoldManifestFile}));const managedFilesWithManifest=expandManagedFiles(outputDirectory,[...generatedFiles]);const collectHiddenOutputDirectories=()=>[promptOutputs.some((value5)=>value5.startsWith(".agents/"))||subagentFiles.some((value5)=>value5.startsWith(".agents/"))||scriptFiles.some((value5)=>value5.startsWith(".agents/"))||hookFiles.some((value5)=>value5.startsWith(".agents/"))?".agents":null,harnessFiles.some((value5)=>value5.startsWith(".claude/"))?".claude":null,harnessFiles.some((value5)=>value5.startsWith(".codex/"))?".codex":null,harnessFiles.some((value5)=>value5.startsWith(".cursor/"))?".cursor":null,harnessFiles.some((value5)=>value5.startsWith(".opencode/"))?".opencode":null,promptSpecFiles.some((value5)=>value5.startsWith(".devpunks/"))||subagentFiles.some((value5)=>value5.startsWith(".devpunks/"))?".devpunks":null].filter((value5)=>value5!==null);const hiddenOutputDirectories=collectHiddenOutputDirectories();return{agentHandoffFile,contextPlan,contextPlanFile,generatedFiles:generatedFiles.toSorted(),harnessFiles:harnessFiles.toSorted(),hiddenOutputDirectories,hookFiles:hookFiles.toSorted(),lintAssets,lintSpecFiles:lintSpecFiles.toSorted(),managedFiles:managedFilesWithManifest,opensrcReferences,outputDirectory,projectionReceiptFile,projectionStatus:projectionReceipt?.status??null,promptOutputs:promptOutputs.toSorted(),promptSpecFiles:promptSpecFiles.toSorted(),promptSpecs,scaffoldManifestFile,scriptFiles:scriptFiles.toSorted(),skillFiles:skillFiles.toSorted(),sourceGuideFiles:sourceGuideFiles.toSorted(),sourceGuides:sourceGuideSummaries,subagentFiles:subagentFiles.toSorted(),subagentManifestSpec}})});var planScaffoldOutput=(options4)=>runScaffoldOutputPipeline({...options4,planOnly:true}).pipe(map7((result4)=>result4));var writeScaffoldOutput=(options4)=>runScaffoldOutputPipeline(options4).pipe(map7((result4)=>result4));var defaultPackIds2=defaultPackIdsForBaseline();var detectedPackIds2=detectedPackIdsForBaseline();var knownPackIds2=knownPackIdsForBaseline();var languagePackIds2=languagePackIdsForBaseline();var surfacePackIds2=surfacePackIdsForBaseline();var packRegistryForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).map(({id:id2,category,triggerPackages,description})=>({category,description,id:id2,triggerPackages}));var packRegistry=packRegistryForBaseline();class UnknownPackIds extends TaggedErrorClass()("@punks/cli/repository-analysis/UnknownPackIds",{cause:Defect(),invalidPackIds:ArraySchema(String5),operation:Literal2("validate-pack-selection")}){}class RepositoryScanError extends TaggedErrorClass("@punks/cli/features/repository-analysis/RepositoryScanError")("RepositoryScanError",{cause:Defect(),operation:Literal2("scan-repository"),rootDirectory:String5}){}var wikiRootPaths2=new Set(["app/wiki","apps/wiki","wiki"]);var pathSegments=(relativePath)=>relativePath.split(/[\\/]+/u);var packDetectionManifests2=(manifests)=>manifests.filter((manifest)=>{const relativePath=pathSegments(manifest.relativePath).join("/");return![...wikiRootPaths2].some((wikiRoot)=>relativePath===wikiRoot||relativePath.startsWith(`${wikiRoot}/`))});var hasFrontendSurface=(result4)=>result4.detectedTechnologies.some((technology)=>technology==="nextjs"||technology==="react");var backendWorkspacePathSegments=new Set(["api","backend","server","services"]);var backendPackageNameSegments=new Set(["api","backend","server","service"]);var hasBackendWorkspaceName=(manifest)=>{const workspaceSegments=pathSegments(manifest.relativePath).slice(0,-1);if(workspaceSegments.some((segment)=>backendWorkspacePathSegments.has(segment))){return true}if(!manifest.packageName){return false}const packageNameSegments=manifest.packageName.replace(/^@[^/]+\//u,"").split(/[^a-zA-Z0-9]+/u).filter((segment)=>segment.length>0).map((segment)=>segment.toLowerCase());return packageNameSegments.some((segment)=>backendPackageNameSegments.has(segment))};var hasBackendSurface=(result4)=>result4.detectedTechnologies.some((technology)=>technology==="better-auth"||technology==="drizzle"||technology==="elysia"||technology==="trpc")||result4.manifests.some(hasBackendWorkspaceName);var detectionToPackId={"better-auth":"better-auth",drizzle:"drizzle",effect:"effect",elysia:"elysia",nextjs:"nextjs",react:"react","tanstack-query":"tanstack-query",trpc:"trpc",turborepo:"turborepo"};var toSortedUnique=(values3)=>[...new Set(values3)].toSorted();var isDetectedLanguage=(value5)=>value5==="python"||value5==="typescript";var detectLanguagePacks=(detection,baseline)=>{const packages=new Set(packDetectionManifests2(detection.manifests).flatMap((manifest)=>manifest.dependencies));const hasTrigger=(trigger)=>trigger.endsWith("/")?[...packages].some((packageName)=>packageName.startsWith(trigger)):packages.has(trigger);return baseline.packs.filter((pack)=>pack.category==="language").filter((pack)=>isDetectedLanguage(pack.id)&&detection.detectedLanguages.includes(pack.id)||pack.triggerPackages.some(hasTrigger)).map((pack)=>pack.id).filter((packId)=>languagePackIdsForBaseline(baseline).includes(packId))};var detectSurfacePacks=(detection,baseline)=>[...hasBackendSurface(detection)?["backend"]:[],...hasFrontendSurface(detection)?["frontend"]:[]].filter((packId)=>surfacePackIdsForBaseline(baseline).includes(packId));var detectPackageTriggeredPacks=(detection,baseline)=>{const packages=new Set(packDetectionManifests2(detection.manifests).flatMap((manifest)=>manifest.dependencies));const hasTrigger=(trigger)=>trigger.endsWith("/")?[...packages].some((packageName)=>packageName.startsWith(trigger)):packages.has(trigger);return baseline.packs.filter((pack)=>pack.category==="detected").filter((pack)=>pack.triggerPackages.some(hasTrigger)).map((pack)=>pack.id)};var resolvePackSelection=(detection,baseline=bundledBaseline)=>{const languagePacks=detectLanguagePacks(detection,baseline);const technologyPacks=detection.detectedTechnologies.flatMap((technology)=>{const packId=detectionToPackId[technology];return packId?[packId]:[]}).filter((packId)=>knownPackIdsForBaseline(baseline).includes(packId));const packageTriggeredPacks=detectPackageTriggeredPacks(detection,baseline);const surfacePacks=detectSurfacePacks(detection,baseline);const defaultPackIds3=defaultPackIdsForBaseline(baseline);const knownPackIds3=knownPackIdsForBaseline(baseline);const detectedPacks=toSortedUnique([...technologyPacks,...packageTriggeredPacks]);const preselectedPacks=toSortedUnique([...defaultPackIds3,...languagePacks,...detectedPacks,...surfacePacks]);const optionalPacks=knownPackIds3.filter((packId)=>!preselectedPacks.includes(packId));return{defaultPacks:defaultPackIds3,detectedPacks:toSortedUnique(detectedPacks),languagePacks:toSortedUnique(languagePacks),optionalPacks,preselectedPacks,surfacePacks:toSortedUnique(surfacePacks)}};var finalizePackSelection=(resolved,additions,removals)=>{const withAdditions=new Set([...resolved.preselectedPacks,...additions]);for(const removal of removals){if(resolved.defaultPacks.includes(removal)){continue}withAdditions.delete(removal)}return[...withAdditions].toSorted()};var canRemovePack=(resolved,packId)=>resolved.preselectedPacks.includes(packId)&&!resolved.defaultPacks.includes(packId);var inspectRepository=fn2("RepositoryAnalysis.inspect")(function*inspectRepository2({baseline,repoShapeMode,rootDirectory,scanner}){const scanned=yield*scanner.scan(rootDirectory);const detection=repoShapeMode==="auto"?scanned:{...scanned,monorepo:repoShapeMode==="monorepo"};return{detection,packs:resolvePackSelection(detection,baseline)}});var scanRepository=fn2("NodeRepositoryScanner.scan")(function*scanRepository2(rootDirectory){const detection=yield*result2(detectRepository(rootDirectory));if(isSuccess2(detection)){return detection.success}const error2=detection.failure;return yield*new RepositoryScanError({cause:error2.cause??error2,operation:"scan-repository",rootDirectory})});var nodeRepositoryScanner={scan:scanRepository};var inspectLocalRepository=({baseline,repoShapeMode,rootDirectory})=>inspectRepository({baseline,repoShapeMode,rootDirectory,scanner:nodeRepositoryScanner});var agentSystemPromptFile=".devpunks/AGENT-SYSTEM-PROMPT.md";var clipboardWorkingDirectory=homedir2();var tryClipboardCommand=({command,args:args2,text:text3,runtime})=>{if(!runtime.commandExists(command)){return{ok:false}}try{runtime.execFile(command,args2,{cwd:clipboardWorkingDirectory,input:text3});return{command,ok:true}}catch{return{ok:false}}};var copyToClipboard=(text3,runtime)=>{const environment=runtime.env??{};if(!shouldUseClipboard(environment)){return{ok:false}}const commandRuntime={commandExists:runtime.commandExists??((command)=>commandExistsOnPath(command,environment)),execFile:runtime.execFile??((command,args2,options4)=>execFileSync2(command,[...args2],{cwd:options4.cwd,env:environment,input:options4.input,stdio:["pipe","ignore","ignore"]}))};const platform=runtime.platform??process.platform;if(platform==="darwin"){return tryClipboardCommand({args:[],command:"pbcopy",runtime:commandRuntime,text:text3})}if(platform==="win32"){return tryClipboardCommand({args:[],command:"clip",runtime:commandRuntime,text:text3})}const candidates=[{args:[],command:"wl-copy"},{args:["-selection","clipboard"],command:"xclip"},{args:["--clipboard","--input"],command:"xsel"}];for(const candidate of candidates){const result4=tryClipboardCommand({...candidate,runtime:commandRuntime,text:text3});if(result4.ok){return result4}}return{ok:false}};var makeScaffoldCapabilities=(runtime)=>({cleanupGitignore:(rootDirectory)=>{removeHarnessDirectoriesFromGitignore(rootDirectory)},copyToClipboard:(text3,override={})=>copyToClipboard(text3,{...override,env:override.env??runtime.commandEnvironment}),ensureTools:(toolIds,baseline,override,options4)=>ensureToolsInstalledBestEffort(toolIds,baseline,override??makeToolCommandRuntime(runtime.commandEnvironment),options4),inspectRepository:inspectLocalRepository,manifestPaths,readSettings:readRepoSettings,scriptEnvironment:runtime.commandEnvironment,scriptRuntimePath:runtime.scriptRuntimePath,writeAgentSystemPrompt:({outputDirectory,content})=>{nodeFilesystem.write(path19.join(outputDirectory,agentSystemPromptFile),`${content}
|
|
389
|
-
`);return agentSystemPromptFile},writeOutput:writeScaffoldOutput});var scaffoldCapabilitiesLayer=effect(ScaffoldCapabilities,CliRuntimeConfig.pipe(map7(makeScaffoldCapabilities)));import{readFileSync as readFileSync9}from"node:fs";var isMissingFile=(cause)=>cause instanceof Error&&("code"in cause)&&cause.code==="ENOENT";var makeRepositoryCheckCapabilities=(runtime,projectSettings)=>({assessSettings:(rootDirectory)=>projectSettings.read(rootDirectory).pipe(map7(({settings,upgrade})=>({settings:{...settings.baselineVersion===undefined?{}:{baselineVersion:settings.baselineVersion},...settings.cliVersion===undefined?{}:{cliVersion:settings.cliVersion}},upgrade})),catchTag2("ProjectSettingsMissing",()=>succeed6(null)),mapError3((cause)=>new RepositoryCheckOperationFailure({cause,message:"Failed to assess project settings.",operation:"assess-project-settings"}))),checkCli:(tag4)=>promise2(()=>autoUpdateCliIfStale({currentVersion:version2,packageName:name,runtime:{commandEnvironment:runtime.commandEnvironment,npmRegistry:runtime.npmRegistry,...runtime.npmUserAgent===undefined?{}:{npmUserAgent:runtime.npmUserAgent}},tag:tag4})),readTextFile:(filePath)=>try_3({catch:(cause)=>new RepositoryCheckOperationFailure({cause,message:`Failed to read changelog: ${filePath}`,operation:"read-changelog"}),try:()=>readFileSync9(filePath,"utf-8")}).pipe(catchIf2((failure)=>isMissingFile(failure.cause),()=>succeed6(null)))});var repositoryCheckCapabilitiesLayer=effect(RepositoryCheckCapabilities,gen2(function*repositoryCheckCapabilitiesLayer2(){const runtime=yield*CliRuntimeConfig;const projectSettings=yield*ProjectSettings;return makeRepositoryCheckCapabilities(runtime,projectSettings)}));import{createHash as createHash5}from"node:crypto";import{execFileSync as execFileSync4}from"node:child_process";import{copyFileSync,existsSync as existsSync11,mkdirSync as mkdirSync6,mkdtempSync as mkdtempSync2,readFileSync as readFileSync11,renameSync as renameSync2,rmSync as rmSync4,writeFileSync as writeFileSync6}from"node:fs";import{tmpdir as tmpdir5}from"node:os";import path21 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";var BaselineChannel2=Literals(["stable","bundled"]);var BaselineSource2=Literals(["bundled","remote","local","control-plane"]);var ScaffoldArtifactKind=Literals(["manifest","archive"]);class ScaffoldArtifactMetadata extends Class4("ScaffoldArtifactMetadata")(orderedSchemaFields(["kind",ScaffoldArtifactKind],["fileName",String5],["contentType",String5],["url",String5],["sha256",String5],["sizeBytes",optional(Number6)])){}var ScaffoldManagedFileKind=Literals(["agent-prompt","context-plan","handoff","harness","hook","lint-spec","manifest","prompt-spec","projection-receipt","required-tools","script","skill","source-guide","subagent"]);class ScaffoldManagedFileSummary extends Class4("ScaffoldManagedFileSummary")(orderedSchemaFields(["path",String5],["sha256",String5],["kind",ScaffoldManagedFileKind])){}class ScaffoldProvenance extends Class4("ScaffoldProvenance")(orderedSchemaFields(["source",BaselineSource2],["channel",BaselineChannel2],["version",String5],["tag",optional(NullOr(String5))],["commit",optional(NullOr(String5))],["sha256",optional(NullOr(String5))])){}class ScaffoldBaselineManifest extends Class4("ScaffoldBaselineManifest")(orderedSchemaFields(["channel",BaselineChannel2],["version",String5],["tag",optional(NullOr(String5))],["commit",optional(NullOr(String5))],["sha256",optional(NullOr(String5))])){}var CliVersionRange=String5.check(isTrimmed(),isNonEmpty());var EmbeddedBaselineFields=[["channel",Literal2("stable")],["version",NonEmptyString],["tag",NonEmptyString],["commit",NonEmptyString],["sha256",optionalKey2(NullOr(NonEmptyString))],["generatedAt",optionalKey2(NonEmptyString)]];var EmbeddedScaffoldBaselineMetadataV1=Struct(orderedSchemaFields(["schemaVersion",Literal2(1)],...EmbeddedBaselineFields,["compatibility",optionalKey2(Struct({cliVersionRange:CliVersionRange}))]));var EmbeddedScaffoldBaselineMetadataV2=Struct(orderedSchemaFields(["schemaVersion",Literal2(2)],...EmbeddedBaselineFields,["compatibility",Struct({cliVersionRange:CliVersionRange})]));var EmbeddedScaffoldBaselineMetadata=Union2([EmbeddedScaffoldBaselineMetadataV1,EmbeddedScaffoldBaselineMetadataV2]);var PublishedScaffoldBaselineManifestV1=Struct(orderedSchemaFields(["schemaVersion",Literal2(1)],["channel",Literal2("stable")],["version",NonEmptyString],["tag",NonEmptyString],["commit",NonEmptyString],["archive",Literal2("scaffold-baseline.tgz")],["archiveSha256",NonEmptyString]));var PublishedScaffoldBaselineManifestV2=Struct(orderedSchemaFields(["schemaVersion",Literal2(2)],["channel",Literal2("stable")],["version",NonEmptyString],["tag",NonEmptyString],["commit",NonEmptyString],["archive",Literal2("scaffold-baseline.tgz")],["archiveSha256",NonEmptyString],["compatibility",Struct({cliVersionRange:CliVersionRange})]));var PublishedScaffoldBaselineManifest=Union2([PublishedScaffoldBaselineManifestV1,PublishedScaffoldBaselineManifestV2]);var prereleaseIdentifier=String.raw`(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)`;var buildIdentifier=String.raw`[0-9A-Za-z-]+`;var versionPattern=new RegExp(String.raw`^(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)(?:-(?<prerelease>${prereleaseIdentifier}(?:\.${prereleaseIdentifier})*))?(?:\+${buildIdentifier}(?:\.${buildIdentifier})*)?$`,"u");var constraintPattern=new RegExp(String.raw`^(?<operator>>=|<=|>|<|=)?(?<major>\d+)(?:\.(?<minor>\d+)(?:\.(?<patch>\d+)(?:-(?<prerelease>${prereleaseIdentifier}(?:\.${prereleaseIdentifier})*))?(?:\+${buildIdentifier}(?:\.${buildIdentifier})*)?)?)?$`,"u");var numericIdentifierPattern=/^\d+$/u;var parseVersion=(value5)=>{const groups=versionPattern.exec(value5)?.groups;return groups===undefined?null:[Number(groups.major),Number(groups.minor),Number(groups.patch),groups.prerelease?.split(".")??[]]};var comparePrereleaseIdentifiers=(left,right)=>{const leftNumeric=numericIdentifierPattern.test(left);const rightNumeric=numericIdentifierPattern.test(right);if(leftNumeric&&rightNumeric){if(BigInt(left)<BigInt(right)){return-1}return BigInt(left)>BigInt(right)?1:0}if(leftNumeric!==rightNumeric){return leftNumeric?-1:1}if(left<right){return-1}return left>right?1:0};var comparePrereleases=(left,right)=>{if(left.length===0||right.length===0){if(left.length===right.length){return 0}return left.length===0?1:-1}for(let index2=0;index2<Math.max(left.length,right.length);index2+=1){const leftIdentifier=left[index2];const rightIdentifier=right[index2];if(leftIdentifier===undefined||rightIdentifier===undefined){if(leftIdentifier===rightIdentifier){return 0}return leftIdentifier===undefined?-1:1}const compared=comparePrereleaseIdentifiers(leftIdentifier,rightIdentifier);if(compared!==0){return compared}}return 0};var compareCoreVersions=(left,right)=>left[0]-right[0]||left[1]-right[1]||left[2]-right[2];var compareVersions2=(left,right)=>compareCoreVersions(left,right)||comparePrereleases(left[3],right[3]);var nextPartialVersion=(version3,precision)=>precision===1?[version3[0]+1,0,0,[]]:[version3[0],version3[1]+1,0,[]];var constraintPrecision=(groups)=>{if(groups.patch!==undefined){return 3}return groups.minor===undefined?1:2};var parseCompatibilityRange=(range2)=>{const normalized=range2.trim();if(normalized==="*"){return[]}return normalized.split(/\s+/u).map((constraint)=>{const groups=constraintPattern.exec(constraint)?.groups;if(groups===undefined){return null}return{operator:groups.operator??"=",precision:constraintPrecision(groups),target:[Number(groups.major),Number(groups.minor??0),Number(groups.patch??0),groups.prerelease?.split(".")??[]]}})};var satisfiesCliCompatibilityRange=(range2,version3)=>{if(range2.trim()==="*"){return true}const constraints=parseCompatibilityRange(range2);const current=parseVersion(version3);if(current===null||constraints.some((constraint)=>constraint===null)){return false}return constraints.every(({operator,precision,target})=>{const compare5=precision===3?compareVersions2:compareCoreVersions;const compared=compare5(current,target);const next=precision===3?undefined:nextPartialVersion(target,precision);switch(operator){case">=":{return compared>=0}case"<=":{return next===undefined?compared<=0:compare5(current,next)<0}case">":{return next===undefined?compared>0:compare5(current,next)>=0}case"<":{return compared<0}default:{return next===undefined?compared===0:compared>=0&&compare5(current,next)<0}}})};import{existsSync as existsSync10,readFileSync as readFileSync10}from"node:fs";import path20 from"node:path";var readJson=(filePath)=>JSON.parse(readFileSync10(filePath,"utf-8"));var validateBaselineAssets=({root,skills})=>{for(const skill of skills){if(!existsSync10(path20.join(root,skill.sourceDirectory))){throw new Error(`Baseline skill asset missing: ${skill.sourceDirectory}`)}}};var loadBaselineFromDirectory=(root,verifiedSummary)=>{const metadata=readJson(path20.join(root,"baseline.json"));if(metadata.version!==verifiedSummary.resolvedVersion){throw new Error("Baseline metadata does not match the verified version.")}const dataRoot2=path20.join(root,"data");const baseline={dataRoot:dataRoot2,hooks:readJson(path20.join(dataRoot2,"catalog","hooks.json")),lintAssets:validateLintCatalog(readJson(path20.join(dataRoot2,"catalog","lint-assets.json"))),packs:readJson(path20.join(dataRoot2,"catalog","packs.json")),root,skills:readJson(path20.join(dataRoot2,"catalog","skills.json")),skillsRoot:path20.join(root,"skills"),summary:verifiedSummary,tools:readJson(path20.join(dataRoot2,"catalog","tools.json"))};validateBaselineAssets(baseline);return baseline};var defaultMessage3=(message)=>String5.pipe(optionalKey2,withConstructorDefault2(succeed6(message)));var BackofficeAccessRole=Literals(["admin","member"]);var BackofficeAccessStatus=Literals(["invited","active","revoked"]);var BackofficeAccessSummary=Struct({email:String5,role:BackofficeAccessRole,status:BackofficeAccessStatus,userId:optionalKey2(String5),invitedBy:optionalKey2(String5),revokedBy:optionalKey2(String5),invitedAt:optionalKey2(String5),activatedAt:optionalKey2(String5),revokedAt:optionalKey2(String5),createdAt:String5,updatedAt:String5}).annotate({identifier:"BackofficeAccessSummary"});var BackofficeAccessList=Struct({users:ArraySchema(BackofficeAccessSummary)}).annotate({identifier:"BackofficeAccessList"});var BackofficeAccessInviteRequest=Struct({email:String5,role:BackofficeAccessRole}).annotate({identifier:"BackofficeAccessInviteRequest"});var BackofficeOperatorSummary=Struct({operatorId:optionalKey2(String5),email:optionalKey2(String5),name:optionalKey2(String5)}).annotate({identifier:"BackofficeOperatorSummary"});var ObservedRepositorySummary=Struct({id:String5,projectUsageId:String5,remoteHost:optionalKey2(String5),remotePath:optionalKey2(String5),remoteUrl:optionalKey2(String5),branch:optionalKey2(String5),lastCommitSha:optionalKey2(String5),dirty:optionalKey2(Boolean4),gitIdentity:optionalKey2(GitIdentity),firstSeenAt:optionalKey2(IsoDateTimeString),lastSeenAt:optionalKey2(IsoDateTimeString)}).annotate({identifier:"ObservedRepositorySummary"});var ProjectUsageEventSummary=Struct({id:String5,eventId:String5,name:String5,source:String5,counted:Boolean4,cliVersion:String5,baseline:optionalKey2(Struct({channel:optionalKey2(String5),version:optionalKey2(String5)})),occurredAt:IsoDateTimeString,operator:optionalKey2(BackofficeOperatorSummary)}).annotate({identifier:"ProjectUsageEventSummary"});var HarnessReportSummary=Struct({id:String5,projectUsageId:optionalKey2(String5),observedRepositoryId:optionalKey2(String5),title:String5,body:optionalKey2(String5),type:String5,severity:String5,status:String5,githubUrl:optionalKey2(String5),createdAt:IsoDateTimeString,updatedAt:IsoDateTimeString,operator:optionalKey2(BackofficeOperatorSummary)}).annotate({identifier:"HarnessReportSummary"});var ProjectUsageSummary=Struct({id:String5,name:optionalKey2(String5),repositoryCount:Finite,countedEventCount:Finite,openReportCount:Finite,latestCliVersion:optionalKey2(String5),latestBaselineChannel:optionalKey2(String5),latestBaselineVersion:optionalKey2(String5),lastActivityAt:optionalKey2(IsoDateTimeString),initializedBy:optionalKey2(BackofficeOperatorSummary),lastUpdatedBy:optionalKey2(BackofficeOperatorSummary)}).annotate({identifier:"ProjectUsageSummary"});var ProjectUsageList=Struct({projects:ArraySchema(ProjectUsageSummary),reports:ArraySchema(HarnessReportSummary)}).annotate({identifier:"ProjectUsageList"});var ProjectUsageDetail=Struct({project:ProjectUsageSummary,repositories:ArraySchema(ObservedRepositorySummary),events:ArraySchema(ProjectUsageEventSummary),reports:ArraySchema(HarnessReportSummary)}).annotate({identifier:"ProjectUsageDetail"});var BackofficeRepositoryMappingRequest=Struct({observedRepositoryId:String5}).annotate({identifier:"BackofficeRepositoryMappingRequest"});var BackofficeReportUpdateRequest=Struct({status:optionalKey2(HarnessReportStatus),githubUrl:optionalKey2(NullOr(String5))}).annotate({identifier:"BackofficeReportUpdateRequest"});class Unauthorized extends TaggedErrorClass()("@punks/contract/errors/Unauthorized",{message:defaultMessage3("Backoffice session is required.")},{httpApiStatus:401,title:"Unauthorized"}){}class BackofficeRequestRejected extends TaggedErrorClass()("@punks/contract/errors/BackofficeRequestRejected",{message:String5},{httpApiStatus:400,title:"Backoffice Request Rejected"}){}class BackofficePersistenceUnavailable extends TaggedErrorClass()("@punks/contract/errors/BackofficePersistenceUnavailable",{message:defaultMessage3("Backoffice persistence is unavailable.")},{httpApiStatus:503,title:"Backoffice Persistence Unavailable"}){}class BackofficeDependencyUnavailable extends TaggedErrorClass()("@punks/contract/errors/BackofficeDependencyUnavailable",{message:defaultMessage3("Backoffice dependency is unavailable.")},{httpApiStatus:503,title:"Backoffice Dependency Unavailable"}){}var listErrors=[HttpApiDecodeError,Forbidden2,Unauthorized,BackofficePersistenceUnavailable];var rejectedErrors=[HttpApiDecodeError,Forbidden2,Unauthorized,BackofficeRequestRejected,BackofficePersistenceUnavailable];var projectUsageListErrors=[...listErrors,BackofficeDependencyUnavailable];var projectUsageDetailErrors=[...rejectedErrors,BackofficeDependencyUnavailable];var BackofficeApi=exports_HttpApiGroup.make("backoffice").add(exports_HttpApiEndpoint.get("currentAccess","/access/current",{success:BackofficeAccessSummary,error:rejectedErrors}),exports_HttpApiEndpoint.get("accessList","/access-users",{success:BackofficeAccessList,error:listErrors}),exports_HttpApiEndpoint.post("inviteAccess","/access-users",{payload:BackofficeAccessInviteRequest,success:BackofficeAccessSummary,error:rejectedErrors}),exports_HttpApiEndpoint.post("revokeAccess","/access-users/:email/revoke",{params:{email:String5},success:BackofficeAccessSummary,error:rejectedErrors}),exports_HttpApiEndpoint.get("projectUsageList","/project-usages",{success:ProjectUsageList,error:projectUsageListErrors}),exports_HttpApiEndpoint.get("projectUsageDetail","/project-usages/:projectUsageId",{params:{projectUsageId:String5},success:ProjectUsageDetail,error:projectUsageDetailErrors}),exports_HttpApiEndpoint.post("mapRepository","/project-usages/:projectUsageId/repositories",{params:{projectUsageId:String5},payload:BackofficeRepositoryMappingRequest,success:ObservedRepositorySummary,error:rejectedErrors}),exports_HttpApiEndpoint.patch("updateReport","/reports/:reportId",{params:{reportId:String5},payload:BackofficeReportUpdateRequest,success:HarnessReportSummary,error:rejectedErrors})).prefix("/backoffice").annotateMerge(exports_OpenApi.annotations({title:"Backoffice project usage"}));var defaultMessage4=(message)=>String5.pipe(optionalKey2,withConstructorDefault2(succeed6(message)));var HarnessReportType=Literals(["bug","docs","workflow","tooling","other"]);var HarnessReportSeverity=Literals(["low","medium","high"]);var HarnessReportLabel=String5.check(isTrimmed(),isNonEmpty(),isMaxLength(50));var HarnessReportLabels=ArraySchema(HarnessReportLabel).check(isMaxLength(10));var HarnessReportInput=Struct({title:optionalKey2(String5),body:optionalKey2(String5),type:HarnessReportType,severity:HarnessReportSeverity,createdAt:IsoDateTimeString,cliVersion:String5,area:optionalKey2(String5),skillPack:optionalKey2(String5),command:optionalKey2(String5),expected:optionalKey2(String5),actual:optionalKey2(String5),steps:optionalKey2(String5),labels:optionalKey2(HarnessReportLabels),projectUsageId:optionalKey2(String5),repository:optionalKey2(ObservedRepositoryInput),githubUrl:optionalKey2(String5)}).annotate({identifier:"HarnessReportInput"});var HarnessReportCreated=Struct({reportId:String5,status:HarnessReportStatus,githubUrl:optionalKey2(String5),title:optionalKey2(String5),deduplicated:optionalKey2(Boolean4),duplicateOf:optionalKey2(String5)}).annotate({identifier:"HarnessReportCreated"});class HarnessReportRejected extends TaggedErrorClass()("@punks/contract/errors/HarnessReportRejected",{message:String5},{httpApiStatus:400,title:"Harness Report Rejected"}){}class HarnessReportPersistenceUnavailable extends TaggedErrorClass()("@punks/contract/errors/HarnessReportPersistenceUnavailable",{message:defaultMessage4("Harness report persistence is unavailable.")},{httpApiStatus:503,title:"Harness Report Persistence Unavailable"}){}class HarnessReportDependencyUnavailable extends TaggedErrorClass()("@punks/contract/errors/HarnessReportDependencyUnavailable",{message:defaultMessage4("Harness report submission dependency is unavailable.")},{httpApiStatus:503,title:"Harness Report Dependency Unavailable"}){}var ReportsApi=exports_HttpApiGroup.make("reports").add(exports_HttpApiEndpoint.post("submit","/",{payload:HarnessReportInput,success:HarnessReportCreated,error:[HttpApiDecodeError,Forbidden2,HarnessReportRejected,HarnessReportDependencyUnavailable,HarnessReportPersistenceUnavailable]})).prefix("/reports").annotateMerge(exports_OpenApi.annotations({title:"Harness reports"}));var defaultMessage5=(message)=>String5.pipe(optionalKey2,withConstructorDefault2(succeed6(message)));var ProductTelemetryEventName=Literals(["cli.artifact.pull.completed","cli.scaffold.init.completed","cli.scaffold.setup.completed","cli.scaffold.update.applied","cli.harness.report.submitted"]);var TelemetrySource=Literals(["normal","local-dev","ci","debug","test"]);var TelemetryBaselineContext=Struct({channel:optionalKey2(BaselineChannel),version:optionalKey2(String5)}).annotate({identifier:"TelemetryBaselineContext"});var ProductTelemetryEventInput=Struct({eventId:String5,name:ProductTelemetryEventName,occurredAt:IsoDateTimeString,cliVersion:String5,source:TelemetrySource,projectUsageId:optionalKey2(String5),repository:optionalKey2(ObservedRepositoryInput),baseline:optionalKey2(TelemetryBaselineContext)}).annotate({identifier:"ProductTelemetryEventInput"});var ProductTelemetryEventAccepted=Struct({eventId:String5,accepted:Boolean4,counted:Boolean4}).annotate({identifier:"ProductTelemetryEventAccepted"});class TelemetryEventRejected extends TaggedErrorClass()("@punks/contract/errors/TelemetryEventRejected",{message:String5},{httpApiStatus:400,title:"Telemetry Event Rejected"}){}class TelemetryPersistenceUnavailable extends TaggedErrorClass()("@punks/contract/errors/TelemetryPersistenceUnavailable",{message:defaultMessage5("Telemetry persistence is unavailable.")},{httpApiStatus:503,title:"Telemetry Persistence Unavailable"}){}var TelemetryApi=exports_HttpApiGroup.make("telemetry").add(exports_HttpApiEndpoint.post("record","/events",{payload:ProductTelemetryEventInput,success:ProductTelemetryEventAccepted,error:[HttpApiDecodeError,Forbidden2,TelemetryEventRejected,TelemetryPersistenceUnavailable]})).prefix("/telemetry").annotateMerge(exports_OpenApi.annotations({title:"Product telemetry"}));var HealthApi=exports_HttpApiGroup.make("health",{topLevel:true}).add(exports_HttpApiEndpoint.get("healthz","/healthz",{success:exports_HttpApiSchema.NoContent.annotate({description:"Empty health response"}),error:[HttpApiDecodeError,Forbidden2]}));var HarnessApi=exports_HttpApi.make("harness").add(HealthApi,BaselineApi,TelemetryApi,ReportsApi,BackofficeApi).prefix("/api").annotateMerge(exports_OpenApi.annotations({title:"Harness Intelligence Control Plane",summary:"Shared typed contract for Devpunks CLI/backend control-plane calls."}));var ControlPlaneOperation=Literals(["record-product-telemetry","resolve-stable-baseline","submit-harness-report"]);class ControlPlaneRequestFailure extends TaggedErrorClass()("@punks/cli/control-plane/ControlPlaneRequestFailure",{cause:Defect(),operation:ControlPlaneOperation,transport:Boolean4}){}var isHttpTransportFailure=(cause)=>isHttpClientError(cause)&&cause.reason._tag==="TransportError";var normalizeControlPlaneFailure=(operation2,effect2)=>effect2.pipe(catchIf2(isHttpClientError,(cause)=>fail6(new ControlPlaneRequestFailure({cause,operation:operation2,transport:isHttpTransportFailure(cause)}))),catchIf2(isSchemaError,(cause)=>fail6(new ControlPlaneRequestFailure({cause,operation:operation2,transport:false}))));var makeControlPlaneClient=({baseUrl:baseUrl2,headers})=>exports_HttpApiClient.make(HarnessApi,{baseUrl:baseUrl2,...headers===undefined?{}:{transformClient:(client)=>client.pipe(exports_HttpClient.mapRequest(exports_HttpClientRequest.setHeaders(headers)))}});var resolveBaselineMetadata=(options4)=>normalizeControlPlaneFailure("resolve-stable-baseline",gen2(function*requestBaselineMetadata(){const client=yield*makeControlPlaneClient(options4);return yield*client.baseline.resolve({params:{channel:options4.request.channel},query:options4.request.version===undefined?{}:{version:options4.request.version}})}));var recordProductTelemetryEvent=(options4)=>normalizeControlPlaneFailure("record-product-telemetry",gen2(function*sendProductTelemetryEvent(){const client=yield*makeControlPlaneClient(options4);return yield*client.telemetry.record({payload:options4.event})}));var submitHarnessReport=(options4)=>normalizeControlPlaneFailure("submit-harness-report",gen2(function*sendHarnessReport(){const client=yield*makeControlPlaneClient(options4);return yield*client.reports.submit({payload:options4.report})}));var trimTrailingSlashes=(value5)=>value5.trim().replace(/\/+$/u,"");var bundledControlPlaneUrl=({disableBundledUrl=false}={})=>{if(disableBundledUrl){return}const config=JSON.parse(readDataFile("control-plane.json"));return typeof config.defaultUrl==="string"&&config.defaultUrl.trim().length>0?trimTrailingSlashes(config.defaultUrl):undefined};var resolveControlPlaneUrl=(explicitUrl,configuration={})=>{const baseUrl2=explicitUrl?.trim()||configuration.baseUrl?.trim()||bundledControlPlaneUrl(configuration);return baseUrl2===undefined||baseUrl2.length===0?undefined:trimTrailingSlashes(baseUrl2)};class BaselineResolutionFailure extends TaggedErrorClass()("@punks/cli/baseline-resolution/BaselineResolutionFailure",{cause:Defect(),message:String5,operation:Literal2("resolve-stable-baseline"),reason:Literals(["corrupt-artifact","remote-access","unsafe-artifact","invalid-artifact"])}){}import{randomUUID}from"node:crypto";import{execFileSync as execFileSync3}from"node:child_process";var disabledTelemetryConfig={disableBundledUrl:true};var git=(cwd,args2)=>{try{return execFileSync3("git",args2,{cwd,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}};var redactRemote=(remote)=>remote.replace(/\/\/[^/@]+@/u,"//");var safeRemoteParts=(remote)=>{const redacted5=redactRemote(remote);const ssh=/^git@(?<host>[^:]+):(?<path>.+)$/u.exec(redacted5);const sshGroups=ssh?.groups;if(sshGroups!==undefined){return{remoteHost:sshGroups.host,remotePath:sshGroups.path.replace(/\.git$/u,""),remoteUrl:redacted5}}try{const url2=new URL(redacted5);return{remoteHost:url2.hostname,remotePath:url2.pathname.replaceAll(/^\/|\.git$/gu,""),remoteUrl:redacted5}}catch{return{remoteUrl:redacted5}}};var observedRepository=(cwd)=>{const remote=git(cwd,["config","--get","remote.origin.url"]);const commitSha=git(cwd,["rev-parse","HEAD"])??undefined;const status2=git(cwd,["status","--short"]);const name2=git(cwd,["config","--local","--get","user.name"])??undefined;const email=git(cwd,["config","--local","--get","user.email"])??undefined;return{...remote===null?{}:safeRemoteParts(remote),...commitSha===undefined?{}:{commitSha},...status2===null?{}:{dirty:status2.length>0},...name2===undefined&&email===undefined?{}:{gitIdentity:{...name2===undefined?{}:{name:name2},...email===undefined?{}:{email}}}}};var isLocalControlPlaneUrl=(value5)=>{if(value5===undefined||value5.trim().length===0){return false}try{const{hostname}=new URL(value5);return hostname==="localhost"||hostname.endsWith(".localhost")||hostname.startsWith("127.")||hostname==="0.0.0.0"||hostname==="::1"||hostname==="[::1]"}catch{return value5.includes("localhost")||value5.includes(".localhost")}};var telemetrySource=(configuration={})=>{if(configuration.telemetrySource==="ci"){return"ci"}if(configuration.telemetrySource==="debug"){return"debug"}if(configuration.telemetrySource==="test"){return"test"}if(isLocalControlPlaneUrl(configuration.baseUrl)){return"local-dev"}return"normal"};var makeProductTelemetryEvent=({name:name2,cwd,baseline,controlPlaneUrl,configuration})=>({cliVersion:version2,eventId:randomUUID(),name:name2,occurredAt:new Date().toISOString(),repository:observedRepository(cwd),source:telemetrySource(configuration??(controlPlaneUrl===undefined?{}:{baseUrl:controlPlaneUrl})),...baseline===undefined?{}:{baseline}});var telemetryBaseUrl=(controlPlaneUrl,configuration=disabledTelemetryConfig)=>resolveControlPlaneUrl(controlPlaneUrl,configuration);var submitProductTelemetryEffect=(event,options4={})=>{const baseUrl2=telemetryBaseUrl(options4.controlPlaneUrl,options4.configuration);if(baseUrl2===undefined){return void_3}return recordProductTelemetryEvent({baseUrl:baseUrl2,event}).pipe(catchTags2({"@punks/cli/control-plane/ControlPlaneRequestFailure":()=>void_3,"@punks/contract/errors/Forbidden":()=>void_3,"@punks/contract/errors/TelemetryEventRejected":()=>void_3,"@punks/contract/errors/TelemetryPersistenceUnavailable":()=>void_3,HttpApiDecodeError:()=>void_3}),asVoid2)};var telemetryTransportEnabled=(controlPlaneUrl,configuration)=>telemetryBaseUrl(controlPlaneUrl,configuration)!==undefined;var makeCliEvent=(name2,options4={})=>makeProductTelemetryEvent({cwd:options4.cwd??process.cwd(),name:name2,...options4.baseline===undefined?{}:{baseline:options4.baseline},...options4.controlPlaneUrl===undefined?{}:{controlPlaneUrl:options4.controlPlaneUrl},...options4.configuration===undefined?{}:{configuration:options4.configuration}});var submitCliEventEffect=(name2,options4={})=>telemetryTransportEnabled(options4.controlPlaneUrl,options4.configuration)?submitProductTelemetryEffect(makeCliEvent(name2,options4),options4):void_3;var assetArchiveName="scaffold-baseline.tgz";var cachedArtifactName=".verified-artifact.tgz";var maximumArchiveRedirects=20;var archiveRedirectStatuses=new Set([301,302,303,307,308]);var bundledFallbackAvailability=new Set(["authority-unconfigured","network","unavailable-status"]);var BaselineArchiveEndpointFailure=Union2([BaselineNotFound,BaselineAuthorityFailure,BaselineIntegrityFailure,BaselineUnavailable]);var isBaselineReleaseTag=(tag4)=>tag4.startsWith("baseline/stable/")&&!/^v\d+\.\d+\.\d+(?:$|-)/u.test(tag4);var normalizeBaselineRequest=(value5)=>{const requested=value5?.trim();if(requested===undefined||requested.length===0||requested==="stable"){return{channel:"stable"}}return requested==="bundled"?{channel:"bundled"}:{channel:"stable",version:requested}};var sha256File=(filePath)=>createHash5("sha256").update(readFileSync11(filePath)).digest("hex");var isSafeTarPath=(entry)=>entry.length>0&&!path21.isAbsolute(entry)&&!entry.split("/").includes("..");var isSafePathSegment=(value5)=>value5.length>0&&value5!=="."&&value5!==".."&&!value5.includes("/")&&!value5.includes("\\");var integrityFailure=(resolution,message,actualDigest)=>new BaselineIntegrityFailure({...actualDigest===undefined?{}:{actualDigest},expectedDigest:resolution.digest,message,request:resolution.requested,resolvedVersion:resolution.resolvedVersion});var verifyEmbeddedBaselineMetadata=(root,resolution,retrieval)=>{let metadata;try{metadata=decodeUnknownSync2(EmbeddedScaffoldBaselineMetadata)(JSON.parse(readFileSync11(path21.join(root,"baseline.json"),"utf-8")))}catch{throw integrityFailure(resolution,`${retrieval} baseline metadata is invalid.`)}if(metadata.channel!==resolution.requested.channel||metadata.version!==resolution.resolvedVersion||resolution.provenance!==`release:${resolution.resolvedVersion}`||metadata.tag!==`baseline/stable/${resolution.resolvedVersion}`||metadata.sha256!==undefined&&metadata.sha256!==null&&metadata.sha256!==resolution.digest||metadata.compatibility!==undefined&&metadata.compatibility.cliVersionRange!==resolution.compatibility.cliVersionRange){throw integrityFailure(resolution,`${retrieval} baseline metadata disagrees with selected authority.`)}};class BaselineArchiveUnavailableError extends Error{name="BaselineArchiveUnavailableError"}var baselineFailureMessage=(cause)=>{if(cause instanceof ControlPlaneRequestFailure||isTimeoutError2(cause)){return"The baseline authority request failed."}if(cause instanceof Error&&typeof cause.message==="string"&&cause.message.trim().length>0){return cause.message}return"Baseline resolution failed."};var parseArchiveUrl=(value5)=>{let url2;try{url2=new URL(value5)}catch{throw new Error("Authority returned an invalid baseline archive URL.")}if(url2.protocol!=="http:"&&url2.protocol!=="https:"){throw new Error("Authority returned an invalid baseline archive URL.")}return url2};var fetchArchiveResponse=async(url2,signal,redirects=0)=>{const response=await fetch(url2,{redirect:"manual",signal}).catch((error2)=>{throw new BaselineArchiveUnavailableError(error2 instanceof Error?error2.message:"Failed to download baseline artifact.",{cause:error2})});if(!archiveRedirectStatuses.has(response.status)){return response}const location2=response.headers.get("location");if(location2===null||redirects>=maximumArchiveRedirects){throw new Error("Authority returned an invalid baseline archive URL.")}const redirectedUrl=parseArchiveUrl(location2).toString();return fetchArchiveResponse(redirectedUrl,signal,redirects+1)};var decodeArchiveEndpointFailure=async(response)=>{const body=await response.json().catch(()=>null);if(body===null){return}try{return decodeUnknownSync2(BaselineArchiveEndpointFailure)(body)}catch{return}};var bundledFallbackEligible=(cause)=>cause instanceof BaselineArchiveUnavailableError||isTimeoutError2(cause)||cause instanceof BaselineUnavailable&&bundledFallbackAvailability.has(cause.availability)||cause instanceof ControlPlaneRequestFailure&&cause.transport;var classifyFailure=(cause)=>{let reason="invalid-artifact";if(cause instanceof BaselineIntegrityFailure){reason="corrupt-artifact"}else if(bundledFallbackEligible(cause)){reason="remote-access"}return new BaselineResolutionFailure({cause,message:baselineFailureMessage(cause),operation:"resolve-stable-baseline",reason})};var extractSafeTgz=(archivePath,targetDirectory)=>{const entries3=execFileSync4("tar",["-tzf",archivePath],{encoding:"utf-8"}).split(/\r?\n/u).filter(Boolean);const unsafe=entries3.find((entry)=>!isSafeTarPath(entry));if(unsafe!==undefined){throw new Error(`Unsafe path in baseline archive: ${unsafe}`)}mkdirSync6(targetDirectory,{recursive:true});execFileSync4("tar",["-xzf",archivePath,"-C",targetDirectory],{stdio:"ignore"})};var download=async(url2,targetPath,timeoutMs)=>{const controller=new AbortController;const timeout3=setTimeout(()=>controller.abort(),timeoutMs);try{const response=await fetchArchiveResponse(parseArchiveUrl(url2).toString(),controller.signal);if(!response.ok){const endpointFailure=await decodeArchiveEndpointFailure(response);if(endpointFailure!==undefined){if(endpointFailure instanceof BaselineUnavailable&&response.status!==503){throw new Error(`Failed to download baseline artifact: ${response.status}`)}throw endpointFailure}if(response.status!==503){throw new Error(`Failed to download baseline artifact: ${response.status}`)}throw new BaselineArchiveUnavailableError(`Failed to download baseline artifact: ${response.status}`)}const bytes=await response.arrayBuffer().catch((error2)=>{throw new BaselineArchiveUnavailableError(error2 instanceof Error?error2.message:"Failed to read baseline artifact response.",{cause:error2})});writeFileSync6(targetPath,new Uint8Array(bytes))}finally{clearTimeout(timeout3)}};var summaryMetadata=(resolution,retrieval)=>({authoritySource:resolution.source,channel:resolution.requested.channel,commit:null,compatibility:resolution.compatibility,digest:resolution.digest,provenance:resolution.provenance,requested:resolution.requested,resolvedVersion:resolution.resolvedVersion,retrieval,sha256:resolution.digest,source:"remote",tag:isBaselineReleaseTag(resolution.provenance)?resolution.provenance:null,version:resolution.resolvedVersion});var decodeLocalCompatibility=(metadata)=>{if(!Object.hasOwn(metadata,"compatibility")){return"*"}const{compatibility}=metadata;if(typeof compatibility!=="object"||compatibility===null||!("cliVersionRange"in compatibility)){throw new Error("Local baseline metadata has invalid CLI compatibility.")}const{cliVersionRange}=compatibility;if(typeof cliVersionRange!=="string"||cliVersionRange.trim().length===0){throw new Error("Local baseline metadata has invalid CLI compatibility.")}return cliVersionRange};var resolveLocalBaseline=(url2,request3)=>{if(!url2.startsWith("file://")){return null}const root=fileURLToPath2(new URL(url2));const metadata=JSON.parse(readFileSync11(path21.join(root,"baseline.json"),"utf-8"));if(typeof metadata.version!=="string"||metadata.version.length===0){throw new Error("Local baseline metadata has no version.")}const cliVersionRange=decodeLocalCompatibility(metadata);if(metadata.tag!==undefined&&metadata.tag!==null&&typeof metadata.tag!=="string"){throw new Error("Local baseline metadata has an invalid tag.")}if(metadata.commit!==undefined&&metadata.commit!==null&&typeof metadata.commit!=="string"){throw new Error("Local baseline metadata has an invalid commit.")}const tag4=metadata.tag??null;const commit=metadata.commit??null;const digest2=digestContentRoots([{prefix:"baseline",root}]);if(request3.version!==undefined&&request3.version!==metadata.version){throw new BaselineIntegrityFailure({expectedDigest:digest2,message:"Local baseline metadata does not match the exact requested version.",request:request3,resolvedVersion:metadata.version})}if(!satisfiesCliCompatibilityRange(cliVersionRange,version2)){throw new BaselineIntegrityFailure({expectedDigest:digest2,message:`Local baseline requires CLI ${cliVersionRange}; current CLI is ${version2}.`,request:request3,resolvedVersion:metadata.version})}return loadBaselineFromDirectory(root,{authoritySource:"local",channel:request3.channel,commit,compatibility:{cliVersionRange},digest:digest2,provenance:tag4??"local-file",requested:request3,resolvedVersion:metadata.version,retrieval:"available",sha256:digest2,source:"local",tag:tag4,version:metadata.version})};var loadExactCachedBaseline=(targetDirectory,resolution)=>{if(!existsSync11(targetDirectory)){return{baseline:null}}try{if(!existsSync11(path21.join(targetDirectory,"baseline.json"))){throw integrityFailure(resolution,"Cached baseline is incomplete.")}const artifactPath=path21.join(targetDirectory,cachedArtifactName);if(!existsSync11(artifactPath)||sha256File(artifactPath)!==resolution.digest){throw integrityFailure(resolution,"Cached artifact does not match authority.")}const verificationDirectory=mkdtempSync2(path21.join(tmpdir5(),"punks-cache-verify-"));try{extractSafeTgz(artifactPath,verificationDirectory);const expected=digestContentRoots([{prefix:"baseline",root:verificationDirectory}]);const actual=digestContentRoots([{include:(relativePath)=>relativePath!==cachedArtifactName,prefix:"baseline",root:targetDirectory}]);if(actual!==expected){throw integrityFailure(resolution,"Cached baseline content changed.")}verifyEmbeddedBaselineMetadata(targetDirectory,resolution,"Cached")}finally{rmSync4(verificationDirectory,{force:true,recursive:true})}return{baseline:loadBaselineFromDirectory(targetDirectory,summaryMetadata(resolution,"cached"))}}catch(error2){rmSync4(targetDirectory,{force:true,recursive:true});return{baseline:null,integrityFailure:error2 instanceof BaselineIntegrityFailure?error2:integrityFailure(resolution,"Cached baseline failed integrity verification.")}}};var materializeBaseline=async(resolution,refresh,timeoutMs,cacheDirectory)=>{if(resolution.source!=="control-plane"){throw integrityFailure(resolution,"Baseline authority source must be control-plane.")}if(!isSafePathSegment(resolution.resolvedVersion)){throw integrityFailure(resolution,"Authority returned an unsafe baseline version.")}parseArchiveUrl(resolution.archive.url);if(!satisfiesCliCompatibilityRange(resolution.compatibility.cliVersionRange,version2)){throw integrityFailure(resolution,`Baseline requires CLI ${resolution.compatibility.cliVersionRange}; current CLI is ${version2}.`)}const targetDirectory=path21.join(cacheDirectory,"devpunks","baselines","verified",resolution.resolvedVersion);const targetParentDirectory=path21.dirname(targetDirectory);let cacheIntegrityFailure;if(!refresh){const cached3=loadExactCachedBaseline(targetDirectory,resolution);if(cached3.baseline!==null){return{artifactPulled:false,baseline:cached3.baseline}}cacheIntegrityFailure=cached3.integrityFailure}mkdirSync6(targetParentDirectory,{recursive:true});const temporaryDirectory=mkdtempSync2(path21.join(targetParentDirectory,".punks-verified-baseline-"));try{const archivePath=path21.join(temporaryDirectory,assetArchiveName);await download(resolution.archive.url,archivePath,timeoutMs).catch((error2)=>{if(cacheIntegrityFailure!==undefined&&bundledFallbackEligible(error2)){throw cacheIntegrityFailure}if(error2 instanceof Error){throw error2}throw new Error("Baseline archive download failed.")});const actualDigest=sha256File(archivePath);if(actualDigest!==resolution.digest||actualDigest!==resolution.archive.sha256){throw integrityFailure(resolution,"Downloaded baseline archive checksum mismatch.",actualDigest)}const extractedDirectory=path21.join(temporaryDirectory,"extracted");extractSafeTgz(archivePath,extractedDirectory);verifyEmbeddedBaselineMetadata(extractedDirectory,resolution,"Downloaded");rmSync4(targetDirectory,{force:true,recursive:true});renameSync2(extractedDirectory,targetDirectory);copyFileSync(archivePath,path21.join(targetDirectory,cachedArtifactName));return{artifactPulled:true,baseline:loadBaselineFromDirectory(targetDirectory,summaryMetadata(resolution,"retrieved"))}}finally{rmSync4(temporaryDirectory,{force:true,recursive:true})}};var resolveBaseline=(options4)=>gen2(function*executeBaselineResolution(){const selectedBaseline=options4.baseline??options4.configuration.release.baseline;const request3=normalizeBaselineRequest(selectedBaseline);const isImplicitStable=selectedBaseline===undefined;if(request3.channel==="bundled"){return yield*try_3({catch:classifyFailure,try:resolveVerifiedBundledBaseline})}const local=yield*try_3({catch:classifyFailure,try:()=>options4.configuration.release.baselineUrl===undefined?null:resolveLocalBaseline(options4.configuration.release.baselineUrl,request3)});if(local!==null){return local}return yield*gen2(function*resolveRemoteBaseline(){const baseUrl2=resolveControlPlaneUrl(undefined,options4.configuration.controlPlane);if(baseUrl2===undefined){return yield*fail6(classifyFailure(new BaselineUnavailable({availability:"authority-unconfigured",message:"The control plane URL is unavailable; baseline authority cannot be resolved.",request:request3})))}const timeoutMs=options4.timeoutMs??1500;const resolution=yield*resolveBaselineMetadata({baseUrl:baseUrl2,request:request3}).pipe(timeout2(timeoutMs),mapError3(classifyFailure));const materialized=yield*tryPromise2({catch:classifyFailure,try:()=>materializeBaseline(resolution,options4.refresh??options4.configuration.release.refreshBaseline,timeoutMs,options4.configuration.release.cacheDirectory)});if(materialized.artifactPulled){yield*submitCliEventEffect("cli.artifact.pull.completed",{...options4.cwd===undefined?{}:{cwd:options4.cwd},baseline:{channel:materialized.baseline.summary.channel,version:materialized.baseline.summary.version},configuration:options4.configuration.controlPlane})}return materialized.baseline}).pipe(catchTag2("@punks/cli/baseline-resolution/BaselineResolutionFailure",(failure)=>isImplicitStable&&bundledFallbackEligible(failure.cause)?try_3({catch:classifyFailure,try:()=>resolveVerifiedBundledBaseline(request3,"fallback")}):fail6(failure)))});var baselineResolveOptions=(baseline,refresh,cwd,configuration)=>{const selectedBaseline=isSome2(baseline)?baseline.value:configuration.release.baseline;return{...selectedBaseline===undefined?{}:{baseline:selectedBaseline},configuration,refresh:refresh||configuration.release.refreshBaseline===true,...cwd===undefined?{}:{cwd}}};import path22 from"node:path";var baselineToolIds2=["agent-browser","opensrc","portless","skills"];var requiredToolsForSkills2=(skillIds,baseline=bundledBaseline)=>[...new Set([...baselineToolIds2,...baseline.skills.filter((skill)=>skillIds.includes(skill.id)).flatMap((skill)=>skill.requiresTools)])].toSorted();var agentSystemPromptFile2=".devpunks/AGENT-SYSTEM-PROMPT.md";var selectedSkills=(finalPacks,baseline)=>[...new Set(finalPacks.flatMap((packId)=>skillsForPack(packId,baseline)))].toSorted();var runScaffold=({scanDirectory,emitJson=false,repoShapeMode="auto",interaction,outputDirectory,displayOutputDirectory,ensureTools:ensureTools2=true,baseline=bundledBaseline,assumeYes=false,toolStdio=emitJson?"ignore":"inherit",toolRuntime,clipboardRuntime,configuration={disableBundledUrl:true},scriptRuntimePath:scriptRuntimePath2,scriptEnvironment})=>gen2(function*executeScaffold(){const capabilities=yield*ScaffoldCapabilities;const projectSettings=yield*ProjectSettings;const effectiveScriptRuntimePath=scriptRuntimePath2??capabilities.scriptRuntimePath;const effectiveScriptEnvironment=scriptEnvironment??capabilities.scriptEnvironment;const baseRequiredTools=requiredToolsForSkills2([],baseline);let toolBootstrapStatuses=[];const resolvedOutputDirectory=path22.resolve(outputDirectory??scanDirectory);yield*interaction.emit({_tag:"SetupStarted"});if(ensureTools2&&baseRequiredTools.length>0){yield*interaction.emit({_tag:"ToolCheck",phase:"base",toolIds:baseRequiredTools});toolBootstrapStatuses=capabilities.ensureTools(baseRequiredTools,baseline,toolRuntime,{stdio:toolStdio});yield*interaction.emit({_tag:"ToolBootstrap",phase:"base",statuses:toolBootstrapStatuses})}const{detection,packs:resolved}=yield*capabilities.inspectRepository({baseline,repoShapeMode,rootDirectory:scanDirectory});yield*interaction.emit({_tag:"Detection",detection});yield*interaction.emit({_tag:"ResolvedPacks",baseline,resolved});let additions=[];let removals=[];let finalPacks=resolved.preselectedPacks;const selectPacksInteractively=()=>gen2(function*selectScaffoldPacks(){while(true){const shouldEditSelection=!(yield*interaction.keepPrefilledSelection());additions=[];if(shouldEditSelection&&resolved.optionalPacks.length>0){additions=yield*interaction.selectPacks({allowed:resolved.optionalPacks,kind:"add"})}const removablePacks=[...new Set([...resolved.preselectedPacks,...additions])].filter((packId)=>canRemovePack(resolved,packId)).toSorted();removals=[];if(shouldEditSelection&&removablePacks.length>0){removals=yield*interaction.selectPacks({allowed:removablePacks,kind:"remove"})}finalPacks=finalizePackSelection(resolved,additions,removals);if(shouldEditSelection){yield*interaction.emit({_tag:"SelectionPreview",addedPacks:additions,baseline,finalPacks,outputDirectory:resolvedOutputDirectory,preselectedPacks:resolved.preselectedPacks,removedPacks:removals})}if(yield*interaction.confirmSelection()){return}yield*interaction.emit({_tag:"SelectionReopened"})}});yield*assumeYes?interaction.emit({_tag:"SelectionAccepted"}):selectPacksInteractively();const skillIds=selectedSkills(finalPacks,baseline);const requiredTools=requiredToolsForSkills2(skillIds,baseline);const checkedToolIds=new Set(toolBootstrapStatuses.map((entry)=>entry.toolId));const remainingRequiredTools=requiredTools.filter((toolId)=>!checkedToolIds.has(toolId));if(ensureTools2&&remainingRequiredTools.length>0){yield*interaction.emit({_tag:"ToolCheck",phase:"selected",toolIds:remainingRequiredTools});const remainingToolBootstrapStatuses=capabilities.ensureTools(remainingRequiredTools,baseline,toolRuntime,{stdio:toolStdio});toolBootstrapStatuses=[...toolBootstrapStatuses,...remainingToolBootstrapStatuses].toSorted((left,right)=>left.toolId.localeCompare(right.toolId));yield*interaction.emit({_tag:"ToolBootstrap",phase:"selected",statuses:remainingToolBootstrapStatuses})}const contextPlan=yield*compileScaffoldContextPlan({baseline,detection,finalPacks,preserveExistingSubagentManifest:true,scanDirectory}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})));const settingsExist=yield*projectSettings.read(resolvedOutputDirectory).pipe(as2(true),catchTag2("ProjectSettingsMissing",()=>succeed6(false)),mapError3((cause)=>new CliValidationError({cause,message:cause.message})));const scaffoldOutput=yield*capabilities.writeOutput({baseline,contextPlan,detection,...displayOutputDirectory===undefined?{}:{displayOutputDirectory},outputDirectory:resolvedOutputDirectory,repoShapeMode,scanDirectory,scriptEnvironment:effectiveScriptEnvironment,scriptRuntimePath:effectiveScriptRuntimePath,toolBootstrapStatuses}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})));if(scaffoldOutput.projectionReceiptFile===null||scaffoldOutput.projectionStatus===null){return yield*new CliValidationError({message:"Scaffold output did not produce harness projection evidence."})}capabilities.cleanupGitignore(scaffoldOutput.outputDirectory);yield*gen2(function*updateProjectSettings(){if(!settingsExist){return}yield*projectSettings.write(scaffoldOutput.outputDirectory,{_tag:"ScaffoldChange",baselineVersion:baseline.summary.version,cliVersion:version2,requiredTools})}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})));const renderedAgentSystemPrompt=formatAgentHandoffSummary({addedPacks:additions,agentHandoffFile:scaffoldOutput.agentHandoffFile,agentSystemPromptFile:agentSystemPromptFile2,baseline:baseline.summary,contextPlan:scaffoldOutput.contextPlan,contextPlanFile:scaffoldOutput.contextPlanFile,cwd:scanDirectory,defaultPacks:resolved.defaultPacks,detectedLanguages:detection.detectedLanguages,detectedPacks:resolved.detectedPacks,detectedTechnologies:detection.detectedTechnologies,finalPacks,generatedFiles:[...scaffoldOutput.generatedFiles,agentSystemPromptFile2],harnessFiles:scaffoldOutput.harnessFiles,hiddenOutputDirectories:scaffoldOutput.hiddenOutputDirectories,hookFiles:scaffoldOutput.hookFiles,languagePacks:resolved.languagePacks,lintAssets:scaffoldOutput.lintAssets,lintSpecFiles:scaffoldOutput.lintSpecFiles,managedFiles:scaffoldOutput.managedFiles,manifests:capabilities.manifestPaths(detection),monorepo:detection.monorepo,monorepoSignals:detection.monorepoSignals,opensrcReferences:scaffoldOutput.opensrcReferences,outputDirectory:scaffoldOutput.outputDirectory,projectionReceiptFile:scaffoldOutput.projectionReceiptFile,projectionStatus:scaffoldOutput.projectionStatus,promptOutputs:scaffoldOutput.promptOutputs,promptSpecFiles:scaffoldOutput.promptSpecFiles,promptSpecs:scaffoldOutput.promptSpecs,removedPacks:removals,repoShapeMode,scaffoldManifestFile:scaffoldOutput.scaffoldManifestFile,scriptFiles:scaffoldOutput.scriptFiles,skillFiles:scaffoldOutput.skillFiles,sourceGuideFiles:scaffoldOutput.sourceGuideFiles,sourceGuides:scaffoldOutput.sourceGuides,subagentFiles:scaffoldOutput.subagentFiles,subagentManifestSpec:scaffoldOutput.subagentManifestSpec,surfacePacks:resolved.surfacePacks,toolBootstrapStatuses});const writtenAgentSystemPromptFile=capabilities.writeAgentSystemPrompt({content:renderedAgentSystemPrompt,outputDirectory:scaffoldOutput.outputDirectory});const result4={addedPacks:additions,agentHandoffFile:scaffoldOutput.agentHandoffFile,agentSystemPromptFile:writtenAgentSystemPromptFile,baseline:baseline.summary,contextPlan:scaffoldOutput.contextPlan,contextPlanFile:scaffoldOutput.contextPlanFile,cwd:scanDirectory,defaultPacks:resolved.defaultPacks,detectedLanguages:detection.detectedLanguages,detectedPacks:resolved.detectedPacks,detectedTechnologies:detection.detectedTechnologies,finalPacks,generatedFiles:[...scaffoldOutput.generatedFiles,writtenAgentSystemPromptFile],harnessFiles:scaffoldOutput.harnessFiles,hiddenOutputDirectories:scaffoldOutput.hiddenOutputDirectories,hookFiles:scaffoldOutput.hookFiles,languagePacks:resolved.languagePacks,lintAssets:scaffoldOutput.lintAssets,lintSpecFiles:scaffoldOutput.lintSpecFiles,managedFiles:scaffoldOutput.managedFiles,manifests:capabilities.manifestPaths(detection),monorepo:detection.monorepo,monorepoSignals:detection.monorepoSignals,opensrcReferences:scaffoldOutput.opensrcReferences,outputDirectory:scaffoldOutput.outputDirectory,projectionReceiptFile:scaffoldOutput.projectionReceiptFile,projectionStatus:scaffoldOutput.projectionStatus,promptOutputs:scaffoldOutput.promptOutputs,promptSpecFiles:scaffoldOutput.promptSpecFiles,promptSpecs:scaffoldOutput.promptSpecs,removedPacks:removals,repoShapeMode,scaffoldManifestFile:scaffoldOutput.scaffoldManifestFile,scriptFiles:scaffoldOutput.scriptFiles,skillFiles:scaffoldOutput.skillFiles,sourceGuideFiles:scaffoldOutput.sourceGuideFiles,sourceGuides:scaffoldOutput.sourceGuides,subagentFiles:scaffoldOutput.subagentFiles,subagentManifestSpec:scaffoldOutput.subagentManifestSpec,surfacePacks:resolved.surfacePacks,toolBootstrapStatuses};const clipboardResult=capabilities.copyToClipboard(renderedAgentSystemPrompt,{...clipboardRuntime,env:clipboardRuntime?.env??effectiveScriptEnvironment});yield*interaction.emit({_tag:"SetupComplete",baseline,clipboard:clipboardResult,emitJson,result:result4});yield*submitCliEventEffect("cli.scaffold.setup.completed",{baseline:{version:baseline.summary.version},configuration,cwd:scanDirectory});return result4});import{cpSync as cpSync2,existsSync as existsSync12,statSync as statSync2,mkdirSync as mkdirSync7,readFileSync as readFileSync12,readdirSync as readdirSync5,rmSync as rmSync5,symlinkSync as symlinkSync2,writeFileSync as writeFileSync7}from"node:fs";import path23 from"node:path";var nativeTypeScriptCompilerCommand=`node --input-type=module -e "await import(new URL('./bin/tsc', import.meta.resolve('@typescript/native/package.json')))" -- tsc`;var wikiFile=(path23,content)=>Object.fromEntries([["path",path23],["content",content]]);var tanstackReplacementPaths=new Set(["package.json",".gitignore","next.config.mjs","postcss.config.mjs","tsconfig.json","src/app/global.css","src/app/layout.tsx","src/app/(home)/layout.tsx","src/app/(home)/page.tsx","src/app/docs/layout.tsx","src/app/docs/[[...slug]]/page.tsx","src/app/og/docs/[...slug]/route.tsx","src/app/api/search/route.ts","src/lib/source.ts"]);var makeTanstackStartWikiFiles=()=>[{content:`{
|
|
389
|
+
`);return agentSystemPromptFile},writeOutput:writeScaffoldOutput});var scaffoldCapabilitiesLayer=effect(ScaffoldCapabilities,CliRuntimeConfig.pipe(map7(makeScaffoldCapabilities)));import{readFileSync as readFileSync9}from"node:fs";var isMissingFile=(cause)=>cause instanceof Error&&("code"in cause)&&cause.code==="ENOENT";var makeRepositoryCheckCapabilities=(runtime,projectSettings)=>({assessSettings:(rootDirectory)=>projectSettings.read(rootDirectory).pipe(map7(({settings,upgrade})=>({settings:{...settings.baselineVersion===undefined?{}:{baselineVersion:settings.baselineVersion},...settings.cliVersion===undefined?{}:{cliVersion:settings.cliVersion}},upgrade})),catchTag2("ProjectSettingsMissing",()=>succeed6(null)),mapError3((cause)=>new RepositoryCheckOperationFailure({cause,message:"Failed to assess project settings.",operation:"assess-project-settings"}))),checkCli:(tag4)=>promise2(()=>autoUpdateCliIfStale({currentVersion:version2,packageName:name,runtime:{commandEnvironment:runtime.commandEnvironment,npmRegistry:runtime.npmRegistry,...runtime.npmUserAgent===undefined?{}:{npmUserAgent:runtime.npmUserAgent}},tag:tag4})),readTextFile:(filePath)=>try_3({catch:(cause)=>new RepositoryCheckOperationFailure({cause,message:`Failed to read changelog: ${filePath}`,operation:"read-changelog"}),try:()=>readFileSync9(filePath,"utf-8")}).pipe(catchIf2((failure)=>isMissingFile(failure.cause),()=>succeed6(null)))});var repositoryCheckCapabilitiesLayer=effect(RepositoryCheckCapabilities,gen2(function*repositoryCheckCapabilitiesLayer2(){const runtime=yield*CliRuntimeConfig;const projectSettings=yield*ProjectSettings;return makeRepositoryCheckCapabilities(runtime,projectSettings)}));import{createHash as createHash5}from"node:crypto";import{execFileSync as execFileSync4}from"node:child_process";import{copyFileSync,existsSync as existsSync11,mkdirSync as mkdirSync6,mkdtempSync as mkdtempSync2,readFileSync as readFileSync11,renameSync as renameSync2,rmSync as rmSync4,writeFileSync as writeFileSync6}from"node:fs";import{tmpdir as tmpdir5}from"node:os";import path21 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";var BaselineChannel2=Literals(["stable","bundled"]);var BaselineSource2=Literals(["bundled","remote","local","control-plane"]);var ScaffoldArtifactKind=Literals(["manifest","archive"]);class ScaffoldArtifactMetadata extends Class4("ScaffoldArtifactMetadata")(orderedSchemaFields(["kind",ScaffoldArtifactKind],["fileName",String5],["contentType",String5],["url",String5],["sha256",String5],["sizeBytes",optional(Number6)])){}var ScaffoldManagedFileKind=Literals(["agent-prompt","context-plan","handoff","harness","hook","lint-spec","manifest","prompt-spec","projection-receipt","required-tools","script","skill","source-guide","subagent"]);class ScaffoldManagedFileSummary extends Class4("ScaffoldManagedFileSummary")(orderedSchemaFields(["path",String5],["sha256",String5],["kind",ScaffoldManagedFileKind])){}class ScaffoldProvenance extends Class4("ScaffoldProvenance")(orderedSchemaFields(["source",BaselineSource2],["channel",BaselineChannel2],["version",String5],["tag",optional(NullOr(String5))],["commit",optional(NullOr(String5))],["sha256",optional(NullOr(String5))])){}class ScaffoldBaselineManifest extends Class4("ScaffoldBaselineManifest")(orderedSchemaFields(["channel",BaselineChannel2],["version",String5],["tag",optional(NullOr(String5))],["commit",optional(NullOr(String5))],["sha256",optional(NullOr(String5))])){}var CliVersionRange=String5.check(isTrimmed(),isNonEmpty());var EmbeddedBaselineFields=[["channel",Literal2("stable")],["version",NonEmptyString],["tag",NonEmptyString],["commit",NonEmptyString],["sha256",optionalKey2(NullOr(NonEmptyString))],["generatedAt",optionalKey2(NonEmptyString)]];var EmbeddedScaffoldBaselineMetadataV1=Struct(orderedSchemaFields(["schemaVersion",Literal2(1)],...EmbeddedBaselineFields,["compatibility",optionalKey2(Struct({cliVersionRange:CliVersionRange}))]));var EmbeddedScaffoldBaselineMetadataV2=Struct(orderedSchemaFields(["schemaVersion",Literal2(2)],...EmbeddedBaselineFields,["compatibility",Struct({cliVersionRange:CliVersionRange})]));var EmbeddedScaffoldBaselineMetadata=Union2([EmbeddedScaffoldBaselineMetadataV1,EmbeddedScaffoldBaselineMetadataV2]);var PublishedScaffoldBaselineManifestV1=Struct(orderedSchemaFields(["schemaVersion",Literal2(1)],["channel",Literal2("stable")],["version",NonEmptyString],["tag",NonEmptyString],["commit",NonEmptyString],["archive",Literal2("scaffold-baseline.tgz")],["archiveSha256",NonEmptyString]));var PublishedScaffoldBaselineManifestV2=Struct(orderedSchemaFields(["schemaVersion",Literal2(2)],["channel",Literal2("stable")],["version",NonEmptyString],["tag",NonEmptyString],["commit",NonEmptyString],["archive",Literal2("scaffold-baseline.tgz")],["archiveSha256",NonEmptyString],["compatibility",Struct({cliVersionRange:CliVersionRange})]));var PublishedScaffoldBaselineManifest=Union2([PublishedScaffoldBaselineManifestV1,PublishedScaffoldBaselineManifestV2]);var prereleaseIdentifier=String.raw`(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)`;var buildIdentifier=String.raw`[0-9A-Za-z-]+`;var versionPattern=new RegExp(String.raw`^(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)(?:-(?<prerelease>${prereleaseIdentifier}(?:\.${prereleaseIdentifier})*))?(?:\+${buildIdentifier}(?:\.${buildIdentifier})*)?$`,"u");var constraintPattern=new RegExp(String.raw`^(?<operator>>=|<=|>|<|=)?(?<major>\d+)(?:\.(?<minor>\d+)(?:\.(?<patch>\d+)(?:-(?<prerelease>${prereleaseIdentifier}(?:\.${prereleaseIdentifier})*))?(?:\+${buildIdentifier}(?:\.${buildIdentifier})*)?)?)?$`,"u");var numericIdentifierPattern=/^\d+$/u;var parseVersion=(value5)=>{const groups=versionPattern.exec(value5)?.groups;return groups===undefined?null:[Number(groups.major),Number(groups.minor),Number(groups.patch),groups.prerelease?.split(".")??[]]};var comparePrereleaseIdentifiers=(left,right)=>{const leftNumeric=numericIdentifierPattern.test(left);const rightNumeric=numericIdentifierPattern.test(right);if(leftNumeric&&rightNumeric){if(BigInt(left)<BigInt(right)){return-1}return BigInt(left)>BigInt(right)?1:0}if(leftNumeric!==rightNumeric){return leftNumeric?-1:1}if(left<right){return-1}return left>right?1:0};var comparePrereleases=(left,right)=>{if(left.length===0||right.length===0){if(left.length===right.length){return 0}return left.length===0?1:-1}for(let index2=0;index2<Math.max(left.length,right.length);index2+=1){const leftIdentifier=left[index2];const rightIdentifier=right[index2];if(leftIdentifier===undefined||rightIdentifier===undefined){if(leftIdentifier===rightIdentifier){return 0}return leftIdentifier===undefined?-1:1}const compared=comparePrereleaseIdentifiers(leftIdentifier,rightIdentifier);if(compared!==0){return compared}}return 0};var compareCoreVersions=(left,right)=>left[0]-right[0]||left[1]-right[1]||left[2]-right[2];var compareVersions2=(left,right)=>compareCoreVersions(left,right)||comparePrereleases(left[3],right[3]);var nextPartialVersion=(version3,precision)=>precision===1?[version3[0]+1,0,0,[]]:[version3[0],version3[1]+1,0,[]];var constraintPrecision=(groups)=>{if(groups.patch!==undefined){return 3}return groups.minor===undefined?1:2};var parseCompatibilityRange=(range2)=>{const normalized=range2.trim();if(normalized==="*"){return[]}return normalized.split(/\s+/u).map((constraint)=>{const groups=constraintPattern.exec(constraint)?.groups;if(groups===undefined){return null}return{operator:groups.operator??"=",precision:constraintPrecision(groups),target:[Number(groups.major),Number(groups.minor??0),Number(groups.patch??0),groups.prerelease?.split(".")??[]]}})};var satisfiesCliCompatibilityRange=(range2,version3)=>{if(range2.trim()==="*"){return true}const constraints=parseCompatibilityRange(range2);const current=parseVersion(version3);if(current===null||constraints.some((constraint)=>constraint===null)){return false}return constraints.every(({operator,precision,target})=>{const compare5=precision===3?compareVersions2:compareCoreVersions;const compared=compare5(current,target);const next=precision===3?undefined:nextPartialVersion(target,precision);switch(operator){case">=":{return compared>=0}case"<=":{return next===undefined?compared<=0:compare5(current,next)<0}case">":{return next===undefined?compared>0:compare5(current,next)>=0}case"<":{return compared<0}default:{return next===undefined?compared===0:compared>=0&&compare5(current,next)<0}}})};import{existsSync as existsSync10,readFileSync as readFileSync10}from"node:fs";import path20 from"node:path";var readJson=(filePath)=>JSON.parse(readFileSync10(filePath,"utf-8"));var validateBaselineAssets=({root,skills})=>{for(const skill of skills){if(!existsSync10(path20.join(root,skill.sourceDirectory))){throw new Error(`Baseline skill asset missing: ${skill.sourceDirectory}`)}}};var loadBaselineFromDirectory=(root,verifiedSummary)=>{const metadata=readJson(path20.join(root,"baseline.json"));if(metadata.version!==verifiedSummary.resolvedVersion){throw new Error("Baseline metadata does not match the verified version.")}const dataRoot2=path20.join(root,"data");const baseline={dataRoot:dataRoot2,hooks:readJson(path20.join(dataRoot2,"catalog","hooks.json")),lintAssets:validateLintCatalog(readJson(path20.join(dataRoot2,"catalog","lint-assets.json"))),packs:readJson(path20.join(dataRoot2,"catalog","packs.json")),root,skills:readJson(path20.join(dataRoot2,"catalog","skills.json")),skillsRoot:path20.join(root,"skills"),summary:verifiedSummary,tools:readJson(path20.join(dataRoot2,"catalog","tools.json"))};validateBaselineAssets(baseline);return baseline};var defaultMessage3=(message)=>String5.pipe(optionalKey2,withConstructorDefault2(succeed6(message)));var BackofficeAccessRole=Literals(["admin","member"]);var BackofficeAccessStatus=Literals(["invited","active","revoked"]);var BackofficeAccessSummary=Struct({email:String5,role:BackofficeAccessRole,status:BackofficeAccessStatus,userId:optionalKey2(String5),invitedBy:optionalKey2(String5),revokedBy:optionalKey2(String5),invitedAt:optionalKey2(String5),activatedAt:optionalKey2(String5),revokedAt:optionalKey2(String5),createdAt:String5,updatedAt:String5}).annotate({identifier:"BackofficeAccessSummary"});var BackofficeAccessList=Struct({users:ArraySchema(BackofficeAccessSummary)}).annotate({identifier:"BackofficeAccessList"});var BackofficeAccessInviteRequest=Struct({email:String5,role:BackofficeAccessRole}).annotate({identifier:"BackofficeAccessInviteRequest"});var BackofficeOperatorSummary=Struct({operatorId:optionalKey2(String5),email:optionalKey2(String5),name:optionalKey2(String5)}).annotate({identifier:"BackofficeOperatorSummary"});var ObservedRepositorySummary=Struct({id:String5,projectUsageId:String5,remoteHost:optionalKey2(String5),remotePath:optionalKey2(String5),remoteUrl:optionalKey2(String5),branch:optionalKey2(String5),lastCommitSha:optionalKey2(String5),dirty:optionalKey2(Boolean4),gitIdentity:optionalKey2(GitIdentity),firstSeenAt:optionalKey2(IsoDateTimeString),lastSeenAt:optionalKey2(IsoDateTimeString)}).annotate({identifier:"ObservedRepositorySummary"});var ProjectUsageEventSummary=Struct({id:String5,eventId:String5,name:String5,source:String5,counted:Boolean4,cliVersion:String5,baseline:optionalKey2(Struct({channel:optionalKey2(String5),version:optionalKey2(String5)})),occurredAt:IsoDateTimeString,operator:optionalKey2(BackofficeOperatorSummary)}).annotate({identifier:"ProjectUsageEventSummary"});var HarnessReportSummary=Struct({id:String5,projectUsageId:optionalKey2(String5),observedRepositoryId:optionalKey2(String5),title:String5,body:optionalKey2(String5),type:String5,severity:String5,status:String5,githubUrl:optionalKey2(String5),createdAt:IsoDateTimeString,updatedAt:IsoDateTimeString,operator:optionalKey2(BackofficeOperatorSummary)}).annotate({identifier:"HarnessReportSummary"});var ProjectUsageSummary=Struct({id:String5,name:optionalKey2(String5),repositoryCount:Finite,countedEventCount:Finite,openReportCount:Finite,latestCliVersion:optionalKey2(String5),latestBaselineChannel:optionalKey2(String5),latestBaselineVersion:optionalKey2(String5),lastActivityAt:optionalKey2(IsoDateTimeString),initializedBy:optionalKey2(BackofficeOperatorSummary),lastUpdatedBy:optionalKey2(BackofficeOperatorSummary)}).annotate({identifier:"ProjectUsageSummary"});var ProjectUsageList=Struct({projects:ArraySchema(ProjectUsageSummary),reports:ArraySchema(HarnessReportSummary)}).annotate({identifier:"ProjectUsageList"});var ProjectUsageDetail=Struct({project:ProjectUsageSummary,repositories:ArraySchema(ObservedRepositorySummary),events:ArraySchema(ProjectUsageEventSummary),reports:ArraySchema(HarnessReportSummary)}).annotate({identifier:"ProjectUsageDetail"});var BackofficeRepositoryMappingRequest=Struct({observedRepositoryId:String5}).annotate({identifier:"BackofficeRepositoryMappingRequest"});var BackofficeReportUpdateRequest=Struct({status:optionalKey2(HarnessReportStatus),githubUrl:optionalKey2(NullOr(String5))}).annotate({identifier:"BackofficeReportUpdateRequest"});class Unauthorized extends TaggedErrorClass()("@punks/contract/errors/Unauthorized",{message:defaultMessage3("Backoffice session is required.")},{httpApiStatus:401,title:"Unauthorized"}){}class BackofficeRequestRejected extends TaggedErrorClass()("@punks/contract/errors/BackofficeRequestRejected",{message:String5},{httpApiStatus:400,title:"Backoffice Request Rejected"}){}class BackofficePersistenceUnavailable extends TaggedErrorClass()("@punks/contract/errors/BackofficePersistenceUnavailable",{message:defaultMessage3("Backoffice persistence is unavailable.")},{httpApiStatus:503,title:"Backoffice Persistence Unavailable"}){}class BackofficeDependencyUnavailable extends TaggedErrorClass()("@punks/contract/errors/BackofficeDependencyUnavailable",{message:defaultMessage3("Backoffice dependency is unavailable.")},{httpApiStatus:503,title:"Backoffice Dependency Unavailable"}){}var listErrors=[HttpApiDecodeError,Forbidden2,Unauthorized,BackofficePersistenceUnavailable];var rejectedErrors=[HttpApiDecodeError,Forbidden2,Unauthorized,BackofficeRequestRejected,BackofficePersistenceUnavailable];var projectUsageListErrors=[...listErrors,BackofficeDependencyUnavailable];var projectUsageDetailErrors=[...rejectedErrors,BackofficeDependencyUnavailable];var BackofficeApi=exports_HttpApiGroup.make("backoffice").add(exports_HttpApiEndpoint.get("currentAccess","/access/current",{success:BackofficeAccessSummary,error:rejectedErrors}),exports_HttpApiEndpoint.get("accessList","/access-users",{success:BackofficeAccessList,error:listErrors}),exports_HttpApiEndpoint.post("inviteAccess","/access-users",{payload:BackofficeAccessInviteRequest,success:BackofficeAccessSummary,error:rejectedErrors}),exports_HttpApiEndpoint.post("revokeAccess","/access-users/:email/revoke",{params:{email:String5},success:BackofficeAccessSummary,error:rejectedErrors}),exports_HttpApiEndpoint.get("projectUsageList","/project-usages",{success:ProjectUsageList,error:projectUsageListErrors}),exports_HttpApiEndpoint.get("projectUsageDetail","/project-usages/:projectUsageId",{params:{projectUsageId:String5},success:ProjectUsageDetail,error:projectUsageDetailErrors}),exports_HttpApiEndpoint.post("mapRepository","/project-usages/:projectUsageId/repositories",{params:{projectUsageId:String5},payload:BackofficeRepositoryMappingRequest,success:ObservedRepositorySummary,error:rejectedErrors}),exports_HttpApiEndpoint.patch("updateReport","/reports/:reportId",{params:{reportId:String5},payload:BackofficeReportUpdateRequest,success:HarnessReportSummary,error:rejectedErrors})).prefix("/backoffice").annotateMerge(exports_OpenApi.annotations({title:"Backoffice project usage"}));var defaultMessage4=(message)=>String5.pipe(optionalKey2,withConstructorDefault2(succeed6(message)));var HarnessReportType=Literals(["bug","docs","workflow","tooling","other"]);var HarnessReportSeverity=Literals(["low","medium","high"]);var HarnessReportLabel=String5.check(isTrimmed(),isNonEmpty(),isMaxLength(50));var HarnessReportLabels=ArraySchema(HarnessReportLabel).check(isMaxLength(10));var HarnessReportInput=Struct({title:optionalKey2(String5),body:optionalKey2(String5),type:HarnessReportType,severity:HarnessReportSeverity,createdAt:IsoDateTimeString,cliVersion:String5,area:optionalKey2(String5),skillPack:optionalKey2(String5),command:optionalKey2(String5),expected:optionalKey2(String5),actual:optionalKey2(String5),steps:optionalKey2(String5),labels:optionalKey2(HarnessReportLabels),projectUsageId:optionalKey2(String5),repository:optionalKey2(ObservedRepositoryInput),githubUrl:optionalKey2(String5)}).annotate({identifier:"HarnessReportInput"});var HarnessReportCreated=Struct({reportId:String5,status:HarnessReportStatus,githubUrl:optionalKey2(String5),title:optionalKey2(String5),deduplicated:optionalKey2(Boolean4),duplicateOf:optionalKey2(String5)}).annotate({identifier:"HarnessReportCreated"});class HarnessReportRejected extends TaggedErrorClass()("@punks/contract/errors/HarnessReportRejected",{message:String5},{httpApiStatus:400,title:"Harness Report Rejected"}){}class HarnessReportPersistenceUnavailable extends TaggedErrorClass()("@punks/contract/errors/HarnessReportPersistenceUnavailable",{message:defaultMessage4("Harness report persistence is unavailable.")},{httpApiStatus:503,title:"Harness Report Persistence Unavailable"}){}class HarnessReportDependencyUnavailable extends TaggedErrorClass()("@punks/contract/errors/HarnessReportDependencyUnavailable",{message:defaultMessage4("Harness report submission dependency is unavailable.")},{httpApiStatus:503,title:"Harness Report Dependency Unavailable"}){}var ReportsApi=exports_HttpApiGroup.make("reports").add(exports_HttpApiEndpoint.post("submit","/",{payload:HarnessReportInput,success:HarnessReportCreated,error:[HttpApiDecodeError,Forbidden2,HarnessReportRejected,HarnessReportDependencyUnavailable,HarnessReportPersistenceUnavailable]})).prefix("/reports").annotateMerge(exports_OpenApi.annotations({title:"Harness reports"}));var defaultMessage5=(message)=>String5.pipe(optionalKey2,withConstructorDefault2(succeed6(message)));var ProductTelemetryEventName=Literals(["cli.artifact.pull.completed","cli.scaffold.init.completed","cli.scaffold.setup.completed","cli.scaffold.update.applied","cli.harness.report.submitted"]);var TelemetrySource=Literals(["normal","local-dev","ci","debug","test"]);var TelemetryBaselineContext=Struct({channel:optionalKey2(BaselineChannel),version:optionalKey2(String5)}).annotate({identifier:"TelemetryBaselineContext"});var ProductTelemetryEventInput=Struct({eventId:String5,name:ProductTelemetryEventName,occurredAt:IsoDateTimeString,cliVersion:String5,source:TelemetrySource,projectUsageId:optionalKey2(String5),repository:optionalKey2(ObservedRepositoryInput),baseline:optionalKey2(TelemetryBaselineContext)}).annotate({identifier:"ProductTelemetryEventInput"});var ProductTelemetryEventAccepted=Struct({eventId:String5,accepted:Boolean4,counted:Boolean4}).annotate({identifier:"ProductTelemetryEventAccepted"});class TelemetryEventRejected extends TaggedErrorClass()("@punks/contract/errors/TelemetryEventRejected",{message:String5},{httpApiStatus:400,title:"Telemetry Event Rejected"}){}class TelemetryPersistenceUnavailable extends TaggedErrorClass()("@punks/contract/errors/TelemetryPersistenceUnavailable",{message:defaultMessage5("Telemetry persistence is unavailable.")},{httpApiStatus:503,title:"Telemetry Persistence Unavailable"}){}var TelemetryApi=exports_HttpApiGroup.make("telemetry").add(exports_HttpApiEndpoint.post("record","/events",{payload:ProductTelemetryEventInput,success:ProductTelemetryEventAccepted,error:[HttpApiDecodeError,Forbidden2,TelemetryEventRejected,TelemetryPersistenceUnavailable]})).prefix("/telemetry").annotateMerge(exports_OpenApi.annotations({title:"Product telemetry"}));var HealthApi=exports_HttpApiGroup.make("health",{topLevel:true}).add(exports_HttpApiEndpoint.get("healthz","/healthz",{success:exports_HttpApiSchema.NoContent.annotate({description:"Empty health response"}),error:[HttpApiDecodeError,Forbidden2]}));var HarnessApi=exports_HttpApi.make("harness").add(HealthApi,BaselineApi,TelemetryApi,ReportsApi,BackofficeApi).prefix("/api").annotateMerge(exports_OpenApi.annotations({title:"Harness Intelligence Control Plane",summary:"Shared typed contract for Devpunks CLI/backend control-plane calls."}));var ControlPlaneOperation=Literals(["record-product-telemetry","resolve-stable-baseline","submit-harness-report"]);class ControlPlaneRequestFailure extends TaggedErrorClass()("@punks/cli/control-plane/ControlPlaneRequestFailure",{cause:Defect(),operation:ControlPlaneOperation,transport:Boolean4}){}var isHttpTransportFailure=(cause)=>isHttpClientError(cause)&&cause.reason._tag==="TransportError";var normalizeControlPlaneFailure=(operation2,effect2)=>effect2.pipe(catchIf2(isHttpClientError,(cause)=>fail6(new ControlPlaneRequestFailure({cause,operation:operation2,transport:isHttpTransportFailure(cause)}))),catchIf2(isSchemaError,(cause)=>fail6(new ControlPlaneRequestFailure({cause,operation:operation2,transport:false}))));var makeControlPlaneClient=({baseUrl:baseUrl2,headers})=>exports_HttpApiClient.make(HarnessApi,{baseUrl:baseUrl2,...headers===undefined?{}:{transformClient:(client)=>client.pipe(exports_HttpClient.mapRequest(exports_HttpClientRequest.setHeaders(headers)))}});var resolveBaselineMetadata=(options4)=>normalizeControlPlaneFailure("resolve-stable-baseline",gen2(function*requestBaselineMetadata(){const client=yield*makeControlPlaneClient(options4);return yield*client.baseline.resolve({params:{channel:options4.request.channel},query:options4.request.version===undefined?{}:{version:options4.request.version}})}));var recordProductTelemetryEvent=(options4)=>normalizeControlPlaneFailure("record-product-telemetry",gen2(function*sendProductTelemetryEvent(){const client=yield*makeControlPlaneClient(options4);return yield*client.telemetry.record({payload:options4.event})}));var submitHarnessReport=(options4)=>normalizeControlPlaneFailure("submit-harness-report",gen2(function*sendHarnessReport(){const client=yield*makeControlPlaneClient(options4);return yield*client.reports.submit({payload:options4.report})}));var trimTrailingSlashes=(value5)=>value5.trim().replace(/\/+$/u,"");var bundledControlPlaneUrl=({disableBundledUrl=false}={})=>{if(disableBundledUrl){return}const config=JSON.parse(readDataFile("control-plane.json"));return typeof config.defaultUrl==="string"&&config.defaultUrl.trim().length>0?trimTrailingSlashes(config.defaultUrl):undefined};var resolveControlPlaneUrl=(explicitUrl,configuration={})=>{const baseUrl2=explicitUrl?.trim()||configuration.baseUrl?.trim()||bundledControlPlaneUrl(configuration);return baseUrl2===undefined||baseUrl2.length===0?undefined:trimTrailingSlashes(baseUrl2)};class BaselineResolutionFailure extends TaggedErrorClass()("@punks/cli/baseline-resolution/BaselineResolutionFailure",{cause:Defect(),message:String5,operation:Literal2("resolve-stable-baseline"),reason:Literals(["corrupt-artifact","remote-access","unsafe-artifact","invalid-artifact"])}){}import{randomUUID}from"node:crypto";import{execFileSync as execFileSync3}from"node:child_process";var disabledTelemetryConfig={disableBundledUrl:true};var git=(cwd,args2)=>{try{return execFileSync3("git",args2,{cwd,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}};var redactRemote=(remote)=>remote.replace(/\/\/[^/@]+@/u,"//");var safeRemoteParts=(remote)=>{const redacted5=redactRemote(remote);const ssh=/^git@(?<host>[^:]+):(?<path>.+)$/u.exec(redacted5);const sshGroups=ssh?.groups;if(sshGroups!==undefined){return{remoteHost:sshGroups.host,remotePath:sshGroups.path.replace(/\.git$/u,""),remoteUrl:redacted5}}try{const url2=new URL(redacted5);return{remoteHost:url2.hostname,remotePath:url2.pathname.replaceAll(/^\/|\.git$/gu,""),remoteUrl:redacted5}}catch{return{remoteUrl:redacted5}}};var observedRepository=(cwd)=>{const remote=git(cwd,["config","--get","remote.origin.url"]);const commitSha=git(cwd,["rev-parse","HEAD"])??undefined;const status2=git(cwd,["status","--short"]);const name2=git(cwd,["config","--local","--get","user.name"])??undefined;const email=git(cwd,["config","--local","--get","user.email"])??undefined;return{...remote===null?{}:safeRemoteParts(remote),...commitSha===undefined?{}:{commitSha},...status2===null?{}:{dirty:status2.length>0},...name2===undefined&&email===undefined?{}:{gitIdentity:{...name2===undefined?{}:{name:name2},...email===undefined?{}:{email}}}}};var isLocalControlPlaneUrl=(value5)=>{if(value5===undefined||value5.trim().length===0){return false}try{const{hostname}=new URL(value5);return hostname==="localhost"||hostname.endsWith(".localhost")||hostname.startsWith("127.")||hostname==="0.0.0.0"||hostname==="::1"||hostname==="[::1]"}catch{return value5.includes("localhost")||value5.includes(".localhost")}};var telemetrySource=(configuration={})=>{if(configuration.telemetrySource==="ci"){return"ci"}if(configuration.telemetrySource==="debug"){return"debug"}if(configuration.telemetrySource==="test"){return"test"}if(isLocalControlPlaneUrl(configuration.baseUrl)){return"local-dev"}return"normal"};var makeProductTelemetryEvent=({name:name2,cwd,baseline,controlPlaneUrl,configuration})=>({cliVersion:version2,eventId:randomUUID(),name:name2,occurredAt:new Date().toISOString(),repository:observedRepository(cwd),source:telemetrySource(configuration??(controlPlaneUrl===undefined?{}:{baseUrl:controlPlaneUrl})),...baseline===undefined?{}:{baseline}});var telemetryBaseUrl=(controlPlaneUrl,configuration=disabledTelemetryConfig)=>resolveControlPlaneUrl(controlPlaneUrl,configuration);var submitProductTelemetryEffect=(event,options4={})=>{const baseUrl2=telemetryBaseUrl(options4.controlPlaneUrl,options4.configuration);if(baseUrl2===undefined){return void_3}return recordProductTelemetryEvent({baseUrl:baseUrl2,event}).pipe(catchTags2({"@punks/cli/control-plane/ControlPlaneRequestFailure":()=>void_3,"@punks/contract/errors/Forbidden":()=>void_3,"@punks/contract/errors/TelemetryEventRejected":()=>void_3,"@punks/contract/errors/TelemetryPersistenceUnavailable":()=>void_3,HttpApiDecodeError:()=>void_3}),asVoid2)};var telemetryTransportEnabled=(controlPlaneUrl,configuration)=>telemetryBaseUrl(controlPlaneUrl,configuration)!==undefined;var makeCliEvent=(name2,options4={})=>makeProductTelemetryEvent({cwd:options4.cwd??process.cwd(),name:name2,...options4.baseline===undefined?{}:{baseline:options4.baseline},...options4.controlPlaneUrl===undefined?{}:{controlPlaneUrl:options4.controlPlaneUrl},...options4.configuration===undefined?{}:{configuration:options4.configuration}});var submitCliEventEffect=(name2,options4={})=>telemetryTransportEnabled(options4.controlPlaneUrl,options4.configuration)?submitProductTelemetryEffect(makeCliEvent(name2,options4),options4):void_3;var assetArchiveName="scaffold-baseline.tgz";var cachedArtifactName=".verified-artifact.tgz";var maximumArchiveRedirects=20;var defaultRemoteBaselineTimeoutMs=5000;var archiveRedirectStatuses=new Set([301,302,303,307,308]);var bundledFallbackAvailability=new Set(["authority-unconfigured","network","unavailable-status"]);var BaselineArchiveEndpointFailure=Union2([BaselineNotFound,BaselineAuthorityFailure,BaselineIntegrityFailure,BaselineUnavailable]);var isBaselineReleaseTag=(tag4)=>tag4.startsWith("baseline/stable/")&&!/^v\d+\.\d+\.\d+(?:$|-)/u.test(tag4);var normalizeBaselineRequest=(value5)=>{const requested=value5?.trim();if(requested===undefined||requested.length===0||requested==="stable"){return{channel:"stable"}}return requested==="bundled"?{channel:"bundled"}:{channel:"stable",version:requested}};var sha256File=(filePath)=>createHash5("sha256").update(readFileSync11(filePath)).digest("hex");var isSafeTarPath=(entry)=>entry.length>0&&!path21.isAbsolute(entry)&&!entry.split("/").includes("..");var isSafePathSegment=(value5)=>value5.length>0&&value5!=="."&&value5!==".."&&!value5.includes("/")&&!value5.includes("\\");var integrityFailure=(resolution,message,actualDigest)=>new BaselineIntegrityFailure({...actualDigest===undefined?{}:{actualDigest},expectedDigest:resolution.digest,message,request:resolution.requested,resolvedVersion:resolution.resolvedVersion});var verifyEmbeddedBaselineMetadata=(root,resolution,retrieval)=>{let metadata;try{metadata=decodeUnknownSync2(EmbeddedScaffoldBaselineMetadata)(JSON.parse(readFileSync11(path21.join(root,"baseline.json"),"utf-8")))}catch{throw integrityFailure(resolution,`${retrieval} baseline metadata is invalid.`)}if(metadata.channel!==resolution.requested.channel||metadata.version!==resolution.resolvedVersion||resolution.provenance!==`release:${resolution.resolvedVersion}`||metadata.tag!==`baseline/stable/${resolution.resolvedVersion}`||metadata.sha256!==undefined&&metadata.sha256!==null&&metadata.sha256!==resolution.digest||metadata.compatibility!==undefined&&metadata.compatibility.cliVersionRange!==resolution.compatibility.cliVersionRange){throw integrityFailure(resolution,`${retrieval} baseline metadata disagrees with selected authority.`)}};class BaselineArchiveUnavailableError extends Error{name="BaselineArchiveUnavailableError"}var baselineFailureMessage=(cause)=>{if(cause instanceof ControlPlaneRequestFailure||isTimeoutError2(cause)){return"The baseline authority request failed."}if(cause instanceof Error&&typeof cause.message==="string"&&cause.message.trim().length>0){return cause.message}return"Baseline resolution failed."};var parseArchiveUrl=(value5)=>{let url2;try{url2=new URL(value5)}catch{throw new Error("Authority returned an invalid baseline archive URL.")}if(url2.protocol!=="http:"&&url2.protocol!=="https:"){throw new Error("Authority returned an invalid baseline archive URL.")}return url2};var fetchArchiveResponse=async(url2,signal,redirects=0)=>{const response=await fetch(url2,{redirect:"manual",signal}).catch((error2)=>{throw new BaselineArchiveUnavailableError(error2 instanceof Error?error2.message:"Failed to download baseline artifact.",{cause:error2})});if(!archiveRedirectStatuses.has(response.status)){return response}const location2=response.headers.get("location");if(location2===null||redirects>=maximumArchiveRedirects){throw new Error("Authority returned an invalid baseline archive URL.")}const redirectedUrl=parseArchiveUrl(location2).toString();return fetchArchiveResponse(redirectedUrl,signal,redirects+1)};var decodeArchiveEndpointFailure=async(response)=>{const body=await response.json().catch(()=>null);if(body===null){return}try{return decodeUnknownSync2(BaselineArchiveEndpointFailure)(body)}catch{return}};var bundledFallbackEligible=(cause)=>cause instanceof BaselineArchiveUnavailableError||isTimeoutError2(cause)||cause instanceof BaselineUnavailable&&bundledFallbackAvailability.has(cause.availability)||cause instanceof ControlPlaneRequestFailure&&cause.transport;var classifyFailure=(cause)=>{let reason="invalid-artifact";if(cause instanceof BaselineIntegrityFailure){reason="corrupt-artifact"}else if(bundledFallbackEligible(cause)){reason="remote-access"}return new BaselineResolutionFailure({cause,message:baselineFailureMessage(cause),operation:"resolve-stable-baseline",reason})};var extractSafeTgz=(archivePath,targetDirectory)=>{const entries3=execFileSync4("tar",["-tzf",archivePath],{encoding:"utf-8"}).split(/\r?\n/u).filter(Boolean);const unsafe=entries3.find((entry)=>!isSafeTarPath(entry));if(unsafe!==undefined){throw new Error(`Unsafe path in baseline archive: ${unsafe}`)}mkdirSync6(targetDirectory,{recursive:true});execFileSync4("tar",["-xzf",archivePath,"-C",targetDirectory],{stdio:"ignore"})};var download=async(url2,targetPath,timeoutMs)=>{const controller=new AbortController;const timeout3=setTimeout(()=>controller.abort(),timeoutMs);try{const response=await fetchArchiveResponse(parseArchiveUrl(url2).toString(),controller.signal);if(!response.ok){const endpointFailure=await decodeArchiveEndpointFailure(response);if(endpointFailure!==undefined){if(endpointFailure instanceof BaselineUnavailable&&response.status!==503){throw new Error(`Failed to download baseline artifact: ${response.status}`)}throw endpointFailure}if(response.status!==503){throw new Error(`Failed to download baseline artifact: ${response.status}`)}throw new BaselineArchiveUnavailableError(`Failed to download baseline artifact: ${response.status}`)}const bytes=await response.arrayBuffer().catch((error2)=>{throw new BaselineArchiveUnavailableError(error2 instanceof Error?error2.message:"Failed to read baseline artifact response.",{cause:error2})});writeFileSync6(targetPath,new Uint8Array(bytes))}finally{clearTimeout(timeout3)}};var summaryMetadata=(resolution,retrieval)=>({authoritySource:resolution.source,channel:resolution.requested.channel,commit:null,compatibility:resolution.compatibility,digest:resolution.digest,provenance:resolution.provenance,requested:resolution.requested,resolvedVersion:resolution.resolvedVersion,retrieval,sha256:resolution.digest,source:"remote",tag:isBaselineReleaseTag(resolution.provenance)?resolution.provenance:null,version:resolution.resolvedVersion});var decodeLocalCompatibility=(metadata)=>{if(!Object.hasOwn(metadata,"compatibility")){return"*"}const{compatibility}=metadata;if(typeof compatibility!=="object"||compatibility===null||!("cliVersionRange"in compatibility)){throw new Error("Local baseline metadata has invalid CLI compatibility.")}const{cliVersionRange}=compatibility;if(typeof cliVersionRange!=="string"||cliVersionRange.trim().length===0){throw new Error("Local baseline metadata has invalid CLI compatibility.")}return cliVersionRange};var resolveLocalBaseline=(url2,request3)=>{if(!url2.startsWith("file://")){return null}const root=fileURLToPath2(new URL(url2));const metadata=JSON.parse(readFileSync11(path21.join(root,"baseline.json"),"utf-8"));if(typeof metadata.version!=="string"||metadata.version.length===0){throw new Error("Local baseline metadata has no version.")}const cliVersionRange=decodeLocalCompatibility(metadata);if(metadata.tag!==undefined&&metadata.tag!==null&&typeof metadata.tag!=="string"){throw new Error("Local baseline metadata has an invalid tag.")}if(metadata.commit!==undefined&&metadata.commit!==null&&typeof metadata.commit!=="string"){throw new Error("Local baseline metadata has an invalid commit.")}const tag4=metadata.tag??null;const commit=metadata.commit??null;const digest2=digestContentRoots([{prefix:"baseline",root}]);if(request3.version!==undefined&&request3.version!==metadata.version){throw new BaselineIntegrityFailure({expectedDigest:digest2,message:"Local baseline metadata does not match the exact requested version.",request:request3,resolvedVersion:metadata.version})}if(!satisfiesCliCompatibilityRange(cliVersionRange,version2)){throw new BaselineIntegrityFailure({expectedDigest:digest2,message:`Local baseline requires CLI ${cliVersionRange}; current CLI is ${version2}.`,request:request3,resolvedVersion:metadata.version})}return loadBaselineFromDirectory(root,{authoritySource:"local",channel:request3.channel,commit,compatibility:{cliVersionRange},digest:digest2,provenance:tag4??"local-file",requested:request3,resolvedVersion:metadata.version,retrieval:"available",sha256:digest2,source:"local",tag:tag4,version:metadata.version})};var loadExactCachedBaseline=(targetDirectory,resolution)=>{if(!existsSync11(targetDirectory)){return{baseline:null}}try{if(!existsSync11(path21.join(targetDirectory,"baseline.json"))){throw integrityFailure(resolution,"Cached baseline is incomplete.")}const artifactPath=path21.join(targetDirectory,cachedArtifactName);if(!existsSync11(artifactPath)||sha256File(artifactPath)!==resolution.digest){throw integrityFailure(resolution,"Cached artifact does not match authority.")}const verificationDirectory=mkdtempSync2(path21.join(tmpdir5(),"punks-cache-verify-"));try{extractSafeTgz(artifactPath,verificationDirectory);const expected=digestContentRoots([{prefix:"baseline",root:verificationDirectory}]);const actual=digestContentRoots([{include:(relativePath)=>relativePath!==cachedArtifactName,prefix:"baseline",root:targetDirectory}]);if(actual!==expected){throw integrityFailure(resolution,"Cached baseline content changed.")}verifyEmbeddedBaselineMetadata(targetDirectory,resolution,"Cached")}finally{rmSync4(verificationDirectory,{force:true,recursive:true})}return{baseline:loadBaselineFromDirectory(targetDirectory,summaryMetadata(resolution,"cached"))}}catch(error2){rmSync4(targetDirectory,{force:true,recursive:true});return{baseline:null,integrityFailure:error2 instanceof BaselineIntegrityFailure?error2:integrityFailure(resolution,"Cached baseline failed integrity verification.")}}};var materializeBaseline=async(resolution,refresh,timeoutMs,cacheDirectory)=>{if(resolution.source!=="control-plane"){throw integrityFailure(resolution,"Baseline authority source must be control-plane.")}if(!isSafePathSegment(resolution.resolvedVersion)){throw integrityFailure(resolution,"Authority returned an unsafe baseline version.")}parseArchiveUrl(resolution.archive.url);if(!satisfiesCliCompatibilityRange(resolution.compatibility.cliVersionRange,version2)){throw integrityFailure(resolution,`Baseline requires CLI ${resolution.compatibility.cliVersionRange}; current CLI is ${version2}.`)}const targetDirectory=path21.join(cacheDirectory,"devpunks","baselines","verified",resolution.resolvedVersion);const targetParentDirectory=path21.dirname(targetDirectory);let cacheIntegrityFailure;if(!refresh){const cached3=loadExactCachedBaseline(targetDirectory,resolution);if(cached3.baseline!==null){return{artifactPulled:false,baseline:cached3.baseline}}cacheIntegrityFailure=cached3.integrityFailure}mkdirSync6(targetParentDirectory,{recursive:true});const temporaryDirectory=mkdtempSync2(path21.join(targetParentDirectory,".punks-verified-baseline-"));try{const archivePath=path21.join(temporaryDirectory,assetArchiveName);await download(resolution.archive.url,archivePath,timeoutMs).catch((error2)=>{if(cacheIntegrityFailure!==undefined&&bundledFallbackEligible(error2)){throw cacheIntegrityFailure}if(error2 instanceof Error){throw error2}throw new Error("Baseline archive download failed.")});const actualDigest=sha256File(archivePath);if(actualDigest!==resolution.digest||actualDigest!==resolution.archive.sha256){throw integrityFailure(resolution,"Downloaded baseline archive checksum mismatch.",actualDigest)}const extractedDirectory=path21.join(temporaryDirectory,"extracted");extractSafeTgz(archivePath,extractedDirectory);verifyEmbeddedBaselineMetadata(extractedDirectory,resolution,"Downloaded");rmSync4(targetDirectory,{force:true,recursive:true});renameSync2(extractedDirectory,targetDirectory);copyFileSync(archivePath,path21.join(targetDirectory,cachedArtifactName));return{artifactPulled:true,baseline:loadBaselineFromDirectory(targetDirectory,summaryMetadata(resolution,"retrieved"))}}finally{rmSync4(temporaryDirectory,{force:true,recursive:true})}};var resolveBaseline=(options4)=>gen2(function*executeBaselineResolution(){const selectedBaseline=options4.baseline??options4.configuration.release.baseline;const request3=normalizeBaselineRequest(selectedBaseline);const isImplicitStable=selectedBaseline===undefined;if(request3.channel==="bundled"){return yield*try_3({catch:classifyFailure,try:resolveVerifiedBundledBaseline})}const local=yield*try_3({catch:classifyFailure,try:()=>options4.configuration.release.baselineUrl===undefined?null:resolveLocalBaseline(options4.configuration.release.baselineUrl,request3)});if(local!==null){return local}return yield*gen2(function*resolveRemoteBaseline(){const baseUrl2=resolveControlPlaneUrl(undefined,options4.configuration.controlPlane);if(baseUrl2===undefined){return yield*fail6(classifyFailure(new BaselineUnavailable({availability:"authority-unconfigured",message:"The control plane URL is unavailable; baseline authority cannot be resolved.",request:request3})))}const timeoutMs=options4.timeoutMs??defaultRemoteBaselineTimeoutMs;const resolution=yield*resolveBaselineMetadata({baseUrl:baseUrl2,request:request3}).pipe(timeout2(timeoutMs),mapError3(classifyFailure));const materialized=yield*tryPromise2({catch:classifyFailure,try:()=>materializeBaseline(resolution,options4.refresh??options4.configuration.release.refreshBaseline,timeoutMs,options4.configuration.release.cacheDirectory)});if(materialized.artifactPulled){yield*submitCliEventEffect("cli.artifact.pull.completed",{...options4.cwd===undefined?{}:{cwd:options4.cwd},baseline:{channel:materialized.baseline.summary.channel,version:materialized.baseline.summary.version},configuration:options4.configuration.controlPlane})}return materialized.baseline}).pipe(catchTag2("@punks/cli/baseline-resolution/BaselineResolutionFailure",(failure)=>isImplicitStable&&bundledFallbackEligible(failure.cause)?try_3({catch:classifyFailure,try:()=>resolveVerifiedBundledBaseline(request3,"fallback")}):fail6(failure)))});var baselineResolveOptions=(baseline,refresh,cwd,configuration)=>{const selectedBaseline=isSome2(baseline)?baseline.value:configuration.release.baseline;return{...selectedBaseline===undefined?{}:{baseline:selectedBaseline},configuration,refresh:refresh||configuration.release.refreshBaseline===true,...cwd===undefined?{}:{cwd}}};import path22 from"node:path";var baselineToolIds2=["agent-browser","opensrc","portless","skills"];var requiredToolsForSkills2=(skillIds,baseline=bundledBaseline)=>[...new Set([...baselineToolIds2,...baseline.skills.filter((skill)=>skillIds.includes(skill.id)).flatMap((skill)=>skill.requiresTools)])].toSorted();var agentSystemPromptFile2=".devpunks/AGENT-SYSTEM-PROMPT.md";var selectedSkills=(finalPacks,baseline)=>[...new Set(finalPacks.flatMap((packId)=>skillsForPack(packId,baseline)))].toSorted();var runScaffold=({scanDirectory,emitJson=false,repoShapeMode="auto",interaction,outputDirectory,displayOutputDirectory,ensureTools:ensureTools2=true,baseline=bundledBaseline,assumeYes=false,toolStdio=emitJson?"ignore":"inherit",toolRuntime,clipboardRuntime,configuration={disableBundledUrl:true},scriptRuntimePath:scriptRuntimePath2,scriptEnvironment})=>gen2(function*executeScaffold(){const capabilities=yield*ScaffoldCapabilities;const projectSettings=yield*ProjectSettings;const effectiveScriptRuntimePath=scriptRuntimePath2??capabilities.scriptRuntimePath;const effectiveScriptEnvironment=scriptEnvironment??capabilities.scriptEnvironment;const baseRequiredTools=requiredToolsForSkills2([],baseline);let toolBootstrapStatuses=[];const resolvedOutputDirectory=path22.resolve(outputDirectory??scanDirectory);yield*interaction.emit({_tag:"SetupStarted"});if(ensureTools2&&baseRequiredTools.length>0){yield*interaction.emit({_tag:"ToolCheck",phase:"base",toolIds:baseRequiredTools});toolBootstrapStatuses=capabilities.ensureTools(baseRequiredTools,baseline,toolRuntime,{stdio:toolStdio});yield*interaction.emit({_tag:"ToolBootstrap",phase:"base",statuses:toolBootstrapStatuses})}const{detection,packs:resolved}=yield*capabilities.inspectRepository({baseline,repoShapeMode,rootDirectory:scanDirectory});yield*interaction.emit({_tag:"Detection",detection});yield*interaction.emit({_tag:"ResolvedPacks",baseline,resolved});let additions=[];let removals=[];let finalPacks=resolved.preselectedPacks;const selectPacksInteractively=()=>gen2(function*selectScaffoldPacks(){while(true){const shouldEditSelection=!(yield*interaction.keepPrefilledSelection());additions=[];if(shouldEditSelection&&resolved.optionalPacks.length>0){additions=yield*interaction.selectPacks({allowed:resolved.optionalPacks,kind:"add"})}const removablePacks=[...new Set([...resolved.preselectedPacks,...additions])].filter((packId)=>canRemovePack(resolved,packId)).toSorted();removals=[];if(shouldEditSelection&&removablePacks.length>0){removals=yield*interaction.selectPacks({allowed:removablePacks,kind:"remove"})}finalPacks=finalizePackSelection(resolved,additions,removals);if(shouldEditSelection){yield*interaction.emit({_tag:"SelectionPreview",addedPacks:additions,baseline,finalPacks,outputDirectory:resolvedOutputDirectory,preselectedPacks:resolved.preselectedPacks,removedPacks:removals})}if(yield*interaction.confirmSelection()){return}yield*interaction.emit({_tag:"SelectionReopened"})}});yield*assumeYes?interaction.emit({_tag:"SelectionAccepted"}):selectPacksInteractively();const skillIds=selectedSkills(finalPacks,baseline);const requiredTools=requiredToolsForSkills2(skillIds,baseline);const checkedToolIds=new Set(toolBootstrapStatuses.map((entry)=>entry.toolId));const remainingRequiredTools=requiredTools.filter((toolId)=>!checkedToolIds.has(toolId));if(ensureTools2&&remainingRequiredTools.length>0){yield*interaction.emit({_tag:"ToolCheck",phase:"selected",toolIds:remainingRequiredTools});const remainingToolBootstrapStatuses=capabilities.ensureTools(remainingRequiredTools,baseline,toolRuntime,{stdio:toolStdio});toolBootstrapStatuses=[...toolBootstrapStatuses,...remainingToolBootstrapStatuses].toSorted((left,right)=>left.toolId.localeCompare(right.toolId));yield*interaction.emit({_tag:"ToolBootstrap",phase:"selected",statuses:remainingToolBootstrapStatuses})}const contextPlan=yield*compileScaffoldContextPlan({baseline,detection,finalPacks,preserveExistingSubagentManifest:true,scanDirectory}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})));const settingsExist=yield*projectSettings.read(resolvedOutputDirectory).pipe(as2(true),catchTag2("ProjectSettingsMissing",()=>succeed6(false)),mapError3((cause)=>new CliValidationError({cause,message:cause.message})));const scaffoldOutput=yield*capabilities.writeOutput({baseline,contextPlan,detection,...displayOutputDirectory===undefined?{}:{displayOutputDirectory},outputDirectory:resolvedOutputDirectory,repoShapeMode,scanDirectory,scriptEnvironment:effectiveScriptEnvironment,scriptRuntimePath:effectiveScriptRuntimePath,toolBootstrapStatuses}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})));if(scaffoldOutput.projectionReceiptFile===null||scaffoldOutput.projectionStatus===null){return yield*new CliValidationError({message:"Scaffold output did not produce harness projection evidence."})}capabilities.cleanupGitignore(scaffoldOutput.outputDirectory);yield*gen2(function*updateProjectSettings(){if(!settingsExist){return}yield*projectSettings.write(scaffoldOutput.outputDirectory,{_tag:"ScaffoldChange",baselineVersion:baseline.summary.version,cliVersion:version2,requiredTools})}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})));const renderedAgentSystemPrompt=formatAgentHandoffSummary({addedPacks:additions,agentHandoffFile:scaffoldOutput.agentHandoffFile,agentSystemPromptFile:agentSystemPromptFile2,baseline:baseline.summary,contextPlan:scaffoldOutput.contextPlan,contextPlanFile:scaffoldOutput.contextPlanFile,cwd:scanDirectory,defaultPacks:resolved.defaultPacks,detectedLanguages:detection.detectedLanguages,detectedPacks:resolved.detectedPacks,detectedTechnologies:detection.detectedTechnologies,finalPacks,generatedFiles:[...scaffoldOutput.generatedFiles,agentSystemPromptFile2],harnessFiles:scaffoldOutput.harnessFiles,hiddenOutputDirectories:scaffoldOutput.hiddenOutputDirectories,hookFiles:scaffoldOutput.hookFiles,languagePacks:resolved.languagePacks,lintAssets:scaffoldOutput.lintAssets,lintSpecFiles:scaffoldOutput.lintSpecFiles,managedFiles:scaffoldOutput.managedFiles,manifests:capabilities.manifestPaths(detection),monorepo:detection.monorepo,monorepoSignals:detection.monorepoSignals,opensrcReferences:scaffoldOutput.opensrcReferences,outputDirectory:scaffoldOutput.outputDirectory,projectionReceiptFile:scaffoldOutput.projectionReceiptFile,projectionStatus:scaffoldOutput.projectionStatus,promptOutputs:scaffoldOutput.promptOutputs,promptSpecFiles:scaffoldOutput.promptSpecFiles,promptSpecs:scaffoldOutput.promptSpecs,removedPacks:removals,repoShapeMode,scaffoldManifestFile:scaffoldOutput.scaffoldManifestFile,scriptFiles:scaffoldOutput.scriptFiles,skillFiles:scaffoldOutput.skillFiles,sourceGuideFiles:scaffoldOutput.sourceGuideFiles,sourceGuides:scaffoldOutput.sourceGuides,subagentFiles:scaffoldOutput.subagentFiles,subagentManifestSpec:scaffoldOutput.subagentManifestSpec,surfacePacks:resolved.surfacePacks,toolBootstrapStatuses});const writtenAgentSystemPromptFile=capabilities.writeAgentSystemPrompt({content:renderedAgentSystemPrompt,outputDirectory:scaffoldOutput.outputDirectory});const result4={addedPacks:additions,agentHandoffFile:scaffoldOutput.agentHandoffFile,agentSystemPromptFile:writtenAgentSystemPromptFile,baseline:baseline.summary,contextPlan:scaffoldOutput.contextPlan,contextPlanFile:scaffoldOutput.contextPlanFile,cwd:scanDirectory,defaultPacks:resolved.defaultPacks,detectedLanguages:detection.detectedLanguages,detectedPacks:resolved.detectedPacks,detectedTechnologies:detection.detectedTechnologies,finalPacks,generatedFiles:[...scaffoldOutput.generatedFiles,writtenAgentSystemPromptFile],harnessFiles:scaffoldOutput.harnessFiles,hiddenOutputDirectories:scaffoldOutput.hiddenOutputDirectories,hookFiles:scaffoldOutput.hookFiles,languagePacks:resolved.languagePacks,lintAssets:scaffoldOutput.lintAssets,lintSpecFiles:scaffoldOutput.lintSpecFiles,managedFiles:scaffoldOutput.managedFiles,manifests:capabilities.manifestPaths(detection),monorepo:detection.monorepo,monorepoSignals:detection.monorepoSignals,opensrcReferences:scaffoldOutput.opensrcReferences,outputDirectory:scaffoldOutput.outputDirectory,projectionReceiptFile:scaffoldOutput.projectionReceiptFile,projectionStatus:scaffoldOutput.projectionStatus,promptOutputs:scaffoldOutput.promptOutputs,promptSpecFiles:scaffoldOutput.promptSpecFiles,promptSpecs:scaffoldOutput.promptSpecs,removedPacks:removals,repoShapeMode,scaffoldManifestFile:scaffoldOutput.scaffoldManifestFile,scriptFiles:scaffoldOutput.scriptFiles,skillFiles:scaffoldOutput.skillFiles,sourceGuideFiles:scaffoldOutput.sourceGuideFiles,sourceGuides:scaffoldOutput.sourceGuides,subagentFiles:scaffoldOutput.subagentFiles,subagentManifestSpec:scaffoldOutput.subagentManifestSpec,surfacePacks:resolved.surfacePacks,toolBootstrapStatuses};const clipboardResult=capabilities.copyToClipboard(renderedAgentSystemPrompt,{...clipboardRuntime,env:clipboardRuntime?.env??effectiveScriptEnvironment});yield*interaction.emit({_tag:"SetupComplete",baseline,clipboard:clipboardResult,emitJson,result:result4});yield*submitCliEventEffect("cli.scaffold.setup.completed",{baseline:{version:baseline.summary.version},configuration,cwd:scanDirectory});return result4});import{cpSync as cpSync2,existsSync as existsSync12,statSync as statSync2,mkdirSync as mkdirSync7,readFileSync as readFileSync12,readdirSync as readdirSync5,rmSync as rmSync5,symlinkSync as symlinkSync2,writeFileSync as writeFileSync7}from"node:fs";import path23 from"node:path";var nativeTypeScriptCompilerCommand=`node --input-type=module -e "await import(new URL('./bin/tsc', import.meta.resolve('@typescript/native/package.json')))" -- tsc`;var wikiFile=(path23,content)=>Object.fromEntries([["path",path23],["content",content]]);var tanstackReplacementPaths=new Set(["package.json",".gitignore","next.config.mjs","postcss.config.mjs","tsconfig.json","src/app/global.css","src/app/layout.tsx","src/app/(home)/layout.tsx","src/app/(home)/page.tsx","src/app/docs/layout.tsx","src/app/docs/[[...slug]]/page.tsx","src/app/og/docs/[...slug]/route.tsx","src/app/api/search/route.ts","src/lib/source.ts"]);var makeTanstackStartWikiFiles=()=>[{content:`{
|
|
390
390
|
"name": "@repo/wiki",
|
|
391
391
|
"version": "0.0.0",
|
|
392
392
|
"private": true,
|
|
@@ -1524,13 +1524,13 @@ Keep this framework pinned unless the user explicitly changes it. \`punks update
|
|
|
1524
1524
|
`;writeFileSync7(gitignorePath,`${contentWithTrailingNewline}${missingLines.join(`
|
|
1525
1525
|
`)}
|
|
1526
1526
|
`);return relativePosixPath2(outputDirectory,gitignorePath)};var hasFlatRoutePage=(directoryPath)=>existsSync12(`${directoryPath}.md`)||existsSync12(`${directoryPath}.mdx`);var isNestedRouteSeedBlockedByFlatPage=({wikiDirectory,filePath})=>{const normalized=filePath.split(path23.sep).join(path23.posix.sep);const match8=normalized.match(/^content\/docs\/project\/(?<project>[^/]+)\/(?:index\.mdx|meta\.json)$/u);const project2=match8?.groups?.project;if(project2===undefined){return false}return hasFlatRoutePage(path23.join(wikiDirectory,"content","docs","project",project2))};var appendCreatedFile=(createdFiles,createdFile)=>{if(createdFile!==null&&!createdFiles.includes(createdFile)){createdFiles.push(createdFile)}};var scaffoldWiki=({outputDirectory,wikiRoot,targetRoot,backlogProvider,wikiFramework})=>{const template=makeWikiScaffoldTemplate(wikiRoot,wikiFramework);const createdFiles=[];const wikiDirectory=path23.join(outputDirectory,targetRoot);for(const directory3 of template.topLevelDirectories){mkdirSync7(path23.join(wikiDirectory,directory3),{recursive:true})}for(const rawSubdirectory of template.rawSubdirectories){mkdirSync7(path23.join(wikiDirectory,"raw",rawSubdirectory),{recursive:true});const keepFile=path23.join(wikiDirectory,"raw",rawSubdirectory,".gitkeep");const createdFile=writeMissingFile({content:"",outputDirectory,targetPath:keepFile});appendCreatedFile(createdFiles,createdFile)}const directoryKeepFiles=[path23.join(wikiDirectory,"content","docs","project",".gitkeep"),path23.join(wikiDirectory,"specs",".gitkeep")];for(const keepFile of directoryKeepFiles){if(directoryHasEntries(path23.dirname(keepFile))){continue}const createdFile=writeMissingFile({content:"",outputDirectory,targetPath:keepFile});appendCreatedFile(createdFiles,createdFile)}for(const file5 of template.files){if(isNestedRouteSeedBlockedByFlatPage({filePath:file5.path,wikiDirectory})){continue}const writeFile3=file5.path==="scripts/sync-content.mjs"?writeManagedFile:writeMissingFile;const createdFile=writeFile3({content:file5.content,outputDirectory,targetPath:path23.join(wikiDirectory,file5.path)});appendCreatedFile(createdFiles,createdFile)}const updatedPackageFile=updateExistingWikiPackage({outputDirectory,packagePath:path23.join(wikiDirectory,"package.json"),wikiFramework});appendCreatedFile(createdFiles,updatedPackageFile);const updatedGitignoreFile=updateExistingWikiGitignore({expectedContent:template.files.find((file5)=>file5.path===".gitignore")?.content,gitignorePath:path23.join(wikiDirectory,".gitignore"),outputDirectory});appendCreatedFile(createdFiles,updatedGitignoreFile);if(wikiFramework==="tanstack-start"){const updatedViteConfig=updateExistingTanstackViteConfig({outputDirectory,viteConfigPath:path23.join(wikiDirectory,"vite.config.ts")});appendCreatedFile(createdFiles,updatedViteConfig)}const agentsPath=path23.join(wikiDirectory,"AGENTS.md");const agentsFile=writeMissingFile({content:template.agentsMarkdown,outputDirectory,targetPath:agentsPath});appendCreatedFile(createdFiles,agentsFile);const claudePath=path23.join(wikiDirectory,"CLAUDE.md");if(!existsSync12(claudePath)){symlinkSync2("AGENTS.md",claudePath);createdFiles.push(relativePosixPath2(outputDirectory,claudePath))}const indexPath=path23.join(wikiDirectory,"index.md");const indexFile=writeMissingFile({content:template.indexMarkdown,outputDirectory,targetPath:indexPath});appendCreatedFile(createdFiles,indexFile);const logPath=path23.join(wikiDirectory,"log.md");const logFile=writeMissingFile({content:template.logMarkdown,outputDirectory,targetPath:logPath});appendCreatedFile(createdFiles,logFile);const backlogProviderFile=writeMissingFile({content:renderBacklogProviderMarkdown(backlogProvider),outputDirectory,targetPath:path23.join(wikiDirectory,"backlog-provider.md")});appendCreatedFile(createdFiles,backlogProviderFile);const wikiFrameworkFile=writeMissingFile({content:renderWikiFrameworkMarkdown(wikiFramework),outputDirectory,targetPath:path23.join(wikiDirectory,"wiki-framework.md")});appendCreatedFile(createdFiles,wikiFrameworkFile);return createdFiles.toSorted()};var isWikiOutputDirectory=(outputDirectory)=>{const normalized=path23.resolve(outputDirectory);return path23.basename(normalized)==="wiki"};var appSurfacedWikiRoot="app/wiki";var wikiRootMarkerFiles=["package.json","backlog-provider.md","wiki-framework.md"];var isDirectory=(directoryPath)=>{try{return statSync2(directoryPath).isDirectory()}catch{return false}};var hasWikiRootMarkers=(directoryPath)=>wikiRootMarkerFiles.some((marker)=>existsSync12(path23.join(directoryPath,marker)));var hasRootWorkspaces=(outputDirectory)=>{const packagePath=path23.join(outputDirectory,"package.json");if(!existsSync12(packagePath)){return false}try{const packageJson=JSON.parse(readFileSync12(packagePath,"utf-8"));return packageJson.workspaces!==undefined}catch{return false}};var hasRootMonorepoSignals=(outputDirectory)=>existsSync12(path23.join(outputDirectory,"pnpm-workspace.yaml"))||existsSync12(path23.join(outputDirectory,"turbo.json"))||hasRootWorkspaces(outputDirectory);var hasAppPackageSurfaces=(outputDirectory)=>{if(hasRootMonorepoSignals(outputDirectory)){return false}const appDirectory=path23.join(outputDirectory,"app");if(!isDirectory(appDirectory)){return false}return readdirSync5(appDirectory,{withFileTypes:true}).some((entry)=>entry.isDirectory()&&existsSync12(path23.join(appDirectory,entry.name,"package.json")))};var stageWikiTarget=({outputDirectory,monorepo})=>{if(isWikiOutputDirectory(outputDirectory)){const parent=path23.basename(path23.dirname(path23.resolve(outputDirectory)));let wikiRoot="wiki";if(parent==="apps"){wikiRoot="apps/wiki"}else if(parent==="app"){wikiRoot=appSurfacedWikiRoot}return{targetRoot:".",wikiRoot}}if(!hasRootMonorepoSignals(outputDirectory)&&(hasWikiRootMarkers(path23.join(outputDirectory,appSurfacedWikiRoot))||hasAppPackageSurfaces(outputDirectory))){return{targetRoot:appSurfacedWikiRoot,wikiRoot:appSurfacedWikiRoot}}return{targetRoot:monorepo?"apps/wiki":"wiki",wikiRoot:monorepo?"apps/wiki":"wiki"}};var scaffoldWikiForDirectory=({outputDirectory,monorepo,wikiFramework="next"})=>{const wikiTarget=stageWikiTarget({monorepo,outputDirectory});return scaffoldWiki({backlogProvider:"github",outputDirectory,targetRoot:wikiTarget.targetRoot,wikiFramework,wikiRoot:wikiTarget.wikiRoot})};var runStageScaffold=({commandId,outputDirectory,interaction,baseline=bundledBaseline,configuration={disableBundledUrl:true},scriptRuntimePath:scriptRuntimePath2="node",scriptEnvironment={}})=>gen2(function*executeStageScaffold(){const projectSettings=yield*ProjectSettings;const stage=stageScaffoldById[commandId];const settings=yield*interaction.selectRepoSettings();const{backlogProvider,assetProviderSlug,backlogProjectUrl,repositoryManager}=settings;const wikiFramework=yield*interaction.selectWikiFramework();const detection=yield*detectRepository(outputDirectory).pipe(mapError3((cause)=>new CliValidationError({cause,message:`Could not inspect repository at ${outputDirectory}.`})));const scaffoldBaseline=baselineWithDefaultSkills(baseline);const finalPacks=defaultPackIdsForBaseline(scaffoldBaseline);const wikiTarget=stageWikiTarget({monorepo:detection.monorepo,outputDirectory});const wikiPromptTarget=wikiPromptTargetFor({targetRoot:wikiTarget.targetRoot,wikiFramework,wikiRoot:wikiTarget.wikiRoot});const contextPlan=yield*compileScaffoldContextPlan({additionalPromptTargets:[wikiPromptTarget],additionalScopes:wikiTarget.targetRoot==="."?[]:[{id:wikiTarget.targetRoot,kind:"docs",manifest:null,relativeWorkspacePath:wikiTarget.targetRoot}],baseline:scaffoldBaseline,detection,finalPacks,preserveExistingSubagentManifest:false,scanDirectory:outputDirectory}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})));const defaultSkills=skillIdsForContextPlan(contextPlan);const requiredTools=[...new Set([...requiredToolsForSkills2(defaultSkills,scaffoldBaseline),...requiredToolsForRepositoryManager2(repositoryManager)])].toSorted();const desiredSettings={assetProviderSlug,backlogProjectUrl,backlogProvider,baselineVersion:scaffoldBaseline.summary.version,cliVersion:version2,repositoryManager,requiredTools};const outputOptions={additionalPromptTargets:[wikiPromptTarget],baseline:scaffoldBaseline,contextPlan,detection,outputDirectory,repoShapeMode:"auto",scanDirectory:outputDirectory,scriptEnvironment,scriptRuntimePath:scriptRuntimePath2,settings:desiredSettings};const settingsDirectory=path23.join(outputDirectory,".devpunks");const settingsDirectoryExisted=existsSync12(settingsDirectory);const settingsInitialization={calculatedTools:{requiredTools},managedVersions:{baselineVersion:scaffoldBaseline.summary.version,cliVersion:version2},userChoices:{assetProviderSlug,backlogProjectUrl,backlogProvider,repositoryManager}};let settingsRollbackArmed=true;yield*projectSettings.initialize(outputDirectory,settingsInitialization).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})));return yield*gen2(function*applyInitializedStage(){const lifecycle=yield*runInitScaffoldLifecycle({apply:({desiredState})=>gen2(function*applyStageScaffold(){const projectedWikiFiles=[wikiPromptTarget.relativePath,path23.posix.join(wikiTarget.targetRoot,"CLAUDE.md")].filter((file5)=>!existsSync12(path23.join(outputDirectory,file5)));const scaffoldOutput2=yield*writeScaffoldOutput({...outputOptions,contextPlan:desiredState.contextPlan,desiredState,settings:desiredState.settings}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})));const wikiFiles2=yield*sync2(()=>[...new Set([...scaffoldWiki({outputDirectory,...wikiTarget,backlogProvider,wikiFramework}),...projectedWikiFiles.filter((file5)=>existsSync12(path23.join(outputDirectory,file5)))])].toSorted());return{scaffoldOutput:scaffoldOutput2,wikiFiles:wikiFiles2}}),gather:()=>planScaffoldOutput(outputOptions).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})),map7((plan)=>desiredScaffoldStateInput({...plan,settings:desiredSettings})))});if(lifecycle._tag==="ScaffoldLifecycleCompilationFailed"){return yield*new CliValidationError({cause:lifecycle.compilation,message:lifecycle.compilation.errors.map(({message})=>message).join(`
|
|
1527
|
-
`)})}const{scaffoldOutput,wikiFiles}=lifecycle.application;if(scaffoldOutput.projectionReceiptFile===null||scaffoldOutput.projectionStatus===null){return yield*new CliValidationError({message:"Init scaffold did not produce harness projection evidence."})}settingsRollbackArmed=false;const stageSkillFiles=stage.skills.map((skillId)=>copySkillDirectory({baseline,outputDirectory,skillId}));removeHarnessDirectoriesFromGitignore(outputDirectory);const skillFiles=[...new Set([...scaffoldOutput.skillFiles,...stageSkillFiles])].toSorted();const operatorPrompt=stage.renderPrompt({backlogProvider,wikiFramework,wikiRoot:wikiTarget.wikiRoot});writeAgentSystemPrompt({content:formatAgentHandoffSummary({addedPacks:[],agentHandoffFile:scaffoldOutput.agentHandoffFile,agentSystemPromptFile:agentSystemPromptFile3,baseline:scaffoldBaseline.summary,contextPlan:scaffoldOutput.contextPlan,contextPlanFile:scaffoldOutput.contextPlanFile,cwd:outputDirectory,defaultPacks:finalPacks,detectedLanguages:detection.detectedLanguages,detectedPacks:[],detectedTechnologies:detection.detectedTechnologies,finalPacks,generatedFiles:[...scaffoldOutput.generatedFiles,agentSystemPromptFile3].toSorted(),harnessFiles:scaffoldOutput.harnessFiles,hiddenOutputDirectories:scaffoldOutput.hiddenOutputDirectories,hookFiles:scaffoldOutput.hookFiles,languagePacks:[],lintAssets:scaffoldOutput.lintAssets,lintSpecFiles:scaffoldOutput.lintSpecFiles,managedFiles:scaffoldOutput.managedFiles,manifests:detection.manifests.map((manifest)=>path23.relative(detection.cwd,manifest.path)||"package.json"),monorepo:detection.monorepo,monorepoSignals:detection.monorepoSignals,opensrcReferences:scaffoldOutput.opensrcReferences,outputDirectory:scaffoldOutput.outputDirectory,projectionReceiptFile:scaffoldOutput.projectionReceiptFile,projectionStatus:scaffoldOutput.projectionStatus,promptOutputs:scaffoldOutput.promptOutputs,promptSpecFiles:scaffoldOutput.promptSpecFiles,promptSpecs:scaffoldOutput.promptSpecs,removedPacks:[],repoShapeMode:"auto",scaffoldManifestFile:scaffoldOutput.scaffoldManifestFile,scriptFiles:scaffoldOutput.scriptFiles,skillFiles,sourceGuideFiles:scaffoldOutput.sourceGuideFiles,sourceGuides:scaffoldOutput.sourceGuides,subagentFiles:scaffoldOutput.subagentFiles,subagentManifestSpec:scaffoldOutput.subagentManifestSpec,surfacePacks:[],toolBootstrapStatuses:[]}),outputDirectory});yield*interaction.emit({_tag:"InitComplete",commandId,hiddenOutputDirectories:scaffoldOutput.hiddenOutputDirectories,operatorPrompt,outputDirectory,settings,skillFiles,summary:stage.summary,wikiFiles,wikiFramework});yield*submitCliEventEffect("cli.scaffold.init.completed",{baseline:{version:baseline.summary.version},configuration,cwd:outputDirectory});return{assetProviderSlug,backlogProjectUrl,backlogProvider,contextPlan:scaffoldOutput.contextPlan,contextPlanFile:scaffoldOutput.contextPlanFile,outputDirectory,projectionReceiptFile:scaffoldOutput.projectionReceiptFile,projectionStatus:scaffoldOutput.projectionStatus,repositoryManager,skillFiles,wikiFiles,wikiFramework}}).pipe(onError2(()=>gen2(function*rollbackInitializedStage(){if(!settingsRollbackArmed){return}yield*projectSettings.rollbackInitialization(outputDirectory,{initialization:settingsInitialization,removeSettingsDirectory:!settingsDirectoryExisted}).pipe(result2)})))});import{existsSync as existsSync13}from"node:fs";import path24 from"node:path";var findOperatorProjectRoot=(cwd)=>{let directory3=path24.resolve(cwd);const filesystemRoot=path24.parse(directory3).root;while(true){if(existsSync13(path24.join(directory3,".git"))){return directory3}if(directory3===filesystemRoot){return path24.resolve(cwd)}directory3=path24.dirname(directory3)}};var resolveActiveOperatorAgent=(environment)=>{const configured=environment.HI_OPERATOR_AGENT?.trim();if(configured!==undefined&&configured.length>0){return configured.toLowerCase().replaceAll(/[_\s]+/gu,"-")}if(environment.CLAUDE_CODE!==undefined||environment.CLAUDE_PROJECT_DIR!==undefined){return"claude-code"}if(environment.CODEX_HOME!==undefined||environment.CODEX_THREAD_ID!==undefined){return"codex"}return};import{createHash as createHash7}from"node:crypto";import{spawnSync as spawnSync3}from"node:child_process";import{chmodSync as chmodSync2,cpSync as cpSync3,existsSync as existsSync14,lstatSync as lstatSync4,mkdirSync as mkdirSync8,mkdtempSync as mkdtempSync3,realpathSync as realpathSync3,readdirSync as readdirSync6,readFileSync as readFileSync13,readlinkSync as readlinkSync3,rmSync as rmSync6,symlinkSync as symlinkSync3,writeFileSync as writeFileSync8}from"node:fs";import{tmpdir as tmpdir6}from"node:os";import path25 from"node:path";import{createHash as createHash6}from"node:crypto";var nodeScaffoldContentHasher={sha256:(file5)=>{const{content:fileContent,encoding}=file5;let content=fileContent;if(encoding==="base64"){content=Buffer.from(fileContent,"base64")}else if(encoding==="symlink"){content=`symlink:${fileContent}`}return createHash6("sha256").update(content).digest("hex")}};var scaffoldManifestFile=".devpunks/scaffold-manifest.json";var agentHandoffFile=".devpunks/AGENT-HANDOFF.md";var agentSystemPromptFile4=".devpunks/AGENT-SYSTEM-PROMPT.md";var legacyRequiredToolsFile=".devpunks/required-tools.json";var repoSettingsDisplayFile=".devpunks/settings.json";var encodeJson4=encodeSync2(fromJsonString2(Unknown2));var encodePrettyJson3=(value5)=>JSON.stringify(JSON.parse(encodeJson4(value5)),null,2);var updateCompleteMessage=({applyRequested,hasManagedUpdates})=>{if(applyRequested&&hasManagedUpdates){return"Managed scaffold files updated."}if(applyRequested){return"No managed scaffold changes were needed."}return"No files were written."};var managedFileSchema=Struct({kind:ScaffoldManagedFileKind,path:String5,sha256:String5});var managedDependencyReceiptSchema=Struct({name:String5,section:Literals(["dependencies","devDependencies","peerDependencies"]),version:String5,workspace:String5});var managedStructuredEntryKindSchema=Literals(["field","key"]);var managedStructuredEntryReceiptSchema=Struct({file:String5,kind:managedStructuredEntryKindSchema,path:ArraySchema(String5),value:Unknown2});var scaffoldManifestSchema=fromJsonString2(Struct({baseline:optional(Unknown2),finalPacks:ArraySchema(String5),generatedFiles:optional(ArraySchema(String5)),managedDependencies:optional(ArraySchema(managedDependencyReceiptSchema)),managedFileModes:optional(Record(String5,Union2([Number6,Null2]))),managedFileTypes:optional(Record(String5,Literals(["file","symlink"]))),managedFiles:optional(ArraySchema(managedFileSchema)),managedStructuredEntries:optional(ArraySchema(managedStructuredEntryReceiptSchema)),repoShapeMode:optional(String5),version:optional(String5)}));var ownershipMetadataOperationChanges=({allChanges,applied,required:required2})=>{if(!required2||allChanges.some(({path:relativePath})=>relativePath===scaffoldManifestFile)){return[]}return[{action:"update",state:applied?"completed":"planned",subject:scaffoldManifestFile}]};var noopHumanOutput=(_line)=>void_3;var parseManifest=decodeUnknownSync2(scaffoldManifestSchema);var hashContent2=(content)=>createHash7("sha256").update(content).digest("hex");var fileMode2=(mode)=>mode%512;var normalizeRepoShapeMode=(value5)=>value5==="monorepo"||value5==="single"?value5:"auto";var normalizePacks=(values3,baseline)=>{const known=new Set(baseline.packs.map((pack)=>pack.id));const unknown2=values3.filter((value5)=>!known.has(value5));if(unknown2.length>0){throw new Error(`Unknown packs in ${scaffoldManifestFile}: ${unknown2.join(", ")}`)}return[...new Set(values3)].toSorted()};var selectedSkills3=(finalPacks,baseline)=>[...new Set(finalPacks.flatMap((packId)=>skillsForPack(packId,baseline)))].toSorted();var readManifest=(rootDirectory)=>{const manifestPath=path25.join(rootDirectory,scaffoldManifestFile);if(!existsSync14(manifestPath)){throw new Error(`Missing ${scaffoldManifestFile}. Run \`hi scaffold\` first.`)}return parseManifest(readFileSync13(manifestPath,"utf-8"))};var pathLexists=(absolutePath)=>{try{lstatSync4(absolutePath);return true}catch(error2){if(error2.code==="ENOENT"){return false}throw error2}};var resolveContainedReceiptPath=(rootDirectory,relativePath,{followLeaf=true}={})=>{const absoluteRoot=path25.resolve(rootDirectory);const absolutePath=path25.resolve(absoluteRoot,relativePath);const lexicalRelative=path25.relative(absoluteRoot,absolutePath);if(absolutePath===absoluteRoot||path25.isAbsolute(relativePath)||lexicalRelative===".."||lexicalRelative.startsWith(`..${path25.sep}`)||path25.isAbsolute(lexicalRelative)){throw new Error(`Managed receipt path escapes scaffold root: ${relativePath}`)}let existingPath=followLeaf?absolutePath:path25.dirname(absolutePath);while(!pathLexists(existingPath)){const parent=path25.dirname(existingPath);if(parent===existingPath){throw new Error(`Managed receipt path escapes scaffold root: ${relativePath}`)}existingPath=parent}const realRoot=realpathSync3(absoluteRoot);const realExistingPath=realpathSync3(existingPath);const realRelative=path25.relative(realRoot,realExistingPath);if(realRelative===".."||realRelative.startsWith(`..${path25.sep}`)||path25.isAbsolute(realRelative)){throw new Error(`Managed receipt path escapes scaffold root: ${relativePath}`)}return absolutePath};var resolveMutableJsonPath=(rootDirectory,relativePath)=>{const absolutePath=resolveContainedReceiptPath(rootDirectory,relativePath);if(pathLexists(absolutePath)&&lstatSync4(absolutePath).isSymbolicLink()){throw new Error(`Mutable JSON path must not be a symbolic link: ${relativePath}`)}return absolutePath};var stableJsonStringify=(value5)=>{if(Array.isArray(value5)){return`[${value5.map(stableJsonStringify).join(",")}]`}if(value5!==null&&typeof value5==="object"){const entries3=Object.entries(value5).toSorted(([left],[right])=>left.localeCompare(right));return`{${entries3.map(([key,entryValue])=>`${JSON.stringify(key)}:${stableJsonStringify(entryValue)}`).join(",")}}`}return JSON.stringify(value5)};var lifecycleHookCommand=(value5)=>{if(typeof value5!=="object"||value5===null||Array.isArray(value5)){return}const record3=value5;if(typeof record3.command==="string"){return record3.command}if(Array.isArray(record3.hooks)){return record3.hooks.map(lifecycleHookCommand).find((command)=>command!==undefined)}};var managedLifecycleHook=(entry)=>{if(entry.path.length!==2||entry.path[0]!=="hooks"||!Array.isArray(entry.value)){return}const value5=entry.value.length===1?entry.value[0]:undefined;const command=lifecycleHookCommand(value5);return command===undefined?undefined:{command,value:value5}};var contentForDiff=(rootDirectory,relativePath)=>{const absolutePath=path25.join(rootDirectory,relativePath);if(!pathLexists(absolutePath)){return""}const stat3=lstatSync4(absolutePath);if(stat3.isSymbolicLink()){return`symlink:${readlinkSync3(absolutePath)}
|
|
1527
|
+
`)})}const{scaffoldOutput,wikiFiles}=lifecycle.application;if(scaffoldOutput.projectionReceiptFile===null||scaffoldOutput.projectionStatus===null){return yield*new CliValidationError({message:"Init scaffold did not produce harness projection evidence."})}settingsRollbackArmed=false;const stageSkillFiles=stage.skills.map((skillId)=>copySkillDirectory({baseline,outputDirectory,skillId}));removeHarnessDirectoriesFromGitignore(outputDirectory);const skillFiles=[...new Set([...scaffoldOutput.skillFiles,...stageSkillFiles])].toSorted();const operatorPrompt=stage.renderPrompt({backlogProvider,wikiFramework,wikiRoot:wikiTarget.wikiRoot});writeAgentSystemPrompt({content:formatAgentHandoffSummary({addedPacks:[],agentHandoffFile:scaffoldOutput.agentHandoffFile,agentSystemPromptFile:agentSystemPromptFile3,baseline:scaffoldBaseline.summary,contextPlan:scaffoldOutput.contextPlan,contextPlanFile:scaffoldOutput.contextPlanFile,cwd:outputDirectory,defaultPacks:finalPacks,detectedLanguages:detection.detectedLanguages,detectedPacks:[],detectedTechnologies:detection.detectedTechnologies,finalPacks,generatedFiles:[...scaffoldOutput.generatedFiles,agentSystemPromptFile3].toSorted(),harnessFiles:scaffoldOutput.harnessFiles,hiddenOutputDirectories:scaffoldOutput.hiddenOutputDirectories,hookFiles:scaffoldOutput.hookFiles,languagePacks:[],lintAssets:scaffoldOutput.lintAssets,lintSpecFiles:scaffoldOutput.lintSpecFiles,managedFiles:scaffoldOutput.managedFiles,manifests:detection.manifests.map((manifest)=>path23.relative(detection.cwd,manifest.path)||"package.json"),monorepo:detection.monorepo,monorepoSignals:detection.monorepoSignals,opensrcReferences:scaffoldOutput.opensrcReferences,outputDirectory:scaffoldOutput.outputDirectory,projectionReceiptFile:scaffoldOutput.projectionReceiptFile,projectionStatus:scaffoldOutput.projectionStatus,promptOutputs:scaffoldOutput.promptOutputs,promptSpecFiles:scaffoldOutput.promptSpecFiles,promptSpecs:scaffoldOutput.promptSpecs,removedPacks:[],repoShapeMode:"auto",scaffoldManifestFile:scaffoldOutput.scaffoldManifestFile,scriptFiles:scaffoldOutput.scriptFiles,skillFiles,sourceGuideFiles:scaffoldOutput.sourceGuideFiles,sourceGuides:scaffoldOutput.sourceGuides,subagentFiles:scaffoldOutput.subagentFiles,subagentManifestSpec:scaffoldOutput.subagentManifestSpec,surfacePacks:[],toolBootstrapStatuses:[]}),outputDirectory});yield*interaction.emit({_tag:"InitComplete",commandId,hiddenOutputDirectories:scaffoldOutput.hiddenOutputDirectories,operatorPrompt,outputDirectory,settings,skillFiles,summary:stage.summary,wikiFiles,wikiFramework});yield*submitCliEventEffect("cli.scaffold.init.completed",{baseline:{version:baseline.summary.version},configuration,cwd:outputDirectory});return{assetProviderSlug,backlogProjectUrl,backlogProvider,contextPlan:scaffoldOutput.contextPlan,contextPlanFile:scaffoldOutput.contextPlanFile,outputDirectory,projectionReceiptFile:scaffoldOutput.projectionReceiptFile,projectionStatus:scaffoldOutput.projectionStatus,repositoryManager,skillFiles,wikiFiles,wikiFramework}}).pipe(onError2(()=>gen2(function*rollbackInitializedStage(){if(!settingsRollbackArmed){return}yield*projectSettings.rollbackInitialization(outputDirectory,{initialization:settingsInitialization,removeSettingsDirectory:!settingsDirectoryExisted}).pipe(result2)})))});import{existsSync as existsSync13}from"node:fs";import path24 from"node:path";var findOperatorProjectRoot=(cwd)=>{let directory3=path24.resolve(cwd);const filesystemRoot=path24.parse(directory3).root;while(true){if(existsSync13(path24.join(directory3,".git"))){return directory3}if(directory3===filesystemRoot){return path24.resolve(cwd)}directory3=path24.dirname(directory3)}};var resolveActiveOperatorAgent=(environment,fallback)=>{const configured=environment.HI_OPERATOR_AGENT?.trim();if(configured!==undefined&&configured.length>0){return configured.toLowerCase().replaceAll(/[_\s]+/gu,"-")}if(environment.CLAUDE_CODE!==undefined||environment.CLAUDE_PROJECT_DIR!==undefined){return"claude-code"}if(environment.CODEX_HOME!==undefined||environment.CODEX_THREAD_ID!==undefined){return"codex"}const selected=fallback?.trim();return selected===undefined||selected.length===0?undefined:selected.toLowerCase().replaceAll(/[_\s]+/gu,"-")};import{createHash as createHash7}from"node:crypto";import{spawnSync as spawnSync3}from"node:child_process";import{chmodSync as chmodSync2,cpSync as cpSync3,existsSync as existsSync14,lstatSync as lstatSync4,mkdirSync as mkdirSync8,mkdtempSync as mkdtempSync3,realpathSync as realpathSync3,readdirSync as readdirSync6,readFileSync as readFileSync13,readlinkSync as readlinkSync3,rmSync as rmSync6,symlinkSync as symlinkSync3,writeFileSync as writeFileSync8}from"node:fs";import{tmpdir as tmpdir6}from"node:os";import path25 from"node:path";import{createHash as createHash6}from"node:crypto";var nodeScaffoldContentHasher={sha256:(file5)=>{const{content:fileContent,encoding}=file5;let content=fileContent;if(encoding==="base64"){content=Buffer.from(fileContent,"base64")}else if(encoding==="symlink"){content=`symlink:${fileContent}`}return createHash6("sha256").update(content).digest("hex")}};var scaffoldManifestFile=".devpunks/scaffold-manifest.json";var agentHandoffFile=".devpunks/AGENT-HANDOFF.md";var agentSystemPromptFile4=".devpunks/AGENT-SYSTEM-PROMPT.md";var legacyRequiredToolsFile=".devpunks/required-tools.json";var repoSettingsDisplayFile=".devpunks/settings.json";var encodeJson4=encodeSync2(fromJsonString2(Unknown2));var encodePrettyJson3=(value5)=>JSON.stringify(JSON.parse(encodeJson4(value5)),null,2);var updateCompleteMessage=({applyRequested,hasManagedUpdates})=>{if(applyRequested&&hasManagedUpdates){return"Managed scaffold files updated."}if(applyRequested){return"No managed scaffold changes were needed."}return"No files were written."};var managedFileSchema=Struct({kind:ScaffoldManagedFileKind,path:String5,sha256:String5});var managedDependencyReceiptSchema=Struct({name:String5,section:Literals(["dependencies","devDependencies","peerDependencies"]),version:String5,workspace:String5});var managedStructuredEntryKindSchema=Literals(["field","key"]);var managedStructuredEntryReceiptSchema=Struct({file:String5,kind:managedStructuredEntryKindSchema,path:ArraySchema(String5),value:Unknown2});var scaffoldManifestSchema=fromJsonString2(Struct({baseline:optional(Unknown2),finalPacks:ArraySchema(String5),generatedFiles:optional(ArraySchema(String5)),managedDependencies:optional(ArraySchema(managedDependencyReceiptSchema)),managedFileModes:optional(Record(String5,Union2([Number6,Null2]))),managedFileTypes:optional(Record(String5,Literals(["file","symlink"]))),managedFiles:optional(ArraySchema(managedFileSchema)),managedStructuredEntries:optional(ArraySchema(managedStructuredEntryReceiptSchema)),repoShapeMode:optional(String5),version:optional(String5)}));var ownershipMetadataOperationChanges=({allChanges,applied,required:required2})=>{if(!required2||allChanges.some(({path:relativePath})=>relativePath===scaffoldManifestFile)){return[]}return[{action:"update",state:applied?"completed":"planned",subject:scaffoldManifestFile}]};var noopHumanOutput=(_line)=>void_3;var parseManifest=decodeUnknownSync2(scaffoldManifestSchema);var hashContent2=(content)=>createHash7("sha256").update(content).digest("hex");var fileMode2=(mode)=>mode%512;var normalizeRepoShapeMode=(value5)=>value5==="monorepo"||value5==="single"?value5:"auto";var normalizePacks=(values3,baseline)=>{const known=new Set(baseline.packs.map((pack)=>pack.id));const unknown2=values3.filter((value5)=>!known.has(value5));if(unknown2.length>0){throw new Error(`Unknown packs in ${scaffoldManifestFile}: ${unknown2.join(", ")}`)}return[...new Set(values3)].toSorted()};var selectedSkills3=(finalPacks,baseline)=>[...new Set(finalPacks.flatMap((packId)=>skillsForPack(packId,baseline)))].toSorted();var readManifest=(rootDirectory)=>{const manifestPath=path25.join(rootDirectory,scaffoldManifestFile);if(!existsSync14(manifestPath)){throw new Error(`Missing ${scaffoldManifestFile}. Run \`hi scaffold\` first.`)}return parseManifest(readFileSync13(manifestPath,"utf-8"))};var pathLexists=(absolutePath)=>{try{lstatSync4(absolutePath);return true}catch(error2){if(error2.code==="ENOENT"){return false}throw error2}};var resolveContainedReceiptPath=(rootDirectory,relativePath,{followLeaf=true}={})=>{const absoluteRoot=path25.resolve(rootDirectory);const absolutePath=path25.resolve(absoluteRoot,relativePath);const lexicalRelative=path25.relative(absoluteRoot,absolutePath);if(absolutePath===absoluteRoot||path25.isAbsolute(relativePath)||lexicalRelative===".."||lexicalRelative.startsWith(`..${path25.sep}`)||path25.isAbsolute(lexicalRelative)){throw new Error(`Managed receipt path escapes scaffold root: ${relativePath}`)}let existingPath=followLeaf?absolutePath:path25.dirname(absolutePath);while(!pathLexists(existingPath)){const parent=path25.dirname(existingPath);if(parent===existingPath){throw new Error(`Managed receipt path escapes scaffold root: ${relativePath}`)}existingPath=parent}const realRoot=realpathSync3(absoluteRoot);const realExistingPath=realpathSync3(existingPath);const realRelative=path25.relative(realRoot,realExistingPath);if(realRelative===".."||realRelative.startsWith(`..${path25.sep}`)||path25.isAbsolute(realRelative)){throw new Error(`Managed receipt path escapes scaffold root: ${relativePath}`)}return absolutePath};var resolveMutableJsonPath=(rootDirectory,relativePath)=>{const absolutePath=resolveContainedReceiptPath(rootDirectory,relativePath);if(pathLexists(absolutePath)&&lstatSync4(absolutePath).isSymbolicLink()){throw new Error(`Mutable JSON path must not be a symbolic link: ${relativePath}`)}return absolutePath};var stableJsonStringify=(value5)=>{if(Array.isArray(value5)){return`[${value5.map(stableJsonStringify).join(",")}]`}if(value5!==null&&typeof value5==="object"){const entries3=Object.entries(value5).toSorted(([left],[right])=>left.localeCompare(right));return`{${entries3.map(([key,entryValue])=>`${JSON.stringify(key)}:${stableJsonStringify(entryValue)}`).join(",")}}`}return JSON.stringify(value5)};var lifecycleHookCommand=(value5)=>{if(typeof value5!=="object"||value5===null||Array.isArray(value5)){return}const record3=value5;if(typeof record3.command==="string"){return record3.command}if(Array.isArray(record3.hooks)){return record3.hooks.map(lifecycleHookCommand).find((command)=>command!==undefined)}};var managedLifecycleHook=(entry)=>{if(entry.path.length!==2||entry.path[0]!=="hooks"||!Array.isArray(entry.value)){return}const value5=entry.value.length===1?entry.value[0]:undefined;const command=lifecycleHookCommand(value5);return command===undefined?undefined:{command,value:value5}};var contentForDiff=(rootDirectory,relativePath)=>{const absolutePath=path25.join(rootDirectory,relativePath);if(!pathLexists(absolutePath)){return""}const stat3=lstatSync4(absolutePath);if(stat3.isSymbolicLink()){return`symlink:${readlinkSync3(absolutePath)}
|
|
1528
1528
|
`}return readFileSync13(absolutePath,"utf-8")};var jsonContentEquals=(left,right)=>{try{return stableJsonStringify(JSON.parse(left))===stableJsonStringify(JSON.parse(right))}catch{return false}};var hashPath=(rootDirectory,relativePath)=>{const absolutePath=path25.join(rootDirectory,relativePath);if(!pathLexists(absolutePath)){return null}const stat3=lstatSync4(absolutePath);const content=stat3.isSymbolicLink()?`symlink:${readlinkSync3(absolutePath)}`:readFileSync13(absolutePath);return hashContent2(content)};var ignoredWikiAlignmentRootDirectoryNames=new Set([".next",".nitro",".output",".source",".tanstack",".turbo","build","coverage","dist","node_modules"]);var hasIgnoredWikiAlignmentRootDirectory=(relativePath)=>{const firstSegment=relativePath.split("/").find(Boolean);return firstSegment!==undefined&&ignoredWikiAlignmentRootDirectoryNames.has(firstSegment)};var wikiAlignmentRootDirectories=["apps/wiki","app/wiki","wiki"];var hasIgnoredWikiAlignmentPath=(relativePath)=>wikiAlignmentRootDirectories.some((wikiRoot)=>{const prefix=`${wikiRoot}/`;return relativePath.startsWith(prefix)&&hasIgnoredWikiAlignmentRootDirectory(relativePath.slice(prefix.length))});var collectRelativeFiles2=(rootDirectory,relativeDirectory)=>{const absoluteDirectory=path25.join(rootDirectory,relativeDirectory);if(!existsSync14(absoluteDirectory)){return[]}const files=[];const visit2=(currentDirectory)=>{for(const entry of readdirSync6(currentDirectory,{withFileTypes:true})){const absolutePath=path25.join(currentDirectory,entry.name);const relativePath=path25.relative(rootDirectory,absolutePath).split(path25.sep).join("/");const wikiRelativePath=path25.relative(absoluteDirectory,absolutePath).split(path25.sep).join("/");if(hasIgnoredWikiAlignmentRootDirectory(wikiRelativePath)){continue}if(entry.isDirectory()){visit2(absolutePath);continue}if(entry.isFile()||entry.isSymbolicLink()){files.push(relativePath)}}};visit2(absoluteDirectory);return files.toSorted()};var copyManagedFile=({fromDirectory,toDirectory,relativePath})=>{const sourcePath=path25.join(fromDirectory,relativePath);const targetPath=path25.join(toDirectory,relativePath);const stat3=lstatSync4(sourcePath);mkdirSync8(path25.dirname(targetPath),{recursive:true});if(existsSync14(targetPath)){rmSync6(targetPath,{force:true,recursive:true})}if(stat3.isSymbolicLink()){symlinkSync3(readlinkSync3(sourcePath),targetPath);return}cpSync3(sourcePath,targetPath,{force:true})};var hasActionablePackDrift=({finalPacks,resolvedPacks})=>{const recorded=new Set(finalPacks);return resolvedPacks.some((pack)=>!recorded.has(pack))};var acceptResolvedPacks=({baseline,finalPacks,resolvedPacks})=>{const recorded=new Set(finalPacks);const acceptedCategories=new Set(["default","detected"]);const acceptedPackIds=new Set(baseline.packs.filter((pack)=>acceptedCategories.has(pack.category)).map((pack)=>pack.id));const accepted=resolvedPacks.filter((pack)=>!recorded.has(pack)&&acceptedPackIds.has(pack));return[...new Set([...finalPacks,...accepted])].toSorted()};var summarizeCounts2=(changes)=>{const rows=new Map;for(const change of changes){const key=`${change.status} ${change.kind}`;rows.set(key,(rows.get(key)??0)+1)}return[...rows.entries()].toSorted(([left],[right])=>left.localeCompare(right)).map(([label,count])=>`• ${label}: ${count}`)};var summarizeChanges2=(changes)=>{if(changes.length===0){return"No managed file changes."}const sampleSize=20;const sample2=changes.slice(0,sampleSize);const remaining=changes.length-sample2.length;return[`Total changed managed files: ${changes.length}`,"","By status/kind:",...summarizeCounts2(changes),"","Sample:",...sample2.map((change)=>`• ${change.path} (${change.status})`),...remaining>0?[`• ... ${remaining} more omitted from terminal summary`]:[]].join(`
|
|
1529
1529
|
`)};var summarizeStaleFiles2=(staleFiles)=>{const sampleSize=20;const sample2=staleFiles.slice(0,sampleSize);const remaining=staleFiles.length-sample2.length;return[`Total stale managed files: ${staleFiles.length}`,"",...sample2.map((file5)=>`• ${file5}`),...remaining>0?[`• ... ${remaining} more omitted from terminal summary`]:[]].join(`
|
|
1530
1530
|
`)};var packDriftPrompt=({rootDirectory,finalPacks,resolvedPacks})=>["You are updating a repo whose current package manifests resolve to a different punks pack set than the recorded scaffold manifest.","",`Repo root: ${rootDirectory}`,`Recorded packs: ${finalPacks.join(", ")}`,`Currently resolved packs: ${resolvedPacks.join(", ")}`,"","Run `hi scaffold` from the repo root and intentionally accept/edit the new pack selection. Then inspect the generated prompt specs, skills, hooks, and subagent manifests before continuing product work."].join(`
|
|
1531
1531
|
`);var buildChanges=({rootDirectory,expectedDirectory,expectedFiles,previousFiles})=>{const previousByPath=new Map(previousFiles.map((file5)=>[file5.path,file5]));return expectedFiles.flatMap((expected)=>{const currentHash=hashPath(rootDirectory,expected.path);if(currentHash===expected.sha256){return[]}if(currentHash!==null&&expected.path.endsWith(".json")&&jsonContentEquals(contentForDiff(rootDirectory,expected.path),contentForDiff(expectedDirectory,expected.path))){return[]}const previous=previousByPath.get(expected.path);let status2="changed";if(currentHash===null){status2="missing"}else if(previous!==undefined&¤tHash!==previous.sha256){status2="local-edited"}return[{kind:expected.kind,path:expected.path,status:status2}]}).toSorted((left,right)=>left.path.localeCompare(right.path))};var syncSubagentsScriptFile=".agents/scripts/sync-subagents.mjs";var projectAuthoredWikiSyncFile="apps/wiki/scripts/sync-content.mjs";var isWikiManagedPath=(relativePath)=>relativePath.startsWith("wiki/")||relativePath.startsWith("app/wiki/")||relativePath.startsWith("apps/wiki/");var canonicalClaudePromptSource=(relativePath)=>relativePath===".claude/CLAUDE.md"?".agents/AGENTS.md":path25.posix.join(path25.posix.dirname(relativePath),"AGENTS.md");var isConsumerOwnedClaudePrompt=({relativePath,rootDirectory,previousFile,recordedFileType})=>{if(path25.posix.basename(relativePath)!=="CLAUDE.md"){return false}const absolutePath=path25.join(rootDirectory,relativePath);const targetExists=pathLexists(absolutePath);if(targetExists&&lstatSync4(absolutePath).isSymbolicLink()){const currentHash=hashPath(rootDirectory,relativePath);const canonicalTarget=path25.relative(path25.dirname(absolutePath),path25.join(rootDirectory,canonicalClaudePromptSource(relativePath)));return previousFile===undefined||recordedFileType!==undefined&&recordedFileType!=="symlink"||(currentHash===null?readlinkSync3(absolutePath)!==canonicalTarget:currentHash!==previousFile.sha256)}return targetExists&&!lstatSync4(absolutePath).isSymbolicLink()&&(previousFile===undefined||recordedFileType!=="file"||hashPath(rootDirectory,relativePath)!==previousFile.sha256)};var isManagedClaudePromptCopy=({relativePath,rootDirectory,previousFile,recordedFileType})=>{if(path25.posix.basename(relativePath)!=="CLAUDE.md"||previousFile===undefined||recordedFileType!==undefined&&recordedFileType!=="file"){return false}const targetPath=path25.join(rootDirectory,relativePath);const sourceRelativePath=canonicalClaudePromptSource(relativePath);const sourcePath=path25.join(rootDirectory,sourceRelativePath);return existsSync14(targetPath)&&lstatSync4(targetPath).isFile()&&existsSync14(sourcePath)&&lstatSync4(sourcePath).isFile()&&hashPath(rootDirectory,relativePath)===previousFile.sha256&&(recordedFileType==="file"||hashContent2(readFileSync13(targetPath))===hashContent2(readFileSync13(sourcePath)))};var isTailoredSyncSubagentsScript=(rootDirectory)=>{const scriptPath=path25.join(rootDirectory,syncSubagentsScriptFile);if(!existsSync14(scriptPath)){return false}const content=readFileSync13(scriptPath,"utf-8");return/["'`](?:app|apps|packages|infra)\//u.test(content)};var isProjectAuthoredManagedFile=({file:file5,rootDirectory})=>{if(file5.path===projectAuthoredWikiSyncFile){return existsSync14(path25.join(rootDirectory,file5.path))}if(file5.path===".agents/scripts/sync-subagents.mjs"){return isTailoredSyncSubagentsScript(rootDirectory)}if(file5.kind==="agent-prompt"||file5.kind==="handoff"||file5.kind==="manifest"||file5.kind==="prompt-spec"||file5.kind==="subagent"){return true}return file5.path===".claude/CLAUDE.md"||file5.path===".codex/AGENTS.md"||file5.path===".opencode/AGENTS.md"||file5.path.startsWith(".claude/agents/")||file5.path.startsWith(".codex/agents/")||file5.path.startsWith(".cursor/agents/")||file5.path.startsWith(".opencode/agents/")};var buildLegacyRequiredToolsPromptChanges=({rootDirectory})=>{const promptFiles=[agentHandoffFile,agentSystemPromptFile4];return promptFiles.flatMap((promptFile)=>{const absolutePath=path25.join(rootDirectory,promptFile);if(!existsSync14(absolutePath)){return[]}const current=readFileSync13(absolutePath,"utf-8");if(!current.includes(legacyRequiredToolsFile)){return[]}return[{kind:"handoff",path:promptFile,status:"local-edited"}]})};var rewriteLegacyRequiredToolsPrompt=({rootDirectory,relativePath})=>{const absolutePath=path25.join(rootDirectory,relativePath);if(!existsSync14(absolutePath)){return}const current=readFileSync13(absolutePath,"utf-8");if(!current.includes(legacyRequiredToolsFile)){return}writeFileSync8(absolutePath,current.replaceAll(legacyRequiredToolsFile,repoSettingsDisplayFile))};var copyIfExists=({rootDirectory,targetDirectory,relativePath,ignoreGeneratedRootDirectories=false})=>{const sourcePath=path25.join(rootDirectory,relativePath);if(!existsSync14(sourcePath)){return}const targetPath=path25.join(targetDirectory,relativePath);const stat3=lstatSync4(sourcePath);mkdirSync8(path25.dirname(targetPath),{recursive:true});if(stat3.isSymbolicLink()){symlinkSync3(readlinkSync3(sourcePath),targetPath);return}cpSync3(sourcePath,targetPath,{filter:(source)=>{const relativeSource=path25.relative(sourcePath,source).split(path25.sep).join("/");return!ignoreGeneratedRootDirectories||!hasIgnoredWikiAlignmentRootDirectory(relativeSource)},recursive:true,verbatimSymlinks:true})};var readWikiFrameworkPin=(wikiDirectory)=>{const pinPath=path25.join(wikiDirectory,"wiki-framework.md");if(!existsSync14(pinPath)){return"next"}const content=readFileSync13(pinPath,"utf-8");if(content.includes("`tanstack-start`")){return"tanstack-start"}if(content.includes("`next`")){return"next"}return"next"};var wikiRootForAlignment=(rootDirectory,detection,hasRootMarkers)=>{if(hasRootMarkers("apps/wiki")){return"apps/wiki"}if(hasRootMarkers("app/wiki")){return"app/wiki"}if(existsSync14(path25.join(rootDirectory,"apps/wiki"))){return"apps/wiki"}if(existsSync14(path25.join(rootDirectory,"wiki"))){return"wiki"}return detection.monorepo?"apps/wiki":"wiki"};var buildWikiAlignment=({rootDirectory,detection,expectedDirectory,scriptEnvironment,scriptRuntimePath:scriptRuntimePath2})=>{const hasWikiRootMarkers2=(relativeRoot)=>{const absoluteRoot=path25.join(rootDirectory,relativeRoot);return["package.json","backlog-provider.md","wiki-framework.md"].some((marker)=>existsSync14(path25.join(absoluteRoot,marker)))};const wikiRoot=wikiRootForAlignment(rootDirectory,detection,hasWikiRootMarkers2);copyIfExists({ignoreGeneratedRootDirectories:true,relativePath:wikiRoot,rootDirectory,targetDirectory:expectedDirectory});copyIfExists({relativePath:"docs",rootDirectory,targetDirectory:expectedDirectory});const wikiFramework=readWikiFrameworkPin(path25.join(expectedDirectory,wikiRoot));scaffoldWikiForDirectory({monorepo:wikiRoot==="apps/wiki",outputDirectory:expectedDirectory,wikiFramework});const syncScript=path25.join(expectedDirectory,wikiRoot,"scripts","sync-content.mjs");if(existsSync14(syncScript)){runJavaScriptFileSync({cwd:expectedDirectory,file:syncScript,...scriptEnvironment===undefined?{}:{environment:scriptEnvironment},...scriptRuntimePath2===undefined?{}:{runtimePath:scriptRuntimePath2}})}const expectedFiles=collectRelativeFiles2(expectedDirectory,wikiRoot).map((relativePath)=>({kind:"harness",path:relativePath,sha256:hashPath(expectedDirectory,relativePath)??""})).filter((file5)=>!isProjectAuthoredManagedFile({file:file5,rootDirectory}));return{changes:buildChanges({expectedDirectory,expectedFiles,previousFiles:[],rootDirectory}),expectedDirectory,expectedFiles}};var readValidatedWikiFrameworkPin=(wikiDirectory)=>{const pinPath=path25.join(wikiDirectory,"wiki-framework.md");if(!existsSync14(pinPath)){return"next"}const content=readFileSync13(pinPath,"utf-8");if(content.includes("`tanstack-start`")){return"tanstack-start"}if(content.includes("`next`")){return"next"}throw new Error(`Invalid wiki framework pin: ${pinPath}`)};var buildGitignoreCleanup=({rootDirectory,expectedDirectory})=>{const relativePath=".gitignore";if(!existsSync14(path25.join(rootDirectory,relativePath))){return[]}copyManagedFile({fromDirectory:rootDirectory,relativePath,toDirectory:expectedDirectory});const cleanup=removeHarnessDirectoriesFromGitignore(expectedDirectory);if(cleanup.removedPatterns.length===0){return[]}const expectedFile={kind:"harness",path:relativePath,sha256:hashPath(expectedDirectory,relativePath)??""};return buildChanges({expectedDirectory,expectedFiles:[expectedFile],previousFiles:[],rootDirectory})};var semanticFile=({content,encoding="utf-8",kind="harness",mode=420,path:relativePath})=>({content,encoding,kind,...encoding==="symlink"?{}:{mode},path:relativePath,provenance:{revision:version2,source:"scaffold-semantics"}});var isJsonValue=(value5)=>{if(value5===null||typeof value5==="boolean"||typeof value5==="number"||typeof value5==="string"){return true}if(Array.isArray(value5)){return value5.every(isJsonValue)}return typeof value5==="object"&&Object.values(value5).every(isJsonValue)};var isJsonObject2=(value5)=>isJsonValue(value5)&&typeof value5==="object"&&value5!==null&&!Array.isArray(value5);var isStringArray2=(value5)=>Array.isArray(value5)&&value5.every((entry)=>typeof entry==="string");var projectionSemanticState=({desiredState})=>{const files=new Map;const structuredEntries=[];for(const projection of desiredState.projections){for(const action2 of projection.actions){const applyFileSemantics=()=>{if(action2.operation==="use-native-mirror"&&typeof action2.nativePath==="string"&&typeof action2.canonicalPath==="string"){const nativeRoot=`${action2.nativePath.split("/skills/")[0]}/skills`;const canonicalRoot=`${action2.canonicalPath.split("/skills/")[0]}/skills`;files.set(nativeRoot,semanticFile({content:path25.posix.relative(path25.posix.dirname(nativeRoot),canonicalRoot),encoding:"symlink",path:nativeRoot}))}if(action2.operation==="mirror"&&action2.id.includes(":lifecycle-hook:")&&typeof action2.source==="string"&&typeof action2.target==="string"&&action2.source!==action2.target){files.set(action2.target,semanticFile({content:path25.posix.relative(path25.posix.dirname(action2.target),action2.source),encoding:"symlink",kind:action2.target.includes("/hooks/")?"hook":"harness",path:action2.target}))}if(action2.operation==="merge-json"&&typeof action2.file==="string"&&isStringArray2(action2.path)&&isJsonValue(action2.value)){const value5=action2.file===".claude/settings.json"?[action2.value]:action2.value;structuredEntries.push({file:action2.file,kind:"field",path:action2.path,provenance:{revision:version2,source:"harness-projection"},value:value5})}};applyFileSemantics();const applyJsonKeySemantics=()=>{if(action2.operation==="merge-json"&&typeof action2.target==="string"&&action2.file===undefined&&!action2.target.includes("#")&&isJsonObject2(action2.value)){for(const[key,value5]of Object.entries(action2.value)){if(action2.target==="opencode.json"&&key==="formatter"&&isJsonObject2(value5)&&"harness-format-edited-file"in value5){structuredEntries.push({file:action2.target,kind:"key",path:["formatter","harness-format-edited-file"],provenance:{revision:version2,source:"harness-projection"},value:value5["harness-format-edited-file"]});continue}structuredEntries.push({file:action2.target,kind:"key",path:[key],provenance:{revision:version2,source:"harness-projection"},value:value5})}}};applyJsonKeySemantics();const applyHookConfigSemantics=()=>{const{config}=action2;if(action2.operation==="mirror"&&isJsonObject2(config)&&typeof config.path==="string"&&typeof config.event==="string"&&typeof config.command==="string"&&(config.timeout===undefined||typeof config.timeout==="number")){structuredEntries.push({file:config.path,kind:"field",path:["hooks",config.event],provenance:{revision:version2,source:"harness-projection"},value:[{command:config.command,...config.timeout===undefined?{}:{timeout:config.timeout}}]})}};applyHookConfigSemantics()}}const codexHookActions=desiredState.projections.flatMap(({actions})=>actions).filter((action2)=>action2.operation==="merge-toml"&&action2.id.includes(":lifecycle-hook:"));const applyCodexHookSemantics=()=>{if(codexHookActions.length===0){return}const hasUpdateCheck=codexHookActions.some((action2)=>action2.id.includes("scaffold-update-check"));const hasFormatHook=codexHookActions.some((action2)=>action2.id.includes("format-edited-file"));const lines2=["[agents]","max_depth = 1","","[features]","codex_hooks = true","","[hooks]"];if(hasUpdateCheck||hasFormatHook){const hooks=[...hasUpdateCheck?[' { type = "command", command = "node \\"$(git rev-parse --show-toplevel)/.codex/hooks/scaffold-update-check.mjs\\" codex", statusMessage = "Checking Harness scaffold", timeout = 60 },']:[],...hasFormatHook?[' { type = "command", command = "node \\"$(git rev-parse --show-toplevel)/.codex/hooks/format-edited-file.mjs\\" session-start", statusMessage = "Capturing edited-file baseline", timeout = 30 },']:[]];lines2.push("SessionStart = [",' { matcher = "startup|resume", hooks = [',...hooks," ] },","]")}if(hasFormatHook){lines2.push("PostToolUse = [",' { matcher = "Bash|apply_patch|.*apply.?patch.*|edit|write|multiedit", hooks = [',' { type = "command", command = "node \\"$(git rev-parse --show-toplevel)/.codex/hooks/format-edited-file.mjs\\" post", statusMessage = "Auto-formatting edited files", timeout = 30 },'," ] },","]")}lines2.push("");files.set(".codex/config.toml",semanticFile({content:lines2.join(`
|
|
1532
1532
|
`),path:".codex/config.toml"}))};applyCodexHookSemantics();return{files:[...files.values()],structuredEntries}};var wikiRootForDetection=(detection)=>{const detectedManifestPaths=new Set(detection.manifests.map(({relativePath})=>relativePath.split(path25.sep).join("/")));if(detectedManifestPaths.has("apps/wiki/package.json")){return"apps/wiki"}if(detectedManifestPaths.has("app/wiki/package.json")){return"app/wiki"}if(detectedManifestPaths.has("wiki/package.json")){return"wiki"}return detection.monorepo?"apps/wiki":"wiki"};var wikiSemanticState=({detection,finalPacks,framework,settings})=>{if(!finalPacks.includes("docs")){return{files:[],structuredEntries:[]}}const wikiRoot=wikiRootForDetection(detection);const template=makeWikiScaffoldTemplate(wikiRoot,framework);const files=[...template.files.map((file5)=>semanticFile({...file5,path:path25.posix.join(wikiRoot,file5.path)})),...template.rawSubdirectories.map((directory3)=>semanticFile({content:"",path:path25.posix.join(wikiRoot,"raw",directory3,".gitkeep")})),semanticFile({content:"",path:path25.posix.join(wikiRoot,"content/docs/project/.gitkeep")}),semanticFile({content:"",path:path25.posix.join(wikiRoot,"specs/.gitkeep")}),semanticFile({content:template.agentsMarkdown,path:path25.posix.join(wikiRoot,"AGENTS.md")}),semanticFile({content:"AGENTS.md",encoding:"symlink",path:path25.posix.join(wikiRoot,"CLAUDE.md")}),semanticFile({content:template.indexMarkdown,path:path25.posix.join(wikiRoot,"index.md")}),semanticFile({content:template.logMarkdown,path:path25.posix.join(wikiRoot,"log.md")}),semanticFile({content:renderBacklogProviderMarkdown(settings.backlogProvider),path:path25.posix.join(wikiRoot,"backlog-provider.md")}),semanticFile({content:renderWikiFrameworkMarkdown(framework),path:path25.posix.join(wikiRoot,"wiki-framework.md")})];return{files,structuredEntries:[]}};var semanticDesiredState=({desiredState,detection,finalPacks,wikiFramework,settings})=>{const projection=projectionSemanticState({desiredState});const wiki=wikiSemanticState({detection,finalPacks,framework:wikiFramework,settings});return{files:[...projection.files,...wiki.files],structuredEntries:[...projection.structuredEntries,...wiki.structuredEntries]}};var desiredFileBytes=(file5)=>file5.encoding==="base64"?Buffer.from(file5.content,"base64"):file5.content;var desiredFileFingerprint=(file5)=>JSON.stringify({mode:file5.mode===undefined?null:fileMode2(file5.mode),sha256:hashContent2(file5.encoding==="symlink"?`symlink:${file5.content}`:desiredFileBytes(file5)),type:file5.encoding==="symlink"?"symlink":"file"});var observeManagedFile=({expectedMode,kind,relativePath,rootDirectory})=>{const absolutePath=resolveContainedReceiptPath(rootDirectory,relativePath,{followLeaf:false});const projectAuthored=isProjectAuthoredManagedFile({file:{kind,path:relativePath,sha256:""},rootDirectory});if(!pathLexists(absolutePath)){return{fingerprint:"missing",kind,mode:null,path:relativePath,projectAuthored,sha256:null,type:"missing"}}const stat3=lstatSync4(absolutePath);if(!stat3.isSymbolicLink()&&!stat3.isFile()){return{fingerprint:JSON.stringify({mode:null,sha256:null,type:"other"}),kind,mode:fileMode2(stat3.mode),path:relativePath,projectAuthored,sha256:null,type:"other"}}const isSymlink=stat3.isSymbolicLink();const bytes=isSymlink?undefined:readFileSync13(absolutePath);const sha256=hashContent2(isSymlink?`symlink:${readlinkSync3(absolutePath)}`:bytes??"");const mode=isSymlink?null:fileMode2(stat3.mode);return{...bytes===undefined?{}:{content:bytes.toString("utf-8")},fingerprint:JSON.stringify({mode:expectedMode===undefined||isSymlink?null:mode,sha256,type:isSymlink?"symlink":"file"}),kind,mode,path:relativePath,projectAuthored,sha256,type:isSymlink?"symlink":"file"}};var packageFileForWorkspace=(workspace)=>workspace==="."?"package.json":path25.posix.join(workspace,"package.json");var readJsonObject=(absolutePath)=>{try{const value5=JSON.parse(readFileSync13(absolutePath,"utf-8"));return typeof value5==="object"&&value5!==null&&!Array.isArray(value5)?value5:null}catch{return null}};var applyManagedLifecycleHook=({action:action2,entryFile,leaf,parent,priorEntry})=>{const desiredHook=action2._tag==="SafeRemoveScaffoldEntry"?undefined:managedLifecycleHook(action2.desired);let previousHook;if(action2._tag==="SafeRemoveScaffoldEntry"){previousHook=managedLifecycleHook(action2.previous)}else if(priorEntry!==undefined){previousHook=managedLifecycleHook(priorEntry)}const managedHook=desiredHook??previousHook;if(managedHook===undefined){return false}const current=parent[leaf];if(current!==undefined&&!Array.isArray(current)){throw new Error(`Lifecycle hook configuration is not an array: ${entryFile}`)}const previousValue=(previousHook??desiredHook)?.value;let removedPrevious=false;const consumerHooks=(current??[]).filter((hook)=>{if(!removedPrevious&&previousValue!==undefined&&stableJsonStringify(hook)===stableJsonStringify(previousValue)){removedPrevious=true;return false}return true});if(action2._tag==="SafeRemoveScaffoldEntry"){if(consumerHooks.length===0){Reflect.deleteProperty(parent,leaf)}else{parent[leaf]=consumerHooks}}else{parent[leaf]=[...consumerHooks,(desiredHook??managedHook).value]}return true};var receiptForFile=({kind,relativePath,rootDirectory})=>{const absolutePath=resolveContainedReceiptPath(rootDirectory,relativePath,{followLeaf:false});const stat3=lstatSync4(absolutePath);const type2=stat3.isSymbolicLink()?"symlink":"file";return{kind,mode:type2==="symlink"?null:fileMode2(stat3.mode),path:relativePath,sha256:hashPath(rootDirectory,relativePath)??"",type:type2}};var writeJsonDocument=(absolutePath,document)=>{mkdirSync8(path25.dirname(absolutePath),{recursive:true});writeFileSync8(absolutePath,`${encodePrettyJson3(document)}
|
|
1533
|
-
`)};var usesClassicYarn=(rootDirectory,configuredManager,configuredVersion)=>{if(configuredManager==="yarn"&&configuredVersion!==null){return/^1(?:\.|$)/u.test(configuredVersion)}if(configuredManager!==null){return false}const yarnLockfile=path25.join(rootDirectory,"yarn.lock");return existsSync14(yarnLockfile)&&/(?:^|\n)# yarn lockfile v1(?:\n|$)/u.test(readFileSync13(yarnLockfile,"utf-8"))};var dependencyLockfileCommand=(rootDirectory)=>{const rootManifest=readJsonObject(path25.join(rootDirectory,"package.json"));const configuredValue=typeof rootManifest?.packageManager==="string"?rootManifest.packageManager:null;const configuredMatch=configuredValue===null?null:/^(?<manager>[^@]+)(?:@(?<version>.+))?$/u.exec(configuredValue);const configured=configuredMatch?.groups?.manager??null;const configuredVersion=configuredMatch?.groups?.version??null;const manager=configured??[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["package-lock.json","npm"],["yarn.lock","yarn"]].find(([lockfile])=>existsSync14(path25.join(rootDirectory,lockfile)))?.[1]??null;switch(manager){case"bun":{return["bun",["install","--lockfile-only"]]}case"npm":{return["npm",["install","--package-lock-only","--ignore-scripts"]]}case"pnpm":{return["pnpm",["install","--lockfile-only","--ignore-scripts"]]}case"yarn":{if(usesClassicYarn(rootDirectory,configured,configuredVersion)){return["yarn",["install","--ignore-scripts","--non-interactive"]]}return["yarn",["install","--mode=update-lockfile"]]}default:{return null}}};var defaultDependencyProcess=(command,args2,cwd)=>{const result4=spawnSync3(command,[...args2],{cwd,encoding:"utf-8",stdio:"pipe"});if(result4.error!==undefined||result4.status!==0){throw new Error(result4.error?.message||result4.stderr.trim()||`${command} exited ${result4.status??1}`)}};var dependencyLockfiles=["bun.lock","bun.lockb","package-lock.json","pnpm-lock.yaml","yarn.lock"];var snapshotDependencyLockfiles=(rootDirectory)=>new Map(dependencyLockfiles.map((lockfile)=>{const absolutePath=path25.join(rootDirectory,lockfile);return[absolutePath,existsSync14(absolutePath)?readFileSync13(absolutePath):null]}));var restoreDependencyLockfiles=(snapshot)=>{for(const[absolutePath,content]of snapshot){if(content===null){rmSync6(absolutePath,{force:true})}else{writeFileSync8(absolutePath,content)}}};var makeScaffoldReconciliationApplicators=({dependencyProcess,priorReceipt,rootDirectory})=>({applyDependency:(action2)=>try_3({catch:(cause)=>cause,try:()=>{const entry=action2._tag==="SafeRemoveScaffoldEntry"?action2.previous:action2.desired;const absolutePath=resolveMutableJsonPath(rootDirectory,packageFileForWorkspace(entry.workspace));const document=readJsonObject(absolutePath);if(document===null){throw new Error(`Package manifest is not a JSON object: ${packageFileForWorkspace(entry.workspace)}`)}const sectionValue=document[entry.section];if(sectionValue!==undefined&&(typeof sectionValue!=="object"||sectionValue===null||Array.isArray(sectionValue))){throw new Error(`Package dependency section is not an object: ${entry.section}`)}const section2=sectionValue??{};const previousPackageManifest=readFileSync13(absolutePath);const lockfileSnapshot=snapshotDependencyLockfiles(rootDirectory);if(action2._tag==="SafeRemoveScaffoldEntry"){Reflect.deleteProperty(section2,entry.name)}else{section2[entry.name]=entry.version}document[entry.section]=section2;writeJsonDocument(absolutePath,document);const lockfileCommand=dependencyLockfileCommand(rootDirectory);if(lockfileCommand!==null){try{dependencyProcess(lockfileCommand[0],lockfileCommand[1],rootDirectory)}catch(error2){writeFileSync8(absolutePath,previousPackageManifest);restoreDependencyLockfiles(lockfileSnapshot);throw error2}}return action2._tag==="SafeRemoveScaffoldEntry"?null:{name:entry.name,section:entry.section,version:entry.version,workspace:entry.workspace}}}),applyFile:(action2)=>try_3({catch:(cause)=>cause,try:()=>{const relativePath=action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.path:action2.desired.path;const absolutePath=resolveContainedReceiptPath(rootDirectory,relativePath,{followLeaf:false});if(action2._tag==="SafeRemoveScaffoldEntry"){rmSync6(absolutePath,{force:true,recursive:true});return null}const{desired}=action2;mkdirSync8(path25.dirname(absolutePath),{recursive:true});if(desired.encoding==="symlink"){rmSync6(absolutePath,{force:true,recursive:true});symlinkSync3(desired.content,absolutePath)}else{if(pathLexists(absolutePath)&&lstatSync4(absolutePath).isSymbolicLink()){rmSync6(absolutePath,{force:true})}writeFileSync8(absolutePath,desired.encoding==="base64"?Buffer.from(desired.content,"base64"):desired.content);if(desired.mode!==undefined){chmodSync2(absolutePath,fileMode2(desired.mode))}}return receiptForFile({kind:desired.kind,relativePath,rootDirectory})}}),applyStructuredEntry:(action2)=>try_3({catch:(cause)=>cause,try:()=>{const entry=action2._tag==="SafeRemoveScaffoldEntry"?action2.previous:action2.desired;const absolutePath=resolveMutableJsonPath(rootDirectory,entry.file);const document=existsSync14(absolutePath)?readJsonObject(absolutePath):{};if(document===null){throw new Error(`Structured configuration is not a JSON object: ${entry.file}`)}if(entry.path.length===0){throw new Error(`Structured entry path is empty: ${entry.file}`)}let parent=document;for(const segment of entry.path.slice(0,-1)){const value5=parent[segment];if(value5===undefined){const child={};parent[segment]=child;parent=child}else if(typeof value5==="object"&&value5!==null&&!Array.isArray(value5)){parent=value5}else{throw new Error(`Structured configuration cannot traverse ${segment}: ${entry.file}`)}}const leaf=entry.path.at(-1)??"";const priorEntry=priorReceipt.structuredEntries.find((candidate)=>JSON.stringify([candidate.file,candidate.kind,candidate.path])===action2.identity);const appliedLifecycleHook=applyManagedLifecycleHook({action:action2,entryFile:entry.file,leaf,parent,...priorEntry===undefined?{}:{priorEntry}});if(!appliedLifecycleHook&&action2._tag==="SafeRemoveScaffoldEntry"){Reflect.deleteProperty(parent,leaf)}else if(!appliedLifecycleHook){parent[leaf]=entry.value}writeJsonDocument(absolutePath,document);return action2._tag==="SafeRemoveScaffoldEntry"?null:{file:entry.file,kind:entry.kind,path:entry.path,value:entry.value}}}),persistReceipt:(receipt)=>try_3({catch:(cause)=>cause,try:()=>{const manifestPath=path25.join(rootDirectory,scaffoldManifestFile);const manifest=readJsonObject(manifestPath);if(manifest===null){throw new Error(`Scaffold manifest is not a JSON object: ${scaffoldManifestFile}`)}manifest.managedFiles=receipt.files.map(({kind,path:relativePath,sha256})=>({kind,path:relativePath,sha256}));manifest.managedFileTypes=Object.fromEntries(receipt.files.map(({path:relativePath,type:type2})=>[relativePath,type2]));manifest.managedFileModes=Object.fromEntries(receipt.files.map(({mode,path:relativePath,type:type2})=>[relativePath,type2==="symlink"?null:mode]));manifest.managedDependencies=receipt.dependencies;manifest.managedStructuredEntries=receipt.structuredEntries;manifest.scaffoldDegradations=receipt.degradations;writeJsonDocument(manifestPath,manifest)}})});var reconciliationControlledPaths=({desiredState,plan,priorReceipt})=>{const entryPath=new Map;const recordEntryPath=(item,identity3,relativePath)=>{entryPath.set(`${item}\x00${identity3}`,relativePath)};for(const file5 of[...desiredState.files,...priorReceipt.files]){recordEntryPath("file",file5.path,file5.path)}for(const dependency of[...desiredState.dependencies,...priorReceipt.dependencies]){recordEntryPath("dependency",JSON.stringify([dependency.workspace,dependency.section,dependency.name]),packageFileForWorkspace(dependency.workspace))}for(const entry of[...desiredState.structuredEntries,...priorReceipt.structuredEntries]){recordEntryPath("structured-entry",JSON.stringify([entry.file,entry.kind,entry.path]),entry.file)}const paths=new Set([...desiredState.dependencies.map(({workspace})=>packageFileForWorkspace(workspace)),...desiredState.structuredEntries.map(({file:file5})=>file5)]);for(const action2 of plan.actions){if(action2.item==="file"){paths.add(action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.path:action2.desired.path)}else if(action2.item==="dependency"){paths.add(packageFileForWorkspace(action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.workspace:action2.desired.workspace))}else{paths.add(action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.file:action2.desired.file)}}for(const conflict of plan.conflicts){const relativePath=entryPath.get(`${conflict.item}\x00${conflict.identity}`);if(relativePath!==undefined){paths.add(relativePath)}}for(const skip of plan.skips){const relativePath=entryPath.get(`${skip.item}\x00${skip.identity}`);if(relativePath!==undefined){paths.add(relativePath)}}for(const failure of plan.failures){if(failure._tag==="CrossFamilyScaffoldOwnershipFailure"){paths.add(failure.path);continue}if("item"in failure){const relativePath=entryPath.get(`${failure.item}\x00${failure.identity}`);if(relativePath!==undefined){paths.add(relativePath)}}}return paths};var removableStaleManagedFiles=({plan,reconciliationPaths,staleFiles})=>{const safeFileActionPaths=new Set(plan.actions.flatMap((action2)=>{if(action2.item!=="file"){return[]}return[action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.path:action2.desired.path]}));return staleFiles.filter((relativePath)=>!reconciliationPaths.has(relativePath)||safeFileActionPaths.has(relativePath)).toSorted()};var reconciliationStatus=(outcomes)=>{const blocked=outcomes.some(({_tag})=>_tag==="ScaffoldActionBlocked"||_tag==="ScaffoldActionFailed"||_tag==="ScaffoldConflictPreserved"||_tag==="ScaffoldPlanningFailed");if(!blocked){return"succeeded"}return outcomes.some(({_tag})=>_tag==="ScaffoldActionSucceeded")?"partial":"failed"};var publicReconciliationOperation=(action2)=>{if(action2._tag==="SafeCreateScaffoldEntry"){return"create"}return action2._tag==="SafeUpdateScaffoldEntry"?"update":"remove"};var publicReconciliationActions=(plan)=>plan.actions.map((action2)=>({identity:action2.identity,item:action2.item,operation:publicReconciliationOperation(action2)}));var mergePrioritizedChanges=(target,changes)=>{const priority={changed:0,"local-edited":1,missing:2};for(const change of changes){const previous=target.get(change.path);if(previous===undefined||priority[change.status]>priority[previous.status]){target.set(change.path,change)}}};var observeStructuredValue=(document,entry)=>{let value5=document;for(const[index2,segment]of entry.path.entries()){if(typeof value5!=="object"||value5===null||Array.isArray(value5)){return{_tag:"InvalidStructuredObservation",message:`Structured configuration cannot traverse ${entry.path.slice(0,index2).join(".")}: ${entry.file}`}}if(!Object.hasOwn(value5,segment)){return{_tag:"MissingStructuredObservation"}}value5=value5[segment]}const expectedHook=managedLifecycleHook(entry);if(expectedHook!==undefined){if(!Array.isArray(value5)){return{_tag:"InvalidStructuredObservation",message:`Lifecycle hook configuration is not an array: ${entry.file}`}}const observedHook=value5.find((candidate)=>stableJsonStringify(candidate)===stableJsonStringify(expectedHook.value));return observedHook===undefined?{_tag:"MissingStructuredObservation"}:{_tag:"PresentStructuredObservation",value:[observedHook]}}return{_tag:"PresentStructuredObservation",value:value5}};var dependencyObservationIdentity=({name:name2,section:section2,workspace})=>JSON.stringify([workspace,section2,name2]);var structuredObservationIdentity=({file:file5,kind,path:entryPath})=>JSON.stringify([file5,kind,entryPath]);var observedEntryKey=(item,identity3)=>JSON.stringify([item,identity3]);var observeDesiredState=({desiredState,manifest,rootDirectory,semanticState})=>{const desiredFiles=new Map([...desiredState.files,...semanticState.files].map((file5)=>[file5.path,file5]));const files=new Map;for(const file5 of manifest.managedFiles??[]){files.set(file5.path,{kind:file5.kind})}for(const file5 of desiredFiles.values()){files.set(file5.path,{kind:file5.kind,...file5.mode===undefined?{}:{mode:file5.mode}})}const dependencyEntries=new Map([...desiredState.dependencies,...manifest.managedDependencies??[]].map((entry)=>[dependencyObservationIdentity(entry),entry]));const structuredEntries=new Map([...desiredState.structuredEntries,...semanticState.structuredEntries,...manifest.managedStructuredEntries??[]].map((entry)=>[structuredObservationIdentity(entry),entry]));const invalidEntries=new Map;for(const entry of structuredEntries.values()){const identity3=structuredObservationIdentity(entry);try{resolveMutableJsonPath(rootDirectory,entry.file);if(!files.has(entry.file)){files.set(entry.file,{kind:"harness"})}}catch(error2){invalidEntries.set(observedEntryKey("structured-entry",identity3),{identity:identity3,item:"structured-entry",message:error2 instanceof Error?error2.message:String(error2)})}}const dependencies=[...dependencyEntries.values()].flatMap((dependency)=>{const identity3=dependencyObservationIdentity(dependency);let manifestPath;try{manifestPath=resolveMutableJsonPath(rootDirectory,packageFileForWorkspace(dependency.workspace))}catch(error2){invalidEntries.set(observedEntryKey("dependency",identity3),{identity:identity3,item:"dependency",message:error2 instanceof Error?error2.message:String(error2)});return[]}if(!existsSync14(manifestPath)){return[]}const packageManifest=readJsonObject(manifestPath);if(packageManifest===null){invalidEntries.set(observedEntryKey("dependency",identity3),{identity:identity3,item:"dependency",message:`Package manifest is not a JSON object: ${packageFileForWorkspace(dependency.workspace)}`});return[]}const section2=packageManifest[dependency.section];if(section2===undefined){return[]}if(typeof section2!=="object"||section2===null||Array.isArray(section2)){invalidEntries.set(observedEntryKey("dependency",identity3),{identity:identity3,item:"dependency",message:`Package dependency section is not an object: ${dependency.section}`});return[]}const value5=section2[dependency.name];if(value5===undefined){return[]}if(typeof value5!=="string"){invalidEntries.set(observedEntryKey("dependency",identity3),{identity:identity3,item:"dependency",message:`Package dependency version is not a string: ${identity3}`});return[]}return[{name:dependency.name,section:dependency.section,version:value5,workspace:dependency.workspace}]});const observedStructuredEntries=[...structuredEntries.values()].flatMap((entry)=>{const identity3=structuredObservationIdentity(entry);let absolutePath;try{absolutePath=resolveMutableJsonPath(rootDirectory,entry.file)}catch(error2){invalidEntries.set(observedEntryKey("structured-entry",identity3),{identity:identity3,item:"structured-entry",message:error2 instanceof Error?error2.message:String(error2)});return[]}if(!existsSync14(absolutePath)){return[]}const document=readJsonObject(absolutePath);if(document===null){invalidEntries.set(observedEntryKey("structured-entry",identity3),{identity:identity3,item:"structured-entry",message:`Structured configuration is not a JSON object: ${entry.file}`});return[]}const observation=observeStructuredValue(document,entry);if(observation._tag==="InvalidStructuredObservation"){invalidEntries.set(observedEntryKey("structured-entry",identity3),{identity:identity3,item:"structured-entry",message:observation.message});return[]}return observation._tag==="MissingStructuredObservation"?[]:[{file:entry.file,kind:entry.kind,path:entry.path,value:observation.value}]});const observedFiles=[...files].flatMap(([relativePath,file5])=>{try{return[observeManagedFile({...file5.mode===undefined?{}:{expectedMode:file5.mode},kind:file5.kind,relativePath,rootDirectory})]}catch(error2){invalidEntries.set(observedEntryKey("file",relativePath),{identity:relativePath,item:"file",message:error2 instanceof Error?error2.message:String(error2)});return[]}});return{dependencies,files:observedFiles,invalidEntries:[...invalidEntries.values()].toSorted((left,right)=>left.identity.localeCompare(right.identity)),structuredEntries:observedStructuredEntries,version:"1"}};var priorReceiptFromManifest=(manifest,rootDirectory,desiredFiles)=>{const desiredModes=new Map(desiredFiles.map((file5)=>[file5.path,file5.mode]));return{dependencies:manifest.managedDependencies??[],files:(manifest.managedFiles??[]).filter(({path:relativePath})=>relativePath!==scaffoldManifestFile).map((file5)=>{const type2=manifest.managedFileTypes?.[file5.path]==="symlink"?"symlink":"file";const recordedMode=manifest.managedFileModes?.[file5.path];const absolutePath=resolveContainedReceiptPath(rootDirectory,file5.path,{followLeaf:false});const currentMode=type2==="file"&&pathLexists(absolutePath)&&lstatSync4(absolutePath).isFile()?fileMode2(lstatSync4(absolutePath).mode):undefined;const desiredMode=desiredModes.get(file5.path);let inferredMode;if(recordedMode===undefined&&type2==="symlink"){inferredMode=null}else if(recordedMode===undefined&¤tMode!==undefined&&desiredMode!==undefined&¤tMode===desiredMode%512&&hashPath(rootDirectory,file5.path)===file5.sha256){inferredMode=currentMode}const mode=recordedMode===undefined?inferredMode:recordedMode;return{kind:file5.kind,...mode===undefined?{}:{mode},path:file5.path,sha256:file5.sha256,type:type2}}),structuredEntries:(manifest.managedStructuredEntries??[]).map((entry)=>({...entry,value:entry.value})),version:"1"}};var changeStatus=({path:relativePath,observedFiles,previousFiles})=>{const observed=observedFiles.get(relativePath);if(observed===undefined||observed.type==="missing"){return"missing"}const previous=previousFiles.find((file5)=>file5.path===relativePath);return previous!==undefined&&previous.sha256!==observed.sha256?"local-edited":"changed"};var compareObservedState=({desiredState,manifest,observedState,semanticState})=>{const previousFiles=manifest.managedFiles??[];const observedFiles=new Map(observedState.files.map((file5)=>[file5.path,file5]));const semanticPaths=new Set(semanticState.files.map((file5)=>file5.path));const changes=new Map;const addChange=(change)=>{const previous=changes.get(change.path);const priority={changed:0,"local-edited":1,missing:2};if(previous===undefined||priority[change.status]>priority[previous.status]){changes.set(change.path,change)}};const comparableFiles=new Map([...desiredState.files,...semanticState.files].map((file5)=>[file5.path,file5]));const compareFiles=()=>{for(const file5 of comparableFiles.values()){const observed=observedFiles.get(file5.path);if(file5.kind==="context-plan"||file5.kind==="projection-receipt"||observed?.projectAuthored===true&&!semanticPaths.has(file5.path)){continue}const fingerprintMatches=observed?.fingerprint===desiredFileFingerprint(file5);const jsonMatches=!fingerprintMatches&&file5.encoding!=="base64"&&file5.encoding!=="symlink"&&file5.mode===undefined&&file5.path.endsWith(".json")&&jsonContentEquals(observed?.content??"",file5.content);if(fingerprintMatches||jsonMatches){continue}addChange({kind:file5.kind,path:file5.path,status:changeStatus({observedFiles,path:file5.path,previousFiles})})}};compareFiles();const observedDependencies=new Map(observedState.dependencies.map((dependency)=>[`${dependency.workspace}:${dependency.section}:${dependency.name}`,dependency]));for(const dependency of desiredState.dependencies){const identity3=`${dependency.workspace}:${dependency.section}:${dependency.name}`;if(observedDependencies.get(identity3)?.version===dependency.version){continue}const packageFile=packageFileForWorkspace(dependency.workspace);addChange({kind:"manifest",path:packageFile,status:changeStatus({observedFiles,path:packageFile,previousFiles})})}const observedStructuredEntries=new Map(observedState.structuredEntries.map((entry)=>[JSON.stringify([entry.file,entry.kind,entry.path]),entry]));for(const entry of[...desiredState.structuredEntries,...semanticState.structuredEntries]){if(entry.file===repoSettingsDisplayFile&&observedFiles.get(entry.file)?.type==="missing"){continue}const identity3=JSON.stringify([entry.file,entry.kind,entry.path]);const observed=observedStructuredEntries.get(identity3);if(observed!==undefined&&stableJsonStringify(observed.value)===stableJsonStringify(entry.value)){continue}addChange({kind:"harness",path:entry.file,status:changeStatus({observedFiles,path:entry.file,previousFiles})})}const desiredPaths=new Set([...desiredState.files.map((file5)=>file5.path),...desiredState.dependencies.map((dependency)=>packageFileForWorkspace(dependency.workspace)),...desiredState.structuredEntries.map((entry)=>entry.file),...semanticState.files.map((file5)=>file5.path),...semanticState.structuredEntries.map((entry)=>entry.file)]);const staleFiles=previousFiles.filter(({path:relativePath})=>relativePath!==scaffoldManifestFile).filter(({kind})=>kind!=="context-plan"&&kind!=="projection-receipt").filter((file5)=>observedFiles.get(file5.path)?.projectAuthored!==true).map((file5)=>file5.path).filter((file5)=>!desiredPaths.has(file5)).toSorted();return{changedFiles:[...changes.values()].toSorted((left,right)=>left.path.localeCompare(right.path)),staleFiles}};var resolveUpdateToolRuntime=({scriptEnvironment,toolRuntime})=>{if(toolRuntime!==undefined){return toolRuntime}if(scriptEnvironment===undefined){return}return makeToolCommandRuntime(Object.fromEntries(Object.entries(scriptEnvironment).filter((entry)=>entry[1]!==undefined)))};var runScaffoldOperation=({operation:operation2,rootDirectory,interaction,check:requestedCheck=false,write:requestedWrite=false,yes:requestedYes=false,emitJson:requestedEmitJson=false,ensureTools:requestedEnsureTools=true,baseline=bundledBaseline,allowBundledBaselineDriftApply=false,toolStdio:requestedToolStdio,toolRuntime,scaffoldLifecycle={},reconciliationApplicators,dependencyProcess=defaultDependencyProcess,configuration={disableBundledUrl:true},emitOutput=true,scriptEnvironment,scriptRuntimePath:scriptRuntimePath2})=>{const check3=operation2==="check"||requestedCheck;const write2=operation2==="update"&&requestedWrite;const yes=operation2==="update"&&requestedYes;const emitJson=operation2==="update"&&requestedEmitJson;const ensureTools2=operation2==="update"&&requestedEnsureTools;const toolStdio=requestedToolStdio??(emitJson?"ignore":"inherit");const resolvedToolRuntime=resolveUpdateToolRuntime({scriptEnvironment,toolRuntime});let updateStagingDirectory=null;let wikiStagingDirectory=null;return gen2(function*executeScaffoldOperation(){const projectSettings=yield*ProjectSettings;const writeHuman=noopHumanOutput;const manifest=yield*try_3({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Failed to read scaffold manifest."}),try:()=>readManifest(rootDirectory)});yield*try_3({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Invalid managed file receipt path."}),try:()=>{for(const file5 of manifest.managedFiles??[]){resolveContainedReceiptPath(rootDirectory,file5.path,{followLeaf:false})}}});const finalPacks=yield*try_3({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Invalid scaffold manifest."}),try:()=>normalizePacks(manifest.finalPacks,baseline)});const repoShapeMode=normalizeRepoShapeMode(manifest.repoShapeMode);const detection=applyRepoShapeMode(yield*detectRepository(rootDirectory),repoShapeMode);const resolved=resolvePackSelection(detection,baseline);const manifestBaseline=manifest.baseline;const baselineDrift=typeof manifestBaseline?.version==="string"&&manifestBaseline.version!==baseline.summary.version;const resolvedPacks=resolved.preselectedPacks;const packDrift=hasActionablePackDrift({finalPacks,resolvedPacks});const updateFinalPacks=write2||yes?acceptResolvedPacks({baseline,finalPacks,resolvedPacks}):finalPacks;const wikiRoot=wikiRootForDetection(detection);const wikiFramework=yield*try_3({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Invalid wiki framework pin."}),try:()=>readValidatedWikiFrameworkPin(path25.join(rootDirectory,wikiRoot))});const wikiPromptTarget=wikiPromptTargetFor({wikiFramework,wikiRoot});const wikiPromptTargets=updateFinalPacks.includes("docs")?[wikiPromptTarget]:[];const expectedDirectory=mkdtempSync3(path25.join(tmpdir6(),"punks-update-"));updateStagingDirectory=expectedDirectory;const repoSettingsOnDisk=yield*projectSettings.read(rootDirectory).pipe(map7(some2),catchTag2("ProjectSettingsMissing",()=>succeed6(none2())),mapError3((cause)=>new CliValidationError({cause,message:cause.message})));const inferredRepoSettings=isNone2(repoSettingsOnDisk)?yield*projectSettings.infer(rootDirectory).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message}))):none2();const repoSettings=match(repoSettingsOnDisk,{onNone:()=>inferredRepoSettings,onSome:({settings})=>some2(settings)});if(isNone2(repoSettings)){return yield*fail6(new CliValidationError({message:`Project settings are missing at ${path25.join(rootDirectory,projectSettingsFile)}.`}))}const calculatedRequiredTools=requiredToolsForSkills2(selectedSkills3(updateFinalPacks,baseline),baseline);const settingsRequiredTools=deriveRequiredTools({repositoryManager:repoSettings.value.repositoryManager,requiredTools:calculatedRequiredTools});const contextPlan=yield*compileScaffoldContextPlan({additionalPromptTargets:wikiPromptTargets,baseline,detection,finalPacks:updateFinalPacks,preserveExistingSubagentManifest:false,scanDirectory:rootDirectory}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})));const settingsChanges=isSome2(repoSettings)?yield*gen2(function*settingsChanges(){if(isSome2(repoSettingsOnDisk)){const source=path25.join(rootDirectory,projectSettingsFile);const destination=path25.join(expectedDirectory,projectSettingsFile);mkdirSync8(path25.dirname(destination),{recursive:true});cpSync3(source,destination);yield*projectSettings.write(expectedDirectory,{_tag:"CalculatedToolsChange",requiredTools:calculatedRequiredTools});yield*projectSettings.write(expectedDirectory,{_tag:"ManagedVersionsChange",baselineVersion:baseline.summary.version,cliVersion:version2})}else{yield*projectSettings.initialize(expectedDirectory,{calculatedTools:{requiredTools:calculatedRequiredTools},managedVersions:{baselineVersion:baseline.summary.version,cliVersion:version2},userChoices:{assetProviderSlug:repoSettings.value.assetProviderSlug,backlogProvider:repoSettings.value.backlogProvider,...repoSettings.value.backlogProjectUrl===undefined?{}:{backlogProjectUrl:repoSettings.value.backlogProjectUrl},repositoryManager:repoSettings.value.repositoryManager}})}const expectedFile={kind:"harness",path:projectSettingsFile,sha256:hashPath(expectedDirectory,projectSettingsFile)??""};return buildChanges({expectedDirectory,expectedFiles:[expectedFile],previousFiles:[],rootDirectory})}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message}))):[];const materialize=(desiredState)=>writeScaffoldOutput({additionalPromptTargets:wikiPromptTargets,baseline,contextPlan:desiredState?.contextPlan??contextPlan,detection,displayOutputDirectory:rootDirectory,outputDirectory:expectedDirectory,preserveExistingManagedFiles:false,repoShapeMode,scanDirectory:rootDirectory,...scriptEnvironment===undefined?{}:{scriptEnvironment},...scriptRuntimePath2===undefined?{}:{scriptRuntimePath:scriptRuntimePath2},...desiredState===undefined?{}:{desiredState,...isSome2(repoSettings)?{settings:desiredState.settings}:{}}}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})),map7((output2)=>{if(desiredState===undefined){return output2}const contextEvidence=new Set([".devpunks/context-plan.json",".devpunks/harness-projection-receipt.json"]);for(const relativePath of contextEvidence){rmSync6(path25.join(expectedDirectory,relativePath),{force:true})}const manifestPath=path25.join(expectedDirectory,scaffoldManifestFile);const stagedManifest=JSON.parse(readFileSync13(manifestPath,"utf-8"));stagedManifest.generatedFiles=(stagedManifest.generatedFiles??[]).filter((relativePath)=>!contextEvidence.has(relativePath));stagedManifest.managedFiles=(stagedManifest.managedFiles??[]).filter(({path:relativePath})=>!contextEvidence.has(relativePath));if(typeof stagedManifest.managedFileTypes==="object"&&stagedManifest.managedFileTypes!==null){stagedManifest.managedFileTypes=Object.fromEntries(Object.entries(stagedManifest.managedFileTypes).filter(([relativePath])=>!contextEvidence.has(relativePath)))}delete stagedManifest.contextPlanFile;delete stagedManifest.projectionReceiptFile;delete stagedManifest.projectionStatus;writeFileSync8(manifestPath,encodePrettyJson3(stagedManifest));return{...output2,contextPlanFile:null,generatedFiles:output2.generatedFiles.filter((relativePath)=>!contextEvidence.has(relativePath)),managedFiles:output2.managedFiles.filter(({path:relativePath})=>!contextEvidence.has(relativePath)),projectionReceiptFile:null,projectionStatus:null}}));const expected=yield*gen2(function*expected(){const desiredSettings={...repoSettings.value,baselineVersion:baseline.summary.version,cliVersion:version2,requiredTools:settingsRequiredTools};const gather=()=>planScaffoldOutput({additionalPromptTargets:wikiPromptTargets,baseline,contextPlan,detection,displayOutputDirectory:rootDirectory,outputDirectory:rootDirectory,preserveExistingManagedFiles:false,repoShapeMode,scanDirectory:rootDirectory,...scriptEnvironment===undefined?{}:{scriptEnvironment},...scriptRuntimePath2===undefined?{}:{scriptRuntimePath:scriptRuntimePath2},...isSome2(repoSettings)?{settings:desiredSettings}:{}}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})),map7((plan)=>({...plan,files:plan.files.filter(({kind})=>kind!=="projection-receipt")})),map7((plan)=>desiredScaffoldStateInput({...plan,settings:desiredSettings})));const observe=({desiredState})=>sync2(()=>{const semanticState=semanticDesiredState({desiredState,detection,finalPacks:updateFinalPacks,settings:desiredSettings,wikiFramework});return observeDesiredState({desiredState,manifest,rootDirectory,semanticState})});const compiler=scaffoldLifecycle.compileDesiredState===undefined?{}:{compile:scaffoldLifecycle.compileDesiredState};const planReconciliation=scaffoldLifecycle.planReconciliation??((input2)=>planScaffoldReconciliation(input2,nodeScaffoldContentHasher));const reconcile=({desiredState,observedState})=>{const semanticState=semanticDesiredState({desiredState,detection,finalPacks:updateFinalPacks,settings:desiredSettings,wikiFramework});const structuredEntries=[...desiredState.structuredEntries,...semanticState.structuredEntries].filter(({file:file5})=>file5!==repoSettingsDisplayFile);const entryOwnedPaths=new Set([...desiredState.dependencies.map(({workspace})=>packageFileForWorkspace(workspace)),...structuredEntries.map(({file:file5})=>file5)]);const belongsToLegacyFileLane=({kind,path:relativePath})=>kind==="context-plan"||kind==="projection-receipt"||kind==="agent-prompt"||kind==="handoff"||kind==="manifest"||kind==="prompt-spec"||kind==="required-tools"||kind==="subagent"||path25.posix.basename(relativePath)==="CLAUDE.md"||isWikiManagedPath(relativePath)||relativePath===projectAuthoredWikiSyncFile||relativePath===syncSubagentsScriptFile&&isTailoredSyncSubagentsScript(rootDirectory);const files=[...desiredState.files,...semanticState.files].filter((file5)=>!entryOwnedPaths.has(file5.path)&&!belongsToLegacyFileLane(file5));const stagedDesiredState={...desiredState,files,structuredEntries};const manifestReceipt=priorReceiptFromManifest(manifest,rootDirectory,stagedDesiredState.files);const applicationReceipt={...manifestReceipt,files:manifestReceipt.files.filter(({path:relativePath})=>!entryOwnedPaths.has(relativePath)),structuredEntries:manifestReceipt.structuredEntries.filter(({file:file5})=>file5!==repoSettingsDisplayFile)};const planningReceipt={...applicationReceipt,files:applicationReceipt.files.filter((file5)=>!belongsToLegacyFileLane(file5))};const plan=planReconciliation({desiredState:stagedDesiredState,observedState,priorReceipt:planningReceipt});const comparison=compareObservedState({desiredState,manifest,observedState,semanticState});return materialize(desiredState).pipe(map7((output2)=>({comparison,desiredState:stagedDesiredState,output:output2,plan,priorReceipt:applicationReceipt})))};if(operation2==="check"){const lifecycle2=yield*runCheckScaffoldLifecycle({...compiler,compare:reconcile,gather,observe});if(lifecycle2._tag==="ScaffoldLifecycleCompilationFailed"){return yield*fail6(new CliValidationError({message:lifecycle2.compilation.errors.map(({message})=>message).join(`
|
|
1533
|
+
`)};var usesClassicYarn=(rootDirectory,configuredManager,configuredVersion)=>{if(configuredManager==="yarn"&&configuredVersion!==null){return/^1(?:\.|$)/u.test(configuredVersion)}if(configuredManager!==null){return false}const yarnLockfile=path25.join(rootDirectory,"yarn.lock");return existsSync14(yarnLockfile)&&/(?:^|\n)# yarn lockfile v1(?:\n|$)/u.test(readFileSync13(yarnLockfile,"utf-8"))};var dependencyLockfileCommand=(rootDirectory)=>{const rootManifest=readJsonObject(path25.join(rootDirectory,"package.json"));const configuredValue=typeof rootManifest?.packageManager==="string"?rootManifest.packageManager:null;const configuredMatch=configuredValue===null?null:/^(?<manager>[^@]+)(?:@(?<version>.+))?$/u.exec(configuredValue);const configured=configuredMatch?.groups?.manager??null;const configuredVersion=configuredMatch?.groups?.version??null;const manager=configured??[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["package-lock.json","npm"],["yarn.lock","yarn"]].find(([lockfile])=>existsSync14(path25.join(rootDirectory,lockfile)))?.[1]??null;switch(manager){case"bun":{return["bun",["install","--lockfile-only"]]}case"npm":{return["npm",["install","--package-lock-only","--ignore-scripts"]]}case"pnpm":{return["pnpm",["install","--lockfile-only","--ignore-scripts"]]}case"yarn":{if(usesClassicYarn(rootDirectory,configured,configuredVersion)){return["yarn",["install","--ignore-scripts","--non-interactive"]]}return["yarn",["install","--mode=update-lockfile"]]}default:{return null}}};var defaultDependencyProcess=(command,args2,cwd)=>{const result4=spawnSync3(command,[...args2],{cwd,encoding:"utf-8",stdio:"pipe"});if(result4.error!==undefined||result4.status!==0){throw new Error(result4.error?.message||result4.stderr.trim()||`${command} exited ${result4.status??1}`)}};var dependencyLockfiles=["bun.lock","bun.lockb","package-lock.json","pnpm-lock.yaml","yarn.lock"];var snapshotDependencyLockfiles=(rootDirectory)=>new Map(dependencyLockfiles.map((lockfile)=>{const absolutePath=path25.join(rootDirectory,lockfile);return[absolutePath,existsSync14(absolutePath)?readFileSync13(absolutePath):null]}));var restoreDependencyLockfiles=(snapshot)=>{for(const[absolutePath,content]of snapshot){if(content===null){rmSync6(absolutePath,{force:true})}else{writeFileSync8(absolutePath,content)}}};var makeScaffoldReconciliationApplicators=({dependencyProcess,priorReceipt,rootDirectory})=>({applyDependency:(action2)=>try_3({catch:(cause)=>cause,try:()=>{const entry=action2._tag==="SafeRemoveScaffoldEntry"?action2.previous:action2.desired;const absolutePath=resolveMutableJsonPath(rootDirectory,packageFileForWorkspace(entry.workspace));const document=readJsonObject(absolutePath);if(document===null){throw new Error(`Package manifest is not a JSON object: ${packageFileForWorkspace(entry.workspace)}`)}const sectionValue=document[entry.section];if(sectionValue!==undefined&&(typeof sectionValue!=="object"||sectionValue===null||Array.isArray(sectionValue))){throw new Error(`Package dependency section is not an object: ${entry.section}`)}const section2=sectionValue??{};const previousPackageManifest=readFileSync13(absolutePath);const lockfileSnapshot=snapshotDependencyLockfiles(rootDirectory);if(action2._tag==="SafeRemoveScaffoldEntry"){Reflect.deleteProperty(section2,entry.name)}else{section2[entry.name]=entry.version}document[entry.section]=section2;writeJsonDocument(absolutePath,document);const lockfileCommand=dependencyLockfileCommand(rootDirectory);if(lockfileCommand!==null){try{dependencyProcess(lockfileCommand[0],lockfileCommand[1],rootDirectory)}catch(error2){writeFileSync8(absolutePath,previousPackageManifest);restoreDependencyLockfiles(lockfileSnapshot);throw error2}}return action2._tag==="SafeRemoveScaffoldEntry"?null:{name:entry.name,section:entry.section,version:entry.version,workspace:entry.workspace}}}),applyFile:(action2)=>try_3({catch:(cause)=>cause,try:()=>{const relativePath=action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.path:action2.desired.path;const absolutePath=resolveContainedReceiptPath(rootDirectory,relativePath,{followLeaf:false});if(action2._tag==="SafeRemoveScaffoldEntry"){rmSync6(absolutePath,{force:true,recursive:true});return null}const{desired}=action2;mkdirSync8(path25.dirname(absolutePath),{recursive:true});if(desired.encoding==="symlink"){rmSync6(absolutePath,{force:true,recursive:true});symlinkSync3(desired.content,absolutePath)}else{if(pathLexists(absolutePath)&&lstatSync4(absolutePath).isSymbolicLink()){rmSync6(absolutePath,{force:true})}writeFileSync8(absolutePath,desired.encoding==="base64"?Buffer.from(desired.content,"base64"):desired.content);if(desired.mode!==undefined){chmodSync2(absolutePath,fileMode2(desired.mode))}}return receiptForFile({kind:desired.kind,relativePath,rootDirectory})}}),applyStructuredEntry:(action2)=>try_3({catch:(cause)=>cause,try:()=>{const entry=action2._tag==="SafeRemoveScaffoldEntry"?action2.previous:action2.desired;const absolutePath=resolveMutableJsonPath(rootDirectory,entry.file);const document=existsSync14(absolutePath)?readJsonObject(absolutePath):{};if(document===null){throw new Error(`Structured configuration is not a JSON object: ${entry.file}`)}if(entry.path.length===0){throw new Error(`Structured entry path is empty: ${entry.file}`)}let parent=document;for(const segment of entry.path.slice(0,-1)){const value5=parent[segment];if(value5===undefined){const child={};parent[segment]=child;parent=child}else if(typeof value5==="object"&&value5!==null&&!Array.isArray(value5)){parent=value5}else{throw new Error(`Structured configuration cannot traverse ${segment}: ${entry.file}`)}}const leaf=entry.path.at(-1)??"";const priorEntry=priorReceipt.structuredEntries.find((candidate)=>JSON.stringify([candidate.file,candidate.kind,candidate.path])===action2.identity);const appliedLifecycleHook=applyManagedLifecycleHook({action:action2,entryFile:entry.file,leaf,parent,...priorEntry===undefined?{}:{priorEntry}});if(!appliedLifecycleHook&&action2._tag==="SafeRemoveScaffoldEntry"){Reflect.deleteProperty(parent,leaf)}else if(!appliedLifecycleHook){parent[leaf]=entry.value}writeJsonDocument(absolutePath,document);return action2._tag==="SafeRemoveScaffoldEntry"?null:{file:entry.file,kind:entry.kind,path:entry.path,value:entry.value}}}),persistReceipt:(receipt)=>try_3({catch:(cause)=>cause,try:()=>{const manifestPath=path25.join(rootDirectory,scaffoldManifestFile);const manifest=readJsonObject(manifestPath);if(manifest===null){throw new Error(`Scaffold manifest is not a JSON object: ${scaffoldManifestFile}`)}manifest.managedFiles=receipt.files.map(({kind,path:relativePath,sha256})=>({kind,path:relativePath,sha256}));manifest.managedFileTypes=Object.fromEntries(receipt.files.map(({path:relativePath,type:type2})=>[relativePath,type2]));manifest.managedFileModes=Object.fromEntries(receipt.files.map(({mode,path:relativePath,type:type2})=>[relativePath,type2==="symlink"?null:mode]));manifest.managedDependencies=receipt.dependencies;manifest.managedStructuredEntries=receipt.structuredEntries;manifest.scaffoldDegradations=receipt.degradations;writeJsonDocument(manifestPath,manifest)}})});var reconciliationControlledPaths=({desiredState,plan,priorReceipt})=>{const entryPath=new Map;const recordEntryPath=(item,identity3,relativePath)=>{entryPath.set(`${item}\x00${identity3}`,relativePath)};for(const file5 of[...desiredState.files,...priorReceipt.files]){recordEntryPath("file",file5.path,file5.path)}for(const dependency of[...desiredState.dependencies,...priorReceipt.dependencies]){recordEntryPath("dependency",JSON.stringify([dependency.workspace,dependency.section,dependency.name]),packageFileForWorkspace(dependency.workspace))}for(const entry of[...desiredState.structuredEntries,...priorReceipt.structuredEntries]){recordEntryPath("structured-entry",JSON.stringify([entry.file,entry.kind,entry.path]),entry.file)}const paths=new Set([...desiredState.dependencies.map(({workspace})=>packageFileForWorkspace(workspace)),...desiredState.structuredEntries.map(({file:file5})=>file5)]);for(const action2 of plan.actions){if(action2.item==="file"){paths.add(action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.path:action2.desired.path)}else if(action2.item==="dependency"){paths.add(packageFileForWorkspace(action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.workspace:action2.desired.workspace))}else{paths.add(action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.file:action2.desired.file)}}for(const conflict of plan.conflicts){const relativePath=entryPath.get(`${conflict.item}\x00${conflict.identity}`);if(relativePath!==undefined){paths.add(relativePath)}}for(const skip of plan.skips){const relativePath=entryPath.get(`${skip.item}\x00${skip.identity}`);if(relativePath!==undefined){paths.add(relativePath)}}for(const failure of plan.failures){if(failure._tag==="CrossFamilyScaffoldOwnershipFailure"){paths.add(failure.path);continue}if("item"in failure){const relativePath=entryPath.get(`${failure.item}\x00${failure.identity}`);if(relativePath!==undefined){paths.add(relativePath)}}}return paths};var removableStaleManagedFiles=({plan,reconciliationPaths,staleFiles})=>{const safeFileActionPaths=new Set(plan.actions.flatMap((action2)=>{if(action2.item!=="file"){return[]}return[action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.path:action2.desired.path]}));return staleFiles.filter((relativePath)=>!reconciliationPaths.has(relativePath)||safeFileActionPaths.has(relativePath)).toSorted()};var reconciliationStatus=(outcomes)=>{const blocked=outcomes.some(({_tag})=>_tag==="ScaffoldActionBlocked"||_tag==="ScaffoldActionFailed"||_tag==="ScaffoldConflictPreserved"||_tag==="ScaffoldPlanningFailed");if(!blocked){return"succeeded"}return outcomes.some(({_tag})=>_tag==="ScaffoldActionSucceeded")?"partial":"failed"};var publicReconciliationOperation=(action2)=>{if(action2._tag==="SafeCreateScaffoldEntry"){return"create"}return action2._tag==="SafeUpdateScaffoldEntry"?"update":"remove"};var publicReconciliationActions=(plan)=>plan.actions.map((action2)=>({identity:action2.identity,item:action2.item,operation:publicReconciliationOperation(action2)}));var mergePrioritizedChanges=(target,changes)=>{const priority={changed:0,"local-edited":1,missing:2};for(const change of changes){const previous=target.get(change.path);if(previous===undefined||priority[change.status]>priority[previous.status]){target.set(change.path,change)}}};var observeStructuredValue=(document,entry)=>{let value5=document;for(const[index2,segment]of entry.path.entries()){if(typeof value5!=="object"||value5===null||Array.isArray(value5)){return{_tag:"InvalidStructuredObservation",message:`Structured configuration cannot traverse ${entry.path.slice(0,index2).join(".")}: ${entry.file}`}}if(!Object.hasOwn(value5,segment)){return{_tag:"MissingStructuredObservation"}}value5=value5[segment]}const expectedHook=managedLifecycleHook(entry);if(expectedHook!==undefined){if(!Array.isArray(value5)){return{_tag:"InvalidStructuredObservation",message:`Lifecycle hook configuration is not an array: ${entry.file}`}}const observedHook=value5.find((candidate)=>stableJsonStringify(candidate)===stableJsonStringify(expectedHook.value));return observedHook===undefined?{_tag:"MissingStructuredObservation"}:{_tag:"PresentStructuredObservation",value:[observedHook]}}return{_tag:"PresentStructuredObservation",value:value5}};var dependencyObservationIdentity=({name:name2,section:section2,workspace})=>JSON.stringify([workspace,section2,name2]);var structuredObservationIdentity=({file:file5,kind,path:entryPath})=>JSON.stringify([file5,kind,entryPath]);var observedEntryKey=(item,identity3)=>JSON.stringify([item,identity3]);var observeDesiredState=({desiredState,manifest,rootDirectory,semanticState})=>{const desiredFiles=new Map([...desiredState.files,...semanticState.files].map((file5)=>[file5.path,file5]));const files=new Map;for(const file5 of manifest.managedFiles??[]){files.set(file5.path,{kind:file5.kind})}for(const file5 of desiredFiles.values()){files.set(file5.path,{kind:file5.kind,...file5.mode===undefined?{}:{mode:file5.mode}})}const dependencyEntries=new Map([...desiredState.dependencies,...manifest.managedDependencies??[]].map((entry)=>[dependencyObservationIdentity(entry),entry]));const structuredEntries=new Map([...desiredState.structuredEntries,...semanticState.structuredEntries,...manifest.managedStructuredEntries??[]].map((entry)=>[structuredObservationIdentity(entry),entry]));const invalidEntries=new Map;for(const entry of structuredEntries.values()){const identity3=structuredObservationIdentity(entry);try{resolveMutableJsonPath(rootDirectory,entry.file);if(!files.has(entry.file)){files.set(entry.file,{kind:"harness"})}}catch(error2){invalidEntries.set(observedEntryKey("structured-entry",identity3),{identity:identity3,item:"structured-entry",message:error2 instanceof Error?error2.message:String(error2)})}}const dependencies=[...dependencyEntries.values()].flatMap((dependency)=>{const identity3=dependencyObservationIdentity(dependency);let manifestPath;try{manifestPath=resolveMutableJsonPath(rootDirectory,packageFileForWorkspace(dependency.workspace))}catch(error2){invalidEntries.set(observedEntryKey("dependency",identity3),{identity:identity3,item:"dependency",message:error2 instanceof Error?error2.message:String(error2)});return[]}if(!existsSync14(manifestPath)){return[]}const packageManifest=readJsonObject(manifestPath);if(packageManifest===null){invalidEntries.set(observedEntryKey("dependency",identity3),{identity:identity3,item:"dependency",message:`Package manifest is not a JSON object: ${packageFileForWorkspace(dependency.workspace)}`});return[]}const section2=packageManifest[dependency.section];if(section2===undefined){return[]}if(typeof section2!=="object"||section2===null||Array.isArray(section2)){invalidEntries.set(observedEntryKey("dependency",identity3),{identity:identity3,item:"dependency",message:`Package dependency section is not an object: ${dependency.section}`});return[]}const value5=section2[dependency.name];if(value5===undefined){return[]}if(typeof value5!=="string"){invalidEntries.set(observedEntryKey("dependency",identity3),{identity:identity3,item:"dependency",message:`Package dependency version is not a string: ${identity3}`});return[]}return[{name:dependency.name,section:dependency.section,version:value5,workspace:dependency.workspace}]});const observedStructuredEntries=[...structuredEntries.values()].flatMap((entry)=>{const identity3=structuredObservationIdentity(entry);let absolutePath;try{absolutePath=resolveMutableJsonPath(rootDirectory,entry.file)}catch(error2){invalidEntries.set(observedEntryKey("structured-entry",identity3),{identity:identity3,item:"structured-entry",message:error2 instanceof Error?error2.message:String(error2)});return[]}if(!existsSync14(absolutePath)){return[]}const document=readJsonObject(absolutePath);if(document===null){invalidEntries.set(observedEntryKey("structured-entry",identity3),{identity:identity3,item:"structured-entry",message:`Structured configuration is not a JSON object: ${entry.file}`});return[]}const observation=observeStructuredValue(document,entry);if(observation._tag==="InvalidStructuredObservation"){invalidEntries.set(observedEntryKey("structured-entry",identity3),{identity:identity3,item:"structured-entry",message:observation.message});return[]}return observation._tag==="MissingStructuredObservation"?[]:[{file:entry.file,kind:entry.kind,path:entry.path,value:observation.value}]});const observedFiles=[...files].flatMap(([relativePath,file5])=>{try{return[observeManagedFile({...file5.mode===undefined?{}:{expectedMode:file5.mode},kind:file5.kind,relativePath,rootDirectory})]}catch(error2){invalidEntries.set(observedEntryKey("file",relativePath),{identity:relativePath,item:"file",message:error2 instanceof Error?error2.message:String(error2)});return[]}});return{dependencies,files:observedFiles,invalidEntries:[...invalidEntries.values()].toSorted((left,right)=>left.identity.localeCompare(right.identity)),structuredEntries:observedStructuredEntries,version:"1"}};var priorReceiptFromManifest=(manifest,rootDirectory,desiredFiles)=>{const desiredModes=new Map(desiredFiles.map((file5)=>[file5.path,file5.mode]));return{dependencies:manifest.managedDependencies??[],files:(manifest.managedFiles??[]).filter(({path:relativePath})=>relativePath!==scaffoldManifestFile).map((file5)=>{const type2=manifest.managedFileTypes?.[file5.path]==="symlink"?"symlink":"file";const recordedMode=manifest.managedFileModes?.[file5.path];const absolutePath=resolveContainedReceiptPath(rootDirectory,file5.path,{followLeaf:false});const currentMode=type2==="file"&&pathLexists(absolutePath)&&lstatSync4(absolutePath).isFile()?fileMode2(lstatSync4(absolutePath).mode):undefined;const desiredMode=desiredModes.get(file5.path);let inferredMode;if(recordedMode===undefined&&type2==="symlink"){inferredMode=null}else if(recordedMode===undefined&¤tMode!==undefined&&desiredMode!==undefined&¤tMode===desiredMode%512&&hashPath(rootDirectory,file5.path)===file5.sha256){inferredMode=currentMode}const mode=recordedMode===undefined?inferredMode:recordedMode;return{kind:file5.kind,...mode===undefined?{}:{mode},path:file5.path,sha256:file5.sha256,type:type2}}),structuredEntries:(manifest.managedStructuredEntries??[]).map((entry)=>({...entry,value:entry.value})),version:"1"}};var changeStatus=({path:relativePath,observedFiles,previousFiles})=>{const observed=observedFiles.get(relativePath);if(observed===undefined||observed.type==="missing"){return"missing"}const previous=previousFiles.find((file5)=>file5.path===relativePath);return previous!==undefined&&previous.sha256!==observed.sha256?"local-edited":"changed"};var compareObservedState=({desiredState,manifest,observedState,semanticState})=>{const previousFiles=manifest.managedFiles??[];const observedFiles=new Map(observedState.files.map((file5)=>[file5.path,file5]));const semanticPaths=new Set(semanticState.files.map((file5)=>file5.path));const changes=new Map;const addChange=(change)=>{const previous=changes.get(change.path);const priority={changed:0,"local-edited":1,missing:2};if(previous===undefined||priority[change.status]>priority[previous.status]){changes.set(change.path,change)}};const comparableFiles=new Map([...desiredState.files,...semanticState.files].map((file5)=>[file5.path,file5]));const compareFiles=()=>{for(const file5 of comparableFiles.values()){const observed=observedFiles.get(file5.path);if(file5.kind==="context-plan"||file5.kind==="projection-receipt"||observed?.projectAuthored===true&&!semanticPaths.has(file5.path)){continue}const fingerprintMatches=observed?.fingerprint===desiredFileFingerprint(file5);const jsonMatches=!fingerprintMatches&&file5.encoding!=="base64"&&file5.encoding!=="symlink"&&file5.mode===undefined&&file5.path.endsWith(".json")&&jsonContentEquals(observed?.content??"",file5.content);if(fingerprintMatches||jsonMatches){continue}addChange({kind:file5.kind,path:file5.path,status:changeStatus({observedFiles,path:file5.path,previousFiles})})}};compareFiles();const observedDependencies=new Map(observedState.dependencies.map((dependency)=>[`${dependency.workspace}:${dependency.section}:${dependency.name}`,dependency]));for(const dependency of desiredState.dependencies){const identity3=`${dependency.workspace}:${dependency.section}:${dependency.name}`;if(observedDependencies.get(identity3)?.version===dependency.version){continue}const packageFile=packageFileForWorkspace(dependency.workspace);addChange({kind:"manifest",path:packageFile,status:changeStatus({observedFiles,path:packageFile,previousFiles})})}const observedStructuredEntries=new Map(observedState.structuredEntries.map((entry)=>[JSON.stringify([entry.file,entry.kind,entry.path]),entry]));for(const entry of[...desiredState.structuredEntries,...semanticState.structuredEntries]){if(entry.file===repoSettingsDisplayFile&&observedFiles.get(entry.file)?.type==="missing"){continue}const identity3=JSON.stringify([entry.file,entry.kind,entry.path]);const observed=observedStructuredEntries.get(identity3);if(observed!==undefined&&stableJsonStringify(observed.value)===stableJsonStringify(entry.value)){continue}addChange({kind:"harness",path:entry.file,status:changeStatus({observedFiles,path:entry.file,previousFiles})})}const desiredPaths=new Set([...desiredState.files.map((file5)=>file5.path),...desiredState.dependencies.map((dependency)=>packageFileForWorkspace(dependency.workspace)),...desiredState.structuredEntries.map((entry)=>entry.file),...semanticState.files.map((file5)=>file5.path),...semanticState.structuredEntries.map((entry)=>entry.file)]);const staleFiles=previousFiles.filter(({path:relativePath})=>relativePath!==scaffoldManifestFile).filter(({kind})=>kind!=="context-plan"&&kind!=="projection-receipt").filter((file5)=>observedFiles.get(file5.path)?.projectAuthored!==true).map((file5)=>file5.path).filter((file5)=>!desiredPaths.has(file5)).toSorted();return{changedFiles:[...changes.values()].toSorted((left,right)=>left.path.localeCompare(right.path)),staleFiles}};var resolveUpdateToolRuntime=({scriptEnvironment,toolRuntime})=>{if(toolRuntime!==undefined){return toolRuntime}if(scriptEnvironment===undefined){return}return makeToolCommandRuntime(Object.fromEntries(Object.entries(scriptEnvironment).filter((entry)=>entry[1]!==undefined)))};var runScaffoldOperation=({operation:operation2,rootDirectory,interaction,check:requestedCheck=false,write:requestedWrite=false,yes:requestedYes=false,emitJson:requestedEmitJson=false,ensureTools:requestedEnsureTools=true,baseline=bundledBaseline,allowBundledBaselineDriftApply=false,toolStdio:requestedToolStdio,toolRuntime,scaffoldLifecycle={},reconciliationApplicators,dependencyProcess=defaultDependencyProcess,configuration={disableBundledUrl:true},emitOutput=true,scriptEnvironment,scriptRuntimePath:scriptRuntimePath2})=>{const check3=operation2==="check"||requestedCheck;const write2=operation2==="update"&&requestedWrite;const yes=operation2==="update"&&requestedYes;const emitJson=operation2==="update"&&requestedEmitJson;const ensureTools2=operation2==="update"&&requestedEnsureTools;const toolStdio=requestedToolStdio??(emitJson?"ignore":"inherit");const resolvedToolRuntime=resolveUpdateToolRuntime({scriptEnvironment,toolRuntime});let updateStagingDirectory=null;let wikiStagingDirectory=null;return gen2(function*executeScaffoldOperation(){const projectSettings=yield*ProjectSettings;const writeHuman=noopHumanOutput;const manifest=yield*try_3({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Failed to read scaffold manifest."}),try:()=>readManifest(rootDirectory)});yield*try_3({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Invalid managed file receipt path."}),try:()=>{for(const file5 of manifest.managedFiles??[]){resolveContainedReceiptPath(rootDirectory,file5.path,{followLeaf:false})}}});const finalPacks=yield*try_3({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Invalid scaffold manifest."}),try:()=>normalizePacks(manifest.finalPacks,baseline)});const repoShapeMode=normalizeRepoShapeMode(manifest.repoShapeMode);const detection=applyRepoShapeMode(yield*detectRepository(rootDirectory),repoShapeMode);const resolved=resolvePackSelection(detection,baseline);const manifestBaseline=manifest.baseline;const baselineDrift=typeof manifestBaseline?.version==="string"&&manifestBaseline.version!==baseline.summary.version;const resolvedPacks=resolved.preselectedPacks;const packDrift=hasActionablePackDrift({finalPacks,resolvedPacks});const updateFinalPacks=write2||yes?acceptResolvedPacks({baseline,finalPacks,resolvedPacks}):finalPacks;const wikiRoot=wikiRootForDetection(detection);const wikiFramework=yield*try_3({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Invalid wiki framework pin."}),try:()=>readValidatedWikiFrameworkPin(path25.join(rootDirectory,wikiRoot))});const wikiPromptTarget=wikiPromptTargetFor({wikiFramework,wikiRoot});const wikiPromptTargets=updateFinalPacks.includes("docs")?[wikiPromptTarget]:[];const expectedDirectory=mkdtempSync3(path25.join(tmpdir6(),"punks-update-"));updateStagingDirectory=expectedDirectory;const repoSettingsOnDisk=yield*projectSettings.read(rootDirectory).pipe(map7(some2),catchTag2("ProjectSettingsMissing",()=>succeed6(none2())),mapError3((cause)=>new CliValidationError({cause,message:cause.message})));const inferredRepoSettings=isNone2(repoSettingsOnDisk)?yield*projectSettings.infer(rootDirectory).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message}))):none2();const repoSettings=match(repoSettingsOnDisk,{onNone:()=>inferredRepoSettings,onSome:({settings})=>some2(settings)});if(isNone2(repoSettings)){return yield*fail6(new CliValidationError({message:`Project settings are missing at ${path25.join(rootDirectory,projectSettingsFile)}.`}))}const calculatedRequiredTools=requiredToolsForSkills2(selectedSkills3(updateFinalPacks,baseline),baseline);const settingsRequiredTools=deriveRequiredTools({repositoryManager:repoSettings.value.repositoryManager,requiredTools:calculatedRequiredTools});const contextPlan=yield*compileScaffoldContextPlan({additionalPromptTargets:wikiPromptTargets,baseline,detection,finalPacks:updateFinalPacks,preserveExistingSubagentManifest:false,scanDirectory:rootDirectory}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})));const settingsChanges=isSome2(repoSettings)?yield*gen2(function*settingsChanges2(){if(isSome2(repoSettingsOnDisk)){const source=path25.join(rootDirectory,projectSettingsFile);const destination=path25.join(expectedDirectory,projectSettingsFile);mkdirSync8(path25.dirname(destination),{recursive:true});cpSync3(source,destination);yield*projectSettings.write(expectedDirectory,{_tag:"CalculatedToolsChange",requiredTools:calculatedRequiredTools});yield*projectSettings.write(expectedDirectory,{_tag:"ManagedVersionsChange",baselineVersion:baseline.summary.version,cliVersion:version2})}else{yield*projectSettings.initialize(expectedDirectory,{calculatedTools:{requiredTools:calculatedRequiredTools},managedVersions:{baselineVersion:baseline.summary.version,cliVersion:version2},userChoices:{assetProviderSlug:repoSettings.value.assetProviderSlug,backlogProvider:repoSettings.value.backlogProvider,...repoSettings.value.backlogProjectUrl===undefined?{}:{backlogProjectUrl:repoSettings.value.backlogProjectUrl},repositoryManager:repoSettings.value.repositoryManager}})}const expectedFile={kind:"harness",path:projectSettingsFile,sha256:hashPath(expectedDirectory,projectSettingsFile)??""};return buildChanges({expectedDirectory,expectedFiles:[expectedFile],previousFiles:[],rootDirectory})}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message}))):[];const materialize=(desiredState)=>writeScaffoldOutput({additionalPromptTargets:wikiPromptTargets,baseline,contextPlan:desiredState?.contextPlan??contextPlan,detection,displayOutputDirectory:rootDirectory,outputDirectory:expectedDirectory,preserveExistingManagedFiles:false,repoShapeMode,scanDirectory:rootDirectory,...scriptEnvironment===undefined?{}:{scriptEnvironment},...scriptRuntimePath2===undefined?{}:{scriptRuntimePath:scriptRuntimePath2},...desiredState===undefined?{}:{desiredState,...isSome2(repoSettings)?{settings:desiredState.settings}:{}}}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})),map7((output2)=>{if(desiredState===undefined){return output2}const contextEvidence=new Set([".devpunks/context-plan.json",".devpunks/harness-projection-receipt.json"]);for(const relativePath of contextEvidence){rmSync6(path25.join(expectedDirectory,relativePath),{force:true})}const manifestPath=path25.join(expectedDirectory,scaffoldManifestFile);const stagedManifest=JSON.parse(readFileSync13(manifestPath,"utf-8"));stagedManifest.generatedFiles=(stagedManifest.generatedFiles??[]).filter((relativePath)=>!contextEvidence.has(relativePath));stagedManifest.managedFiles=(stagedManifest.managedFiles??[]).filter(({path:relativePath})=>!contextEvidence.has(relativePath));if(typeof stagedManifest.managedFileTypes==="object"&&stagedManifest.managedFileTypes!==null){stagedManifest.managedFileTypes=Object.fromEntries(Object.entries(stagedManifest.managedFileTypes).filter(([relativePath])=>!contextEvidence.has(relativePath)))}delete stagedManifest.contextPlanFile;delete stagedManifest.projectionReceiptFile;delete stagedManifest.projectionStatus;writeFileSync8(manifestPath,encodePrettyJson3(stagedManifest));return{...output2,contextPlanFile:null,generatedFiles:output2.generatedFiles.filter((relativePath)=>!contextEvidence.has(relativePath)),managedFiles:output2.managedFiles.filter(({path:relativePath})=>!contextEvidence.has(relativePath)),projectionReceiptFile:null,projectionStatus:null}}));const expected=yield*gen2(function*expected2(){const desiredSettings={...repoSettings.value,baselineVersion:baseline.summary.version,cliVersion:version2,requiredTools:settingsRequiredTools};const gather=()=>planScaffoldOutput({additionalPromptTargets:wikiPromptTargets,baseline,contextPlan,detection,displayOutputDirectory:rootDirectory,outputDirectory:rootDirectory,preserveExistingManagedFiles:false,repoShapeMode,scanDirectory:rootDirectory,...scriptEnvironment===undefined?{}:{scriptEnvironment},...scriptRuntimePath2===undefined?{}:{scriptRuntimePath:scriptRuntimePath2},...isSome2(repoSettings)?{settings:desiredSettings}:{}}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})),map7((plan)=>({...plan,files:plan.files.filter(({kind})=>kind!=="projection-receipt")})),map7((plan)=>desiredScaffoldStateInput({...plan,settings:desiredSettings})));const observe=({desiredState})=>sync2(()=>{const semanticState=semanticDesiredState({desiredState,detection,finalPacks:updateFinalPacks,settings:desiredSettings,wikiFramework});return observeDesiredState({desiredState,manifest,rootDirectory,semanticState})});const compiler=scaffoldLifecycle.compileDesiredState===undefined?{}:{compile:scaffoldLifecycle.compileDesiredState};const planReconciliation=scaffoldLifecycle.planReconciliation??((input2)=>planScaffoldReconciliation(input2,nodeScaffoldContentHasher));const reconcile=({desiredState,observedState})=>{const semanticState=semanticDesiredState({desiredState,detection,finalPacks:updateFinalPacks,settings:desiredSettings,wikiFramework});const structuredEntries=[...desiredState.structuredEntries,...semanticState.structuredEntries].filter(({file:file5})=>file5!==repoSettingsDisplayFile);const entryOwnedPaths=new Set([...desiredState.dependencies.map(({workspace})=>packageFileForWorkspace(workspace)),...structuredEntries.map(({file:file5})=>file5)]);const belongsToLegacyFileLane=({kind,path:relativePath})=>kind==="context-plan"||kind==="projection-receipt"||kind==="agent-prompt"||kind==="handoff"||kind==="manifest"||kind==="prompt-spec"||kind==="required-tools"||kind==="subagent"||path25.posix.basename(relativePath)==="CLAUDE.md"||isWikiManagedPath(relativePath)||relativePath===projectAuthoredWikiSyncFile||relativePath===syncSubagentsScriptFile&&isTailoredSyncSubagentsScript(rootDirectory);const files=[...desiredState.files,...semanticState.files].filter((file5)=>!entryOwnedPaths.has(file5.path)&&!belongsToLegacyFileLane(file5));const stagedDesiredState={...desiredState,files,structuredEntries};const manifestReceipt=priorReceiptFromManifest(manifest,rootDirectory,stagedDesiredState.files);const applicationReceipt={...manifestReceipt,files:manifestReceipt.files.filter(({path:relativePath})=>!entryOwnedPaths.has(relativePath)),structuredEntries:manifestReceipt.structuredEntries.filter(({file:file5})=>file5!==repoSettingsDisplayFile)};const planningReceipt={...applicationReceipt,files:applicationReceipt.files.filter((file5)=>!belongsToLegacyFileLane(file5))};const plan=planReconciliation({desiredState:stagedDesiredState,observedState,priorReceipt:planningReceipt});const comparison=compareObservedState({desiredState,manifest,observedState,semanticState});return materialize(desiredState).pipe(map7((output2)=>({comparison,desiredState:stagedDesiredState,output:output2,plan,priorReceipt:applicationReceipt})))};if(operation2==="check"){const lifecycle2=yield*runCheckScaffoldLifecycle({...compiler,compare:reconcile,gather,observe});if(lifecycle2._tag==="ScaffoldLifecycleCompilationFailed"){return yield*fail6(new CliValidationError({message:lifecycle2.compilation.errors.map(({message})=>message).join(`
|
|
1534
1534
|
`)}))}return lifecycle2.comparison}const lifecycle=yield*runUpdateScaffoldLifecycle({...compiler,gather,observe,reconcile});if(lifecycle._tag==="ScaffoldLifecycleCompilationFailed"){return yield*fail6(new CliValidationError({message:lifecycle.compilation.errors.map(({message})=>message).join(`
|
|
1535
1535
|
`)}))}return lifecycle.reconciliation});const observedComparison=expected.comparison;const expectedOutput=expected.output;const reconciliationPlan=expected.plan;const receiptEntryOwnedPaths=new Set([...expected.desiredState.dependencies.map(({workspace})=>packageFileForWorkspace(workspace)),...expected.desiredState.structuredEntries.map(({file:file5})=>file5)]);const reconciliationPaths=reconciliationControlledPaths({desiredState:expected.desiredState,plan:reconciliationPlan,priorReceipt:expected.priorReceipt});const previousFiles=manifest.managedFiles??[];const previousFilesByPath=new Map(previousFiles.map((file5)=>[file5.path,file5]));const stageLegacyClaudeSymlinks=()=>{const stagedLegacyClaudeSymlinkFiles2=previousFiles.filter((file5)=>{if(file5.kind!=="harness"||path25.posix.basename(file5.path)!=="CLAUDE.md"||existsSync14(path25.join(expectedDirectory,file5.path))||!existsSync14(path25.join(rootDirectory,file5.path))||!lstatSync4(path25.join(rootDirectory,file5.path)).isSymbolicLink()||hashPath(rootDirectory,file5.path)!==file5.sha256){return false}const canonicalSource=path25.join(rootDirectory,canonicalClaudePromptSource(file5.path));return existsSync14(canonicalSource)&&lstatSync4(canonicalSource).isFile()});for(const file5 of stagedLegacyClaudeSymlinkFiles2){copyManagedFile({fromDirectory:rootDirectory,relativePath:file5.path,toDirectory:expectedDirectory})}return stagedLegacyClaudeSymlinkFiles2};const stagedLegacyClaudeSymlinkFiles=stageLegacyClaudeSymlinks();const claudeCandidatePaths=new Set([...previousFiles.filter(({kind,path:relativePath})=>kind==="harness"&&path25.posix.basename(relativePath)==="CLAUDE.md").map(({path:relativePath})=>relativePath),...collectRelativeFiles2(expectedDirectory,".").filter((relativePath)=>path25.posix.basename(relativePath)==="CLAUDE.md")]);const managedClaudeCopyPaths=new Set([...claudeCandidatePaths].filter((relativePath)=>{const previousFile=previousFilesByPath.get(relativePath);return isManagedClaudePromptCopy({previousFile,recordedFileType:previousFile===undefined?undefined:manifest.managedFileTypes?.[relativePath],relativePath,rootDirectory})}));const stageManagedClaudeCopies=()=>{for(const relativePath of managedClaudeCopyPaths){const canonicalSourceRelativePath=canonicalClaudePromptSource(relativePath);const stagedCanonicalSource=path25.join(expectedDirectory,canonicalSourceRelativePath);const currentCanonicalSource=path25.join(rootDirectory,canonicalSourceRelativePath);const previousCanonicalSource=previousFilesByPath.get(canonicalSourceRelativePath);const canonicalSource=previousCanonicalSource!==undefined&&hashPath(rootDirectory,canonicalSourceRelativePath)===previousCanonicalSource.sha256?stagedCanonicalSource:currentCanonicalSource;if(existsSync14(canonicalSource)&&lstatSync4(canonicalSource).isFile()){const stagedTarget=path25.join(expectedDirectory,relativePath);mkdirSync8(path25.dirname(stagedTarget),{recursive:true});rmSync6(stagedTarget,{force:true,recursive:true});cpSync3(canonicalSource,stagedTarget)}else{copyManagedFile({fromDirectory:rootDirectory,relativePath,toDirectory:expectedDirectory})}}};stageManagedClaudeCopies();const managedClaudeCanonicalSourcePaths=new Set([...managedClaudeCopyPaths].map(canonicalClaudePromptSource).filter((relativePath)=>{const previousFile=previousFilesByPath.get(relativePath);return previousFile!==undefined&&hashPath(rootDirectory,relativePath)===previousFile.sha256&&expectedOutput.managedFiles.some(({path:expectedPath})=>expectedPath===relativePath)}));const preservedManagedClaudeCopyFiles=[...managedClaudeCopyPaths].filter((relativePath)=>!expectedOutput.managedFiles.some(({path:expectedPath})=>expectedPath===relativePath)).flatMap((relativePath)=>{const previousFile=previousFilesByPath.get(relativePath);return previousFile===undefined?[]:[{...previousFile,sha256:hashPath(expectedDirectory,relativePath)??""}]});const consumerOwnedClaudePaths=new Set([...claudeCandidatePaths].filter((relativePath)=>{if(managedClaudeCopyPaths.has(relativePath)){return false}const previousFile=previousFilesByPath.get(relativePath);return isConsumerOwnedClaudePrompt({previousFile,recordedFileType:previousFile===undefined?undefined:manifest.managedFileTypes?.[relativePath],relativePath,rootDirectory})}));const recordedContextEvidence=previousFiles.filter(({kind})=>kind==="context-plan"||kind==="projection-receipt");yield*try_3({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Recorded context evidence drifted."}),try:()=>{for(const file5 of recordedContextEvidence){if(hashPath(rootDirectory,file5.path)!==file5.sha256){throw new Error(`Recorded context evidence drifted: ${file5.path}`)}}}});const prepareManagedState=()=>{const preservedContextEvidence=previousFiles.filter(({kind})=>kind==="context-plan"||kind==="projection-receipt").map((file5)=>{copyManagedFile({fromDirectory:rootDirectory,relativePath:file5.path,toDirectory:expectedDirectory});return file5});const expectedManagedFiles2=[...expectedOutput.managedFiles.filter(({path:relativePath})=>!receiptEntryOwnedPaths.has(relativePath)).filter(({path:relativePath})=>!consumerOwnedClaudePaths.has(relativePath)&&!preservedContextEvidence.some(({path:preservedPath})=>preservedPath===relativePath)).filter((file5)=>!isProjectAuthoredManagedFile({file:file5,rootDirectory})||pathLexists(path25.join(rootDirectory,file5.path))).map((file5)=>managedClaudeCopyPaths.has(file5.path)?{...file5,sha256:hashPath(expectedDirectory,file5.path)??""}:file5),...stagedLegacyClaudeSymlinkFiles,...preservedManagedClaudeCopyFiles,...preservedContextEvidence].filter(({path:relativePath})=>relativePath!==scaffoldManifestFile).toSorted((left,right)=>left.path.localeCompare(right.path));const expectedManifestPath=path25.join(expectedDirectory,scaffoldManifestFile);const expectedManifest=JSON.parse(readFileSync13(expectedManifestPath,"utf-8"));if(preservedContextEvidence.length>0){expectedManifest.generatedFiles=[...new Set([...expectedManifest.generatedFiles??[],...preservedContextEvidence.map(({path:relativePath})=>relativePath)])].toSorted();if(preservedContextEvidence.some(({kind})=>kind==="context-plan")){expectedManifest.contextPlanFile=".devpunks/context-plan.json"}if(preservedContextEvidence.some(({kind})=>kind==="projection-receipt")){const projectionReceiptFile=".devpunks/harness-projection-receipt.json";const projectionReceipt=JSON.parse(readFileSync13(path25.join(expectedDirectory,projectionReceiptFile),"utf-8"));expectedManifest.projectionReceiptFile=projectionReceiptFile;if(typeof projectionReceipt.status==="string"){expectedManifest.projectionStatus=projectionReceipt.status}}}const expectedManagedPaths=new Set(expectedManagedFiles2.map(({path:relativePath})=>relativePath));const expectedManagedFileTypes2=Object.fromEntries([...expectedManagedPaths].map((relativePath)=>[relativePath,lstatSync4(path25.join(expectedDirectory,relativePath)).isSymbolicLink()?"symlink":"file"]));expectedManifest.managedFiles=manifest.managedFiles??[];expectedManifest.managedFileTypes=manifest.managedFileTypes??{};expectedManifest.managedFileModes=manifest.managedFileModes??{};expectedManifest.managedDependencies=manifest.managedDependencies??[];expectedManifest.managedStructuredEntries=manifest.managedStructuredEntries??[];writeFileSync8(expectedManifestPath,encodePrettyJson3(expectedManifest));const reconciliationFilePaths=new Set(expected.desiredState.files.map(({path:relativePath})=>relativePath));const applicationPriorReceipt2={...expected.priorReceipt,files:[...expected.priorReceipt.files.filter(({path:relativePath})=>reconciliationFilePaths.has(relativePath)),...expectedManagedFiles2.filter(({path:relativePath})=>!reconciliationFilePaths.has(relativePath)).map((file5)=>{const absolutePath=path25.join(expectedDirectory,file5.path);const type2=lstatSync4(absolutePath).isSymbolicLink()?"symlink":"file";return{...file5,mode:type2==="symlink"?null:fileMode2(lstatSync4(absolutePath).mode),type:type2}})].toSorted((left,right)=>left.path.localeCompare(right.path))};const stagedChanges2=buildChanges({expectedDirectory,expectedFiles:expectedManagedFiles2.filter((file5)=>file5.kind!=="context-plan"&&file5.kind!=="projection-receipt"&&(managedClaudeCopyPaths.has(file5.path)||managedClaudeCanonicalSourcePaths.has(file5.path)||!isProjectAuthoredManagedFile({file:file5,rootDirectory}))),previousFiles,rootDirectory});return{applicationPriorReceipt:applicationPriorReceipt2,expectedManagedFileTypes:expectedManagedFileTypes2,expectedManagedFiles:expectedManagedFiles2,stagedChanges:stagedChanges2}};const{applicationPriorReceipt,expectedManagedFiles,expectedManagedFileTypes,stagedChanges}=prepareManagedState();const compileManagedChanges=()=>{const changesByPath=new Map;const applicableObservedChanges=observedComparison.changedFiles.filter(({path:relativePath})=>pathLexists(path25.join(expectedDirectory,relativePath)));mergePrioritizedChanges(changesByPath,[...stagedChanges,...applicableObservedChanges]);const changes2=[...changesByPath.values()].toSorted((left,right)=>left.path.localeCompare(right.path));const legacyRequiredToolsPromptChanges2=buildLegacyRequiredToolsPromptChanges({rootDirectory});const gitignoreChanges2=buildGitignoreCleanup({expectedDirectory,rootDirectory});const compileWikiAlignment=()=>{const shouldAlignWiki=updateFinalPacks.includes("docs")||expectedOutput.managedFiles.some((file5)=>isWikiManagedPath(file5.path));if(shouldAlignWiki){const wikiExpectedDirectory=mkdtempSync3(path25.join(tmpdir6(),"punks-wiki-update-"));wikiStagingDirectory=wikiExpectedDirectory;return buildWikiAlignment({detection,expectedDirectory:wikiExpectedDirectory,rootDirectory,...scriptEnvironment===undefined?{}:{scriptEnvironment},...scriptRuntimePath2===undefined?{}:{scriptRuntimePath:scriptRuntimePath2}})}return null};const wikiAlignment2=compileWikiAlignment();const allChangesByPath=new Map;mergePrioritizedChanges(allChangesByPath,[...changes2,...legacyRequiredToolsPromptChanges2,...gitignoreChanges2,...wikiAlignment2?.changes??[],...settingsChanges]);const allChanges2=[...allChangesByPath.values()].toSorted((left,right)=>left.path.localeCompare(right.path));const expectedPaths=new Set([...expectedManagedFiles.map((file5)=>file5.path),...wikiAlignment2?.expectedFiles.map((file5)=>file5.path)??[]]);const structuredConfigurationFiles=new Set([".claude/settings.json",".cursor/hooks.json",repoSettingsDisplayFile]);const staleFiles2=removableStaleManagedFiles({plan:reconciliationPlan,reconciliationPaths,staleFiles:[...new Set(previousFiles.filter(({path:relativePath})=>relativePath!==scaffoldManifestFile).filter((file5)=>!isProjectAuthoredManagedFile({file:file5,rootDirectory})).filter((file5)=>!consumerOwnedClaudePaths.has(file5.path)).map((file5)=>file5.path).filter((file5)=>!hasIgnoredWikiAlignmentPath(file5)).filter((file5)=>!structuredConfigurationFiles.has(file5)).filter((file5)=>!expectedPaths.has(file5)))]});const ownershipMetadata=(files,fileTypes)=>{const ownedFiles=files.filter(({path:relativePath})=>relativePath!==scaffoldManifestFile&&!reconciliationPaths.has(relativePath));const ownedPaths=new Set(ownedFiles.map(({path:relativePath})=>relativePath));return JSON.stringify({fileTypes:Object.fromEntries(Object.entries(fileTypes).filter(([relativePath])=>ownedPaths.has(relativePath)).toSorted(([left],[right])=>left.localeCompare(right))),files:ownedFiles.map(({path:relativePath,kind})=>Object.fromEntries([["path",relativePath],["kind",kind]])).toSorted((left,right)=>left.path.localeCompare(right.path))})};const hasOwnershipMetadataUpdate2=previousFiles.some(({path:relativePath})=>relativePath===scaffoldManifestFile)||manifest.managedFileTypes?.[scaffoldManifestFile]!==undefined||ownershipMetadata(previousFiles,manifest.managedFileTypes??{})!==ownershipMetadata(expectedManagedFiles,expectedManagedFileTypes);const hasManagedUpdates2=allChanges2.length>0||staleFiles2.length>0||hasOwnershipMetadataUpdate2||reconciliationPlan.actions.length>0||reconciliationPlan.conflicts.length>0||reconciliationPlan.failures.length>0;const needsAttention2=hasManagedUpdates2||packDrift||baselineDrift;const driftPrompt2=packDrift?packDriftPrompt({finalPacks,resolvedPacks,rootDirectory}):null;return{allChanges:allChanges2,changes:changes2,driftPrompt:driftPrompt2,gitignoreChanges:gitignoreChanges2,hasManagedUpdates:hasManagedUpdates2,hasOwnershipMetadataUpdate:hasOwnershipMetadataUpdate2,legacyRequiredToolsPromptChanges:legacyRequiredToolsPromptChanges2,needsAttention:needsAttention2,staleFiles:staleFiles2,wikiAlignment:wikiAlignment2}};const{allChanges,changes,driftPrompt,gitignoreChanges,hasManagedUpdates,hasOwnershipMetadataUpdate,legacyRequiredToolsPromptChanges,needsAttention,staleFiles,wikiAlignment}=compileManagedChanges();const decideApplication=()=>gen2(function*decideScaffoldApplication(){const presentUpdatePlan=()=>gen2(function*presentScaffoldUpdatePlan(){if(emitOutput&&!emitJson){yield*interaction.emit({_tag:"Detection",detection});yield*interaction.emit({_tag:"RecordedPacks",packs:finalPacks});yield*interaction.emit({_tag:"Baseline",active:baseline.summary,drift:baselineDrift,recordedVersion:typeof manifestBaseline?.version==="string"?manifestBaseline.version:null});if(packDrift){yield*interaction.emit({_tag:"PackDrift",baseline,prompt:driftPrompt??"",resolved})}yield*interaction.emit({_tag:"ManagedChanges",changes:allChanges});if(staleFiles.length>0){yield*interaction.emit({_tag:"StaleFiles",files:staleFiles})}}yield*writeHuman(renderCommandSection("Update Detection",formatDetectionSummary(detection)));yield*writeHuman("");yield*writeHuman(renderCommandSection("Recorded Packs",finalPacks.length===0?"∅":finalPacks.map((pack)=>`• ${pack}`).join(`
|
|
1536
1536
|
`)));yield*writeHuman("");yield*writeHuman(renderCommandSection("Baseline",[`active: ${baseline.summary.source}/${baseline.summary.channel} ${baseline.summary.version}`,`recorded: ${typeof manifestBaseline?.version==="string"?manifestBaseline.version:"unknown"}`,`drift: ${baselineDrift?"yes":"no"}`].join(`
|
|
@@ -1538,12 +1538,12 @@ Keep this framework pinned unless the user explicitly changes it. \`punks update
|
|
|
1538
1538
|
`)))}yield*writeHuman("");yield*writeHuman(renderCommandSection("Managed Changes",summarizeChanges2(allChanges)));if(staleFiles.length>0){yield*writeHuman("");yield*writeHuman(renderCommandSection("Stale Managed Files",summarizeStaleFiles2(staleFiles)))}});yield*presentUpdatePlan();let applyRequested2=false;if(write2||yes){applyRequested2=true}else if(!check3&&!emitJson&&hasManagedUpdates){applyRequested2=yield*interaction.confirmApply()}const unsafeBundledBaselineDrift=applyRequested2&&baselineDrift&&baseline.summary.source==="bundled"&&!allowBundledBaselineDriftApply;if(unsafeBundledBaselineDrift){return yield*fail6(new CliValidationError({message:["Refusing to apply bundled scaffold assets because the recorded scaffold baseline differs from the active bundled baseline.",`Recorded baseline: ${typeof manifestBaseline?.version==="string"?manifestBaseline.version:"unknown"}.`,`Active baseline: ${baseline.summary.source}/${baseline.summary.channel} ${baseline.summary.version}.`,"Run `hi update --baseline stable --refresh-baseline` when online, upgrade the global `hi`/`hint` CLI if it cannot resolve stable, or pass `--baseline bundled` only when you intentionally want the bundled baseline."].join(`
|
|
1539
1539
|
`)}))}return applyRequested2});const applyRequested=yield*decideApplication();const shouldApply=applyRequested&&(hasManagedUpdates||baselineDrift);const bootstrapRequiredTools=()=>gen2(function*bootstrapScaffoldTools(){if(!applyRequested||!ensureTools2||settingsRequiredTools.length===0){return[]}const requiredTools=settingsRequiredTools;if(emitOutput&&!emitJson){yield*interaction.emit({_tag:"EnsuringTools",toolIds:requiredTools})}yield*writeHuman("");yield*writeHuman(renderHint(`Ensuring required tools: ${requiredTools.join(", ")}`));const statuses=ensureToolsInstalledBestEffort(requiredTools,baseline,resolvedToolRuntime,{stdio:toolStdio});yield*writeHuman(renderCommandSection("Tool bootstrap",statuses.map((entry)=>`• ${entry.toolId}: ${formatToolBootstrapStatus(entry)}`).join(`
|
|
1540
1540
|
`)));const failureDetails=formatToolBootstrapFailureDetails(statuses);if(emitOutput&&!emitJson){yield*interaction.emit({_tag:"ToolBootstrap",statuses});if(failureDetails!==null){yield*interaction.emit({_tag:"ToolBootstrapWarning",statuses})}}if(failureDetails!==null){yield*writeHuman("");yield*writeHuman(renderCommandSection("Tool Bootstrap Warning",failureDetails))}return statuses});const plannedReconciliation={outcomes:scaffoldReconciliationPlanOutcomes(reconciliationPlan),plannedActions:publicReconciliationActions(reconciliationPlan),receipt:null,receiptPersisted:false,status:"planned"};const toolBootstrapStatuses=yield*bootstrapRequiredTools();const applyManagedChanges=()=>gen2(function*applyScaffoldChanges(){if(!shouldApply){return plannedReconciliation}snapshotPreExistingSkillHomes(rootDirectory);for(const change of changes.filter(({path:relativePath})=>!reconciliationPaths.has(relativePath))){copyManagedFile({fromDirectory:expectedDirectory,relativePath:change.path,toDirectory:rootDirectory})}for(const change of gitignoreChanges){copyManagedFile({fromDirectory:expectedDirectory,relativePath:change.path,toDirectory:rootDirectory})}for(const change of legacyRequiredToolsPromptChanges){rewriteLegacyRequiredToolsPrompt({relativePath:change.path,rootDirectory})}if(wikiAlignment!==null){for(const change of wikiAlignment.changes){copyManagedFile({fromDirectory:wikiAlignment.expectedDirectory,relativePath:change.path,toDirectory:rootDirectory})}}for(const change of settingsChanges.filter(({path:relativePath})=>!reconciliationPaths.has(relativePath))){copyManagedFile({fromDirectory:expectedDirectory,relativePath:change.path,toDirectory:rootDirectory})}for(const staleFile of staleFiles){rmSync6(resolveContainedReceiptPath(rootDirectory,staleFile,{followLeaf:false}),{force:true,recursive:true})}copyManagedFile({fromDirectory:expectedDirectory,relativePath:scaffoldManifestFile,toDirectory:rootDirectory});removeHarnessDirectoriesFromGitignore(rootDirectory);const application=yield*applyScaffoldReconciliation({adapters:(()=>{const defaults2=makeScaffoldReconciliationApplicators({dependencyProcess,priorReceipt:applicationPriorReceipt,rootDirectory});return reconciliationApplicators?.(defaults2)??defaults2})(),plan:reconciliationPlan,priorReceipt:applicationPriorReceipt}).pipe(catchTag2("@punks/cli/scaffold-state/ScaffoldApplicationFailures",({partialResult})=>succeed6(partialResult)));return{...application,plannedActions:publicReconciliationActions(reconciliationPlan),status:reconciliationStatus(application.outcomes)}});const reconciliation=yield*applyManagedChanges();const finalizeUpdateResult=()=>{const buildFinalResult=()=>{const toolBootstrapFailed=toolBootstrapStatuses.some((entry)=>entry.status==="failed");const operationIssues=[...toolBootstrapStatuses.filter((entry)=>entry.status==="failed").map((entry)=>({action:"bootstrap",code:entry.toolId,errorMessage:entry.errorMessage,kind:"handled-failure",subject:entry.toolId})),...reconciliation?.status==="failed"?[{action:"reconcile",code:"reconciliation-failed",kind:"handled-failure",subject:"managed-scaffold"}]:[]];const unresolvedBaselineDrift=baselineDrift&&(!shouldApply||reconciliation.status!=="succeeded");const unresolvedPackDrift=packDrift&&(!shouldApply||reconciliation.status!=="succeeded");const operationDegradations=[...check3&&hasManagedUpdates?[{code:"managed-drift",subject:"managed-scaffold"}]:[],...unresolvedPackDrift?[{code:"pack-drift",subject:"packs"}]:[],...unresolvedBaselineDrift?[{code:"baseline-drift",subject:"baseline"}]:[],...reconciliation?.status==="partial"?[{code:"reconciliation-partial",subject:"managed-scaffold"}]:[],...reconciliation.outcomes.filter((outcome)=>outcome._tag==="ScaffoldConflictPreserved").map((outcome)=>({code:"scaffold-conflict-preserved",subject:outcome.identity}))];const operationChanges=[...allChanges.filter((change)=>!reconciliationPaths.has(change.path)).map((change)=>({action:change.status,state:shouldApply?"completed":"planned",subject:change.path})),...staleFiles.filter((subject)=>!reconciliationPaths.has(subject)).map((subject)=>({action:"remove",state:shouldApply?"completed":"planned",subject})),...publicReconciliationActions(reconciliationPlan).map((action2)=>({action:action2.operation,state:shouldApply&&reconciliation.outcomes.some((outcome)=>outcome._tag==="ScaffoldActionSucceeded"&&outcome.identity===action2.identity&&outcome.item===action2.item&&outcome.operation===action2.operation)?"completed":"planned",subject:action2.identity})),...ownershipMetadataOperationChanges({allChanges,applied:shouldApply,required:hasOwnershipMetadataUpdate})];const operationStatus=(()=>{if(operationIssues.length>0){return operationChanges.some(({state})=>state==="completed")?"partial":"failed"}if(operationDegradations.length>0){return"degraded"}if(shouldApply){return"success"}return hasManagedUpdates?"planned":"no-op"})();const operationResult={changes:operationChanges,degradations:operationDegradations,issues:operationIssues,nextActions:operationStatus==="no-op"||operationStatus==="success"?[{kind:"none"}]:[...toolBootstrapFailed?[{kind:"run",subject:"hi tools ensure"}]:[],...operationDegradations.length>0||operationIssues.some((issue)=>issue.action!=="bootstrap")?[{kind:"review",subject:"managed-scaffold"}]:[]],status:operationStatus,warnings:baselineDrift?[{code:"baseline-drift",subject:"baseline"}]:[]};const result4={applied:shouldApply,baselineDrift,changedFiles:allChanges,checkFailed:check3&&needsAttention,driftPrompt,finalPacks:updateFinalPacks,operation:operationResult,packDrift,reconciliation,repoShapeMode,resolvedPacks,rootDirectory,scaffoldManifestFile,staleFiles,toolBootstrapStatuses};return result4};return gen2(function*finalizeScaffoldUpdate(){const result4=buildFinalResult();yield*writeHuman("");yield*writeHuman(renderCommandSection("Update Complete",[updateCompleteMessage({applyRequested,hasManagedUpdates}),`Changed files: ${allChanges.length}`,`Stale files: ${staleFiles.length}`,`Manifests scanned: ${manifestPaths(detection).join(", ")||"∅"}`,"Guidance: keep phase skills out of scoped `AGENTS.md` primary-skill lines; invoke them from the parent goal/handoff flow.","Guidance: update does not detect overlapping skills; follow-up agent owns skill reconciliation.","Skill homes: `.agents/skills`, `.claude/skills`, `.codex/skills`, `.cursor/skills`, `.opencode/skills`.","Exact name/id overlap: keep HI baseline active, remove active local copies or mirrors, archive evidence.","Archive target: `.devpunks/replaced-skills/<skill-id>/...`; inspect `.devpunks/pre-existing-skills` when present.","Non-overlaps stay mirrored; semantic overlap or baseline integration goes to `hi report`."].join(`
|
|
1541
|
-
`)));if(emitOutput&&emitJson){yield*interaction.emit({_tag:"Json",result:result4})}else if(emitOutput){yield*interaction.emit({_tag:"Complete",applyRequested,changedFiles:allChanges.length,hasManagedUpdates,manifestPaths:manifestPaths(detection),staleFiles:staleFiles.length})}if(result4.applied){yield*submitCliEventEffect("cli.scaffold.update.applied",{baseline:{version:baseline.summary.version},configuration,cwd:rootDirectory})}return result4})};return yield*finalizeUpdateResult()}).pipe(ensuring2(sync2(()=>{if(updateStagingDirectory!==null){rmSync6(updateStagingDirectory,{force:true,recursive:true})}if(wikiStagingDirectory!==null){rmSync6(wikiStagingDirectory,{force:true,recursive:true})}})))};var runUpdate=(options4)=>runScaffoldOperation({...options4,operation:"update"});var failureMessage=(cause)=>cause instanceof Error?cause.message:String(cause);var silentUpdateInteraction={confirmApply:()=>succeed6(false),emit:()=>void_3};var nonBlankEnvironmentValue=(value5)=>value5!==undefined&&value5.trim().length>0?value5:undefined;var operatorSkillOperationsLayer=effect(OperatorSkillOperations,gen2(function*makeOperatorSkillOperations(){const runtime=yield*CliRuntimeConfig;const skillsCli=yield*SkillsCli;return{run:(action2)=>gen2(function*runOperatorSkillOperation(){const cwd=process.cwd();const activeAgent=resolveActiveOperatorAgent(runtime.commandEnvironment);if(activeAgent===undefined){return yield*new InvalidOperatorContext({message:"Cannot determine the active agent. Set HI_OPERATOR_AGENT to the Skills CLI agent name."})}const migrationRetryToken=nonBlankEnvironmentValue(runtime.commandEnvironment.HI_OPERATOR_MIGRATION_RETRY);const mutationRetryToken=nonBlankEnvironmentValue(runtime.commandEnvironment.HI_OPERATOR_MUTATION_RETRY);return yield*executeOperatorAction({action:action2,input:{activeAgent,activeCliVersion:version2,cwd,projectRoot:findOperatorProjectRoot(cwd)},...migrationRetryToken===undefined?{}:{migrationRetryToken},...mutationRetryToken===undefined?{}:{mutationRetryToken}})}).pipe(provideService2(SkillsCli,skillsCli))}}));var resolveFeatureBaseline=({baseline,refreshBaseline,rootDirectory,controlPlane,release,runtime,httpClient})=>resolveBaseline(baselineResolveOptions(fromNullishOr(baseline),refreshBaseline,rootDirectory,{controlPlane,release,runtime})).pipe(provideService2(HttpClient,httpClient));var reportSubmissionOperationsLayer=effect(ReportSubmissionOperations,gen2(function*makeReportSubmissionOperations(){const controlPlane=yield*CliControlPlaneConfig;const httpClient=yield*HttpClient;return{cliVersion:version2,observeRepository:observedRepository,recordSubmitted:(rootDirectory)=>submitCliEventEffect("cli.harness.report.submitted",{configuration:controlPlane,cwd:rootDirectory}).pipe(provideService2(HttpClient,httpClient),mapError3((cause)=>new ReportSubmissionOperationFailure({cause,message:failureMessage(cause),operation:"record-submitted"}))),resolveControlPlaneUrl:()=>succeed6(resolveControlPlaneUrl(undefined,controlPlane)),submit:(baseUrl2,report)=>submitHarnessReport({baseUrl:baseUrl2,report}).pipe(provideService2(HttpClient,httpClient),mapError3((cause)=>new ReportSubmissionOperationFailure({cause,message:failureMessage(cause),operation:"submit-report"})))}}));var repositoryCheckOperationsLayer=effect(RepositoryCheckOperations,gen2(function*makeRepositoryCheckOperations(){const controlPlane=yield*CliControlPlaneConfig;const release=yield*CliReleaseConfig;const runtime=yield*CliRuntimeConfig;const httpClient=yield*HttpClient;const projectSettings=yield*ProjectSettings;return{...release.baseline===undefined?{}:{configuredBaseline:release.baseline},checkUpdate:(input2)=>gen2(function*checkUpdate(){const baseline=yield*resolveFeatureBaseline({baseline:input2.baseline,controlPlane,httpClient,refreshBaseline:input2.refreshBaseline,release,rootDirectory:input2.rootDirectory,runtime});const update3=yield*runUpdate({baseline,check:true,configuration:controlPlane,emitJson:false,emitOutput:false,interaction:silentUpdateInteraction,rootDirectory:input2.rootDirectory,scriptEnvironment:runtime.commandEnvironment,scriptRuntimePath:runtime.scriptRuntimePath,write:false,yes:false}).pipe(provideService2(HttpClient,httpClient));const{operation:_operation,reconciliation:_reconciliation,...publicUpdate}=update3;return{baselineVersion:baseline.summary.version,update:publicUpdate}}).pipe(provideService2(ProjectSettings,projectSettings),mapError3((cause)=>new RepositoryCheckOperationFailure({cause,message:failureMessage(cause),operation:"check-repository-update"}))),cliVersion:version2,updateTag:release.updateTag}}));var repositoryScaffoldingResult=(result4)=>({machinePayload:{...result4,toolBootstrapStatuses:(result4.toolBootstrapStatuses??[]).map((tool)=>({...tool.status==="failed"?{errorMessage:`Required tool '${tool.toolId}' is unavailable after bootstrap.`}:{},status:tool.status,toolId:tool.toolId}))},outputDirectory:result4.outputDirectory,projectionStatus:result4.projectionStatus,toolBootstrapStatuses:(result4.toolBootstrapStatuses??[]).map((tool)=>({...tool.status==="failed"?{errorMessage:`Required tool '${tool.toolId}' is unavailable after bootstrap.`}:{},status:tool.status,toolId:tool.toolId}))});var repositoryScaffoldingOperationsLayer=effect(RepositoryScaffoldingOperations,gen2(function*makeRepositoryScaffoldingOperations(){const controlPlane=yield*CliControlPlaneConfig;const release=yield*CliReleaseConfig;const runtime=yield*CliRuntimeConfig;const httpClient=yield*HttpClient;const projectSettings=yield*ProjectSettings;const scaffoldCapabilities=yield*ScaffoldCapabilities;return{run:(input2,interaction)=>gen2(function*run(){const baseline=yield*resolveFeatureBaseline({baseline:input2.baseline,controlPlane,httpClient,refreshBaseline:input2.refreshBaseline,release,rootDirectory:input2.kind==="init"?input2.outputDirectory:input2.scanDirectory,runtime});if(input2.kind==="init"){const result5=yield*runStageScaffold({baseline,commandId:"init",configuration:controlPlane,interaction,outputDirectory:input2.outputDirectory,scriptEnvironment:runtime.commandEnvironment,scriptRuntimePath:runtime.scriptRuntimePath}).pipe(provideService2(HttpClient,httpClient),provideService2(ProjectSettings,projectSettings));return repositoryScaffoldingResult(result5)}const result4=yield*runScaffold({assumeYes:input2.assumeYes,baseline,configuration:controlPlane,emitJson:input2.emitJson,interaction,...input2.outputDirectory===undefined?{}:{outputDirectory:input2.outputDirectory},repoShapeMode:input2.repoShape,scanDirectory:input2.scanDirectory,scriptEnvironment:runtime.commandEnvironment,scriptRuntimePath:runtime.scriptRuntimePath,toolStdio:input2.toolStdio}).pipe(provideService2(HttpClient,httpClient),provideService2(ProjectSettings,projectSettings),provideService2(ScaffoldCapabilities,scaffoldCapabilities));return repositoryScaffoldingResult(result4)}).pipe(mapError3((cause)=>new RepositoryScaffoldingOperationFailure({cause,message:failureMessage(cause),operation:input2.kind==="init"?"initialize-repository":"setup-repository"})))}}));var scaffoldUpdateOperationsLayer=effect(ScaffoldUpdateOperations,gen2(function*makeScaffoldUpdateOperations(){const controlPlane=yield*CliControlPlaneConfig;const release=yield*CliReleaseConfig;const runtime=yield*CliRuntimeConfig;const httpClient=yield*HttpClient;const projectSettings=yield*ProjectSettings;return{run:(input2,interaction)=>gen2(function*run(){const baseline=yield*resolveFeatureBaseline({baseline:input2.baseline,controlPlane,httpClient,refreshBaseline:input2.refreshBaseline,release,rootDirectory:input2.rootDirectory,runtime});return yield*runUpdate({allowBundledBaselineDriftApply:input2.baseline==="bundled"||release.baseline==="bundled",baseline,check:input2.check,configuration:controlPlane,emitJson:input2.emitJson,emitOutput:false,interaction,rootDirectory:input2.rootDirectory,scriptEnvironment:runtime.commandEnvironment,scriptRuntimePath:runtime.scriptRuntimePath,toolStdio:input2.toolStdio,write:input2.write,yes:input2.yes}).pipe(provideService2(HttpClient,httpClient),provideService2(ProjectSettings,projectSettings))}).pipe(mapError3((cause)=>new ScaffoldUpdateOperationFailure({cause,message:failureMessage(cause),operation:"update-scaffold"})))}}));var toolEnsureOperationsLayer=effect(ToolEnsureOperations,gen2(function*makeToolEnsureOperations(){const controlPlane=yield*CliControlPlaneConfig;const release=yield*CliReleaseConfig;const runtime=yield*CliRuntimeConfig;const httpClient=yield*HttpClient;const scaffoldCapabilities=yield*ScaffoldCapabilities;return{run:(input2)=>gen2(function*run(){const baseline=yield*resolveFeatureBaseline({baseline:input2.baseline,controlPlane,httpClient,refreshBaseline:input2.refreshBaseline,release,rootDirectory:input2.rootDirectory,runtime});return ensureTools({baseline,capabilities:scaffoldCapabilities,rootDirectory:input2.rootDirectory,stdio:input2.stdio})}).pipe(mapError3((cause)=>new ToolEnsureOperationFailure({cause,message:failureMessage(cause),operation:"ensure-tools"})))}}));var featureApplicationOperationsLayer=mergeAll2(operatorSkillOperationsLayer,reportSubmissionOperationsLayer,repositoryCheckOperationsLayer,repositoryScaffoldingOperationsLayer,scaffoldUpdateOperationsLayer,toolEnsureOperationsLayer);var encodeJson5=encodeSync2(fromJsonString2(Unknown2));var encodePrettyJson4=(value5)=>JSON.stringify(JSON.parse(encodeJson5(value5)),null,2);var yesValues=new Set(["","y","yes"]);var writeLines=(prompt,lines2)=>forEach2(lines2,prompt.writeLine,{discard:true});var renderToolBootstrap=(event)=>{const failureDetails=formatToolBootstrapFailureDetails(event.statuses);return[renderCommandSection(event.phase==="base"?"Base tool check":"Tool bootstrap",event.statuses.map((entry)=>`• ${entry.toolId}: ${formatToolBootstrapStatus(entry)}`).join(`
|
|
1541
|
+
`)));if(emitOutput&&emitJson){yield*interaction.emit({_tag:"Json",result:result4})}else if(emitOutput){yield*interaction.emit({_tag:"Complete",applyRequested,changedFiles:allChanges.length,hasManagedUpdates,manifestPaths:manifestPaths(detection),staleFiles:staleFiles.length})}if(result4.applied){yield*submitCliEventEffect("cli.scaffold.update.applied",{baseline:{version:baseline.summary.version},configuration,cwd:rootDirectory})}return result4})};return yield*finalizeUpdateResult()}).pipe(ensuring2(sync2(()=>{if(updateStagingDirectory!==null){rmSync6(updateStagingDirectory,{force:true,recursive:true})}if(wikiStagingDirectory!==null){rmSync6(wikiStagingDirectory,{force:true,recursive:true})}})))};var runUpdate=(options4)=>runScaffoldOperation({...options4,operation:"update"});var failureMessage=(cause)=>cause instanceof Error?cause.message:String(cause);var silentUpdateInteraction={confirmApply:()=>succeed6(false),emit:()=>void_3};var nonBlankEnvironmentValue=(value5)=>value5!==undefined&&value5.trim().length>0?value5:undefined;var operatorSkillOperationsLayer=effect(OperatorSkillOperations,gen2(function*makeOperatorSkillOperations(){const runtime=yield*CliRuntimeConfig;const skillsCli=yield*SkillsCli;return{run:(action2,selectAgent)=>gen2(function*runOperatorSkillOperation(){const cwd=process.cwd();const detectedAgent=resolveActiveOperatorAgent(runtime.commandEnvironment);let selectedAgent;if(detectedAgent===undefined){if(selectAgent===undefined){return yield*new InvalidOperatorContext({message:"Cannot determine the active agent. Set HI_OPERATOR_AGENT to the Skills CLI agent name."})}selectedAgent=yield*selectAgent}const activeAgent=resolveActiveOperatorAgent(runtime.commandEnvironment,selectedAgent);if(activeAgent===undefined){return yield*new InvalidOperatorContext({message:"Cannot determine the active agent. Set HI_OPERATOR_AGENT to the Skills CLI agent name."})}const migrationRetryToken=nonBlankEnvironmentValue(runtime.commandEnvironment.HI_OPERATOR_MIGRATION_RETRY);const mutationRetryToken=nonBlankEnvironmentValue(runtime.commandEnvironment.HI_OPERATOR_MUTATION_RETRY);return yield*executeOperatorAction({action:action2,input:{activeAgent,activeCliVersion:version2,cwd,projectRoot:findOperatorProjectRoot(cwd)},...migrationRetryToken===undefined?{}:{migrationRetryToken},...mutationRetryToken===undefined?{}:{mutationRetryToken}})}).pipe(provideService2(SkillsCli,skillsCli))}}));var resolveFeatureBaseline=({baseline,refreshBaseline,rootDirectory,controlPlane,release,runtime,httpClient})=>resolveBaseline(baselineResolveOptions(fromNullishOr(baseline),refreshBaseline,rootDirectory,{controlPlane,release,runtime})).pipe(provideService2(HttpClient,httpClient));var reportSubmissionOperationsLayer=effect(ReportSubmissionOperations,gen2(function*makeReportSubmissionOperations(){const controlPlane=yield*CliControlPlaneConfig;const httpClient=yield*HttpClient;return{cliVersion:version2,observeRepository:observedRepository,recordSubmitted:(rootDirectory)=>submitCliEventEffect("cli.harness.report.submitted",{configuration:controlPlane,cwd:rootDirectory}).pipe(provideService2(HttpClient,httpClient),mapError3((cause)=>new ReportSubmissionOperationFailure({cause,message:failureMessage(cause),operation:"record-submitted"}))),resolveControlPlaneUrl:()=>succeed6(resolveControlPlaneUrl(undefined,controlPlane)),submit:(baseUrl2,report)=>submitHarnessReport({baseUrl:baseUrl2,report}).pipe(provideService2(HttpClient,httpClient),mapError3((cause)=>new ReportSubmissionOperationFailure({cause,message:failureMessage(cause),operation:"submit-report"})))}}));var repositoryCheckOperationsLayer=effect(RepositoryCheckOperations,gen2(function*makeRepositoryCheckOperations(){const controlPlane=yield*CliControlPlaneConfig;const release=yield*CliReleaseConfig;const runtime=yield*CliRuntimeConfig;const httpClient=yield*HttpClient;const projectSettings=yield*ProjectSettings;return{...release.baseline===undefined?{}:{configuredBaseline:release.baseline},checkUpdate:(input2)=>gen2(function*checkUpdate(){const baseline=yield*resolveFeatureBaseline({baseline:input2.baseline,controlPlane,httpClient,refreshBaseline:input2.refreshBaseline,release,rootDirectory:input2.rootDirectory,runtime});const update3=yield*runUpdate({baseline,check:true,configuration:controlPlane,emitJson:false,emitOutput:false,interaction:silentUpdateInteraction,rootDirectory:input2.rootDirectory,scriptEnvironment:runtime.commandEnvironment,scriptRuntimePath:runtime.scriptRuntimePath,write:false,yes:false}).pipe(provideService2(HttpClient,httpClient));const{operation:_operation,reconciliation:_reconciliation,...publicUpdate}=update3;return{baselineVersion:baseline.summary.version,update:publicUpdate}}).pipe(provideService2(ProjectSettings,projectSettings),mapError3((cause)=>new RepositoryCheckOperationFailure({cause,message:failureMessage(cause),operation:"check-repository-update"}))),cliVersion:version2,updateTag:release.updateTag}}));var repositoryScaffoldingResult=(result4)=>({machinePayload:{...result4,toolBootstrapStatuses:(result4.toolBootstrapStatuses??[]).map((tool)=>({...tool.status==="failed"?{errorMessage:`Required tool '${tool.toolId}' is unavailable after bootstrap.`}:{},status:tool.status,toolId:tool.toolId}))},outputDirectory:result4.outputDirectory,projectionStatus:result4.projectionStatus,toolBootstrapStatuses:(result4.toolBootstrapStatuses??[]).map((tool)=>({...tool.status==="failed"?{errorMessage:`Required tool '${tool.toolId}' is unavailable after bootstrap.`}:{},status:tool.status,toolId:tool.toolId}))});var repositoryScaffoldingOperationsLayer=effect(RepositoryScaffoldingOperations,gen2(function*makeRepositoryScaffoldingOperations(){const controlPlane=yield*CliControlPlaneConfig;const release=yield*CliReleaseConfig;const runtime=yield*CliRuntimeConfig;const httpClient=yield*HttpClient;const projectSettings=yield*ProjectSettings;const scaffoldCapabilities=yield*ScaffoldCapabilities;return{run:(input2,interaction)=>gen2(function*run6(){const baseline=yield*resolveFeatureBaseline({baseline:input2.baseline,controlPlane,httpClient,refreshBaseline:input2.refreshBaseline,release,rootDirectory:input2.kind==="init"?input2.outputDirectory:input2.scanDirectory,runtime});if(input2.kind==="init"){const result5=yield*runStageScaffold({baseline,commandId:"init",configuration:controlPlane,interaction,outputDirectory:input2.outputDirectory,scriptEnvironment:runtime.commandEnvironment,scriptRuntimePath:runtime.scriptRuntimePath}).pipe(provideService2(HttpClient,httpClient),provideService2(ProjectSettings,projectSettings));return repositoryScaffoldingResult(result5)}const result4=yield*runScaffold({assumeYes:input2.assumeYes,baseline,configuration:controlPlane,emitJson:input2.emitJson,interaction,...input2.outputDirectory===undefined?{}:{outputDirectory:input2.outputDirectory},repoShapeMode:input2.repoShape,scanDirectory:input2.scanDirectory,scriptEnvironment:runtime.commandEnvironment,scriptRuntimePath:runtime.scriptRuntimePath,toolStdio:input2.toolStdio}).pipe(provideService2(HttpClient,httpClient),provideService2(ProjectSettings,projectSettings),provideService2(ScaffoldCapabilities,scaffoldCapabilities));return repositoryScaffoldingResult(result4)}).pipe(mapError3((cause)=>new RepositoryScaffoldingOperationFailure({cause,message:failureMessage(cause),operation:input2.kind==="init"?"initialize-repository":"setup-repository"})))}}));var scaffoldUpdateOperationsLayer=effect(ScaffoldUpdateOperations,gen2(function*makeScaffoldUpdateOperations(){const controlPlane=yield*CliControlPlaneConfig;const release=yield*CliReleaseConfig;const runtime=yield*CliRuntimeConfig;const httpClient=yield*HttpClient;const projectSettings=yield*ProjectSettings;return{run:(input2,interaction)=>gen2(function*run6(){const baseline=yield*resolveFeatureBaseline({baseline:input2.baseline,controlPlane,httpClient,refreshBaseline:input2.refreshBaseline,release,rootDirectory:input2.rootDirectory,runtime});return yield*runUpdate({allowBundledBaselineDriftApply:input2.baseline==="bundled"||release.baseline==="bundled",baseline,check:input2.check,configuration:controlPlane,emitJson:input2.emitJson,emitOutput:false,interaction,rootDirectory:input2.rootDirectory,scriptEnvironment:runtime.commandEnvironment,scriptRuntimePath:runtime.scriptRuntimePath,toolStdio:input2.toolStdio,write:input2.write,yes:input2.yes}).pipe(provideService2(HttpClient,httpClient),provideService2(ProjectSettings,projectSettings))}).pipe(mapError3((cause)=>new ScaffoldUpdateOperationFailure({cause,message:failureMessage(cause),operation:"update-scaffold"})))}}));var toolEnsureOperationsLayer=effect(ToolEnsureOperations,gen2(function*makeToolEnsureOperations(){const controlPlane=yield*CliControlPlaneConfig;const release=yield*CliReleaseConfig;const runtime=yield*CliRuntimeConfig;const httpClient=yield*HttpClient;const scaffoldCapabilities=yield*ScaffoldCapabilities;return{run:(input2)=>gen2(function*run6(){const baseline=yield*resolveFeatureBaseline({baseline:input2.baseline,controlPlane,httpClient,refreshBaseline:input2.refreshBaseline,release,rootDirectory:input2.rootDirectory,runtime});return ensureTools({baseline,capabilities:scaffoldCapabilities,rootDirectory:input2.rootDirectory,stdio:input2.stdio})}).pipe(mapError3((cause)=>new ToolEnsureOperationFailure({cause,message:failureMessage(cause),operation:"ensure-tools"})))}}));var featureApplicationOperationsLayer=mergeAll2(operatorSkillOperationsLayer,reportSubmissionOperationsLayer,repositoryCheckOperationsLayer,repositoryScaffoldingOperationsLayer,scaffoldUpdateOperationsLayer,toolEnsureOperationsLayer);var encodeJson5=encodeSync2(fromJsonString2(Unknown2));var encodePrettyJson4=(value5)=>JSON.stringify(JSON.parse(encodeJson5(value5)),null,2);var yesValues=new Set(["","y","yes"]);var writeLines=(prompt,lines2)=>forEach2(lines2,prompt.writeLine,{discard:true});var renderToolBootstrap=(event)=>{const failureDetails=formatToolBootstrapFailureDetails(event.statuses);return[renderCommandSection(event.phase==="base"?"Base tool check":"Tool bootstrap",event.statuses.map((entry)=>`• ${entry.toolId}: ${formatToolBootstrapStatus(entry)}`).join(`
|
|
1542
1542
|
`)),...failureDetails===null?[]:["",renderCommandSection("Tool Bootstrap Warning",failureDetails)]]};var renderEvent=(event)=>{switch(event._tag){case"SetupStarted":{return[renderScaffoldTitle(),"",renderSetupIntro()]}case"ToolCheck":{return["",renderHint(`${event.phase==="base"?"Checking base scaffold tools":"Ensuring selected-pack tools"}: ${event.toolIds.join(", ")}`)]}case"ToolBootstrap":{return renderToolBootstrap(event)}case"Detection":{return["",renderCommandSection("Detection",formatDetectionSummary(event.detection))]}case"ResolvedPacks":{return["",renderCommandSection("Resolved packs",formatResolvedPackSummary({...event.resolved,baseline:event.baseline}))]}case"SelectionAccepted":{return["",renderHint("Non-interactive mode: accepting prefilled pack selection.")]}case"SelectionPreview":{return["",renderCommandSection("Selection preview",formatSelectionPreview({addedPacks:event.addedPacks,baseline:event.baseline,finalPacks:event.finalPacks,outputDirectory:event.outputDirectory,preselectedPacks:event.preselectedPacks,removedPacks:event.removedPacks}))]}case"SelectionReopened":{return["",renderHint("Reopening pack selection editor.")]}case"SetupComplete":{const{result:result4}=event;return["",renderCommandSection("Scaffold Complete",["Scaffold files were written successfully.",`Output directory: \`${result4.outputDirectory}\``,`Prompt file: \`${result4.agentSystemPromptFile}\``].join(`
|
|
1543
1543
|
`)),"",renderCommandSection("Selection",formatConfirmationSummary(result4,event.baseline)),"",renderNotes([`Output directory: ${result4.outputDirectory}`]),...result4.hiddenOutputDirectories.length>0?[renderNotes([`Hidden output directories: ${result4.hiddenOutputDirectories.join(", ")}`])]:[],"",renderCommandSection("Paste Into Your Next Agent",[event.clipboard.ok?`Agent prompt copied to clipboard via \`${event.clipboard.command}\`.`:"Clipboard copy failed. Open the generated prompt file and paste it manually.",`Prompt file: \`${result4.agentSystemPromptFile}\``,`Agent handoff file: \`${result4.agentHandoffFile}\``,`If you are an agent in this terminal, open \`${result4.agentSystemPromptFile}\` and follow it now.`,"Paste the generated agent prompt into your next agent now."].join(`
|
|
1544
1544
|
`)),...event.emitJson?["",renderDivider(),renderJsonLabel(),encodePrettyJson4(result4)]:[]]}case"InitComplete":{const backlogProviderLabels3={"azure-devops":"Azure DevOps",github:"GitHub Projects and Issues",linear:"Linear",monday:"monday.com"};const wikiFrameworkLabels3={next:"Next.js","tanstack-start":"TanStack Start"};const repositoryManagerLabels={"azure-devops":"Azure DevOps",bitbucket:"Bitbucket",github:"GitHub",gitlab:"GitLab"};return[renderScaffoldTitle(),"",renderStageIntro({body:event.summary,title:"Requirements"}),"",renderCommandSection("Scaffolded skills",event.skillFiles.map((file5)=>`• ${file5}`).join(`
|
|
1545
1545
|
`)),...event.wikiFiles.length>0?["",renderCommandSection("Scaffolded wiki files",event.wikiFiles.map((file5)=>`• ${file5}`).join(`
|
|
1546
1546
|
`))]:[],"","",renderNotes([`Output directory: ${event.outputDirectory}`,`Hidden output directories: ${event.hiddenOutputDirectories.join(", ")}`]),"",renderCommandSection("Backlog provider",`${backlogProviderLabels3[event.settings.backlogProvider]} (${event.settings.backlogProvider})`),"",renderCommandSection("Wiki framework",`${wikiFrameworkLabels3[event.wikiFramework]} (${event.wikiFramework})`),"",renderCommandSection("Repository manager",`selected repository manager: ${repositoryManagerLabels[event.settings.repositoryManager]} (\`${event.settings.repositoryManager}\`)`),"",renderCommandSection("Operator prompt",event.operatorPrompt)]}}};var selectPacks=(prompt,request3)=>{const add4=request3.kind==="add";return writeLines(prompt,["",renderCommandSection(add4?"Add optional packs":"Edit prefilled packs",[add4?"Select any extra packs you want to include beyond the prefilled scaffold set.":"Select any removable packs you want to drop from the prefilled scaffold set.","",`available packs: ${request3.allowed.length}`].join(`
|
|
1547
|
-
`))]).pipe(andThen2(prompt.multiSelect({choices:request3.allowed.map((packId)=>{const description=request3.descriptions?.[packId];return description===undefined?{title:packId,value:packId}:{description,title:packId,value:packId}}),message:add4?"Select optional packs to add. Press enter with no selection to add nothing.":"Select prefilled packs to remove. Press enter with no selection to keep all prefilled packs.",selectAll:add4?"Select all optional packs":"Select all removable packs",selectNone:add4?"Add nothing":"Remove nothing (keep all)"})))};var makeRepositoryScaffoldingInteraction=(prompt)=>({confirmSelection:()=>map7(prompt.readLine(renderQuestion("Apply this scaffold selection? [Y/n]: ")),(answer)=>yesValues.has(answer.trim().toLowerCase())),emit:(event)=>writeLines(prompt,renderEvent(event)),keepPrefilledSelection:()=>map7(prompt.readLine(renderQuestion("Keep the prefilled pack selection as-is? [Y/n]: ")),(answer)=>yesValues.has(answer.trim().toLowerCase())),selectPacks:(request3)=>selectPacks(prompt,request3),selectRepoSettings:()=>selectRepoSettings({prompt,retryCommand:"hi init"}),selectWikiFramework:()=>map7(prompt.singleSelect({choices:[{description:"default",title:"Next.js",value:"next"},{title:"TanStack Start",value:"tanstack-start"}],defaultValue:"next",message:"Select wiki framework"}),(answer)=>answer)});var repositoryScaffoldingInteractionLayer=effect(RepositoryScaffoldingInteraction,map7(CliPrompt,makeRepositoryScaffoldingInteraction));import{execFileSync as execFileSync5}from"node:child_process";import{existsSync as existsSync15,linkSync,mkdirSync as mkdirSync9,mkdtempSync as mkdtempSync4,readFileSync as readFileSync14,renameSync as renameSync3,rmdirSync,unlinkSync,writeFileSync as writeFileSync9}from"node:fs";import path26 from"node:path";var isMissingFile2=(cause)=>typeof cause==="object"&&cause!==null&&("code"in cause)&&cause.code==="ENOENT";var hasErrorCode=(cause,code)=>typeof cause==="object"&&cause!==null&&("code"in cause)&&cause.code===code;var hasExitStatus=(cause,status2)=>typeof cause==="object"&&cause!==null&&("status"in cause)&&cause.status===status2;var hasRepositoryGitDirectory=(rootDirectory)=>{let currentDirectory=path26.resolve(rootDirectory);while(true){const gitMarker=path26.join(currentDirectory,".git");if(existsSync15(gitMarker)){execFileSync5("git",["rev-parse","--resolve-git-dir",gitMarker],{encoding:"utf-8",stdio:["ignore","pipe","pipe"]});return true}const parentDirectory=path26.dirname(currentDirectory);if(parentDirectory===currentDirectory){return false}currentDirectory=parentDirectory}};var cleanupFailure=(filePath,cause,message)=>new ProjectSettingsAccessFailure({cause,message,operation:"write",path:filePath});var repositoryGitConfigFailure=(rootDirectory,cause)=>new ProjectSettingsAccessFailure({cause,message:`Failed to read repository git config for ${rootDirectory}.`,operation:"read",path:rootDirectory});var ProjectSettingsFileSystemLive=succeed5(ProjectSettingsFileSystem,{createTextFile:(filePath,content)=>suspend2(()=>{try{mkdirSync9(path26.dirname(filePath),{recursive:true});writeFileSync9(filePath,content,{flag:"wx"});return succeed6(true)}catch(error2){return hasErrorCode(error2,"EEXIST")?succeed6(false):fail6(new ProjectSettingsAccessFailure({cause:error2,message:`Failed to create ${filePath}.`,operation:"write",path:filePath}))}}),directoryExists:(directoryPath)=>sync2(()=>existsSync15(directoryPath)),joinPath:(...segments)=>path26.join(...segments),readRepositoryGitConfig:(rootDirectory)=>suspend2(()=>{try{if(!hasRepositoryGitDirectory(rootDirectory)){return succeed6(none2())}return succeed6(some2(execFileSync5("git",["-C",rootDirectory,"config","--local","--get-regexp","^remote\\..*\\.url$"],{encoding:"utf-8",stdio:["ignore","pipe","pipe"]})))}catch(error2){return hasExitStatus(error2,1)?succeed6(none2()):fail6(repositoryGitConfigFailure(rootDirectory,error2))}}),readTextFile:(filePath)=>suspend2(()=>{try{return succeed6(some2(readFileSync14(filePath,"utf-8")))}catch(error2){return isMissingFile2(error2)?succeed6(none2()):fail6(new ProjectSettingsAccessFailure({cause:error2,message:`Failed to read ${filePath}.`,operation:"read",path:filePath}))}}),removeEmptyDirectory:(directoryPath)=>suspend2(()=>{try{rmdirSync(directoryPath);return void_3}catch(error2){return hasErrorCode(error2,"ENOENT")||hasErrorCode(error2,"ENOTEMPTY")?void_3:fail6(new ProjectSettingsAccessFailure({cause:error2,message:`Failed to remove empty directory ${directoryPath}.`,operation:"write",path:directoryPath}))}}),removeTextFileIfContent:(filePath,expectedContent)=>suspend2(()=>{let recoveryDirectory;try{recoveryDirectory=mkdtempSync4(path26.join(path26.dirname(filePath),`.${path26.basename(filePath)}.hi-cleanup-`))}catch(error2){return isMissingFile2(error2)?succeed6(false):fail6(cleanupFailure(filePath,error2,`Failed to reserve cleanup recovery for ${filePath}.`))}const recoveryPath=path26.join(recoveryDirectory,"claimed");try{renameSync3(filePath,recoveryPath)}catch(error2){try{rmdirSync(recoveryDirectory)}catch{}return isMissingFile2(error2)?succeed6(false):fail6(cleanupFailure(filePath,error2,`Failed to claim ${filePath} for unchanged-content cleanup.`))}let content;try{content=readFileSync14(recoveryPath,"utf-8")}catch(error2){try{linkSync(recoveryPath,filePath)}catch{}return fail6(cleanupFailure(filePath,error2,`Failed to inspect claimed ${filePath}; claimed bytes remain at ${recoveryPath}.`))}if(content===expectedContent){try{unlinkSync(recoveryPath)}catch(error2){return fail6(cleanupFailure(filePath,error2,`Failed to remove unchanged ${filePath}; claimed bytes remain at ${recoveryPath}.`))}try{rmdirSync(recoveryDirectory);return succeed6(true)}catch(error2){return fail6(cleanupFailure(filePath,error2,`Removed unchanged ${filePath}, but failed to remove empty cleanup directory ${recoveryDirectory}.`))}}try{linkSync(recoveryPath,filePath);return succeed6(false)}catch(error2){return fail6(cleanupFailure(filePath,error2,`Failed to restore changed ${filePath}; claimed bytes remain at ${recoveryPath}.`))}}),writeTextFile:(filePath,content)=>try_3({catch:(cause)=>new ProjectSettingsAccessFailure({cause,message:`Failed to write ${filePath}.`,operation:"write",path:filePath}),try:()=>{mkdirSync9(path26.dirname(filePath),{recursive:true});writeFileSync9(filePath,content)}})});import{spawn as spawn2}from"node:child_process";import{createHash as createHash8}from"node:crypto";import{readFileSync as readFileSync15,realpathSync as realpathSync4}from"node:fs";import{mkdtemp as mkdtemp2,rm as rm2}from"node:fs/promises";import{tmpdir as tmpdir7}from"node:os";import path27 from"node:path";var minimumSkillsCliVersion="1.5.20";var operatorSkillOrigin="https://github.com/wearedevpunks/skills.git";var operatorSkillRelativePath=path27.join("skills","agnostic","cli","hi-cli");var sha256Pattern=/^[0-9a-f]{64}$/u;var terminationGraceMs=250;class SkillsCliProcessTreeCleanupDefectError extends Error{_tag="SkillsCliProcessTreeCleanupDefect";constructor(message){super(message);this.name="SkillsCliProcessTreeCleanupDefectError"}}var defaultProcessTreeOptions={platform:process.platform,taskkillExecutable:"taskkill"};var listedSkillSchema=ArraySchema(Struct({agents:ArraySchema(String5),name:String5,path:String5,scope:Literals(["project","global"])}));var normalizeAgent=(agent)=>agent.trim().toLowerCase().replaceAll(/[_\s]+/gu,"-");var scopeArguments=(scope3)=>scope3==="global"?["--global"]:[];var failureContext=(operation2,request3)=>({agent:request3.agent,operation:operation2,scope:request3.scope});var parseVersion2=(value5)=>{const match8=/^v?(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)$/u.exec(value5.trim());return match8===null?undefined:[Number(match8[1]),Number(match8[2]),Number(match8[3])]};var compareVersions3=(left,right)=>{for(const index2 of[0,1,2]){const difference3=left[index2]-right[index2];if(difference3!==0){return difference3}}return 0};var isContainedPath=(root,candidate)=>{const relative=path27.relative(root,candidate);return relative!==".."&&!relative.startsWith(`..${path27.sep}`)&&!path27.isAbsolute(relative)};var terminateProcessTree=(child,options4,onTerminated)=>{const{pid}=child;if(pid===undefined){child.kill("SIGKILL");onTerminated({_tag:"CleanupFailed",message:"Skills CLI process cleanup could not identify the direct child"});return()=>{}}if(options4.platform==="win32"){let completed2=false;let fallback;let taskkill;const listeners={stopChild:()=>{},stopTaskkill:()=>{}};const cleanup=()=>{listeners.stopChild();listeners.stopTaskkill();if(fallback!==undefined){clearTimeout(fallback)}};const finish2=(termination)=>{if(completed2){return}completed2=true;cleanup();onTerminated(termination)};const onDirectChildClose=()=>{finish2({_tag:"CleanupFailed",message:"Windows process-tree cleanup failed; only the direct child exit was verified"})};const terminateDirectChild=(reason)=>{listeners.stopTaskkill();if(child.exitCode!==null||child.signalCode!==null){finish2({_tag:"CleanupFailed",message:`${reason}; only the direct child exit was verified`});return}child.once("close",onDirectChildClose);listeners.stopChild=()=>{child.removeListener("close",onDirectChildClose)};child.kill("SIGKILL");fallback=setTimeout(()=>{finish2({_tag:"CleanupFailed",message:`${reason}; direct child exit could not be verified`})},terminationGraceMs)};const onTaskkillError=(error2)=>{terminateDirectChild(`Windows process-tree cleanup failed: ${error2.message}`)};const onTaskkillClose=(status2)=>{if(status2===0){finish2({_tag:"TreeTerminated"});return}terminateDirectChild(`Windows process-tree cleanup exited with status ${status2??-1}`)};try{taskkill=spawn2(options4.taskkillExecutable,["/pid",String(pid),"/T","/F"],{shell:false,stdio:"ignore",windowsHide:true});taskkill.once("error",onTaskkillError);taskkill.once("close",onTaskkillClose);listeners.stopTaskkill=()=>{taskkill?.removeListener("error",onTaskkillError);taskkill?.removeListener("close",onTaskkillClose)}}catch(error2){terminateDirectChild(`Windows process-tree cleanup failed: ${error2 instanceof Error?error2.message:String(error2)}`)}return()=>{completed2=true;cleanup()}}let completed=false;let poll;const isRunning=()=>{try{process.kill(-pid,0);return true}catch(error2){return error2.code!=="ESRCH"}};const signal=(value5)=>{try{process.kill(-pid,value5)}catch(error2){if(error2.code!=="ESRCH"){child.kill(value5)}}};signal("SIGTERM");const escalation=setTimeout(()=>{signal("SIGKILL")},terminationGraceMs);const timers={};const finish=(termination)=>{if(completed){return}completed=true;clearTimeout(escalation);if(timers.deadline!==undefined){clearTimeout(timers.deadline)}if(poll!==undefined){clearImmediate(poll)}onTerminated(termination)};const awaitExit=()=>{if(!isRunning()){finish({_tag:"TreeTerminated"});return}poll=setImmediate(awaitExit)};timers.deadline=setTimeout(()=>{signal("SIGKILL");finish(isRunning()?{_tag:"CleanupFailed",message:"POSIX process-group cleanup did not complete before the termination deadline"}:{_tag:"TreeTerminated"})},terminationGraceMs*2);awaitExit();return()=>{completed=true;clearTimeout(escalation);if(timers.deadline!==undefined){clearTimeout(timers.deadline)}if(poll!==undefined){clearImmediate(poll)}}};var terminateChild=(child,processTree)=>callback2((resume)=>{const cancel=terminateProcessTree(child,processTree,(termination)=>{resume(succeed6(termination))});return sync2(cancel)}).pipe(flatMap4((termination)=>termination._tag==="CleanupFailed"?failCause3(combine2(interrupt2(),die2(new SkillsCliProcessTreeCleanupDefectError(termination.message)))):void_3));var makeSkillsCliLive=(options4)=>{const executable=options4.executable??"skills";const gitExecutable=options4.gitExecutable??"git";const timeoutEnabled=options4.timeoutMs!==false;const timeoutMs=typeof options4.timeoutMs==="number"?options4.timeoutMs:30000;const{environment}=options4;const processTree=options4.processTree??defaultProcessTreeOptions;const removeTemporaryDirectory=options4.removeTemporaryDirectory??((directory3)=>rm2(directory3,{force:true,recursive:true}));const temporaryDirectoryRoot=options4.temporaryDirectoryRoot??tmpdir7();const runCommand=fn2("SkillsCli.runCommand")(function*runCommand(operation2,request3,command,args2,cwd,commandLabel){const result4=yield*callback2((resume)=>{let child;try{child=spawn2(command,args2,{cwd,detached:true,env:environment,shell:false,stdio:["ignore","pipe","pipe"],windowsHide:true})}catch(error2){resume(succeed6({error:error2,status:null,stderr:"",stdout:""}));return}let completed=false;let timedOut=false;let stderr="";let stdout="";let cancelTermination;const finish=(processResult)=>{if(completed){return}completed=true;cancelTermination?.();resume(succeed6(processResult))};const timeout3=timeoutEnabled?setTimeout(()=>{timedOut=true;cancelTermination=terminateProcessTree(child,processTree,(termination)=>{const cleanupFailed=termination._tag==="CleanupFailed";finish({error:Object.assign(new Error(cleanupFailed?termination.message:`${commandLabel} ${operation2} timed out`),{code:cleanupFailed?"EPROCESSTREE":"ETIMEDOUT"}),status:null,stderr,stdout})})},timeoutMs):undefined;child.stdout?.setEncoding("utf-8");child.stderr?.setEncoding("utf-8");child.stdout?.on("data",(chunk)=>{stdout+=chunk});child.stderr?.on("data",(chunk)=>{stderr+=chunk});child.once("error",(error2)=>{if(timeout3!==undefined){clearTimeout(timeout3)}finish({error:error2,status:null,stderr,stdout})});child.once("close",(status2)=>{if(!timedOut){if(timeout3!==undefined){clearTimeout(timeout3)}finish({status:status2,stderr,stdout})}});return sync2(()=>{if(timeout3!==undefined){clearTimeout(timeout3)}}).pipe(andThen2(terminateChild(child,processTree)))});const context4=failureContext(operation2,request3);const code=result4.error?.code;if(code==="ENOENT"){return yield*new SkillsCliUnavailable({...context4,executable:command,message:`${commandLabel} executable is unavailable: ${command}`})}if(code==="ETIMEDOUT"){return yield*new SkillsCliTimeout({...context4,message:`${commandLabel} ${operation2} timed out after ${timeoutMs}ms`,timeoutMs})}if(code==="EPROCESSTREE"){return yield*new SkillsCliExit({...context4,exitCode:-1,message:`${commandLabel} ${operation2} process cleanup failed`,stderr:result4.error?.message??""})}if(result4.error!==undefined||result4.status!==0){return yield*new SkillsCliExit({...context4,exitCode:result4.status??-1,message:`${commandLabel} ${operation2} exited unsuccessfully`,stderr:result4.stderr||result4.error?.message||""})}return result4.stdout});const run6=(operation2,request3,args2)=>runCommand(operation2,request3,executable,args2,request3.cwd,"Skills CLI");const runGit=(request3,args2,cwd)=>runCommand("install",request3,gitExecutable,args2,cwd,"Git");const temporaryDirectoryFailure=(request3,message,cause)=>new SkillsCliExit({...failureContext("install",request3),exitCode:-1,message,stderr:cause instanceof Error?cause.message:String(cause)});const withMaterializedTarget=(request3,use)=>acquireUseRelease2(tryPromise2({catch:(cause)=>temporaryDirectoryFailure(request3,"Cannot create a temporary operator-skill checkout",cause),try:()=>mkdtemp2(path27.join(temporaryDirectoryRoot,"hi-operator-skill-"))}),(temporaryRoot)=>gen2(function*materializeTarget(){const checkoutRoot=path27.join(temporaryRoot,"source");yield*runGit(request3,["init",checkoutRoot],request3.cwd);yield*runGit(request3,["remote","add","origin",operatorSkillOrigin],checkoutRoot);yield*runGit(request3,["fetch","--depth=1","origin",request3.target.revision],checkoutRoot);const fetchedRevision=(yield*runGit(request3,["rev-parse","FETCH_HEAD^{commit}"],checkoutRoot)).trim();if(fetchedRevision!==request3.target.revision){return yield*new SkillsCliMalformedOutput({...failureContext("install",request3),message:"Git fetched an unexpected operator-skill revision",stdout:fetchedRevision})}yield*runGit(request3,["checkout","--detach","FETCH_HEAD"],checkoutRoot);const canonicalCheckout=yield*try_3({catch:(cause)=>temporaryDirectoryFailure(request3,"Cannot resolve the temporary operator-skill checkout",cause),try:()=>realpathSync4(checkoutRoot)});const localSource=yield*try_3({catch:(cause)=>temporaryDirectoryFailure(request3,"Cannot resolve the materialized operator-skill source",cause),try:()=>realpathSync4(path27.join(canonicalCheckout,operatorSkillRelativePath))});if(!isContainedPath(canonicalCheckout,localSource)){return yield*new SkillsCliMalformedOutput({...failureContext("install",request3),message:"Materialized operator-skill source escapes the checkout",stdout:localSource})}return yield*use(localSource)}),(temporaryRoot)=>tryPromise2({catch:(cause)=>temporaryDirectoryFailure(request3,"Cannot clean up the temporary operator-skill checkout",cause),try:()=>removeTemporaryDirectory(temporaryRoot)}));const ensureSupportedVersion=fn2("SkillsCli.ensureSupportedVersion")(function*ensureSupportedVersion(operation2,request3){const stdout=yield*run6(operation2,request3,["--version"]);const version3=parseVersion2(stdout);if(version3===undefined){return yield*new SkillsCliMalformedOutput({...failureContext(operation2,request3),message:"Skills CLI returned a malformed version",stdout})}const minimumVersion=parseVersion2(minimumSkillsCliVersion);if(compareVersions3(version3,minimumVersion)<0){return yield*new SkillsCliUnsupportedVersion({...failureContext(operation2,request3),message:`Skills CLI ${minimumSkillsCliVersion} or newer is required`,minimumVersion:minimumSkillsCliVersion,version:stdout.trim()})}});const verifyListedSkill=(request3,skill,verifiedSkills)=>{const fail12=(reason,message)=>new SkillsCliVerificationFailure({...failureContext("list",request3),message,reason,skillName:skill.name,skillPath:skill.path,verifiedSkills});return gen2(function*verifySkillIdentity(){if(!path27.isAbsolute(skill.path)||path27.parse(skill.path).root===path27.normalize(skill.path)){return yield*fail12("unsafe-path",`Skills CLI reported an unsafe path for ${skill.name}`)}if(request3.target.contentManifest.length===0){return yield*fail12("malformed","Operator-skill content manifest is empty")}let canonicalRoot;try{canonicalRoot=realpathSync4(skill.path)}catch(error2){const{code}=error2;return yield*fail12(code==="ENOENT"?"missing":"unreadable",`Cannot resolve the CLI-reported ${skill.name} copy`)}const seenPaths=new Set;for(const entry of request3.target.contentManifest){const normalizedRelativePath=path27.normalize(entry.path);if(entry.path===""||path27.isAbsolute(entry.path)||normalizedRelativePath===".."||normalizedRelativePath.startsWith(`..${path27.sep}`)||!sha256Pattern.test(entry.sha256)||seenPaths.has(normalizedRelativePath)){return yield*fail12("malformed","Operator-skill content manifest is malformed")}seenPaths.add(normalizedRelativePath);const filePath=path27.resolve(skill.path,normalizedRelativePath);if(!isContainedPath(path27.resolve(skill.path),filePath)){return yield*fail12("unsafe-path","Operator-skill manifest escapes the reported path")}let canonicalFilePath;try{canonicalFilePath=realpathSync4(filePath)}catch(error2){const{code}=error2;return yield*fail12(code==="ENOENT"?"missing":"unreadable",`Cannot resolve ${entry.path} from the CLI-reported ${skill.name} copy`)}if(!isContainedPath(canonicalRoot,canonicalFilePath)){return yield*fail12("unsafe-path",`${entry.path} escapes the CLI-reported copy`)}let content;try{content=readFileSync15(canonicalFilePath)}catch(error2){const{code}=error2;return yield*fail12(code==="ENOENT"?"missing":"unreadable",`Cannot read ${entry.path} from the CLI-reported ${skill.name} copy`)}const actualSha256=createHash8("sha256").update(content).digest("hex");if(actualSha256!==entry.sha256){return yield*fail12("identity-mismatch",`CLI-reported ${skill.name} content does not match the immutable target`)}}return{...skill,cliCompatibility:request3.target.cliCompatibility,revision:request3.target.revision,source:request3.target.source,version:request3.target.version}})};const list2=fn2("SkillsCli.list")(function*list(request3){yield*ensureSupportedVersion("list",request3);const stdout=yield*run6("list",request3,["list",...scopeArguments(request3.scope),"--agent",request3.agent,"--json"]);const decoded=yield*try_3({catch:()=>new SkillsCliMalformedOutput({...failureContext("list",request3),message:"Skills CLI list returned malformed JSON",stdout}),try:()=>decodeUnknownSync2(listedSkillSchema)(JSON.parse(stdout))});const normalized=decoded.map((skill)=>({...skill,agents:skill.agents.map(normalizeAgent).toSorted()}));if(normalized.some((skill)=>skill.scope!==request3.scope)){return yield*new SkillsCliMalformedOutput({...failureContext("list",request3),message:`Skills CLI list returned a scope other than ${request3.scope}`,stdout})}const requestedAgent=normalizeAgent(request3.agent);const listed=[];const verified=()=>listed.filter((skill)=>("version"in skill));let unbound;for(const skill of normalized){if(skill.name!=="hi-cli"){listed.push(skill);continue}if(!skill.agents.includes(requestedAgent)){unbound??=skill;continue}listed.push(yield*verifyListedSkill(request3,skill,verified()))}if(unbound!==undefined){return yield*new SkillsCliBindingFailure({...failureContext("list",request3),message:`Skills CLI listed ${unbound.name} without the active agent binding`,reportedAgents:unbound.agents,skillName:unbound.name,verifiedSkills:verified()})}return listed});const install=fn2("SkillsCli.install")(function*install(request3){yield*ensureSupportedVersion("install",request3);yield*withMaterializedTarget(request3,(localSource)=>run6("install",request3,["add",localSource,"--skill","hi-cli",...scopeArguments(request3.scope),"--agent",request3.agent,"--yes","--copy"]))});const remove7=fn2("SkillsCli.remove")(function*remove(request3){yield*ensureSupportedVersion("remove",request3);yield*run6("remove",request3,["remove",request3.name,...scopeArguments(request3.scope),"--agent",request3.agent,"--yes"])});return succeed5(SkillsCli,{install,list:list2,remove:remove7})};var startupCheckWorkerEnv="HI_STARTUP_CHECK_WORKER";var startupCheckCliEnv="HI_STARTUP_CHECK_CLI";var startupCheckSkillEnv="HI_STARTUP_CHECK_SKILL";var processEnvironment=process.env;var processProvider=makeEnvironmentProvider(processEnvironment);var startupCheckCacheFile=path28.join(homedir3(),".cache","hi","startup-check.json");var effectBuiltIns=exports_GlobalFlag.BuiltIns.filter((flag)=>flag!==exports_GlobalFlag.Wizard);var rootCommands=commandRegistry.command.subcommands.flatMap(({commands:commands2})=>commands2);var rootCommandNames=rootCommands.map(({name:commandName})=>commandName);var forceColorEnvironment=(runtime)=>{if(runtime.commandEnvironment.FORCE_COLOR==="0"){return{FORCE_COLOR:"0"}}if(runtime.forceColor){return{FORCE_COLOR:"1"}}return{}};var makeRootRenderEnvironment=(runtime,mode)=>makeHumanRenderEnvironment({columns:process.stdout.columns,environment:{...runtime.colorForegroundBackground===undefined?{}:{COLORFGBG:runtime.colorForegroundBackground},...forceColorEnvironment(runtime),...runtime.noColor?{NO_COLOR:"1"}:{},...runtime.terminalTheme===undefined?{}:{HI_THEME:runtime.terminalTheme}},mode,stdoutIsTTY:process.stdout.isTTY===true});var renderRootCommandGuide=(runtime,mode)=>renderRootScreen(renderCommandGuide(commandRegistry.discovery),makeRootRenderEnvironment(runtime,mode));var makeWizardGlobalFlag=(runtime)=>exports_GlobalFlag.action({flag:exports_Flag.boolean("wizard").pipe(exports_Flag.withDescription("Show the interactive command guide")),run:()=>sync2(()=>{const mode=selectOutputMode({jsonSelected:false,stdinIsTTY:process.stdin.isTTY===true,stdoutIsTTY:process.stdout.isTTY===true});process.stdout.write(renderRootCommandGuide(runtime,mode==="interactive"?mode:"plain"))})});var makeRootCommand=(runtime)=>commandRegistry.command.pipe(exports_Command.withGlobalFlags([makeWizardGlobalFlag(runtime)]));var isRootHelpAction=(nativeAction)=>nativeAction==="--help"||nativeAction==="-h";var isHelpArgument=(argument)=>argument==="--help"||argument.startsWith("--help=")||/^-[^-]*h/u.test(argument)&&argument!=="-";var classifyRootHelp=(commandArguments,nativeAction)=>{if(!isRootHelpAction(nativeAction)){return"none"}if(commandArguments.length===1&&(commandArguments[0]==="--help"||commandArguments[0]==="-h")){return"exact"}const helpIndex=commandArguments.findIndex(isHelpArgument);const rootCommandIndex=commandArguments.findIndex((argument)=>rootCommandNames.includes(argument));return rootCommandIndex!==-1&&rootCommandIndex<helpIndex?"nested":"invalid"};var defaultCliFormatter=exports_CliOutput.defaultFormatter();var cliOutputLayer=exports_CliOutput.layer({...defaultCliFormatter,formatVersion:(_name,currentVersion)=>`${currentVersion}
|
|
1547
|
+
`))]).pipe(andThen2(prompt.multiSelect({choices:request3.allowed.map((packId)=>{const description=request3.descriptions?.[packId];return description===undefined?{title:packId,value:packId}:{description,title:packId,value:packId}}),message:add4?"Select optional packs to add. Press enter with no selection to add nothing.":"Select prefilled packs to remove. Press enter with no selection to keep all prefilled packs.",selectAll:add4?"Select all optional packs":"Select all removable packs",selectNone:add4?"Add nothing":"Remove nothing (keep all)"})))};var makeRepositoryScaffoldingInteraction=(prompt)=>({confirmSelection:()=>map7(prompt.readLine(renderQuestion("Apply this scaffold selection? [Y/n]: ")),(answer)=>yesValues.has(answer.trim().toLowerCase())),emit:(event)=>writeLines(prompt,renderEvent(event)),keepPrefilledSelection:()=>map7(prompt.readLine(renderQuestion("Keep the prefilled pack selection as-is? [Y/n]: ")),(answer)=>yesValues.has(answer.trim().toLowerCase())),selectPacks:(request3)=>selectPacks(prompt,request3),selectRepoSettings:()=>selectRepoSettings({prompt,retryCommand:"hi init"}),selectWikiFramework:()=>map7(prompt.singleSelect({choices:[{description:"default",title:"Next.js",value:"next"},{title:"TanStack Start",value:"tanstack-start"}],defaultValue:"next",message:"Select wiki framework"}),(answer)=>answer)});var repositoryScaffoldingInteractionLayer=effect(RepositoryScaffoldingInteraction,map7(CliPrompt,makeRepositoryScaffoldingInteraction));import{execFileSync as execFileSync5}from"node:child_process";import{existsSync as existsSync15,linkSync,mkdirSync as mkdirSync9,mkdtempSync as mkdtempSync4,readFileSync as readFileSync14,renameSync as renameSync3,rmdirSync,unlinkSync,writeFileSync as writeFileSync9}from"node:fs";import path26 from"node:path";var isMissingFile2=(cause)=>typeof cause==="object"&&cause!==null&&("code"in cause)&&cause.code==="ENOENT";var hasErrorCode=(cause,code)=>typeof cause==="object"&&cause!==null&&("code"in cause)&&cause.code===code;var hasExitStatus=(cause,status2)=>typeof cause==="object"&&cause!==null&&("status"in cause)&&cause.status===status2;var hasRepositoryGitDirectory=(rootDirectory)=>{let currentDirectory=path26.resolve(rootDirectory);while(true){const gitMarker=path26.join(currentDirectory,".git");if(existsSync15(gitMarker)){execFileSync5("git",["rev-parse","--resolve-git-dir",gitMarker],{encoding:"utf-8",stdio:["ignore","pipe","pipe"]});return true}const parentDirectory=path26.dirname(currentDirectory);if(parentDirectory===currentDirectory){return false}currentDirectory=parentDirectory}};var cleanupFailure=(filePath,cause,message)=>new ProjectSettingsAccessFailure({cause,message,operation:"write",path:filePath});var repositoryGitConfigFailure=(rootDirectory,cause)=>new ProjectSettingsAccessFailure({cause,message:`Failed to read repository git config for ${rootDirectory}.`,operation:"read",path:rootDirectory});var ProjectSettingsFileSystemLive=succeed5(ProjectSettingsFileSystem,{createTextFile:(filePath,content)=>suspend2(()=>{try{mkdirSync9(path26.dirname(filePath),{recursive:true});writeFileSync9(filePath,content,{flag:"wx"});return succeed6(true)}catch(error2){return hasErrorCode(error2,"EEXIST")?succeed6(false):fail6(new ProjectSettingsAccessFailure({cause:error2,message:`Failed to create ${filePath}.`,operation:"write",path:filePath}))}}),directoryExists:(directoryPath)=>sync2(()=>existsSync15(directoryPath)),joinPath:(...segments)=>path26.join(...segments),readRepositoryGitConfig:(rootDirectory)=>suspend2(()=>{try{if(!hasRepositoryGitDirectory(rootDirectory)){return succeed6(none2())}return succeed6(some2(execFileSync5("git",["-C",rootDirectory,"config","--local","--get-regexp","^remote\\..*\\.url$"],{encoding:"utf-8",stdio:["ignore","pipe","pipe"]})))}catch(error2){return hasExitStatus(error2,1)?succeed6(none2()):fail6(repositoryGitConfigFailure(rootDirectory,error2))}}),readTextFile:(filePath)=>suspend2(()=>{try{return succeed6(some2(readFileSync14(filePath,"utf-8")))}catch(error2){return isMissingFile2(error2)?succeed6(none2()):fail6(new ProjectSettingsAccessFailure({cause:error2,message:`Failed to read ${filePath}.`,operation:"read",path:filePath}))}}),removeEmptyDirectory:(directoryPath)=>suspend2(()=>{try{rmdirSync(directoryPath);return void_3}catch(error2){return hasErrorCode(error2,"ENOENT")||hasErrorCode(error2,"ENOTEMPTY")?void_3:fail6(new ProjectSettingsAccessFailure({cause:error2,message:`Failed to remove empty directory ${directoryPath}.`,operation:"write",path:directoryPath}))}}),removeTextFileIfContent:(filePath,expectedContent)=>suspend2(()=>{let recoveryDirectory;try{recoveryDirectory=mkdtempSync4(path26.join(path26.dirname(filePath),`.${path26.basename(filePath)}.hi-cleanup-`))}catch(error2){return isMissingFile2(error2)?succeed6(false):fail6(cleanupFailure(filePath,error2,`Failed to reserve cleanup recovery for ${filePath}.`))}const recoveryPath=path26.join(recoveryDirectory,"claimed");try{renameSync3(filePath,recoveryPath)}catch(error2){try{rmdirSync(recoveryDirectory)}catch{}return isMissingFile2(error2)?succeed6(false):fail6(cleanupFailure(filePath,error2,`Failed to claim ${filePath} for unchanged-content cleanup.`))}let content;try{content=readFileSync14(recoveryPath,"utf-8")}catch(error2){try{linkSync(recoveryPath,filePath)}catch{}return fail6(cleanupFailure(filePath,error2,`Failed to inspect claimed ${filePath}; claimed bytes remain at ${recoveryPath}.`))}if(content===expectedContent){try{unlinkSync(recoveryPath)}catch(error2){return fail6(cleanupFailure(filePath,error2,`Failed to remove unchanged ${filePath}; claimed bytes remain at ${recoveryPath}.`))}try{rmdirSync(recoveryDirectory);return succeed6(true)}catch(error2){return fail6(cleanupFailure(filePath,error2,`Removed unchanged ${filePath}, but failed to remove empty cleanup directory ${recoveryDirectory}.`))}}try{linkSync(recoveryPath,filePath);return succeed6(false)}catch(error2){return fail6(cleanupFailure(filePath,error2,`Failed to restore changed ${filePath}; claimed bytes remain at ${recoveryPath}.`))}}),writeTextFile:(filePath,content)=>try_3({catch:(cause)=>new ProjectSettingsAccessFailure({cause,message:`Failed to write ${filePath}.`,operation:"write",path:filePath}),try:()=>{mkdirSync9(path26.dirname(filePath),{recursive:true});writeFileSync9(filePath,content)}})});import{spawn as spawn2}from"node:child_process";import{createHash as createHash8}from"node:crypto";import{readFileSync as readFileSync15,realpathSync as realpathSync4}from"node:fs";import{mkdtemp as mkdtemp2,rm as rm2}from"node:fs/promises";import{tmpdir as tmpdir7}from"node:os";import path27 from"node:path";var minimumSkillsCliVersion="1.5.20";var operatorSkillOrigin="https://github.com/wearedevpunks/skills.git";var operatorSkillRelativePath=path27.join("skills","agnostic","cli","hi-cli");var sha256Pattern=/^[0-9a-f]{64}$/u;var terminationGraceMs=250;class SkillsCliProcessTreeCleanupDefectError extends Error{_tag="SkillsCliProcessTreeCleanupDefect";constructor(message){super(message);this.name="SkillsCliProcessTreeCleanupDefectError"}}var defaultProcessTreeOptions={platform:process.platform,taskkillExecutable:"taskkill"};var listedSkillSchema=ArraySchema(Struct({agents:ArraySchema(String5),name:String5,path:String5,scope:Literals(["project","global"])}));var normalizeAgent=(agent)=>agent.trim().toLowerCase().replaceAll(/[_\s]+/gu,"-");var scopeArguments=(scope3)=>scope3==="global"?["--global"]:[];var failureContext=(operation2,request3)=>({agent:request3.agent,operation:operation2,scope:request3.scope});var parseVersion2=(value5)=>{const match8=/^v?(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)$/u.exec(value5.trim());return match8===null?undefined:[Number(match8[1]),Number(match8[2]),Number(match8[3])]};var compareVersions3=(left,right)=>{for(const index2 of[0,1,2]){const difference3=left[index2]-right[index2];if(difference3!==0){return difference3}}return 0};var isContainedPath=(root,candidate)=>{const relative=path27.relative(root,candidate);return relative!==".."&&!relative.startsWith(`..${path27.sep}`)&&!path27.isAbsolute(relative)};var terminateProcessTree=(child,options4,onTerminated)=>{const{pid}=child;if(pid===undefined){child.kill("SIGKILL");onTerminated({_tag:"CleanupFailed",message:"Skills CLI process cleanup could not identify the direct child"});return()=>{}}if(options4.platform==="win32"){let completed2=false;let fallback;let taskkill;const listeners={stopChild:()=>{},stopTaskkill:()=>{}};const cleanup=()=>{listeners.stopChild();listeners.stopTaskkill();if(fallback!==undefined){clearTimeout(fallback)}};const finish2=(termination)=>{if(completed2){return}completed2=true;cleanup();onTerminated(termination)};const onDirectChildClose=()=>{finish2({_tag:"CleanupFailed",message:"Windows process-tree cleanup failed; only the direct child exit was verified"})};const terminateDirectChild=(reason)=>{listeners.stopTaskkill();if(child.exitCode!==null||child.signalCode!==null){finish2({_tag:"CleanupFailed",message:`${reason}; only the direct child exit was verified`});return}child.once("close",onDirectChildClose);listeners.stopChild=()=>{child.removeListener("close",onDirectChildClose)};child.kill("SIGKILL");fallback=setTimeout(()=>{finish2({_tag:"CleanupFailed",message:`${reason}; direct child exit could not be verified`})},terminationGraceMs)};const onTaskkillError=(error2)=>{terminateDirectChild(`Windows process-tree cleanup failed: ${error2.message}`)};const onTaskkillClose=(status2)=>{if(status2===0){finish2({_tag:"TreeTerminated"});return}terminateDirectChild(`Windows process-tree cleanup exited with status ${status2??-1}`)};try{taskkill=spawn2(options4.taskkillExecutable,["/pid",String(pid),"/T","/F"],{shell:false,stdio:"ignore",windowsHide:true});taskkill.once("error",onTaskkillError);taskkill.once("close",onTaskkillClose);listeners.stopTaskkill=()=>{taskkill?.removeListener("error",onTaskkillError);taskkill?.removeListener("close",onTaskkillClose)}}catch(error2){terminateDirectChild(`Windows process-tree cleanup failed: ${error2 instanceof Error?error2.message:String(error2)}`)}return()=>{completed2=true;cleanup()}}let completed=false;let poll;const isRunning=()=>{try{process.kill(-pid,0);return true}catch(error2){return error2.code!=="ESRCH"}};const signal=(value5)=>{try{process.kill(-pid,value5)}catch(error2){if(error2.code!=="ESRCH"){child.kill(value5)}}};signal("SIGTERM");const escalation=setTimeout(()=>{signal("SIGKILL")},terminationGraceMs);const timers={};const finish=(termination)=>{if(completed){return}completed=true;clearTimeout(escalation);if(timers.deadline!==undefined){clearTimeout(timers.deadline)}if(poll!==undefined){clearImmediate(poll)}onTerminated(termination)};const awaitExit=()=>{if(!isRunning()){finish({_tag:"TreeTerminated"});return}poll=setImmediate(awaitExit)};timers.deadline=setTimeout(()=>{signal("SIGKILL");finish(isRunning()?{_tag:"CleanupFailed",message:"POSIX process-group cleanup did not complete before the termination deadline"}:{_tag:"TreeTerminated"})},terminationGraceMs*2);awaitExit();return()=>{completed=true;clearTimeout(escalation);if(timers.deadline!==undefined){clearTimeout(timers.deadline)}if(poll!==undefined){clearImmediate(poll)}}};var terminateChild=(child,processTree)=>callback2((resume)=>{const cancel=terminateProcessTree(child,processTree,(termination)=>{resume(succeed6(termination))});return sync2(cancel)}).pipe(flatMap4((termination)=>termination._tag==="CleanupFailed"?failCause3(combine2(interrupt2(),die2(new SkillsCliProcessTreeCleanupDefectError(termination.message)))):void_3));var makeSkillsCliLive=(options4)=>{const executable=options4.executable??"skills";const gitExecutable=options4.gitExecutable??"git";const timeoutEnabled=options4.timeoutMs!==false;const timeoutMs=typeof options4.timeoutMs==="number"?options4.timeoutMs:30000;const{environment}=options4;const processTree=options4.processTree??defaultProcessTreeOptions;const removeTemporaryDirectory=options4.removeTemporaryDirectory??((directory3)=>rm2(directory3,{force:true,recursive:true}));const temporaryDirectoryRoot=options4.temporaryDirectoryRoot??tmpdir7();const runCommand=fn2("SkillsCli.runCommand")(function*runCommand2(operation2,request3,command,args2,cwd,commandLabel){const result4=yield*callback2((resume)=>{let child;try{child=spawn2(command,args2,{cwd,detached:true,env:environment,shell:false,stdio:["ignore","pipe","pipe"],windowsHide:true})}catch(error2){resume(succeed6({error:error2,status:null,stderr:"",stdout:""}));return}let completed=false;let timedOut=false;let stderr="";let stdout="";let cancelTermination;const finish=(processResult)=>{if(completed){return}completed=true;cancelTermination?.();resume(succeed6(processResult))};const timeout3=timeoutEnabled?setTimeout(()=>{timedOut=true;cancelTermination=terminateProcessTree(child,processTree,(termination)=>{const cleanupFailed=termination._tag==="CleanupFailed";finish({error:Object.assign(new Error(cleanupFailed?termination.message:`${commandLabel} ${operation2} timed out`),{code:cleanupFailed?"EPROCESSTREE":"ETIMEDOUT"}),status:null,stderr,stdout})})},timeoutMs):undefined;child.stdout?.setEncoding("utf-8");child.stderr?.setEncoding("utf-8");child.stdout?.on("data",(chunk)=>{stdout+=chunk});child.stderr?.on("data",(chunk)=>{stderr+=chunk});child.once("error",(error2)=>{if(timeout3!==undefined){clearTimeout(timeout3)}finish({error:error2,status:null,stderr,stdout})});child.once("close",(status2)=>{if(!timedOut){if(timeout3!==undefined){clearTimeout(timeout3)}finish({status:status2,stderr,stdout})}});return sync2(()=>{if(timeout3!==undefined){clearTimeout(timeout3)}}).pipe(andThen2(terminateChild(child,processTree)))});const context4=failureContext(operation2,request3);const code=result4.error?.code;if(code==="ENOENT"){return yield*new SkillsCliUnavailable({...context4,executable:command,message:`${commandLabel} executable is unavailable: ${command}`})}if(code==="ETIMEDOUT"){return yield*new SkillsCliTimeout({...context4,message:`${commandLabel} ${operation2} timed out after ${timeoutMs}ms`,timeoutMs})}if(code==="EPROCESSTREE"){return yield*new SkillsCliExit({...context4,exitCode:-1,message:`${commandLabel} ${operation2} process cleanup failed`,stderr:result4.error?.message??""})}if(result4.error!==undefined||result4.status!==0){return yield*new SkillsCliExit({...context4,exitCode:result4.status??-1,message:`${commandLabel} ${operation2} exited unsuccessfully`,stderr:result4.stderr||result4.error?.message||""})}return result4.stdout});const run6=(operation2,request3,args2)=>runCommand(operation2,request3,executable,args2,request3.cwd,"Skills CLI");const runGit=(request3,args2,cwd)=>runCommand("install",request3,gitExecutable,args2,cwd,"Git");const temporaryDirectoryFailure=(request3,message,cause)=>new SkillsCliExit({...failureContext("install",request3),exitCode:-1,message,stderr:cause instanceof Error?cause.message:String(cause)});const withMaterializedTarget=(request3,use)=>acquireUseRelease2(tryPromise2({catch:(cause)=>temporaryDirectoryFailure(request3,"Cannot create a temporary operator-skill checkout",cause),try:()=>mkdtemp2(path27.join(temporaryDirectoryRoot,"hi-operator-skill-"))}),(temporaryRoot)=>gen2(function*materializeTarget(){const checkoutRoot=path27.join(temporaryRoot,"source");yield*runGit(request3,["init",checkoutRoot],request3.cwd);yield*runGit(request3,["remote","add","origin",operatorSkillOrigin],checkoutRoot);yield*runGit(request3,["fetch","--depth=1","origin",request3.target.revision],checkoutRoot);const fetchedRevision=(yield*runGit(request3,["rev-parse","FETCH_HEAD^{commit}"],checkoutRoot)).trim();if(fetchedRevision!==request3.target.revision){return yield*new SkillsCliMalformedOutput({...failureContext("install",request3),message:"Git fetched an unexpected operator-skill revision",stdout:fetchedRevision})}yield*runGit(request3,["checkout","--detach","FETCH_HEAD"],checkoutRoot);const canonicalCheckout=yield*try_3({catch:(cause)=>temporaryDirectoryFailure(request3,"Cannot resolve the temporary operator-skill checkout",cause),try:()=>realpathSync4(checkoutRoot)});const localSource=yield*try_3({catch:(cause)=>temporaryDirectoryFailure(request3,"Cannot resolve the materialized operator-skill source",cause),try:()=>realpathSync4(path27.join(canonicalCheckout,operatorSkillRelativePath))});if(!isContainedPath(canonicalCheckout,localSource)){return yield*new SkillsCliMalformedOutput({...failureContext("install",request3),message:"Materialized operator-skill source escapes the checkout",stdout:localSource})}return yield*use(localSource)}),(temporaryRoot)=>tryPromise2({catch:(cause)=>temporaryDirectoryFailure(request3,"Cannot clean up the temporary operator-skill checkout",cause),try:()=>removeTemporaryDirectory(temporaryRoot)}));const ensureSupportedVersion=fn2("SkillsCli.ensureSupportedVersion")(function*ensureSupportedVersion2(operation2,request3){const stdout=yield*run6(operation2,request3,["--version"]);const version3=parseVersion2(stdout);if(version3===undefined){return yield*new SkillsCliMalformedOutput({...failureContext(operation2,request3),message:"Skills CLI returned a malformed version",stdout})}const minimumVersion=parseVersion2(minimumSkillsCliVersion);if(compareVersions3(version3,minimumVersion)<0){return yield*new SkillsCliUnsupportedVersion({...failureContext(operation2,request3),message:`Skills CLI ${minimumSkillsCliVersion} or newer is required`,minimumVersion:minimumSkillsCliVersion,version:stdout.trim()})}});const verifyListedSkill=(request3,skill,verifiedSkills)=>{const fail12=(reason,message)=>new SkillsCliVerificationFailure({...failureContext("list",request3),message,reason,skillName:skill.name,skillPath:skill.path,verifiedSkills});return gen2(function*verifySkillIdentity(){if(!path27.isAbsolute(skill.path)||path27.parse(skill.path).root===path27.normalize(skill.path)){return yield*fail12("unsafe-path",`Skills CLI reported an unsafe path for ${skill.name}`)}if(request3.target.contentManifest.length===0){return yield*fail12("malformed","Operator-skill content manifest is empty")}let canonicalRoot;try{canonicalRoot=realpathSync4(skill.path)}catch(error2){const{code}=error2;return yield*fail12(code==="ENOENT"?"missing":"unreadable",`Cannot resolve the CLI-reported ${skill.name} copy`)}const seenPaths=new Set;for(const entry of request3.target.contentManifest){const normalizedRelativePath=path27.normalize(entry.path);if(entry.path===""||path27.isAbsolute(entry.path)||normalizedRelativePath===".."||normalizedRelativePath.startsWith(`..${path27.sep}`)||!sha256Pattern.test(entry.sha256)||seenPaths.has(normalizedRelativePath)){return yield*fail12("malformed","Operator-skill content manifest is malformed")}seenPaths.add(normalizedRelativePath);const filePath=path27.resolve(skill.path,normalizedRelativePath);if(!isContainedPath(path27.resolve(skill.path),filePath)){return yield*fail12("unsafe-path","Operator-skill manifest escapes the reported path")}let canonicalFilePath;try{canonicalFilePath=realpathSync4(filePath)}catch(error2){const{code}=error2;return yield*fail12(code==="ENOENT"?"missing":"unreadable",`Cannot resolve ${entry.path} from the CLI-reported ${skill.name} copy`)}if(!isContainedPath(canonicalRoot,canonicalFilePath)){return yield*fail12("unsafe-path",`${entry.path} escapes the CLI-reported copy`)}let content;try{content=readFileSync15(canonicalFilePath)}catch(error2){const{code}=error2;return yield*fail12(code==="ENOENT"?"missing":"unreadable",`Cannot read ${entry.path} from the CLI-reported ${skill.name} copy`)}const actualSha256=createHash8("sha256").update(content).digest("hex");if(actualSha256!==entry.sha256){return yield*fail12("identity-mismatch",`CLI-reported ${skill.name} content does not match the immutable target`)}}return{...skill,cliCompatibility:request3.target.cliCompatibility,revision:request3.target.revision,source:request3.target.source,version:request3.target.version}})};const list2=fn2("SkillsCli.list")(function*list3(request3){yield*ensureSupportedVersion("list",request3);const stdout=yield*run6("list",request3,["list",...scopeArguments(request3.scope),"--agent",request3.agent,"--json"]);const decoded=yield*try_3({catch:()=>new SkillsCliMalformedOutput({...failureContext("list",request3),message:"Skills CLI list returned malformed JSON",stdout}),try:()=>decodeUnknownSync2(listedSkillSchema)(JSON.parse(stdout))});const normalized=decoded.map((skill)=>({...skill,agents:skill.agents.map(normalizeAgent).toSorted()}));if(normalized.some((skill)=>skill.scope!==request3.scope)){return yield*new SkillsCliMalformedOutput({...failureContext("list",request3),message:`Skills CLI list returned a scope other than ${request3.scope}`,stdout})}const requestedAgent=normalizeAgent(request3.agent);const listed=[];const verified=()=>listed.filter((skill)=>("version"in skill));let unbound;for(const skill of normalized){if(skill.name!=="hi-cli"){listed.push(skill);continue}if(!skill.agents.includes(requestedAgent)){unbound??=skill;continue}listed.push(yield*verifyListedSkill(request3,skill,verified()))}if(unbound!==undefined){return yield*new SkillsCliBindingFailure({...failureContext("list",request3),message:`Skills CLI listed ${unbound.name} without the active agent binding`,reportedAgents:unbound.agents,skillName:unbound.name,verifiedSkills:verified()})}return listed});const install=fn2("SkillsCli.install")(function*install2(request3){yield*ensureSupportedVersion("install",request3);yield*withMaterializedTarget(request3,(localSource)=>run6("install",request3,["add",localSource,"--skill","hi-cli",...scopeArguments(request3.scope),"--agent",request3.agent,"--yes","--copy"]))});const remove7=fn2("SkillsCli.remove")(function*remove8(request3){yield*ensureSupportedVersion("remove",request3);yield*run6("remove",request3,["remove",request3.name,...scopeArguments(request3.scope),"--agent",request3.agent,"--yes"])});return succeed5(SkillsCli,{install,list:list2,remove:remove7})};var startupCheckWorkerEnv="HI_STARTUP_CHECK_WORKER";var startupCheckCliEnv="HI_STARTUP_CHECK_CLI";var startupCheckSkillEnv="HI_STARTUP_CHECK_SKILL";var processEnvironment=process.env;var processProvider=makeEnvironmentProvider(processEnvironment);var startupCheckCacheFile=path28.join(homedir3(),".cache","hi","startup-check.json");var effectBuiltIns=exports_GlobalFlag.BuiltIns.filter((flag)=>flag!==exports_GlobalFlag.Wizard);var rootCommands=commandRegistry.command.subcommands.flatMap(({commands:commands2})=>commands2);var rootCommandNames=rootCommands.map(({name:commandName})=>commandName);var forceColorEnvironment=(runtime)=>{if(runtime.commandEnvironment.FORCE_COLOR==="0"){return{FORCE_COLOR:"0"}}if(runtime.forceColor){return{FORCE_COLOR:"1"}}return{}};var makeRootRenderEnvironment=(runtime,mode)=>makeHumanRenderEnvironment({columns:process.stdout.columns,environment:{...runtime.colorForegroundBackground===undefined?{}:{COLORFGBG:runtime.colorForegroundBackground},...forceColorEnvironment(runtime),...runtime.noColor?{NO_COLOR:"1"}:{},...runtime.terminalTheme===undefined?{}:{HI_THEME:runtime.terminalTheme}},mode,stdoutIsTTY:process.stdout.isTTY===true});var renderRootCommandGuide=(runtime,mode)=>renderRootScreen(renderCommandGuide(commandRegistry.discovery),makeRootRenderEnvironment(runtime,mode));var makeWizardGlobalFlag=(runtime)=>exports_GlobalFlag.action({flag:exports_Flag.boolean("wizard").pipe(exports_Flag.withDescription("Show the interactive command guide")),run:()=>sync2(()=>{const mode=selectOutputMode({jsonSelected:false,stdinIsTTY:process.stdin.isTTY===true,stdoutIsTTY:process.stdout.isTTY===true});process.stdout.write(renderRootCommandGuide(runtime,mode==="interactive"?mode:"plain"))})});var makeRootCommand=(runtime)=>commandRegistry.command.pipe(exports_Command.withGlobalFlags([makeWizardGlobalFlag(runtime)]));var isRootHelpAction=(nativeAction)=>nativeAction==="--help"||nativeAction==="-h";var isHelpArgument=(argument)=>argument==="--help"||argument.startsWith("--help=")||/^-[^-]*h/u.test(argument)&&argument!=="-";var classifyRootHelp=(commandArguments,nativeAction)=>{if(!isRootHelpAction(nativeAction)){return"none"}if(commandArguments.length===1&&(commandArguments[0]==="--help"||commandArguments[0]==="-h")){return"exact"}const helpIndex=commandArguments.findIndex(isHelpArgument);const rootCommandIndex=commandArguments.findIndex((argument)=>rootCommandNames.includes(argument));return rootCommandIndex!==-1&&rootCommandIndex<helpIndex?"nested":"invalid"};var defaultCliFormatter=exports_CliOutput.defaultFormatter();var cliOutputLayer=exports_CliOutput.layer({...defaultCliFormatter,formatVersion:(_name,currentVersion)=>`${currentVersion}
|
|
1548
1548
|
`});var jsonCliFormatter={...defaultCliFormatter,formatCliError:()=>"",formatError:()=>"",formatErrors:()=>"",formatHelpDoc:()=>""};var jsonCliConsole=Object.assign(Object.create(globalThis.console),{error:(...args2)=>{if(args2.length!==1||args2[0]!==""){globalThis.console.error(...args2)}},log:(...args2)=>{if(args2.length!==1||args2[0]!==""){globalThis.console.log(...args2)}}});var cliArgv=process.argv.length===3&&process.argv[2]==="-v"?[...process.argv.slice(0,2),"--version"]:process.argv;var flattenCommandRegistrations=(registrations)=>registrations.flatMap((registration2)=>[registration2,...flattenCommandRegistrations(registration2.children)]);var commandOptionDescriptors=new Map(flattenCommandRegistrations(commandRegistry.registrations).map(({command,metadata})=>{const help=command.buildHelpDoc(metadata.path);return[metadata.path.join(" "),new Map(help.flags.flatMap(({aliases,name:optionName2,type:type2})=>{const canonicalOption=`--${optionName2}`;const descriptor={canonicalOption,takesValue:type2!=="boolean"};return[[canonicalOption,descriptor],...aliases.map((alias)=>[alias,descriptor])]}))]}));var rootOptionDescriptors=(rootCommand2)=>{const declaredFlags=rootCommand2.globalFlags;const globalFlags=[...new Set([...effectBuiltIns,...declaredFlags])];return new Map(globalFlags.flatMap((globalFlag)=>{const help=exports_Command.make("global-option-metadata",{value:globalFlag.flag}).buildHelpDoc([]);return help.flags.flatMap(({aliases,name:optionName2,type:type2})=>{const canonicalOption=`--${optionName2}`;const descriptor={canonicalOption,...globalFlag._tag==="Action"?{nativeAction:true}:{},takesValue:type2!=="boolean"};return[[canonicalOption,descriptor],...aliases.map((alias)=>[alias,descriptor])]})}))};var commandOptionsForArguments=(arguments_)=>{const[command]=commandRegistry.reference.filter(({path:registeredPath})=>registeredPath.every((segment,index2)=>arguments_[index2]===segment)).toSorted((left,right)=>right.path.length-left.path.length);return command===undefined?new Map:commandOptionDescriptors.get(command.path.join(" "))??new Map};var commandHelpForArguments=(arguments_)=>{const[commandPath]=commandRegistry.reference.map(({path:registeredPath})=>registeredPath).filter((registeredPath)=>registeredPath.every((segment,index2)=>arguments_[index2]===segment)).toSorted((left,right)=>right.length-left.length);return`${commandPath===undefined?"hi":commandPath.join(" ")} --help`};var shouldCheckSelfUpdate=(runtime)=>runtime.updateChecksEnabled&&process.argv.includes("--help")===false&&process.argv.includes("-h")===false&&process.argv.includes("--version")===false&&process.argv.includes("-v")===false;var shouldCheckHiCliSkillUpdate=(runtime)=>runtime.skillUpdateChecksEnabled&&process.argv.includes("--help")===false&&process.argv.includes("-h")===false&&process.argv.includes("--version")===false&&process.argv.includes("-v")===false;var shouldAskForSelfUpdate=(runtime,outputMode)=>shouldCheckSelfUpdate(runtime)&&process.argv.slice(2).includes("upgrade")===false&&outputMode!=="json"&&process.stdin.isTTY===true&&process.stdout.isTTY===true;var formatCommand=({command,environment})=>{const envPrefix=environment===undefined?[]:Object.entries(environment).map(([key,value5])=>`${key}=${value5}`);return[...envPrefix,...command].join(" ")};var askYesNo=async(question)=>{const readline2=createInterface3({input:process.stdin,output:process.stdout});try{const response=await readline2.question(renderQuestion(`${question} [y/N]: `));const answer=response.trim();return answer.toLowerCase()==="y"||answer.toLowerCase()==="yes"}finally{readline2.close()}};var isPromptAbort=(error2)=>error2 instanceof Error&&error2.name==="AbortError";var runInteractiveCliUpdate=async(runtime,outputMode)=>{if(!shouldAskForSelfUpdate(runtime,outputMode)){return false}const result4=await autoUpdateCliIfStale({currentVersion:version2,packageName:name,runtime:{commandEnvironment:runtime.commandEnvironment,npmRegistry:runtime.npmRegistry,...runtime.npmUserAgent===undefined?{}:{npmUserAgent:runtime.npmUserAgent}},tag:runtime.updateTag,timeoutMs:5000});if(result4.status==="current"||result4.status==="unavailable"){return false}if(result4.check===null){return false}if(result4.status!=="available"){const command="command"in result4?result4.command:null;console.error(renderSelfUpdateNotice({command,currentVersion:result4.check.currentVersion,latestVersion:result4.check.latestVersion,packageName:result4.check.packageName}));return false}console.error(renderSelfUpdateNotice({command:result4.command,currentVersion:result4.check.currentVersion,latestVersion:result4.check.latestVersion,packageName:result4.check.packageName}));if(!await askYesNo("Update CLI before running this command?")){return false}if(runCliInstallCommand({baseEnvironment:runtime.commandEnvironment,command:result4.command,environment:result4.environment})){console.log(renderCommandSection("CLI upgraded",[`${result4.check.packageName} ${result4.check.currentVersion} -> ${result4.check.latestVersion}`,`Installer: ${result4.packageManager}`,`Command: ${formatCommand(result4)}`,"Re-run your command to use the upgraded CLI."].join(`
|
|
1549
1549
|
`)));return true}console.error(renderCommandSection("CLI upgrade failed",`Command failed: ${formatCommand({command:result4.command})}`));process.exitCode=1;return true};var runCliUpdateCheck=async(runtime)=>{const result4=await autoUpdateCliIfStale({currentVersion:version2,packageName:name,runtime:{commandEnvironment:runtime.commandEnvironment,npmRegistry:runtime.npmRegistry,...runtime.npmUserAgent===undefined?{}:{npmUserAgent:runtime.npmUserAgent}},tag:runtime.updateTag});if(result4.status==="available"||result4.status==="manager-not-detected"||result4.status==="failed"){console.error(renderSelfUpdateNotice({command:result4.command,currentVersion:result4.check.currentVersion,latestVersion:result4.check.latestVersion,packageName:result4.check.packageName}))}};var runHiCliSkillCheck=runOperatorSkillApplication("status").pipe(tap2((result4)=>sync2(()=>{if(result4.lifecycle._tag==="Inspected"&&result4.lifecycle.installed._tag==="Absent"){console.error("hi startup checks: `hi-cli` skill not found. Run `hi operator install`, or `hi operator migrate` when legacy `dp-cli` is present.")}})),matchEffect3({onFailure:()=>void_3,onSuccess:()=>void_3}));var runStartupChecks=({checkCli,checkSkill,runtime})=>gen2(function*executeStartupChecks(){if(checkCli){yield*promise2(()=>runCliUpdateCheck(runtime))}if(checkSkill){yield*runHiCliSkillCheck}});var hasFreshStartupCheck=(runtime)=>{if(!Number.isFinite(runtime.startupCheckIntervalMs)||runtime.startupCheckIntervalMs<=0){return false}try{const parsed=JSON.parse(readFileSync16(startupCheckCacheFile,"utf-8"));return typeof parsed.checkedAt==="number"&&Date.now()-parsed.checkedAt<runtime.startupCheckIntervalMs}catch{return false}};var markStartupCheckStarted=()=>{mkdirSync10(path28.dirname(startupCheckCacheFile),{recursive:true});writeFileSync10(startupCheckCacheFile,JSON.stringify({checkedAt:Date.now()},null,2))};var startBackgroundStartupChecks=(runtime,outputMode)=>{const checkCli=shouldCheckSelfUpdate(runtime)&&!shouldAskForSelfUpdate(runtime,outputMode);const checkSkill=shouldCheckHiCliSkillUpdate(runtime);if(!checkCli&&!checkSkill||hasFreshStartupCheck(runtime)){return}const[,entrypoint]=process.argv;if(entrypoint===undefined||!existsSync16(entrypoint)){return}try{markStartupCheckStarted();const worker=spawn3(process.execPath,[entrypoint],{cwd:process.cwd(),detached:true,env:{...runtime.commandEnvironment,[startupCheckWorkerEnv]:"1",[startupCheckCliEnv]:checkCli?"1":"0",[startupCheckSkillEnv]:checkSkill?"1":"0"},stdio:["ignore","ignore","inherit"]});worker.once("error",()=>{});worker.unref()}catch{}};var main=gen2(function*main2(){const runtime=yield*CliRuntimeConfig;configureBrand({...runtime.colorForegroundBackground===undefined?{}:{colorForegroundBackground:runtime.colorForegroundBackground},forceColor:runtime.forceColor,forceColorDisabled:runtime.commandEnvironment.FORCE_COLOR==="0",noColor:runtime.noColor,...runtime.terminalTheme===undefined?{}:{terminalTheme:runtime.terminalTheme}});const rootCommand2=makeRootCommand(runtime);const cli=exports_Command.runWith(rootCommand2,{version:version2});const commandArguments=cliArgv.slice(2);const argumentScan=analyzeCliArguments({args:commandArguments,commandOptionsForArguments,rootOptions:rootOptionDescriptors(rootCommand2),stdinIsTTY:process.stdin.isTTY===true,stdoutIsTTY:process.stdout.isTTY===true});const outputMode=argumentScan.mode;const parsedArguments=argumentScan.arguments;if(runtime.startupWorker){yield*runStartupChecks({checkCli:runtime.startupCheckCli,checkSkill:runtime.startupCheckSkill,runtime});return}const stopBeforeCommand=yield*tryPromise2({catch:(cause)=>cause,try:()=>runInteractiveCliUpdate(runtime,outputMode)}).pipe(matchEffect3({onFailure:(error2)=>sync2(()=>{if(isPromptAbort(error2)){process.exitCode=130;return true}return false}),onSuccess:succeed6}));if(stopBeforeCommand){return}if(outputMode!=="json"){startBackgroundStartupChecks(runtime,outputMode)}const{nativeAction}=argumentScan;if(outputMode==="json"&&nativeAction!==undefined){process.exitCode=present({humanEnvironment:makeRootRenderEnvironment(runtime,"plain"),mode:outputMode,outcome:{failure:{code:"json-native-action",detail:`CLI-native action \`${nativeAction}\` does not support JSON output. Remove \`--json\` and retry.`,recoverable:true,subject:nativeAction},kind:"expected-failure"}});return}const{missingOption}=argumentScan;if(missingOption!==undefined){const normalizedOption=missingOption.replace(/^-+/u,"");process.exitCode=present({humanEnvironment:makeRootRenderEnvironment(runtime,"plain"),mode:outputMode,outcome:{failure:{code:"missing-command-input",detail:`Missing value for \`${missingOption}\`.`,recoverable:true,recoveryCommand:commandHelpForArguments(argumentScan.commandArguments),subject:normalizedOption},kind:"expected-failure"}});return}const rootHelpDisposition=classifyRootHelp(commandArguments,nativeAction);if(rootHelpDisposition==="exact"){process.stdout.write(renderRootCommandGuide(runtime,outputMode==="interactive"?outputMode:"plain"));return}if(rootHelpDisposition==="invalid"){process.exitCode=present({humanEnvironment:makeRootRenderEnvironment(runtime,"plain"),mode:outputMode,outcome:{failure:{code:"invalid-root-help-invocation",detail:"Root help accepts only `hi --help` or `hi -h`.",recoverable:true,recoveryCommand:"hi --help",subject:nativeAction??"--help"},kind:"expected-failure"}});return}if(parsedArguments.length===0){if(outputMode==="json"){process.exitCode=present({humanEnvironment:makeRootRenderEnvironment(runtime,"plain"),mode:outputMode,outcome:{failure:{code:"missing-command",detail:"Choose a Harness command.",recoverable:true,recoveryCommand:"hi --help",subject:"command"},kind:"expected-failure"}});return}process.stdout.write(renderRootCommandGuide(runtime,outputMode==="interactive"?outputMode:"plain"));return}let capturedOutcome;const commandEffect=outputMode==="json"?cli(parsedArguments).pipe(provideService2(exports_CliOutput.Formatter,jsonCliFormatter),provideService2(Console,jsonCliConsole)):cli(parsedArguments);const outcome=yield*commandEffect.pipe(provideService2(SelectedOutputMode,outputMode),provideService2(RootPresentationSink,{publish:(publishedOutcome)=>sync2(()=>{capturedOutcome=publishedOutcome})}),match6({onFailure:presentationOutcome,onSuccess:()=>capturedOutcome}));if(outcome===undefined){return}const humanMode=outputMode==="interactive"?outputMode:"plain";const exitCode=present({humanEnvironment:makeRootRenderEnvironment(runtime,humanMode),mode:outputMode,outcome});if(exitCode!==0){process.exitCode=exitCode}});var cliConfigLayer=makeCliConfigLayer(processProvider,processEnvironment);var ProjectSettingsLive=ProjectSettingsDefault.pipe(provide2(ProjectSettingsFileSystemLive));var scaffoldCapabilitiesLive=scaffoldCapabilitiesLayer.pipe(provide2(cliConfigLayer));var skillsCliLive=makeSkillsCliLive({environment:processEnvironment});var featureApplicationDependencies=mergeAll2(exports_FetchHttpClient.layer,ProjectSettingsLive,cliConfigLayer,scaffoldCapabilitiesLive,skillsCliLive);var featureApplicationOperationsLive=featureApplicationOperationsLayer.pipe(provide2(featureApplicationDependencies));var mainLayer=mergeAll2(layer15,exports_CliConfig.layer({builtIns:effectBuiltIns}),exports_FetchHttpClient.layer,cliOutputLayer,cliPromptLayer,updateInteractionLayer.pipe(provide2(cliPromptLayer)),repositoryScaffoldingInteractionLayer.pipe(provide2(cliPromptLayer)),ProjectSettingsLive,cliConfigLayer,scaffoldCapabilitiesLive,repositoryCheckCapabilitiesLayer.pipe(provide2(merge2(cliConfigLayer,ProjectSettingsLive))),featureApplicationOperationsLive);if(__require.main==__require.module){main.pipe(provide4(mainLayer),runMain2)}export{rootCommands,rootCommandNames,main};
|