@tessl/cli 0.24.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bundle.mjs CHANGED
@@ -4,7 +4,7 @@ import*as fs$7 from"node:fs";import fs__default,{watch,existsSync,writeFileSync
4
4
  ;import require$$0$b from"diagnostics_channel";import require$$1$9 from"module";import require$$0$a from"tty";import require$$3$1 from"worker_threads";import require$$1$b,{AggregationTemporality,InstrumentType,AggregationType}from"@opentelemetry/sdk-metrics";import require$$1$a from"async_hooks";import require$$0$c,{EventEmitter as EventEmitter$1}from"events";import*as process$4 from"process";import process__default from"process";import*as http$2 from"http";import http__default from"http";import*as require$$1$6 from"https";import require$$1__default$1 from"https";import{ATTR_K8S_POD_UID,ATTR_K8S_NAMESPACE_NAME,ATTR_K8S_POD_NAME,ATTR_VCS_REF_BASE_NAME,ATTR_VCS_CHANGE_ID,ATTR_USER_ID,ATTR_USER_EMAIL}from"@opentelemetry/semantic-conventions/incubating";import*as require$$0$8 from"child_process";import require$$0__default$1,{execSync}from"child_process";import readline$4,{createInterface}from"readline"
5
5
  ;import fsp,{realpath,readlink,readdir,lstat,access,readFile as readFile$1,mkdir,writeFile,chmod}from"node:fs/promises";import{dirname as dirname$2}from"path/posix";import{fileURLToPath as fileURLToPath$1,URL as URL$1}from"node:url";import require$$0$i,{EventEmitter,once as once$1,addAbortListener,on,setMaxListeners}from"node:events";import require$$0$d,{PassThrough,Stream as Stream$2,Readable as Readable$1,Transform as Transform$2,getDefaultHighWaterMark,Duplex,Writable}from"node:stream";import{StringDecoder}from"node:string_decoder";import process$5,{env as env$2,cwd,platform as platform$2,hrtime,execPath,execArgv}from"node:process";import tty$2 from"node:tty";import require$$5$5,{performance as performance$2}from"node:perf_hooks";import require$$0$f from"assert";import require$$0$n,{Buffer as Buffer$1}from"node:buffer";import{pipeline,finished}from"node:stream/promises";import require$$0$o,{createGunzip,createGzip}from"node:zlib";import require$$0$g from"buffer"
6
6
  ;import{createHash as createHash$1,randomUUID as randomUUID$1}from"node:crypto";import require$$2$7,{setTimeout as setTimeout$1}from"node:timers";import cp,{execFile,ChildProcess,spawnSync,spawn}from"node:child_process";import require$$1$c from"string_decoder";import{tsImport}from"tsx/esm/api";import{mkdir as mkdir$1,rm,rename,unlink,readFile as readFile$2}from"fs/promises";import{pipeline as pipeline$1}from"stream/promises";import open from"open";import*as readline$3 from"node:readline";import{createInterface as createInterface$1}from"node:readline";import require$$1$e,{AsyncLocalStorage,AsyncResource}from"node:async_hooks";import require$$0$l,{stripVTControlCharacters,promisify,styleText,debuglog,inspect as inspect$1,callbackify,aborted as aborted$1}from"node:util";import require$$0$h from"net";import{setTimeout as setTimeout$2,scheduler as scheduler$1,setImmediate as setImmediate$1}from"node:timers/promises";import{serialize}from"node:v8";import{createRequire}from"node:module"
7
- ;import{setTimeout as setTimeout$3}from"timers/promises";import require$$0$j from"node:assert";import require$$0$k from"node:net";import require$$2$6 from"node:http";import require$$5$4 from"node:querystring";import require$$0$m from"node:diagnostics_channel";import require$$4$2 from"node:tls";import require$$8$1 from"node:util/types";import require$$1$d from"node:worker_threads";import require$$1$f from"node:console";import require$$1$g from"node:dns";import{pino}from"pino";import"pino-pretty";import require$$4$1 from"tls";var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function getAugmentedNamespace(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var r=function e(){var r=!1;try{
7
+ ;import{setTimeout as setTimeout$3}from"timers/promises";import require$$0$j from"node:assert";import require$$0$k from"node:net";import require$$2$6 from"node:http";import require$$5$4 from"node:querystring";import require$$0$m from"node:diagnostics_channel";import require$$4$2 from"node:tls";import require$$8$1 from"node:util/types";import require$$1$d from"node:worker_threads";import require$$1$f from"node:console";import require$$1$g from"node:dns";import{levels,pino}from"pino";import"pino-pretty";import require$$4$1 from"tls";var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function getAugmentedNamespace(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var r=function e(){var r=!1;try{
8
8
  r=this instanceof e}catch{}return r?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})}),r}var main$2={exports:{}},version$6="17.2.1",require$$4={version:version$6},hasRequiredMain;function requireMain(){if(hasRequiredMain)return main$2.exports;hasRequiredMain=1
9
9
  ;const e=fs$8,t=path__default,r=require$$0__default,n=crypto$3,i=require$$4.version,s=["🔐 encrypt with Dotenvx: https://dotenvx.com","🔐 prevent committing .env to code: https://dotenvx.com/precommit","🔐 prevent building .env in docker: https://dotenvx.com/prebuild","📡 observe env with Radar: https://dotenvx.com/radar","📡 auto-backup env with Radar: https://dotenvx.com/radar","📡 version env with Radar: https://dotenvx.com/radar","🛠️ run anywhere with `dotenvx run -- yourcommand`","⚙️ specify custom .env file path with { path: '/custom/path/.env' }","⚙️ enable debug logging with { debug: true }","⚙️ override existing env vars with { override: true }","⚙️ suppress all logs with { quiet: true }","⚙️ write to custom object with { processEnv: myObject }","⚙️ load multiple .env files with { path: ['.env.local', '.env'] }"];function o(e){return"string"==typeof e?!["false","0","no","off",""].includes(e.toLowerCase()):Boolean(e)}function a(e){
10
10
  return process.stdout.isTTY?`${e}`:e}const c=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function u(e){console.log(`[dotenv@${i}][DEBUG] ${e}`)}function l(e){console.log(`[dotenv@${i}] ${e}`)}function d(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function p(e,t){let r;try{r=new URL(t)}catch(e){if("ERR_INVALID_URL"===e.code){const e=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw e.code="INVALID_DOTENV_KEY",e}throw e}const n=r.password;if(!n){const e=new Error("INVALID_DOTENV_KEY: Missing key part");throw e.code="INVALID_DOTENV_KEY",e}const i=r.searchParams.get("environment");if(!i){const e=new Error("INVALID_DOTENV_KEY: Missing environment part")
@@ -12,14 +12,14 @@ return process.stdout.isTTY?`${e}`:e}const c=/(?:^|^)\s*(?:export\s+)?([
12
12
  ;for(const e of r.path)g.push(A(e))}else g=[A(r.path)];const m={};for(const t of g)try{const n=f.parse(e.readFileSync(t,{encoding:i}));f.populate(m,n,r)}catch(e){d&&u(`Failed to load ${t} ${e.message}`),h=e}const y=f.populate(c,m,r);if(d=o(c.DOTENV_CONFIG_DEBUG||d),p=o(c.DOTENV_CONFIG_QUIET||p),d||!p){const e=Object.keys(y).length,r=[];for(const e of g)try{const n=t.relative(process.cwd(),e);r.push(n)}catch(t){d&&u(`Failed to load ${e} ${t.message}`),h=t}l(`injecting env (${e}) from ${r.join(",")} ${a(`-- tip: ${s[Math.floor(Math.random()*s.length)]}`)}`)}return h?{parsed:m,error:h}:{parsed:m}},_configVault:function(e){const t=o(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),r=o(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);!t&&r||l("Loading env from encrypted .env.vault");const n=f._parseVault(e);let i=process.env;return e&&null!=e.processEnv&&(i=e.processEnv),f.populate(i,n,e),{parsed:n}},_parseVault:function(e){const t=h(e=e||{});e.path=t;const r=f.configDotenv(e);if(!r.parsed){
13
13
  const e=new Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code="MISSING_DATA",e}const n=d(e).split(","),i=n.length;let s;for(let e=0;e<i;e++)try{const t=p(r,n[e].trim());s=f.decrypt(t.ciphertext,t.key);break}catch(t){if(e+1>=i)throw t}return f.parse(s)},config:function(e){if(0===d(e).length)return f.configDotenv(e);const t=h(e);return t?f._configVault(e):(function(e){console.error(`[dotenv@${i}][WARN] ${e}`)}(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),f.configDotenv(e))},decrypt:function(e,t){const r=Buffer.from(t.slice(-64),"hex");let i=Buffer.from(e,"base64");const s=i.subarray(0,12),o=i.subarray(-16);i=i.subarray(12,-16);try{const e=n.createDecipheriv("aes-256-gcm",r,s);return e.setAuthTag(o),`${e.update(i)}${e.final()}`}catch(e){const t=e instanceof RangeError,r="Invalid key length"===e.message,n="Unsupported state or unable to authenticate data"===e.message;if(t||r){
14
14
  const e=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw e.code="INVALID_DOTENV_KEY",e}if(n){const e=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw e.code="DECRYPTION_FAILED",e}throw e}},parse:function(e){const t={};let r,n=e.toString();for(n=n.replace(/\r\n?/gm,"\n");null!=(r=c.exec(n));){const e=r[1];let n=r[2]||"";n=n.trim();const i=n[0];n=n.replace(/^(['"`])([\s\S]*)\1$/gm,"$2"),'"'===i&&(n=n.replace(/\\n/g,"\n"),n=n.replace(/\\r/g,"\r")),t[e]=n}return t},populate:function(e,t,r={}){const n=Boolean(r&&r.debug),i=Boolean(r&&r.override),s={};if("object"!=typeof t){const e=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw e.code="OBJECT_REQUIRED",e}for(const r of Object.keys(t))Object.prototype.hasOwnProperty.call(e,r)?(!0===i&&(e[r]=t[r],s[r]=t[r]),n&&u(!0===i?`"${r}" is already defined and WAS overwritten`:`"${r}" is already defined and was NOT overwritten`)):(e[r]=t[r],s[r]=t[r])
15
- ;return s}};return main$2.exports.configDotenv=f.configDotenv,main$2.exports._configVault=f._configVault,main$2.exports._parseVault=f._parseVault,main$2.exports.config=f.config,main$2.exports.decrypt=f.decrypt,main$2.exports.parse=f.parse,main$2.exports.populate=f.populate,main$2.exports=f,main$2.exports}var mainExports=requireMain();const getModelPrefix=()=>"",getDefaultModel=()=>`${getModelPrefix()}auto`,getModelAliases=()=>[`${getModelPrefix()}auto`,`${getModelPrefix()}anthropic-reasoning`,`${getModelPrefix()}openai-reasoning`],getClaudeCodeSdkModels=()=>({DEFAULT:`${getModelPrefix()}anthropic/claude-sonnet-4-20250514`,SMALL_FAST:`${getModelPrefix()}anthropic/claude-3-5-haiku-20241022`});function isCliBuild(){return!0}function IsAsyncIterator$3(e){return IsObject$3(e)&&!IsArray$3(e)&&!IsUint8Array$3(e)&&Symbol.asyncIterator in e}function IsArray$3(e){return Array.isArray(e)}function IsBigInt$3(e){return"bigint"==typeof e}function IsBoolean$3(e){return"boolean"==typeof e}
16
- function IsDate$3(e){return e instanceof globalThis.Date}function IsFunction$3(e){return"function"==typeof e}function IsIterator$3(e){return IsObject$3(e)&&!IsArray$3(e)&&!IsUint8Array$3(e)&&Symbol.iterator in e}function IsNull$3(e){return null===e}function IsNumber$3(e){return"number"==typeof e}function IsObject$3(e){return"object"==typeof e&&null!==e}function IsRegExp$2(e){return e instanceof globalThis.RegExp}function IsString$3(e){return"string"==typeof e}function IsSymbol$3(e){return"symbol"==typeof e}function IsUint8Array$3(e){return e instanceof globalThis.Uint8Array}function IsUndefined$3(e){return void 0===e}function ArrayType$1(e){return e.map(e=>Visit$7(e))}function DateType$1(e){return new Date(e.getTime())}function Uint8ArrayType$1(e){return new Uint8Array(e)}function RegExpType(e){return new RegExp(e.source,e.flags)}function ObjectType$1(e){const t={};for(const r of Object.getOwnPropertyNames(e))t[r]=Visit$7(e[r])
17
- ;for(const r of Object.getOwnPropertySymbols(e))t[r]=Visit$7(e[r]);return t}function Visit$7(e){return IsArray$3(e)?ArrayType$1(e):IsDate$3(e)?DateType$1(e):IsUint8Array$3(e)?Uint8ArrayType$1(e):IsRegExp$2(e)?RegExpType(e):IsObject$3(e)?ObjectType$1(e):e}function Clone$1(e){return Visit$7(e)}function CloneType(e,t){return Clone$1(void 0===t?e:{...t,...e})}function IsAsyncIterator$2(e){return IsObject$2(e)&&globalThis.Symbol.asyncIterator in e}function IsIterator$2(e){return IsObject$2(e)&&globalThis.Symbol.iterator in e}function IsPromise$2(e){return e instanceof globalThis.Promise}function IsDate$2(e){return e instanceof Date&&globalThis.Number.isFinite(e.getTime())}function IsMap(e){return e instanceof globalThis.Map}function IsSet(e){return e instanceof globalThis.Set}function IsTypedArray(e){return globalThis.ArrayBuffer.isView(e)}function IsUint8Array$2(e){return e instanceof globalThis.Uint8Array}function HasPropertyKey(e,t){return t in e}function IsObject$2(e){
18
- return null!==e&&"object"==typeof e}function IsArray$2(e){return globalThis.Array.isArray(e)&&!globalThis.ArrayBuffer.isView(e)}function IsUndefined$2(e){return void 0===e}function IsNull$2(e){return null===e}function IsBoolean$2(e){return"boolean"==typeof e}function IsNumber$2(e){return"number"==typeof e}function IsInteger$2(e){return globalThis.Number.isInteger(e)}function IsBigInt$2(e){return"bigint"==typeof e}function IsString$2(e){return"string"==typeof e}function IsFunction$2(e){return"function"==typeof e}function IsSymbol$2(e){return"symbol"==typeof e}function IsValueType(e){return IsBigInt$2(e)||IsBoolean$2(e)||IsNull$2(e)||IsNumber$2(e)||IsString$2(e)||IsSymbol$2(e)||IsUndefined$2(e)}var TypeSystemPolicy;function ImmutableArray(e){return globalThis.Object.freeze(e).map(e=>Immutable(e))}function ImmutableDate(e){return e}function ImmutableUint8Array(e){return e}function ImmutableRegExp(e){return e}function ImmutableObject(e){const t={}
19
- ;for(const r of Object.getOwnPropertyNames(e))t[r]=Immutable(e[r]);for(const r of Object.getOwnPropertySymbols(e))t[r]=Immutable(e[r]);return globalThis.Object.freeze(t)}function Immutable(e){return IsArray$3(e)?ImmutableArray(e):IsDate$3(e)?ImmutableDate(e):IsUint8Array$3(e)?ImmutableUint8Array(e):IsRegExp$2(e)?ImmutableRegExp(e):IsObject$3(e)?ImmutableObject(e):e}function CreateType(e,t){const r=void 0!==t?{...t,...e}:e;switch(TypeSystemPolicy.InstanceMode){case"freeze":return Immutable(r);case"clone":return Clone$1(r);default:return r}}!function(e){function t(t){const r=IsObject$2(t);return e.AllowArrayObject?r:r&&!IsArray$2(t)}e.InstanceMode="default",e.ExactOptionalPropertyTypes=!1,e.AllowArrayObject=!1,e.AllowNaN=!1,e.AllowNullVoid=!1,e.IsExactOptionalProperty=function(t,r){return e.ExactOptionalPropertyTypes?r in t:void 0!==t[r]},e.IsObjectLike=t,e.IsRecordLike=function(e){return t(e)&&!(e instanceof Date)&&!(e instanceof Uint8Array)},e.IsNumberLike=function(t){
20
- return e.AllowNaN?IsNumber$2(t):Number.isFinite(t)},e.IsVoidLike=function(t){const r=IsUndefined$2(t);return e.AllowNullVoid?r||null===t:r}}(TypeSystemPolicy||(TypeSystemPolicy={}));class TypeBoxError extends Error{constructor(e){super(e)}}const TransformKind=Symbol.for("TypeBox.Transform"),ReadonlyKind=Symbol.for("TypeBox.Readonly"),OptionalKind=Symbol.for("TypeBox.Optional"),Hint=Symbol.for("TypeBox.Hint"),Kind=Symbol.for("TypeBox.Kind");function IsReadonly(e){return IsObject$3(e)&&"Readonly"===e[ReadonlyKind]}function IsOptional$1(e){return IsObject$3(e)&&"Optional"===e[OptionalKind]}function IsAny$1(e){return IsKindOf$1(e,"Any")}function IsArgument$1(e){return IsKindOf$1(e,"Argument")}function IsArray$1(e){return IsKindOf$1(e,"Array")}function IsAsyncIterator$1(e){return IsKindOf$1(e,"AsyncIterator")}function IsBigInt$1(e){return IsKindOf$1(e,"BigInt")}function IsBoolean$1(e){return IsKindOf$1(e,"Boolean")}function IsComputed$1(e){return IsKindOf$1(e,"Computed")}
21
- function IsConstructor$1(e){return IsKindOf$1(e,"Constructor")}function IsDate$1(e){return IsKindOf$1(e,"Date")}function IsFunction$1(e){return IsKindOf$1(e,"Function")}function IsInteger$1(e){return IsKindOf$1(e,"Integer")}function IsIntersect$1(e){return IsKindOf$1(e,"Intersect")}function IsIterator$1(e){return IsKindOf$1(e,"Iterator")}function IsKindOf$1(e,t){return IsObject$3(e)&&Kind in e&&e[Kind]===t}function IsLiteralValue$1(e){return IsBoolean$3(e)||IsNumber$3(e)||IsString$3(e)}function IsLiteral$1(e){return IsKindOf$1(e,"Literal")}function IsMappedKey$1(e){return IsKindOf$1(e,"MappedKey")}function IsMappedResult$1(e){return IsKindOf$1(e,"MappedResult")}function IsNever$1(e){return IsKindOf$1(e,"Never")}function IsNot$1(e){return IsKindOf$1(e,"Not")}function IsNull$1(e){return IsKindOf$1(e,"Null")}function IsNumber$1(e){return IsKindOf$1(e,"Number")}function IsObject$1(e){return IsKindOf$1(e,"Object")}function IsPromise$1(e){return IsKindOf$1(e,"Promise")}
22
- function IsRecord$1(e){return IsKindOf$1(e,"Record")}function IsRef$1(e){return IsKindOf$1(e,"Ref")}function IsRegExp$1(e){return IsKindOf$1(e,"RegExp")}function IsString$1(e){return IsKindOf$1(e,"String")}function IsSymbol$1(e){return IsKindOf$1(e,"Symbol")}function IsTemplateLiteral$1(e){return IsKindOf$1(e,"TemplateLiteral")}function IsThis$1(e){return IsKindOf$1(e,"This")}function IsTransform$1(e){return IsObject$3(e)&&TransformKind in e}function IsTuple$1(e){return IsKindOf$1(e,"Tuple")}function IsUndefined$1(e){return IsKindOf$1(e,"Undefined")}function IsUnion$1(e){return IsKindOf$1(e,"Union")}function IsUint8Array$1(e){return IsKindOf$1(e,"Uint8Array")}function IsUnknown$1(e){return IsKindOf$1(e,"Unknown")}function IsUnsafe$1(e){return IsKindOf$1(e,"Unsafe")}function IsVoid$1(e){return IsKindOf$1(e,"Void")}function IsKind$1(e){return IsObject$3(e)&&Kind in e&&IsString$3(e[Kind])}function IsSchema$1(e){
15
+ ;return s}};return main$2.exports.configDotenv=f.configDotenv,main$2.exports._configVault=f._configVault,main$2.exports._parseVault=f._parseVault,main$2.exports.config=f.config,main$2.exports.decrypt=f.decrypt,main$2.exports.parse=f.parse,main$2.exports.populate=f.populate,main$2.exports=f,main$2.exports}var mainExports=requireMain();const getModelPrefix=()=>"",getDefaultModel=()=>`${getModelPrefix()}auto`,getClaudeCodeSdkModels=()=>({DEFAULT:`${getModelPrefix()}anthropic/claude-sonnet-4-20250514`,SMALL_FAST:`${getModelPrefix()}anthropic/claude-3-5-haiku-20241022`});function isCliBuild(){return!0}function IsAsyncIterator$3(e){return IsObject$3(e)&&!IsArray$3(e)&&!IsUint8Array$3(e)&&Symbol.asyncIterator in e}function IsArray$3(e){return Array.isArray(e)}function IsBigInt$3(e){return"bigint"==typeof e}function IsBoolean$3(e){return"boolean"==typeof e}function IsDate$3(e){return e instanceof globalThis.Date}function IsFunction$3(e){return"function"==typeof e}function IsIterator$3(e){
16
+ return IsObject$3(e)&&!IsArray$3(e)&&!IsUint8Array$3(e)&&Symbol.iterator in e}function IsNull$3(e){return null===e}function IsNumber$3(e){return"number"==typeof e}function IsObject$3(e){return"object"==typeof e&&null!==e}function IsRegExp$2(e){return e instanceof globalThis.RegExp}function IsString$3(e){return"string"==typeof e}function IsSymbol$3(e){return"symbol"==typeof e}function IsUint8Array$3(e){return e instanceof globalThis.Uint8Array}function IsUndefined$3(e){return void 0===e}function ArrayType$1(e){return e.map(e=>Visit$7(e))}function DateType$1(e){return new Date(e.getTime())}function Uint8ArrayType$1(e){return new Uint8Array(e)}function RegExpType(e){return new RegExp(e.source,e.flags)}function ObjectType$1(e){const t={};for(const r of Object.getOwnPropertyNames(e))t[r]=Visit$7(e[r]);for(const r of Object.getOwnPropertySymbols(e))t[r]=Visit$7(e[r]);return t}function Visit$7(e){
17
+ return IsArray$3(e)?ArrayType$1(e):IsDate$3(e)?DateType$1(e):IsUint8Array$3(e)?Uint8ArrayType$1(e):IsRegExp$2(e)?RegExpType(e):IsObject$3(e)?ObjectType$1(e):e}function Clone$1(e){return Visit$7(e)}function CloneType(e,t){return Clone$1(void 0===t?e:{...t,...e})}function IsAsyncIterator$2(e){return IsObject$2(e)&&globalThis.Symbol.asyncIterator in e}function IsIterator$2(e){return IsObject$2(e)&&globalThis.Symbol.iterator in e}function IsPromise$2(e){return e instanceof globalThis.Promise}function IsDate$2(e){return e instanceof Date&&globalThis.Number.isFinite(e.getTime())}function IsMap(e){return e instanceof globalThis.Map}function IsSet(e){return e instanceof globalThis.Set}function IsTypedArray(e){return globalThis.ArrayBuffer.isView(e)}function IsUint8Array$2(e){return e instanceof globalThis.Uint8Array}function HasPropertyKey(e,t){return t in e}function IsObject$2(e){return null!==e&&"object"==typeof e}function IsArray$2(e){
18
+ return globalThis.Array.isArray(e)&&!globalThis.ArrayBuffer.isView(e)}function IsUndefined$2(e){return void 0===e}function IsNull$2(e){return null===e}function IsBoolean$2(e){return"boolean"==typeof e}function IsNumber$2(e){return"number"==typeof e}function IsInteger$2(e){return globalThis.Number.isInteger(e)}function IsBigInt$2(e){return"bigint"==typeof e}function IsString$2(e){return"string"==typeof e}function IsFunction$2(e){return"function"==typeof e}function IsSymbol$2(e){return"symbol"==typeof e}function IsValueType(e){return IsBigInt$2(e)||IsBoolean$2(e)||IsNull$2(e)||IsNumber$2(e)||IsString$2(e)||IsSymbol$2(e)||IsUndefined$2(e)}var TypeSystemPolicy;function ImmutableArray(e){return globalThis.Object.freeze(e).map(e=>Immutable(e))}function ImmutableDate(e){return e}function ImmutableUint8Array(e){return e}function ImmutableRegExp(e){return e}function ImmutableObject(e){const t={};for(const r of Object.getOwnPropertyNames(e))t[r]=Immutable(e[r])
19
+ ;for(const r of Object.getOwnPropertySymbols(e))t[r]=Immutable(e[r]);return globalThis.Object.freeze(t)}function Immutable(e){return IsArray$3(e)?ImmutableArray(e):IsDate$3(e)?ImmutableDate(e):IsUint8Array$3(e)?ImmutableUint8Array(e):IsRegExp$2(e)?ImmutableRegExp(e):IsObject$3(e)?ImmutableObject(e):e}function CreateType(e,t){const r=void 0!==t?{...t,...e}:e;switch(TypeSystemPolicy.InstanceMode){case"freeze":return Immutable(r);case"clone":return Clone$1(r);default:return r}}!function(e){function t(t){const r=IsObject$2(t);return e.AllowArrayObject?r:r&&!IsArray$2(t)}e.InstanceMode="default",e.ExactOptionalPropertyTypes=!1,e.AllowArrayObject=!1,e.AllowNaN=!1,e.AllowNullVoid=!1,e.IsExactOptionalProperty=function(t,r){return e.ExactOptionalPropertyTypes?r in t:void 0!==t[r]},e.IsObjectLike=t,e.IsRecordLike=function(e){return t(e)&&!(e instanceof Date)&&!(e instanceof Uint8Array)},e.IsNumberLike=function(t){return e.AllowNaN?IsNumber$2(t):Number.isFinite(t)},e.IsVoidLike=function(t){
20
+ const r=IsUndefined$2(t);return e.AllowNullVoid?r||null===t:r}}(TypeSystemPolicy||(TypeSystemPolicy={}));class TypeBoxError extends Error{constructor(e){super(e)}}const TransformKind=Symbol.for("TypeBox.Transform"),ReadonlyKind=Symbol.for("TypeBox.Readonly"),OptionalKind=Symbol.for("TypeBox.Optional"),Hint=Symbol.for("TypeBox.Hint"),Kind=Symbol.for("TypeBox.Kind");function IsReadonly(e){return IsObject$3(e)&&"Readonly"===e[ReadonlyKind]}function IsOptional$1(e){return IsObject$3(e)&&"Optional"===e[OptionalKind]}function IsAny$1(e){return IsKindOf$1(e,"Any")}function IsArgument$1(e){return IsKindOf$1(e,"Argument")}function IsArray$1(e){return IsKindOf$1(e,"Array")}function IsAsyncIterator$1(e){return IsKindOf$1(e,"AsyncIterator")}function IsBigInt$1(e){return IsKindOf$1(e,"BigInt")}function IsBoolean$1(e){return IsKindOf$1(e,"Boolean")}function IsComputed$1(e){return IsKindOf$1(e,"Computed")}function IsConstructor$1(e){return IsKindOf$1(e,"Constructor")}function IsDate$1(e){
21
+ return IsKindOf$1(e,"Date")}function IsFunction$1(e){return IsKindOf$1(e,"Function")}function IsInteger$1(e){return IsKindOf$1(e,"Integer")}function IsIntersect$1(e){return IsKindOf$1(e,"Intersect")}function IsIterator$1(e){return IsKindOf$1(e,"Iterator")}function IsKindOf$1(e,t){return IsObject$3(e)&&Kind in e&&e[Kind]===t}function IsLiteralValue$1(e){return IsBoolean$3(e)||IsNumber$3(e)||IsString$3(e)}function IsLiteral$1(e){return IsKindOf$1(e,"Literal")}function IsMappedKey$1(e){return IsKindOf$1(e,"MappedKey")}function IsMappedResult$1(e){return IsKindOf$1(e,"MappedResult")}function IsNever$1(e){return IsKindOf$1(e,"Never")}function IsNot$1(e){return IsKindOf$1(e,"Not")}function IsNull$1(e){return IsKindOf$1(e,"Null")}function IsNumber$1(e){return IsKindOf$1(e,"Number")}function IsObject$1(e){return IsKindOf$1(e,"Object")}function IsPromise$1(e){return IsKindOf$1(e,"Promise")}function IsRecord$1(e){return IsKindOf$1(e,"Record")}function IsRef$1(e){return IsKindOf$1(e,"Ref")}
22
+ function IsRegExp$1(e){return IsKindOf$1(e,"RegExp")}function IsString$1(e){return IsKindOf$1(e,"String")}function IsSymbol$1(e){return IsKindOf$1(e,"Symbol")}function IsTemplateLiteral$1(e){return IsKindOf$1(e,"TemplateLiteral")}function IsThis$1(e){return IsKindOf$1(e,"This")}function IsTransform$1(e){return IsObject$3(e)&&TransformKind in e}function IsTuple$1(e){return IsKindOf$1(e,"Tuple")}function IsUndefined$1(e){return IsKindOf$1(e,"Undefined")}function IsUnion$1(e){return IsKindOf$1(e,"Union")}function IsUint8Array$1(e){return IsKindOf$1(e,"Uint8Array")}function IsUnknown$1(e){return IsKindOf$1(e,"Unknown")}function IsUnsafe$1(e){return IsKindOf$1(e,"Unsafe")}function IsVoid$1(e){return IsKindOf$1(e,"Void")}function IsKind$1(e){return IsObject$3(e)&&Kind in e&&IsString$3(e[Kind])}function IsSchema$1(e){
23
23
  return IsAny$1(e)||IsArgument$1(e)||IsArray$1(e)||IsBoolean$1(e)||IsBigInt$1(e)||IsAsyncIterator$1(e)||IsComputed$1(e)||IsConstructor$1(e)||IsDate$1(e)||IsFunction$1(e)||IsInteger$1(e)||IsIntersect$1(e)||IsIterator$1(e)||IsLiteral$1(e)||IsMappedKey$1(e)||IsMappedResult$1(e)||IsNever$1(e)||IsNot$1(e)||IsNull$1(e)||IsNumber$1(e)||IsObject$1(e)||IsPromise$1(e)||IsRecord$1(e)||IsRef$1(e)||IsRegExp$1(e)||IsString$1(e)||IsSymbol$1(e)||IsTemplateLiteral$1(e)||IsThis$1(e)||IsTuple$1(e)||IsUndefined$1(e)||IsUnion$1(e)||IsUint8Array$1(e)||IsUnknown$1(e)||IsUnsafe$1(e)||IsVoid$1(e)||IsKind$1(e)}const KnownTypes=["Argument","Any","Array","AsyncIterator","BigInt","Boolean","Computed","Constructor","Date","Enum","Function","Integer","Intersect","Iterator","Literal","MappedKey","MappedResult","Not","Null","Number","Object","Promise","Record","Ref","RegExp","String","Symbol","TemplateLiteral","This","Tuple","Undefined","Union","Uint8Array","Unknown","Void"];function IsPattern(e){try{
24
24
  return new RegExp(e),!0}catch{return!1}}function IsControlCharacterFree(e){if(!IsString$3(e))return!1;for(let t=0;t<e.length;t++){const r=e.charCodeAt(t);if(r>=7&&r<=13||27===r||127===r)return!1}return!0}function IsAdditionalProperties(e){return IsOptionalBoolean(e)||IsSchema(e)}function IsOptionalBigInt(e){return IsUndefined$3(e)||IsBigInt$3(e)}function IsOptionalNumber(e){return IsUndefined$3(e)||IsNumber$3(e)}function IsOptionalBoolean(e){return IsUndefined$3(e)||IsBoolean$3(e)}function IsOptionalString(e){return IsUndefined$3(e)||IsString$3(e)}function IsOptionalPattern(e){return IsUndefined$3(e)||IsString$3(e)&&IsControlCharacterFree(e)&&IsPattern(e)}function IsOptionalFormat(e){return IsUndefined$3(e)||IsString$3(e)&&IsControlCharacterFree(e)}function IsOptionalSchema(e){return IsUndefined$3(e)||IsSchema(e)}function IsOptional(e){return IsObject$3(e)&&"Optional"===e[OptionalKind]}function IsAny(e){return IsKindOf(e,"Any")&&IsOptionalString(e.$id)}function IsArgument(e){
25
25
  return IsKindOf(e,"Argument")&&IsNumber$3(e.index)}function IsArray(e){return IsKindOf(e,"Array")&&"array"===e.type&&IsOptionalString(e.$id)&&IsSchema(e.items)&&IsOptionalNumber(e.minItems)&&IsOptionalNumber(e.maxItems)&&IsOptionalBoolean(e.uniqueItems)&&IsOptionalSchema(e.contains)&&IsOptionalNumber(e.minContains)&&IsOptionalNumber(e.maxContains)}function IsAsyncIterator(e){return IsKindOf(e,"AsyncIterator")&&"AsyncIterator"===e.type&&IsOptionalString(e.$id)&&IsSchema(e.items)}function IsBigInt(e){return IsKindOf(e,"BigInt")&&"bigint"===e.type&&IsOptionalString(e.$id)&&IsOptionalBigInt(e.exclusiveMaximum)&&IsOptionalBigInt(e.exclusiveMinimum)&&IsOptionalBigInt(e.maximum)&&IsOptionalBigInt(e.minimum)&&IsOptionalBigInt(e.multipleOf)}function IsBoolean(e){return IsKindOf(e,"Boolean")&&"boolean"===e.type&&IsOptionalString(e.$id)}function IsComputed(e){return IsKindOf(e,"Computed")&&IsString$3(e.target)&&IsArray$3(e.parameters)&&e.parameters.every(e=>IsSchema(e))}function IsConstructor(e){
@@ -88,7 +88,7 @@ return globalThis.Object.getOwnPropertyNames(e).reduce((t,r)=>({...t,[r]:Compute
88
88
  function Void(e){return CreateType({[Kind]:"Void",type:"void"},e)}var TypeBuilder=Object.freeze({__proto__:null,Any:Any$1,Argument,Array:Array$1,AsyncIterator,Awaited,BigInt:BigInt$1,Boolean:Boolean$1,Capitalize,Composite,Const,Constructor,ConstructorParameters,Date:Date$1,Enum,Exclude,Extends,Extract,Function:Function$1,Index,InstanceType,Instantiate,Integer,Intersect:Intersect$1,Iterator,KeyOf,Literal,Lowercase,Mapped,Module,Never,Not,Null,Number:Number$1,Object:Object$1,Omit,Optional,Parameters,Partial,Pick,Promise:Promise$1,Readonly,ReadonlyOptional,Record,Recursive,Ref,RegExp:RegExp$1,Required,Rest,ReturnType,String:String$1,Symbol:Symbol$1,TemplateLiteral,Transform:Transform$1,Tuple,Uint8Array:Uint8Array$1,Uncapitalize,Undefined,Union:Union$1,Unknown,Unsafe,Uppercase,Void});const Type=TypeBuilder;function _nullishCoalesce$V(e,t){return null!=e?e:t()}const ProjectConfigSchema=Type.Object({name:Type.Optional(Type.String({description:"Project name"}))
89
89
  }),CONFIG_DIR_NAME=".tessl",AGENTS_MD_FILENAME="AGENTS.md",SYSTEM_PROMPT_FILENAME="tessl-system-prompt.md",TESSL_CONFIG_FILE_NAME="tessl-config.jsonc",TMP_DIR_NAME="tmp",DEFAULT_TESSL_DIRS={customToolDirectory:join(CONFIG_DIR_NAME,"tools"),frameworkDirectory:join(CONFIG_DIR_NAME,"framework"),tmpDirectory:join(CONFIG_DIR_NAME,TMP_DIR_NAME),testRunnerDirectory:join(CONFIG_DIR_NAME,TMP_DIR_NAME,"test-runners"),testResultsDirectory:join(CONFIG_DIR_NAME,TMP_DIR_NAME,"test-results"),sessionDataDirectory:join(CONFIG_DIR_NAME,TMP_DIR_NAME,"session-data"),toolOutputLogsDirectory:join(CONFIG_DIR_NAME,TMP_DIR_NAME,"tool-output-logs")};function getDefaultGlobalConfigDir(e,t){const r=_nullishCoalesce$V(t,()=>os$2.homedir()),n=_nullishCoalesce$V(_nullishCoalesce$V(e,()=>"production"),()=>"development");return path__default.join(r,"production"===n?".tessl":`.tessl_${n}`)}function getProvisionedEnvPath(e,t){return join$1(getDefaultGlobalConfigDir(e,t),"dotenv")}function getLocalCliEnvPath(){
90
90
  const e=fileURLToPath(import.meta.url),t=dirname(e),r=join$1(t,"..","..","..","..");return join$1(r,".cli.env")}function loadEnvAndWatch(){loadEnv(),setupFileWatchers()}function loadEnvFile(e){fs__default.existsSync(e)&&mainExports.config({path:e,override:!0,quiet:!0})}function loadEnv(){loadEnvFile(getProvisionedEnvPath("production")),process.env.TESSL_LLM_API_KEY?process.env.ANTHROPIC_AUTH_TOKEN=process.env.TESSL_LLM_API_KEY:delete process.env.ANTHROPIC_AUTH_TOKEN,process.env.TESSL_LLM_BASE_URL?process.env.ANTHROPIC_BASE_URL=process.env.TESSL_LLM_BASE_URL:delete process.env.ANTHROPIC_BASE_URL;const e=getClaudeCodeSdkModels();process.env.ANTHROPIC_MODEL=e.DEFAULT,process.env.ANTHROPIC_SMALL_FAST_MODEL=e.SMALL_FAST}let localCliWatcher=null,provisionedEnvWatcher=null,cleanupRegistered=!1;function createFileWatcher(e,t){const r=dirname(e),n=basename(e);if(!fs__default.existsSync(r))return null;const i=watch(r,(e,r)=>{r!==n||"change"!==e&&"rename"!==e||t()});return i.on("error",()=>{}),
91
- i.unref(),i}function cleanup(){localCliWatcher&&(localCliWatcher.close(),localCliWatcher=null),provisionedEnvWatcher&&(provisionedEnvWatcher.close(),provisionedEnvWatcher=null)}function setupFileWatchers(){cleanup(),localCliWatcher=createFileWatcher(getLocalCliEnvPath(),loadEnv),provisionedEnvWatcher=createFileWatcher(getProvisionedEnvPath("production"),loadEnv),cleanupRegistered||(process.on("SIGINT",cleanup),process.on("SIGTERM",cleanup),cleanupRegistered=!0)}function getTesslCmdName(){return"tessl"}process.env={...process.env,ROLLUP_BUNDLING_CLI:!0,NODE_ENV:"production",GLOBAL_CONFIG_DIR:".tessl",STAMPED_REVISION:"ad9dbabe5cdba9abbffd5dcdb298eaf58fc1b8f6",STAMPED_RELEASE_DATE:"2025-10-02T13:51:27.075Z",STAMPED_VERSION:"v0.24.0",TESSL_BASE_API_URL:"https://api.tessl.io",WORKOS_CLIENT_ID:"client_01HXSHDD9KV92A4892CWHZZDDR",POSTHOG_API_KEY:"phc_S8tHJaPxa5ORnP0RVyyTaJHeCcft6XMqfjx9ZlJWvkO",POSTHOG_FEEDBACK_SURVEY_ID:"0197d0d3-6704-0000-e36e-569911acb8ee",
91
+ i.unref(),i}function cleanup(){localCliWatcher&&(localCliWatcher.close(),localCliWatcher=null),provisionedEnvWatcher&&(provisionedEnvWatcher.close(),provisionedEnvWatcher=null)}function setupFileWatchers(){cleanup(),localCliWatcher=createFileWatcher(getLocalCliEnvPath(),loadEnv),provisionedEnvWatcher=createFileWatcher(getProvisionedEnvPath("production"),loadEnv),cleanupRegistered||(process.on("SIGINT",cleanup),process.on("SIGTERM",cleanup),cleanupRegistered=!0)}function getTesslCmdName(){return"tessl"}process.env={...process.env,ROLLUP_BUNDLING_CLI:!0,NODE_ENV:"production",GLOBAL_CONFIG_DIR:".tessl",STAMPED_REVISION:"515d0a25e7557543b259c4962f29ebdd5fb410ba",STAMPED_RELEASE_DATE:"2025-10-07T14:52:51.036Z",STAMPED_VERSION:"v0.26.0",TESSL_BASE_API_URL:"https://api.tessl.io",WORKOS_CLIENT_ID:"client_01HXSHDD9KV92A4892CWHZZDDR",POSTHOG_API_KEY:"phc_S8tHJaPxa5ORnP0RVyyTaJHeCcft6XMqfjx9ZlJWvkO",POSTHOG_FEEDBACK_SURVEY_ID:"0197d0d3-6704-0000-e36e-569911acb8ee",
92
92
  POSTHOG_FEEDBACK_SURVEY_QUESTION_ID:"e34e48fc-938a-4af1-b255-3c55d6bdcbc7"},loadEnvAndWatch();var _globalThis$2="object"==typeof globalThis?globalThis:global,VERSION$a="1.9.0",re$2=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function _makeCompatibilityCheck(e){var t=new Set([e]),r=new Set,n=e.match(re$2);if(!n)return function(){return!1};var i=+n[1],s=+n[2],o=+n[3];if(null!=n[4])return function(t){return t===e};function a(e){return r.add(e),!1}function c(e){return t.add(e),!0}return function(e){if(t.has(e))return!0;if(r.has(e))return!1;var n=e.match(re$2);if(!n)return a(e);var u=+n[1],l=+n[2],d=+n[3];return null!=n[4]||i!==u?a(e):0===i?s===l&&o<=d?c(e):a(e):s<=l?c(e):a(e)}}var isCompatible=_makeCompatibilityCheck(VERSION$a),major=VERSION$a.split(".")[0],GLOBAL_OPENTELEMETRY_API_KEY=Symbol.for("opentelemetry.js.api."+major),_global$1=_globalThis$2;function registerGlobal(e,t,r,n){var i;void 0===n&&(n=!1)
93
93
  ;var s=_global$1[GLOBAL_OPENTELEMETRY_API_KEY]=null!==(i=_global$1[GLOBAL_OPENTELEMETRY_API_KEY])&&void 0!==i?i:{version:VERSION$a};if(!n&&s[e]){var o=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return r.error(o.stack||o.message),!1}if(s.version!==VERSION$a){o=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+VERSION$a);return r.error(o.stack||o.message),!1}return s[e]=t,r.debug("@opentelemetry/api: Registered a global for "+e+" v"+VERSION$a+"."),!0}function getGlobal(e){var t,r,n=null===(t=_global$1[GLOBAL_OPENTELEMETRY_API_KEY])||void 0===t?void 0:t.version;if(n&&isCompatible(n))return null===(r=_global$1[GLOBAL_OPENTELEMETRY_API_KEY])||void 0===r?void 0:r[e]}function unregisterGlobal(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+VERSION$a+".");var r=_global$1[GLOBAL_OPENTELEMETRY_API_KEY];r&&delete r[e]}var __read$4=function(e,t){
94
94
  var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,s=r.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(n=s.next()).done;)o.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=s.return)&&r.call(s)}finally{if(i)throw i.error}}return o},__spreadArray$3=function(e,t,r){if(r||2===arguments.length)for(var n,i=0,s=t.length;i<s;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||Array.prototype.slice.call(t))},DiagComponentLogger=function(){function e(e){this._namespace=e.namespace||"DiagComponentLogger"}return e.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return logProxy("debug",this._namespace,e)},e.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return logProxy("error",this._namespace,e)},e.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return logProxy("info",this._namespace,e)},e.prototype.warn=function(){
@@ -184,24 +184,24 @@ var e=Error.prepareStackTrace;Error.prepareStackTrace=function(e,t){return t};va
184
184
  ;var n=/^((\/?)(?:[^\/]*\/)*)((\.{1,2}|[^\/]+?|)(\.[^.\/]*|))[\/]*$/,i={};return i.parse=function(e){if("string"!=typeof e)throw new TypeError("Parameter 'pathString' must be a string, not "+typeof e);var t,r=(t=e,n.exec(t).slice(1));if(!r||5!==r.length)throw new TypeError("Invalid path '"+e+"'");return{root:r[1],dir:r[0].slice(0,-1),base:r[2],ext:r[4],name:r[3]}},pathParse.exports=e?r.parse:i.parse,pathParse.exports.posix=i.parse,pathParse.exports.win32=r.parse,pathParse.exports}function requireNodeModulesPaths(){if(hasRequiredNodeModulesPaths)return nodeModulesPaths;hasRequiredNodeModulesPaths=1;var e=path__default,t=e.parse||requirePathParse(),r=function(r,n){var i="/";/^([A-Za-z]:)/.test(r)?i="":/^\\\\/.test(r)&&(i="\\\\");for(var s=[r],o=t(r);o.dir!==s[s.length-1];)s.push(o.dir),o=t(o.dir);return s.reduce(function(t,r){return t.concat(n.map(function(t){return e.resolve(i,r,t)}))},[])};return nodeModulesPaths=function(e,t,n){
185
185
  var i=t&&t.moduleDirectory?[].concat(t.moduleDirectory):["node_modules"];if(t&&"function"==typeof t.paths)return t.paths(n,e,function(){return r(e,i)},t);var s=r(e,i);return t&&t.paths?s.concat(t.paths):s},nodeModulesPaths}function requireNormalizeOptions(){return hasRequiredNormalizeOptions?normalizeOptions$3:(hasRequiredNormalizeOptions=1,normalizeOptions$3=function(e,t){return t||{}})}function requireImplementation(){if(hasRequiredImplementation)return implementation;hasRequiredImplementation=1;var e=Object.prototype.toString,t=Math.max,r=function(e,t){for(var r=[],n=0;n<e.length;n+=1)r[n]=e[n];for(var i=0;i<t.length;i+=1)r[i+e.length]=t[i];return r};return implementation=function(n){var i=this;if("function"!=typeof i||"[object Function]"!==e.apply(i))throw new TypeError("Function.prototype.bind called on incompatible "+i);for(var s,o=function(e,t){for(var r=[],n=t,i=0;n<e.length;n+=1,i+=1)r[i]=e[n];return r}(arguments,1),a=t(0,i.length-o.length),c=[],u=0;u<a;u++)c[u]="$"+u
186
186
  ;if(s=Function("binder","return function ("+function(e,t){for(var r="",n=0;n<e.length;n+=1)r+=e[n],n+1<e.length&&(r+=t);return r}(c,",")+"){ return binder.apply(this,arguments); }")(function(){if(this instanceof s){var e=i.apply(this,r(o,arguments));return Object(e)===e?e:this}return i.apply(n,r(o,arguments))}),i.prototype){var l=function(){};l.prototype=i.prototype,s.prototype=new l,l.prototype=null}return s},implementation}function requireFunctionBind(){if(hasRequiredFunctionBind)return functionBind;hasRequiredFunctionBind=1;var e=requireImplementation();return functionBind=Function.prototype.bind||e}function requireHasown(){if(hasRequiredHasown)return hasown;hasRequiredHasown=1;var e=Function.prototype.call,t=Object.prototype.hasOwnProperty,r=requireFunctionBind();return hasown=r.call(e,t)}
187
- var assert$5=!0,async_hooks$1=">= 8",buffer_ieee754$1=">= 0.5 && < 0.9.7",buffer$2=!0,child_process$1=!0,cluster$1=">= 0.5",console$2=!0,constants$f=!0,crypto$2=!0,_debug_agent$1=">= 1 && < 8",_debugger$1="< 8",dgram$1=!0,diagnostics_channel$1=[">= 14.17 && < 15",">= 15.1"],dns$2=!0,domain$1=">= 0.7.12",events$2=!0,freelist$1="< 6",fs$6=!0,_http_agent$1=">= 0.11.1",_http_client$1=">= 0.11.1",_http_common$1=">= 0.11.1",_http_incoming$1=">= 0.11.1",_http_outgoing$1=">= 0.11.1",_http_server$1=">= 0.11.1",http$1=!0,http2$1=">= 8.8",https$1=!0,inspector$1=">= 8",_linklist$1="< 8",module$1=!0,net$1=!0,os$1=!0,path$5=!0,perf_hooks$1=">= 8.5",process$3=">= 1",punycode$3=">= 0.5",querystring$1=!0,readline$2=!0,repl$1=!0,smalloc$1=">= 0.11.5 && < 3",_stream_duplex$2=">= 0.9.4",_stream_transform$2=">= 0.9.4",_stream_wrap$1=">= 1.4.1",_stream_passthrough$2=">= 0.9.4",_stream_readable$2=">= 0.9.4",_stream_writable$2=">= 0.9.4",stream$8=!0,string_decoder$2=!0,sys$1=[">= 0.4 && < 0.7",">= 0.8"],timers$2=!0,_tls_common$1=">= 0.11.13",_tls_legacy$1=">= 0.11.3 && < 10",_tls_wrap$1=">= 0.11.3",tls$1=!0,trace_events$1=">= 10",tty$1=!0,url$1=!0,util$d=!0,v8$1=">= 1",vm$1=!0,wasi$1=[">= 13.4 && < 13.5",">= 18.17 && < 19",">= 20"],worker_threads$1=">= 11.7",zlib$1=">= 0.5",require$$1$4={
187
+ var assert$5=!0,async_hooks$1=">= 8",buffer_ieee754$1=">= 0.5 && < 0.9.7",buffer$2=!0,child_process$1=!0,cluster$1=">= 0.5",console$2=!0,constants$f=!0,crypto$2=!0,_debug_agent$1=">= 1 && < 8",_debugger$1="< 8",dgram$1=!0,diagnostics_channel$1=[">= 14.17 && < 15",">= 15.1"],dns$2=!0,domain$1=">= 0.7.12",events$2=!0,freelist$1="< 6",fs$6=!0,_http_agent$1=">= 0.11.1",_http_client$1=">= 0.11.1",_http_common$1=">= 0.11.1",_http_incoming$1=">= 0.11.1",_http_outgoing$1=">= 0.11.1",_http_server$1=">= 0.11.1",http$1=!0,http2$1=">= 8.8",https$1=!0,inspector$1=">= 8",_linklist$1="< 8",module$1=!0,net$1=!0,os$1=!0,path$5=!0,perf_hooks$1=">= 8.5",process$3=">= 1",punycode$3=">= 0.5",querystring$1=!0,readline$2=!0,repl$1=!0,smalloc$1=">= 0.11.5 && < 3",_stream_duplex$2=">= 0.9.4",_stream_transform$2=">= 0.9.4",_stream_wrap$1=">= 1.4.1",_stream_passthrough$2=">= 0.9.4",_stream_readable$2=">= 0.9.4",_stream_writable$2=">= 0.9.4",stream$8=!0,string_decoder$2=!0,sys$1=[">= 0.4 && < 0.7",">= 0.8"],timers$2=!0,_tls_common$1=">= 0.11.13",_tls_legacy$1=">= 0.11.3 && < 10",_tls_wrap$1=">= 0.11.3",tls$1=!0,trace_events$1=">= 10",tty$1=!0,url$1=!0,util$c=!0,v8$1=">= 1",vm$1=!0,wasi$1=[">= 13.4 && < 13.5",">= 18.17 && < 19",">= 20"],worker_threads$1=">= 11.7",zlib$1=">= 0.5",require$$1$4={
188
188
  assert:assert$5,"node:assert":[">= 14.18 && < 15",">= 16"],"assert/strict":">= 15","node:assert/strict":">= 16",async_hooks:async_hooks$1,"node:async_hooks":[">= 14.18 && < 15",">= 16"],buffer_ieee754:buffer_ieee754$1,buffer:buffer$2,"node:buffer":[">= 14.18 && < 15",">= 16"],child_process:child_process$1,"node:child_process":[">= 14.18 && < 15",">= 16"],cluster:cluster$1,"node:cluster":[">= 14.18 && < 15",">= 16"],console:console$2,"node:console":[">= 14.18 && < 15",">= 16"],constants:constants$f,"node:constants":[">= 14.18 && < 15",">= 16"],crypto:crypto$2,"node:crypto":[">= 14.18 && < 15",">= 16"],_debug_agent:_debug_agent$1,_debugger:_debugger$1,dgram:dgram$1,"node:dgram":[">= 14.18 && < 15",">= 16"],diagnostics_channel:diagnostics_channel$1,"node:diagnostics_channel":[">= 14.18 && < 15",">= 16"],dns:dns$2,"node:dns":[">= 14.18 && < 15",">= 16"],"dns/promises":">= 15","node:dns/promises":">= 16",domain:domain$1,"node:domain":[">= 14.18 && < 15",">= 16"],events:events$2,
189
189
  "node:events":[">= 14.18 && < 15",">= 16"],freelist:freelist$1,fs:fs$6,"node:fs":[">= 14.18 && < 15",">= 16"],"fs/promises":[">= 10 && < 10.1",">= 14"],"node:fs/promises":[">= 14.18 && < 15",">= 16"],_http_agent:_http_agent$1,"node:_http_agent":[">= 14.18 && < 15",">= 16"],_http_client:_http_client$1,"node:_http_client":[">= 14.18 && < 15",">= 16"],_http_common:_http_common$1,"node:_http_common":[">= 14.18 && < 15",">= 16"],_http_incoming:_http_incoming$1,"node:_http_incoming":[">= 14.18 && < 15",">= 16"],_http_outgoing:_http_outgoing$1,"node:_http_outgoing":[">= 14.18 && < 15",">= 16"],_http_server:_http_server$1,"node:_http_server":[">= 14.18 && < 15",">= 16"],http:http$1,"node:http":[">= 14.18 && < 15",">= 16"],http2:http2$1,"node:http2":[">= 14.18 && < 15",">= 16"],https:https$1,"node:https":[">= 14.18 && < 15",">= 16"],inspector:inspector$1,"node:inspector":[">= 14.18 && < 15",">= 16"],"inspector/promises":[">= 19"],"node:inspector/promises":[">= 19"],_linklist:_linklist$1,
190
190
  module:module$1,"node:module":[">= 14.18 && < 15",">= 16"],net:net$1,"node:net":[">= 14.18 && < 15",">= 16"],"node-inspect/lib/_inspect":">= 7.6 && < 12","node-inspect/lib/internal/inspect_client":">= 7.6 && < 12","node-inspect/lib/internal/inspect_repl":">= 7.6 && < 12",os:os$1,"node:os":[">= 14.18 && < 15",">= 16"],path:path$5,"node:path":[">= 14.18 && < 15",">= 16"],"path/posix":">= 15.3","node:path/posix":">= 16","path/win32":">= 15.3","node:path/win32":">= 16",perf_hooks:perf_hooks$1,"node:perf_hooks":[">= 14.18 && < 15",">= 16"],process:process$3,"node:process":[">= 14.18 && < 15",">= 16"],punycode:punycode$3,"node:punycode":[">= 14.18 && < 15",">= 16"],querystring:querystring$1,"node:querystring":[">= 14.18 && < 15",">= 16"],readline:readline$2,"node:readline":[">= 14.18 && < 15",">= 16"],"readline/promises":">= 17","node:readline/promises":">= 17",repl:repl$1,"node:repl":[">= 14.18 && < 15",">= 16"],"node:sea":[">= 20.12 && < 21",">= 21.7"],smalloc:smalloc$1,
191
191
  "node:sqlite":[">= 22.13 && < 23",">= 23.4"],_stream_duplex:_stream_duplex$2,"node:_stream_duplex":[">= 14.18 && < 15",">= 16"],_stream_transform:_stream_transform$2,"node:_stream_transform":[">= 14.18 && < 15",">= 16"],_stream_wrap:_stream_wrap$1,"node:_stream_wrap":[">= 14.18 && < 15",">= 16"],_stream_passthrough:_stream_passthrough$2,"node:_stream_passthrough":[">= 14.18 && < 15",">= 16"],_stream_readable:_stream_readable$2,"node:_stream_readable":[">= 14.18 && < 15",">= 16"],_stream_writable:_stream_writable$2,"node:_stream_writable":[">= 14.18 && < 15",">= 16"],stream:stream$8,"node:stream":[">= 14.18 && < 15",">= 16"],"stream/consumers":">= 16.7","node:stream/consumers":">= 16.7","stream/promises":">= 15","node:stream/promises":">= 16","stream/web":">= 16.5","node:stream/web":">= 16.5",string_decoder:string_decoder$2,"node:string_decoder":[">= 14.18 && < 15",">= 16"],sys:sys$1,"node:sys":[">= 14.18 && < 15",">= 16"],"test/reporters":">= 19.9 && < 20.2",
192
- "node:test/reporters":[">= 18.17 && < 19",">= 19.9",">= 20"],"test/mock_loader":">= 22.3 && < 22.7","node:test/mock_loader":">= 22.3 && < 22.7","node:test":[">= 16.17 && < 17",">= 18"],timers:timers$2,"node:timers":[">= 14.18 && < 15",">= 16"],"timers/promises":">= 15","node:timers/promises":">= 16",_tls_common:_tls_common$1,"node:_tls_common":[">= 14.18 && < 15",">= 16"],_tls_legacy:_tls_legacy$1,_tls_wrap:_tls_wrap$1,"node:_tls_wrap":[">= 14.18 && < 15",">= 16"],tls:tls$1,"node:tls":[">= 14.18 && < 15",">= 16"],trace_events:trace_events$1,"node:trace_events":[">= 14.18 && < 15",">= 16"],tty:tty$1,"node:tty":[">= 14.18 && < 15",">= 16"],url:url$1,"node:url":[">= 14.18 && < 15",">= 16"],util:util$d,"node:util":[">= 14.18 && < 15",">= 16"],"util/types":">= 15.3","node:util/types":">= 16","v8/tools/arguments":">= 10 && < 12","v8/tools/codemap":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/consarray":[">= 4.4 && < 5",">= 5.2 && < 12"],
192
+ "node:test/reporters":[">= 18.17 && < 19",">= 19.9",">= 20"],"test/mock_loader":">= 22.3 && < 22.7","node:test/mock_loader":">= 22.3 && < 22.7","node:test":[">= 16.17 && < 17",">= 18"],timers:timers$2,"node:timers":[">= 14.18 && < 15",">= 16"],"timers/promises":">= 15","node:timers/promises":">= 16",_tls_common:_tls_common$1,"node:_tls_common":[">= 14.18 && < 15",">= 16"],_tls_legacy:_tls_legacy$1,_tls_wrap:_tls_wrap$1,"node:_tls_wrap":[">= 14.18 && < 15",">= 16"],tls:tls$1,"node:tls":[">= 14.18 && < 15",">= 16"],trace_events:trace_events$1,"node:trace_events":[">= 14.18 && < 15",">= 16"],tty:tty$1,"node:tty":[">= 14.18 && < 15",">= 16"],url:url$1,"node:url":[">= 14.18 && < 15",">= 16"],util:util$c,"node:util":[">= 14.18 && < 15",">= 16"],"util/types":">= 15.3","node:util/types":">= 16","v8/tools/arguments":">= 10 && < 12","v8/tools/codemap":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/consarray":[">= 4.4 && < 5",">= 5.2 && < 12"],
193
193
  "v8/tools/csvparser":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/logreader":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/profile_view":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/splaytree":[">= 4.4 && < 5",">= 5.2 && < 12"],v8:v8$1,"node:v8":[">= 14.18 && < 15",">= 16"],vm:vm$1,"node:vm":[">= 14.18 && < 15",">= 16"],wasi:wasi$1,"node:wasi":[">= 18.17 && < 19",">= 20"],worker_threads:worker_threads$1,"node:worker_threads":[">= 14.18 && < 15",">= 16"],zlib:zlib$1,"node:zlib":[">= 14.18 && < 15",">= 16"]},isCoreModule,hasRequiredIsCoreModule,async$8,hasRequiredAsync$9;function requireIsCoreModule(){if(hasRequiredIsCoreModule)return isCoreModule;hasRequiredIsCoreModule=1;var e=requireHasown();function t(e,t){for(var r=e.split("."),n=t.split(" "),i=n.length>1?n[0]:"=",s=(n.length>1?n[1]:n[0]).split("."),o=0;o<3;++o){var a=parseInt(r[o]||0,10),c=parseInt(s[o]||0,10);if(a!==c)return"<"===i?a<c:">="===i&&a>=c}return">="===i}function r(e,r){var n=r.split(/ ?&& ?/);if(0===n.length)return!1
194
194
  ;for(var i=0;i<n.length;++i)if(!t(e,n[i]))return!1;return!0}var n=require$$1$4;return isCoreModule=function(t,i){return e(n,t)&&function(e,t){if("boolean"==typeof t)return t;var n=void 0===e?process.versions&&process.versions.node:e;if("string"!=typeof n)throw new TypeError(void 0===e?"Unable to determine current node version":"If provided, a valid node version is required");if(t&&"object"==typeof t){for(var i=0;i<t.length;++i)if(r(n,t[i]))return!0;return!1}return r(n,t)}(i,n[t])},isCoreModule}function requireAsync$9(){if(hasRequiredAsync$9)return async$8;hasRequiredAsync$9=1;var e=fs$8,t=requireHomedir(),r=path__default,n=requireCaller(),i=requireNodeModulesPaths(),s=requireNormalizeOptions(),o=requireIsCoreModule(),a="win32"!==process.platform&&e.realpath&&"function"==typeof e.realpath.native?e.realpath.native:e.realpath,c=t(),u=function(t,r){e.stat(t,function(e,t){return e?"ENOENT"===e.code||"ENOTDIR"===e.code?r(null,!1):r(e):r(null,t.isFile()||t.isFIFO())})},l=function(t,r){
195
195
  e.stat(t,function(e,t){return e?"ENOENT"===e.code||"ENOTDIR"===e.code?r(null,!1):r(e):r(null,t.isDirectory())})},d=function(e,t){a(e,function(r,n){r&&"ENOENT"!==r.code?t(r):t(null,r?e:n)})},p=function(e,t,r,n){r&&!1===r.preserveSymlinks?e(t,n):n(null,t)},h=function(e,t,r){e(t,function(e,t){if(e)r(e);else try{var n=JSON.parse(t);r(null,n)}catch(e){r(null)}})};return async$8=function(t,a,A){var f=A,g=a;if("function"==typeof a&&(f=g,g={}),"string"!=typeof t){var m=new TypeError("Path must be a string.");return process.nextTick(function(){f(m)})}var y=(g=s(t,g)).isFile||u,E=g.isDirectory||l,b=g.readFile||e.readFile,C=g.realpath||d,v=g.readPackage||h;if(g.readFile&&g.readPackage){var I=new TypeError("`readFile` and `readPackage` are mutually exclusive.");return process.nextTick(function(){f(I)})}var _=g.packageIterator,S=g.extensions||[".js"],D=!1!==g.includeCoreModules,w=g.basedir||r.dirname(n()),R=g.filename||w;g.paths=g.paths||[r.join(c,".node_modules"),r.join(c,".node_libraries")]
196
196
  ;var B,T=r.resolve(w);function x(e,r,n){e?f(e):r?f(null,r,n):k(B,function(e,r,n){if(e)f(e);else if(r)p(C,r,g,function(e,t){e?f(e):f(null,t,n)});else{var i=new Error("Cannot find module '"+t+"' from '"+R+"'");i.code="MODULE_NOT_FOUND",f(i)}})}function $(e,t,n){var i=t,s=n;"function"==typeof i&&(s=i,i=void 0),function e(t,n,i){if(0===t.length)return s(null,void 0,i);var o=n+t[0],a=i;a?c(null,a):F(r.dirname(o),c);function c(i,c,l){if(a=c,i)return s(i);if(l&&a&&g.pathFilter){var d=r.relative(l,o),p=d.slice(0,d.length-t[0].length),h=g.pathFilter(a,n,p);if(h)return e([""].concat(S.slice()),r.resolve(l,h),a)}y(o,u)}function u(r,i){return r?s(r):i?s(null,o,a):void e(t.slice(1),n,a)}}([""].concat(S),e,i)}function F(e,t){return""===e||"/"===e||"win32"===process.platform&&/^\w:[/\\]*$/.test(e)||/[/\\]node_modules[/\\]*$/.test(e)?t(null):void p(C,e,g,function(n,i){if(n)return F(r.dirname(e),t);var s=r.join(i,"package.json");y(s,function(n,i){if(!i)return F(r.dirname(e),t);v(b,s,function(r,n){
197
197
  r&&t(r);var i=n;i&&g.packageFilter&&(i=g.packageFilter(i,s)),t(null,i,e)})})})}function k(e,t,n){var i=n,s=t;"function"==typeof s&&(i=s,s=g.package),p(C,e,g,function(t,n){if(t)return i(t);var o=r.join(n,"package.json");y(o,function(t,n){return t?i(t):n?void v(b,o,function(t,n){if(t)return i(t);var s=n;if(s&&g.packageFilter&&(s=g.packageFilter(s,o)),s&&s.main){if("string"!=typeof s.main){var a=new TypeError("package “"+s.name+"” `main` must be a string");return a.code="INVALID_PACKAGE_MAIN",i(a)}return"."!==s.main&&"./"!==s.main||(s.main="index"),void $(r.resolve(e,s.main),s,function(t,n,s){return t?i(t):n?i(null,n,s):s?void k(r.resolve(e,s.main),s,function(t,n,s){return t?i(t):n?i(null,n,s):void $(r.join(e,"index"),s,i)}):$(r.join(e,"index"),s,i)})}$(r.join(e,"/index"),s,i)}):$(r.join(e,"index"),s,i)})})}function Q(e,t){if(0===t.length)return e(null,void 0);var n=t[0];function i(t,r,i){return t?e(t):r?e(null,r,i):void k(n,g.package,s)}function s(r,n,i){
198
198
  return r?e(r):n?e(null,n,i):void Q(e,t.slice(1))}E(r.dirname(n),function(r,s){if(r)return e(r);if(!s)return Q(e,t.slice(1));$(n,g.package,i)})}p(C,T,g,function(e,n){e?f(e):function(e){if(/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/.test(t))B=r.resolve(e,t),"."!==t&&".."!==t&&"/"!==t.slice(-1)||(B+="/"),/\/$/.test(t)&&B===e?k(B,g.package,x):$(B,g.package,x);else{if(D&&o(t))return f(null,t);!function(e,t,n){var s=function(){return function(e,t,n){for(var s=i(t,n,e),o=0;o<s.length;o++)s[o]=r.join(s[o],e);return s}(e,t,g)};Q(n,_?_(e,t,s,g):s())}(t,e,function(e,r,n){if(e)f(e);else{if(r)return p(C,r,g,function(e,t){e?f(e):f(null,t,n)});var i=new Error("Cannot find module '"+t+"' from '"+R+"'");i.code="MODULE_NOT_FOUND",f(i)}})}}(n)})},async$8}
199
- var assert$4=!0,async_hooks=">= 8",buffer_ieee754=">= 0.5 && < 0.9.7",buffer$1=!0,child_process=!0,cluster=">= 0.5",console$1=!0,constants$e=!0,crypto$1=!0,_debug_agent=">= 1 && < 8",_debugger="< 8",dgram=!0,diagnostics_channel=[">= 14.17 && < 15",">= 15.1"],dns$1=!0,domain=">= 0.7.12",events$1=!0,freelist="< 6",fs$5=!0,_http_agent=">= 0.11.1",_http_client=">= 0.11.1",_http_common=">= 0.11.1",_http_incoming=">= 0.11.1",_http_outgoing=">= 0.11.1",_http_server=">= 0.11.1",http=!0,http2=">= 8.8",https=!0,inspector=">= 8",_linklist="< 8",module=!0,net=!0,os=!0,path$4=!0,perf_hooks=">= 8.5",process$2=">= 1",punycode$2=">= 0.5",querystring=!0,readline$1=!0,repl=!0,smalloc=">= 0.11.5 && < 3",_stream_duplex$1=">= 0.9.4",_stream_transform$1=">= 0.9.4",_stream_wrap=">= 1.4.1",_stream_passthrough$1=">= 0.9.4",_stream_readable$1=">= 0.9.4",_stream_writable$1=">= 0.9.4",stream$7=!0,string_decoder$1=!0,sys=[">= 0.4 && < 0.7",">= 0.8"],timers$1=!0,_tls_common=">= 0.11.13",_tls_legacy=">= 0.11.3 && < 10",_tls_wrap=">= 0.11.3",tls=!0,trace_events=">= 10",tty=!0,url=!0,util$c=!0,v8=">= 1",vm=!0,wasi=[">= 13.4 && < 13.5",">= 18.17 && < 19",">= 20"],worker_threads=">= 11.7",zlib=">= 0.5",require$$1$3={
199
+ var assert$4=!0,async_hooks=">= 8",buffer_ieee754=">= 0.5 && < 0.9.7",buffer$1=!0,child_process=!0,cluster=">= 0.5",console$1=!0,constants$e=!0,crypto$1=!0,_debug_agent=">= 1 && < 8",_debugger="< 8",dgram=!0,diagnostics_channel=[">= 14.17 && < 15",">= 15.1"],dns$1=!0,domain=">= 0.7.12",events$1=!0,freelist="< 6",fs$5=!0,_http_agent=">= 0.11.1",_http_client=">= 0.11.1",_http_common=">= 0.11.1",_http_incoming=">= 0.11.1",_http_outgoing=">= 0.11.1",_http_server=">= 0.11.1",http=!0,http2=">= 8.8",https=!0,inspector=">= 8",_linklist="< 8",module=!0,net=!0,os=!0,path$4=!0,perf_hooks=">= 8.5",process$2=">= 1",punycode$2=">= 0.5",querystring=!0,readline$1=!0,repl=!0,smalloc=">= 0.11.5 && < 3",_stream_duplex$1=">= 0.9.4",_stream_transform$1=">= 0.9.4",_stream_wrap=">= 1.4.1",_stream_passthrough$1=">= 0.9.4",_stream_readable$1=">= 0.9.4",_stream_writable$1=">= 0.9.4",stream$7=!0,string_decoder$1=!0,sys=[">= 0.4 && < 0.7",">= 0.8"],timers$1=!0,_tls_common=">= 0.11.13",_tls_legacy=">= 0.11.3 && < 10",_tls_wrap=">= 0.11.3",tls=!0,trace_events=">= 10",tty=!0,url=!0,util$b=!0,v8=">= 1",vm=!0,wasi=[">= 13.4 && < 13.5",">= 18.17 && < 19",">= 20"],worker_threads=">= 11.7",zlib=">= 0.5",require$$1$3={
200
200
  assert:assert$4,"node:assert":[">= 14.18 && < 15",">= 16"],"assert/strict":">= 15","node:assert/strict":">= 16",async_hooks,"node:async_hooks":[">= 14.18 && < 15",">= 16"],buffer_ieee754,buffer:buffer$1,"node:buffer":[">= 14.18 && < 15",">= 16"],child_process,"node:child_process":[">= 14.18 && < 15",">= 16"],cluster,"node:cluster":[">= 14.18 && < 15",">= 16"],console:console$1,"node:console":[">= 14.18 && < 15",">= 16"],constants:constants$e,"node:constants":[">= 14.18 && < 15",">= 16"],crypto:crypto$1,"node:crypto":[">= 14.18 && < 15",">= 16"],_debug_agent,_debugger,dgram,"node:dgram":[">= 14.18 && < 15",">= 16"],diagnostics_channel,"node:diagnostics_channel":[">= 14.18 && < 15",">= 16"],dns:dns$1,"node:dns":[">= 14.18 && < 15",">= 16"],"dns/promises":">= 15","node:dns/promises":">= 16",domain,"node:domain":[">= 14.18 && < 15",">= 16"],events:events$1,"node:events":[">= 14.18 && < 15",">= 16"],freelist,fs:fs$5,"node:fs":[">= 14.18 && < 15",">= 16"],
201
201
  "fs/promises":[">= 10 && < 10.1",">= 14"],"node:fs/promises":[">= 14.18 && < 15",">= 16"],_http_agent,"node:_http_agent":[">= 14.18 && < 15",">= 16"],_http_client,"node:_http_client":[">= 14.18 && < 15",">= 16"],_http_common,"node:_http_common":[">= 14.18 && < 15",">= 16"],_http_incoming,"node:_http_incoming":[">= 14.18 && < 15",">= 16"],_http_outgoing,"node:_http_outgoing":[">= 14.18 && < 15",">= 16"],_http_server,"node:_http_server":[">= 14.18 && < 15",">= 16"],http,"node:http":[">= 14.18 && < 15",">= 16"],http2,"node:http2":[">= 14.18 && < 15",">= 16"],https,"node:https":[">= 14.18 && < 15",">= 16"],inspector,"node:inspector":[">= 14.18 && < 15",">= 16"],"inspector/promises":[">= 19"],"node:inspector/promises":[">= 19"],_linklist,module,"node:module":[">= 14.18 && < 15",">= 16"],net,"node:net":[">= 14.18 && < 15",">= 16"],"node-inspect/lib/_inspect":">= 7.6 && < 12","node-inspect/lib/internal/inspect_client":">= 7.6 && < 12","node-inspect/lib/internal/inspect_repl":">= 7.6 && < 12",
202
202
  os,"node:os":[">= 14.18 && < 15",">= 16"],path:path$4,"node:path":[">= 14.18 && < 15",">= 16"],"path/posix":">= 15.3","node:path/posix":">= 16","path/win32":">= 15.3","node:path/win32":">= 16",perf_hooks,"node:perf_hooks":[">= 14.18 && < 15",">= 16"],process:process$2,"node:process":[">= 14.18 && < 15",">= 16"],punycode:punycode$2,"node:punycode":[">= 14.18 && < 15",">= 16"],querystring,"node:querystring":[">= 14.18 && < 15",">= 16"],readline:readline$1,"node:readline":[">= 14.18 && < 15",">= 16"],"readline/promises":">= 17","node:readline/promises":">= 17",repl,"node:repl":[">= 14.18 && < 15",">= 16"],"node:sea":[">= 20.12 && < 21",">= 21.7"],smalloc,"node:sqlite":">= 23.4",_stream_duplex:_stream_duplex$1,"node:_stream_duplex":[">= 14.18 && < 15",">= 16"],_stream_transform:_stream_transform$1,"node:_stream_transform":[">= 14.18 && < 15",">= 16"],_stream_wrap,"node:_stream_wrap":[">= 14.18 && < 15",">= 16"],_stream_passthrough:_stream_passthrough$1,
203
203
  "node:_stream_passthrough":[">= 14.18 && < 15",">= 16"],_stream_readable:_stream_readable$1,"node:_stream_readable":[">= 14.18 && < 15",">= 16"],_stream_writable:_stream_writable$1,"node:_stream_writable":[">= 14.18 && < 15",">= 16"],stream:stream$7,"node:stream":[">= 14.18 && < 15",">= 16"],"stream/consumers":">= 16.7","node:stream/consumers":">= 16.7","stream/promises":">= 15","node:stream/promises":">= 16","stream/web":">= 16.5","node:stream/web":">= 16.5",string_decoder:string_decoder$1,"node:string_decoder":[">= 14.18 && < 15",">= 16"],sys,"node:sys":[">= 14.18 && < 15",">= 16"],"test/reporters":">= 19.9 && < 20.2","node:test/reporters":[">= 18.17 && < 19",">= 19.9",">= 20"],"test/mock_loader":">= 22.3 && < 22.7","node:test/mock_loader":">= 22.3 && < 22.7","node:test":[">= 16.17 && < 17",">= 18"],timers:timers$1,"node:timers":[">= 14.18 && < 15",">= 16"],"timers/promises":">= 15","node:timers/promises":">= 16",_tls_common,"node:_tls_common":[">= 14.18 && < 15",">= 16"],
204
- _tls_legacy,_tls_wrap,"node:_tls_wrap":[">= 14.18 && < 15",">= 16"],tls,"node:tls":[">= 14.18 && < 15",">= 16"],trace_events,"node:trace_events":[">= 14.18 && < 15",">= 16"],tty,"node:tty":[">= 14.18 && < 15",">= 16"],url,"node:url":[">= 14.18 && < 15",">= 16"],util:util$c,"node:util":[">= 14.18 && < 15",">= 16"],"util/types":">= 15.3","node:util/types":">= 16","v8/tools/arguments":">= 10 && < 12","v8/tools/codemap":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/consarray":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/csvparser":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/logreader":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/profile_view":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/splaytree":[">= 4.4 && < 5",">= 5.2 && < 12"],v8,"node:v8":[">= 14.18 && < 15",">= 16"],vm,"node:vm":[">= 14.18 && < 15",">= 16"],wasi,"node:wasi":[">= 18.17 && < 19",">= 20"],worker_threads,"node:worker_threads":[">= 14.18 && < 15",">= 16"],zlib,"node:zlib":[">= 14.18 && < 15",">= 16"]
204
+ _tls_legacy,_tls_wrap,"node:_tls_wrap":[">= 14.18 && < 15",">= 16"],tls,"node:tls":[">= 14.18 && < 15",">= 16"],trace_events,"node:trace_events":[">= 14.18 && < 15",">= 16"],tty,"node:tty":[">= 14.18 && < 15",">= 16"],url,"node:url":[">= 14.18 && < 15",">= 16"],util:util$b,"node:util":[">= 14.18 && < 15",">= 16"],"util/types":">= 15.3","node:util/types":">= 16","v8/tools/arguments":">= 10 && < 12","v8/tools/codemap":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/consarray":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/csvparser":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/logreader":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/profile_view":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/splaytree":[">= 4.4 && < 5",">= 5.2 && < 12"],v8,"node:v8":[">= 14.18 && < 15",">= 16"],vm,"node:vm":[">= 14.18 && < 15",">= 16"],wasi,"node:wasi":[">= 18.17 && < 19",">= 20"],worker_threads,"node:worker_threads":[">= 14.18 && < 15",">= 16"],zlib,"node:zlib":[">= 14.18 && < 15",">= 16"]
205
205
  },core_1,hasRequiredCore,isCore,hasRequiredIsCore,sync$7,hasRequiredSync$6,resolve$1,hasRequiredResolve$1;function requireCore(){if(hasRequiredCore)return core_1;hasRequiredCore=1;var e=requireIsCoreModule(),t=require$$1$3,r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=e(n));return core_1=r}function requireIsCore(){if(hasRequiredIsCore)return isCore;hasRequiredIsCore=1;var e=requireIsCoreModule();return isCore=function(t){return e(t)}}function requireSync$6(){if(hasRequiredSync$6)return sync$7;hasRequiredSync$6=1;var e=requireIsCoreModule(),t=fs$8,r=path__default,n=requireHomedir(),i=requireCaller(),s=requireNodeModulesPaths(),o=requireNormalizeOptions(),a="win32"!==process.platform&&t.realpathSync&&"function"==typeof t.realpathSync.native?t.realpathSync.native:t.realpathSync,c=n(),u=function(e){try{var r=t.statSync(e,{throwIfNoEntry:!1})}catch(e){if(e&&("ENOENT"===e.code||"ENOTDIR"===e.code))return!1;throw e}return!!r&&(r.isFile()||r.isFIFO())},l=function(e){try{
206
206
  var r=t.statSync(e,{throwIfNoEntry:!1})}catch(e){if(e&&("ENOENT"===e.code||"ENOTDIR"===e.code))return!1;throw e}return!!r&&r.isDirectory()},d=function(e){try{return a(e)}catch(e){if("ENOENT"!==e.code)throw e}return e},p=function(e,t,r){return r&&!1===r.preserveSymlinks?e(t):t},h=function(e,t){var r=e(t);try{return JSON.parse(r)}catch(e){}};return sync$7=function(n,a){if("string"!=typeof n)throw new TypeError("Path must be a string.");var A=o(n,a),f=A.isFile||u,g=A.readFileSync||t.readFileSync,m=A.isDirectory||l,y=A.realpathSync||d,E=A.readPackageSync||h;if(A.readFileSync&&A.readPackageSync)throw new TypeError("`readFileSync` and `readPackageSync` are mutually exclusive.");var b=A.packageIterator,C=A.extensions||[".js"],v=!1!==A.includeCoreModules,I=A.basedir||r.dirname(i()),_=A.filename||I;A.paths=A.paths||[r.join(c,".node_modules"),r.join(c,".node_libraries")];var S=p(y,r.resolve(I),A);if(/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/.test(n)){var D=r.resolve(S,n)
207
207
  ;"."!==n&&".."!==n&&"/"!==n.slice(-1)||(D+="/");var w=T(D)||$(D);if(w)return p(y,w,A)}else{if(v&&e(n))return n;var R=function(e,t){for(var n=function(){return function(e,t,n){for(var i=s(t,n,e),o=0;o<i.length;o++)i[o]=r.join(i[o],e);return i}(e,t,A)},i=b?b(e,t,n,A):n(),o=0;o<i.length;o++){var a=i[o];if(m(r.dirname(a))){var c=T(a);if(c)return c;var u=$(a);if(u)return u}}}(n,S);if(R)return p(y,R,A)}var B=new Error("Cannot find module '"+n+"' from '"+_+"'");throw B.code="MODULE_NOT_FOUND",B;function T(e){var t=x(r.dirname(e));if(t&&t.dir&&t.pkg&&A.pathFilter){var n=r.relative(t.dir,e),i=A.pathFilter(t.pkg,e,n);i&&(e=r.resolve(t.dir,i))}if(f(e))return e;for(var s=0;s<C.length;s++){var o=e+C[s];if(f(o))return o}}function x(e){if(""!==e&&"/"!==e&&!("win32"===process.platform&&/^\w:[/\\]*$/.test(e)||/[/\\]node_modules[/\\]*$/.test(e))){var t=r.join(p(y,e,A),"package.json");if(!f(t))return x(r.dirname(e));var n=E(g,t);return n&&A.packageFilter&&(n=A.packageFilter(n,e)),{pkg:n,dir:e}}}
@@ -315,9 +315,9 @@ t):(r.forEach(r=>{if("otlp"===r){const r=process.env.OTEL_EXPORTER_OTLP_METRICS_
315
315
  })):"prometheus"===r?t.push(new d.PrometheusExporter):e.diag.warn(`Unsupported OTEL_METRICS_EXPORTER value: "${r}". Supported values are: otlp, console, prometheus, none.`)}),t)):t}();if(this._meterProviderConfig||o.length>0){const t=[];this._meterProviderConfig?.readers&&t.push(...this._meterProviderConfig.readers),0===t.length&&o.forEach(e=>t.push(e));const r=new p.MeterProvider({resource:this._resource,views:this._meterProviderConfig?.views??[],readers:t});this._meterProvider=r,e.metrics.setGlobalMeterProvider(r);for(const t of this._instrumentations)t.setMeterProvider(e.metrics.getMeterProvider())}}shutdown(){const e=[];return this._tracerProvider&&e.push(this._tracerProvider.shutdown()),this._loggerProvider&&e.push(this._loggerProvider.shutdown()),this._meterProvider&&e.push(this._meterProvider.shutdown()),Promise.all(e).then(()=>{})}configureLoggerProviderFromEnv(){const t=(0,g.getStringListFromEnv)("OTEL_LOGS_EXPORTER")??[]
316
316
  ;if(0===t.length&&(e.diag.debug("OTEL_LOGS_EXPORTER is empty. Using default otlp exporter."),t.push("otlp")),t.includes("none"))return void e.diag.info('OTEL_LOGS_EXPORTER contains "none". Logger provider will not be initialized.');const r=[];t.forEach(t=>{if("otlp"===t){const t=((0,g.getStringFromEnv)("OTEL_EXPORTER_OTLP_LOGS_PROTOCOL")??(0,g.getStringFromEnv)("OTEL_EXPORTER_OTLP_PROTOCOL"))?.trim();switch(t){case"grpc":r.push(new o.OTLPLogExporter);break;case"http/json":r.push(new s.OTLPLogExporter);break;case"http/protobuf":case void 0:case"":r.push(new a.OTLPLogExporter);break;default:e.diag.warn(`Unsupported OTLP logs protocol: "${t}". Using http/protobuf.`),r.push(new a.OTLPLogExporter)}}else"console"===t?r.push(new i.ConsoleLogRecordExporter):e.diag.warn(`Unsupported OTEL_LOGS_EXPORTER value: "${t}". Supported values are: otlp, console, none.`)}),r.length>0&&(this._loggerProviderConfig={
317
317
  logRecordProcessors:r.map(e=>e instanceof i.ConsoleLogRecordExporter?new i.SimpleLogRecordProcessor(e):new i.BatchLogRecordProcessor(e))})}},sdk$1}function requireSrc$2(){return hasRequiredSrc$2||(hasRequiredSrc$2=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.NodeSDK=e.tracing=e.resources=e.node=e.metrics=e.logs=e.core=e.contextBase=e.api=void 0,e.api=require$$0$6,e.contextBase=require$$0$6,e.core=require$$1$5,e.logs=require$$2$1,e.metrics=require$$1$b,e.node=requireSrc$6(),e.resources=require$$5$2,e.tracing=require$$6;var t=requireSdk();Object.defineProperty(e,"NodeSDK",{enumerable:!0,get:function(){return t.NodeSDK}})}(src$7)),src$7}var srcExports$3=requireSrc$2(),srcExports$2=requireSrc$6();function register$1(){if(process.env.TELEMETRY_USER){const e="https://7530.tessl.io:443";process.env.OTEL_EXPORTER_OTLP_ENDPOINT=e,process.env.OTEL_EXPORTER_OTLP_PROTOCOL="http/json",
318
- process.env.OTEL_EXPORTER_OTLP_HEADERS=`Authorization=Basic ${Buffer.from(`${process.env.TELEMETRY_USER}:${process.env.TELEMETRY_PASSWORD}`).toString("base64")}`}const e=[];e.push(new srcExports$4.UndiciInstrumentation);const t=new srcExports$3.NodeSDK({resource:resourceFromAttributes({[ATTR_SERVICE_NAME]:"stepper",[ATTR_K8S_POD_NAME]:process.env.INJECTED_POD_NAME,[ATTR_K8S_NAMESPACE_NAME]:process.env.INJECTED_POD_NAMESPACE,[ATTR_K8S_POD_UID]:process.env.INJECTED_POD_UID,[ATTR_VCS_CHANGE_ID]:"ad9dbabe5cdba9abbffd5dcdb298eaf58fc1b8f6",[ATTR_VCS_REF_BASE_NAME]:"ad9dbabe5cdba9abbffd5dcdb298eaf58fc1b8f6"}),instrumentations:e,spanProcessors:[new srcExports$2.SimpleSpanProcessor(process.env.TELEMETRY_USER?new OTLPTraceExporter$1:new srcExports$5.OTLPTraceExporter)]});return t.start(),{shutdown:async()=>{await t.shutdown()}}}"yes"===process.env.TESSL_DEBUG_MONITORING&&diag.setLogger(new DiagConsoleLogger,DiagLogLevel.INFO);const sdk=register$1();function isAbortError$3(e){
318
+ process.env.OTEL_EXPORTER_OTLP_HEADERS=`Authorization=Basic ${Buffer.from(`${process.env.TELEMETRY_USER}:${process.env.TELEMETRY_PASSWORD}`).toString("base64")}`}const e=[];e.push(new srcExports$4.UndiciInstrumentation);const t=new srcExports$3.NodeSDK({resource:resourceFromAttributes({[ATTR_SERVICE_NAME]:"stepper",[ATTR_K8S_POD_NAME]:process.env.INJECTED_POD_NAME,[ATTR_K8S_NAMESPACE_NAME]:process.env.INJECTED_POD_NAMESPACE,[ATTR_K8S_POD_UID]:process.env.INJECTED_POD_UID,[ATTR_VCS_CHANGE_ID]:"515d0a25e7557543b259c4962f29ebdd5fb410ba",[ATTR_VCS_REF_BASE_NAME]:"515d0a25e7557543b259c4962f29ebdd5fb410ba"}),instrumentations:e,spanProcessors:[new srcExports$2.SimpleSpanProcessor(process.env.TELEMETRY_USER?new OTLPTraceExporter$1:new srcExports$5.OTLPTraceExporter)]});return t.start(),{shutdown:async()=>{await t.shutdown()}}}"yes"===process.env.TESSL_DEBUG_MONITORING&&diag.setLogger(new DiagConsoleLogger,DiagLogLevel.INFO);const sdk=register$1();function isAbortError$3(e){
319
319
  return"object"==typeof e&&null!==e&&"AbortError"===e.name}function someErrorIs(e,t,r=32){return!(r<=0)&&(!!t(e)||(!!(e instanceof AggregateError&&e.errors.some(e=>someErrorIs(e,t,r-1)))||!!(e instanceof Error&&"cause"in e&&someErrorIs(e.cause,t,r-1))))}const tracer$1=trace$1.getTracer("stepper/otel");let currentUser,bag;function setOtelUser(e){currentUser=e;const t=trace$1.getActiveSpan();currentUser&&t&&(t.setAttribute(ATTR_USER_ID,currentUser.id),t.setAttribute(ATTR_USER_EMAIL,currentUser.email))}async function withSpan(e,t){return tracer$1.startActiveSpan(e,async e=>{currentUser&&(e.setAttribute(ATTR_USER_ID,currentUser.id),e.setAttribute(ATTR_USER_EMAIL,currentUser.email));try{return await t(e)}catch(t){throw annotateSpanWithError(e,t),t}finally{e.end()}})}function annotateSpanWithError(e,t){let r;someErrorIs(t,e=>isAbortError$3(e))&&e.setAttribute("cancelled",!0),t instanceof Error&&(r=t.message),e.setStatus({code:SpanStatusCode.ERROR,message:r})}function execSyncFailsafe(e){try{
320
- return execSync(e,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",cwd:import.meta.dirname}).trim()}catch(e){return"unknown"}}function isGitDirty(){return"clean"}function initSysinfo(e={}){bag||(bag={}),bag.gitRevision="ad9dbabe5cdba9abbffd5dcdb298eaf58fc1b8f6",bag.gitDirty=isGitDirty(),bag.releaseDate="2025-10-02T13:51:27.075Z",bag.version="v0.24.0",bag.osImplementation=os$2.type(),bag.osRelease=os$2.release(),bag.argv=JSON.stringify(process.argv),bag.nodeVersion=process.version,bag.nodeExecPath=process.execPath,bag.nodeFirstPath=execSyncFailsafe("which node"),Object.assign(bag,e)}function getSysinfo(){if(!bag)throw new Error("Sysinfo not initialized");return{...bag}}const GLOBAL_DIR_NAME=".tessl",PROJECTS_DIR_NAME="projects";function getGlobalDir(){const e=process.env.TESSL_GLOBAL_DIR;if(e&&""!==e.trim())return e;let t=GLOBAL_DIR_NAME;return join(homedir$1(),t)}function getProjectCacheDir(){const e=process.env.TESSL_PROJECT_CACHE_DIR;if(e&&""!==e.trim())return e
320
+ return execSync(e,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",cwd:import.meta.dirname}).trim()}catch(e){return"unknown"}}function isGitDirty(){return"clean"}function initSysinfo(e={}){bag||(bag={}),bag.gitRevision="515d0a25e7557543b259c4962f29ebdd5fb410ba",bag.gitDirty=isGitDirty(),bag.releaseDate="2025-10-07T14:52:51.036Z",bag.version="v0.26.0",bag.osImplementation=os$2.type(),bag.osRelease=os$2.release(),bag.argv=JSON.stringify(process.argv),bag.nodeVersion=process.version,bag.nodeExecPath=process.execPath,bag.nodeFirstPath=execSyncFailsafe("which node"),Object.assign(bag,e)}function getSysinfo(){if(!bag)throw new Error("Sysinfo not initialized");return{...bag}}const GLOBAL_DIR_NAME=".tessl",PROJECTS_DIR_NAME="projects";function getGlobalDir(){const e=process.env.TESSL_GLOBAL_DIR;if(e&&""!==e.trim())return e;let t=GLOBAL_DIR_NAME;return join(homedir$1(),t)}function getProjectCacheDir(){const e=process.env.TESSL_PROJECT_CACHE_DIR;if(e&&""!==e.trim())return e
321
321
  ;const t=getGlobalDir(),r=getProjectDir().replace(/[/\\:]/g,"-").replace(/^-+/,"");return join(t,PROJECTS_DIR_NAME,r)}function getProjectDir(e=!1){const t=process.env.TESSL_PROJECT_DIR;if(t&&""!==t.trim())return t;let r=process.cwd();for(;;){const t=join(r,CONFIG_DIR_NAME);if(existsSync(t))return r;const n=dirname$1(r);if(n===r||n===homedir$1()){if(e)throw new Error("Tessl project root not found");return process.cwd()}r=n}}const T_AND_C_FILE="terms-and-conditions",T_AND_C_URL="https://tessl.io/policies/terms",T_AND_C_QUESTION=`You'll need to review and accept our Terms of Service at ${T_AND_C_URL} before running Tessl.\n\nAccept Terms of Service? [Y/n] `;async function checkLegal(){const e=getGlobalDir(),t=join$1(e,T_AND_C_FILE);if(!existsSync$1(t)||"accepted"!==readFileSync(t,"utf-8")){const e=createInterface({input:process.stdin,output:process.stdout}),r=await new Promise(t=>{e.question(T_AND_C_QUESTION,r=>{e.close(),t(r.toLowerCase())})});if("n"!==r){const e=dirname(t)
322
322
  ;return existsSync$1(e)||mkdirSync(e,{recursive:!0}),writeFileSync(t,"accepted","utf-8"),!0}return!1}return!0}const balanced=(e,t,r)=>{const n=e instanceof RegExp?maybeMatch(e,r):e,i=t instanceof RegExp?maybeMatch(t,r):t,s=null!==n&&null!=i&&range$3(n,i,r);return s&&{start:s[0],end:s[1],pre:r.slice(0,s[0]),body:r.slice(s[0]+n.length,s[1]),post:r.slice(s[1]+i.length)}},maybeMatch=(e,t)=>{const r=t.match(e);return r?r[0]:null},range$3=(e,t,r)=>{let n,i,s,o,a,c=r.indexOf(e),u=r.indexOf(t,c+1),l=c;if(c>=0&&u>0){if(e===t)return[c,u];for(n=[],s=r.length;l>=0&&!a;){if(l===c)n.push(l),c=r.indexOf(e,l+1);else if(1===n.length){const e=n.pop();void 0!==e&&(a=[e,u])}else i=n.pop(),void 0!==i&&i<s&&(s=i,o=u),u=r.indexOf(t,l+1);l=c<u&&c>=0?c:u}n.length&&void 0!==o&&(a=[s,o])}return a
323
323
  },escSlash="\0SLASH"+Math.random()+"\0",escOpen="\0OPEN"+Math.random()+"\0",escClose="\0CLOSE"+Math.random()+"\0",escComma="\0COMMA"+Math.random()+"\0",escPeriod="\0PERIOD"+Math.random()+"\0",escSlashPattern=new RegExp(escSlash,"g"),escOpenPattern=new RegExp(escOpen,"g"),escClosePattern=new RegExp(escClose,"g"),escCommaPattern=new RegExp(escComma,"g"),escPeriodPattern=new RegExp(escPeriod,"g"),slashPattern=/\\\\/g,openPattern=/\\{/g,closePattern=/\\}/g,commaPattern=/\\,/g,periodPattern=/\\./g;function numeric(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function escapeBraces(e){return e.replace(slashPattern,escSlash).replace(openPattern,escOpen).replace(closePattern,escClose).replace(commaPattern,escComma).replace(periodPattern,escPeriod)}function unescapeBraces(e){return e.replace(escSlashPattern,"\\").replace(escOpenPattern,"{").replace(escClosePattern,"}").replace(escCommaPattern,",").replace(escPeriodPattern,".")}function parseCommaParts(e){if(!e)return[""]
@@ -648,7 +648,7 @@ constants$c.exports}var constantsExports=requireConstants$c();function ansiRegex
648
648
  return 161===e||164===e||167===e||168===e||170===e||173===e||174===e||e>=176&&e<=180||e>=182&&e<=186||e>=188&&e<=191||198===e||208===e||215===e||216===e||e>=222&&e<=225||230===e||e>=232&&e<=234||236===e||237===e||240===e||242===e||243===e||e>=247&&e<=250||252===e||254===e||257===e||273===e||275===e||283===e||294===e||295===e||299===e||e>=305&&e<=307||312===e||e>=319&&e<=322||324===e||e>=328&&e<=331||333===e||338===e||339===e||358===e||359===e||363===e||462===e||464===e||466===e||468===e||470===e||472===e||474===e||476===e||593===e||609===e||708===e||711===e||e>=713&&e<=715||717===e||720===e||e>=728&&e<=731||733===e||735===e||e>=768&&e<=879||e>=913&&e<=929||e>=931&&e<=937||e>=945&&e<=961||e>=963&&e<=969||1025===e||e>=1040&&e<=1103||1105===e||8208===e||e>=8211&&e<=8214||8216===e||8217===e||8220===e||8221===e||e>=8224&&e<=8226||e>=8228&&e<=8231||8240===e||8242===e||8243===e||8245===e||8251===e||8254===e||8308===e||8319===e||e>=8321&&e<=8324||8364===e||8451===e||8453===e||8457===e||8467===e||8470===e||8481===e||8482===e||8486===e||8491===e||8531===e||8532===e||e>=8539&&e<=8542||e>=8544&&e<=8555||e>=8560&&e<=8569||8585===e||e>=8592&&e<=8601||8632===e||8633===e||8658===e||8660===e||8679===e||8704===e||8706===e||8707===e||8711===e||8712===e||8715===e||8719===e||8721===e||8725===e||8730===e||e>=8733&&e<=8736||8739===e||8741===e||e>=8743&&e<=8748||8750===e||e>=8756&&e<=8759||8764===e||8765===e||8776===e||8780===e||8786===e||8800===e||8801===e||e>=8804&&e<=8807||8810===e||8811===e||8814===e||8815===e||8834===e||8835===e||8838===e||8839===e||8853===e||8857===e||8869===e||8895===e||8978===e||e>=9312&&e<=9449||e>=9451&&e<=9547||e>=9552&&e<=9587||e>=9600&&e<=9615||e>=9618&&e<=9621||9632===e||9633===e||e>=9635&&e<=9641||9650===e||9651===e||9654===e||9655===e||9660===e||9661===e||9664===e||9665===e||e>=9670&&e<=9672||9675===e||e>=9678&&e<=9681||e>=9698&&e<=9701||9711===e||9733===e||9734===e||9737===e||9742===e||9743===e||9756===e||9758===e||9792===e||9794===e||9824===e||9825===e||e>=9827&&e<=9829||e>=9831&&e<=9834||9836===e||9837===e||9839===e||9886===e||9887===e||9919===e||e>=9926&&e<=9933||e>=9935&&e<=9939||e>=9941&&e<=9953||9955===e||9960===e||9961===e||e>=9963&&e<=9969||9972===e||e>=9974&&e<=9977||9979===e||9980===e||9982===e||9983===e||10045===e||e>=10102&&e<=10111||e>=11094&&e<=11097||e>=12872&&e<=12879||e>=57344&&e<=63743||e>=65024&&e<=65039||65533===e||e>=127232&&e<=127242||e>=127248&&e<=127277||e>=127280&&e<=127337||e>=127344&&e<=127373||127375===e||127376===e||e>=127387&&e<=127404||e>=917760&&e<=917999||e>=983040&&e<=1048573||e>=1048576&&e<=1114109
649
649
  }function isFullWidth(e){return 12288===e||e>=65281&&e<=65376||e>=65504&&e<=65510}function isWide(e){
650
650
  return e>=4352&&e<=4447||8986===e||8987===e||9001===e||9002===e||e>=9193&&e<=9196||9200===e||9203===e||9725===e||9726===e||9748===e||9749===e||e>=9776&&e<=9783||e>=9800&&e<=9811||9855===e||e>=9866&&e<=9871||9875===e||9889===e||9898===e||9899===e||9917===e||9918===e||9924===e||9925===e||9934===e||9940===e||9962===e||9970===e||9971===e||9973===e||9978===e||9981===e||9989===e||9994===e||9995===e||10024===e||10060===e||10062===e||e>=10067&&e<=10069||10071===e||e>=10133&&e<=10135||10160===e||10175===e||11035===e||11036===e||11088===e||11093===e||e>=11904&&e<=11929||e>=11931&&e<=12019||e>=12032&&e<=12245||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12353&&e<=12438||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12773||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=42124||e>=42128&&e<=42182||e>=43360&&e<=43388||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=94176&&e<=94180||94192===e||94193===e||e>=94208&&e<=100343||e>=100352&&e<=101589||e>=101631&&e<=101640||e>=110576&&e<=110579||e>=110581&&e<=110587||110589===e||110590===e||e>=110592&&e<=110882||110898===e||e>=110928&&e<=110930||110933===e||e>=110948&&e<=110951||e>=110960&&e<=111355||e>=119552&&e<=119638||e>=119648&&e<=119670||126980===e||127183===e||127374===e||e>=127377&&e<=127386||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||127568===e||127569===e||e>=127584&&e<=127589||e>=127744&&e<=127776||e>=127789&&e<=127797||e>=127799&&e<=127868||e>=127870&&e<=127891||e>=127904&&e<=127946||e>=127951&&e<=127955||e>=127968&&e<=127984||127988===e||e>=127992&&e<=128062||128064===e||e>=128066&&e<=128252||e>=128255&&e<=128317||e>=128331&&e<=128334||e>=128336&&e<=128359||128378===e||128405===e||128406===e||128420===e||e>=128507&&e<=128591||e>=128640&&e<=128709||128716===e||e>=128720&&e<=128722||e>=128725&&e<=128727||e>=128732&&e<=128735||128747===e||128748===e||e>=128756&&e<=128764||e>=128992&&e<=129003||129008===e||e>=129292&&e<=129338||e>=129340&&e<=129349||e>=129351&&e<=129535||e>=129648&&e<=129660||e>=129664&&e<=129673||e>=129679&&e<=129734||e>=129742&&e<=129756||e>=129759&&e<=129769||e>=129776&&e<=129784||e>=131072&&e<=196605||e>=196608&&e<=262141
651
- }function validate$3(e){if(!Number.isSafeInteger(e))throw new TypeError(`Expected a code point, got \`${typeof e}\`.`)}function eastAsianWidth(e,{ambiguousAsWide:t=!1}={}){return validate$3(e),isFullWidth(e)||isWide(e)||t&&isAmbiguous(e)?2:1}
651
+ }function validate$4(e){if(!Number.isSafeInteger(e))throw new TypeError(`Expected a code point, got \`${typeof e}\`.`)}function eastAsianWidth(e,{ambiguousAsWide:t=!1}={}){return validate$4(e),isFullWidth(e)||isWide(e)||t&&isAmbiguous(e)?2:1}
652
652
  var emojiRegex$6=()=>/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE89\uDE8F-\uDEC2\uDEC6\uDECE-\uDEDC\uDEDF-\uDEE9]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g
653
653
  ;const segmenter=new Intl.Segmenter,defaultIgnorableCodePointRegex=/^\p{Default_Ignorable_Code_Point}$/u;function stringWidth$2(e,t={}){if("string"!=typeof e||0===e.length)return 0;const{ambiguousIsNarrow:r=!0,countAnsiEscapeCodes:n=!1}=t;if(n||(e=stripAnsi$2(e)),0===e.length)return 0;let i=0;const s={ambiguousAsWide:!r};for(const{segment:t}of segmenter.segment(e)){const e=t.codePointAt(0);e<=31||e>=127&&e<=159||(e>=8203&&e<=8207||65279===e||e>=768&&e<=879||e>=6832&&e<=6911||e>=7616&&e<=7679||e>=8400&&e<=8447||e>=65056&&e<=65071||e>=55296&&e<=57343||e>=65024&&e<=65039||defaultIgnorableCodePointRegex.test(t)||(emojiRegex$6().test(t)?i+=2:i+=eastAsianWidth(e,s)))}return i}function widestLine(e){let t=0;for(const r of e.split("\n"))t=Math.max(t,stringWidth$2(r));return t}const cache$7={},measureText=e=>{if(0===e.length)return{width:0,height:0};const t=cache$7[e];if(t)return t;const r=widestLine(e),n=e.split("\n").length;return cache$7[e]={width:r,height:n},{width:r,height:n}
654
654
  },ANSI_BACKGROUND_OFFSET=10,wrapAnsi16=(e=0)=>t=>`[${t+e}m`,wrapAnsi256=(e=0)=>t=>`[${38+e};5;${t}m`,wrapAnsi16m=(e=0)=>(t,r,n)=>`[${38+e};2;${t};${r};${n}m`,styles$1={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}}
@@ -757,10 +757,10 @@ clear:n.clear}},getOptions=(e={})=>e instanceof Stream$2?{stdout:e,stdin:process
757
757
  "[15~":"f5","[17~":"f6","[18~":"f7","[19~":"f8","[20~":"f9","[21~":"f10","[23~":"f11","[24~":"f12","[A":"up","[B":"down","[C":"right","[D":"left","[E":"clear","[F":"end","[H":"home",OA:"up",OB:"down",OC:"right",OD:"left",OE:"clear",OF:"end",OH:"home","[1~":"home","[2~":"insert","[3~":"delete","[4~":"end","[5~":"pageup","[6~":"pagedown","[[5~":"pageup","[[6~":"pagedown","[7~":"home","[8~":"end","[a":"up","[b":"down","[c":"right","[d":"left","[e":"clear","[2$":"insert","[3$":"delete","[5$":"pageup","[6$":"pagedown","[7$":"home","[8$":"end",Oa:"up",Ob:"down",Oc:"right",Od:"left",Oe:"clear","[2^":"insert","[3^":"delete","[5^":"pageup","[6^":"pagedown","[7^":"home","[8^":"end","[Z":"tab"},nonAlphanumericKeys=[...Object.values(keyName),"backspace"],isShiftKey=e=>["[a","[b","[c","[d","[e","[2$","[3$","[5$","[6$","[7$","[8$","[Z"].includes(e),isCtrlKey=e=>["Oa","Ob","Oc","Od","Oe","[2^","[3^","[5^","[6^","[7^","[8^"].includes(e),parseKeypress=(e="")=>{let t
758
758
  ;Buffer$1.isBuffer(e)?e[0]>127&&void 0===e[1]?(e[0]-=128,e=""+String(e)):e=String(e):void 0!==e&&"string"!=typeof e?e=String(e):e||(e="");const r={name:"",ctrl:!1,meta:!1,shift:!1,option:!1,sequence:e,raw:e};if(r.sequence=r.sequence||e||r.name,"\r"===e)r.raw=void 0,r.name="return";else if("\n"===e)r.name="enter";else if("\t"===e)r.name="tab";else if("\b"===e||"\b"===e)r.name="backspace",r.meta=""===e.charAt(0);else if(""===e||""===e)r.name="delete",r.meta=""===e.charAt(0);else if(""===e||""===e)r.name="escape",r.meta=2===e.length;else if(" "===e||" "===e)r.name="space",r.meta=2===e.length;else if(1===e.length&&e<="")r.name=String.fromCharCode(e.charCodeAt(0)+"a".charCodeAt(0)-1),r.ctrl=!0;else if(1===e.length&&e>="0"&&e<="9")r.name="number";else if(1===e.length&&e>="a"&&e<="z")r.name=e;else if(1===e.length&&e>="A"&&e<="Z")r.name=e.toLowerCase(),r.shift=!0;else if(t=metaKeyCodeRe.exec(e))r.meta=!0,r.shift=/^[A-Z]$/.test(t[1]);else if(t=fnKeyRe.exec(e)){const n=[...e]
759
759
  ;""===n[0]&&""===n[1]&&(r.option=!0);const i=[t[1],t[2],t[4],t[6]].filter(Boolean).join(""),s=(t[3]||t[5]||1)-1;r.ctrl=!!(4&s),r.meta=!!(10&s),r.shift=!!(1&s),r.code=i,r.name=keyName[i],r.shift=isShiftKey(i)||r.shift,r.ctrl=isCtrlKey(i)||r.ctrl}return r},useStdin=()=>reactExports.useContext(StdinContext),useInput=(e,t={})=>{const{stdin:r,setRawMode:n,internal_exitOnCtrlC:i,internal_eventEmitter:s}=useStdin();reactExports.useEffect(()=>{if(!1!==t.isActive)return n(!0),()=>{n(!1)}},[t.isActive,n]),reactExports.useEffect(()=>{if(!1===t.isActive)return;const r=t=>{const r=parseKeypress(t),n={upArrow:"up"===r.name,downArrow:"down"===r.name,leftArrow:"left"===r.name,rightArrow:"right"===r.name,pageDown:"pagedown"===r.name,pageUp:"pageup"===r.name,return:"return"===r.name,escape:"escape"===r.name,ctrl:r.ctrl,shift:r.shift,tab:"tab"===r.name,backspace:"backspace"===r.name,delete:"delete"===r.name,meta:r.meta||"escape"===r.name||r.option};let s=r.ctrl?r.name:r.sequence
760
- ;nonAlphanumericKeys.includes(r.name)&&(s=""),s.startsWith("")&&(s=s.slice(1)),1===s.length&&"string"==typeof s[0]&&/[A-Z]/.test(s[0])&&(n.shift=!0),"c"===s&&n.ctrl&&i||reconciler.batchedUpdates(()=>{e(s,n)})};return s?.on("input",r),()=>{s?.removeListener("input",r)}},[t.isActive,r,i,e])},useApp=()=>reactExports.useContext(AppContext);function createScanner(e,t=!1){const r=e.length;let n=0,i="",s=0,o=16,a=0,c=0,u=0,l=0,d=0;function p(t,r){let i=0,s=0;for(;i<t;){let t=e.charCodeAt(n);if(t>=48&&t<=57)s=16*s+t-48;else if(t>=65&&t<=70)s=16*s+t-65+10;else{if(!(t>=97&&t<=102))break;s=16*s+t-97+10}n++,i++}return i<t&&(s=-1),s}function h(){if(i="",d=0,s=n,c=a,l=u,n>=r)return s=r,o=17;let t=e.charCodeAt(n);if(isWhiteSpace$1(t)){do{n++,i+=String.fromCharCode(t),t=e.charCodeAt(n)}while(isWhiteSpace$1(t));return o=15}if(isLineBreak(t))return n++,i+=String.fromCharCode(t),13===t&&10===e.charCodeAt(n)&&(n++,i+="\n"),a++,u=n,o=14;switch(t){case 123:return n++,o=1;case 125:return n++,o=2;case 91:
760
+ ;nonAlphanumericKeys.includes(r.name)&&(s=""),s.startsWith("")&&(s=s.slice(1)),1===s.length&&"string"==typeof s[0]&&/[A-Z]/.test(s[0])&&(n.shift=!0),"c"===s&&n.ctrl&&i||reconciler.batchedUpdates(()=>{e(s,n)})};return s?.on("input",r),()=>{s?.removeListener("input",r)}},[t.isActive,r,i,e])},useApp=()=>reactExports.useContext(AppContext);function createScanner(e,t=!1){const r=e.length;let n=0,i="",s=0,o=16,a=0,c=0,u=0,l=0,d=0;function p(t,r){let i=0,s=0;for(;i<t;){let t=e.charCodeAt(n);if(t>=48&&t<=57)s=16*s+t-48;else if(t>=65&&t<=70)s=16*s+t-65+10;else{if(!(t>=97&&t<=102))break;s=16*s+t-97+10}n++,i++}return i<t&&(s=-1),s}function h(){if(i="",d=0,s=n,c=a,l=u,n>=r)return s=r,o=17;let t=e.charCodeAt(n);if(isWhiteSpace$2(t)){do{n++,i+=String.fromCharCode(t),t=e.charCodeAt(n)}while(isWhiteSpace$2(t));return o=15}if(isLineBreak(t))return n++,i+=String.fromCharCode(t),13===t&&10===e.charCodeAt(n)&&(n++,i+="\n"),a++,u=n,o=14;switch(t){case 123:return n++,o=1;case 125:return n++,o=2;case 91:
761
761
  return n++,o=3;case 93:return n++,o=4;case 58:return n++,o=6;case 44:return n++,o=5;case 34:return n++,i=function(){let t="",i=n;for(;;){if(n>=r){t+=e.substring(i,n),d=2;break}const s=e.charCodeAt(n);if(34===s){t+=e.substring(i,n),n++;break}if(92!==s){if(s>=0&&s<=31){if(isLineBreak(s)){t+=e.substring(i,n),d=2;break}d=6}n++}else{if(t+=e.substring(i,n),n++,n>=r){d=2;break}switch(e.charCodeAt(n++)){case 34:t+='"';break;case 92:t+="\\";break;case 47:t+="/";break;case 98:t+="\b";break;case 102:t+="\f";break;case 110:t+="\n";break;case 114:t+="\r";break;case 116:t+="\t";break;case 117:const e=p(4);e>=0?t+=String.fromCharCode(e):d=4;break;default:d=5}i=n}}return t}(),o=10;case 47:const c=n-1;if(47===e.charCodeAt(n+1)){for(n+=2;n<r&&!isLineBreak(e.charCodeAt(n));)n++;return i=e.substring(c,n),o=12}if(42===e.charCodeAt(n+1)){n+=2;const t=r-1;let s=!1;for(;n<t;){const t=e.charCodeAt(n);if(42===t&&47===e.charCodeAt(n+1)){n+=2,s=!0;break}n++,isLineBreak(t)&&(13===t&&10===e.charCodeAt(n)&&n++,a++,
762
762
  u=n)}return s||(n++,d=1),i=e.substring(c,n),o=13}return i+=String.fromCharCode(t),n++,o=16;case 45:if(i+=String.fromCharCode(t),n++,n===r||!isDigit(e.charCodeAt(n)))return o=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return i+=function(){let t=n;if(48===e.charCodeAt(n))n++;else for(n++;n<e.length&&isDigit(e.charCodeAt(n));)n++;if(n<e.length&&46===e.charCodeAt(n)){if(n++,!(n<e.length&&isDigit(e.charCodeAt(n))))return d=3,e.substring(t,n);for(n++;n<e.length&&isDigit(e.charCodeAt(n));)n++}let r=n;if(n<e.length&&(69===e.charCodeAt(n)||101===e.charCodeAt(n)))if(n++,(n<e.length&&43===e.charCodeAt(n)||45===e.charCodeAt(n))&&n++,n<e.length&&isDigit(e.charCodeAt(n))){for(n++;n<e.length&&isDigit(e.charCodeAt(n));)n++;r=n}else d=3;return e.substring(t,r)}(),o=11;default:for(;n<r&&A(t);)n++,t=e.charCodeAt(n);if(s!==n){switch(i=e.substring(s,n),i){case"true":return o=8;case"false":return o=9;case"null":return o=7}return o=16}return i+=String.fromCharCode(t),
763
- n++,o=16}}function A(e){if(isWhiteSpace$1(e)||isLineBreak(e))return!1;switch(e){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}return{setPosition:function(e){n=e,i="",s=0,o=16,d=0},getPosition:()=>n,scan:t?function(){let e;do{e=h()}while(e>=12&&e<=15);return e}:h,getToken:()=>o,getTokenValue:()=>i,getTokenOffset:()=>s,getTokenLength:()=>n-s,getTokenStartLine:()=>c,getTokenStartCharacter:()=>s-l,getTokenError:()=>d}}function isWhiteSpace$1(e){return 32===e||9===e}function isLineBreak(e){return 10===e||13===e}function isDigit(e){return e>=48&&e<=57}var CharacterCodes;!function(e){e[e.lineFeed=10]="lineFeed",e[e.carriageReturn=13]="carriageReturn",e[e.space=32]="space",e[e._0=48]="_0",e[e._1=49]="_1",e[e._2=50]="_2",e[e._3=51]="_3",e[e._4=52]="_4",e[e._5=53]="_5",e[e._6=54]="_6",e[e._7=55]="_7",e[e._8=56]="_8",e[e._9=57]="_9",e[e.a=97]="a",e[e.b=98]="b",e[e.c=99]="c",e[e.d=100]="d",e[e.e=101]="e",e[e.f=102]="f",e[e.g=103]="g",e[e.h=104]="h",
763
+ n++,o=16}}function A(e){if(isWhiteSpace$2(e)||isLineBreak(e))return!1;switch(e){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}return{setPosition:function(e){n=e,i="",s=0,o=16,d=0},getPosition:()=>n,scan:t?function(){let e;do{e=h()}while(e>=12&&e<=15);return e}:h,getToken:()=>o,getTokenValue:()=>i,getTokenOffset:()=>s,getTokenLength:()=>n-s,getTokenStartLine:()=>c,getTokenStartCharacter:()=>s-l,getTokenError:()=>d}}function isWhiteSpace$2(e){return 32===e||9===e}function isLineBreak(e){return 10===e||13===e}function isDigit(e){return e>=48&&e<=57}var CharacterCodes;!function(e){e[e.lineFeed=10]="lineFeed",e[e.carriageReturn=13]="carriageReturn",e[e.space=32]="space",e[e._0=48]="_0",e[e._1=49]="_1",e[e._2=50]="_2",e[e._3=51]="_3",e[e._4=52]="_4",e[e._5=53]="_5",e[e._6=54]="_6",e[e._7=55]="_7",e[e._8=56]="_8",e[e._9=57]="_9",e[e.a=97]="a",e[e.b=98]="b",e[e.c=99]="c",e[e.d=100]="d",e[e.e=101]="e",e[e.f=102]="f",e[e.g=103]="g",e[e.h=104]="h",
764
764
  e[e.i=105]="i",e[e.j=106]="j",e[e.k=107]="k",e[e.l=108]="l",e[e.m=109]="m",e[e.n=110]="n",e[e.o=111]="o",e[e.p=112]="p",e[e.q=113]="q",e[e.r=114]="r",e[e.s=115]="s",e[e.t=116]="t",e[e.u=117]="u",e[e.v=118]="v",e[e.w=119]="w",e[e.x=120]="x",e[e.y=121]="y",e[e.z=122]="z",e[e.A=65]="A",e[e.B=66]="B",e[e.C=67]="C",e[e.D=68]="D",e[e.E=69]="E",e[e.F=70]="F",e[e.G=71]="G",e[e.H=72]="H",e[e.I=73]="I",e[e.J=74]="J",e[e.K=75]="K",e[e.L=76]="L",e[e.M=77]="M",e[e.N=78]="N",e[e.O=79]="O",e[e.P=80]="P",e[e.Q=81]="Q",e[e.R=82]="R",e[e.S=83]="S",e[e.T=84]="T",e[e.U=85]="U",e[e.V=86]="V",e[e.W=87]="W",e[e.X=88]="X",e[e.Y=89]="Y",e[e.Z=90]="Z",e[e.asterisk=42]="asterisk",e[e.backslash=92]="backslash",e[e.closeBrace=125]="closeBrace",e[e.closeBracket=93]="closeBracket",e[e.colon=58]="colon",e[e.comma=44]="comma",e[e.dot=46]="dot",e[e.doubleQuote=34]="doubleQuote",e[e.minus=45]="minus",e[e.openBrace=123]="openBrace",e[e.openBracket=91]="openBracket",e[e.plus=43]="plus",e[e.slash=47]="slash",
765
765
  e[e.formFeed=12]="formFeed",e[e.tab=9]="tab"}(CharacterCodes||(CharacterCodes={}));const cachedSpaces=new Array(20).fill(0).map((e,t)=>" ".repeat(t)),maxCachedValues=200,cachedBreakLinesWithSpaces={" ":{"\n":new Array(maxCachedValues).fill(0).map((e,t)=>"\n"+" ".repeat(t)),"\r":new Array(maxCachedValues).fill(0).map((e,t)=>"\r"+" ".repeat(t)),"\r\n":new Array(maxCachedValues).fill(0).map((e,t)=>"\r\n"+" ".repeat(t))},"\t":{"\n":new Array(maxCachedValues).fill(0).map((e,t)=>"\n"+"\t".repeat(t)),"\r":new Array(maxCachedValues).fill(0).map((e,t)=>"\r"+"\t".repeat(t)),"\r\n":new Array(maxCachedValues).fill(0).map((e,t)=>"\r\n"+"\t".repeat(t))}},supportedEols=["\n","\r","\r\n"];function format$4(e,t,r){let n,i,s,o,a;if(t){for(o=t.offset,a=o+t.length,s=o;s>0&&!isEOL(e,s-1);)s--;let c=a;for(;c<e.length&&!isEOL(e,c);)c++;i=e.substring(s,c),n=computeIndentLevel(i,r)}else i=e,n=0,s=0,o=0,a=e.length;const c=getEOL(r,e),u=supportedEols.includes(c);let l,d=0,p=0
766
766
  ;l=r.insertSpaces?cachedSpaces[r.tabSize||4]??repeat$1(cachedSpaces[1],r.tabSize||4):"\t";const h="\t"===l?"\t":" ";let A=createScanner(i,!1),f=!1;function g(){if(d>1)return repeat$1(c,d)+repeat$1(l,n+p);const e=l.length*(n+p);return!u||e>cachedBreakLinesWithSpaces[h][c].length?c+repeat$1(l,n+p):e<=0?c:cachedBreakLinesWithSpaces[h][c][e]}function m(){let e=A.scan();for(d=0;15===e||14===e;)14===e&&r.keepLines?d+=1:14===e&&(d=1),e=A.scan();return f=16===e||0!==A.getTokenError(),e}const y=[];function E(r,n,i){f||t&&!(n<a&&i>o)||e.substring(n,i)===r||y.push({offset:n,length:i-n,content:r})}let b=m();if(r.keepLines&&d>0&&E(repeat$1(c,d),0,0),17!==b){let e=A.getTokenOffset()+s;E(l.length*n<20&&r.insertSpaces?cachedSpaces[l.length*n]:repeat$1(l,n),s,e)}for(;17!==b;){let e=A.getTokenOffset()+A.getTokenLength()+s,t=m(),n="",i=!1;for(;0===d&&(12===t||13===t);){let r=A.getTokenOffset()+s;E(cachedSpaces[1],e,r),e=A.getTokenOffset()+A.getTokenLength()+s,i=12===t,n=i?g():"",t=m()}
@@ -836,31 +836,31 @@ value:function(e){return this.transformers.reduce(function(e,t){return t.onStrin
836
836
  if("initial"===e){var r=t.match(/^[^\S\n]*(?=\S)/gm),n=r&&Math.min.apply(Math,_toConsumableArray(r.map(function(e){return e.length})));if(n){var i=new RegExp("^.{"+n+"}","gm");return t.replace(i,"")}return t}if("all"===e)return t.replace(/^[^\S\n]+/gm,"");throw new Error("Unknown type: "+e)}}},replaceResultTransformer=function(e,t){return{onEndResult:function(r){if(null==e||null==t)throw new Error("replaceResultTransformer requires at least 2 arguments.");return r.replace(e,t)}}},replaceSubstitutionTransformer=function(e,t){return{onSubstitution:function(r,n){if(null==e||null==t)throw new Error("replaceSubstitutionTransformer requires at least 2 arguments.");return null==r?r:r.toString().replace(e,t)}}},defaults$1={separator:"",conjunction:"",serial:!1},inlineArrayTransformer=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:defaults$1;return{onSubstitution:function(t,r){if(Array.isArray(t)){
837
837
  var n=t.length,i=e.separator,s=e.conjunction,o=e.serial,a=r.match(/(\n?[^\S\n]+)$/);if(t=a?t.join(i+a[1]):t.join(i+" "),s&&n>1){var c=t.lastIndexOf(i);t=t.slice(0,c)+(o?i:"")+" "+s+t.slice(c+1)}}return t}}},splitStringTransformer=function(e){return{onSubstitution:function(t,r){return"string"==typeof t&&t.includes(e)&&(t=t.split(e)),t}}},isValidValue=function(e){return null!=e&&!Number.isNaN(e)&&"boolean"!=typeof e},removeNonPrintingValuesTransformer=function(){return{onSubstitution:function(e){return Array.isArray(e)?e.filter(isValidValue):isValidValue(e)?e:""}}};new TemplateTag(inlineArrayTransformer({separator:","}),stripIndentTransformer,trimResultTransformer),new TemplateTag(inlineArrayTransformer({separator:",",conjunction:"and"}),stripIndentTransformer,trimResultTransformer),new TemplateTag(inlineArrayTransformer({separator:",",conjunction:"or"}),stripIndentTransformer,trimResultTransformer),
838
838
  new TemplateTag(splitStringTransformer("\n"),removeNonPrintingValuesTransformer,inlineArrayTransformer,stripIndentTransformer,trimResultTransformer),new TemplateTag(splitStringTransformer("\n"),inlineArrayTransformer,stripIndentTransformer,trimResultTransformer,replaceSubstitutionTransformer(/&/g,"&amp;"),replaceSubstitutionTransformer(/</g,"&lt;"),replaceSubstitutionTransformer(/>/g,"&gt;"),replaceSubstitutionTransformer(/"/g,"&quot;"),replaceSubstitutionTransformer(/'/g,"&#x27;"),replaceSubstitutionTransformer(/`/g,"&#x60;")),new TemplateTag(replaceResultTransformer(/(?:\n(?:\s*))+/g," "),trimResultTransformer),new TemplateTag(replaceResultTransformer(/(?:\n\s*)/g,""),trimResultTransformer),new TemplateTag(inlineArrayTransformer({separator:","}),replaceResultTransformer(/(?:\s+)/g," "),trimResultTransformer),new TemplateTag(inlineArrayTransformer({separator:",",conjunction:"or"}),replaceResultTransformer(/(?:\s+)/g," "),trimResultTransformer),new TemplateTag(inlineArrayTransformer({
839
- separator:",",conjunction:"and"}),replaceResultTransformer(/(?:\s+)/g," "),trimResultTransformer),new TemplateTag(inlineArrayTransformer,stripIndentTransformer,trimResultTransformer),new TemplateTag(inlineArrayTransformer,replaceResultTransformer(/(?:\s+)/g," "),trimResultTransformer);var stripIndent=new TemplateTag(stripIndentTransformer,trimResultTransformer),stripIndents=new TemplateTag(stripIndentTransformer("all"),trimResultTransformer),error$2,hasRequiredError$1,decode$4,hasRequiredDecode$1,constants$a,hasRequiredConstants$a,objects,hasRequiredObjects,strings,hasRequiredStrings,encode$4,hasRequiredEncode$1,helpers$2,hasRequiredHelpers$1,normalize$1,hasRequiredNormalize,lang,hasRequiredLang,validate$2,hasRequiredValidate$1,purlComponent,hasRequiredPurlComponent,purlQualifierNames,hasRequiredPurlQualifierNames,purlType,hasRequiredPurlType,packageUrl,hasRequiredPackageUrl,packageurlJs,hasRequiredPackageurlJs;function requireError$1(){if(hasRequiredError$1)return error$2
839
+ separator:",",conjunction:"and"}),replaceResultTransformer(/(?:\s+)/g," "),trimResultTransformer),new TemplateTag(inlineArrayTransformer,stripIndentTransformer,trimResultTransformer),new TemplateTag(inlineArrayTransformer,replaceResultTransformer(/(?:\s+)/g," "),trimResultTransformer);var stripIndent=new TemplateTag(stripIndentTransformer,trimResultTransformer),stripIndents=new TemplateTag(stripIndentTransformer("all"),trimResultTransformer),error$2,hasRequiredError$1,decode$4,hasRequiredDecode$1,constants$a,hasRequiredConstants$a,objects,hasRequiredObjects,strings,hasRequiredStrings,encode$4,hasRequiredEncode$1,helpers$2,hasRequiredHelpers$1,normalize$1,hasRequiredNormalize,lang,hasRequiredLang,validate$3,hasRequiredValidate$1,purlComponent,hasRequiredPurlComponent,purlQualifierNames,hasRequiredPurlQualifierNames,purlType,hasRequiredPurlType,packageUrl,hasRequiredPackageUrl,packageurlJs,hasRequiredPackageurlJs;function requireError$1(){if(hasRequiredError$1)return error$2
840
840
  ;function e(e=""){const{length:t}=e;let r="";if(t){const n=e.charCodeAt(0);r=n>=65||n<=90?`${e[0].toLowerCase()}${e.slice(1)}`:e,t>1&&46===e.charCodeAt(t-1)&&46!==e.charCodeAt(t-2)&&(r=r.slice(0,-1))}return`Invalid purl: ${r}`}hasRequiredError$1=1;class t extends Error{constructor(t){super(e(t))}}return error$2={formatPurlErrorMessage:e,PurlError:t}}function requireDecode$1(){if(hasRequiredDecode$1)return decode$4;hasRequiredDecode$1=1;const{PurlError:e}=requireError$1(),{decodeURIComponent:t}=globalThis;return decode$4={decodePurlComponent:function(r,n){try{return t(n)}catch{}throw new e(`unable to decode "${r}" component`)}}}function requireConstants$a(){if(hasRequiredConstants$a)return constants$a;hasRequiredConstants$a=1;const e=new URLSearchParams;return constants$a={LOOP_SENTINEL:1e6,REUSED_SEARCH_PARAMS:e,REUSED_SEARCH_PARAMS_KEY:"_",REUSED_SEARCH_PARAMS_OFFSET:2}}function requireObjects(){if(hasRequiredObjects)return objects;hasRequiredObjects=1
841
841
  ;const{LOOP_SENTINEL:e}=requireConstants$a();return objects={isObject:function(e){return null!==e&&"object"==typeof e},recursiveFreeze:function(t){if(null===t||"object"!=typeof t&&"function"!=typeof t||Object.isFrozen(t))return t;const r=[t];let{length:n}=r,i=0;for(;i<n;){if(i===e)throw new Error("Detected infinite loop in object crawl of recursiveFreeze");const t=r[i++];if(Object.freeze(t),Array.isArray(t))for(let e=0,{length:i}=t;e<i;e+=1){const i=t[e];null===i||"object"!=typeof i&&"function"!=typeof i||Object.isFrozen(i)||(r[n++]=i)}else{const e=Reflect.ownKeys(t);for(let i=0,{length:s}=e;i<s;i+=1){const s=t[e[i]];null===s||"object"!=typeof s&&"function"!=typeof s||Object.isFrozen(s)||(r[n++]=s)}}}return t}},objects}function requireStrings(){if(hasRequiredStrings)return strings;hasRequiredStrings=1
842
842
  ;const{compare:e}=new Intl.Collator,t=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;return strings={isBlank:function(e){for(let t=0,{length:r}=e;t<r;t+=1){const r=e.charCodeAt(t);if(32!==r&&9!==r&&10!==r&&11!==r&&12!==r&&13!==r&&160!==r&&5760!==r&&8192!==r&&8193!==r&&8194!==r&&8195!==r&&8196!==r&&8197!==r&&8198!==r&&8199!==r&&8200!==r&&8201!==r&&8202!==r&&8232!==r&&8233!==r&&8239!==r&&8287!==r&&12288!==r&&65279!==r)return!1}return!0},isNonEmptyString:function(e){return"string"==typeof e&&e.length>0},isSemverString:function(e){return"string"==typeof e&&t.test(e)},localeCompare:e,lowerName:function(e){e.name=e.name.toLowerCase()},lowerNamespace:function(e){const{namespace:t}=e;"string"==typeof t&&(e.namespace=t.toLowerCase())},lowerVersion:function(e){const{version:t}=e;"string"==typeof t&&(e.version=t.toLowerCase())},
843
843
  replaceDashesWithUnderscores:function(e){let t="",r=0,n=0;for(;-1!==(n=e.indexOf("-",r));)t=t+e.slice(r,n)+"_",r=n+1;return r?t+e.slice(r):e},replaceUnderscoresWithDashes:function(e){let t="",r=0,n=0;for(;-1!==(n=e.indexOf("_",r));)t=t+e.slice(r,n)+"-",r=n+1;return r?t+e.slice(r):e},trimLeadingSlashes:function(e){let t=0;for(;47===e.charCodeAt(t);)t+=1;return 0===t?e:e.slice(t)}},strings}function requireEncode$1(){if(hasRequiredEncode$1)return encode$4;hasRequiredEncode$1=1;const{REUSED_SEARCH_PARAMS:e,REUSED_SEARCH_PARAMS_KEY:t,REUSED_SEARCH_PARAMS_OFFSET:r}=requireConstants$a(),{isObject:n}=requireObjects(),{isNonEmptyString:i}=requireStrings(),{encodeURIComponent:s}=globalThis;function o(e){return e.replace(/\+/g,"%20")}return encode$4={encodeNamespace:function(e){return i(e)?s(e).replace(/%3A/g,":").replace(/%2F/g,"/"):""},encodeVersion:function(e){return i(e)?s(e).replace(/%3A/g,":").replace(/%2B/g,"+"):""},encodeQualifiers:function(e){if(n(e)){
844
844
  const t=Object.keys(e).sort(),r=new URLSearchParams;for(let n=0,{length:i}=t;n<i;n+=1){const i=t[n];r.set(i,e[i])}return o(r.toString())}return""},encodeQualifierParam:function(n){return i(n)?(e.set(t,n),o(e.toString().slice(r))):""},encodeSubpath:function(e){return i(e)?s(e).replace(/%2F/g,"/"):""},encodeURIComponent:s},encode$4}function requireHelpers$1(){if(hasRequiredHelpers$1)return helpers$2;return hasRequiredHelpers$1=1,helpers$2={createHelpersNamespaceObject:function(e,t={}){const{comparator:r,...n}={__proto__:null,...t},i=Object.keys(e).sort(),s=[...new Set([...Object.values(e)].map(Object.keys).flat())].sort(r),o=Object.create(null);for(let t=0,{length:r}=s;t<r;t+=1){const r=s[t],a=Object.create(null);for(let t=0,{length:s}=i;t<s;t+=1){const s=i[t],o=e[s][r]??n[s];void 0!==o&&(a[s]=o)}o[r]=a}return o}},helpers$2}function requireNormalize(){if(hasRequiredNormalize)return normalize$1;hasRequiredNormalize=1;const{isObject:e}=requireObjects(),{isBlank:t}=requireStrings()
845
845
  ;function r(e,t){let r="",n=0;for(;47===e.charCodeAt(n);)n+=1;let i=e.indexOf("/",n);if(-1===i)return e.slice(n);for(;-1!==i;){const s=e.slice(n,i);for((void 0===t||t(s))&&(r=r+(0===r.length?"":"/")+s),n=i+1;47===e.charCodeAt(n);)n+=1;i=e.indexOf("/",n)}const s=e.slice(n);return 0===s.length||void 0!==t&&!t(s)||(r=r+"/"+s),r}function n(e){const{length:r}=e;return(1!==r||46!==e.charCodeAt(0))&&((2!==r||46!==e.charCodeAt(0)||46!==e.charCodeAt(1))&&!t(e))}return normalize$1={normalizeName:function(e){return"string"==typeof e?e.trim():void 0},normalizeNamespace:function(e){return"string"==typeof e?r(e):void 0},normalizePath:r,normalizeQualifiers:function(t){let r;for(const{0:n,1:i}of function(t){if(e(t))return t instanceof URLSearchParams?t.entries():Object.entries(t);return"string"==typeof t?new URLSearchParams(t).entries():Object.entries({})}(t)){const e=("string"==typeof i?i:String(i)).trim();0!==e.length&&(void 0===r&&(r={__proto__:null}),r[n.toLowerCase()]=e)}return r},
846
- normalizeSubpath:function(e){return"string"==typeof e?r(e,n):void 0},normalizeType:function(e){return"string"==typeof e?e.trim().toLowerCase():void 0},normalizeVersion:function(e){return"string"==typeof e?e.trim():void 0}}}function requireLang(){if(hasRequiredLang)return lang;return hasRequiredLang=1,lang={isNullishOrEmptyString:function(e){return null==e||"string"==typeof e&&0===e.length}}}function requireValidate$1(){if(hasRequiredValidate$1)return validate$2;hasRequiredValidate$1=1;const{PurlError:e}=requireError$1(),{isNullishOrEmptyString:t}=requireLang(),{isNonEmptyString:r}=requireStrings();function n(t,r){if(!s("qualifier",t,r))return!1;for(let n=0,{length:i}=t;n<i;n+=1){const i=t.charCodeAt(n);if(!(i>=48&&i<=57||i>=65&&i<=90||i>=97&&i<=122||46===i||45===i||95===i)){if(r)throw new e(`qualifier "${t}" contains an illegal character`);return!1}}return!0}function i(r,n,i){if(t(n)){if(i)throw new e(`"${r}" is a required component`);return!1}return!0}function s(t,n,i){if(r(n)){
847
- const r=n.charCodeAt(0);if(r>=48&&r<=57){if(i)throw new e(`${t} "${n}" cannot start with a number`);return!1}}return!0}function o(t,r,n){if(null==r||"string"==typeof r)return!0;if(n)throw new e(`"'${t}" must be a string`);return!1}return validate$2={validateEmptyByType:function(r,n,i,s){if(!t(i)){if(s)throw new e(`${r} "${n}" component must be empty`);return!1}return!0},validateName:function(e,t){return i("name",e,t)&&o("name",e,t)},validateNamespace:function(e,t){return o("namespace",e,t)},validateQualifiers:function(t,r){if(null==t)return!0;if("object"!=typeof t){if(r)throw new e('"qualifiers" must be an object');return!1}const i="function"==typeof t.keys?t.keys():Object.keys(t);for(const e of i)if(!n(e,r))return!1;return!0},validateQualifierKey:n,validateRequired:i,validateRequiredByType:function(r,n,i,s){if(t(i)){if(s)throw new e(`${r} requires a "${n}" component`);return!1}return!0},validateStartsWithoutNumber:s,validateStrings:o,validateSubpath:function(e,t){
848
- return o("subpath",e,t)},validateType:function(t,r){if(!i("type",t,r)||!o("type",t,r)||!s("type",t,r))return!1;for(let n=0,{length:i}=t;n<i;n+=1){const i=t.charCodeAt(n);if(!(i>=48&&i<=57||i>=65&&i<=90||i>=97&&i<=122||46===i||43===i||45===i)){if(r)throw new e(`type "${t}" contains an illegal character`);return!1}}return!0},validateVersion:function(e,t){return o("version",e,t)}},validate$2}function requirePurlComponent(){if(hasRequiredPurlComponent)return purlComponent;hasRequiredPurlComponent=1
846
+ normalizeSubpath:function(e){return"string"==typeof e?r(e,n):void 0},normalizeType:function(e){return"string"==typeof e?e.trim().toLowerCase():void 0},normalizeVersion:function(e){return"string"==typeof e?e.trim():void 0}}}function requireLang(){if(hasRequiredLang)return lang;return hasRequiredLang=1,lang={isNullishOrEmptyString:function(e){return null==e||"string"==typeof e&&0===e.length}}}function requireValidate$1(){if(hasRequiredValidate$1)return validate$3;hasRequiredValidate$1=1;const{PurlError:e}=requireError$1(),{isNullishOrEmptyString:t}=requireLang(),{isNonEmptyString:r}=requireStrings();function n(t,r){if(!s("qualifier",t,r))return!1;for(let n=0,{length:i}=t;n<i;n+=1){const i=t.charCodeAt(n);if(!(i>=48&&i<=57||i>=65&&i<=90||i>=97&&i<=122||46===i||45===i||95===i)){if(r)throw new e(`qualifier "${t}" contains an illegal character`);return!1}}return!0}function i(r,n,i){if(t(n)){if(i)throw new e(`"${r}" is a required component`);return!1}return!0}function s(t,n,i){if(r(n)){
847
+ const r=n.charCodeAt(0);if(r>=48&&r<=57){if(i)throw new e(`${t} "${n}" cannot start with a number`);return!1}}return!0}function o(t,r,n){if(null==r||"string"==typeof r)return!0;if(n)throw new e(`"'${t}" must be a string`);return!1}return validate$3={validateEmptyByType:function(r,n,i,s){if(!t(i)){if(s)throw new e(`${r} "${n}" component must be empty`);return!1}return!0},validateName:function(e,t){return i("name",e,t)&&o("name",e,t)},validateNamespace:function(e,t){return o("namespace",e,t)},validateQualifiers:function(t,r){if(null==t)return!0;if("object"!=typeof t){if(r)throw new e('"qualifiers" must be an object');return!1}const i="function"==typeof t.keys?t.keys():Object.keys(t);for(const e of i)if(!n(e,r))return!1;return!0},validateQualifierKey:n,validateRequired:i,validateRequiredByType:function(r,n,i,s){if(t(i)){if(s)throw new e(`${r} requires a "${n}" component`);return!1}return!0},validateStartsWithoutNumber:s,validateStrings:o,validateSubpath:function(e,t){
848
+ return o("subpath",e,t)},validateType:function(t,r){if(!i("type",t,r)||!o("type",t,r)||!s("type",t,r))return!1;for(let n=0,{length:i}=t;n<i;n+=1){const i=t.charCodeAt(n);if(!(i>=48&&i<=57||i>=65&&i<=90||i>=97&&i<=122||46===i||43===i||45===i)){if(r)throw new e(`type "${t}" contains an illegal character`);return!1}}return!0},validateVersion:function(e,t){return o("version",e,t)}},validate$3}function requirePurlComponent(){if(hasRequiredPurlComponent)return purlComponent;hasRequiredPurlComponent=1
849
849
  ;const{encodeNamespace:e,encodeVersion:t,encodeQualifiers:r,encodeQualifierParam:n,encodeSubpath:i,encodeURIComponent:s}=requireEncode$1(),{createHelpersNamespaceObject:o}=requireHelpers$1(),{normalizeType:a,normalizeNamespace:c,normalizeName:u,normalizeVersion:l,normalizeQualifiers:d,normalizeSubpath:p}=requireNormalize(),{localeCompare:h,isNonEmptyString:A}=requireStrings(),{validateType:f,validateNamespace:g,validateName:m,validateVersion:y,validateQualifiers:E,validateQualifierKey:b,validateSubpath:C}=requireValidate$1(),v={__proto__:null,type:0,namespace:1,name:2,version:3,qualifiers:4,qualifierKey:5,qualifierValue:6,subpath:7};function I(e){return v[e]??e}return purlComponent={PurlComponent:o({encode:{namespace:e,version:t,qualifiers:r,qualifierKey:n,qualifierValue:n,subpath:i},normalize:{type:a,namespace:c,name:u,version:l,qualifiers:d,subpath:p},validate:{type:f,namespace:g,name:m,version:y,qualifierKey:b,qualifiers:E,subpath:C}},{comparator:function(e,t){return h(I(e),I(t))},
850
850
  encode:e=>A(e)?s(e):"",normalize:e=>"string"==typeof e?e:void 0,validate:(e,t)=>!0})}}function requirePurlQualifierNames(){return hasRequiredPurlQualifierNames?purlQualifierNames:(hasRequiredPurlQualifierNames=1,purlQualifierNames={PurlQualifierNames:{__proto__:null,RepositoryUrl:"repository_url",DownloadUrl:"download_url",VcsUrl:"vcs_url",FileName:"file_name",Checksum:"checksum"}})}function requirePurlType(){if(hasRequiredPurlType)return purlType;hasRequiredPurlType=1;const{isNullishOrEmptyString:e}=requireLang(),{createHelpersNamespaceObject:t}=requireHelpers$1(),{isSemverString:r,lowerName:n,lowerNamespace:i,lowerVersion:s,replaceDashesWithUnderscores:o,replaceUnderscoresWithDashes:a}=requireStrings(),{validateEmptyByType:c,validateRequiredByType:u}=requireValidate$1(),{PurlError:l}=requireError$1();return purlType={PurlType:t({normalize:{alpm:e=>(i(e),n(e),e),apk:e=>(i(e),n(e),e),bitbucket:e=>(i(e),n(e),e),bitnami:e=>(n(e),e),composer:e=>(i(e),n(e),e),deb:e=>(i(e),n(e),e),
851
851
  gitlab:e=>(i(e),n(e),e),github:e=>(i(e),n(e),e),hex:e=>(i(e),n(e),e),huggingface:e=>(s(e),e),mlflow:e=>(e.qualifiers?.repository_url?.includes("databricks")&&n(e),e),npm:e=>(i(e),n(e),e),luarocks:e=>(s(e),e),oci:e=>(n(e),e),pub:e=>(n(e),e.name=o(e.name),e),pypi:e=>(i(e),n(e),e.name=a(e.name),e),qpkg:e=>(i(e),e),rpm:e=>(i(e),e)},validate:{conan(t,r){if(e(t.namespace)){if(t.qualifiers?.channel){if(r)throw new l('conan requires a "namespace" component when a "channel" qualifier is present');return!1}}else if(e(t.qualifiers)){if(r)throw new l('conan requires a "qualifiers" component when a namespace is present');return!1}return!0},cran:(e,t)=>u("cran","version",e.version,t),golang(e){const{version:t}=e;if(("string"==typeof t?t.length:0)&&118===t.charCodeAt(0)&&!r(t.slice(1))){if(throws)throw new l('golang "version" component starting with a "v" must be followed by a valid semver version');return!1}return!0},maven:(e,t)=>u("maven","namespace",e.namespace,t),
852
852
  mlflow:(e,t)=>c("mlflow","namespace",e.namespace,t),oci:(e,t)=>c("oci","namespace",e.namespace,t),pub(e,t){const{name:r}=e;for(let e=0,{length:n}=r;e<n;e+=1){const n=r.charCodeAt(e);if(!(n>=48&&n<=57||n>=97&&n<=122||95===n)){if(t)throw new l('pub "name" component may only contain [a-z0-9_] characters');return!1}}return!0},swift:(e,t)=>u("swift","namespace",e.namespace,t)&&u("swift","version",e.version,t)}},{normalize:e=>e,validate:(e,t)=>!0})},purlType}function requirePackageUrl(){if(hasRequiredPackageUrl)return packageUrl;hasRequiredPackageUrl=1;const{decodePurlComponent:e}=requireDecode$1(),{isObject:t,recursiveFreeze:r}=requireObjects(),{isBlank:n,isNonEmptyString:i,trimLeadingSlashes:s}=requireStrings(),{PurlComponent:o}=requirePurlComponent(),{PurlQualifierNames:a}=requirePurlQualifierNames(),{PurlType:c}=requirePurlType(),{PurlError:u}=requireError$1();class l{static Component=r(o);static KnownQualifierNames=r(a);static Type=r(c);constructor(e,r,n,s,a,u){
853
853
  const l=i(e)?o.type.normalize(e):e;o.type.validate(l,!0);const d=i(r)?o.namespace.normalize(r):r;o.namespace.validate(d,!0);const p=i(n)?o.name.normalize(n):n;o.name.validate(p,!0);const h=i(s)?o.version.normalize(s):s;o.version.validate(h,!0);const A="string"==typeof a||t(a)?o.qualifiers.normalize(a):a;o.qualifiers.validate(A,!0);const f=i(u)?o.subpath.normalize(u):u;o.subpath.validate(f,!0),this.type=l,this.name=p,this.namespace=d??void 0,this.version=h??void 0,this.qualifiers=A??void 0,this.subpath=f??void 0;const g=c[l];g&&(g.normalize(this),g.validate(this,!0))}toString(){const{namespace:e,name:t,version:r,qualifiers:n,subpath:i,type:s}=this;let a=`pkg:${o.type.encode(s)}/`;return e&&(a=`${a}${o.namespace.encode(e)}/`),a=`${a}${o.name.encode(t)}`,r&&(a=`${a}@${o.version.encode(r)}`),n&&(a=`${a}?${o.qualifiers.encode(n)}`),i&&(a=`${a}#${o.subpath.encode(i)}`),a}static fromString(e){return new l(...l.parseString(e))}static parseString(t){
854
854
  if("string"!=typeof t)throw new Error("A purl string argument is required.");if(n(t))return[void 0,void 0,void 0,void 0,void 0,void 0];const r=t.indexOf(":");let i,o;if(-1!==r)try{const e=t.slice(0,r),n=t.slice(r+1),a=s(n);i=new URL(`${e}:${a}`),o=n.length===a.length?i:new URL(t)}catch(e){throw new u("failed to parse as URL",{cause:e})}if("pkg:"!==i?.protocol)throw new u('missing required "pkg" scheme component');if(""!==o.username||""!==o.password)throw new u('cannot contain a "user:pass@host:port"');const{pathname:a}=i,c=a.indexOf("/"),l=e("type",-1===c?a:a.slice(0,c));if(c<1)return[l,void 0,void 0,void 0,void 0,void 0];let d,p=a.lastIndexOf("@");-1!==p&&47===a.charCodeAt(p-1)&&(p=-1);const h=a.slice(l.length+1,-1===p?a.length:p);let A,f;-1!==p&&(d=e("version",a.slice(p+1)));const g=h.lastIndexOf("/");let m;-1===g?f=e("name",h):(f=e("name",h.slice(g+1)),A=e("namespace",h.slice(0,g)));const{searchParams:y}=i;let E;0!==y.size&&(y.forEach(t=>e("qualifiers",t)),m=y);const{hash:b}=i
855
- ;return 0!==b.length&&(E=e("subpath",b.slice(1))),[l,A,f,d,m,E]}}for(const e of["Component","KnownQualifierNames","Type"])Reflect.defineProperty(l,e,{...Reflect.getOwnPropertyDescriptor(l,e),writable:!1});return Reflect.setPrototypeOf(l.prototype,null),packageUrl={PackageURL:l,PurlComponent:o,PurlQualifierNames:a,PurlType:c}}function requirePackageurlJs(){if(hasRequiredPackageurlJs)return packageurlJs;hasRequiredPackageurlJs=1;const{PackageURL:e,PurlComponent:t,PurlQualifierNames:r,PurlType:n}=requirePackageUrl();return packageurlJs={PackageURL:e,PurlComponent:t,PurlQualifierNames:r,PurlType:n}}var packageurlJsExports=requirePackageurlJs(),util$b,objectUtil$1;!function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),n={};for(const e of r)n[e]=t[e];return e.objectValues(n)},
856
- e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(const r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(util$b||(util$b={})),(objectUtil$1||(objectUtil$1={})).mergeShapes=(e,t)=>({...e,...t});const ZodParsedType$1=util$b.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType$1=e=>{switch(typeof e){case"undefined":return ZodParsedType$1.undefined;case"string":return ZodParsedType$1.string
855
+ ;return 0!==b.length&&(E=e("subpath",b.slice(1))),[l,A,f,d,m,E]}}for(const e of["Component","KnownQualifierNames","Type"])Reflect.defineProperty(l,e,{...Reflect.getOwnPropertyDescriptor(l,e),writable:!1});return Reflect.setPrototypeOf(l.prototype,null),packageUrl={PackageURL:l,PurlComponent:o,PurlQualifierNames:a,PurlType:c}}function requirePackageurlJs(){if(hasRequiredPackageurlJs)return packageurlJs;hasRequiredPackageurlJs=1;const{PackageURL:e,PurlComponent:t,PurlQualifierNames:r,PurlType:n}=requirePackageUrl();return packageurlJs={PackageURL:e,PurlComponent:t,PurlQualifierNames:r,PurlType:n}}var packageurlJsExports=requirePackageurlJs(),util$a,objectUtil$1;!function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),n={};for(const e of r)n[e]=t[e];return e.objectValues(n)},
856
+ e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(const r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(util$a||(util$a={})),(objectUtil$1||(objectUtil$1={})).mergeShapes=(e,t)=>({...e,...t});const ZodParsedType$1=util$a.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType$1=e=>{switch(typeof e){case"undefined":return ZodParsedType$1.undefined;case"string":return ZodParsedType$1.string
857
857
  ;case"number":return Number.isNaN(e)?ZodParsedType$1.nan:ZodParsedType$1.number;case"boolean":return ZodParsedType$1.boolean;case"function":return ZodParsedType$1.function;case"bigint":return ZodParsedType$1.bigint;case"symbol":return ZodParsedType$1.symbol;case"object":return Array.isArray(e)?ZodParsedType$1.array:null===e?ZodParsedType$1.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?ZodParsedType$1.promise:"undefined"!=typeof Map&&e instanceof Map?ZodParsedType$1.map:"undefined"!=typeof Set&&e instanceof Set?ZodParsedType$1.set:"undefined"!=typeof Date&&e instanceof Date?ZodParsedType$1.date:ZodParsedType$1.object;default:return ZodParsedType$1.unknown}
858
- },ZodIssueCode$1=util$b.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),quotelessJson=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");let ZodError$2=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},n=e=>{
859
- for(const i of e.issues)if("invalid_union"===i.code)i.unionErrors.map(n);else if("invalid_return_type"===i.code)n(i.returnTypeError);else if("invalid_arguments"===i.code)n(i.argumentsError);else if(0===i.path.length)r._errors.push(t(i));else{let e=r,n=0;for(;n<i.path.length;){const r=i.path[n];n===i.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(i))):e[r]=e[r]||{_errors:[]},e=e[r],n++}}};return n(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util$b.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const n of this.issues)if(n.path.length>0){const r=n.path[0];t[r]=t[r]||[],t[r].push(e(n))}else r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}};ZodError$2.create=e=>new ZodError$2(e);const errorMap$1=(e,t)=>{let r;switch(e.code){case ZodIssueCode$1.invalid_type:
860
- r=e.received===ZodParsedType$1.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case ZodIssueCode$1.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,util$b.jsonStringifyReplacer)}`;break;case ZodIssueCode$1.unrecognized_keys:r=`Unrecognized key(s) in object: ${util$b.joinValues(e.keys,", ")}`;break;case ZodIssueCode$1.invalid_union:r="Invalid input";break;case ZodIssueCode$1.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${util$b.joinValues(e.options)}`;break;case ZodIssueCode$1.invalid_enum_value:r=`Invalid enum value. Expected ${util$b.joinValues(e.options)}, received '${e.received}'`;break;case ZodIssueCode$1.invalid_arguments:r="Invalid function arguments";break;case ZodIssueCode$1.invalid_return_type:r="Invalid function return type";break;case ZodIssueCode$1.invalid_date:r="Invalid date";break;case ZodIssueCode$1.invalid_string:
861
- "object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:util$b.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case ZodIssueCode$1.too_small:
858
+ },ZodIssueCode$1=util$a.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),quotelessJson=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");let ZodError$2=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},n=e=>{
859
+ for(const i of e.issues)if("invalid_union"===i.code)i.unionErrors.map(n);else if("invalid_return_type"===i.code)n(i.returnTypeError);else if("invalid_arguments"===i.code)n(i.argumentsError);else if(0===i.path.length)r._errors.push(t(i));else{let e=r,n=0;for(;n<i.path.length;){const r=i.path[n];n===i.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(i))):e[r]=e[r]||{_errors:[]},e=e[r],n++}}};return n(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util$a.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const n of this.issues)if(n.path.length>0){const r=n.path[0];t[r]=t[r]||[],t[r].push(e(n))}else r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}};ZodError$2.create=e=>new ZodError$2(e);const errorMap$1=(e,t)=>{let r;switch(e.code){case ZodIssueCode$1.invalid_type:
860
+ r=e.received===ZodParsedType$1.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case ZodIssueCode$1.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,util$a.jsonStringifyReplacer)}`;break;case ZodIssueCode$1.unrecognized_keys:r=`Unrecognized key(s) in object: ${util$a.joinValues(e.keys,", ")}`;break;case ZodIssueCode$1.invalid_union:r="Invalid input";break;case ZodIssueCode$1.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${util$a.joinValues(e.options)}`;break;case ZodIssueCode$1.invalid_enum_value:r=`Invalid enum value. Expected ${util$a.joinValues(e.options)}, received '${e.received}'`;break;case ZodIssueCode$1.invalid_arguments:r="Invalid function arguments";break;case ZodIssueCode$1.invalid_return_type:r="Invalid function return type";break;case ZodIssueCode$1.invalid_date:r="Invalid date";break;case ZodIssueCode$1.invalid_string:
861
+ "object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:util$a.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case ZodIssueCode$1.too_small:
862
862
  r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case ZodIssueCode$1.too_big:
863
- r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case ZodIssueCode$1.custom:r="Invalid input";break;case ZodIssueCode$1.invalid_intersection_types:r="Intersection results could not be merged";break;case ZodIssueCode$1.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case ZodIssueCode$1.not_finite:r="Number must be finite";break;default:r=t.defaultError,util$b.assertNever(e)}return{message:r}}
863
+ r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case ZodIssueCode$1.custom:r="Invalid input";break;case ZodIssueCode$1.invalid_intersection_types:r="Intersection results could not be merged";break;case ZodIssueCode$1.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case ZodIssueCode$1.not_finite:r="Number must be finite";break;default:r=t.defaultError,util$a.assertNever(e)}return{message:r}}
864
864
  ;let overrideErrorMap$1=errorMap$1;function setErrorMap(e){overrideErrorMap$1=e}function getErrorMap$1(){return overrideErrorMap$1}const makeIssue$1=e=>{const{data:t,path:r,errorMaps:n,issueData:i}=e,s=[...r,...i.path||[]],o={...i,path:s};if(void 0!==i.message)return{...i,path:s,message:i.message};let a="";const c=n.filter(e=>!!e).slice().reverse();for(const e of c)a=e(o,{data:t,defaultError:a}).message;return{...i,path:s,message:a}},EMPTY_PATH=[];function addIssueToContext$1(e,t){const r=getErrorMap$1(),n=makeIssue$1({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===errorMap$1?void 0:errorMap$1].filter(e=>!!e)});e.common.issues.push(n)}let ParseStatus$1=class e{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const n of t){if("aborted"===n.status)return INVALID$1;"dirty"===n.status&&e.dirty(),r.push(n.value)}
865
865
  return{status:e.value,value:r}}static async mergeObjectAsync(t,r){const n=[];for(const e of r){const t=await e.key,r=await e.value;n.push({key:t,value:r})}return e.mergeObjectSync(t,n)}static mergeObjectSync(e,t){const r={};for(const n of t){const{key:t,value:i}=n;if("aborted"===t.status)return INVALID$1;if("aborted"===i.status)return INVALID$1;"dirty"===t.status&&e.dirty(),"dirty"===i.status&&e.dirty(),"__proto__"===t.value||void 0===i.value&&!n.alwaysSet||(r[t.value]=i.value)}return{status:e.value,value:r}}};const INVALID$1=Object.freeze({status:"aborted"}),DIRTY$1=e=>({status:"dirty",value:e}),OK$1=e=>({status:"valid",value:e}),isAborted$1=e=>"aborted"===e.status,isDirty$1=e=>"dirty"===e.status,isValid$1=e=>"valid"===e.status,isAsync$1=e=>"undefined"!=typeof Promise&&e instanceof Promise;var errorUtil$2;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(errorUtil$2||(errorUtil$2={}));let ParseInputLazyPath$1=class{
866
866
  constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const handleResult$2=(e,t)=>{if(isValid$1(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new ZodError$2(e.common.issues);return this._error=t,this._error}}};function processCreateParams$1(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:i}=e;if(t&&(r||n))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:i};return{errorMap:(t,i)=>{const{message:s}=e;return"invalid_enum_value"===t.code?{message:s??i.defaultError}:void 0===i.data?{
@@ -877,33 +877,33 @@ i?addIssueToContext$1(r,{code:ZodIssueCode$1.too_big,maximum:n.value,type:"strin
877
877
  validation:"nanoid",code:ZodIssueCode$1.invalid_string,message:n.message}),t.dirty());else if("cuid"===n.kind)cuidRegex$1.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext$1(r,{validation:"cuid",code:ZodIssueCode$1.invalid_string,message:n.message}),t.dirty());else if("cuid2"===n.kind)cuid2Regex$1.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext$1(r,{validation:"cuid2",code:ZodIssueCode$1.invalid_string,message:n.message}),t.dirty());else if("ulid"===n.kind)ulidRegex$1.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext$1(r,{validation:"ulid",code:ZodIssueCode$1.invalid_string,message:n.message}),t.dirty());else if("url"===n.kind)try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),addIssueToContext$1(r,{validation:"url",code:ZodIssueCode$1.invalid_string,message:n.message}),t.dirty()}else if("regex"===n.kind){n.regex.lastIndex=0;n.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext$1(r,{validation:"regex",
878
878
  code:ZodIssueCode$1.invalid_string,message:n.message}),t.dirty())}else if("trim"===n.kind)e.data=e.data.trim();else if("includes"===n.kind)e.data.includes(n.value,n.position)||(r=this._getOrReturnCtx(e,r),addIssueToContext$1(r,{code:ZodIssueCode$1.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),t.dirty());else if("toLowerCase"===n.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===n.kind)e.data=e.data.toUpperCase();else if("startsWith"===n.kind)e.data.startsWith(n.value)||(r=this._getOrReturnCtx(e,r),addIssueToContext$1(r,{code:ZodIssueCode$1.invalid_string,validation:{startsWith:n.value},message:n.message}),t.dirty());else if("endsWith"===n.kind)e.data.endsWith(n.value)||(r=this._getOrReturnCtx(e,r),addIssueToContext$1(r,{code:ZodIssueCode$1.invalid_string,validation:{endsWith:n.value},message:n.message}),t.dirty());else if("datetime"===n.kind){datetimeRegex$1(n).test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext$1(r,{
879
879
  code:ZodIssueCode$1.invalid_string,validation:"datetime",message:n.message}),t.dirty())}else if("date"===n.kind){dateRegex$1.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext$1(r,{code:ZodIssueCode$1.invalid_string,validation:"date",message:n.message}),t.dirty())}else if("time"===n.kind){timeRegex$1(n).test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext$1(r,{code:ZodIssueCode$1.invalid_string,validation:"time",message:n.message}),t.dirty())}else"duration"===n.kind?durationRegex$1.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext$1(r,{validation:"duration",code:ZodIssueCode$1.invalid_string,message:n.message}),t.dirty()):"ip"===n.kind?isValidIP$1(e.data,n.version)||(r=this._getOrReturnCtx(e,r),addIssueToContext$1(r,{validation:"ip",code:ZodIssueCode$1.invalid_string,message:n.message}),t.dirty()):"jwt"===n.kind?isValidJWT$2(e.data,n.alg)||(r=this._getOrReturnCtx(e,r),addIssueToContext$1(r,{validation:"jwt",code:ZodIssueCode$1.invalid_string,
880
- message:n.message}),t.dirty()):"cidr"===n.kind?isValidCidr$1(e.data,n.version)||(r=this._getOrReturnCtx(e,r),addIssueToContext$1(r,{validation:"cidr",code:ZodIssueCode$1.invalid_string,message:n.message}),t.dirty()):"base64"===n.kind?base64Regex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext$1(r,{validation:"base64",code:ZodIssueCode$1.invalid_string,message:n.message}),t.dirty()):"base64url"===n.kind?base64urlRegex$1.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext$1(r,{validation:"base64url",code:ZodIssueCode$1.invalid_string,message:n.message}),t.dirty()):util$b.assertNever(n);return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:ZodIssueCode$1.invalid_string,...errorUtil$2.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:"email",...errorUtil$2.errToObj(e)})}url(e){return this._addCheck({kind:"url",...errorUtil$2.errToObj(e)})}
880
+ message:n.message}),t.dirty()):"cidr"===n.kind?isValidCidr$1(e.data,n.version)||(r=this._getOrReturnCtx(e,r),addIssueToContext$1(r,{validation:"cidr",code:ZodIssueCode$1.invalid_string,message:n.message}),t.dirty()):"base64"===n.kind?base64Regex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext$1(r,{validation:"base64",code:ZodIssueCode$1.invalid_string,message:n.message}),t.dirty()):"base64url"===n.kind?base64urlRegex$1.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext$1(r,{validation:"base64url",code:ZodIssueCode$1.invalid_string,message:n.message}),t.dirty()):util$a.assertNever(n);return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:ZodIssueCode$1.invalid_string,...errorUtil$2.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:"email",...errorUtil$2.errToObj(e)})}url(e){return this._addCheck({kind:"url",...errorUtil$2.errToObj(e)})}
881
881
  emoji(e){return this._addCheck({kind:"emoji",...errorUtil$2.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...errorUtil$2.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...errorUtil$2.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...errorUtil$2.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...errorUtil$2.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...errorUtil$2.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...errorUtil$2.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...errorUtil$2.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...errorUtil$2.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...errorUtil$2.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...errorUtil$2.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",
882
882
  precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...errorUtil$2.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...errorUtil$2.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...errorUtil$2.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...errorUtil$2.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...errorUtil$2.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...errorUtil$2.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...errorUtil$2.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...errorUtil$2.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,
883
883
  ...errorUtil$2.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...errorUtil$2.errToObj(t)})}nonempty(e){return this.min(1,errorUtil$2.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){
884
884
  return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}};function floatSafeRemainder$1(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n;return Number.parseInt(e.toFixed(i).replace(".",""))%Number.parseInt(t.toFixed(i).replace(".",""))/10**i}
885
- ZodString$2.create=e=>new ZodString$2({checks:[],typeName:ZodFirstPartyTypeKind$1.ZodString,coerce:e?.coerce??!1,...processCreateParams$1(e)});let ZodNumber$1=class e extends ZodType$2{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==ZodParsedType$1.number){const t=this._getOrReturnCtx(e);return addIssueToContext$1(t,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType$1.number,received:t.parsedType}),INVALID$1}let t;const r=new ParseStatus$1;for(const n of this._def.checks)if("int"===n.kind)util$b.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),addIssueToContext$1(t,{code:ZodIssueCode$1.invalid_type,expected:"integer",received:"float",message:n.message}),r.dirty());else if("min"===n.kind){(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext$1(t,{code:ZodIssueCode$1.too_small,minimum:n.value,type:"number",
886
- inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty())}else if("max"===n.kind){(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext$1(t,{code:ZodIssueCode$1.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty())}else"multipleOf"===n.kind?0!==floatSafeRemainder$1(e.data,n.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext$1(t,{code:ZodIssueCode$1.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):"finite"===n.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),addIssueToContext$1(t,{code:ZodIssueCode$1.not_finite,message:n.message}),r.dirty()):util$b.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,errorUtil$2.toString(t))}gt(e,t){return this.setLimit("min",e,!1,errorUtil$2.toString(t))}lte(e,t){return this.setLimit("max",e,!0,errorUtil$2.toString(t))}lt(e,t){return this.setLimit("max",e,!1,errorUtil$2.toString(t))}
885
+ ZodString$2.create=e=>new ZodString$2({checks:[],typeName:ZodFirstPartyTypeKind$1.ZodString,coerce:e?.coerce??!1,...processCreateParams$1(e)});let ZodNumber$1=class e extends ZodType$2{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==ZodParsedType$1.number){const t=this._getOrReturnCtx(e);return addIssueToContext$1(t,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType$1.number,received:t.parsedType}),INVALID$1}let t;const r=new ParseStatus$1;for(const n of this._def.checks)if("int"===n.kind)util$a.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),addIssueToContext$1(t,{code:ZodIssueCode$1.invalid_type,expected:"integer",received:"float",message:n.message}),r.dirty());else if("min"===n.kind){(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext$1(t,{code:ZodIssueCode$1.too_small,minimum:n.value,type:"number",
886
+ inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty())}else if("max"===n.kind){(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext$1(t,{code:ZodIssueCode$1.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty())}else"multipleOf"===n.kind?0!==floatSafeRemainder$1(e.data,n.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext$1(t,{code:ZodIssueCode$1.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):"finite"===n.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),addIssueToContext$1(t,{code:ZodIssueCode$1.not_finite,message:n.message}),r.dirty()):util$a.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,errorUtil$2.toString(t))}gt(e,t){return this.setLimit("min",e,!1,errorUtil$2.toString(t))}lte(e,t){return this.setLimit("max",e,!0,errorUtil$2.toString(t))}lt(e,t){return this.setLimit("max",e,!1,errorUtil$2.toString(t))}
887
887
  setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:errorUtil$2.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:"int",message:errorUtil$2.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil$2.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil$2.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil$2.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil$2.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil$2.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:errorUtil$2.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil$2.toString(e)
888
- })._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil$2.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&util$b.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}};ZodNumber$1.create=e=>new ZodNumber$1({checks:[],typeName:ZodFirstPartyTypeKind$1.ZodNumber,coerce:e?.coerce||!1,...processCreateParams$1(e)});let ZodBigInt$1=class e extends ZodType$2{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){
889
- if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ZodParsedType$1.bigint)return this._getInvalidInput(e);let t;const r=new ParseStatus$1;for(const n of this._def.checks)if("min"===n.kind){(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext$1(t,{code:ZodIssueCode$1.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty())}else if("max"===n.kind){(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext$1(t,{code:ZodIssueCode$1.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty())}else"multipleOf"===n.kind?e.data%n.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),addIssueToContext$1(t,{code:ZodIssueCode$1.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):util$b.assertNever(n);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e)
888
+ })._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil$2.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&util$a.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}};ZodNumber$1.create=e=>new ZodNumber$1({checks:[],typeName:ZodFirstPartyTypeKind$1.ZodNumber,coerce:e?.coerce||!1,...processCreateParams$1(e)});let ZodBigInt$1=class e extends ZodType$2{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){
889
+ if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ZodParsedType$1.bigint)return this._getInvalidInput(e);let t;const r=new ParseStatus$1;for(const n of this._def.checks)if("min"===n.kind){(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext$1(t,{code:ZodIssueCode$1.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty())}else if("max"===n.kind){(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext$1(t,{code:ZodIssueCode$1.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty())}else"multipleOf"===n.kind?e.data%n.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),addIssueToContext$1(t,{code:ZodIssueCode$1.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):util$a.assertNever(n);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e)
890
890
  ;return addIssueToContext$1(t,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType$1.bigint,received:t.parsedType}),INVALID$1}gte(e,t){return this.setLimit("min",e,!0,errorUtil$2.toString(t))}gt(e,t){return this.setLimit("min",e,!1,errorUtil$2.toString(t))}lte(e,t){return this.setLimit("max",e,!0,errorUtil$2.toString(t))}lt(e,t){return this.setLimit("max",e,!1,errorUtil$2.toString(t))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:errorUtil$2.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil$2.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil$2.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil$2.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),
891
891
  inclusive:!0,message:errorUtil$2.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil$2.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}};ZodBigInt$1.create=e=>new ZodBigInt$1({checks:[],typeName:ZodFirstPartyTypeKind$1.ZodBigInt,coerce:e?.coerce??!1,...processCreateParams$1(e)});let ZodBoolean$1=class extends ZodType$2{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==ZodParsedType$1.boolean){const t=this._getOrReturnCtx(e);return addIssueToContext$1(t,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType$1.boolean,received:t.parsedType}),INVALID$1}return OK$1(e.data)}};ZodBoolean$1.create=e=>new ZodBoolean$1({typeName:ZodFirstPartyTypeKind$1.ZodBoolean,coerce:e?.coerce||!1,...processCreateParams$1(e)})
892
- ;let ZodDate$1=class e extends ZodType$2{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==ZodParsedType$1.date){const t=this._getOrReturnCtx(e);return addIssueToContext$1(t,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType$1.date,received:t.parsedType}),INVALID$1}if(Number.isNaN(e.data.getTime())){return addIssueToContext$1(this._getOrReturnCtx(e),{code:ZodIssueCode$1.invalid_date}),INVALID$1}const t=new ParseStatus$1;let r;for(const n of this._def.checks)"min"===n.kind?e.data.getTime()<n.value&&(r=this._getOrReturnCtx(e,r),addIssueToContext$1(r,{code:ZodIssueCode$1.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),t.dirty()):"max"===n.kind?e.data.getTime()>n.value&&(r=this._getOrReturnCtx(e,r),addIssueToContext$1(r,{code:ZodIssueCode$1.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),t.dirty()):util$b.assertNever(n);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){
892
+ ;let ZodDate$1=class e extends ZodType$2{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==ZodParsedType$1.date){const t=this._getOrReturnCtx(e);return addIssueToContext$1(t,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType$1.date,received:t.parsedType}),INVALID$1}if(Number.isNaN(e.data.getTime())){return addIssueToContext$1(this._getOrReturnCtx(e),{code:ZodIssueCode$1.invalid_date}),INVALID$1}const t=new ParseStatus$1;let r;for(const n of this._def.checks)"min"===n.kind?e.data.getTime()<n.value&&(r=this._getOrReturnCtx(e,r),addIssueToContext$1(r,{code:ZodIssueCode$1.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),t.dirty()):"max"===n.kind?e.data.getTime()>n.value&&(r=this._getOrReturnCtx(e,r),addIssueToContext$1(r,{code:ZodIssueCode$1.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),t.dirty()):util$a.assertNever(n);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){
893
893
  return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:errorUtil$2.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:errorUtil$2.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}};ZodDate$1.create=e=>new ZodDate$1({checks:[],coerce:e?.coerce||!1,typeName:ZodFirstPartyTypeKind$1.ZodDate,...processCreateParams$1(e)});let ZodSymbol$1=class extends ZodType$2{_parse(e){if(this._getType(e)!==ZodParsedType$1.symbol){const t=this._getOrReturnCtx(e);return addIssueToContext$1(t,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType$1.symbol,received:t.parsedType}),INVALID$1}return OK$1(e.data)}};ZodSymbol$1.create=e=>new ZodSymbol$1({
894
894
  typeName:ZodFirstPartyTypeKind$1.ZodSymbol,...processCreateParams$1(e)});let ZodUndefined$1=class extends ZodType$2{_parse(e){if(this._getType(e)!==ZodParsedType$1.undefined){const t=this._getOrReturnCtx(e);return addIssueToContext$1(t,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType$1.undefined,received:t.parsedType}),INVALID$1}return OK$1(e.data)}};ZodUndefined$1.create=e=>new ZodUndefined$1({typeName:ZodFirstPartyTypeKind$1.ZodUndefined,...processCreateParams$1(e)});let ZodNull$1=class extends ZodType$2{_parse(e){if(this._getType(e)!==ZodParsedType$1.null){const t=this._getOrReturnCtx(e);return addIssueToContext$1(t,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType$1.null,received:t.parsedType}),INVALID$1}return OK$1(e.data)}};ZodNull$1.create=e=>new ZodNull$1({typeName:ZodFirstPartyTypeKind$1.ZodNull,...processCreateParams$1(e)});let ZodAny$1=class extends ZodType$2{constructor(){super(...arguments),this._any=!0}_parse(e){return OK$1(e.data)}}
895
895
  ;ZodAny$1.create=e=>new ZodAny$1({typeName:ZodFirstPartyTypeKind$1.ZodAny,...processCreateParams$1(e)});let ZodUnknown$2=class extends ZodType$2{constructor(){super(...arguments),this._unknown=!0}_parse(e){return OK$1(e.data)}};ZodUnknown$2.create=e=>new ZodUnknown$2({typeName:ZodFirstPartyTypeKind$1.ZodUnknown,...processCreateParams$1(e)});let ZodNever$2=class extends ZodType$2{_parse(e){const t=this._getOrReturnCtx(e);return addIssueToContext$1(t,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType$1.never,received:t.parsedType}),INVALID$1}};ZodNever$2.create=e=>new ZodNever$2({typeName:ZodFirstPartyTypeKind$1.ZodNever,...processCreateParams$1(e)});let ZodVoid$1=class extends ZodType$2{_parse(e){if(this._getType(e)!==ZodParsedType$1.undefined){const t=this._getOrReturnCtx(e);return addIssueToContext$1(t,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType$1.void,received:t.parsedType}),INVALID$1}return OK$1(e.data)}};ZodVoid$1.create=e=>new ZodVoid$1({
896
896
  typeName:ZodFirstPartyTypeKind$1.ZodVoid,...processCreateParams$1(e)});let ZodArray$2=class e extends ZodType$2{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==ZodParsedType$1.array)return addIssueToContext$1(t,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType$1.array,received:t.parsedType}),INVALID$1;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,i=t.data.length<n.exactLength.value;(e||i)&&(addIssueToContext$1(t,{code:e?ZodIssueCode$1.too_big:ZodIssueCode$1.too_small,minimum:i?n.exactLength.value:void 0,maximum:e?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(null!==n.minLength&&t.data.length<n.minLength.value&&(addIssueToContext$1(t,{code:ZodIssueCode$1.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),null!==n.maxLength&&t.data.length>n.maxLength.value&&(addIssueToContext$1(t,{
897
897
  code:ZodIssueCode$1.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>n.type._parseAsync(new ParseInputLazyPath$1(t,e,t.path,r)))).then(e=>ParseStatus$1.mergeArray(r,e));const i=[...t.data].map((e,r)=>n.type._parseSync(new ParseInputLazyPath$1(t,e,t.path,r)));return ParseStatus$1.mergeArray(r,i)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:errorUtil$2.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:errorUtil$2.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:errorUtil$2.toString(r)}})}nonempty(e){return this.min(1,e)}};function deepPartialify$1(e){if(e instanceof ZodObject$2){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=ZodOptional$2.create(deepPartialify$1(n))}return new ZodObject$2({...e._def,shape:()=>t})}
898
- return e instanceof ZodArray$2?new ZodArray$2({...e._def,type:deepPartialify$1(e.element)}):e instanceof ZodOptional$2?ZodOptional$2.create(deepPartialify$1(e.unwrap())):e instanceof ZodNullable$2?ZodNullable$2.create(deepPartialify$1(e.unwrap())):e instanceof ZodTuple$1?ZodTuple$1.create(e.items.map(e=>deepPartialify$1(e))):e}ZodArray$2.create=(e,t)=>new ZodArray$2({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind$1.ZodArray,...processCreateParams$1(t)});let ZodObject$2=class e extends ZodType$2{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=util$b.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==ZodParsedType$1.object){const t=this._getOrReturnCtx(e);return addIssueToContext$1(t,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType$1.object,
898
+ return e instanceof ZodArray$2?new ZodArray$2({...e._def,type:deepPartialify$1(e.element)}):e instanceof ZodOptional$2?ZodOptional$2.create(deepPartialify$1(e.unwrap())):e instanceof ZodNullable$2?ZodNullable$2.create(deepPartialify$1(e.unwrap())):e instanceof ZodTuple$1?ZodTuple$1.create(e.items.map(e=>deepPartialify$1(e))):e}ZodArray$2.create=(e,t)=>new ZodArray$2({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind$1.ZodArray,...processCreateParams$1(t)});let ZodObject$2=class e extends ZodType$2{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=util$a.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==ZodParsedType$1.object){const t=this._getOrReturnCtx(e);return addIssueToContext$1(t,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType$1.object,
899
899
  received:t.parsedType}),INVALID$1}const{status:t,ctx:r}=this._processInputParams(e),{shape:n,keys:i}=this._getCached(),s=[];if(!(this._def.catchall instanceof ZodNever$2&&"strip"===this._def.unknownKeys))for(const e in r.data)i.includes(e)||s.push(e);const o=[];for(const e of i){const t=n[e],i=r.data[e];o.push({key:{status:"valid",value:e},value:t._parse(new ParseInputLazyPath$1(r,i,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof ZodNever$2){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of s)o.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)s.length>0&&(addIssueToContext$1(r,{code:ZodIssueCode$1.unrecognized_keys,keys:s}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of s){const n=r.data[t];o.push({key:{status:"valid",value:t},value:e._parse(new ParseInputLazyPath$1(r,n,r.path,t)),alwaysSet:t in r.data
900
900
  })}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of o){const r=await t.key,n=await t.value;e.push({key:r,value:n,alwaysSet:t.alwaysSet})}return e}).then(e=>ParseStatus$1.mergeObjectSync(t,e)):ParseStatus$1.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return errorUtil$2.errToObj,new e({...this._def,unknownKeys:"strict",...void 0!==t?{errorMap:(e,r)=>{const n=this._def.errorMap?.(e,r).message??r.defaultError;return"unrecognized_keys"===e.code?{message:errorUtil$2.errToObj(t).message??n}:{message:n}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ZodFirstPartyTypeKind$1.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){
901
- return new e({...this._def,catchall:t})}pick(t){const r={};for(const e of util$b.objectKeys(t))t[e]&&this.shape[e]&&(r[e]=this.shape[e]);return new e({...this._def,shape:()=>r})}omit(t){const r={};for(const e of util$b.objectKeys(this.shape))t[e]||(r[e]=this.shape[e]);return new e({...this._def,shape:()=>r})}deepPartial(){return deepPartialify$1(this)}partial(t){const r={};for(const e of util$b.objectKeys(this.shape)){const n=this.shape[e];t&&!t[e]?r[e]=n:r[e]=n.optional()}return new e({...this._def,shape:()=>r})}required(t){const r={};for(const e of util$b.objectKeys(this.shape))if(t&&!t[e])r[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof ZodOptional$2;)t=t._def.innerType;r[e]=t}return new e({...this._def,shape:()=>r})}keyof(){return createZodEnum$1(util$b.objectKeys(this.shape))}};ZodObject$2.create=(e,t)=>new ZodObject$2({shape:()=>e,unknownKeys:"strip",catchall:ZodNever$2.create(),typeName:ZodFirstPartyTypeKind$1.ZodObject,...processCreateParams$1(t)}),
901
+ return new e({...this._def,catchall:t})}pick(t){const r={};for(const e of util$a.objectKeys(t))t[e]&&this.shape[e]&&(r[e]=this.shape[e]);return new e({...this._def,shape:()=>r})}omit(t){const r={};for(const e of util$a.objectKeys(this.shape))t[e]||(r[e]=this.shape[e]);return new e({...this._def,shape:()=>r})}deepPartial(){return deepPartialify$1(this)}partial(t){const r={};for(const e of util$a.objectKeys(this.shape)){const n=this.shape[e];t&&!t[e]?r[e]=n:r[e]=n.optional()}return new e({...this._def,shape:()=>r})}required(t){const r={};for(const e of util$a.objectKeys(this.shape))if(t&&!t[e])r[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof ZodOptional$2;)t=t._def.innerType;r[e]=t}return new e({...this._def,shape:()=>r})}keyof(){return createZodEnum$1(util$a.objectKeys(this.shape))}};ZodObject$2.create=(e,t)=>new ZodObject$2({shape:()=>e,unknownKeys:"strip",catchall:ZodNever$2.create(),typeName:ZodFirstPartyTypeKind$1.ZodObject,...processCreateParams$1(t)}),
902
902
  ZodObject$2.strictCreate=(e,t)=>new ZodObject$2({shape:()=>e,unknownKeys:"strict",catchall:ZodNever$2.create(),typeName:ZodFirstPartyTypeKind$1.ZodObject,...processCreateParams$1(t)}),ZodObject$2.lazycreate=(e,t)=>new ZodObject$2({shape:e,unknownKeys:"strip",catchall:ZodNever$2.create(),typeName:ZodFirstPartyTypeKind$1.ZodObject,...processCreateParams$1(t)});let ZodUnion$2=class extends ZodType$2{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const r=e.map(e=>new ZodError$2(e.ctx.common.issues));return addIssueToContext$1(t,{code:ZodIssueCode$1.invalid_union,unionErrors:r}),INVALID$1});{let e
903
903
  ;const n=[];for(const i of r){const r={...t,common:{...t.common,issues:[]},parent:null},s=i._parseSync({data:t.data,path:t.path,parent:r});if("valid"===s.status)return s;"dirty"!==s.status||e||(e={result:s,ctx:r}),r.common.issues.length&&n.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const i=n.map(e=>new ZodError$2(e));return addIssueToContext$1(t,{code:ZodIssueCode$1.invalid_union,unionErrors:i}),INVALID$1}}get options(){return this._def.options}};ZodUnion$2.create=(e,t)=>new ZodUnion$2({options:e,typeName:ZodFirstPartyTypeKind$1.ZodUnion,...processCreateParams$1(t)})
904
- ;const getDiscriminator$1=e=>e instanceof ZodLazy$1?getDiscriminator$1(e.schema):e instanceof ZodEffects$1?getDiscriminator$1(e.innerType()):e instanceof ZodLiteral$1?[e.value]:e instanceof ZodEnum$2?e.options:e instanceof ZodNativeEnum$1?util$b.objectValues(e.enum):e instanceof ZodDefault$2?getDiscriminator$1(e._def.innerType):e instanceof ZodUndefined$1?[void 0]:e instanceof ZodNull$1?[null]:e instanceof ZodOptional$2?[void 0,...getDiscriminator$1(e.unwrap())]:e instanceof ZodNullable$2?[null,...getDiscriminator$1(e.unwrap())]:e instanceof ZodBranded$1||e instanceof ZodReadonly$2?getDiscriminator$1(e.unwrap()):e instanceof ZodCatch$2?getDiscriminator$1(e._def.innerType):[];let ZodDiscriminatedUnion$1=class e extends ZodType$2{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType$1.object)return addIssueToContext$1(t,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType$1.object,received:t.parsedType}),INVALID$1
904
+ ;const getDiscriminator$1=e=>e instanceof ZodLazy$1?getDiscriminator$1(e.schema):e instanceof ZodEffects$1?getDiscriminator$1(e.innerType()):e instanceof ZodLiteral$1?[e.value]:e instanceof ZodEnum$2?e.options:e instanceof ZodNativeEnum$1?util$a.objectValues(e.enum):e instanceof ZodDefault$2?getDiscriminator$1(e._def.innerType):e instanceof ZodUndefined$1?[void 0]:e instanceof ZodNull$1?[null]:e instanceof ZodOptional$2?[void 0,...getDiscriminator$1(e.unwrap())]:e instanceof ZodNullable$2?[null,...getDiscriminator$1(e.unwrap())]:e instanceof ZodBranded$1||e instanceof ZodReadonly$2?getDiscriminator$1(e.unwrap()):e instanceof ZodCatch$2?getDiscriminator$1(e._def.innerType):[];let ZodDiscriminatedUnion$1=class e extends ZodType$2{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType$1.object)return addIssueToContext$1(t,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType$1.object,received:t.parsedType}),INVALID$1
905
905
  ;const r=this.discriminator,n=t.data[r],i=this.optionsMap.get(n);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(addIssueToContext$1(t,{code:ZodIssueCode$1.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),INVALID$1)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){const i=new Map;for(const e of r){const r=getDiscriminator$1(e.shape[t]);if(!r.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const n of r){if(i.has(n))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(n)}`);i.set(n,e)}}return new e({typeName:ZodFirstPartyTypeKind$1.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,...processCreateParams$1(n)})}};function mergeValues$2(e,t){
906
- const r=getParsedType$1(e),n=getParsedType$1(t);if(e===t)return{valid:!0,data:e};if(r===ZodParsedType$1.object&&n===ZodParsedType$1.object){const r=util$b.objectKeys(t),n=util$b.objectKeys(e).filter(e=>-1!==r.indexOf(e)),i={...e,...t};for(const r of n){const n=mergeValues$2(e[r],t[r]);if(!n.valid)return{valid:!1};i[r]=n.data}return{valid:!0,data:i}}if(r===ZodParsedType$1.array&&n===ZodParsedType$1.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let n=0;n<e.length;n++){const i=mergeValues$2(e[n],t[n]);if(!i.valid)return{valid:!1};r.push(i.data)}return{valid:!0,data:r}}return r===ZodParsedType$1.date&&n===ZodParsedType$1.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}let ZodIntersection$2=class extends ZodType$2{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(e,n)=>{if(isAborted$1(e)||isAborted$1(n))return INVALID$1;const i=mergeValues$2(e.value,n.value);return i.valid?((isDirty$1(e)||isDirty$1(n))&&t.dirty(),{status:t.value,value:i.data
906
+ const r=getParsedType$1(e),n=getParsedType$1(t);if(e===t)return{valid:!0,data:e};if(r===ZodParsedType$1.object&&n===ZodParsedType$1.object){const r=util$a.objectKeys(t),n=util$a.objectKeys(e).filter(e=>-1!==r.indexOf(e)),i={...e,...t};for(const r of n){const n=mergeValues$2(e[r],t[r]);if(!n.valid)return{valid:!1};i[r]=n.data}return{valid:!0,data:i}}if(r===ZodParsedType$1.array&&n===ZodParsedType$1.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let n=0;n<e.length;n++){const i=mergeValues$2(e[n],t[n]);if(!i.valid)return{valid:!1};r.push(i.data)}return{valid:!0,data:r}}return r===ZodParsedType$1.date&&n===ZodParsedType$1.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}let ZodIntersection$2=class extends ZodType$2{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(e,n)=>{if(isAborted$1(e)||isAborted$1(n))return INVALID$1;const i=mergeValues$2(e.value,n.value);return i.valid?((isDirty$1(e)||isDirty$1(n))&&t.dirty(),{status:t.value,value:i.data
907
907
  }):(addIssueToContext$1(r,{code:ZodIssueCode$1.invalid_intersection_types}),INVALID$1)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>n(e,t)):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};ZodIntersection$2.create=(e,t,r)=>new ZodIntersection$2({left:e,right:t,typeName:ZodFirstPartyTypeKind$1.ZodIntersection,...processCreateParams$1(r)});let ZodTuple$1=class e extends ZodType$2{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ZodParsedType$1.array)return addIssueToContext$1(r,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType$1.array,received:r.parsedType}),INVALID$1;if(r.data.length<this._def.items.length)return addIssueToContext$1(r,{code:ZodIssueCode$1.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),
908
908
  INVALID$1;!this._def.rest&&r.data.length>this._def.items.length&&(addIssueToContext$1(r,{code:ZodIssueCode$1.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const n=[...r.data].map((e,t)=>{const n=this._def.items[t]||this._def.rest;return n?n._parse(new ParseInputLazyPath$1(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(n).then(e=>ParseStatus$1.mergeArray(t,e)):ParseStatus$1.mergeArray(t,n)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};ZodTuple$1.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple$1({items:e,typeName:ZodFirstPartyTypeKind$1.ZodTuple,rest:null,...processCreateParams$1(t)})};let ZodRecord$2=class e extends ZodType$2{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e)
909
909
  ;if(r.parsedType!==ZodParsedType$1.object)return addIssueToContext$1(r,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType$1.object,received:r.parsedType}),INVALID$1;const n=[],i=this._def.keyType,s=this._def.valueType;for(const e in r.data)n.push({key:i._parse(new ParseInputLazyPath$1(r,e,r.path,e)),value:s._parse(new ParseInputLazyPath$1(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?ParseStatus$1.mergeObjectAsync(t,n):ParseStatus$1.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(t,r,n){return new e(r instanceof ZodType$2?{keyType:t,valueType:r,typeName:ZodFirstPartyTypeKind$1.ZodRecord,...processCreateParams$1(n)}:{keyType:ZodString$2.create(),valueType:t,typeName:ZodFirstPartyTypeKind$1.ZodRecord,...processCreateParams$1(r)})}},ZodMap$1=class extends ZodType$2{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e)
@@ -912,12 +912,12 @@ typeName:ZodFirstPartyTypeKind$1.ZodMap,...processCreateParams$1(r)});let ZodSet
912
912
  const o=[...r.data.values()].map((e,t)=>i._parse(new ParseInputLazyPath$1(r,e,r.path,t)));return r.common.async?Promise.all(o).then(e=>s(e)):s(o)}min(t,r){return new e({...this._def,minSize:{value:t,message:errorUtil$2.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:errorUtil$2.toString(r)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};ZodSet$1.create=(e,t)=>new ZodSet$1({valueType:e,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind$1.ZodSet,...processCreateParams$1(t)});class ZodFunction extends ZodType$2{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType$1.function)return addIssueToContext$1(t,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType$1.function,received:t.parsedType}),INVALID$1;function r(e,r){return makeIssue$1({data:e,path:t.path,
913
913
  errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,getErrorMap$1(),errorMap$1].filter(e=>!!e),issueData:{code:ZodIssueCode$1.invalid_arguments,argumentsError:r}})}function n(e,r){return makeIssue$1({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,getErrorMap$1(),errorMap$1].filter(e=>!!e),issueData:{code:ZodIssueCode$1.invalid_return_type,returnTypeError:r}})}const i={errorMap:t.common.contextualErrorMap},s=t.data;if(this._def.returns instanceof ZodPromise$1){const e=this;return OK$1(async function(...t){const o=new ZodError$2([]),a=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(r(t,e)),o}),c=await Reflect.apply(s,this,a);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(n(c,e)),o})})}{const e=this;return OK$1(function(...t){const o=e._def.args.safeParse(t,i);if(!o.success)throw new ZodError$2([r(t,o.error)]);const a=Reflect.apply(s,this,o.data),c=e._def.returns.safeParse(a,i)
914
914
  ;if(!c.success)throw new ZodError$2([n(a,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ZodFunction({...this._def,args:ZodTuple$1.create(e).rest(ZodUnknown$2.create())})}returns(e){return new ZodFunction({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new ZodFunction({args:e||ZodTuple$1.create([]).rest(ZodUnknown$2.create()),returns:t||ZodUnknown$2.create(),typeName:ZodFirstPartyTypeKind$1.ZodFunction,...processCreateParams$1(r)})}}let ZodLazy$1=class extends ZodType$2{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};ZodLazy$1.create=(e,t)=>new ZodLazy$1({getter:e,typeName:ZodFirstPartyTypeKind$1.ZodLazy,...processCreateParams$1(t)});let ZodLiteral$1=class extends ZodType$2{_parse(e){if(e.data!==this._def.value){
915
- const t=this._getOrReturnCtx(e);return addIssueToContext$1(t,{received:t.data,code:ZodIssueCode$1.invalid_literal,expected:this._def.value}),INVALID$1}return{status:"valid",value:e.data}}get value(){return this._def.value}};function createZodEnum$1(e,t){return new ZodEnum$2({values:e,typeName:ZodFirstPartyTypeKind$1.ZodEnum,...processCreateParams$1(t)})}ZodLiteral$1.create=(e,t)=>new ZodLiteral$1({value:e,typeName:ZodFirstPartyTypeKind$1.ZodLiteral,...processCreateParams$1(t)});let ZodEnum$2=class e extends ZodType$2{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return addIssueToContext$1(t,{expected:util$b.joinValues(r),received:t.parsedType,code:ZodIssueCode$1.invalid_type}),INVALID$1}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return addIssueToContext$1(t,{received:t.data,code:ZodIssueCode$1.invalid_enum_value,options:r}),INVALID$1}return OK$1(e.data)}
916
- get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(t,r=this._def){return e.create(t,{...this._def,...r})}exclude(t,r=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...r})}};ZodEnum$2.create=createZodEnum$1;let ZodNativeEnum$1=class extends ZodType$2{_parse(e){const t=util$b.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==ZodParsedType$1.string&&r.parsedType!==ZodParsedType$1.number){const e=util$b.objectValues(t);return addIssueToContext$1(r,{expected:util$b.joinValues(e),received:r.parsedType,code:ZodIssueCode$1.invalid_type}),INVALID$1}if(this._cache||(this._cache=new Set(util$b.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=util$b.objectValues(t);return addIssueToContext$1(r,{
915
+ const t=this._getOrReturnCtx(e);return addIssueToContext$1(t,{received:t.data,code:ZodIssueCode$1.invalid_literal,expected:this._def.value}),INVALID$1}return{status:"valid",value:e.data}}get value(){return this._def.value}};function createZodEnum$1(e,t){return new ZodEnum$2({values:e,typeName:ZodFirstPartyTypeKind$1.ZodEnum,...processCreateParams$1(t)})}ZodLiteral$1.create=(e,t)=>new ZodLiteral$1({value:e,typeName:ZodFirstPartyTypeKind$1.ZodLiteral,...processCreateParams$1(t)});let ZodEnum$2=class e extends ZodType$2{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return addIssueToContext$1(t,{expected:util$a.joinValues(r),received:t.parsedType,code:ZodIssueCode$1.invalid_type}),INVALID$1}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return addIssueToContext$1(t,{received:t.data,code:ZodIssueCode$1.invalid_enum_value,options:r}),INVALID$1}return OK$1(e.data)}
916
+ get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(t,r=this._def){return e.create(t,{...this._def,...r})}exclude(t,r=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...r})}};ZodEnum$2.create=createZodEnum$1;let ZodNativeEnum$1=class extends ZodType$2{_parse(e){const t=util$a.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==ZodParsedType$1.string&&r.parsedType!==ZodParsedType$1.number){const e=util$a.objectValues(t);return addIssueToContext$1(r,{expected:util$a.joinValues(e),received:r.parsedType,code:ZodIssueCode$1.invalid_type}),INVALID$1}if(this._cache||(this._cache=new Set(util$a.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=util$a.objectValues(t);return addIssueToContext$1(r,{
917
917
  received:r.data,code:ZodIssueCode$1.invalid_enum_value,options:e}),INVALID$1}return OK$1(e.data)}get enum(){return this._def.values}};ZodNativeEnum$1.create=(e,t)=>new ZodNativeEnum$1({values:e,typeName:ZodFirstPartyTypeKind$1.ZodNativeEnum,...processCreateParams$1(t)});let ZodPromise$1=class extends ZodType$2{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType$1.promise&&!1===t.common.async)return addIssueToContext$1(t,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType$1.promise,received:t.parsedType}),INVALID$1;const r=t.parsedType===ZodParsedType$1.promise?t.data:Promise.resolve(t.data);return OK$1(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};ZodPromise$1.create=(e,t)=>new ZodPromise$1({type:e,typeName:ZodFirstPartyTypeKind$1.ZodPromise,...processCreateParams$1(t)});let ZodEffects$1=class extends ZodType$2{innerType(){return this._def.schema}sourceType(){
918
918
  return this._def.schema._def.typeName===ZodFirstPartyTypeKind$1.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,i={addIssue:e=>{addIssueToContext$1(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===n.type){const e=n.transform(r.data,i);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return INVALID$1;const n=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===n.status?INVALID$1:"dirty"===n.status||"dirty"===t.value?DIRTY$1(n.value):n});{if("aborted"===t.value)return INVALID$1;const n=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===n.status?INVALID$1:"dirty"===n.status||"dirty"===t.value?DIRTY$1(n.value):n}}if("refinement"===n.type){const e=e=>{const t=n.refinement(e,i);if(r.common.async)return Promise.resolve(t)
919
919
  ;if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const n=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===n.status?INVALID$1:("dirty"===n.status&&t.dirty(),e(n.value),{status:t.value,value:n.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?INVALID$1:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))))}if("transform"===n.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!isValid$1(e))return INVALID$1;const s=n.transform(e.value,i);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:s}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r
920
- }).then(e=>isValid$1(e)?Promise.resolve(n.transform(e.value,i)).then(e=>({status:t.value,value:e})):INVALID$1)}util$b.assertNever(n)}};ZodEffects$1.create=(e,t,r)=>new ZodEffects$1({schema:e,typeName:ZodFirstPartyTypeKind$1.ZodEffects,effect:t,...processCreateParams$1(r)}),ZodEffects$1.createWithPreprocess=(e,t,r)=>new ZodEffects$1({schema:t,effect:{type:"preprocess",transform:e},typeName:ZodFirstPartyTypeKind$1.ZodEffects,...processCreateParams$1(r)});let ZodOptional$2=class extends ZodType$2{_parse(e){return this._getType(e)===ZodParsedType$1.undefined?OK$1(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ZodOptional$2.create=(e,t)=>new ZodOptional$2({innerType:e,typeName:ZodFirstPartyTypeKind$1.ZodOptional,...processCreateParams$1(t)});let ZodNullable$2=class extends ZodType$2{_parse(e){return this._getType(e)===ZodParsedType$1.null?OK$1(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}
920
+ }).then(e=>isValid$1(e)?Promise.resolve(n.transform(e.value,i)).then(e=>({status:t.value,value:e})):INVALID$1)}util$a.assertNever(n)}};ZodEffects$1.create=(e,t,r)=>new ZodEffects$1({schema:e,typeName:ZodFirstPartyTypeKind$1.ZodEffects,effect:t,...processCreateParams$1(r)}),ZodEffects$1.createWithPreprocess=(e,t,r)=>new ZodEffects$1({schema:t,effect:{type:"preprocess",transform:e},typeName:ZodFirstPartyTypeKind$1.ZodEffects,...processCreateParams$1(r)});let ZodOptional$2=class extends ZodType$2{_parse(e){return this._getType(e)===ZodParsedType$1.undefined?OK$1(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ZodOptional$2.create=(e,t)=>new ZodOptional$2({innerType:e,typeName:ZodFirstPartyTypeKind$1.ZodOptional,...processCreateParams$1(t)});let ZodNullable$2=class extends ZodType$2{_parse(e){return this._getType(e)===ZodParsedType$1.null?OK$1(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}
921
921
  ;ZodNullable$2.create=(e,t)=>new ZodNullable$2({innerType:e,typeName:ZodFirstPartyTypeKind$1.ZodNullable,...processCreateParams$1(t)});let ZodDefault$2=class extends ZodType$2{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===ZodParsedType$1.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ZodDefault$2.create=(e,t)=>new ZodDefault$2({innerType:e,typeName:ZodFirstPartyTypeKind$1.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...processCreateParams$1(t)});let ZodCatch$2=class extends ZodType$2{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return isAsync$1(n)?n.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new ZodError$2(r.common.issues)},input:r.data})})):{
922
922
  status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new ZodError$2(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};ZodCatch$2.create=(e,t)=>new ZodCatch$2({innerType:e,typeName:ZodFirstPartyTypeKind$1.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...processCreateParams$1(t)});let ZodNaN$1=class extends ZodType$2{_parse(e){if(this._getType(e)!==ZodParsedType$1.nan){const t=this._getOrReturnCtx(e);return addIssueToContext$1(t,{code:ZodIssueCode$1.invalid_type,expected:ZodParsedType$1.nan,received:t.parsedType}),INVALID$1}return{status:"valid",value:e.data}}};ZodNaN$1.create=e=>new ZodNaN$1({typeName:ZodFirstPartyTypeKind$1.ZodNaN,...processCreateParams$1(e)});const BRAND=Symbol("zod_brand");let ZodBranded$1=class extends ZodType$2{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}
923
923
  },ZodPipeline$1=class e extends ZodType$2{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?INVALID$1:"dirty"===e.status?(t.dirty(),DIRTY$1(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})()}{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?INVALID$1:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(t,r){return new e({in:t,out:r,typeName:ZodFirstPartyTypeKind$1.ZodPipeline})}},ZodReadonly$2=class extends ZodType$2{_parse(e){const t=this._def.innerType._parse(e),r=e=>(isValid$1(e)&&(e.value=Object.freeze(e.value)),e);return isAsync$1(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}};function cleanParams(e,t){const r="function"==typeof e?e(t):"string"==typeof e?{message:e
@@ -926,7 +926,7 @@ e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersecti
926
926
  })=>custom$1(t=>t instanceof e,t),stringType$1=ZodString$2.create,numberType$1=ZodNumber$1.create,nanType=ZodNaN$1.create,bigIntType=ZodBigInt$1.create,booleanType$1=ZodBoolean$1.create,dateType=ZodDate$1.create,symbolType=ZodSymbol$1.create,undefinedType=ZodUndefined$1.create,nullType=ZodNull$1.create,anyType$1=ZodAny$1.create,unknownType$1=ZodUnknown$2.create,neverType=ZodNever$2.create,voidType=ZodVoid$1.create,arrayType$1=ZodArray$2.create,objectType$1=ZodObject$2.create,strictObjectType=ZodObject$2.strictCreate,unionType$1=ZodUnion$2.create,discriminatedUnionType$1=ZodDiscriminatedUnion$1.create,intersectionType=ZodIntersection$2.create,tupleType=ZodTuple$1.create,recordType$1=ZodRecord$2.create,mapType=ZodMap$1.create,setType=ZodSet$1.create,functionType=ZodFunction.create,lazyType=ZodLazy$1.create,literalType$1=ZodLiteral$1.create,enumType$1=ZodEnum$2.create,nativeEnumType=ZodNativeEnum$1.create,promiseType=ZodPromise$1.create,effectsType=ZodEffects$1.create,optionalType$1=ZodOptional$2.create,nullableType=ZodNullable$2.create,preprocessType=ZodEffects$1.createWithPreprocess,pipelineType=ZodPipeline$1.create,ostring=()=>stringType$1().optional(),onumber=()=>numberType$1().optional(),oboolean=()=>booleanType$1().optional(),coerce={
927
927
  string:e=>ZodString$2.create({...e,coerce:!0}),number:e=>ZodNumber$1.create({...e,coerce:!0}),boolean:e=>ZodBoolean$1.create({...e,coerce:!0}),bigint:e=>ZodBigInt$1.create({...e,coerce:!0}),date:e=>ZodDate$1.create({...e,coerce:!0})},NEVER=INVALID$1;var z=Object.freeze({__proto__:null,BRAND,DIRTY:DIRTY$1,EMPTY_PATH,INVALID:INVALID$1,NEVER,OK:OK$1,ParseStatus:ParseStatus$1,Schema:ZodType$2,ZodAny:ZodAny$1,ZodArray:ZodArray$2,ZodBigInt:ZodBigInt$1,ZodBoolean:ZodBoolean$1,ZodBranded:ZodBranded$1,ZodCatch:ZodCatch$2,ZodDate:ZodDate$1,ZodDefault:ZodDefault$2,ZodDiscriminatedUnion:ZodDiscriminatedUnion$1,ZodEffects:ZodEffects$1,ZodEnum:ZodEnum$2,ZodError:ZodError$2,get ZodFirstPartyTypeKind(){return ZodFirstPartyTypeKind$1},ZodFunction,ZodIntersection:ZodIntersection$2,ZodIssueCode:ZodIssueCode$1,ZodLazy:ZodLazy$1,ZodLiteral:ZodLiteral$1,ZodMap:ZodMap$1,ZodNaN:ZodNaN$1,ZodNativeEnum:ZodNativeEnum$1,ZodNever:ZodNever$2,ZodNull:ZodNull$1,ZodNullable:ZodNullable$2,ZodNumber:ZodNumber$1,
928
928
  ZodObject:ZodObject$2,ZodOptional:ZodOptional$2,ZodParsedType:ZodParsedType$1,ZodPipeline:ZodPipeline$1,ZodPromise:ZodPromise$1,ZodReadonly:ZodReadonly$2,ZodRecord:ZodRecord$2,ZodSchema:ZodType$2,ZodSet:ZodSet$1,ZodString:ZodString$2,ZodSymbol:ZodSymbol$1,ZodTransformer:ZodEffects$1,ZodTuple:ZodTuple$1,ZodType:ZodType$2,ZodUndefined:ZodUndefined$1,ZodUnion:ZodUnion$2,ZodUnknown:ZodUnknown$2,ZodVoid:ZodVoid$1,addIssueToContext:addIssueToContext$1,any:anyType$1,array:arrayType$1,bigint:bigIntType,boolean:booleanType$1,coerce,custom:custom$1,date:dateType,datetimeRegex:datetimeRegex$1,defaultErrorMap:errorMap$1,discriminatedUnion:discriminatedUnionType$1,effect:effectsType,enum:enumType$1,function:functionType,getErrorMap:getErrorMap$1,getParsedType:getParsedType$1,instanceof:instanceOfType,intersection:intersectionType,isAborted:isAborted$1,isAsync:isAsync$1,isDirty:isDirty$1,isValid:isValid$1,late,lazy:lazyType,literal:literalType$1,makeIssue:makeIssue$1,map:mapType,nan:nanType,
929
- nativeEnum:nativeEnumType,never:neverType,null:nullType,nullable:nullableType,number:numberType$1,object:objectType$1,get objectUtil(){return objectUtil$1},oboolean,onumber,optional:optionalType$1,ostring,pipeline:pipelineType,preprocess:preprocessType,promise:promiseType,quotelessJson,record:recordType$1,set:setType,setErrorMap,strictObject:strictObjectType,string:stringType$1,symbol:symbolType,transformer:effectsType,tuple:tupleType,undefined:undefinedType,union:unionType$1,unknown:unknownType$1,get util(){return util$b},void:voidType});function xmlish(e,t,r={}){return void 0===t?"":`<${e}${Object.entries(r).map(([e,t])=>` ${e}="${t}"`).join("")}>\n${t}\n</${e}>`}var tarStream={},fixedSize,hasRequiredFixedSize,fastFifo,hasRequiredFastFifo,b4a,hasRequiredB4a,passThroughDecoder,hasRequiredPassThroughDecoder,utf8Decoder,hasRequiredUtf8Decoder,textDecoder$1,hasRequiredTextDecoder,streamx,hasRequiredStreamx;function requireFixedSize(){return hasRequiredFixedSize||(hasRequiredFixedSize=1,
929
+ nativeEnum:nativeEnumType,never:neverType,null:nullType,nullable:nullableType,number:numberType$1,object:objectType$1,get objectUtil(){return objectUtil$1},oboolean,onumber,optional:optionalType$1,ostring,pipeline:pipelineType,preprocess:preprocessType,promise:promiseType,quotelessJson,record:recordType$1,set:setType,setErrorMap,strictObject:strictObjectType,string:stringType$1,symbol:symbolType,transformer:effectsType,tuple:tupleType,undefined:undefinedType,union:unionType$1,unknown:unknownType$1,get util(){return util$a},void:voidType});function xmlish(e,t,r={}){return void 0===t?"":`<${e}${Object.entries(r).map(([e,t])=>` ${e}="${t}"`).join("")}>\n${t}\n</${e}>`}var tarStream={},fixedSize,hasRequiredFixedSize,fastFifo,hasRequiredFastFifo,b4a,hasRequiredB4a,passThroughDecoder,hasRequiredPassThroughDecoder,utf8Decoder,hasRequiredUtf8Decoder,textDecoder$1,hasRequiredTextDecoder,streamx,hasRequiredStreamx;function requireFixedSize(){return hasRequiredFixedSize||(hasRequiredFixedSize=1,
930
930
  fixedSize=class{constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}clear(){this.top=this.btm=0,this.next=null,this.buffer.fill(void 0)}push(e){return void 0===this.buffer[this.top]&&(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){const e=this.buffer[this.btm];if(void 0!==e)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}peek(){return this.buffer[this.btm]}isEmpty(){return void 0===this.buffer[this.btm]}}),fixedSize}function requireFastFifo(){if(hasRequiredFastFifo)return fastFifo;hasRequiredFastFifo=1;const e=requireFixedSize();return fastFifo=class{constructor(t){this.hwm=t||16,this.head=new e(this.hwm),this.tail=this.head,this.length=0}clear(){this.head=this.tail,this.head.clear(),this.length=0}push(t){if(this.length++,!this.head.push(t)){const r=this.head;this.head=r.next=new e(2*this.head.buffer.length),
931
931
  this.head.push(t)}}shift(){0!==this.length&&this.length--;const e=this.tail.shift();if(void 0===e&&this.tail.next){const e=this.tail.next;return this.tail.next=null,this.tail=e,this.tail.shift()}return e}peek(){const e=this.tail.peek();return void 0===e&&this.tail.next?this.tail.next.peek():e}isEmpty(){return 0===this.length}}}function requireB4a(){if(hasRequiredB4a)return b4a;function e(e){return Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength)}return hasRequiredB4a=1,b4a={isBuffer:function(e){return Buffer.isBuffer(e)||e instanceof Uint8Array},isEncoding:function(e){return Buffer.isEncoding(e)},alloc:function(e,t,r){return Buffer.alloc(e,t,r)},allocUnsafe:function(e){return Buffer.allocUnsafe(e)},allocUnsafeSlow:function(e){return Buffer.allocUnsafeSlow(e)},byteLength:function(e,t){return Buffer.byteLength(e,t)},compare:function(e,t){return Buffer.compare(e,t)},concat:function(e,t){return Buffer.concat(e,t)},copy:function(t,r,n,i,s){return e(t).copy(r,n,i,s)},
932
932
  equals:function(t,r){return e(t).equals(r)},fill:function(t,r,n,i,s){return e(t).fill(r,n,i,s)},from:function(e,t,r){return Buffer.from(e,t,r)},includes:function(t,r,n,i){return e(t).includes(r,n,i)},indexOf:function(t,r,n,i){return e(t).indexOf(r,n,i)},lastIndexOf:function(t,r,n,i){return e(t).lastIndexOf(r,n,i)},swap16:function(t){return e(t).swap16()},swap32:function(t){return e(t).swap32()},swap64:function(t){return e(t).swap64()},toBuffer:e,toString:function(t,r,n,i){return e(t).toString(r,n,i)},write:function(t,r,n,i,s){return e(t).write(r,n,i,s)},writeDoubleLE:function(t,r,n){return e(t).writeDoubleLE(r,n)},writeFloatLE:function(t,r,n){return e(t).writeFloatLE(r,n)},writeUInt32LE:function(t,r,n){return e(t).writeUInt32LE(r,n)},writeInt32LE:function(t,r,n){return e(t).writeInt32LE(r,n)},readDoubleLE:function(t,r){return e(t).readDoubleLE(r)},readFloatLE:function(t,r){return e(t).readFloatLE(r)},readUInt32LE:function(t,r){return e(t).readUInt32LE(r)},readInt32LE:function(t,r){
@@ -1183,9 +1183,9 @@ return t>=e.length?-1:(e.charCodeAt(t)|TO_LOWER_BIT)===CharCodes.LOWER_X?(this.s
1183
1183
  }return-1}emitNotTerminatedNamedEntity(){var e;const{result:t,decodeTree:r}=this,n=(r[t]&BinTrieFlags.VALUE_LENGTH)>>14;return this.emitNamedEntityData(t,n,this.consumed),null===(e=this.errors)||void 0===e||e.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(e,t,r){const{decodeTree:n}=this;return this.emitCodePoint(1===t?n[e]&~BinTrieFlags.VALUE_LENGTH:n[e+1],r),3===t&&this.emitCodePoint(n[e+2],r),r}end(){var e;switch(this.state){case EntityDecoderState.NamedEntity:return 0===this.result||this.decodeMode===DecodingMode.Attribute&&this.result!==this.treeIndex?0:this.emitNotTerminatedNamedEntity();case EntityDecoderState.NumericDecimal:return this.emitNumericEntity(0,2);case EntityDecoderState.NumericHex:return this.emitNumericEntity(0,3);case EntityDecoderState.NumericStart:return null===(e=this.errors)||void 0===e||e.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case EntityDecoderState.EntityStart:return 0}}}function getDecoder(e){let t=""
1184
1184
  ;const r=new EntityDecoder(e,e=>t+=fromCodePoint$1(e));return function(e,n){let i=0,s=0;for(;(s=e.indexOf("&",s))>=0;){t+=e.slice(i,s),r.startEntity(n);const o=r.write(e,s+1);if(o<0){i=s+r.end();break}i=s+o,s=0===o?i+1:i}const o=t+e.slice(i);return t="",o}}function determineBranch(e,t,r,n){const i=(t&BinTrieFlags.BRANCH_LENGTH)>>7,s=t&BinTrieFlags.JUMP_TABLE;if(0===i)return 0!==s&&n===s?r:-1;if(s){const t=n-s;return t<0||t>=i?-1:e[r+t]-1}let o=r,a=o+i-1;for(;o<=a;){const t=o+a>>>1,r=e[t];if(r<n)o=t+1;else{if(!(r>n))return e[t+i];a=t-1}}return-1}const htmlDecoder=getDecoder(htmlDecodeTree);function decodeHTML(e,t=DecodingMode.Legacy){return htmlDecoder(e,t)}function _class$1(e){return Object.prototype.toString.call(e)}function isString$2(e){return"[object String]"===_class$1(e)}getDecoder(xmlDecodeTree);const _hasOwnProperty=Object.prototype.hasOwnProperty;function has$1(e,t){return _hasOwnProperty.call(e,t)}function assign$2(e){
1185
1185
  return Array.prototype.slice.call(arguments,1).forEach(function(t){if(t){if("object"!=typeof t)throw new TypeError(t+"must be object");Object.keys(t).forEach(function(r){e[r]=t[r]})}}),e}function arrayReplaceAt(e,t,r){return[].concat(e.slice(0,t),r,e.slice(t+1))}function isValidEntityCode(e){return!(e>=55296&&e<=57343)&&(!(e>=64976&&e<=65007)&&(!!(65535&~e&&65534!=(65535&e))&&(!(e>=0&&e<=8)&&(11!==e&&(!(e>=14&&e<=31)&&(!(e>=127&&e<=159)&&!(e>1114111)))))))}function fromCodePoint(e){if(e>65535){const t=55296+((e-=65536)>>10),r=56320+(1023&e);return String.fromCharCode(t,r)}return String.fromCharCode(e)}const UNESCAPE_MD_RE=/\\([!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/g,ENTITY_RE=/&([a-z#][a-z0-9]{1,31});/gi,UNESCAPE_ALL_RE=new RegExp(UNESCAPE_MD_RE.source+"|"+ENTITY_RE.source,"gi"),DIGITAL_ENTITY_TEST_RE=/^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))$/i;function replaceEntityPattern(e,t){if(35===t.charCodeAt(0)&&DIGITAL_ENTITY_TEST_RE.test(t)){
1186
- const r="x"===t[1].toLowerCase()?parseInt(t.slice(2),16):parseInt(t.slice(1),10);return isValidEntityCode(r)?fromCodePoint(r):e}const r=decodeHTML(e);return r!==e?r:e}function unescapeMd(e){return e.indexOf("\\")<0?e:e.replace(UNESCAPE_MD_RE,"$1")}function unescapeAll(e){return e.indexOf("\\")<0&&e.indexOf("&")<0?e:e.replace(UNESCAPE_ALL_RE,function(e,t,r){return t||replaceEntityPattern(e,r)})}const HTML_ESCAPE_TEST_RE=/[&<>"]/,HTML_ESCAPE_REPLACE_RE=/[&<>"]/g,HTML_REPLACEMENTS={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"};function replaceUnsafeChar(e){return HTML_REPLACEMENTS[e]}function escapeHtml$2(e){return HTML_ESCAPE_TEST_RE.test(e)?e.replace(HTML_ESCAPE_REPLACE_RE,replaceUnsafeChar):e}const REGEXP_ESCAPE_RE=/[.?*+^$[\]\\(){}|-]/g;function escapeRE$1(e){return e.replace(REGEXP_ESCAPE_RE,"\\$&")}function isSpace(e){switch(e){case 9:case 32:return!0}return!1}function isWhiteSpace(e){if(e>=8192&&e<=8202)return!0;switch(e){case 9:case 10:case 11:case 12:case 13:case 32:case 160:
1187
- case 5760:case 8239:case 8287:case 12288:return!0}return!1}function isPunctChar(e){return P.test(e)||regex.test(e)}function isMdAsciiPunct(e){switch(e){case 33:case 34:case 35:case 36:case 37:case 38:case 39:case 40:case 41:case 42:case 43:case 44:case 45:case 46:case 47:case 58:case 59:case 60:case 61:case 62:case 63:case 64:case 91:case 92:case 93:case 94:case 95:case 96:case 123:case 124:case 125:case 126:return!0;default:return!1}}function normalizeReference(e){return e=e.trim().replace(/\s+/g," "),"Ṿ"==="ẞ".toLowerCase()&&(e=e.replace(/ẞ/g,"ß")),e.toLowerCase().toUpperCase()}const lib$5={mdurl,ucmicro};var utils$9=Object.freeze({__proto__:null,arrayReplaceAt,assign:assign$2,escapeHtml:escapeHtml$2,escapeRE:escapeRE$1,fromCodePoint,has:has$1,isMdAsciiPunct,isPunctChar,isSpace,isString:isString$2,isValidEntityCode,isWhiteSpace,lib:lib$5,normalizeReference,unescapeAll,unescapeMd});function parseLinkLabel(e,t,r){let n,i,s,o;const a=e.posMax,c=e.pos;for(e.pos=t+1,n=1;e.pos<a;){
1188
- if(s=e.src.charCodeAt(e.pos),93===s&&(n--,0===n)){i=!0;break}if(o=e.pos,e.md.inline.skipToken(e),91===s)if(o===e.pos-1)n++;else if(r)return e.pos=c,-1}let u=-1;return i&&(u=e.pos),e.pos=c,u}function parseLinkDestination(e,t,r){let n,i=t;const s={ok:!1,pos:0,str:""};if(60===e.charCodeAt(i)){for(i++;i<r;){if(n=e.charCodeAt(i),10===n)return s;if(60===n)return s;if(62===n)return s.pos=i+1,s.str=unescapeAll(e.slice(t+1,i)),s.ok=!0,s;92===n&&i+1<r?i+=2:i++}return s}let o=0;for(;i<r&&(n=e.charCodeAt(i),32!==n)&&!(n<32||127===n);)if(92===n&&i+1<r){if(32===e.charCodeAt(i+1))break;i+=2}else{if(40===n&&(o++,o>32))return s;if(41===n){if(0===o)break;o--}i++}return t===i||0!==o||(s.str=unescapeAll(e.slice(t,i)),s.pos=i,s.ok=!0),s}function parseLinkTitle(e,t,r,n){let i,s=t;const o={ok:!1,can_continue:!1,pos:0,str:"",marker:0};if(n)o.str=n.str,o.marker=n.marker;else{if(s>=r)return o;let n=e.charCodeAt(s);if(34!==n&&39!==n&&40!==n)return o;t++,s++,40===n&&(n=41),o.marker=n}for(;s<r;){
1186
+ const r="x"===t[1].toLowerCase()?parseInt(t.slice(2),16):parseInt(t.slice(1),10);return isValidEntityCode(r)?fromCodePoint(r):e}const r=decodeHTML(e);return r!==e?r:e}function unescapeMd(e){return e.indexOf("\\")<0?e:e.replace(UNESCAPE_MD_RE,"$1")}function unescapeAll(e){return e.indexOf("\\")<0&&e.indexOf("&")<0?e:e.replace(UNESCAPE_ALL_RE,function(e,t,r){return t||replaceEntityPattern(e,r)})}const HTML_ESCAPE_TEST_RE=/[&<>"]/,HTML_ESCAPE_REPLACE_RE=/[&<>"]/g,HTML_REPLACEMENTS={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"};function replaceUnsafeChar(e){return HTML_REPLACEMENTS[e]}function escapeHtml$2(e){return HTML_ESCAPE_TEST_RE.test(e)?e.replace(HTML_ESCAPE_REPLACE_RE,replaceUnsafeChar):e}const REGEXP_ESCAPE_RE=/[.?*+^$[\]\\(){}|-]/g;function escapeRE$1(e){return e.replace(REGEXP_ESCAPE_RE,"\\$&")}function isSpace(e){switch(e){case 9:case 32:return!0}return!1}function isWhiteSpace$1(e){if(e>=8192&&e<=8202)return!0;switch(e){case 9:case 10:case 11:case 12:case 13:case 32:case 160:
1187
+ case 5760:case 8239:case 8287:case 12288:return!0}return!1}function isPunctChar(e){return P.test(e)||regex.test(e)}function isMdAsciiPunct(e){switch(e){case 33:case 34:case 35:case 36:case 37:case 38:case 39:case 40:case 41:case 42:case 43:case 44:case 45:case 46:case 47:case 58:case 59:case 60:case 61:case 62:case 63:case 64:case 91:case 92:case 93:case 94:case 95:case 96:case 123:case 124:case 125:case 126:return!0;default:return!1}}function normalizeReference(e){return e=e.trim().replace(/\s+/g," "),"Ṿ"==="ẞ".toLowerCase()&&(e=e.replace(/ẞ/g,"ß")),e.toLowerCase().toUpperCase()}const lib$5={mdurl,ucmicro};var utils$9=Object.freeze({__proto__:null,arrayReplaceAt,assign:assign$2,escapeHtml:escapeHtml$2,escapeRE:escapeRE$1,fromCodePoint,has:has$1,isMdAsciiPunct,isPunctChar,isSpace,isString:isString$2,isValidEntityCode,isWhiteSpace:isWhiteSpace$1,lib:lib$5,normalizeReference,unescapeAll,unescapeMd});function parseLinkLabel(e,t,r){let n,i,s,o;const a=e.posMax,c=e.pos;for(e.pos=t+1,
1188
+ n=1;e.pos<a;){if(s=e.src.charCodeAt(e.pos),93===s&&(n--,0===n)){i=!0;break}if(o=e.pos,e.md.inline.skipToken(e),91===s)if(o===e.pos-1)n++;else if(r)return e.pos=c,-1}let u=-1;return i&&(u=e.pos),e.pos=c,u}function parseLinkDestination(e,t,r){let n,i=t;const s={ok:!1,pos:0,str:""};if(60===e.charCodeAt(i)){for(i++;i<r;){if(n=e.charCodeAt(i),10===n)return s;if(60===n)return s;if(62===n)return s.pos=i+1,s.str=unescapeAll(e.slice(t+1,i)),s.ok=!0,s;92===n&&i+1<r?i+=2:i++}return s}let o=0;for(;i<r&&(n=e.charCodeAt(i),32!==n)&&!(n<32||127===n);)if(92===n&&i+1<r){if(32===e.charCodeAt(i+1))break;i+=2}else{if(40===n&&(o++,o>32))return s;if(41===n){if(0===o)break;o--}i++}return t===i||0!==o||(s.str=unescapeAll(e.slice(t,i)),s.pos=i,s.ok=!0),s}function parseLinkTitle(e,t,r,n){let i,s=t;const o={ok:!1,can_continue:!1,pos:0,str:"",marker:0};if(n)o.str=n.str,o.marker=n.marker;else{if(s>=r)return o;let n=e.charCodeAt(s);if(34!==n&&39!==n&&40!==n)return o;t++,s++,40===n&&(n=41),o.marker=n}for(;s<r;){
1189
1189
  if(i=e.charCodeAt(s),i===o.marker)return o.pos=s+1,o.str+=unescapeAll(e.slice(t,s)),o.ok=!0,o;if(40===i&&41===o.marker)return o;92===i&&s+1<r&&s++,s++}return o.can_continue=!0,o.str+=unescapeAll(e.slice(t,s)),o}var helpers=Object.freeze({__proto__:null,parseLinkDestination,parseLinkLabel,parseLinkTitle});const default_rules={};function Renderer(){this.rules=assign$2({},default_rules)}function Ruler(){this.__rules__=[],this.__cache__=null}function Token(e,t,r){this.type=e,this.tag=t,this.attrs=null,this.map=null,this.nesting=r,this.level=0,this.children=null,this.content="",this.markup="",this.info="",this.meta=null,this.block=!1,this.hidden=!1}function StateCore(e,t,r){this.src=e,this.env=r,this.tokens=[],this.inlineMode=!1,this.md=t}default_rules.code_inline=function(e,t,r,n,i){const s=e[t];return"<code"+i.renderAttrs(s)+">"+escapeHtml$2(s.content)+"</code>"},default_rules.code_block=function(e,t,r,n,i){const s=e[t]
1190
1190
  ;return"<pre"+i.renderAttrs(s)+"><code>"+escapeHtml$2(e[t].content)+"</code></pre>\n"},default_rules.fence=function(e,t,r,n,i){const s=e[t],o=s.info?unescapeAll(s.info).trim():"";let a,c="",u="";if(o){const e=o.split(/(\s+)/g);c=e[0],u=e.slice(2).join("")}if(a=r.highlight&&r.highlight(s.content,c,u)||escapeHtml$2(s.content),0===a.indexOf("<pre"))return a+"\n";if(o){const e=s.attrIndex("class"),t=s.attrs?s.attrs.slice():[];e<0?t.push(["class",r.langPrefix+c]):(t[e]=t[e].slice(),t[e][1]+=" "+r.langPrefix+c);const n={attrs:t};return`<pre><code${i.renderAttrs(n)}>${a}</code></pre>\n`}return`<pre><code${i.renderAttrs(s)}>${a}</code></pre>\n`},default_rules.image=function(e,t,r,n,i){const s=e[t];return s.attrs[s.attrIndex("alt")][1]=i.renderInlineAsText(s.children,r,n),i.renderToken(e,t,r)},default_rules.hardbreak=function(e,t,r){return r.xhtmlOut?"<br />\n":"<br>\n"},default_rules.softbreak=function(e,t,r){return r.breaks?r.xhtmlOut?"<br />\n":"<br>\n":"\n"},
1191
1191
  default_rules.text=function(e,t){return escapeHtml$2(e[t].content)},default_rules.html_block=function(e,t){return e[t].content},default_rules.html_inline=function(e,t){return e[t].content},Renderer.prototype.renderAttrs=function(e){let t,r,n;if(!e.attrs)return"";for(n="",t=0,r=e.attrs.length;t<r;t++)n+=" "+escapeHtml$2(e.attrs[t][0])+'="'+escapeHtml$2(e.attrs[t][1])+'"';return n},Renderer.prototype.renderToken=function(e,t,r){const n=e[t];let i="";if(n.hidden)return"";n.block&&-1!==n.nesting&&t&&e[t-1].hidden&&(i+="\n"),i+=(-1===n.nesting?"</":"<")+n.tag,i+=this.renderAttrs(n),0===n.nesting&&r.xhtmlOut&&(i+=" /");let s=!1;if(n.block&&(s=!0,1===n.nesting&&t+1<e.length)){const r=e[t+1];("inline"===r.type||r.hidden||-1===r.nesting&&r.tag===n.tag)&&(s=!1)}return i+=s?">\n":">",i},Renderer.prototype.renderInline=function(e,t,r){let n="";const i=this.rules;for(let s=0,o=e.length;s<o;s++){const o=e[s].type;void 0!==i[o]?n+=i[o](e,s,t,r,this):n+=this.renderToken(e,s,t)}return n},
@@ -1196,7 +1196,7 @@ r.push(e)},this),this.__cache__=null,r},Ruler.prototype.enableOnly=function(e,t)
1196
1196
  const o=n[s];if("link_close"!==o.type){if("html_inline"===o.type&&(isLinkOpen$1(o.content)&&i>0&&i--,isLinkClose$1(o.content)&&i++),!(i>0)&&"text"===o.type&&e.md.linkify.test(o.content)){const i=o.content;let a=e.md.linkify.match(i);const c=[];let u=o.level,l=0;a.length>0&&0===a[0].index&&s>0&&"text_special"===n[s-1].type&&(a=a.slice(1));for(let t=0;t<a.length;t++){const r=a[t].url,n=e.md.normalizeLink(r);if(!e.md.validateLink(n))continue;let s=a[t].text;s=a[t].schema?"mailto:"!==a[t].schema||/^mailto:/i.test(s)?e.md.normalizeLinkText(s):e.md.normalizeLinkText("mailto:"+s).replace(/^mailto:/,""):e.md.normalizeLinkText("http://"+s).replace(/^http:\/\//,"");const o=a[t].index;if(o>l){const t=new e.Token("text","",0);t.content=i.slice(l,o),t.level=u,c.push(t)}const d=new e.Token("link_open","a",1);d.attrs=[["href",n]],d.level=u++,d.markup="linkify",d.info="auto",c.push(d);const p=new e.Token("text","",0);p.content=s,p.level=u,c.push(p);const h=new e.Token("link_close","a",-1);h.level=--u,
1197
1197
  h.markup="linkify",h.info="auto",c.push(h),l=a[t].lastIndex}if(l<i.length){const t=new e.Token("text","",0);t.content=i.slice(l),t.level=u,c.push(t)}t[r].children=n=arrayReplaceAt(n,s,c)}}else for(s--;n[s].level!==o.level&&"link_open"!==n[s].type;)s--}}}const RARE_RE=/\+-|\.\.|\?\?\?\?|!!!!|,,|--/,SCOPED_ABBR_TEST_RE=/\((c|tm|r)\)/i,SCOPED_ABBR_RE=/\((c|tm|r)\)/gi,SCOPED_ABBR={c:"©",r:"®",tm:"™"};function replaceFn(e,t){return SCOPED_ABBR[t.toLowerCase()]}function replace_scoped(e){let t=0;for(let r=e.length-1;r>=0;r--){const n=e[r];"text"!==n.type||t||(n.content=n.content.replace(SCOPED_ABBR_RE,replaceFn)),"link_open"===n.type&&"auto"===n.info&&t--,"link_close"===n.type&&"auto"===n.info&&t++}}function replace_rare(e){let t=0;for(let r=e.length-1;r>=0;r--){const n=e[r]
1198
1198
  ;"text"!==n.type||t||RARE_RE.test(n.content)&&(n.content=n.content.replace(/\+-/g,"±").replace(/\.{2,}/g,"…").replace(/([?!])…/g,"$1..").replace(/([?!]){4,}/g,"$1$1$1").replace(/,{2,}/g,",").replace(/(^|[^-])---(?=[^-]|$)/gm,"$1—").replace(/(^|\s)--(?=\s|$)/gm,"$1–").replace(/(^|[^-\s])--(?=[^-\s]|$)/gm,"$1–")),"link_open"===n.type&&"auto"===n.info&&t--,"link_close"===n.type&&"auto"===n.info&&t++}}function replace(e){let t;if(e.md.options.typographer)for(t=e.tokens.length-1;t>=0;t--)"inline"===e.tokens[t].type&&(SCOPED_ABBR_TEST_RE.test(e.tokens[t].content)&&replace_scoped(e.tokens[t].children),RARE_RE.test(e.tokens[t].content)&&replace_rare(e.tokens[t].children))}const QUOTE_TEST_RE=/['"]/,QUOTE_RE=/['"]/g,APOSTROPHE="’";function replaceAt(e,t,r){return e.slice(0,t)+r+e.slice(t+1)}function process_inlines(e,t){let r;const n=[];for(let i=0;i<e.length;i++){const s=e[i],o=e[i].level;for(r=n.length-1;r>=0&&!(n[r].level<=o);r--);if(n.length=r+1,"text"!==s.type)continue
1199
- ;let a=s.content,c=0,u=a.length;e:for(;c<u;){QUOTE_RE.lastIndex=c;const l=QUOTE_RE.exec(a);if(!l)break;let d=!0,p=!0;c=l.index+1;const h="'"===l[0];let A=32;if(l.index-1>=0)A=a.charCodeAt(l.index-1);else for(r=i-1;r>=0&&("softbreak"!==e[r].type&&"hardbreak"!==e[r].type);r--)if(e[r].content){A=e[r].content.charCodeAt(e[r].content.length-1);break}let f=32;if(c<u)f=a.charCodeAt(c);else for(r=i+1;r<e.length&&("softbreak"!==e[r].type&&"hardbreak"!==e[r].type);r++)if(e[r].content){f=e[r].content.charCodeAt(0);break}const g=isMdAsciiPunct(A)||isPunctChar(String.fromCharCode(A)),m=isMdAsciiPunct(f)||isPunctChar(String.fromCharCode(f)),y=isWhiteSpace(A),E=isWhiteSpace(f);if(E?d=!1:m&&(y||g||(d=!1)),y?p=!1:g&&(E||m||(p=!1)),34===f&&'"'===l[0]&&A>=48&&A<=57&&(p=d=!1),d&&p&&(d=g,p=m),d||p){if(p)for(r=n.length-1;r>=0;r--){let d=n[r];if(n[r].level<o)break;if(d.single===h&&n[r].level===o){let o,p;d=n[r],h?(o=t.md.options.quotes[2],p=t.md.options.quotes[3]):(o=t.md.options.quotes[0],
1199
+ ;let a=s.content,c=0,u=a.length;e:for(;c<u;){QUOTE_RE.lastIndex=c;const l=QUOTE_RE.exec(a);if(!l)break;let d=!0,p=!0;c=l.index+1;const h="'"===l[0];let A=32;if(l.index-1>=0)A=a.charCodeAt(l.index-1);else for(r=i-1;r>=0&&("softbreak"!==e[r].type&&"hardbreak"!==e[r].type);r--)if(e[r].content){A=e[r].content.charCodeAt(e[r].content.length-1);break}let f=32;if(c<u)f=a.charCodeAt(c);else for(r=i+1;r<e.length&&("softbreak"!==e[r].type&&"hardbreak"!==e[r].type);r++)if(e[r].content){f=e[r].content.charCodeAt(0);break}const g=isMdAsciiPunct(A)||isPunctChar(String.fromCharCode(A)),m=isMdAsciiPunct(f)||isPunctChar(String.fromCharCode(f)),y=isWhiteSpace$1(A),E=isWhiteSpace$1(f);if(E?d=!1:m&&(y||g||(d=!1)),y?p=!1:g&&(E||m||(p=!1)),34===f&&'"'===l[0]&&A>=48&&A<=57&&(p=d=!1),d&&p&&(d=g,p=m),d||p){if(p)for(r=n.length-1;r>=0;r--){let d=n[r];if(n[r].level<o)break;if(d.single===h&&n[r].level===o){let o,p;d=n[r],h?(o=t.md.options.quotes[2],p=t.md.options.quotes[3]):(o=t.md.options.quotes[0],
1200
1200
  p=t.md.options.quotes[1]),s.content=replaceAt(s.content,l.index,p),e[d.token].content=replaceAt(e[d.token].content,d.pos,o),c+=p.length-1,d.token===i&&(c+=o.length-1),a=s.content,u=a.length,n.length=r;continue e}}d?n.push({token:i,pos:l.index,single:h,level:o}):p&&h&&(s.content=replaceAt(s.content,l.index,APOSTROPHE))}else h&&(s.content=replaceAt(s.content,l.index,APOSTROPHE))}}}function smartquotes(e){if(e.md.options.typographer)for(let t=e.tokens.length-1;t>=0;t--)"inline"===e.tokens[t].type&&QUOTE_TEST_RE.test(e.tokens[t].content)&&process_inlines(e.tokens[t].children,e)}function text_join(e){let t,r;const n=e.tokens,i=n.length;for(let e=0;e<i;e++){if("inline"!==n[e].type)continue;const i=n[e].children,s=i.length;for(t=0;t<s;t++)"text_special"===i[t].type&&(i[t].type="text");for(t=r=0;t<s;t++)"text"===i[t].type&&t+1<s&&"text"===i[t+1].type?i[t+1].content=i[t].content+i[t+1].content:(t!==r&&(i[r]=i[t]),r++);t!==r&&(i.length=r)}}
1201
1201
  const _rules$2=[["normalize",normalize],["block",block$1],["inline",inline],["linkify",linkify$1],["replacements",replace],["smartquotes",smartquotes],["text_join",text_join]];function Core(){this.ruler=new Ruler;for(let e=0;e<_rules$2.length;e++)this.ruler.push(_rules$2[e][0],_rules$2[e][1])}function StateBlock(e,t,r,n){this.src=e,this.md=t,this.env=r,this.tokens=n,this.bMarks=[],this.eMarks=[],this.tShift=[],this.sCount=[],this.bsCount=[],this.blkIndent=0,this.line=0,this.lineMax=0,this.tight=!1,this.ddIndent=-1,this.listIndent=-1,this.parentType="root",this.level=0;const i=this.src;for(let e=0,t=0,r=0,n=0,s=i.length,o=!1;t<s;t++){const a=i.charCodeAt(t);if(!o){if(isSpace(a)){r++,9===a?n+=4-n%4:n++;continue}o=!0}10!==a&&t!==s-1||(10!==a&&t++,this.bMarks.push(e),this.eMarks.push(t),this.tShift.push(r),this.sCount.push(n),this.bsCount.push(0),o=!1,r=0,n=0,e=t+1)}this.bMarks.push(i.length),this.eMarks.push(i.length),this.tShift.push(0),this.sCount.push(0),this.bsCount.push(0),
1202
1202
  this.lineMax=this.bMarks.length-1}Core.prototype.process=function(e){const t=this.ruler.getRules("");for(let r=0,n=t.length;r<n;r++)t[r](e)},Core.prototype.State=StateCore,StateBlock.prototype.push=function(e,t,r){const n=new Token(e,t,r);return n.block=!0,r<0&&this.level--,n.level=this.level,r>0&&this.level++,this.tokens.push(n),n},StateBlock.prototype.isEmpty=function(e){return this.bMarks[e]+this.tShift[e]>=this.eMarks[e]},StateBlock.prototype.skipEmptyLines=function(e){for(let t=this.lineMax;e<t&&!(this.bMarks[e]+this.tShift[e]<this.eMarks[e]);e++);return e},StateBlock.prototype.skipSpaces=function(e){for(let t=this.src.length;e<t;e++){if(!isSpace(this.src.charCodeAt(e)))break}return e},StateBlock.prototype.skipSpacesBack=function(e,t){if(e<=t)return e;for(;e>t;)if(!isSpace(this.src.charCodeAt(--e)))return e+1;return e},StateBlock.prototype.skipChars=function(e,t){for(let r=this.src.length;e<r&&this.src.charCodeAt(e)===t;e++);return e},
@@ -1219,7 +1219,7 @@ if(t+2>r)return!1;let i=t+1;if(e.sCount[i]<e.blkIndent)return!1;if(e.sCount[i]-e
1219
1219
  const _rules$1=[["table",table$1,["paragraph","reference"]],["code",code],["fence",fence,["paragraph","reference","blockquote","list"]],["blockquote",blockquote,["paragraph","reference","blockquote","list"]],["hr",hr,["paragraph","reference","blockquote","list"]],["list",list,["paragraph","reference","blockquote"]],["reference",reference],["html_block",html_block,["paragraph","reference","blockquote"]],["heading",heading,["paragraph","reference","blockquote"]],["lheading",lheading],["paragraph",paragraph]];function ParserBlock(){this.ruler=new Ruler;for(let e=0;e<_rules$1.length;e++)this.ruler.push(_rules$1[e][0],_rules$1[e][1],{alt:(_rules$1[e][2]||[]).slice()})}function StateInline(e,t,r,n){this.src=e,this.env=r,this.md=t,this.tokens=n,this.tokens_meta=Array(n.length),this.pos=0,this.posMax=this.src.length,this.level=0,this.pending="",this.pendingLevel=0,this.cache={},this.delimiters=[],this._prev_delimiters=[],this.backticks={},this.backticksScanned=!1,this.linkLevel=0}
1220
1220
  function isTerminatorChar(e){switch(e){case 10:case 33:case 35:case 36:case 37:case 38:case 42:case 43:case 45:case 58:case 60:case 61:case 62:case 64:case 91:case 92:case 93:case 94:case 95:case 96:case 123:case 125:case 126:return!0;default:return!1}}function text(e,t){let r=e.pos;for(;r<e.posMax&&!isTerminatorChar(e.src.charCodeAt(r));)r++;return r!==e.pos&&(t||(e.pending+=e.src.slice(e.pos,r)),e.pos=r,!0)}ParserBlock.prototype.tokenize=function(e,t,r){const n=this.ruler.getRules(""),i=n.length,s=e.md.options.maxNesting;let o=t,a=!1;for(;o<r&&(e.line=o=e.skipEmptyLines(o),!(o>=r))&&!(e.sCount[o]<e.blkIndent);){if(e.level>=s){e.line=r;break}const t=e.line;let c=!1;for(let s=0;s<i;s++)if(c=n[s](e,o,r,!1),c){if(t>=e.line)throw new Error("block rule didn't increment state.line");break}if(!c)throw new Error("none of the block rules matched");e.tight=!a,e.isEmpty(e.line-1)&&(a=!0),o=e.line,o<r&&e.isEmpty(o)&&(a=!0,o++,e.line=o)}},ParserBlock.prototype.parse=function(e,t,r,n){if(!e)return
1221
1221
  ;const i=new this.State(e,t,r,n);this.tokenize(i,i.line,i.lineMax)},ParserBlock.prototype.State=StateBlock,StateInline.prototype.pushPending=function(){const e=new Token("text","",0);return e.content=this.pending,e.level=this.pendingLevel,this.tokens.push(e),this.pending="",e},StateInline.prototype.push=function(e,t,r){this.pending&&this.pushPending();const n=new Token(e,t,r);let i=null;return r<0&&(this.level--,this.delimiters=this._prev_delimiters.pop()),n.level=this.level,r>0&&(this.level++,this._prev_delimiters.push(this.delimiters),this.delimiters=[],i={delimiters:this.delimiters}),this.pendingLevel=this.level,this.tokens.push(n),this.tokens_meta.push(i),n},StateInline.prototype.scanDelims=function(e,t){const r=this.posMax,n=this.src.charCodeAt(e),i=e>0?this.src.charCodeAt(e-1):32;let s=e;for(;s<r&&this.src.charCodeAt(s)===n;)s++
1222
- ;const o=s-e,a=s<r?this.src.charCodeAt(s):32,c=isMdAsciiPunct(i)||isPunctChar(String.fromCharCode(i)),u=isMdAsciiPunct(a)||isPunctChar(String.fromCharCode(a)),l=isWhiteSpace(i),d=isWhiteSpace(a),p=!d&&(!u||l||c),h=!l&&(!c||d||u);return{can_open:p&&(t||!h||c),can_close:h&&(t||!p||u),length:o}},StateInline.prototype.Token=Token;const SCHEME_RE=/(?:^|[^a-z0-9.+-])([a-z][a-z0-9.+-]*)$/i;function linkify(e,t){if(!e.md.options.linkify)return!1;if(e.linkLevel>0)return!1;const r=e.pos;if(r+3>e.posMax)return!1;if(58!==e.src.charCodeAt(r))return!1;if(47!==e.src.charCodeAt(r+1))return!1;if(47!==e.src.charCodeAt(r+2))return!1;const n=e.pending.match(SCHEME_RE);if(!n)return!1;const i=n[1],s=e.md.linkify.matchAtStart(e.src.slice(r-i.length));if(!s)return!1;let o=s.url;if(o.length<=i.length)return!1;o=o.replace(/\*+$/,"");const a=e.md.normalizeLink(o);if(!e.md.validateLink(a))return!1;if(!t){e.pending=e.pending.slice(0,-i.length);const t=e.push("link_open","a",1);t.attrs=[["href",a]],
1222
+ ;const o=s-e,a=s<r?this.src.charCodeAt(s):32,c=isMdAsciiPunct(i)||isPunctChar(String.fromCharCode(i)),u=isMdAsciiPunct(a)||isPunctChar(String.fromCharCode(a)),l=isWhiteSpace$1(i),d=isWhiteSpace$1(a),p=!d&&(!u||l||c),h=!l&&(!c||d||u);return{can_open:p&&(t||!h||c),can_close:h&&(t||!p||u),length:o}},StateInline.prototype.Token=Token;const SCHEME_RE=/(?:^|[^a-z0-9.+-])([a-z][a-z0-9.+-]*)$/i;function linkify(e,t){if(!e.md.options.linkify)return!1;if(e.linkLevel>0)return!1;const r=e.pos;if(r+3>e.posMax)return!1;if(58!==e.src.charCodeAt(r))return!1;if(47!==e.src.charCodeAt(r+1))return!1;if(47!==e.src.charCodeAt(r+2))return!1;const n=e.pending.match(SCHEME_RE);if(!n)return!1;const i=n[1],s=e.md.linkify.matchAtStart(e.src.slice(r-i.length));if(!s)return!1;let o=s.url;if(o.length<=i.length)return!1;o=o.replace(/\*+$/,"");const a=e.md.normalizeLink(o);if(!e.md.validateLink(a))return!1;if(!t){e.pending=e.pending.slice(0,-i.length);const t=e.push("link_open","a",1);t.attrs=[["href",a]],
1223
1223
  t.markup="linkify",t.info="auto";e.push("text","",0).content=e.md.normalizeLinkText(o);const r=e.push("link_close","a",-1);r.markup="linkify",r.info="auto"}return e.pos+=o.length-i.length,!0}function newline(e,t){let r=e.pos;if(10!==e.src.charCodeAt(r))return!1;const n=e.pending.length-1,i=e.posMax;if(!t)if(n>=0&&32===e.pending.charCodeAt(n))if(n>=1&&32===e.pending.charCodeAt(n-1)){let t=n-1;for(;t>=1&&32===e.pending.charCodeAt(t-1);)t--;e.pending=e.pending.slice(0,t),e.push("hardbreak","br",0)}else e.pending=e.pending.slice(0,-1),e.push("softbreak","br",0);else e.push("softbreak","br",0);for(r++;r<i&&isSpace(e.src.charCodeAt(r));)r++;return e.pos=r,!0}const ESCAPED=[];for(let e=0;e<256;e++)ESCAPED.push(0);function escape$1(e,t){let r=e.pos;const n=e.posMax;if(92!==e.src.charCodeAt(r))return!1;if(r++,r>=n)return!1;let i=e.src.charCodeAt(r);if(10===i){for(t||e.push("hardbreak","br",0),r++;r<n&&(i=e.src.charCodeAt(r),isSpace(i));)r++;return e.pos=r,!0}let s=e.src[r]
1224
1224
  ;if(i>=55296&&i<=56319&&r+1<n){const t=e.src.charCodeAt(r+1);t>=56320&&t<=57343&&(s+=e.src[r+1],r++)}const o="\\"+s;if(!t){const t=e.push("text_special","",0);i<256&&0!==ESCAPED[i]?t.content=s:t.content=o,t.markup=o,t.info="escape"}return e.pos=r+1,!0}function backtick(e,t){let r=e.pos;if(96!==e.src.charCodeAt(r))return!1;const n=r;r++;const i=e.posMax;for(;r<i&&96===e.src.charCodeAt(r);)r++;const s=e.src.slice(n,r),o=s.length;if(e.backticksScanned&&(e.backticks[o]||0)<=n)return t||(e.pending+=s),e.pos+=o,!0;let a,c=r;for(;-1!==(a=e.src.indexOf("`",c));){for(c=a+1;c<i&&96===e.src.charCodeAt(c);)c++;const n=c-a;if(n===o){if(!t){const t=e.push("code_inline","code",0);t.markup=s,t.content=e.src.slice(r,a).replace(/\n/g," ").replace(/^ (.+) $/,"$1")}return e.pos=c,!0}e.backticks[n]=a}return e.backticksScanned=!0,t||(e.pending+=s),e.pos+=o,!0}function strikethrough_tokenize(e,t){const r=e.pos,n=e.src.charCodeAt(r);if(t)return!1;if(126!==n)return!1;const i=e.scanDelims(e.pos,!0)
1225
1225
  ;let s=i.length;const o=String.fromCharCode(n);if(s<2)return!1;let a;s%2&&(a=e.push("text","",0),a.content=o,s--);for(let t=0;t<s;t+=2)a=e.push("text","",0),a.content=o+o,e.delimiters.push({marker:n,length:0,token:e.tokens.length-1,end:-1,open:i.can_open,close:i.can_close});return e.pos+=i.length,!0}function postProcess$2(e,t){let r;const n=[],i=t.length;for(let s=0;s<i;s++){const i=t[s];if(126!==i.marker)continue;if(-1===i.end)continue;const o=t[i.end];r=e.tokens[i.token],r.type="s_open",r.tag="s",r.nesting=1,r.markup="~~",r.content="",r=e.tokens[o.token],r.type="s_close",r.tag="s",r.nesting=-1,r.markup="~~",r.content="","text"===e.tokens[o.token-1].type&&"~"===e.tokens[o.token-1].content&&n.push(o.token-1)}for(;n.length;){const t=n.pop();let i=t+1;for(;i<e.tokens.length&&"s_close"===e.tokens[i].type;)i++;i--,t!==i&&(r=e.tokens[i],e.tokens[i]=e.tokens[t],e.tokens[t]=r)}}function strikethrough_postProcess(e){const t=e.tokens_meta,r=e.tokens_meta.length;postProcess$2(e,e.delimiters)
@@ -1235,11 +1235,11 @@ const _rules=[["text",text],["linkify",linkify],["newline",newline],["escape",es
1235
1235
  t.src_ip4="(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)",t.src_auth="(?:(?:(?!"+t.src_ZCc+"|[@/\\[\\]()]).)+@)?",t.src_port="(?::(?:6(?:[0-4]\\d{3}|5(?:[0-4]\\d{2}|5(?:[0-2]\\d|3[0-5])))|[1-5]?\\d{1,4}))?",t.src_host_terminator="(?=$|[><|]|"+t.src_ZPCc+")(?!"+(e["---"]?"-(?!--)|":"-|")+"_|:\\d|\\.-|\\.(?!$|"+t.src_ZPCc+"))",t.src_path="(?:[/?#](?:(?!"+t.src_ZCc+"|"+r+"|[()[\\]{}.,\"'?!\\-;]).|\\[(?:(?!"+t.src_ZCc+"|\\]).)*\\]|\\((?:(?!"+t.src_ZCc+"|[)]).)*\\)|\\{(?:(?!"+t.src_ZCc+'|[}]).)*\\}|\\"(?:(?!'+t.src_ZCc+'|["]).)+\\"|\\\'(?:(?!'+t.src_ZCc+"|[']).)+\\'|\\'(?="+t.src_pseudo_letter+"|[-])|\\.{2,}[a-zA-Z0-9%/&]|\\.(?!"+t.src_ZCc+"|[.]|$)|"+(e["---"]?"\\-(?!--(?:[^-]|$))(?:-*)|":"\\-+|")+",(?!"+t.src_ZCc+"|$)|;(?!"+t.src_ZCc+"|$)|\\!+(?!"+t.src_ZCc+"|[!]|$)|\\?(?!"+t.src_ZCc+"|[?]|$))+|\\/)?",t.src_email_name='[\\-;:&=\\+\\$,\\.a-zA-Z0-9_][\\-;:&=\\+\\$,\\"\\.a-zA-Z0-9_]*',t.src_xn="xn--[a-z0-9\\-]{1,59}",
1236
1236
  t.src_domain_root="(?:"+t.src_xn+"|"+t.src_pseudo_letter+"{1,63})",t.src_domain="(?:"+t.src_xn+"|(?:"+t.src_pseudo_letter+")|(?:"+t.src_pseudo_letter+"(?:-|"+t.src_pseudo_letter+"){0,61}"+t.src_pseudo_letter+"))",t.src_host="(?:(?:(?:(?:"+t.src_domain+")\\.)*"+t.src_domain+"))",t.tpl_host_fuzzy="(?:"+t.src_ip4+"|(?:(?:(?:"+t.src_domain+")\\.)+(?:%TLDS%)))",t.tpl_host_no_ip_fuzzy="(?:(?:(?:"+t.src_domain+")\\.)+(?:%TLDS%))",t.src_host_strict=t.src_host+t.src_host_terminator,t.tpl_host_fuzzy_strict=t.tpl_host_fuzzy+t.src_host_terminator,t.src_host_port_strict=t.src_host+t.src_port+t.src_host_terminator,t.tpl_host_port_fuzzy_strict=t.tpl_host_fuzzy+t.src_port+t.src_host_terminator,t.tpl_host_port_no_ip_fuzzy_strict=t.tpl_host_no_ip_fuzzy+t.src_port+t.src_host_terminator,t.tpl_host_fuzzy_test="localhost|www\\.|\\.\\d{1,3}\\.|(?:\\.(?:%TLDS%)(?:"+t.src_ZPCc+"|>|$))",t.tpl_email_fuzzy='(^|[><|]|"|\\(|'+t.src_ZCc+")("+t.src_email_name+"@"+t.tpl_host_fuzzy_strict+")",
1237
1237
  t.tpl_link_fuzzy="(^|(?![.:/\\-_@])(?:[$+<=>^`||]|"+t.src_ZPCc+"))((?![$+<=>^`||])"+t.tpl_host_port_fuzzy_strict+t.src_path+")",t.tpl_link_no_ip_fuzzy="(^|(?![.:/\\-_@])(?:[$+<=>^`||]|"+t.src_ZPCc+"))((?![$+<=>^`||])"+t.tpl_host_port_no_ip_fuzzy_strict+t.src_path+")",t}function assign$1(e){return Array.prototype.slice.call(arguments,1).forEach(function(t){t&&Object.keys(t).forEach(function(r){e[r]=t[r]})}),e}function _class(e){return Object.prototype.toString.call(e)}function isString$1(e){return"[object String]"===_class(e)}function isObject$4(e){return"[object Object]"===_class(e)}function isRegExp(e){return"[object RegExp]"===_class(e)}function isFunction$2(e){return"[object Function]"===_class(e)}function escapeRE(e){return e.replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}ParserInline.prototype.skipToken=function(e){const t=e.pos,r=this.ruler.getRules(""),n=r.length,i=e.md.options.maxNesting,s=e.cache;if(void 0!==s[t])return void(e.pos=s[t]);let o=!1;if(e.level<i){
1238
- for(let i=0;i<n;i++)if(e.level++,o=r[i](e,!0),e.level--,o){if(t>=e.pos)throw new Error("inline rule didn't increment state.pos");break}}else e.pos=e.posMax;o||e.pos++,s[t]=e.pos},ParserInline.prototype.tokenize=function(e){const t=this.ruler.getRules(""),r=t.length,n=e.posMax,i=e.md.options.maxNesting;for(;e.pos<n;){const s=e.pos;let o=!1;if(e.level<i)for(let n=0;n<r;n++)if(o=t[n](e,!1),o){if(s>=e.pos)throw new Error("inline rule didn't increment state.pos");break}if(o){if(e.pos>=n)break}else e.pending+=e.src[e.pos++]}e.pending&&e.pushPending()},ParserInline.prototype.parse=function(e,t,r,n){const i=new this.State(e,t,r,n);this.tokenize(i);const s=this.ruler2.getRules(""),o=s.length;for(let e=0;e<o;e++)s[e](i)},ParserInline.prototype.State=StateInline;const defaultOptions$2={fuzzyLink:!0,fuzzyEmail:!0,fuzzyIP:!1};function isOptionsObj(e){return Object.keys(e||{}).reduce(function(e,t){return e||defaultOptions$2.hasOwnProperty(t)},!1)}const defaultSchemas={"http:":{
1238
+ for(let i=0;i<n;i++)if(e.level++,o=r[i](e,!0),e.level--,o){if(t>=e.pos)throw new Error("inline rule didn't increment state.pos");break}}else e.pos=e.posMax;o||e.pos++,s[t]=e.pos},ParserInline.prototype.tokenize=function(e){const t=this.ruler.getRules(""),r=t.length,n=e.posMax,i=e.md.options.maxNesting;for(;e.pos<n;){const s=e.pos;let o=!1;if(e.level<i)for(let n=0;n<r;n++)if(o=t[n](e,!1),o){if(s>=e.pos)throw new Error("inline rule didn't increment state.pos");break}if(o){if(e.pos>=n)break}else e.pending+=e.src[e.pos++]}e.pending&&e.pushPending()},ParserInline.prototype.parse=function(e,t,r,n){const i=new this.State(e,t,r,n);this.tokenize(i);const s=this.ruler2.getRules(""),o=s.length;for(let e=0;e<o;e++)s[e](i)},ParserInline.prototype.State=StateInline;const defaultOptions$4={fuzzyLink:!0,fuzzyEmail:!0,fuzzyIP:!1};function isOptionsObj(e){return Object.keys(e||{}).reduce(function(e,t){return e||defaultOptions$4.hasOwnProperty(t)},!1)}const defaultSchemas={"http:":{
1239
1239
  validate:function(e,t,r){const n=e.slice(t);return r.re.http||(r.re.http=new RegExp("^\\/\\/"+r.re.src_auth+r.re.src_host_port_strict+r.re.src_path,"i")),r.re.http.test(n)?n.match(r.re.http)[0].length:0}},"https:":"http:","ftp:":"http:","//":{validate:function(e,t,r){const n=e.slice(t);return r.re.no_http||(r.re.no_http=new RegExp("^"+r.re.src_auth+"(?:localhost|(?:(?:"+r.re.src_domain+")\\.)+"+r.re.src_domain_root+")"+r.re.src_port+r.re.src_host_terminator+r.re.src_path,"i")),r.re.no_http.test(n)?t>=3&&":"===e[t-3]||t>=3&&"/"===e[t-3]?0:n.match(r.re.no_http)[0].length:0}},"mailto:":{validate:function(e,t,r){const n=e.slice(t);return r.re.mailto||(r.re.mailto=new RegExp("^"+r.re.src_email_name+"@"+r.re.src_host_strict,"i")),r.re.mailto.test(n)?n.match(r.re.mailto)[0].length:0}}
1240
1240
  },tlds_2ch_src_re="a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvwxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvxyz]|t[cdfghjklmnortvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]",tlds_default="biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф".split("|");function resetScanCache(e){e.__index__=-1,e.__text_cache__=""}function createValidator(e){return function(t,r){const n=t.slice(r);return e.test(n)?n.match(e)[0].length:0}}function createNormalizer(){return function(e,t){t.normalize(e)}}function compile$1(e){const t=e.re=reFactory(e.__opts__),r=e.__tlds__.slice();function n(e){return e.replace("%TLDS%",t.src_tlds)}e.onCompile(),e.__tlds_replaced__||r.push(tlds_2ch_src_re),r.push(t.src_xn),t.src_tlds=r.join("|"),t.email_fuzzy=RegExp(n(t.tpl_email_fuzzy),"i"),
1241
1241
  t.link_fuzzy=RegExp(n(t.tpl_link_fuzzy),"i"),t.link_no_ip_fuzzy=RegExp(n(t.tpl_link_no_ip_fuzzy),"i"),t.host_fuzzy_test=RegExp(n(t.tpl_host_fuzzy_test),"i");const i=[];function s(e,t){throw new Error('(LinkifyIt) Invalid schema "'+e+'": '+t)}e.__compiled__={},Object.keys(e.__schemas__).forEach(function(t){const r=e.__schemas__[t];if(null===r)return;const n={validate:null,link:null};if(e.__compiled__[t]=n,isObject$4(r))return isRegExp(r.validate)?n.validate=createValidator(r.validate):isFunction$2(r.validate)?n.validate=r.validate:s(t,r),void(isFunction$2(r.normalize)?n.normalize=r.normalize:r.normalize?s(t,r):n.normalize=createNormalizer());isString$1(r)?i.push(t):s(t,r)}),i.forEach(function(t){e.__compiled__[e.__schemas__[t]]&&(e.__compiled__[t].validate=e.__compiled__[e.__schemas__[t]].validate,e.__compiled__[t].normalize=e.__compiled__[e.__schemas__[t]].normalize)}),e.__compiled__[""]={validate:null,normalize:createNormalizer()}
1242
- ;const o=Object.keys(e.__compiled__).filter(function(t){return t.length>0&&e.__compiled__[t]}).map(escapeRE).join("|");e.re.schema_test=RegExp("(^|(?!_)(?:[><|]|"+t.src_ZPCc+"))("+o+")","i"),e.re.schema_search=RegExp("(^|(?!_)(?:[><|]|"+t.src_ZPCc+"))("+o+")","ig"),e.re.schema_at_start=RegExp("^"+e.re.schema_search.source,"i"),e.re.pretest=RegExp("("+e.re.schema_test.source+")|("+e.re.host_fuzzy_test.source+")|@","i"),resetScanCache(e)}function Match(e,t){const r=e.__index__,n=e.__last_index__,i=e.__text_cache__.slice(r,n);this.schema=e.__schema__.toLowerCase(),this.index=r+t,this.lastIndex=n+t,this.raw=i,this.text=i,this.url=i}function createMatch(e,t){const r=new Match(e,t);return e.__compiled__[r.schema].normalize(r,e),r}function LinkifyIt(e,t){if(!(this instanceof LinkifyIt))return new LinkifyIt(e,t);t||isOptionsObj(e)&&(t=e,e={}),this.__opts__=assign$1({},defaultOptions$2,t),this.__index__=-1,this.__last_index__=-1,this.__schema__="",this.__text_cache__="",
1242
+ ;const o=Object.keys(e.__compiled__).filter(function(t){return t.length>0&&e.__compiled__[t]}).map(escapeRE).join("|");e.re.schema_test=RegExp("(^|(?!_)(?:[><|]|"+t.src_ZPCc+"))("+o+")","i"),e.re.schema_search=RegExp("(^|(?!_)(?:[><|]|"+t.src_ZPCc+"))("+o+")","ig"),e.re.schema_at_start=RegExp("^"+e.re.schema_search.source,"i"),e.re.pretest=RegExp("("+e.re.schema_test.source+")|("+e.re.host_fuzzy_test.source+")|@","i"),resetScanCache(e)}function Match(e,t){const r=e.__index__,n=e.__last_index__,i=e.__text_cache__.slice(r,n);this.schema=e.__schema__.toLowerCase(),this.index=r+t,this.lastIndex=n+t,this.raw=i,this.text=i,this.url=i}function createMatch(e,t){const r=new Match(e,t);return e.__compiled__[r.schema].normalize(r,e),r}function LinkifyIt(e,t){if(!(this instanceof LinkifyIt))return new LinkifyIt(e,t);t||isOptionsObj(e)&&(t=e,e={}),this.__opts__=assign$1({},defaultOptions$4,t),this.__index__=-1,this.__last_index__=-1,this.__schema__="",this.__text_cache__="",
1243
1243
  this.__schemas__=assign$1({},defaultSchemas,e),this.__compiled__={},this.__tlds__=tlds_default,this.__tlds_replaced__=!1,this.re={},compile$1(this)}LinkifyIt.prototype.add=function(e,t){return this.__schemas__[e]=t,compile$1(this),this},LinkifyIt.prototype.set=function(e){return this.__opts__=assign$1(this.__opts__,e),this},LinkifyIt.prototype.test=function(e){if(this.__text_cache__=e,this.__index__=-1,!e.length)return!1;let t,r,n,i,s,o,a,c,u;if(this.re.schema_test.test(e))for(a=this.re.schema_search,a.lastIndex=0;null!==(t=a.exec(e));)if(i=this.testSchemaAt(e,t[2],a.lastIndex),i){this.__schema__=t[2],this.__index__=t.index+t[1].length,this.__last_index__=t.index+t[0].length+i;break}return this.__opts__.fuzzyLink&&this.__compiled__["http:"]&&(c=e.search(this.re.host_fuzzy_test),c>=0&&(this.__index__<0||c<this.__index__)&&null!==(r=e.match(this.__opts__.fuzzyIP?this.re.link_fuzzy:this.re.link_no_ip_fuzzy))&&(s=r.index+r[1].length,
1244
1244
  (this.__index__<0||s<this.__index__)&&(this.__schema__="",this.__index__=s,this.__last_index__=r.index+r[0].length))),this.__opts__.fuzzyEmail&&this.__compiled__["mailto:"]&&(u=e.indexOf("@"),u>=0&&null!==(n=e.match(this.re.email_fuzzy))&&(s=n.index+n[1].length,o=n.index+n[0].length,(this.__index__<0||s<this.__index__||s===this.__index__&&o>this.__last_index__)&&(this.__schema__="mailto:",this.__index__=s,this.__last_index__=o))),this.__index__>=0},LinkifyIt.prototype.pretest=function(e){return this.re.pretest.test(e)},LinkifyIt.prototype.testSchemaAt=function(e,t,r){return this.__compiled__[t.toLowerCase()]?this.__compiled__[t.toLowerCase()].validate(e,r,this):0},LinkifyIt.prototype.match=function(e){const t=[];let r=0;this.__index__>=0&&this.__text_cache__===e&&(t.push(createMatch(this,r)),r=this.__last_index__);let n=r?e.slice(r):e;for(;this.test(n);)t.push(createMatch(this,r)),n=n.slice(this.__last_index__),r+=this.__last_index__;return t.length?t:null},
1245
1245
  LinkifyIt.prototype.matchAtStart=function(e){if(this.__text_cache__=e,this.__index__=-1,!e.length)return null;const t=this.re.schema_at_start.exec(e);if(!t)return null;const r=this.testSchemaAt(e,t[2],t[0].length);return r?(this.__schema__=t[2],this.__index__=t.index+t[1].length,this.__last_index__=t.index+t[0].length+r,createMatch(this,0)):null},LinkifyIt.prototype.tlds=function(e,t){return e=Array.isArray(e)?e:[e],t?(this.__tlds__=this.__tlds__.concat(e).sort().filter(function(e,t,r){return e!==r[t-1]}).reverse(),compile$1(this),this):(this.__tlds__=e.slice(),this.__tlds_replaced__=!0,compile$1(this),this)},LinkifyIt.prototype.normalize=function(e){e.schema||(e.url="http://"+e.url),"mailto:"!==e.schema||/^mailto:/i.test(e.url)||(e.url="mailto:"+e.url)},LinkifyIt.prototype.onCompile=function(){}
@@ -1265,10 +1265,10 @@ switch(typeof o[e]){case"boolean":case"number":case"string":if(u[e]!==o[e])retur
1265
1265
  }(i,n)),e.children.push(function(e){return new e("label_close","label",-1)}(n)),e.children.unshift(function(e,t,r,n){var i=new n("checkbox_input","input",0);i.attrs=[["type","checkbox"],["id",t]];var s=/^\[[xX]\][ \u00A0]/.test(e.content);!0===s&&i.attrs.push(["checked","true"]);!0===r.disabled&&i.attrs.push(["disabled","true"]);return i}(e,i,r,n)),r.divWrap&&(e.children.unshift(function(e,t){var r=new t("checkbox_open","div",0);return r.attrs=[["class",e.divClass]],r}(r,n)),e.children.push(function(e){var t=new e("checkbox_close","div",-1);return t}(n)))}return hasRequiredMarkdownItTaskCheckbox=1,markdownItTaskCheckbox=function(i,s){var o;o={disabled:!0,divWrap:!1,divClass:"checkbox",idPrefix:"cbx_",ulClass:"task-list",liClass:"task-list-item"},s=Object.assign({},o,s),i.core.ruler.after("inline","github-task-lists",function(i){for(var o=i.tokens,a=0,c=2;c<o.length;c++)r(o,c)&&(n(o[c],a,s,i.Token),a+=1,e(o[c-2],"class",s.liClass),e(o[t(o,c-2)],"class",s.ulClass))})},
1266
1266
  markdownItTaskCheckbox}var markdownItTaskCheckboxExports=requireMarkdownItTaskCheckbox(),mic=getDefaultExportFromCjs(markdownItTaskCheckboxExports);function _nullishCoalesce$N(e,t){return null!=e?e:t()}function _optionalChain$X(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}const mdi=new MarkdownIt({breaks:!0}).use(markdownItAttrs,{allowedAttributes:["id","class"]}).use(mic,{ulClass:"",liClass:""}),renderTokenOriginal=mdi.renderer.renderToken.bind(mdi.renderer);function markdownToHtml(e){return mdi.render(e)}function _nullishCoalesce$M(e,t){return null!=e?e:t()}function _optionalChain$W(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,
1267
1267
  r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}mdi.renderer.renderToken=(e,t,r)=>{const n=e[t];if(n.map&&1===n.nesting){const[e,t]=n.map;n.attrSet("data-source-lines",`${e+1}-${t}`)}return renderTokenOriginal(e,t,r)},mdi.renderer.rules.fence=(e,t,r,n,i)=>{const s=e[t],[o,a]=_nullishCoalesce$N(_optionalChain$X([s,"optionalAccess",e=>e.map]),()=>[0,0]),c=s.info.trim().split(/\s+/)[0],u=`data-source-lines="${o+1}-${a}"`,l=[c?`language-${c}`:"",s.attrGet("class")||""].filter(Boolean).join(" ");l&&s.attrSet("class",l);return`<pre><code ${u}${i.renderAttrs(s)}>${s.content}</code></pre>\n`};const SPEC_FILE_EXTENSION=".spec.md",SPECIAL_LINK_TEXTS=["@describe","@generate","@use","@test"];function specFromMarkdown(e){return specFromDom(parseHtml(markdownToHtml(e)))}function specFromDom(e){const t=createSections(e);return decorateTestLinks(t),decorateTests(t),decorateUseLinks(t),decorateGenerateLinks(t),decorateDescribeLinks(t),t}
1268
- function decorateTestLinks(e){for(const t of e.querySelectorAll("a"))"@test"===t.text&&t.classList.add("test")}function decorateUseLinks(e){for(const t of e.querySelectorAll("a"))"@use"===t.text&&t.classList.add("use")}function decorateGenerateLinks(e){for(const t of e.querySelectorAll("a"))"@generate"===t.text&&t.classList.add("generate")}function decorateDescribeLinks(e){for(const t of e.querySelectorAll("a"))"@describe"===t.text&&t.classList.add("describe")}function decorateTests(e){for(const t of e.querySelectorAll("a.test"))_optionalChain$W([findParent,"call",e=>e(t,["LI"],["UL","OL"]),"optionalAccess",e=>e.classList,"access",e=>e.add,"call",e=>e("test")]);for(const t of e.querySelectorAll(".locked,.impl")){const e=t.classList.contains("locked"),r=t.classList.contains("impl");t.querySelectorAll("a.test").forEach(t=>{e&&t.classList.add("locked"),r&&t.classList.add("impl")})}for(const t of e.querySelectorAll("a.test:not(.locked):not(.impl)"))t.classList.add("draft")}
1269
- function getApi(e){const t=e.querySelectorAll("code.api");if(0===t.length)throw new Error("Api not found");return t.map(e=>e.innerHTML)}function findApi(e){try{return getApi(e)}catch(e){return[]}}function getUsePaths(e){const t=e.querySelectorAll(".use").map(e=>{if(!_optionalChain$W([e,"access",e=>e.attributes,"access",e=>e.href,"optionalAccess",e=>e.toString,"call",e=>e()]))throw new Error("The @use link is empty");return _optionalChain$W([e,"access",e=>e.attributes,"access",e=>e.href,"optionalAccess",e=>e.toString,"call",e=>e()])});if(new Set(t).size!==t.length)throw new Error("Duplicate @use links found");return t}function findGeneratePaths(e){return e.querySelectorAll(".generate").reduce((e,t)=>(_optionalChain$W([t,"access",e=>e.attributes,"access",e=>e.href,"optionalAccess",e=>e.toString,"call",e=>e()])&&e.push(_optionalChain$W([t,"access",e=>e.attributes,"access",e=>e.href,"optionalAccess",e=>e.toString,"call",e=>e()])),e),[])}function findDescribePaths(e){
1270
- return e.querySelectorAll(".describe").reduce((e,t)=>(_optionalChain$W([t,"access",e=>e.attributes,"access",e=>e.href,"optionalAccess",e=>e.toString,"call",e=>e()])&&e.push(_optionalChain$W([t,"access",e=>e.attributes,"access",e=>e.href,"optionalAccess",e=>e.toString,"call",e=>e()])),e),[])}function findImplementationPaths(e){return{describe:findDescribePaths(e),generate:findGeneratePaths(e)}}function findTests(e){const t=[];for(const r of e.querySelectorAll("a.test")){const e={path:r.attributes.href&&"#"!==r.attributes.href?r.attributes.href:"",sourceLines:findSourceLines(r),kind:testElementKind(r)};t.push(e)}return t}function findSourceLines(e){let t=e;for(;null!==t;){if("data-source-lines"in t.attributes)return t.attributes["data-source-lines"];t=t.parentNode}}function testElementKind(e){if(e.classList.contains("locked"))return"locked";if(e.classList.contains("impl"))return"impl";if(e.classList.contains("draft"))return"draft"
1271
- ;throw new Error(`Unknown test kind for element: ${e.outerHTML}`)}function findTestPaths(e,t){let r=findTests(e);return t&&(r=r.filter(e=>e.kind===t)),r.map(e=>e.path)}function findTest(e,t){const r=findTests(e).find(e=>e.path===t);if(!r)throw new Error(`Test not found: ${t}`);return r}function findParentSection(e,t){return _nullishCoalesce$M(e.closest(`.${t}`),()=>{})}function findAllLinks(e){const t=[];for(const r of e.querySelectorAll("a[href]")){const e=_optionalChain$W([r,"access",e=>e.textContent,"optionalAccess",e=>e.trim,"call",e=>e()]),n=_optionalChain$W([r,"access",e=>e.getAttribute,"call",e=>e("href"),"optionalAccess",e=>e.trim,"call",e=>e()]);e&&n&&(n.startsWith("#")||t.push({text:e,href:n}))}return t}function findRegularLinks(e){return findAllLinks(e).filter(e=>!SPECIAL_LINK_TEXTS.includes(e.text))}function pluralize$1(e,t){if(1===t)return e;const r=new Set(["fish"]),n=e.toLowerCase();if(r.has(n))return e;const i={child:"children",person:"people",mouse:"mice"}[n]
1268
+ function decorateTestLinks(e){for(const t of e.querySelectorAll("a"))"@test"===t.text&&t.classList.add("test")}function decorateUseLinks(e){for(const t of e.querySelectorAll("a"))"@use"===t.text&&t.classList.add("use")}function decorateGenerateLinks(e){for(const t of e.querySelectorAll("a"))"@generate"===t.text&&t.classList.add("generate")}function decorateDescribeLinks(e){for(const t of e.querySelectorAll("a"))"@describe"===t.text&&t.classList.add("describe")}function decorateTests(e){for(const t of e.querySelectorAll("a.test"))_optionalChain$W([findParent,"call",e=>e(t,["LI"],["UL","OL"]),"optionalAccess",e=>e.classList,"access",e=>e.add,"call",e=>e("test")]);for(const t of e.querySelectorAll(".locked"))t.querySelectorAll("a.test").forEach(e=>{e.classList.add("locked")});for(const t of e.querySelectorAll("a.test:not(.locked)"))t.classList.add("draft")}function getApi(e){const t=e.querySelectorAll("code.api");if(0===t.length)throw new Error("Api not found")
1269
+ ;return t.map(e=>e.innerHTML)}function findApi(e){try{return getApi(e)}catch(e){return[]}}function getUsePaths(e){const t=e.querySelectorAll(".use").map(e=>{if(!_optionalChain$W([e,"access",e=>e.attributes,"access",e=>e.href,"optionalAccess",e=>e.toString,"call",e=>e()]))throw new Error("The @use link is empty");return _optionalChain$W([e,"access",e=>e.attributes,"access",e=>e.href,"optionalAccess",e=>e.toString,"call",e=>e()])});if(new Set(t).size!==t.length)throw new Error("Duplicate @use links found");return t}function findGeneratePaths(e){return e.querySelectorAll(".generate").reduce((e,t)=>(_optionalChain$W([t,"access",e=>e.attributes,"access",e=>e.href,"optionalAccess",e=>e.toString,"call",e=>e()])&&e.push(_optionalChain$W([t,"access",e=>e.attributes,"access",e=>e.href,"optionalAccess",e=>e.toString,"call",e=>e()])),e),[])}function findDescribePaths(e){
1270
+ return e.querySelectorAll(".describe").reduce((e,t)=>(_optionalChain$W([t,"access",e=>e.attributes,"access",e=>e.href,"optionalAccess",e=>e.toString,"call",e=>e()])&&e.push(_optionalChain$W([t,"access",e=>e.attributes,"access",e=>e.href,"optionalAccess",e=>e.toString,"call",e=>e()])),e),[])}function findImplementationPaths(e){return{describe:findDescribePaths(e),generate:findGeneratePaths(e)}}function findTests(e){const t=[];for(const r of e.querySelectorAll("a.test")){const e={path:r.attributes.href&&"#"!==r.attributes.href?r.attributes.href:"",sourceLines:findSourceLines(r),kind:testElementKind(r)};t.push(e)}return t}function findSourceLines(e){let t=e;for(;null!==t;){if("data-source-lines"in t.attributes)return t.attributes["data-source-lines"];t=t.parentNode}}function testElementKind(e){if(e.classList.contains("locked"))return"locked";if(e.classList.contains("draft"))return"draft";throw new Error(`Unknown test kind for element: ${e.outerHTML}`)}function findTestPaths(e,t){
1271
+ let r=findTests(e);return t&&(r=r.filter(e=>e.kind===t)),r.map(e=>e.path)}function findTest(e,t){const r=findTests(e).find(e=>e.path===t);if(!r)throw new Error(`Test not found: ${t}`);return r}function findParentSection(e,t){return _nullishCoalesce$M(e.closest(`.${t}`),()=>{})}function findAllLinks(e){const t=[];for(const r of e.querySelectorAll("a[href]")){const e=_optionalChain$W([r,"access",e=>e.textContent,"optionalAccess",e=>e.trim,"call",e=>e()]),n=_optionalChain$W([r,"access",e=>e.getAttribute,"call",e=>e("href"),"optionalAccess",e=>e.trim,"call",e=>e()]);e&&n&&(n.startsWith("#")||t.push({text:e,href:n}))}return t}function findRegularLinks(e){return findAllLinks(e).filter(e=>!SPECIAL_LINK_TEXTS.includes(e.text))}function pluralize$1(e,t){if(1===t)return e;const r=new Set(["fish"]),n=e.toLowerCase();if(r.has(n))return e;const i={child:"children",person:"people",mouse:"mice"}[n]
1272
1272
  ;return void 0!==i?i:n.endsWith("y")&&n.length>1&&!/[aeiou]/.test(n.charAt(n.length-2))?e.slice(0,-1)+"ies":n.endsWith("ch")||n.endsWith("sh")||["s","x","z"].some(e=>n.endsWith(e))?e+"es":n.endsWith("fe")?e.slice(0,-2)+"ves":n.endsWith("f")?e.slice(0,-1)+"ves":e+"s"}function stripSurroundingQuotes(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}const FRAMEWORK=DEFAULT_TESSL_DIRS.frameworkDirectory.replace(/\\/g,"/"),FRAMEWORK_HOOK=Object.freeze({targetFile:AGENTS_MD_FILENAME,expected:`@${FRAMEWORK}/agents.md`,snippet:`\n # Tessl & Spec Driven Development \x3c!-- tessl-managed --\x3e\n\nThis project uses the [Tessl spec driven development framework](${FRAMEWORK}/agents.md) and toolkit for software development: @${FRAMEWORK}/agents.md\n`}),KNOWLEDGE_HOOK=Object.freeze({targetFile:AGENTS_MD_FILENAME,expected:"(./KNOWLEDGE.md)",
1273
1273
  snippet:"# Knowledge Index \x3c!-- tessl-managed --\x3e\n\nDocumentation for dependencies and processes can be found in the [Knowledge Index](./KNOWLEDGE.md)\n"}),PLAN_FILES_HOOK=Object.freeze({targetFile:AGENTS_MD_FILENAME,expected:`@${FRAMEWORK}/plan-files.md`,snippet:`# Plan Files \x3c!-- tessl-managed --\x3e\n\nALWAYS create [plan files](${FRAMEWORK}/plan-files.md) when planning: @${FRAMEWORK}/plan-files.md\n`}),BOOTSTRAP_HOOK=Object.freeze({targetFile:AGENTS_MD_FILENAME,expected:`@${FRAMEWORK}/bootstrap.md`,snippet:`# Project Bootstrapping \x3c!-- tessl-managed --\x3e\n\n\x3c!-- Replace this section with a description of the language(s), test framework(s) and project directory structure. --\x3e\n\nRun the [bootstrap process](${FRAMEWORK}/bootstrap.md) to set up the project: @${FRAMEWORK}/bootstrap.md\n`}),USAGE_SPECS_HOOK=Object.freeze({targetFile:AGENTS_MD_FILENAME,expected:`@${FRAMEWORK}/usage-specs.md`,
1274
1274
  snippet:`# Usage Specs \x3c!-- tessl-managed --\x3e\n\n[Usage specs](${FRAMEWORK}/usage-specs.md) provide important context for third-party dependencies: @${FRAMEWORK}/usage-specs.md\n`}),REQUIRED_TESSL_FRAMEWORK_HOOKS=[FRAMEWORK_HOOK],RECOMMENDED_TESSL_FRAMEWORK_HOOKS=[KNOWLEDGE_HOOK,PLAN_FILES_HOOK],ALL_TESSL_FRAMEWORK_HOOKS=[...REQUIRED_TESSL_FRAMEWORK_HOOKS,...RECOMMENDED_TESSL_FRAMEWORK_HOOKS,BOOTSTRAP_HOOK],KNOWLEDGE_ONLY_HOOKS=[USAGE_SPECS_HOOK,KNOWLEDGE_HOOK],DEFAULT_AGENTS_MD_CONTENT="# Project\n\n";function ensureAgentsMd(e){const t=path__default.resolve(e,AGENTS_MD_FILENAME);if(!fs$8.existsSync(t)){fs$8.writeFileSync(t,DEFAULT_AGENTS_MD_CONTENT);return[path__default.relative(e,t)]}return[]}function addAgentsMdHooks(e,t){const r=[];for(const n of t){const{targetFile:t,expected:i,snippet:s}=n,o=path__default.resolve(e,t),a=fs$8.readFileSync(o,"utf8");if(!a.includes(i)){const t=`${a.trimEnd()}\n\n${s.trim()}`;fs$8.writeFileSync(o,t);const n=path__default.relative(e,o);r.push(n)
@@ -1284,7 +1284,7 @@ const VERSION_PATTERN=".*",FILE_PATH_PATTERN=".*",HASH_TAG_PATTERN="\\((?:spec|c
1284
1284
  ;function extractCodeTag(e){return e.match(CODE_TAG_REGEX)}function calculateCodeHash(e){const t=removeGeneratedCodeTag(e).trim();return createHash("md5").update(t).digest("hex").substring(0,8)}function removeGeneratedCodeTag(e){const t=extractCodeTag(e);if(t){let r=e.replace(t[0],"");return r=r.trim(),r}return e}function addOrReplaceGeneratedCodeComment(e,t,r,n,i=!1){const{version:s}=getSysinfo(),o="unknown"===s?"(local)":s,a={spec:r?calculateSpecHash(r):void 0,code:calculateCodeHash(e)},c=detectLanguage(n||t);if(!c)return e;const u=extractCodeTag(e),l=["GENERATED FROM SPEC - DO NOT EDIT",`@generated with Tessl ${o} from ${t}`];if(l.push(Object.entries(a).filter(([,e])=>e).map(([e,t])=>`(${e}:${t})`).join(" ")),i){const e=(new Date).toISOString().split("T")[0];l.push(`User stamped this file as up-to-date on ${e}`)}let d;if("html"===c.key||"xml"===c.key)d=l.map(e=>`\x3c!-- ${e} --\x3e`).join("\n");else{if(!c.comments.single)return e;{const e=c.comments.single
1285
1285
  ;d=l.map(t=>`${e} ${t}`).join("\n")}}if(d!==_optionalChain$V([extractCodeTag,"call",e=>e(d),"optionalAccess",e=>e[0]]))throw new Error(`Generated comment does not match the expected format: ${d}`);return u?e.replace(u[0],d):d+"\n\n"+e}function extractSpecHash(e){return _optionalChain$V([e.match(/\(spec:([a-f0-9]{8})\)/),"optionalAccess",e=>e[1]])}function extractCodeHash(e){return _optionalChain$V([e.match(/\(code:([a-f0-9]{8})\)/),"optionalAccess",e=>e[1]])}function isCodeFileDirty(e){const t=extractCodeHash(e);if(!t)return!1;return t!==calculateCodeHash(e)}function getCodeStatus(e,t){if(!t)return"missing";const r=isCodeFileDirty(t),n=extractSpecHash(t)!==e;return r&&n?"dirty-outdated":r?"dirty-up-to-date":n?"outdated":"up-to-date"}var GenerateOption;!function(e){e.never="never";e.missing="missing";e.outdated="outdated";e.dirty="dirty";e.always="always"}(GenerateOption||(GenerateOption={}));const common$4={
1286
1286
  generate:()=>z.array(z.nativeEnum(GenerateOption)).transform(e=>Array.from(new Set(e))).refine(e=>!e.includes(GenerateOption.never)||1===e.length,{message:"'never' cannot be combined with other options"}).describe("Control which files to generate: 'never' skips generating files, 'missing' generates files that did not exist, 'outdated' generates files when the spec has changed but the code file remains unmodified, 'dirty' generates files which were manually modified since the last time we generated them, 'always' generates the files regardless of their current state. You can provide multiple options, e.g. ['missing', 'outdated'] to combine the behaviors.")},DIRTY_STATUSES=["dirty-outdated","dirty-up-to-date"];async function checkShouldUpdate({specPath:e,specHash:t,fsd:r,generate:n,generatedFilePath:i}){let s;if(t)s=t;else{const t=await r.readText(e);if(!t)throw new Error(`Spec file not found: ${e}`);s=calculateSpecHash(t)}const o=getCodeStatus(s,await r.readText(i))
1287
- ;for(const e of n)switch(e){case GenerateOption.never:return!1;case GenerateOption.always:return!0;case GenerateOption.missing:case GenerateOption.outdated:if(e.toString()===o)return!0;break;case GenerateOption.dirty:if(DIRTY_STATUSES.includes(o))return!0;break;default:assertUnreachable(e)}return!1}function findTestsConsidering({generateTests:e}){const t={draft:e,locked:[GenerateOption.never],impl:e},r=Object.fromEntries(Object.entries(t).map(([e,t])=>{return[e,(r=t,r.length>0&&!r.some(e=>e===GenerateOption.never))];var r}));return e=>findTests(e).filter(e=>r[e.kind])}function chainImportResolvers(e){return{async resolve(t){for(const r of e){const e=await r.resolve(t);if(e)return e}}}}async function readRootSpec(e,t=!1){if(!await e.isInstalled()){if(!t)throw new Error(`attempting to read root spec from '${e.displayName}', but it does not appear to be installed; please negotiate with the package manager to install it`);return}const r=await e.openFsd(),n=await readPackageTileManifest(r)
1287
+ ;for(const e of n)switch(e){case GenerateOption.never:return!1;case GenerateOption.always:return!0;case GenerateOption.missing:case GenerateOption.outdated:if(e.toString()===o)return!0;break;case GenerateOption.dirty:if(DIRTY_STATUSES.includes(o))return!0;break;default:assertUnreachable(e)}return!1}function findTestsConsidering({generateTests:e}){const t={draft:e,locked:[GenerateOption.never]},r=Object.fromEntries(Object.entries(t).map(([e,t])=>{return[e,(r=t,r.length>0&&!r.some(e=>e===GenerateOption.never))];var r}));return e=>findTests(e).filter(e=>r[e.kind])}function chainImportResolvers(e){return{async resolve(t){for(const r of e){const e=await r.resolve(t);if(e)return e}}}}async function readRootSpec(e,t=!1){if(!await e.isInstalled()){if(!t)throw new Error(`attempting to read root spec from '${e.displayName}', but it does not appear to be installed; please negotiate with the package manager to install it`);return}const r=await e.openFsd(),n=await readPackageTileManifest(r)
1288
1288
  ;if(n)return await r.readText(n.spec);if(!t)throw new Error(`attempting to read root spec from '${e.displayName}', but it does not appear to have a spec`)}async function readPackageTileManifest(e){const t=await e.readText(WELL_KNOWN_PACKAGE_TILE_MANIFEST_FILENAME);return t?parsePackageTileManifest(t):void 0}function isExternalDependency(e){return!(e.startsWith("./")||e.startsWith("../"))}const dangerousBidiChars=["؜","‎","‏","‪","‫","‬","‭","‮","⁦","⁧","⁨","⁩"],invisibleChars=[{char:"­",code:"U+00AD",name:"SOFT HYPHEN"},{char:"͏",code:"U+034F",name:"COMBINING GRAPHEME JOINER"},{char:"؜",code:"U+061C",name:"ARABIC LETTER MARK"},{char:"ᅟ",code:"U+115F",name:"HANGUL CHOSEONG FILLER"},{char:"ᅠ",code:"U+1160",name:"HANGUL JUNGSEONG FILLER"},{char:"឴",code:"U+17B4",name:"KHMER VOWEL INHERENT AQ"},{char:"឵",code:"U+17B5",name:"KHMER VOWEL INHERENT AA"},{char:"᠎",code:"U+180E",name:"MONGOLIAN VOWEL SEPARATOR"},{char:"​",code:"U+200B",name:"ZERO WIDTH SPACE"},{char:"‌",code:"U+200C",
1289
1289
  name:"ZERO WIDTH NON-JOINER"},{char:"‍",code:"U+200D",name:"ZERO WIDTH JOINER"},{char:"‎",code:"U+200E",name:"LEFT-TO-RIGHT MARK"},{char:"‏",code:"U+200F",name:"RIGHT-TO-LEFT MARK"},{char:"‪",code:"U+202A",name:"LEFT-TO-RIGHT EMBEDDING"},{char:"‫",code:"U+202B",name:"RIGHT-TO-LEFT EMBEDDING"},{char:"‬",code:"U+202C",name:"POP DIRECTIONAL FORMATTING"},{char:"‭",code:"U+202D",name:"LEFT-TO-RIGHT OVERRIDE"},{char:"‮",code:"U+202E",name:"RIGHT-TO-LEFT OVERRIDE"},{char:"⁠",code:"U+2060",name:"WORD JOINER"},{char:"⁡",code:"U+2061",name:"FUNCTION APPLICATION"},{char:"⁢",code:"U+2062",name:"INVISIBLE TIMES"},{char:"⁣",code:"U+2063",name:"INVISIBLE SEPARATOR"},{char:"⁤",code:"U+2064",name:"INVISIBLE PLUS"},{char:"⁦",code:"U+2066",name:"LEFT-TO-RIGHT ISOLATE"},{char:"⁧",code:"U+2067",name:"RIGHT-TO-LEFT ISOLATE"},{char:"⁨",code:"U+2068",name:"FIRST STRONG ISOLATE"},{char:"⁩",code:"U+2069",name:"POP DIRECTIONAL ISOLATE"},{char:"",code:"U+206A",name:"INHIBIT SYMMETRIC SWAPPING"},{char:"",
1290
1290
  code:"U+206B",name:"ACTIVATE SYMMETRIC SWAPPING"},{char:"",code:"U+206C",name:"INHIBIT ARABIC FORM SHAPING"},{char:"",code:"U+206D",name:"ACTIVATE ARABIC FORM SHAPING"},{char:"",code:"U+206E",name:"NATIONAL DIGIT SHAPES"},{char:"",code:"U+206F",name:"NOMINAL DIGIT SHAPES"},{char:"\ufeff",code:"U+FEFF",name:"ZERO WIDTH NO-BREAK SPACE"},{char:"",code:"U+FFF9",name:"INTERLINEAR ANNOTATION ANCHOR"},{char:"",code:"U+FFFA",name:"INTERLINEAR ANNOTATION SEPARATOR"},{char:"",code:"U+FFFB",name:"INTERLINEAR ANNOTATION TERMINATOR"}],charLookup=new Map(invisibleChars.map(e=>[e.char,e])),isVariationSelector=e=>e>=65024&&e<=65039,isHighSurrogate=e=>e>=55296&&e<=56319,isLowSurrogate=e=>e>=56320&&e<=57343;function isEmoji(e,t){if(e[t-1]){const r=e.charCodeAt(t-1);if(isHighSurrogate(r)||isLowSurrogate(r)||isVariationSelector(r))return!0}if(e[t+1]){const r=e.charCodeAt(t+1);if(isHighSurrogate(r)||isLowSurrogate(r)||isVariationSelector(r))return!0}return!1}function detectInvisibleChars(e){
@@ -1416,148 +1416,148 @@ linkText:e.text},"Linked file not found, skipping")}catch(t){if(t instanceof Tar
1416
1416
  </template>
1417
1417
  `,u=i(s).user(c),l=await u.text(!0);return enableTestRunners()&&(await r.writeText(a,l),isLocalFsd(r)&&await r.chmod(a,493)),a}const getTestRunnerPath=e=>{if(!e.endsWith(SPEC_FILE_EXTENSION))throw new Error(`Spec path must end with ${SPEC_FILE_EXTENSION}: ${e}`);const t=e.slice(0,-SPEC_FILE_EXTENSION.length);return path$6.join(TEST_RUNNER_DIR,`${t}.test.sh`)};function bashCdToProjectRoot(e,t){const r=path$6.dirname(path$6.resolve(e));return`cd "$(dirname "\${BASH_SOURCE[0]}")/${path$6.relative(r,t)}"`}function isSpec(e){return!!e.endsWith(SPEC_FILE_EXTENSION)}async function listSpecs(e,t=""){const r=[],n=SPEC_FILE_EXTENSION,i=await e.glob(`**/${t}*${n}`);for(const e of i)isSpec(e)&&r.push(e);return r}const getPath=e=>"string"==typeof e?e:e.path,getPaths=e=>e.map(getPath);async function findAllLinkedFiles(e,t,r){const n=await listSpecs(t,""),i={};return await e.reporter.cMap(n,async(n,s)=>{s(`Checking spec ${n}...`);try{(await specLinkedPaths(t,n,r,e.projectDir)).forEach(t=>{
1418
1418
  i[t]?e.reporter.alert("error",`Code file ${t} linked by ${n} is already linked by ${i[t]} and ${n}`):i[t]=n})}catch(t){return void e.reporter.alert("error",`Failed to check spec file ${n}: ${t instanceof Error?t.message:String(t)}`)}}),i}function specLinkedPathsFromContents(e,t,r,n,i=!0){const s=dirname(t),o=specFromMarkdown(e),a=[];for(const e of r){const t=e(o);a.push(...t)}const c=a.map(e=>{const t="string"==typeof e?e:e.path,r=resolve$3(n,s,t),i=relative(n,r);if("string"==typeof e)return i;if("object"==typeof e)return{...e,path:i};throw new Error("Invalid link type")});return i?dedupLinks(c):c}function dedupLinks(e){const t={};return e.forEach(e=>{t[getPath(e)]=e}),Object.values(t)}async function specLinkedPaths(e,t,r,n,i=!0){const s=await e.readText(t);if(void 0===s)throw new Error("Spec file not found");return specLinkedPathsFromContents(s,t,r,n,i)}async function findSpecLinkingFile(e,t,r,n){const i=await listSpecs(t,""),s=relative(e.projectDir,resolve$3(e.projectDir,n))
1419
- ;for(const n of i)try{if((await specLinkedPaths(t,n,r,e.projectDir)).includes(s))return n}catch(t){e.reporter.alert("error",`Failed to check spec file ${n}: ${t instanceof Error?t.message:String(t)}`);continue}}const returnSchema={name:"testOutput",schema:objectType$1({numPassingTests:numberType$1(),numFailingTests:numberType$1(),numErrorTests:numberType$1(),numTotalTests:numberType$1(),numPassingImplTests:numberType$1(),numFailingImplTests:numberType$1(),numErrorImplTests:numberType$1(),testLineCoveragePercentage:numberType$1(),testBranchCoveragePercentage:numberType$1(),testFunctionCoveragePercentage:numberType$1(),testStatementCoveragePercentage:numberType$1()})};async function analyseResults(e,t){const r=formatRunTestCommandUserPrompt(e);return{...await t(RUN_TEST_COMMAND_SYSTEM_TEMPLATE).user(r).object(returnSchema),fullResponse:e}}
1420
- const RUN_TEST_COMMAND_SYSTEM_TEMPLATE='You are a test output parser. Populate the fields based on the test output. If test output contains test coverage related metrics populate them as well, otherwise populate them with -1. If test suites cannot run, report them as errors.\n\nAdditionally, categorize tests separately:\n- Implementation tests: Tests with file names ending with "_impl" (e.g., "something_impl.test.js") \n- Regular tests: All other tests\n\nCount implementation tests separately in the numPassingImplTests, numFailingImplTests, and numErrorImplTests fields. These counts should be subsets of the main totals (e.g., numFailingTests = regular failing tests + numFailingImplTests).',RUN_TEST_COMMAND_USER_TEMPLATE="{testOutput}";function formatRunTestCommandUserPrompt(e){return RUN_TEST_COMMAND_USER_TEMPLATE.replace("{testOutput}",e)}async function runTests(e,t,r,n,i,s){if(!isLocalFsd(r))throw new Error("runTests only works with local FSDs");let o=e
1421
- ;if(o.includes("{files}"))o=o.replace("{files}",t.join(" "));else if(o.includes("{maven-classes}")||o.includes("{gradle-classes}")){const e=t.map(e=>convertFilenameToJavaClass(e,n));if(e.length>0){if(o.includes("{maven-classes}")){const t=formatClassesForTestRunner("maven",e);o=o.replace("{maven-classes}",t)}if(o.includes("{gradle-classes}")){const t=formatClassesForTestRunner("gradle",e);o=o.replace("{gradle-classes}",t)}}else o=o.replace(" {maven-classes}",""),o=o.replace(" {gradle-classes}","")}return await n.exec({cmd:o,cwd:r.root,timeoutSecs:i,mergeStdStreams:!0,inactivityTimeoutSecs:s})}function formatClassesForTestRunner(e,t){return"gradle"===e?t.map(e=>`--tests "${e}"`).join(" "):`-Dtest=${t.join(",")}`}function convertFilenameToJavaClass(e,t){const r=e.replace(/\\/g,"/"),n=r.indexOf("/src/test/java/");if(-1===n){const n=r.match(/.*src\/test\/java\/(.+)\.java$/);if(n&&n[1])return n[1].replace(/\//g,".");t.logger.warn({filePath:e
1422
- },"Could not determine fully qualified class name from path, using simple class name");return(r.split("/").pop()||"").replace(/\.java$/,"")}return r.substring(n+15).replace(/\.java$/,"").replace(/\//g,".")}const testResultFileName="test-results.json",getFullTestResultsPath=e=>`${DEFAULT_TESSL_DIRS.testResultsDirectory}/${e}/${testResultFileName}`,testOutputSchema=returnSchema.schema.extend({fullResponse:stringType$1()}),validateTestOutput=e=>{const t=testOutputSchema.safeParse(e);if(!t.success)throw new Error(`Invalid test output format: ${t.error.errors.map(e=>`${e.path.join(".")}: ${e.message}`).join(", ")}`);return t.data},readTestResults=async(e,t)=>{const r=await t.readText(getFullTestResultsPath(e));if(!r)throw new Error(`No test results found in session data at: ${getFullTestResultsPath(e)}`);const n=JSON.parse(r);return validateTestOutput(n)},saveTestResults=async(e,t,r)=>(await r.writeText(getFullTestResultsPath(e),JSON.stringify(t,null,2)),getFullTestResultsPath(e))
1423
- ;function _nullishCoalesce$L(e,t){return null!=e?e:t()}function _optionalChain$S(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}const testCommandDescription=enableTestRunners()?'Command override to use for running tests in fix loop (e.g. "npm test -- {files}", "mvn test {maven-classes}") - if not provided an appropriate runner will be generated. Supports placeholders: {files} for test file paths, {maven-classes} for Maven test classes, {gradle-classes} for Gradle test classes':'Command to use for running tests (e.g. "npm test -- {files}", "mvn test {maven-classes}", "gradle test {gradle-classes}"). Supports placeholders: {files} for test file paths, {maven-classes} for Maven test classes, {gradle-classes} for Gradle test classes',testParamsSchema=objectType$1({
1424
- spec:stringType$1().describe("Path to the spec to test, relative to the project root. Must be a .spec.md file.").transform(stripSurroundingQuotes).refine(e=>e.endsWith(SPEC_FILE_EXTENSION),{message:`Spec files must end with ${SPEC_FILE_EXTENSION}`}),timeoutSecs:numberType$1().describe("Override test execution timeout, specified in seconds").default(300),...enableTestRunners()&&{regenerateTestRunner:booleanType$1().describe("Force regeneration of the test runner (defaults to using an existing one if available)").optional()},inactivityTimeoutSecs:numberType$1().describe("Override test *inactivity* timeout, specified in seconds. This will cause the test to timeout if nothing is written to stdout or stderr for x seconds").default(10),testCommand:enableTestRunners()?stringType$1().describe(testCommandDescription).optional():stringType$1().describe(testCommandDescription),lockTests:booleanType$1().describe("Lock tests if all tests are passing").optional().default(!1)}),testTool={name:"test",
1425
- type:"fsd",impl:test,paramsSchema:testParamsSchema,description:"Run tests for the provided spec",visibility:"public",denyRunIn:["cloud"],positionalParam:"spec"};async function test({fsd:e,params:t,rc:r,utils:n}){const{spec:i,testCommand:s,timeoutSecs:o,inactivityTimeoutSecs:a}=t,{reporter:c}=r;if(c.hideOverview(),!isLocalFsd(e))throw new Error("test tool only works with local FSDs");const u=await e.readText(i);if(!u)throw new Error(`Failed to find spec: ${i}`);const l=await specLinkedPaths(e,i,[findTestPaths],e.root);if(0===l.length)return c.success([`No test links found in spec: ${i}, nothing to run`]);const d=[];if(await Promise.all(l.map(async t=>{await e.readText(t)&&d.push(t)})),0===d.length)return await saveTestResults(i,{numPassingTests:0,numFailingTests:0,numErrorTests:0,numTotalTests:0,numPassingImplTests:0,numFailingImplTests:0,numErrorImplTests:0,testLineCoveragePercentage:0,testBranchCoveragePercentage:0,testFunctionCoveragePercentage:0,testStatementCoveragePercentage:0,
1426
- fullResponse:"Skipped running tests: No generated test files found."},e),c.success(["No generated test files found."]);let p;if(c.heading(`Running tests for ${i}`),s){const t=await specLinkedPaths(e,i,[findTestPaths],e.root);p=await runTests(s,t,e,r,o,a)}else{const i=await ensureTestRunner({fsd:e,params:t,rc:r,utils:n});if(r.reporter.message("Executing test runner"),p=await r.exec({cmd:`sh ${i}`,cwd:e.root,timeoutSecs:o,inactivityTimeoutSecs:a,mergeStdStreams:!0}),p.code===SUCCESS?"SIGTERM"===p.signal?r.logger.debug({testResults:p,timeoutType:p.timeoutType},"Test script timed out"):r.logger.debug({testResults:p},"Test script ran successfully"):r.logger.error({testResults:p},"Test script encountered an error"),126===p.code||_optionalChain$S([p,"access",e=>e.stdout,"optionalAccess",e=>e.includes,"call",e=>e("Permission denied")]))return r.reporter.failure("Failed to run test file: Permission denied",{testRunnerPath:i})}let h=_nullishCoalesce$L(p.stdout,()=>"")
1427
- ;if("inactivity"===_optionalChain$S([p,"optionalAccess",e=>e.timeoutType]))h+=`Timed out as nothing was output for ${t.inactivityTimeoutSecs} seconds`;else if("process"===_optionalChain$S([p,"optionalAccess",e=>e.timeoutType]))h+=`Timed out after ${t.timeoutSecs} seconds`;else if(p.error){let e="Unexpected error";p.error&&p.error instanceof Error?e=p.error.message:"string"==typeof p.error&&(e=p.error),h+=`Unexpected error running test process. Process exited with error: "${e}", code: ${p.code}, and signal: ${p.signal}`}const A=await analyseResults(h,n.script),f=await saveTestResults(i,A,e),g=0===A.numFailingTests&&0===A.numErrorTests;if(c.alert(g?"success":"error",`${A.numErrorTests} test suite errors, ${A.numPassingTests}/${A.numTotalTests} tests passed.`),g&&t.lockTests){const t=findTests(specFromMarkdown(u)).filter(e=>"draft"===e.kind),r=[...new Set(t.map(e=>e.path))],n=(await Promise.all(r.map(async t=>await e.readText(t)?t:null))).filter(e=>null!==e),s=r.reduce((e,t)=>{
1428
- if(!n.includes(t))return e;const r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`\\[@test\\]\\(${r}\\)`,"g");return e.replace(i,"$& { .locked }")},u);c.message(`Converted ${n.length} draft ${pluralize$1("test",n.length)} to locked.`),await e.writeText(i,s)}return"inactivity"===_optionalChain$S([p,"optionalAccess",e=>e.timeoutType])?r.reporter.summary([`Tests timed out as nothing was output for ${t.inactivityTimeoutSecs} seconds. Consider re-running with a higher value for the --inactivity-timeout-secs param`]):"process"===_optionalChain$S([p,"optionalAccess",e=>e.timeoutType])&&r.reporter.summary([`Tests timed out after ${t.timeoutSecs} seconds. Consider re-running with a higher value for the --timeout-secs parameter`]),r.reporter.summary([`${i}: Saved test results to session data at ${f}`,`${A.numErrorTests} suite errors, ${A.numFailingTests} failures and ${A.numPassingTests}/${A.numTotalTests} passing`]),r.logger.info({result:h
1429
- },`Test results: ${A.numErrorTests} test suite errors, ${A.numPassingTests} out of ${A.numTotalTests} tests passed.`),g?SUCCESS:FAILURE}const ensureTestRunner=async({params:e,fsd:t,rc:r,utils:n})=>{let i=getTestRunnerPath(e.spec);return enableTestRunners()&&"regenerateTestRunner"in e&&e.regenerateTestRunner||!await t.exists(i)?(r.logger.debug({testRunnerPath:i,spec:e.spec},"Generating new test runner"),i=await generateTestRunner({spec:e.spec,fsd:t,projectDir:r.projectDir,script:n.script,systemMessage:await getSystemPrompt(r.projectDir)})):r.logger.debug({testRunnerPath:i,spec:e.spec},"Using existing test runner"),i};class ResponseValidationError extends Error{constructor(e,t){super(e),this.attempts=t}}var dist$1={},composer={},directives={},identity$3={},hasRequiredIdentity$1;function requireIdentity$1(){if(hasRequiredIdentity$1)return identity$3;hasRequiredIdentity$1=1
1430
- ;const e=Symbol.for("yaml.alias"),t=Symbol.for("yaml.document"),r=Symbol.for("yaml.map"),n=Symbol.for("yaml.pair"),i=Symbol.for("yaml.scalar"),s=Symbol.for("yaml.seq"),o=Symbol.for("yaml.node.type"),a=e=>!!e&&"object"==typeof e&&e[o]===i;function c(e){if(e&&"object"==typeof e)switch(e[o]){case r:case s:return!0}return!1}return identity$3.ALIAS=e,identity$3.DOC=t,identity$3.MAP=r,identity$3.NODE_TYPE=o,identity$3.PAIR=n,identity$3.SCALAR=i,identity$3.SEQ=s,identity$3.hasAnchor=e=>(a(e)||c(e))&&!!e.anchor,identity$3.isAlias=t=>!!t&&"object"==typeof t&&t[o]===e,identity$3.isCollection=c,identity$3.isDocument=e=>!!e&&"object"==typeof e&&e[o]===t,identity$3.isMap=e=>!!e&&"object"==typeof e&&e[o]===r,identity$3.isNode=function(t){if(t&&"object"==typeof t)switch(t[o]){case e:case r:case i:case s:return!0}return!1},identity$3.isPair=e=>!!e&&"object"==typeof e&&e[o]===n,identity$3.isScalar=a,identity$3.isSeq=e=>!!e&&"object"==typeof e&&e[o]===s,identity$3}
1431
- var visit={},hasRequiredVisit,hasRequiredDirectives;function requireVisit(){if(hasRequiredVisit)return visit;hasRequiredVisit=1;var e=requireIdentity$1();const t=Symbol("break visit"),r=Symbol("skip children"),n=Symbol("remove node");function i(t,r){const i=c(r);if(e.isDocument(t)){s(null,t.contents,i,Object.freeze([t]))===n&&(t.contents=null)}else s(null,t,i,Object.freeze([]))}function s(r,i,o,a){const c=u(r,i,o,a);if(e.isNode(c)||e.isPair(c))return l(r,a,c),s(r,c,o,a);if("symbol"!=typeof c)if(e.isCollection(i)){a=Object.freeze(a.concat(i));for(let e=0;e<i.items.length;++e){const r=s(e,i.items[e],o,a);if("number"==typeof r)e=r-1;else{if(r===t)return t;r===n&&(i.items.splice(e,1),e-=1)}}}else if(e.isPair(i)){a=Object.freeze(a.concat(i));const e=s("key",i.key,o,a);if(e===t)return t;e===n&&(i.key=null);const r=s("value",i.value,o,a);if(r===t)return t;r===n&&(i.value=null)}return c}async function o(t,r){const i=c(r);if(e.isDocument(t)){
1432
- await a(null,t.contents,i,Object.freeze([t]))===n&&(t.contents=null)}else await a(null,t,i,Object.freeze([]))}async function a(r,i,s,o){const c=await u(r,i,s,o);if(e.isNode(c)||e.isPair(c))return l(r,o,c),a(r,c,s,o);if("symbol"!=typeof c)if(e.isCollection(i)){o=Object.freeze(o.concat(i));for(let e=0;e<i.items.length;++e){const r=await a(e,i.items[e],s,o);if("number"==typeof r)e=r-1;else{if(r===t)return t;r===n&&(i.items.splice(e,1),e-=1)}}}else if(e.isPair(i)){o=Object.freeze(o.concat(i));const e=await a("key",i.key,s,o);if(e===t)return t;e===n&&(i.key=null);const r=await a("value",i.value,s,o);if(r===t)return t;r===n&&(i.value=null)}return c}function c(e){return"object"==typeof e&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function u(t,r,n,i){
1433
- return"function"==typeof n?n(t,r,i):e.isMap(r)?n.Map?.(t,r,i):e.isSeq(r)?n.Seq?.(t,r,i):e.isPair(r)?n.Pair?.(t,r,i):e.isScalar(r)?n.Scalar?.(t,r,i):e.isAlias(r)?n.Alias?.(t,r,i):void 0}function l(t,r,n){const i=r[r.length-1];if(e.isCollection(i))i.items[t]=n;else if(e.isPair(i))"key"===t?i.key=n:i.value=n;else{if(!e.isDocument(i)){const t=e.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${t} parent`)}i.contents=n}}return i.BREAK=t,i.SKIP=r,i.REMOVE=n,o.BREAK=t,o.SKIP=r,o.REMOVE=n,visit.visit=i,visit.visitAsync=o,visit}function requireDirectives(){if(hasRequiredDirectives)return directives;hasRequiredDirectives=1;var e=requireIdentity$1(),t=requireVisit();const r={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},n=e=>e.replace(/[!,[\]{}]/g,e=>r[e]);class i{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},i.defaultYaml,e),this.tags=Object.assign({},i.defaultTags,t)}clone(){const e=new i(this.yaml,this.tags)
1434
- ;return e.docStart=this.docStart,e}atDocument(){const e=new i(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:i.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},i.defaultTags)}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:i.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},i.defaultTags),this.atNextDocument=!1);const r=e.trim().split(/[ \t]+/),n=r.shift();switch(n){case"%TAG":{if(2!==r.length&&(t(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;const[e,n]=r;return this.tags[e]=n,!0}case"%YAML":{if(this.yaml.explicit=!0,1!==r.length)return t(0,"%YAML directive should contain exactly one part"),!1;const[e]=r;if("1.1"===e||"1.2"===e)return this.yaml.version=e,!0;return t(6,`Unsupported YAML version ${e}`,/^\d+\.\d+$/.test(e)),!1}default:return t(0,`Unknown directive ${n}`,!0),!1}}tagName(e,t){if("!"===e)return"!"
1435
- ;if("!"!==e[0])return t(`Not a valid tag: ${e}`),null;if("<"===e[1]){const r=e.slice(2,-1);return"!"===r||"!!"===r?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(">"!==e[e.length-1]&&t("Verbatim tags must end with a >"),r)}const[,r,n]=e.match(/^(.*!)([^!]*)$/s);n||t(`The ${e} tag has no suffix`);const i=this.tags[r];if(i)try{return i+decodeURIComponent(n)}catch(e){return t(String(e)),null}return"!"===r?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(const[t,r]of Object.entries(this.tags))if(e.startsWith(r))return t+n(e.substring(r.length));return"!"===e[0]?e:`!<${e}>`}toString(r){const n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags);let s;if(r&&i.length>0&&e.isNode(r.contents)){const n={};t.visit(r.contents,(t,r)=>{e.isNode(r)&&r.tag&&(n[r.tag]=!0)}),s=Object.keys(n)}else s=[];for(const[e,t]of i)"!!"===e&&"tag:yaml.org,2002:"===t||r&&!s.some(e=>e.startsWith(t))||n.push(`%TAG ${e} ${t}`);return n.join("\n")}}
1436
- return i.defaultYaml={explicit:!1,version:"1.2"},i.defaultTags={"!!":"tag:yaml.org,2002:"},directives.Directives=i,directives}var Document={},Alias={},anchors={},hasRequiredAnchors;function requireAnchors(){if(hasRequiredAnchors)return anchors;hasRequiredAnchors=1;var e=requireIdentity$1(),t=requireVisit();function r(e){const r=new Set;return t.visit(e,{Value(e,t){t.anchor&&r.add(t.anchor)}}),r}function n(e,t){for(let r=1;;++r){const n=`${e}${r}`;if(!t.has(n))return n}}return anchors.anchorIsValid=function(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){const t=JSON.stringify(e);throw new Error(`Anchor must not contain whitespace or control characters: ${t}`)}return!0},anchors.anchorNames=r,anchors.createNodeAnchors=function(t,i){const s=[],o=new Map;let a=null;return{onAnchor:e=>{s.push(e),a??(a=r(t));const o=n(i,a);return a.add(o),o},setAnchors:()=>{for(const t of s){const r=o.get(t);if("object"!=typeof r||!r.anchor||!e.isScalar(r.node)&&!e.isCollection(r.node)){
1437
- const e=new Error("Failed to resolve repeated object (this should not happen)");throw e.source=t,e}r.node.anchor=r.anchor}},sourceObjects:o}},anchors.findNewAnchor=n,anchors}var Node={},applyReviver={},hasRequiredApplyReviver;function requireApplyReviver(){if(hasRequiredApplyReviver)return applyReviver;return hasRequiredApplyReviver=1,applyReviver.applyReviver=function e(t,r,n,i){if(i&&"object"==typeof i)if(Array.isArray(i))for(let r=0,n=i.length;r<n;++r){const n=i[r],s=e(t,i,String(r),n);void 0===s?delete i[r]:s!==n&&(i[r]=s)}else if(i instanceof Map)for(const r of Array.from(i.keys())){const n=i.get(r),s=e(t,i,r,n);void 0===s?i.delete(r):s!==n&&i.set(r,s)}else if(i instanceof Set)for(const r of Array.from(i)){const n=e(t,i,r,r);void 0===n?i.delete(r):n!==r&&(i.delete(r),i.add(n))}else for(const[r,n]of Object.entries(i)){const s=e(t,i,r,n);void 0===s?delete i[r]:s!==n&&(i[r]=s)}return t.call(r,n,i)},applyReviver}var toJS={},hasRequiredToJS,hasRequiredNode$1,hasRequiredAlias
1438
- ;function requireToJS(){if(hasRequiredToJS)return toJS;hasRequiredToJS=1;var e=requireIdentity$1();return toJS.toJS=function t(r,n,i){if(Array.isArray(r))return r.map((e,r)=>t(e,String(r),i));if(r&&"function"==typeof r.toJSON){if(!i||!e.hasAnchor(r))return r.toJSON(n,i);const t={aliasCount:0,count:1,res:void 0};i.anchors.set(r,t),i.onCreate=e=>{t.res=e,delete i.onCreate};const s=r.toJSON(n,i);return i.onCreate&&i.onCreate(s),s}return"bigint"!=typeof r||i?.keep?r:Number(r)},toJS}function requireNode$1(){if(hasRequiredNode$1)return Node;hasRequiredNode$1=1;var e=requireApplyReviver(),t=requireIdentity$1(),r=requireToJS();return Node.NodeBase=class{constructor(e){Object.defineProperty(this,t.NODE_TYPE,{value:e})}clone(){const e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(n,{mapAsMap:i,maxAliasCount:s,onAnchor:o,reviver:a}={}){
1439
- if(!t.isDocument(n))throw new TypeError("A document argument is required");const c={anchors:new Map,doc:n,keep:!0,mapAsMap:!0===i,mapKeyWarned:!1,maxAliasCount:"number"==typeof s?s:100},u=r.toJS(this,"",c);if("function"==typeof o)for(const{count:e,res:t}of c.anchors.values())o(t,e);return"function"==typeof a?e.applyReviver(a,{"":u},"",u):u}},Node}function requireAlias(){if(hasRequiredAlias)return Alias;hasRequiredAlias=1;var e=requireAnchors(),t=requireVisit(),r=requireIdentity$1(),n=requireNode$1(),i=requireToJS();let s=class extends n.NodeBase{constructor(e){super(r.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,n){let i,s;n?.aliasResolveCache?i=n.aliasResolveCache:(i=[],t.visit(e,{Node:(e,t)=>{(r.isAlias(t)||r.hasAnchor(t))&&i.push(t)}}),n&&(n.aliasResolveCache=i));for(const e of i){if(e===this)break;e.anchor===this.source&&(s=e)}return s}toJSON(e,t){if(!t)return{source:this.source}
1440
- ;const{anchors:r,doc:n,maxAliasCount:s}=t,a=this.resolve(n,t);if(!a){const e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(e)}let c=r.get(a);if(c||(i.toJS(a,null,t),c=r.get(a)),!c||void 0===c.res){throw new ReferenceError("This should not happen: Alias anchor was not resolved?")}if(s>=0&&(c.count+=1,0===c.aliasCount&&(c.aliasCount=o(n,a,r)),c.count*c.aliasCount>s)){throw new ReferenceError("Excessive alias count indicates a resource exhaustion attack")}return c.res}toString(t,r,n){const i=`*${this.source}`;if(t){if(e.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){const e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(e)}if(t.implicitKey)return`${i} `}return i}};function o(e,t,n){if(r.isAlias(t)){const r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(r.isCollection(t)){let r=0;for(const i of t.items){const t=o(e,i,n);t>r&&(r=t)}
1441
- return r}if(r.isPair(t)){const r=o(e,t.key,n),i=o(e,t.value,n);return Math.max(r,i)}return 1}return Alias.Alias=s,Alias}var Collection={},createNode={},Scalar={},hasRequiredScalar,hasRequiredCreateNode,hasRequiredCollection;function requireScalar(){if(hasRequiredScalar)return Scalar;hasRequiredScalar=1;var e=requireIdentity$1(),t=requireNode$1(),r=requireToJS();let n=class extends t.NodeBase{constructor(t){super(e.SCALAR),this.value=t}toJSON(e,t){return t?.keep?this.value:r.toJS(this.value,e,t)}toString(){return String(this.value)}};return n.BLOCK_FOLDED="BLOCK_FOLDED",n.BLOCK_LITERAL="BLOCK_LITERAL",n.PLAIN="PLAIN",n.QUOTE_DOUBLE="QUOTE_DOUBLE",n.QUOTE_SINGLE="QUOTE_SINGLE",Scalar.Scalar=n,Scalar.isScalarValue=e=>!e||"function"!=typeof e&&"object"!=typeof e,Scalar}function requireCreateNode(){if(hasRequiredCreateNode)return createNode;hasRequiredCreateNode=1;var e=requireAlias(),t=requireIdentity$1(),r=requireScalar();return createNode.createNode=function(n,i,s){
1442
- if(t.isDocument(n)&&(n=n.contents),t.isNode(n))return n;if(t.isPair(n)){const e=s.schema[t.MAP].createNode?.(s.schema,null,s);return e.items.push(n),e}(n instanceof String||n instanceof Number||n instanceof Boolean||"undefined"!=typeof BigInt&&n instanceof BigInt)&&(n=n.valueOf());const{aliasDuplicateObjects:o,onAnchor:a,onTagObj:c,schema:u,sourceObjects:l}=s;let d;if(o&&n&&"object"==typeof n){if(d=l.get(n),d)return d.anchor??(d.anchor=a(n)),new e.Alias(d.anchor);d={anchor:null,node:null},l.set(n,d)}i?.startsWith("!!")&&(i="tag:yaml.org,2002:"+i.slice(2));let p=function(e,t,r){if(t){const e=r.filter(e=>e.tag===t),n=e.find(e=>!e.format)??e[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return r.find(t=>t.identify?.(e)&&!t.format)}(n,i,u.tags);if(!p){if(n&&"function"==typeof n.toJSON&&(n=n.toJSON()),!n||"object"!=typeof n){const e=new r.Scalar(n);return d&&(d.node=e),e}p=n instanceof Map?u[t.MAP]:Symbol.iterator in Object(n)?u[t.SEQ]:u[t.MAP]}c&&(c(p),delete s.onTagObj)
1443
- ;const h=p?.createNode?p.createNode(s.schema,n,s):"function"==typeof p?.nodeClass?.from?p.nodeClass.from(s.schema,n,s):new r.Scalar(n);return i?h.tag=i:p.default||(h.tag=p.tag),d&&(d.node=h),h},createNode}function requireCollection(){if(hasRequiredCollection)return Collection;hasRequiredCollection=1;var e=requireCreateNode(),t=requireIdentity$1(),r=requireNode$1();function n(t,r,n){let i=n;for(let e=r.length-1;e>=0;--e){const t=r[e];if("number"==typeof t&&Number.isInteger(t)&&t>=0){const e=[];e[t]=i,i=e}else i=new Map([[t,i]])}return e.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}const i=e=>null==e||"object"==typeof e&&!!e[Symbol.iterator]().next().done;let s=class extends r.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){
1444
- const r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(r.schema=e),r.items=r.items.map(r=>t.isNode(r)||t.isPair(r)?r.clone(e):r),this.range&&(r.range=this.range.slice()),r}addIn(e,r){if(i(e))this.add(r);else{const[i,...s]=e,o=this.get(i,!0);if(t.isCollection(o))o.addIn(s,r);else{if(void 0!==o||!this.schema)throw new Error(`Expected YAML collection at ${i}. Remaining path: ${s}`);this.set(i,n(this.schema,s,r))}}}deleteIn(e){const[r,...n]=e;if(0===n.length)return this.delete(r);const i=this.get(r,!0);if(t.isCollection(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}getIn(e,r){const[n,...i]=e,s=this.get(n,!0);return 0===i.length?!r&&t.isScalar(s)?s.value:s:t.isCollection(s)?s.getIn(i,r):void 0}hasAllNullValues(e){return this.items.every(r=>{if(!t.isPair(r))return!1;const n=r.value;return null==n||e&&t.isScalar(n)&&null==n.value&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){const[r,...n]=e
1445
- ;if(0===n.length)return this.has(r);const i=this.get(r,!0);return!!t.isCollection(i)&&i.hasIn(n)}setIn(e,r){const[i,...s]=e;if(0===s.length)this.set(i,r);else{const e=this.get(i,!0);if(t.isCollection(e))e.setIn(s,r);else{if(void 0!==e||!this.schema)throw new Error(`Expected YAML collection at ${i}. Remaining path: ${s}`);this.set(i,n(this.schema,s,r))}}}};return Collection.Collection=s,Collection.collectionFromPath=n,Collection.isEmptyPath=i,Collection}var Pair={},stringifyPair={},stringify$5={},stringifyComment={},hasRequiredStringifyComment;function requireStringifyComment(){if(hasRequiredStringifyComment)return stringifyComment;hasRequiredStringifyComment=1;function e(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}return stringifyComment.indentComment=e,stringifyComment.lineComment=(t,r,n)=>t.endsWith("\n")?e(n,r):n.includes("\n")?"\n"+e(n,r):(t.endsWith(" ")?"":" ")+n,stringifyComment.stringifyComment=e=>e.replace(/^(?!$)(?: $)?/gm,"#"),stringifyComment}
1446
- var stringifyString={},foldFlowLines={},hasRequiredFoldFlowLines,hasRequiredStringifyString,hasRequiredStringify$4,hasRequiredStringifyPair;function requireFoldFlowLines(){if(hasRequiredFoldFlowLines)return foldFlowLines;hasRequiredFoldFlowLines=1;const e="block",t="quoted";function r(e,t,r){let n=t,i=t+1,s=e[i];for(;" "===s||"\t"===s;)if(t<i+r)s=e[++t];else{do{s=e[++t]}while(s&&"\n"!==s);n=t,i=t+1,s=e[i]}return n}return foldFlowLines.FOLD_BLOCK=e,foldFlowLines.FOLD_FLOW="flow",foldFlowLines.FOLD_QUOTED=t,foldFlowLines.foldFlowLines=function(n,i,s="flow",{indentAtStart:o,lineWidth:a=80,minContentWidth:c=20,onFold:u,onOverflow:l}={}){if(!a||a<0)return n;a<c&&(c=0);const d=Math.max(1+c,1+a-i.length);if(n.length<=d)return n;const p=[],h={};let A,f,g=a-i.length;"number"==typeof o&&(o>a-Math.max(2,c)?p.push(0):g=a-o);let m=!1,y=-1,E=-1,b=-1;s===e&&(y=r(n,y,i.length),-1!==y&&(g=y+d));for(let o;o=n[y+=1];){if(s===t&&"\\"===o){switch(E=y,n[y+1]){case"x":y+=3;break;case"u":y+=5;break;case"U":
1447
- y+=9;break;default:y+=1}b=y}if("\n"===o)s===e&&(y=r(n,y,i.length)),g=y+i.length+d,A=void 0;else{if(" "===o&&f&&" "!==f&&"\n"!==f&&"\t"!==f){const e=n[y+1];e&&" "!==e&&"\n"!==e&&"\t"!==e&&(A=y)}if(y>=g)if(A)p.push(A),g=A+d,A=void 0;else if(s===t){for(;" "===f||"\t"===f;)f=o,o=n[y+=1],m=!0;const e=y>b+1?y-2:E-1;if(h[e])return n;p.push(e),h[e]=!0,g=e+d,A=void 0}else m=!0}f=o}if(m&&l&&l(),0===p.length)return n;u&&u();let C=n.slice(0,p[0]);for(let e=0;e<p.length;++e){const r=p[e],o=p[e+1]||n.length;0===r?C=`\n${i}${n.slice(0,o)}`:(s===t&&h[r]&&(C+=`${n[r]}\\`),C+=`\n${i}${n.slice(r+1,o)}`)}return C},foldFlowLines}function requireStringifyString(){if(hasRequiredStringifyString)return stringifyString;hasRequiredStringifyString=1;var e=requireScalar(),t=requireFoldFlowLines();const r=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),n=e=>/^(%|---|\.\.\.)/m.test(e);function i(e,i){const s=JSON.stringify(e)
1448
- ;if(i.options.doubleQuotedAsJSON)return s;const{implicitKey:o}=i,a=i.options.doubleQuotedMinMultiLineLength,c=i.indent||(n(e)?" ":"");let u="",l=0;for(let e=0,t=s[e];t;t=s[++e])if(" "===t&&"\\"===s[e+1]&&"n"===s[e+2]&&(u+=s.slice(l,e)+"\\ ",e+=1,l=e,t="\\"),"\\"===t)switch(s[e+1]){case"u":{u+=s.slice(l,e);const t=s.substr(e+2,4);switch(t){case"0000":u+="\\0";break;case"0007":u+="\\a";break;case"000b":u+="\\v";break;case"001b":u+="\\e";break;case"0085":u+="\\N";break;case"00a0":u+="\\_";break;case"2028":u+="\\L";break;case"2029":u+="\\P";break;default:"00"===t.substr(0,2)?u+="\\x"+t.substr(2):u+=s.substr(e,6)}e+=5,l=e+1}break;case"n":if(o||'"'===s[e+2]||s.length<a)e+=1;else{for(u+=s.slice(l,e)+"\n\n";"\\"===s[e+2]&&"n"===s[e+3]&&'"'!==s[e+4];)u+="\n",e+=2;u+=c," "===s[e+2]&&(u+="\\"),e+=1,l=e+1}break;default:e+=1}return u=l?u+s.slice(l):s,o?u:t.foldFlowLines(u,c,t.FOLD_QUOTED,r(i,!1))}function s(e,s){
1449
- if(!1===s.options.singleQuote||s.implicitKey&&e.includes("\n")||/[ \t]\n|\n[ \t]/.test(e))return i(e,s);const o=s.indent||(n(e)?" ":""),a="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&\n${o}`)+"'";return s.implicitKey?a:t.foldFlowLines(a,o,t.FOLD_FLOW,r(s,!1))}function o(e,t){const{singleQuote:r}=t.options;let n;if(!1===r)n=i;else{const t=e.includes('"'),o=e.includes("'");n=t&&!o?s:o&&!t?i:r?s:i}return n(e,t)}let a;try{a=new RegExp("(^|(?<!\n))\n+(?!\n|$)","g")}catch{a=/\n+(?!\n|$)/g}function c({comment:i,type:s,value:c},u,l,d){const{blockQuote:p,commentString:h,lineWidth:A}=u.options;if(!p||/\n[\t ]+$/.test(c)||/^\s*$/.test(c))return o(c,u);const f=u.indent||(u.forceBlockIndent||n(c)?" ":""),g="literal"===p||"folded"!==p&&s!==e.Scalar.BLOCK_FOLDED&&(s===e.Scalar.BLOCK_LITERAL||!function(e,t,r){if(!t||t<0)return!1;const n=t-r,i=e.length;if(i<=n)return!1;for(let t=0,r=0;t<i;++t)if("\n"===e[t]){if(t-r>n)return!0;if(r=t+1,i-r<=n)return!1}return!0}(c,A,f.length));if(!c)return g?"|\n":">\n"
1450
- ;let m,y;for(y=c.length;y>0;--y){const e=c[y-1];if("\n"!==e&&"\t"!==e&&" "!==e)break}let E=c.substring(y);const b=E.indexOf("\n");-1===b?m="-":c===E||b!==E.length-1?(m="+",d&&d()):m="",E&&(c=c.slice(0,-E.length),"\n"===E[E.length-1]&&(E=E.slice(0,-1)),E=E.replace(a,`$&${f}`));let C,v=!1,I=-1;for(C=0;C<c.length;++C){const e=c[C];if(" "===e)v=!0;else{if("\n"!==e)break;I=C}}let _=c.substring(0,I<C?I+1:C);_&&(c=c.substring(_.length),_=_.replace(/\n+/g,`$&${f}`));let S=(v?f?"2":"1":"")+m;if(i&&(S+=" "+h(i.replace(/ ?[\r\n]+/g," ")),l&&l()),!g){const n=c.replace(/\n+/g,"\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${f}`);let i=!1;const o=r(u,!0);"folded"!==p&&s!==e.Scalar.BLOCK_FOLDED&&(o.onOverflow=()=>{i=!0});const a=t.foldFlowLines(`${_}${n}${E}`,f,t.FOLD_BLOCK,o);if(!i)return`>${S}\n${f}${a}`}return`|${S}\n${f}${_}${c=c.replace(/\n+/g,`$&${f}`)}${E}`}return stringifyString.stringifyString=function(a,u,l,d){
1451
- const{implicitKey:p,inFlow:h}=u,A="string"==typeof a.value?a:Object.assign({},a,{value:String(a.value)});let{type:f}=a;f!==e.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(A.value)&&(f=e.Scalar.QUOTE_DOUBLE);const g=a=>{switch(a){case e.Scalar.BLOCK_FOLDED:case e.Scalar.BLOCK_LITERAL:return p||h?o(A.value,u):c(A,u,l,d);case e.Scalar.QUOTE_DOUBLE:return i(A.value,u);case e.Scalar.QUOTE_SINGLE:return s(A.value,u);case e.Scalar.PLAIN:return function(i,s,a,u){const{type:l,value:d}=i,{actualString:p,implicitKey:h,indent:A,indentStep:f,inFlow:g}=s;if(h&&d.includes("\n")||g&&/[[\]{},]/.test(d))return o(d,s);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(d))return h||g||!d.includes("\n")?o(d,s):c(i,s,a,u);if(!h&&!g&&l!==e.Scalar.PLAIN&&d.includes("\n"))return c(i,s,a,u);if(n(d)){if(""===A)return s.forceBlockIndent=!0,c(i,s,a,u);if(h&&A===f)return o(d,s)}const m=d.replace(/\n+/g,`$&\n${A}`);if(p){
1452
- const e=e=>e.default&&"tag:yaml.org,2002:str"!==e.tag&&e.test?.test(m),{compat:t,tags:r}=s.doc.schema;if(r.some(e)||t?.some(e))return o(d,s)}return h?m:t.foldFlowLines(m,A,t.FOLD_FLOW,r(s,!1))}(A,u,l,d);default:return null}};let m=g(f);if(null===m){const{defaultKeyType:e,defaultStringType:t}=u.options,r=p&&e||t;if(m=g(r),null===m)throw new Error(`Unsupported default string type ${r}`)}return m},stringifyString}function requireStringify$4(){if(hasRequiredStringify$4)return stringify$5;hasRequiredStringify$4=1;var e=requireAnchors(),t=requireIdentity$1(),r=requireStringifyComment(),n=requireStringifyString();return stringify$5.createStringifyContext=function(e,t){const n=Object.assign({blockQuote:!0,commentString:r.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,
1453
- trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t);let i;switch(n.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:"number"==typeof n.indent?" ".repeat(n.indent):" ",inFlow:i,options:n}},stringify$5.stringify=function(r,i,s,o){if(t.isPair(r))return r.toString(i,s,o);if(t.isAlias(r)){if(i.doc.directives)return r.toString(i);if(i.resolvedAliases?.has(r))throw new TypeError("Cannot stringify circular structure without alias nodes");i.resolvedAliases?i.resolvedAliases.add(r):i.resolvedAliases=new Set([r]),r=r.resolve(i.doc)}let a;const c=t.isNode(r)?r:i.doc.createNode(r,{onTagObj:e=>a=e});a??(a=function(e,r){if(r.tag){const t=e.filter(e=>e.tag===r.tag);if(t.length>0)return t.find(e=>e.format===r.format)??t[0]}let n,i;if(t.isScalar(r)){i=r.value;let t=e.filter(e=>e.identify?.(i));if(t.length>1){const e=t.filter(e=>e.test);e.length>0&&(t=e)}
1454
- n=t.find(e=>e.format===r.format)??t.find(e=>!e.format)}else i=r,n=e.find(e=>e.nodeClass&&i instanceof e.nodeClass);if(!n)throw new Error(`Tag not resolved for ${i?.constructor?.name??(null===i?"null":typeof i)} value`);return n}(i.doc.schema.tags,c));const u=function(r,n,{anchors:i,doc:s}){if(!s.directives)return"";const o=[],a=(t.isScalar(r)||t.isCollection(r))&&r.anchor;a&&e.anchorIsValid(a)&&(i.add(a),o.push(`&${a}`));const c=r.tag??(n.default?null:n.tag);return c&&o.push(s.directives.tagString(c)),o.join(" ")}(c,a,i);u.length>0&&(i.indentAtStart=(i.indentAtStart??0)+u.length+1);const l="function"==typeof a.stringify?a.stringify(c,i,s,o):t.isScalar(c)?n.stringifyString(c,i,s,o):c.toString(i,s,o);return u?t.isScalar(c)||"{"===l[0]||"["===l[0]?`${u} ${l}`:`${u}\n${i.indent}${l}`:l},stringify$5}function requireStringifyPair(){if(hasRequiredStringifyPair)return stringifyPair;hasRequiredStringifyPair=1
1455
- ;var e=requireIdentity$1(),t=requireScalar(),r=requireStringify$4(),n=requireStringifyComment();return stringifyPair.stringifyPair=function({key:i,value:s},o,a,c){const{allNullValues:u,doc:l,indent:d,indentStep:p,options:{commentString:h,indentSeq:A,simpleKeys:f}}=o;let g=e.isNode(i)&&i.comment||null;if(f){if(g)throw new Error("With simple keys, key nodes cannot have comments");if(e.isCollection(i)||!e.isNode(i)&&"object"==typeof i){throw new Error("With simple keys, collection cannot be used as a key value")}}let m=!f&&(!i||g&&null==s&&!o.inFlow||e.isCollection(i)||(e.isScalar(i)?i.type===t.Scalar.BLOCK_FOLDED||i.type===t.Scalar.BLOCK_LITERAL:"object"==typeof i));o=Object.assign({},o,{allNullValues:!1,implicitKey:!m&&(f||!u),indent:d+p});let y,E,b,C=!1,v=!1,I=r.stringify(i,o,()=>C=!0,()=>v=!0);if(!m&&!o.inFlow&&I.length>1024){if(f)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");m=!0}if(o.inFlow){if(u||null==s)return C&&a&&a(),
1456
- ""===I?"?":m?`? ${I}`:I}else if(u&&!f||null==s&&m)return I=`? ${I}`,g&&!C?I+=n.lineComment(I,o.indent,h(g)):v&&c&&c(),I;C&&(g=null),m?(g&&(I+=n.lineComment(I,o.indent,h(g))),I=`? ${I}\n${d}:`):(I=`${I}:`,g&&(I+=n.lineComment(I,o.indent,h(g)))),e.isNode(s)?(y=!!s.spaceBefore,E=s.commentBefore,b=s.comment):(y=!1,E=null,b=null,s&&"object"==typeof s&&(s=l.createNode(s))),o.implicitKey=!1,m||g||!e.isScalar(s)||(o.indentAtStart=I.length+1),v=!1,A||!(p.length>=2)||o.inFlow||m||!e.isSeq(s)||s.flow||s.tag||s.anchor||(o.indent=o.indent.substring(2));let _=!1;const S=r.stringify(s,o,()=>_=!0,()=>v=!0);let D=" ";if(g||y||E){if(D=y?"\n":"",E){const e=h(E);D+=`\n${n.indentComment(e,o.indent)}`}""!==S||o.inFlow?D+=`\n${o.indent}`:"\n"===D&&(D="\n\n")}else if(!m&&e.isCollection(s)){const e=S[0],t=S.indexOf("\n"),r=-1!==t,n=o.inFlow??s.flow??0===s.items.length;if(r||!n){let n=!1;if(r&&("&"===e||"!"===e)){let r=S.indexOf(" ");"&"===e&&-1!==r&&r<t&&"!"===S[r+1]&&(r=S.indexOf(" ",r+1)),
1457
- (-1===r||t<r)&&(n=!0)}n||(D=`\n${o.indent}`)}}else""!==S&&"\n"!==S[0]||(D="");return I+=D+S,o.inFlow?_&&a&&a():b&&!_?I+=n.lineComment(I,o.indent,h(b)):v&&c&&c(),I},stringifyPair}var addPairToJSMap={},log$1={},hasRequiredLog;function requireLog(){if(hasRequiredLog)return log$1;hasRequiredLog=1;var e=process__default;return log$1.debug=function(e,...t){"debug"===e&&console.log(...t)},log$1.warn=function(t,r){"debug"!==t&&"warn"!==t||("function"==typeof e.emitWarning?e.emitWarning(r):console.warn(r))},log$1}var merge$4={},hasRequiredMerge$3,hasRequiredAddPairToJSMap,hasRequiredPair;function requireMerge$3(){if(hasRequiredMerge$3)return merge$4;hasRequiredMerge$3=1;var e=requireIdentity$1(),t=requireScalar();const r="<<",n={identify:e=>e===r||"symbol"==typeof e&&e.description===r,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new t.Scalar(Symbol(r)),{addToJSMap:i}),stringify:()=>r};function i(t,r,n){if(n=t&&e.isAlias(n)?n.resolve(t.doc):n,
1458
- e.isSeq(n))for(const e of n.items)s(t,r,e);else if(Array.isArray(n))for(const e of n)s(t,r,e);else s(t,r,n)}function s(t,r,n){const i=t&&e.isAlias(n)?n.resolve(t.doc):n;if(!e.isMap(i))throw new Error("Merge sources must be maps or map aliases");const s=i.toJSON(null,t,Map);for(const[e,t]of s)r instanceof Map?r.has(e)||r.set(e,t):r instanceof Set?r.add(e):Object.prototype.hasOwnProperty.call(r,e)||Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0});return r}return merge$4.addMergeToJSMap=i,merge$4.isMergeKey=(r,i)=>(n.identify(i)||e.isScalar(i)&&(!i.type||i.type===t.Scalar.PLAIN)&&n.identify(i.value))&&r?.doc.schema.tags.some(e=>e.tag===n.tag&&e.default),merge$4.merge=n,merge$4}function requireAddPairToJSMap(){if(hasRequiredAddPairToJSMap)return addPairToJSMap;hasRequiredAddPairToJSMap=1;var e=requireLog(),t=requireMerge$3(),r=requireStringify$4(),n=requireIdentity$1(),i=requireToJS();return addPairToJSMap.addPairToJSMap=function(s,o,{key:a,value:c}){
1459
- if(n.isNode(a)&&a.addToJSMap)a.addToJSMap(s,o,c);else if(t.isMergeKey(s,a))t.addMergeToJSMap(s,o,c);else{const t=i.toJS(a,"",s);if(o instanceof Map)o.set(t,i.toJS(c,t,s));else if(o instanceof Set)o.add(t);else{const u=function(t,i,s){if(null===i)return"";if("object"!=typeof i)return String(i);if(n.isNode(t)&&s?.doc){const n=r.createStringifyContext(s.doc,{});n.anchors=new Set;for(const e of s.anchors.keys())n.anchors.add(e.anchor);n.inFlow=!0,n.inStringifyKey=!0;const i=t.toString(n);if(!s.mapKeyWarned){let t=JSON.stringify(i);t.length>40&&(t=t.substring(0,36)+'..."'),e.warn(s.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${t}. Set mapAsMap: true to use object keys.`),s.mapKeyWarned=!0}return i}return JSON.stringify(i)}(a,t,s),l=i.toJS(c,u,s);u in o?Object.defineProperty(o,u,{value:l,writable:!0,enumerable:!0,configurable:!0}):o[u]=l}}return o},addPairToJSMap}function requirePair(){if(hasRequiredPair)return Pair;hasRequiredPair=1
1460
- ;var e=requireCreateNode(),t=requireStringifyPair(),r=requireAddPairToJSMap(),n=requireIdentity$1();let i=class e{constructor(e,t=null){Object.defineProperty(this,n.NODE_TYPE,{value:n.PAIR}),this.key=e,this.value=t}clone(t){let{key:r,value:i}=this;return n.isNode(r)&&(r=r.clone(t)),n.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(e,t){const n=t?.mapAsMap?new Map:{};return r.addPairToJSMap(t,n,this)}toString(e,r,n){return e?.doc?t.stringifyPair(this,e,r,n):JSON.stringify(this)}};return Pair.Pair=i,Pair.createPair=function(t,r,n){const s=e.createNode(t,void 0,n),o=e.createNode(r,void 0,n);return new i(s,o)},Pair}var Schema={},map$1={},YAMLMap={},stringifyCollection={},hasRequiredStringifyCollection,hasRequiredYAMLMap,hasRequiredMap$1;function requireStringifyCollection(){if(hasRequiredStringifyCollection)return stringifyCollection;hasRequiredStringifyCollection=1;var e=requireIdentity$1(),t=requireStringify$4(),r=requireStringifyComment()
1461
- ;function n({comment:n,items:i},o,{blockItemPrefix:a,flowChars:c,itemIndent:u,onChompKeep:l,onComment:d}){const{indent:p,options:{commentString:h}}=o,A=Object.assign({},o,{indent:u,type:null});let f=!1;const g=[];for(let n=0;n<i.length;++n){const c=i[n];let l=null;if(e.isNode(c))!f&&c.spaceBefore&&g.push(""),s(o,g,c.commentBefore,f),c.comment&&(l=c.comment);else if(e.isPair(c)){const t=e.isNode(c.key)?c.key:null;t&&(!f&&t.spaceBefore&&g.push(""),s(o,g,t.commentBefore,f))}f=!1;let d=t.stringify(c,A,()=>l=null,()=>f=!0);l&&(d+=r.lineComment(d,u,h(l))),f&&l&&(f=!1),g.push(a+d)}let m;if(0===g.length)m=c.start+c.end;else{m=g[0];for(let e=1;e<g.length;++e){const t=g[e];m+=t?`\n${p}${t}`:"\n"}}return n?(m+="\n"+r.indentComment(h(n),p),d&&d()):f&&l&&l(),m}function i({items:n},i,{flowChars:o,itemIndent:a}){const{indent:c,indentStep:u,flowCollectionPadding:l,options:{commentString:d}}=i;a+=u;const p=Object.assign({},i,{indent:a,inFlow:!0,type:null});let h=!1,A=0;const f=[]
1462
- ;for(let o=0;o<n.length;++o){const c=n[o];let u=null;if(e.isNode(c))c.spaceBefore&&f.push(""),s(i,f,c.commentBefore,!1),c.comment&&(u=c.comment);else if(e.isPair(c)){const t=e.isNode(c.key)?c.key:null;t&&(t.spaceBefore&&f.push(""),s(i,f,t.commentBefore,!1),t.comment&&(h=!0));const r=e.isNode(c.value)?c.value:null;r?(r.comment&&(u=r.comment),r.commentBefore&&(h=!0)):null==c.value&&t?.comment&&(u=t.comment)}u&&(h=!0);let l=t.stringify(c,p,()=>u=null);o<n.length-1&&(l+=","),u&&(l+=r.lineComment(l,a,d(u))),!h&&(f.length>A||l.includes("\n"))&&(h=!0),f.push(l),A=f.length}const{start:g,end:m}=o;if(0===f.length)return g+m;if(!h){const e=f.reduce((e,t)=>e+t.length+2,2);h=i.options.lineWidth>0&&e>i.options.lineWidth}if(h){let e=g;for(const t of f)e+=t?`\n${u}${c}${t}`:"\n";return`${e}\n${c}${m}`}return`${g}${l}${f.join(" ")}${l}${m}`}function s({indent:e,options:{commentString:t}},n,i,s){if(i&&s&&(i=i.replace(/^\n+/,"")),i){const s=r.indentComment(t(i),e);n.push(s.trimStart())}}
1463
- return stringifyCollection.stringifyCollection=function(e,t,r){return(t.inFlow??e.flow?i:n)(e,t,r)},stringifyCollection}function requireYAMLMap(){if(hasRequiredYAMLMap)return YAMLMap;hasRequiredYAMLMap=1;var e=requireStringifyCollection(),t=requireAddPairToJSMap(),r=requireCollection(),n=requireIdentity$1(),i=requirePair(),s=requireScalar();function o(e,t){const r=n.isScalar(t)?t.value:t;for(const i of e)if(n.isPair(i)){if(i.key===t||i.key===r)return i;if(n.isScalar(i.key)&&i.key.value===r)return i}}let a=class extends r.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(n.MAP,e),this.items=[]}static from(e,t,r){const{keepUndefined:n,replacer:s}=r,o=new this(e),a=(e,a)=>{if("function"==typeof s)a=s.call(t,e,a);else if(Array.isArray(s)&&!s.includes(e))return;(void 0!==a||n)&&o.items.push(i.createPair(e,a,r))};if(t instanceof Map)for(const[e,r]of t)a(e,r);else if(t&&"object"==typeof t)for(const e of Object.keys(t))a(e,t[e])
1464
- ;return"function"==typeof e.sortMapEntries&&o.items.sort(e.sortMapEntries),o}add(e,t){let r;r=n.isPair(e)?e:e&&"object"==typeof e&&"key"in e?new i.Pair(e.key,e.value):new i.Pair(e,e?.value);const a=o(this.items,r.key),c=this.schema?.sortMapEntries;if(a){if(!t)throw new Error(`Key ${r.key} already set`);n.isScalar(a.value)&&s.isScalarValue(r.value)?a.value.value=r.value:a.value=r.value}else if(c){const e=this.items.findIndex(e=>c(r,e)<0);-1===e?this.items.push(r):this.items.splice(e,0,r)}else this.items.push(r)}delete(e){const t=o(this.items,e);if(!t)return!1;return this.items.splice(this.items.indexOf(t),1).length>0}get(e,t){const r=o(this.items,e),i=r?.value;return(!t&&n.isScalar(i)?i.value:i)??void 0}has(e){return!!o(this.items,e)}set(e,t){this.add(new i.Pair(e,t),!0)}toJSON(e,r,n){const i=n?new n:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(i);for(const e of this.items)t.addPairToJSMap(r,i,e);return i}toString(t,r,i){if(!t)return JSON.stringify(this)
1465
- ;for(const e of this.items)if(!n.isPair(e))throw new Error(`Map items must all be pairs; found ${JSON.stringify(e)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),e.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};return YAMLMap.YAMLMap=a,YAMLMap.findPair=o,YAMLMap}function requireMap$1(){if(hasRequiredMap$1)return map$1;hasRequiredMap$1=1;var e=requireIdentity$1(),t=requireYAMLMap();const r={collection:"map",default:!0,nodeClass:t.YAMLMap,tag:"tag:yaml.org,2002:map",resolve:(t,r)=>(e.isMap(t)||r("Expected a mapping for this tag"),t),createNode:(e,r,n)=>t.YAMLMap.from(e,r,n)};return map$1.map=r,map$1}var seq={},YAMLSeq={},hasRequiredYAMLSeq,hasRequiredSeq;function requireYAMLSeq(){if(hasRequiredYAMLSeq)return YAMLSeq;hasRequiredYAMLSeq=1
1466
- ;var e=requireCreateNode(),t=requireStringifyCollection(),r=requireCollection(),n=requireIdentity$1(),i=requireScalar(),s=requireToJS();let o=class extends r.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(n.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=a(e);if("number"!=typeof t)return!1;return this.items.splice(t,1).length>0}get(e,t){const r=a(e);if("number"!=typeof r)return;const i=this.items[r];return!t&&n.isScalar(i)?i.value:i}has(e){const t=a(e);return"number"==typeof t&&t<this.items.length}set(e,t){const r=a(e);if("number"!=typeof r)throw new Error(`Expected a valid index, not ${e}.`);const s=this.items[r];n.isScalar(s)&&i.isScalarValue(t)?s.value=t:this.items[r]=t}toJSON(e,t){const r=[];t?.onCreate&&t.onCreate(r);let n=0;for(const e of this.items)r.push(s.toJS(e,String(n++),t));return r}toString(e,r,n){return e?t.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",
1467
- onChompKeep:n,onComment:r}):JSON.stringify(this)}static from(t,r,n){const{replacer:i}=n,s=new this(t);if(r&&Symbol.iterator in Object(r)){let t=0;for(let o of r){if("function"==typeof i){const e=r instanceof Set?o:String(t++);o=i.call(r,e,o)}s.items.push(e.createNode(o,void 0,n))}}return s}};function a(e){let t=n.isScalar(e)?e.value:e;return t&&"string"==typeof t&&(t=Number(t)),"number"==typeof t&&Number.isInteger(t)&&t>=0?t:null}return YAMLSeq.YAMLSeq=o,YAMLSeq}function requireSeq(){if(hasRequiredSeq)return seq;hasRequiredSeq=1;var e=requireIdentity$1(),t=requireYAMLSeq();const r={collection:"seq",default:!0,nodeClass:t.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve:(t,r)=>(e.isSeq(t)||r("Expected a sequence for this tag"),t),createNode:(e,r,n)=>t.YAMLSeq.from(e,r,n)};return seq.seq=r,seq}var string$4={},hasRequiredString$2;function requireString$2(){if(hasRequiredString$2)return string$4;hasRequiredString$2=1;var e=requireStringifyString();const t={identify:e=>"string"==typeof e,
1468
- default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:(t,r,n,i)=>(r=Object.assign({actualString:!0},r),e.stringifyString(t,r,n,i))};return string$4.string=t,string$4}var tags={},_null={},hasRequired_null;function require_null(){if(hasRequired_null)return _null;hasRequired_null=1;var e=requireScalar();const t={identify:e=>null==e,createNode:()=>new e.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new e.Scalar(null),stringify:({source:e},r)=>"string"==typeof e&&t.test.test(e)?e:r.options.nullStr};return _null.nullTag=t,_null}var bool$1={},hasRequiredBool$1;function requireBool$1(){if(hasRequiredBool$1)return bool$1;hasRequiredBool$1=1;var e=requireScalar();const t={identify:e=>"boolean"==typeof e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new e.Scalar("t"===t[0]||"T"===t[0]),stringify({source:e,value:r},n){if(e&&t.test.test(e)){if(r===("t"===e[0]||"T"===e[0]))return e}
1469
- return r?n.options.trueStr:n.options.falseStr}};return bool$1.boolTag=t,bool$1}var float$1={},stringifyNumber={},hasRequiredStringifyNumber,hasRequiredFloat$1;function requireStringifyNumber(){if(hasRequiredStringifyNumber)return stringifyNumber;return hasRequiredStringifyNumber=1,stringifyNumber.stringifyNumber=function({format:e,minFractionDigits:t,tag:r,value:n}){if("bigint"==typeof n)return String(n);const i="number"==typeof n?n:Number(n);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let s=JSON.stringify(n);if(!e&&t&&(!r||"tag:yaml.org,2002:float"===r)&&/^\d/.test(s)){let e=s.indexOf(".");e<0&&(e=s.length,s+=".");let r=t-(s.length-e-1);for(;r-- >0;)s+="0"}return s},stringifyNumber}function requireFloat$1(){if(hasRequiredFloat$1)return float$1;hasRequiredFloat$1=1;var e=requireScalar(),t=requireStringifyNumber();const r={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
1470
- resolve:e=>"nan"===e.slice(-3).toLowerCase()?NaN:"-"===e[0]?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:t.stringifyNumber},n={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){const r=Number(e.value);return isFinite(r)?r.toExponential():t.stringifyNumber(e)}},i={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){const r=new e.Scalar(parseFloat(t)),n=t.indexOf(".");return-1!==n&&"0"===t[t.length-1]&&(r.minFractionDigits=t.length-n-1),r},stringify:t.stringifyNumber};return float$1.float=i,float$1.floatExp=n,float$1.floatNaN=r,float$1}var int$1={},hasRequiredInt$1;function requireInt$1(){if(hasRequiredInt$1)return int$1;hasRequiredInt$1=1;var e=requireStringifyNumber()
1471
- ;const t=e=>"bigint"==typeof e||Number.isInteger(e),r=(e,t,r,{intAsBigInt:n})=>n?BigInt(e):parseInt(e.substring(t),r);function n(r,n,i){const{value:s}=r;return t(s)&&s>=0?i+s.toString(n):e.stringifyNumber(r)}const i={identify:e=>t(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>r(e,2,8,n),stringify:e=>n(e,8,"0o")},s={identify:t,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>r(e,0,10,n),stringify:e.stringifyNumber},o={identify:e=>t(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>r(e,2,16,n),stringify:e=>n(e,16,"0x")};return int$1.int=s,int$1.intHex=o,int$1.intOct=i,int$1}var schema$2={},hasRequiredSchema$3;function requireSchema$3(){if(hasRequiredSchema$3)return schema$2;hasRequiredSchema$3=1;var e=requireMap$1(),t=require_null(),r=requireSeq(),n=requireString$2(),i=requireBool$1(),s=requireFloat$1(),o=requireInt$1()
1472
- ;const a=[e.map,r.seq,n.string,t.nullTag,i.boolTag,o.intOct,o.int,o.intHex,s.floatNaN,s.floatExp,s.float];return schema$2.schema=a,schema$2}var schema$1={},hasRequiredSchema$2;function requireSchema$2(){if(hasRequiredSchema$2)return schema$1;hasRequiredSchema$2=1;var e=requireScalar(),t=requireMap$1(),r=requireSeq();function n(e){return"bigint"==typeof e||Number.isInteger(e)}const i=({value:e})=>JSON.stringify(e),s=[{identify:e=>"string"==typeof e,default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:i},{identify:e=>null==e,createNode:()=>new e.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:i},{identify:e=>"boolean"==typeof e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>"true"===e,stringify:i},{identify:n,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:r})=>r?BigInt(e):parseInt(e,10),stringify:({value:e})=>n(e)?e.toString():JSON.stringify(e)},{
1473
- identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:i}],o={default:!0,tag:"",test:/^/,resolve:(e,t)=>(t(`Unresolved plain scalar ${JSON.stringify(e)}`),e)},a=[t.map,r.seq].concat(s,o);return schema$1.schema=a,schema$1}var binary$3={},hasRequiredBinary$1;function requireBinary$1(){if(hasRequiredBinary$1)return binary$3;hasRequiredBinary$1=1;var e=require$$0$g,t=requireScalar(),r=requireStringifyString();const n={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,r){if("function"==typeof e.Buffer)return e.Buffer.from(t,"base64");if("function"==typeof atob){const e=atob(t.replace(/[\n\r]/g,"")),r=new Uint8Array(e.length);for(let t=0;t<e.length;++t)r[t]=e.charCodeAt(t);return r}return r("This environment does not support reading binary tags; either Buffer or atob is required"),t},stringify({comment:n,type:i,value:s},o,a,c){if(!s)return""
1474
- ;const u=s;let l;if("function"==typeof e.Buffer)l=u instanceof e.Buffer?u.toString("base64"):e.Buffer.from(u.buffer).toString("base64");else{if("function"!=typeof btoa)throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");{let e="";for(let t=0;t<u.length;++t)e+=String.fromCharCode(u[t]);l=btoa(e)}}if(i??(i=t.Scalar.BLOCK_LITERAL),i!==t.Scalar.QUOTE_DOUBLE){const e=Math.max(o.options.lineWidth-o.indent.length,o.options.minContentWidth),r=Math.ceil(l.length/e),n=new Array(r);for(let t=0,i=0;t<r;++t,i+=e)n[t]=l.substr(i,e);l=n.join(i===t.Scalar.BLOCK_LITERAL?"\n":" ")}return r.stringifyString({comment:n,type:i,value:l},o,a,c)}};return binary$3.binary=n,binary$3}var omap={},pairs$1={},hasRequiredPairs$1,hasRequiredOmap;function requirePairs$1(){if(hasRequiredPairs$1)return pairs$1;hasRequiredPairs$1=1;var e=requireIdentity$1(),t=requirePair(),r=requireScalar(),n=requireYAMLSeq();function i(n,i){
1475
- if(e.isSeq(n))for(let s=0;s<n.items.length;++s){let o=n.items[s];if(!e.isPair(o)){if(e.isMap(o)){o.items.length>1&&i("Each pair must have its own sequence indicator");const e=o.items[0]||new t.Pair(new r.Scalar(null));if(o.commentBefore&&(e.key.commentBefore=e.key.commentBefore?`${o.commentBefore}\n${e.key.commentBefore}`:o.commentBefore),o.comment){const t=e.value??e.key;t.comment=t.comment?`${o.comment}\n${t.comment}`:o.comment}o=e}n.items[s]=e.isPair(o)?o:new t.Pair(o)}}else i("Expected a sequence for this tag");return n}function s(e,r,i){const{replacer:s}=i,o=new n.YAMLSeq(e);o.tag="tag:yaml.org,2002:pairs";let a=0;if(r&&Symbol.iterator in Object(r))for(let e of r){let n,c;if("function"==typeof s&&(e=s.call(r,String(a++),e)),Array.isArray(e)){if(2!==e.length)throw new TypeError(`Expected [key, value] tuple: ${e}`);n=e[0],c=e[1]}else if(e&&e instanceof Object){const t=Object.keys(e);if(1!==t.length)throw new TypeError(`Expected tuple with one key, not ${t.length} keys`);n=t[0],
1476
- c=e[n]}else n=e;o.items.push(t.createPair(n,c,i))}return o}const o={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:i,createNode:s};return pairs$1.createPairs=s,pairs$1.pairs=o,pairs$1.resolvePairs=i,pairs$1}function requireOmap(){if(hasRequiredOmap)return omap;hasRequiredOmap=1;var e=requireIdentity$1(),t=requireToJS(),r=requireYAMLMap(),n=requireYAMLSeq(),i=requirePairs$1();class s extends n.YAMLSeq{constructor(){super(),this.add=r.YAMLMap.prototype.add.bind(this),this.delete=r.YAMLMap.prototype.delete.bind(this),this.get=r.YAMLMap.prototype.get.bind(this),this.has=r.YAMLMap.prototype.has.bind(this),this.set=r.YAMLMap.prototype.set.bind(this),this.tag=s.tag}toJSON(r,n){if(!n)return super.toJSON(r);const i=new Map;n?.onCreate&&n.onCreate(i);for(const r of this.items){let s,o;if(e.isPair(r)?(s=t.toJS(r.key,"",n),o=t.toJS(r.value,s,n)):s=t.toJS(r,"",n),i.has(s))throw new Error("Ordered maps must not include duplicate keys");i.set(s,o)}return i}static from(e,t,r){
1477
- const n=i.createPairs(e,t,r),s=new this;return s.items=n.items,s}}s.tag="tag:yaml.org,2002:omap";const o={collection:"seq",identify:e=>e instanceof Map,nodeClass:s,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,r){const n=i.resolvePairs(t,r),o=[];for(const{key:t}of n.items)e.isScalar(t)&&(o.includes(t.value)?r(`Ordered maps must not include duplicate keys: ${t.value}`):o.push(t.value));return Object.assign(new s,n)},createNode:(e,t,r)=>s.from(e,t,r)};return omap.YAMLOMap=s,omap.omap=o,omap}var schema={},bool={},hasRequiredBool;function requireBool(){if(hasRequiredBool)return bool;hasRequiredBool=1;var e=requireScalar();function t({value:e,source:t},i){return t&&(e?r:n).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}const r={identify:e=>!0===e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new e.Scalar(!0),stringify:t},n={identify:e=>!1===e,default:!0,tag:"tag:yaml.org,2002:bool",
1478
- test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new e.Scalar(!1),stringify:t};return bool.falseTag=n,bool.trueTag=r,bool}var float={},hasRequiredFloat;function requireFloat(){if(hasRequiredFloat)return float;hasRequiredFloat=1;var e=requireScalar(),t=requireStringifyNumber();const r={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>"nan"===e.slice(-3).toLowerCase()?NaN:"-"===e[0]?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:t.stringifyNumber},n={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){const r=Number(e.value);return isFinite(r)?r.toExponential():t.stringifyNumber(e)}},i={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){
1479
- const r=new e.Scalar(parseFloat(t.replace(/_/g,""))),n=t.indexOf(".");if(-1!==n){const e=t.substring(n+1).replace(/_/g,"");"0"===e[e.length-1]&&(r.minFractionDigits=e.length)}return r},stringify:t.stringifyNumber};return float.float=i,float.floatExp=n,float.floatNaN=r,float}var int={},hasRequiredInt;function requireInt(){if(hasRequiredInt)return int;hasRequiredInt=1;var e=requireStringifyNumber();const t=e=>"bigint"==typeof e||Number.isInteger(e);function r(e,t,r,{intAsBigInt:n}){const i=e[0];if("-"!==i&&"+"!==i||(t+=1),e=e.substring(t).replace(/_/g,""),n){switch(r){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`}const t=BigInt(e);return"-"===i?BigInt(-1)*t:t}const s=parseInt(e,r);return"-"===i?-1*s:s}function n(r,n,i){const{value:s}=r;if(t(s)){const e=s.toString(n);return s<0?"-"+i+e.substr(1):i+e}return e.stringifyNumber(r)}const i={identify:t,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>r(e,2,2,n),
1480
- stringify:e=>n(e,2,"0b")},s={identify:t,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>r(e,1,8,n),stringify:e=>n(e,8,"0")},o={identify:t,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>r(e,0,10,n),stringify:e.stringifyNumber},a={identify:t,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>r(e,2,16,n),stringify:e=>n(e,16,"0x")};return int.int=o,int.intBin=i,int.intHex=a,int.intOct=s,int}var set={},hasRequiredSet;function requireSet(){if(hasRequiredSet)return set;hasRequiredSet=1;var e=requireIdentity$1(),t=requirePair(),r=requireYAMLMap();class n extends r.YAMLMap{constructor(e){super(e),this.tag=n.tag}add(n){let i;i=e.isPair(n)?n:n&&"object"==typeof n&&"key"in n&&"value"in n&&null===n.value?new t.Pair(n.key,null):new t.Pair(n,null);r.findPair(this.items,i.key)||this.items.push(i)}get(t,n){const i=r.findPair(this.items,t)
1481
- ;return!n&&e.isPair(i)?e.isScalar(i.key)?i.key.value:i.key:i}set(e,n){if("boolean"!=typeof n)throw new Error("Expected boolean value for set(key, value) in a YAML set, not "+typeof n);const i=r.findPair(this.items,e);i&&!n?this.items.splice(this.items.indexOf(i),1):!i&&n&&this.items.push(new t.Pair(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,r){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,r);throw new Error("Set items must all have null values")}static from(e,r,n){const{replacer:i}=n,s=new this(e);if(r&&Symbol.iterator in Object(r))for(let e of r)"function"==typeof i&&(e=i.call(r,e,e)),s.items.push(t.createPair(e,null,n));return s}}n.tag="tag:yaml.org,2002:set";const i={collection:"map",identify:e=>e instanceof Set,nodeClass:n,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>n.from(e,t,r),resolve(t,r){if(e.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new n,t)
1482
- ;r("Set items must all have null values")}else r("Expected a mapping for this tag");return t}};return set.YAMLSet=n,set.set=i,set}var timestamp$1={},hasRequiredTimestamp$1,hasRequiredSchema$1,hasRequiredTags,hasRequiredSchema;function requireTimestamp$1(){if(hasRequiredTimestamp$1)return timestamp$1;hasRequiredTimestamp$1=1;var e=requireStringifyNumber();function t(e,t){const r=e[0],n="-"===r||"+"===r?e.substring(1):e,i=e=>t?BigInt(e):Number(e),s=n.replace(/_/g,"").split(":").reduce((e,t)=>e*i(60)+i(t),i(0));return"-"===r?i(-1)*s:s}function r(t){let{value:r}=t,n=e=>e;if("bigint"==typeof r)n=e=>BigInt(e);else if(isNaN(r)||!isFinite(r))return e.stringifyNumber(t);let i="";r<0&&(i="-",r*=n(-1));const s=n(60),o=[r%s];return r<60?o.unshift(0):(r=(r-o[0])/s,o.unshift(r%s),r>=60&&(r=(r-o[0])/s,o.unshift(r))),i+o.map(e=>String(e).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}const n={identify:e=>"bigint"==typeof e||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",
1483
- test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,r,{intAsBigInt:n})=>t(e,n),stringify:r},i={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>t(e,!1),stringify:r},s={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){const r=e.match(s.test);if(!r)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");const[,n,i,o,a,c,u]=r.map(Number),l=r[7]?Number((r[7]+"00").substr(1,3)):0;let d=Date.UTC(n,i-1,o,a||0,c||0,u||0,l);const p=r[8];if(p&&"Z"!==p){let e=t(p,!1);Math.abs(e)<30&&(e*=60),d-=6e4*e}return new Date(d)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};return timestamp$1.floatTime=i,timestamp$1.intTime=n,timestamp$1.timestamp=s,
1484
- timestamp$1}function requireSchema$1(){if(hasRequiredSchema$1)return schema;hasRequiredSchema$1=1;var e=requireMap$1(),t=require_null(),r=requireSeq(),n=requireString$2(),i=requireBinary$1(),s=requireBool(),o=requireFloat(),a=requireInt(),c=requireMerge$3(),u=requireOmap(),l=requirePairs$1(),d=requireSet(),p=requireTimestamp$1();const h=[e.map,r.seq,n.string,t.nullTag,s.trueTag,s.falseTag,a.intBin,a.intOct,a.int,a.intHex,o.floatNaN,o.floatExp,o.float,i.binary,c.merge,u.omap,l.pairs,d.set,p.intTime,p.floatTime,p.timestamp];return schema.schema=h,schema}function requireTags(){if(hasRequiredTags)return tags;hasRequiredTags=1;var e=requireMap$1(),t=require_null(),r=requireSeq(),n=requireString$2(),i=requireBool$1(),s=requireFloat$1(),o=requireInt$1(),a=requireSchema$3(),c=requireSchema$2(),u=requireBinary$1(),l=requireMerge$3(),d=requireOmap(),p=requirePairs$1(),h=requireSchema$1(),A=requireSet(),f=requireTimestamp$1()
1485
- ;const g=new Map([["core",a.schema],["failsafe",[e.map,r.seq,n.string]],["json",c.schema],["yaml11",h.schema],["yaml-1.1",h.schema]]),m={binary:u.binary,bool:i.boolTag,float:s.float,floatExp:s.floatExp,floatNaN:s.floatNaN,floatTime:f.floatTime,int:o.int,intHex:o.intHex,intOct:o.intOct,intTime:f.intTime,map:e.map,merge:l.merge,null:t.nullTag,omap:d.omap,pairs:p.pairs,seq:r.seq,set:A.set,timestamp:f.timestamp},y={"tag:yaml.org,2002:binary":u.binary,"tag:yaml.org,2002:merge":l.merge,"tag:yaml.org,2002:omap":d.omap,"tag:yaml.org,2002:pairs":p.pairs,"tag:yaml.org,2002:set":A.set,"tag:yaml.org,2002:timestamp":f.timestamp};return tags.coreKnownTags=y,tags.getTags=function(e,t,r){const n=g.get(t);if(n&&!e)return r&&!n.includes(l.merge)?n.concat(l.merge):n.slice();let i=n;if(!i){if(!Array.isArray(e)){const e=Array.from(g.keys()).filter(e=>"yaml11"!==e).map(e=>JSON.stringify(e)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${e} or define customTags array`)}i=[]}
1486
- if(Array.isArray(e))for(const t of e)i=i.concat(t);else"function"==typeof e&&(i=e(i.slice()));return r&&(i=i.concat(l.merge)),i.reduce((e,t)=>{const r="string"==typeof t?m[t]:t;if(!r){const e=JSON.stringify(t),r=Object.keys(m).map(e=>JSON.stringify(e)).join(", ");throw new Error(`Unknown custom tag ${e}; use one of ${r}`)}return e.includes(r)||e.push(r),e},[])},tags}function requireSchema(){if(hasRequiredSchema)return Schema;hasRequiredSchema=1;var e=requireIdentity$1(),t=requireMap$1(),r=requireSeq(),n=requireString$2(),i=requireTags();const s=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0;return Schema.Schema=class o{constructor({compat:o,customTags:a,merge:c,resolveKnownTags:u,schema:l,sortMapEntries:d,toStringDefaults:p}){this.compat=Array.isArray(o)?i.getTags(o,"compat"):o?i.getTags(null,o):null,this.name="string"==typeof l&&l||"core",this.knownTags=u?i.coreKnownTags:{},this.tags=i.getTags(a,this.name,c),this.toStringOptions=p??null,Object.defineProperty(this,e.MAP,{value:t.map}),
1487
- Object.defineProperty(this,e.SCALAR,{value:n.string}),Object.defineProperty(this,e.SEQ,{value:r.seq}),this.sortMapEntries="function"==typeof d?d:!0===d?s:null}clone(){const e=Object.create(o.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}},Schema}var stringifyDocument={},hasRequiredStringifyDocument,hasRequiredDocument;function requireStringifyDocument(){if(hasRequiredStringifyDocument)return stringifyDocument;hasRequiredStringifyDocument=1;var e=requireIdentity$1(),t=requireStringify$4(),r=requireStringifyComment();return stringifyDocument.stringifyDocument=function(n,i){const s=[];let o=!0===i.directives;if(!1!==i.directives&&n.directives){const e=n.directives.toString(n);e?(s.push(e),o=!0):n.directives.docStart&&(o=!0)}o&&s.push("---");const a=t.createStringifyContext(n,i),{commentString:c}=a.options;if(n.commentBefore){1!==s.length&&s.unshift("");const e=c(n.commentBefore);s.unshift(r.indentComment(e,""))}let u=!1,l=null;if(n.contents){
1488
- if(e.isNode(n.contents)){if(n.contents.spaceBefore&&o&&s.push(""),n.contents.commentBefore){const e=c(n.contents.commentBefore);s.push(r.indentComment(e,""))}a.forceBlockIndent=!!n.comment,l=n.contents.comment}const i=l?void 0:()=>u=!0;let d=t.stringify(n.contents,a,()=>l=null,i);l&&(d+=r.lineComment(d,"",c(l))),"|"!==d[0]&&">"!==d[0]||"---"!==s[s.length-1]?s.push(d):s[s.length-1]=`--- ${d}`}else s.push(t.stringify(n.contents,a));if(n.directives?.docEnd)if(n.comment){const e=c(n.comment);e.includes("\n")?(s.push("..."),s.push(r.indentComment(e,""))):s.push(`... ${e}`)}else s.push("...");else{let e=n.comment;e&&u&&(e=e.replace(/^\n+/,"")),e&&(u&&!l||""===s[s.length-1]||s.push(""),s.push(r.indentComment(c(e),"")))}return s.join("\n")+"\n"},stringifyDocument}function requireDocument(){if(hasRequiredDocument)return Document;hasRequiredDocument=1
1489
- ;var e=requireAlias(),t=requireCollection(),r=requireIdentity$1(),n=requirePair(),i=requireToJS(),s=requireSchema(),o=requireStringifyDocument(),a=requireAnchors(),c=requireApplyReviver(),u=requireCreateNode(),l=requireDirectives();function d(e){if(r.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}return Document.Document=class p{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,r.NODE_TYPE,{value:r.DOC});let i=null;"function"==typeof t||Array.isArray(t)?i=t:void 0===n&&t&&(n=t,t=void 0);const s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=s;let{version:o}=s;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new l.Directives({version:o}),this.setSchema(o,n),
1490
- this.contents=void 0===e?null:this.createNode(e,i,n)}clone(){const e=Object.create(p.prototype,{[r.NODE_TYPE]:{value:r.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=r.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){d(this.contents)&&this.contents.add(e)}addIn(e,t){d(this.contents)&&this.contents.addIn(e,t)}createAlias(t,r){if(!t.anchor){const e=a.anchorNames(this);t.anchor=!r||e.has(r)?a.findNewAnchor(r||"a",e):r}return new e.Alias(t.anchor)}createNode(e,t,n){let i;if("function"==typeof t)e=t.call({"":e},"",e),i=t;else if(Array.isArray(t)){const e=e=>"number"==typeof e||e instanceof String||e instanceof Number,r=t.filter(e).map(String);r.length>0&&(t=t.concat(r)),i=t}else void 0===n&&t&&(n=t,
1491
- t=void 0);const{aliasDuplicateObjects:s,anchorPrefix:o,flow:c,keepUndefined:l,onTagObj:d,tag:p}=n??{},{onAnchor:h,setAnchors:A,sourceObjects:f}=a.createNodeAnchors(this,o||"a"),g={aliasDuplicateObjects:s??!0,keepUndefined:l??!1,onAnchor:h,onTagObj:d,replacer:i,schema:this.schema,sourceObjects:f},m=u.createNode(e,p,g);return c&&r.isCollection(m)&&(m.flow=!0),A(),m}createPair(e,t,r={}){const i=this.createNode(e,null,r),s=this.createNode(t,null,r);return new n.Pair(i,s)}delete(e){return!!d(this.contents)&&this.contents.delete(e)}deleteIn(e){return t.isEmptyPath(e)?null!=this.contents&&(this.contents=null,!0):!!d(this.contents)&&this.contents.deleteIn(e)}get(e,t){return r.isCollection(this.contents)?this.contents.get(e,t):void 0}getIn(e,n){return t.isEmptyPath(e)?!n&&r.isScalar(this.contents)?this.contents.value:this.contents:r.isCollection(this.contents)?this.contents.getIn(e,n):void 0}has(e){return!!r.isCollection(this.contents)&&this.contents.has(e)}hasIn(e){
1492
- return t.isEmptyPath(e)?void 0!==this.contents:!!r.isCollection(this.contents)&&this.contents.hasIn(e)}set(e,r){null==this.contents?this.contents=t.collectionFromPath(this.schema,[e],r):d(this.contents)&&this.contents.set(e,r)}setIn(e,r){t.isEmptyPath(e)?this.contents=r:null==this.contents?this.contents=t.collectionFromPath(this.schema,Array.from(e),r):d(this.contents)&&this.contents.setIn(e,r)}setSchema(e,t={}){let r;switch("number"==typeof e&&(e=String(e)),e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new l.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new l.Directives({version:e}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{const t=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${t}`)}}
1493
- if(t.schema instanceof Object)this.schema=t.schema;else{if(!r)throw new Error("With a null YAML version, the { schema: Schema } option is required");this.schema=new s.Schema(Object.assign(r,t))}}toJS({json:e,jsonArg:t,mapAsMap:r,maxAliasCount:n,onAnchor:s,reviver:o}={}){const a={anchors:new Map,doc:this,keep:!e,mapAsMap:!0===r,mapKeyWarned:!1,maxAliasCount:"number"==typeof n?n:100},u=i.toJS(this.contents,t??"",a);if("function"==typeof s)for(const{count:e,res:t}of a.anchors.values())s(t,e);return"function"==typeof o?c.applyReviver(o,{"":u},"",u):u}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){const t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return o.stringifyDocument(this,e)}},Document}var errors$4={},hasRequiredErrors$4
1494
- ;function requireErrors$4(){if(hasRequiredErrors$4)return errors$4;hasRequiredErrors$4=1;class e extends Error{constructor(e,t,r,n){super(),this.name=e,this.code=r,this.message=n,this.pos=t}}return errors$4.YAMLError=e,errors$4.YAMLParseError=class extends e{constructor(e,t,r){super("YAMLParseError",e,t,r)}},errors$4.YAMLWarning=class extends e{constructor(e,t,r){super("YAMLWarning",e,t,r)}},errors$4.prettifyError=(e,t)=>r=>{if(-1===r.pos[0])return;r.linePos=r.pos.map(e=>t.linePos(e));const{line:n,col:i}=r.linePos[0];r.message+=` at line ${n}, column ${i}`;let s=i-1,o=e.substring(t.lineStarts[n-1],t.lineStarts[n]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){const e=Math.min(s-39,o.length-79);o="…"+o.substring(e),s-=e-1}if(o.length>80&&(o=o.substring(0,79)+"…"),n>1&&/^ *$/.test(o.substring(0,s))){let r=e.substring(t.lineStarts[n-2],t.lineStarts[n-1]);r.length>80&&(r=r.substring(0,79)+"…\n"),o=r+o}if(/[^ ]/.test(o)){let e=1;const t=r.linePos[1]
1495
- ;t&&t.line===n&&t.col>i&&(e=Math.max(1,Math.min(t.col-i,80-s)));const a=" ".repeat(s)+"^".repeat(e);r.message+=`:\n\n${o}\n${a}\n`}},errors$4}var composeDoc={},composeNode={},composeCollection={},resolveBlockMap={},resolveProps={},hasRequiredResolveProps;function requireResolveProps(){if(hasRequiredResolveProps)return resolveProps;return hasRequiredResolveProps=1,resolveProps.resolveProps=function(e,{flow:t,indicator:r,next:n,offset:i,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,u=a,l=a,d="",p="",h=!1,A=!1,f=null,g=null,m=null,y=null,E=null,b=null,C=null;for(const i of e)switch(A&&("space"!==i.type&&"newline"!==i.type&&"comma"!==i.type&&s(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),A=!1),f&&(u&&"comment"!==i.type&&"newline"!==i.type&&s(f,"TAB_AS_INDENT","Tabs are not allowed as indentation"),f=null),i.type){case"space":t||"doc-start"===r&&"flow-collection"===n?.type||!i.source.includes("\t")||(f=i),l=!0;break;case"comment":{
1496
- l||s(i,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const e=i.source.substring(1)||" ";d?d+=p+e:d=e,p="",u=!1;break}case"newline":u?d?d+=i.source:b&&"seq-item-ind"===r||(c=!0):p+=i.source,u=!0,h=!0,(g||m)&&(y=i),l=!0;break;case"anchor":g&&s(i,"MULTIPLE_ANCHORS","A node can have at most one anchor"),i.source.endsWith(":")&&s(i.offset+i.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),g=i,C??(C=i.offset),u=!1,l=!1,A=!0;break;case"tag":m&&s(i,"MULTIPLE_TAGS","A node can have at most one tag"),m=i,C??(C=i.offset),u=!1,l=!1,A=!0;break;case r:(g||m)&&s(i,"BAD_PROP_ORDER",`Anchors and tags must be after the ${i.source} indicator`),b&&s(i,"UNEXPECTED_TOKEN",`Unexpected ${i.source} in ${t??"collection"}`),b=i,u="seq-item-ind"===r||"explicit-key-ind"===r,l=!1;break;case"comma":if(t){E&&s(i,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),E=i,u=!1,l=!1;break}default:s(i,"UNEXPECTED_TOKEN",`Unexpected ${i.type} token`),u=!1,l=!1}
1497
- const v=e[e.length-1],I=v?v.offset+v.source.length:i;return A&&n&&"space"!==n.type&&"newline"!==n.type&&"comma"!==n.type&&("scalar"!==n.type||""!==n.source)&&s(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),f&&(u&&f.indent<=o||"block-map"===n?.type||"block-seq"===n?.type)&&s(f,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:E,found:b,spaceBefore:c,comment:d,hasNewline:h,anchor:g,tag:m,newlineAfterProp:y,end:I,start:C??I}},resolveProps}var utilContainsNewline={},hasRequiredUtilContainsNewline;function requireUtilContainsNewline(){if(hasRequiredUtilContainsNewline)return utilContainsNewline;return hasRequiredUtilContainsNewline=1,utilContainsNewline.containsNewline=function e(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes("\n"))return!0;if(t.end)for(const e of t.end)if("newline"===e.type)return!0;return!1;case"flow-collection":
1498
- for(const r of t.items){for(const e of r.start)if("newline"===e.type)return!0;if(r.sep)for(const e of r.sep)if("newline"===e.type)return!0;if(e(r.key)||e(r.value))return!0}return!1;default:return!0}},utilContainsNewline}var utilFlowIndentCheck={},hasRequiredUtilFlowIndentCheck;function requireUtilFlowIndentCheck(){if(hasRequiredUtilFlowIndentCheck)return utilFlowIndentCheck;hasRequiredUtilFlowIndentCheck=1;var e=requireUtilContainsNewline();return utilFlowIndentCheck.flowIndentCheck=function(t,r,n){if("flow-collection"===r?.type){const i=r.end[0];if(i.indent===t&&("]"===i.source||"}"===i.source)&&e.containsNewline(r)){n(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}},utilFlowIndentCheck}var utilMapIncludes={},hasRequiredUtilMapIncludes,hasRequiredResolveBlockMap;function requireUtilMapIncludes(){if(hasRequiredUtilMapIncludes)return utilMapIncludes;hasRequiredUtilMapIncludes=1;var e=requireIdentity$1();return utilMapIncludes.mapIncludes=function(t,r,n){
1499
- const{uniqueKeys:i}=t.options;if(!1===i)return!1;const s="function"==typeof i?i:(t,r)=>t===r||e.isScalar(t)&&e.isScalar(r)&&t.value===r.value;return r.some(e=>s(e.key,n))},utilMapIncludes}function requireResolveBlockMap(){if(hasRequiredResolveBlockMap)return resolveBlockMap;hasRequiredResolveBlockMap=1;var e=requirePair(),t=requireYAMLMap(),r=requireResolveProps(),n=requireUtilContainsNewline(),i=requireUtilFlowIndentCheck(),s=requireUtilMapIncludes();const o="All mapping items must start at the same column";return resolveBlockMap.resolveBlockMap=function({composeNode:a,composeEmptyNode:c},u,l,d,p){const h=new(p?.nodeClass??t.YAMLMap)(u.schema);u.atRoot&&(u.atRoot=!1);let A=l.offset,f=null;for(const t of l.items){const{start:p,key:g,sep:m,value:y}=t,E=r.resolveProps(p,{indicator:"explicit-key-ind",next:g??m?.[0],offset:A,onError:d,parentIndent:l.indent,startOnNewline:!0}),b=!E.found;if(b){
1500
- if(g&&("block-seq"===g.type?d(A,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in g&&g.indent!==l.indent&&d(A,"BAD_INDENT",o)),!E.anchor&&!E.tag&&!m){f=E.end,E.comment&&(h.comment?h.comment+="\n"+E.comment:h.comment=E.comment);continue}(E.newlineAfterProp||n.containsNewline(g))&&d(g??p[p.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else E.found?.indent!==l.indent&&d(A,"BAD_INDENT",o);u.atKey=!0;const C=E.end,v=g?a(u,g,E,d):c(u,C,p,null,E,d);u.schema.compat&&i.flowIndentCheck(l.indent,g,d),u.atKey=!1,s.mapIncludes(u,h.items,v)&&d(C,"DUPLICATE_KEY","Map keys must be unique");const I=r.resolveProps(m??[],{indicator:"map-value-ind",next:y,offset:v.range[2],onError:d,parentIndent:l.indent,startOnNewline:!g||"block-scalar"===g.type});if(A=I.end,I.found){b&&("block-map"!==y?.type||I.hasNewline||d(A,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),
1501
- u.options.strict&&E.start<I.found.offset-1024&&d(v.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));const r=y?a(u,y,I,d):c(u,A,m,null,I,d);u.schema.compat&&i.flowIndentCheck(l.indent,y,d),A=r.range[2];const n=new e.Pair(v,r);u.options.keepSourceTokens&&(n.srcToken=t),h.items.push(n)}else{b&&d(v.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),I.comment&&(v.comment?v.comment+="\n"+I.comment:v.comment=I.comment);const r=new e.Pair(v);u.options.keepSourceTokens&&(r.srcToken=t),h.items.push(r)}}return f&&f<A&&d(f,"IMPOSSIBLE","Map comment with trailing content"),h.range=[l.offset,A,f??A],h},resolveBlockMap}var resolveBlockSeq={},hasRequiredResolveBlockSeq;function requireResolveBlockSeq(){if(hasRequiredResolveBlockSeq)return resolveBlockSeq;hasRequiredResolveBlockSeq=1;var e=requireYAMLSeq(),t=requireResolveProps(),r=requireUtilFlowIndentCheck()
1502
- ;return resolveBlockSeq.resolveBlockSeq=function({composeNode:n,composeEmptyNode:i},s,o,a,c){const u=new(c?.nodeClass??e.YAMLSeq)(s.schema);s.atRoot&&(s.atRoot=!1),s.atKey&&(s.atKey=!1);let l=o.offset,d=null;for(const{start:e,value:c}of o.items){const p=t.resolveProps(e,{indicator:"seq-item-ind",next:c,offset:l,onError:a,parentIndent:o.indent,startOnNewline:!0});if(!p.found){if(!(p.anchor||p.tag||c)){d=p.end,p.comment&&(u.comment=p.comment);continue}c&&"block-seq"===c.type?a(p.end,"BAD_INDENT","All sequence items must start at the same column"):a(l,"MISSING_CHAR","Sequence item without - indicator")}const h=c?n(s,c,p,a):i(s,p.end,e,null,p,a);s.schema.compat&&r.flowIndentCheck(o.indent,c,a),l=h.range[2],u.items.push(h)}return u.range=[o.offset,l,d??l],u},resolveBlockSeq}var resolveFlowCollection={},resolveEnd={},hasRequiredResolveEnd,hasRequiredResolveFlowCollection,hasRequiredComposeCollection;function requireResolveEnd(){if(hasRequiredResolveEnd)return resolveEnd
1503
- ;return hasRequiredResolveEnd=1,resolveEnd.resolveEnd=function(e,t,r,n){let i="";if(e){let s=!1,o="";for(const a of e){const{source:e,type:c}=a;switch(c){case"space":s=!0;break;case"comment":{r&&!s&&n(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const t=e.substring(1)||" ";i?i+=o+t:i=t,o="";break}case"newline":i&&(o+=e),s=!0;break;default:n(a,"UNEXPECTED_TOKEN",`Unexpected ${c} at node end`)}t+=e.length}}return{comment:i,offset:t}},resolveEnd}function requireResolveFlowCollection(){if(hasRequiredResolveFlowCollection)return resolveFlowCollection;hasRequiredResolveFlowCollection=1;var e=requireIdentity$1(),t=requirePair(),r=requireYAMLMap(),n=requireYAMLSeq(),i=requireResolveEnd(),s=requireResolveProps(),o=requireUtilContainsNewline(),a=requireUtilMapIncludes();const c="Block collections are not allowed within flow collections",u=e=>e&&("block-map"===e.type||"block-seq"===e.type)
1504
- ;return resolveFlowCollection.resolveFlowCollection=function({composeNode:l,composeEmptyNode:d},p,h,A,f){const g="{"===h.start.source,m=g?"flow map":"flow sequence",y=new(f?.nodeClass??(g?r.YAMLMap:n.YAMLSeq))(p.schema);y.flow=!0;const E=p.atRoot;E&&(p.atRoot=!1),p.atKey&&(p.atKey=!1);let b=h.offset+h.start.source.length;for(let n=0;n<h.items.length;++n){const i=h.items[n],{start:f,key:E,sep:C,value:v}=i,I=s.resolveProps(f,{flow:m,indicator:"explicit-key-ind",next:E??C?.[0],offset:b,onError:A,parentIndent:h.indent,startOnNewline:!1});if(!I.found){if(!(I.anchor||I.tag||C||v)){0===n&&I.comma?A(I.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${m}`):n<h.items.length-1&&A(I.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${m}`),I.comment&&(y.comment?y.comment+="\n"+I.comment:y.comment=I.comment),b=I.end;continue}!g&&p.options.strict&&o.containsNewline(E)&&A(E,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}
1505
- if(0===n)I.comma&&A(I.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${m}`);else if(I.comma||A(I.start,"MISSING_CHAR",`Missing , between ${m} items`),I.comment){let t="";e:for(const e of f)switch(e.type){case"comma":case"space":break;case"comment":t=e.source.substring(1);break e;default:break e}if(t){let r=y.items[y.items.length-1];e.isPair(r)&&(r=r.value??r.key),r.comment?r.comment+="\n"+t:r.comment=t,I.comment=I.comment.substring(t.length+1)}}if(g||C||I.found){p.atKey=!0;const e=I.end,n=E?l(p,E,I,A):d(p,e,f,null,I,A);u(E)&&A(n.range,"BLOCK_IN_FLOW",c),p.atKey=!1;const o=s.resolveProps(C??[],{flow:m,indicator:"map-value-ind",next:v,offset:n.range[2],onError:A,parentIndent:h.indent,startOnNewline:!1});if(o.found){if(!g&&!I.found&&p.options.strict){if(C)for(const e of C){if(e===o.found)break;if("newline"===e.type){A(e,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}
1506
- I.start<o.found.offset-1024&&A(o.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else v&&("source"in v&&v.source&&":"===v.source[0]?A(v,"MISSING_CHAR",`Missing space after : in ${m}`):A(o.start,"MISSING_CHAR",`Missing , or : between ${m} items`));const _=v?l(p,v,o,A):o.found?d(p,o.end,C,null,o,A):null;_?u(v)&&A(_.range,"BLOCK_IN_FLOW",c):o.comment&&(n.comment?n.comment+="\n"+o.comment:n.comment=o.comment);const S=new t.Pair(n,_);if(p.options.keepSourceTokens&&(S.srcToken=i),g){const t=y;a.mapIncludes(p,t.items,n)&&A(e,"DUPLICATE_KEY","Map keys must be unique"),t.items.push(S)}else{const e=new r.YAMLMap(p.schema);e.flow=!0,e.items.push(S);const t=(_??n).range;e.range=[n.range[0],t[1],t[2]],y.items.push(e)}b=_?_.range[2]:o.end}else{const e=v?l(p,v,I,A):d(p,I.end,C,null,I,A);y.items.push(e),b=e.range[2],u(v)&&A(e.range,"BLOCK_IN_FLOW",c)}}const C=g?"}":"]",[v,...I]=h.end;let _=b
1507
- ;if(v&&v.source===C)_=v.offset+v.source.length;else{const e=m[0].toUpperCase()+m.substring(1);A(b,E?"MISSING_CHAR":"BAD_INDENT",E?`${e} must end with a ${C}`:`${e} in block collection must be sufficiently indented and end with a ${C}`),v&&1!==v.source.length&&I.unshift(v)}if(I.length>0){const e=i.resolveEnd(I,_,p.options.strict,A);e.comment&&(y.comment?y.comment+="\n"+e.comment:y.comment=e.comment),y.range=[h.offset,_,e.offset]}else y.range=[h.offset,_,_];return y},resolveFlowCollection}function requireComposeCollection(){if(hasRequiredComposeCollection)return composeCollection;hasRequiredComposeCollection=1;var e=requireIdentity$1(),t=requireScalar(),r=requireYAMLMap(),n=requireYAMLSeq(),i=requireResolveBlockMap(),s=requireResolveBlockSeq(),o=requireResolveFlowCollection();function a(e,t,r,n,a,c){const u="block-map"===r.type?i.resolveBlockMap(e,t,r,n,c):"block-seq"===r.type?s.resolveBlockSeq(e,t,r,n,c):o.resolveFlowCollection(e,t,r,n,c),l=u.constructor
1508
- ;return"!"===a||a===l.tagName?(u.tag=l.tagName,u):(a&&(u.tag=a),u)}return composeCollection.composeCollection=function(i,s,o,c,u){const l=c.tag,d=l?s.directives.tagName(l.source,e=>u(l,"TAG_RESOLVE_FAILED",e)):null;if("block-seq"===o.type){const{anchor:e,newlineAfterProp:t}=c,r=e&&l?e.offset>l.offset?e:l:e??l;if(r&&(!t||t.offset<r.offset)){u(r,"MISSING_CHAR","Missing newline after block sequence props")}}const p="block-map"===o.type?"map":"block-seq"===o.type?"seq":"{"===o.start.source?"map":"seq";if(!l||!d||"!"===d||d===r.YAMLMap.tagName&&"map"===p||d===n.YAMLSeq.tagName&&"seq"===p)return a(i,s,o,u,d);let h=s.schema.tags.find(e=>e.tag===d&&e.collection===p);if(!h){const e=s.schema.knownTags[d];if(!e||e.collection!==p)return e?u(l,"BAD_COLLECTION_TYPE",`${e.tag} used for ${p} collection, but expects ${e.collection??"scalar"}`,!0):u(l,"TAG_RESOLVE_FAILED",`Unresolved tag: ${d}`,!0),a(i,s,o,u,d);s.schema.tags.push(Object.assign({},e,{default:!1})),h=e}
1509
- const A=a(i,s,o,u,d,h),f=h.resolve?.(A,e=>u(l,"TAG_RESOLVE_FAILED",e),s.options)??A,g=e.isNode(f)?f:new t.Scalar(f);return g.range=A.range,g.tag=d,h?.format&&(g.format=h.format),g},composeCollection}var composeScalar={},resolveBlockScalar={},hasRequiredResolveBlockScalar;function requireResolveBlockScalar(){if(hasRequiredResolveBlockScalar)return resolveBlockScalar;hasRequiredResolveBlockScalar=1;var e=requireScalar();return resolveBlockScalar.resolveBlockScalar=function(t,r,n){const i=r.offset,s=function({offset:e,props:t},r,n){if("block-scalar-header"!==t[0].type)return n(t[0],"IMPOSSIBLE","Block scalar header not found"),null;const{source:i}=t[0],s=i[0];let o=0,a="",c=-1;for(let t=1;t<i.length;++t){const r=i[t];if(a||"-"!==r&&"+"!==r){const n=Number(r);!o&&n?o=n:-1===c&&(c=e+t)}else a=r}-1!==c&&n(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let u=!1,l="",d=i.length;for(let e=1;e<t.length;++e){const i=t[e];switch(i.type){case"space":u=!0;case"newline":
1510
- d+=i.source.length;break;case"comment":if(r&&!u){n(i,"MISSING_CHAR","Comments must be separated from other tokens by white space characters")}d+=i.source.length,l=i.source.substring(1);break;case"error":n(i,"UNEXPECTED_TOKEN",i.message),d+=i.source.length;break;default:{n(i,"UNEXPECTED_TOKEN",`Unexpected token in block scalar header: ${i.type}`);const e=i.source;e&&"string"==typeof e&&(d+=e.length)}}}return{mode:s,indent:o,chomp:a,comment:l,length:d}}(r,t.options.strict,n);if(!s)return{value:"",type:null,comment:"",range:[i,i,i]};const o=">"===s.mode?e.Scalar.BLOCK_FOLDED:e.Scalar.BLOCK_LITERAL,a=r.source?function(e){const t=e.split(/\n( *)/),r=t[0],n=r.match(/^( *)/),i=n?.[1]?[n[1],r.slice(n[1].length)]:["",r],s=[i];for(let e=1;e<t.length;e+=2)s.push([t[e],t[e+1]]);return s}(r.source):[];let c=a.length;for(let e=a.length-1;e>=0;--e){const t=a[e][1];if(""!==t&&"\r"!==t)break;c=e}if(0===c){const e="+"===s.chomp&&a.length>0?"\n".repeat(Math.max(1,a.length-1)):"";let t=i+s.length
1511
- ;return r.source&&(t+=r.source.length),{value:e,type:o,comment:s.comment,range:[i,t,t]}}let u=r.indent+s.indent,l=r.offset+s.length,d=0;for(let e=0;e<c;++e){const[r,i]=a[e];if(""!==i&&"\r"!==i){if(r.length<u){const e="Block scalars with more-indented leading empty lines must use an explicit indentation indicator";n(l+r.length,"MISSING_CHAR",e)}if(0===s.indent&&(u=r.length),d=e,0===u&&!t.atRoot){n(l,"BAD_INDENT","Block scalar values in collections must be indented")}break}0===s.indent&&r.length>u&&(u=r.length),l+=r.length+i.length+1}for(let e=a.length-1;e>=c;--e)a[e][0].length>u&&(c=e+1);let p="",h="",A=!1;for(let e=0;e<d;++e)p+=a[e][0].slice(u)+"\n";for(let t=d;t<c;++t){let[r,i]=a[t];l+=r.length+i.length+1;const c="\r"===i[i.length-1];if(c&&(i=i.slice(0,-1)),i&&r.length<u){const e=`Block scalar lines must not be less indented than their ${s.indent?"explicit indentation indicator":"first line"}`;n(l-i.length-(c?2:1),"BAD_INDENT",e),r=""}o===e.Scalar.BLOCK_LITERAL?(p+=h+r.slice(u)+i,
1512
- h="\n"):r.length>u||"\t"===i[0]?(" "===h?h="\n":A||"\n"!==h||(h="\n\n"),p+=h+r.slice(u)+i,h="\n",A=!0):""===i?"\n"===h?p+="\n":h="\n":(p+=h+i,h=" ",A=!1)}switch(s.chomp){case"-":break;case"+":for(let e=c;e<a.length;++e)p+="\n"+a[e][0].slice(u);"\n"!==p[p.length-1]&&(p+="\n");break;default:p+="\n"}const f=i+s.length+r.source.length;return{value:p,type:o,comment:s.comment,range:[i,f,f]}},resolveBlockScalar}var resolveFlowScalar={},hasRequiredResolveFlowScalar,hasRequiredComposeScalar;function requireResolveFlowScalar(){if(hasRequiredResolveFlowScalar)return resolveFlowScalar;hasRequiredResolveFlowScalar=1;var e=requireScalar(),t=requireResolveEnd();function r(e){let t,r;try{t=new RegExp("(.*?)(?<![ \t])[ \t]*\r?\n","sy"),r=new RegExp("[ \t]*(.*?)(?:(?<![ \t])[ \t]*)?\r?\n","sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,r=/[ \t]*(.*?)[ \t]*\r?\n/sy}let n=t.exec(e);if(!n)return e;let i=n[1],s=" ",o=t.lastIndex;for(r.lastIndex=o;n=r.exec(e);)""===n[1]?"\n"===s?i+=s:s="\n":(i+=s+n[1],s=" "),
1513
- o=r.lastIndex;const a=/[ \t]*(.*)/sy;return a.lastIndex=o,n=a.exec(e),i+s+(n?.[1]??"")}function n(e,t){let r="",n=e[t+1];for(;!(" "!==n&&"\t"!==n&&"\n"!==n&&"\r"!==n||"\r"===n&&"\n"!==e[t+2]);)"\n"===n&&(r+="\n"),n=e[(t+=1)+1];return r||(r=" "),{fold:r,offset:t}}const i={0:"\0",a:"",b:"\b",e:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function s(e,t,r,n){const i=e.substr(t,r),s=i.length===r&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;if(isNaN(s)){const i=e.substr(t-2,r+2);return n(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${i}`),i}return String.fromCodePoint(s)}return resolveFlowScalar.resolveFlowScalar=function(o,a,c){const{offset:u,type:l,source:d,end:p}=o;let h,A;const f=(e,t,r)=>c(u+e,t,r);switch(l){case"scalar":h=e.Scalar.PLAIN,A=function(e,t){let n="";switch(e[0]){case"\t":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":
1514
- case">":n=`block scalar indicator ${e[0]}`;break;case"@":case"`":n=`reserved character ${e[0]}`}n&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`);return r(e)}(d,f);break;case"single-quoted-scalar":h=e.Scalar.QUOTE_SINGLE,A=function(e,t){"'"===e[e.length-1]&&1!==e.length||t(e.length,"MISSING_CHAR","Missing closing 'quote");return r(e.slice(1,-1)).replace(/''/g,"'")}(d,f);break;case"double-quoted-scalar":h=e.Scalar.QUOTE_DOUBLE,A=function(e,t){let r="";for(let o=1;o<e.length-1;++o){const a=e[o];if("\r"!==a||"\n"!==e[o+1])if("\n"===a){const{fold:t,offset:i}=n(e,o);r+=t,o=i}else if("\\"===a){let n=e[++o];const a=i[n];if(a)r+=a;else if("\n"===n)for(n=e[o+1];" "===n||"\t"===n;)n=e[1+ ++o];else if("\r"===n&&"\n"===e[o+1])for(n=e[1+ ++o];" "===n||"\t"===n;)n=e[1+ ++o];else if("x"===n||"u"===n||"U"===n){const i={x:2,u:4,U:8}[n];r+=s(e,o+1,i,t),o+=i}else{const n=e.substr(o-1,2);t(o-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${n}`),r+=n}}else if(" "===a||"\t"===a){const t=o
1515
- ;let n=e[o+1];for(;" "===n||"\t"===n;)n=e[1+ ++o];"\n"===n||"\r"===n&&"\n"===e[o+2]||(r+=o>t?e.slice(t,o+1):a)}else r+=a}'"'===e[e.length-1]&&1!==e.length||t(e.length,"MISSING_CHAR",'Missing closing "quote');return r}(d,f);break;default:return c(o,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${l}`),{value:"",type:null,comment:"",range:[u,u+d.length,u+d.length]}}const g=u+d.length,m=t.resolveEnd(p,g,a,c);return{value:A,type:h,comment:m.comment,range:[u,g,m.offset]}},resolveFlowScalar}function requireComposeScalar(){if(hasRequiredComposeScalar)return composeScalar;hasRequiredComposeScalar=1;var e=requireIdentity$1(),t=requireScalar(),r=requireResolveBlockScalar(),n=requireResolveFlowScalar();return composeScalar.composeScalar=function(i,s,o,a){const{value:c,type:u,comment:l,range:d}="block-scalar"===s.type?r.resolveBlockScalar(i,s,a):n.resolveFlowScalar(s,i.options.strict,a),p=o?i.directives.tagName(o.source,e=>a(o,"TAG_RESOLVE_FAILED",e)):null;let h,A
1516
- ;h=i.options.stringKeys&&i.atKey?i.schema[e.SCALAR]:p?function(t,r,n,i,s){if("!"===n)return t[e.SCALAR];const o=[];for(const e of t.tags)if(!e.collection&&e.tag===n){if(!e.default||!e.test)return e;o.push(e)}for(const e of o)if(e.test?.test(r))return e;const a=t.knownTags[n];if(a&&!a.collection)return t.tags.push(Object.assign({},a,{default:!1,test:void 0})),a;return s(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,"tag:yaml.org,2002:str"!==n),t[e.SCALAR]}(i.schema,c,p,o,a):"scalar"===s.type?function({atKey:t,directives:r,schema:n},i,s,o){const a=n.tags.find(e=>(!0===e.default||t&&"key"===e.default)&&e.test?.test(i))||n[e.SCALAR];if(n.compat){const t=n.compat.find(e=>e.default&&e.test?.test(i))??n[e.SCALAR];if(a.tag!==t.tag){o(s,"TAG_RESOLVE_FAILED",`Value may be parsed as either ${r.tagString(a.tag)} or ${r.tagString(t.tag)}`,!0)}}return a}(i,c,s,a):i.schema[e.SCALAR];try{const r=h.resolve(c,e=>a(o??s,"TAG_RESOLVE_FAILED",e),i.options);A=e.isScalar(r)?r:new t.Scalar(r)}catch(e){
1517
- const r=e instanceof Error?e.message:String(e);a(o??s,"TAG_RESOLVE_FAILED",r),A=new t.Scalar(c)}return A.range=d,A.source=c,u&&(A.type=u),p&&(A.tag=p),h.format&&(A.format=h.format),l&&(A.comment=l),A},composeScalar}var utilEmptyScalarPosition={},hasRequiredUtilEmptyScalarPosition,hasRequiredComposeNode,hasRequiredComposeDoc,hasRequiredComposer;function requireUtilEmptyScalarPosition(){if(hasRequiredUtilEmptyScalarPosition)return utilEmptyScalarPosition;return hasRequiredUtilEmptyScalarPosition=1,utilEmptyScalarPosition.emptyScalarPosition=function(e,t,r){if(t){r??(r=t.length);for(let n=r-1;n>=0;--n){let r=t[n];switch(r.type){case"space":case"comment":case"newline":e-=r.source.length;continue}for(r=t[++n];"space"===r?.type;)e+=r.source.length,r=t[++n];break}}return e},utilEmptyScalarPosition}function requireComposeNode(){if(hasRequiredComposeNode)return composeNode;hasRequiredComposeNode=1
1518
- ;var e=requireAlias(),t=requireIdentity$1(),r=requireComposeCollection(),n=requireComposeScalar(),i=requireResolveEnd(),s=requireUtilEmptyScalarPosition();const o={composeNode:a,composeEmptyNode:c};function a(s,a,u,l){const d=s.atKey,{spaceBefore:p,comment:h,anchor:A,tag:f}=u;let g,m=!0;switch(a.type){case"alias":g=function({options:t},{offset:r,source:n,end:s},o){const a=new e.Alias(n.substring(1));""===a.source&&o(r,"BAD_ALIAS","Alias cannot be an empty string");a.source.endsWith(":")&&o(r+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);const c=r+n.length,u=i.resolveEnd(s,c,t.strict,o);a.range=[r,c,u.offset],u.comment&&(a.comment=u.comment);return a}(s,a,l),(A||f)&&l(a,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":g=n.composeScalar(s,a,f,l),A&&(g.anchor=A.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":
1519
- g=r.composeCollection(o,s,a,u,l),A&&(g.anchor=A.source.substring(1));break;default:l(a,"UNEXPECTED_TOKEN","error"===a.type?a.message:`Unsupported token (type: ${a.type})`),g=c(s,a.offset,void 0,null,u,l),m=!1}if(A&&""===g.anchor&&l(A,"BAD_ALIAS","Anchor cannot be an empty string"),d&&s.options.stringKeys&&(!t.isScalar(g)||"string"!=typeof g.value||g.tag&&"tag:yaml.org,2002:str"!==g.tag)){l(f??a,"NON_STRING_KEY","With stringKeys, all keys must be strings")}return p&&(g.spaceBefore=!0),h&&("scalar"===a.type&&""===a.source?g.comment=h:g.commentBefore=h),s.options.keepSourceTokens&&m&&(g.srcToken=a),g}function c(e,t,r,i,{spaceBefore:o,comment:a,anchor:c,tag:u,end:l},d){const p={type:"scalar",offset:s.emptyScalarPosition(t,r,i),indent:-1,source:""},h=n.composeScalar(e,p,u,d);return c&&(h.anchor=c.source.substring(1),""===h.anchor&&d(c,"BAD_ALIAS","Anchor cannot be an empty string")),o&&(h.spaceBefore=!0),a&&(h.comment=a,h.range[2]=l),h}return composeNode.composeEmptyNode=c,
1520
- composeNode.composeNode=a,composeNode}function requireComposeDoc(){if(hasRequiredComposeDoc)return composeDoc;hasRequiredComposeDoc=1;var e=requireDocument(),t=requireComposeNode(),r=requireResolveEnd(),n=requireResolveProps();return composeDoc.composeDoc=function(i,s,{offset:o,start:a,value:c,end:u},l){const d=Object.assign({_directives:s},i),p=new e.Document(void 0,d),h={atKey:!1,atRoot:!0,directives:p.directives,options:p.options,schema:p.schema},A=n.resolveProps(a,{indicator:"doc-start",next:c??u?.[0],offset:o,onError:l,parentIndent:0,startOnNewline:!0});A.found&&(p.directives.docStart=!0,!c||"block-map"!==c.type&&"block-seq"!==c.type||A.hasNewline||l(A.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),p.contents=c?t.composeNode(h,c,A,l):t.composeEmptyNode(h,A.end,a,null,A,l);const f=p.contents.range[2],g=r.resolveEnd(u,f,!1,l);return g.comment&&(p.comment=g.comment),p.range=[o,f,g.offset],p},composeDoc}function requireComposer(){
1521
- if(hasRequiredComposer)return composer;hasRequiredComposer=1;var e=process__default,t=requireDirectives(),r=requireDocument(),n=requireErrors$4(),i=requireIdentity$1(),s=requireComposeDoc(),o=requireResolveEnd();function a(e){if("number"==typeof e)return[e,e+1];if(Array.isArray(e))return 2===e.length?e:[e[0],e[1]];const{offset:t,source:r}=e;return[t,t+("string"==typeof r?r.length:1)]}function c(e){let t="",r=!1,n=!1;for(let i=0;i<e.length;++i){const s=e[i];switch(s[0]){case"#":t+=(""===t?"":n?"\n\n":"\n")+(s.substring(1)||" "),r=!0,n=!1;break;case"%":"#"!==e[i+1]?.[0]&&(i+=1),r=!1;break;default:r||(n=!0),r=!1}}return{comment:t,afterEmptyLine:n}}return composer.Composer=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,r,i)=>{const s=a(e);i?this.warnings.push(new n.YAMLWarning(s,t,r)):this.errors.push(new n.YAMLParseError(s,t,r))},this.directives=new t.Directives({version:e.version||"1.2"}),this.options=e}
1522
- decorate(e,t){const{comment:r,afterEmptyLine:n}=c(this.prelude);if(r){const s=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${r}`:r;else if(n||e.directives.docStart||!s)e.commentBefore=r;else if(i.isCollection(s)&&!s.flow&&s.items.length>0){let e=s.items[0];i.isPair(e)&&(e=e.key);const t=e.commentBefore;e.commentBefore=t?`${r}\n${t}`:r}else{const e=s.commentBefore;s.commentBefore=e?`${r}\n${e}`:r}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:c(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,r=-1){for(const t of e)yield*this.next(t);yield*this.end(t,r)}*next(t){switch(e.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(e,r,n)=>{const i=a(t);i[0]+=e,this.onError(i,"BAD_DIRECTIVE",r,n)}),
1523
- this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{const e=s.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!e.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(e,!1),this.doc&&(yield this.doc),this.doc=e,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{const e=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,r=new n.YAMLParseError(a(t),"UNEXPECTED_TOKEN",e);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){const e="Unexpected doc-end without preceding document";this.errors.push(new n.YAMLParseError(a(t),"UNEXPECTED_TOKEN",e));break}this.doc.directives.docEnd=!0;const e=o.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),e.comment){
1524
- const t=this.doc.comment;this.doc.comment=t?`${t}\n${e.comment}`:e.comment}this.doc.range[2]=e.offset;break}default:this.errors.push(new n.YAMLParseError(a(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){const e=Object.assign({_directives:this.directives},this.options),n=new r.Document(void 0,e);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,t,t],this.decorate(n,!1),yield n}}},composer}var cst={},cstScalar={},hasRequiredCstScalar;function requireCstScalar(){if(hasRequiredCstScalar)return cstScalar;hasRequiredCstScalar=1;var e=requireResolveBlockScalar(),t=requireResolveFlowScalar(),r=requireErrors$4(),n=requireStringifyString();function i(e,t){if(t)for(const r of t)switch(r.type){case"space":case"comment":e.push(r);break;case"newline":return e.push(r),!0}return!1}function s(e,t,r){switch(e.type){case"scalar":
1525
- case"double-quoted-scalar":case"single-quoted-scalar":e.type=r,e.source=t;break;case"block-scalar":{const n=e.props.slice(1);let i=t.length;"block-scalar-header"===e.props[0].type&&(i-=e.props[0].source.length);for(const e of n)e.offset+=i;delete e.props,Object.assign(e,{type:r,source:t,end:n});break}case"block-map":case"block-seq":{const n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:"\n"};delete e.items,Object.assign(e,{type:r,source:t,end:[n]});break}default:{const n="indent"in e?e.indent:-1,i="end"in e&&Array.isArray(e.end)?e.end.filter(e=>"space"===e.type||"comment"===e.type||"newline"===e.type):[];for(const t of Object.keys(e))"type"!==t&&"offset"!==t&&delete e[t];Object.assign(e,{type:r,indent:n,source:t,end:i})}}}return cstScalar.createScalarToken=function(e,t){const{implicitKey:r=!1,indent:s,inFlow:o=!1,offset:a=-1,type:c="PLAIN"}=t,u=n.stringifyString({type:c,value:e},{implicitKey:r,indent:s>0?" ".repeat(s):"",inFlow:o,options:{blockQuote:!0,lineWidth:-1}
1526
- }),l=t.end??[{type:"newline",offset:-1,indent:s,source:"\n"}];switch(u[0]){case"|":case">":{const e=u.indexOf("\n"),t=u.substring(0,e),r=u.substring(e+1)+"\n",n=[{type:"block-scalar-header",offset:a,indent:s,source:t}];return i(n,l)||n.push({type:"newline",offset:-1,indent:s,source:"\n"}),{type:"block-scalar",offset:a,indent:s,props:n,source:r}}case'"':return{type:"double-quoted-scalar",offset:a,indent:s,source:u,end:l};case"'":return{type:"single-quoted-scalar",offset:a,indent:s,source:u,end:l};default:return{type:"scalar",offset:a,indent:s,source:u,end:l}}},cstScalar.resolveAsScalar=function(n,i=!0,s){if(n){const o=(e,t,n)=>{const i="number"==typeof e?e:Array.isArray(e)?e[0]:e.offset;if(!s)throw new r.YAMLParseError([i,i+1],t,n);s(i,t,n)};switch(n.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return t.resolveFlowScalar(n,i,o);case"block-scalar":return e.resolveBlockScalar({options:{strict:i}},n,o)}}return null},cstScalar.setScalarValue=function(e,t,r={}){
1527
- let{afterKey:o=!1,implicitKey:a=!1,inFlow:c=!1,type:u}=r,l="indent"in e?e.indent:null;if(o&&"number"==typeof l&&(l+=2),!u)switch(e.type){case"single-quoted-scalar":u="QUOTE_SINGLE";break;case"double-quoted-scalar":u="QUOTE_DOUBLE";break;case"block-scalar":{const t=e.props[0];if("block-scalar-header"!==t.type)throw new Error("Invalid block scalar header");u=">"===t.source[0]?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:u="PLAIN"}const d=n.stringifyString({type:u,value:t},{implicitKey:a||null===l,indent:null!==l&&l>0?" ".repeat(l):"",inFlow:c,options:{blockQuote:!0,lineWidth:-1}});switch(d[0]){case"|":case">":!function(e,t){const r=t.indexOf("\n"),n=t.substring(0,r),s=t.substring(r+1)+"\n";if("block-scalar"===e.type){const t=e.props[0];if("block-scalar-header"!==t.type)throw new Error("Invalid block scalar header");t.source=n,e.source=s}else{const{offset:t}=e,r="indent"in e?e.indent:-1,o=[{type:"block-scalar-header",offset:t,indent:r,source:n}];i(o,"end"in e?e.end:void 0)||o.push({
1528
- type:"newline",offset:-1,indent:r,source:"\n"});for(const t of Object.keys(e))"type"!==t&&"offset"!==t&&delete e[t];Object.assign(e,{type:"block-scalar",indent:r,props:o,source:s})}}(e,d);break;case'"':s(e,d,"double-quoted-scalar");break;case"'":s(e,d,"single-quoted-scalar");break;default:s(e,d,"scalar")}},cstScalar}var cstStringify={},hasRequiredCstStringify;function requireCstStringify(){if(hasRequiredCstStringify)return cstStringify;hasRequiredCstStringify=1;function e(r){switch(r.type){case"block-scalar":{let t="";for(const n of r.props)t+=e(n);return t+r.source}case"block-map":case"block-seq":{let e="";for(const n of r.items)e+=t(n);return e}case"flow-collection":{let e=r.start.source;for(const n of r.items)e+=t(n);for(const t of r.end)e+=t.source;return e}case"document":{let e=t(r);if(r.end)for(const t of r.end)e+=t.source;return e}default:{let e=r.source;if("end"in r&&r.end)for(const t of r.end)e+=t.source;return e}}}function t({start:t,key:r,sep:n,value:i}){let s=""
1529
- ;for(const e of t)s+=e.source;if(r&&(s+=e(r)),n)for(const e of n)s+=e.source;return i&&(s+=e(i)),s}return cstStringify.stringify=r=>"type"in r?e(r):t(r),cstStringify}var cstVisit={},hasRequiredCstVisit,hasRequiredCst;function requireCstVisit(){if(hasRequiredCstVisit)return cstVisit;hasRequiredCstVisit=1;const e=Symbol("break visit"),t=Symbol("skip children"),r=Symbol("remove item");function n(e,t){"type"in e&&"document"===e.type&&(e={start:e.start,value:e.value}),i(Object.freeze([]),e,t)}function i(t,n,s){let o=s(n,t);if("symbol"==typeof o)return o;for(const a of["key","value"]){const c=n[a];if(c&&"items"in c){for(let n=0;n<c.items.length;++n){const o=i(Object.freeze(t.concat([[a,n]])),c.items[n],s);if("number"==typeof o)n=o-1;else{if(o===e)return e;o===r&&(c.items.splice(n,1),n-=1)}}"function"==typeof o&&"key"===a&&(o=o(n,t))}}return"function"==typeof o?o(n,t):o}return n.BREAK=e,n.SKIP=t,n.REMOVE=r,n.itemAtPath=(e,t)=>{let r=e;for(const[e,n]of t){const t=r?.[e]
1530
- ;if(!t||!("items"in t))return;r=t.items[n]}return r},n.parentCollection=(e,t)=>{const r=n.itemAtPath(e,t.slice(0,-1)),i=t[t.length-1][0],s=r?.[i];if(s&&"items"in s)return s;throw new Error("Parent collection not found")},cstVisit.visit=n,cstVisit}function requireCst(){if(hasRequiredCst)return cst;hasRequiredCst=1;var e=requireCstScalar(),t=requireCstStringify(),r=requireCstVisit();return cst.createScalarToken=e.createScalarToken,cst.resolveAsScalar=e.resolveAsScalar,cst.setScalarValue=e.setScalarValue,cst.stringify=t.stringify,cst.visit=r.visit,cst.BOM="\ufeff",cst.DOCUMENT="",cst.FLOW_END="",cst.SCALAR="",cst.isCollection=e=>!!e&&"items"in e,cst.isScalar=e=>!!e&&("scalar"===e.type||"single-quoted-scalar"===e.type||"double-quoted-scalar"===e.type||"block-scalar"===e.type),cst.prettyToken=function(e){switch(e){case"\ufeff":return"<BOM>";case"":return"<DOC>";case"":return"<FLOW_END>";case"":return"<SCALAR>";default:return JSON.stringify(e)}},cst.tokenType=function(e){switch(e){
1531
- case"\ufeff":return"byte-order-mark";case"":return"doc-mode";case"":return"flow-error-end";case"":return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case"\n":case"\r\n":return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case"\t":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null},cst}var lexer={},hasRequiredLexer;function requireLexer(){if(hasRequiredLexer)return lexer;hasRequiredLexer=1;var e=requireCst();function t(e){switch(e){case void 0:case" ":case"\n":case"\r":case"\t":return!0;default:return!1}}
1532
- const r=new Set("0123456789ABCDEFabcdef"),n=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),i=new Set(",[]{}"),s=new Set(" ,[]{}\n\r\t"),o=e=>!e||s.has(e);return lexer.Lexer=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if("string"!=typeof e)throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let r=this.next??"stream";for(;r&&(t||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;" "===t||"\t"===t;)t=this.buffer[++e];return!t||"#"===t||"\n"===t||"\r"===t&&"\n"===this.buffer[e+1]}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let r=this.buffer[e];if(this.indentNext>0){let t=0;for(;" "===r;)r=this.buffer[++t+e];if("\r"===r){
1533
- const r=this.buffer[t+e+1];if("\n"===r||!r&&!this.atEnd)return e+t+1}return"\n"===r||t>=this.indentNext||!r&&!this.atEnd?e+t:-1}if("-"===r||"."===r){const r=this.buffer.substr(e,3);if(("---"===r||"..."===r)&&t(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return("number"!=typeof e||-1!==e&&e<this.pos)&&(e=this.buffer.indexOf("\n",this.pos),this.lineEndPos=e),-1===e?this.atEnd?this.buffer.substring(this.pos):null:("\r"===this.buffer[e-1]&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection()
1534
- ;case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(null===t)return this.setNext("stream");if(t[0]===e.BOM&&(yield*this.pushCount(1),t=t.substring(1)),"%"===t[0]){let e=t.length,r=t.indexOf("#");for(;-1!==r;){const n=t[r-1];if(" "===n||"\t"===n){e=r-1;break}r=t.indexOf("#",r+1)}for(;;){const r=t[e-1];if(" "!==r&&"\t"!==r)break;e-=1}const n=(yield*this.pushCount(e))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){const e=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-e),yield*this.pushNewline(),"stream"}return yield e.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){const e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if("-"===e||"."===e){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start")
1535
- ;const e=this.peek(3);if(("---"===e||"..."===e)&&t(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,"---"===e?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!t(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){const[e,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if(("-"===e||"?"===e||":"===e)&&t(r)){const e=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=e,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);const e=this.getLine();if(null===e)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":
1536
- return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(o),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=(yield*this.parseBlockScalarHeader()),t+=(yield*this.pushSpaces(!0)),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let r,n,i=-1;do{r=yield*this.pushNewline(),r>0?(n=yield*this.pushSpaces(!1),this.indentValue=i=n):n=0,n+=(yield*this.pushSpaces(!0))}while(r+n>0);const s=this.getLine();if(null===s)return this.setNext("flow");if(-1!==i&&i<this.indentNext&&"#"!==s[0]||0===i&&(s.startsWith("---")||s.startsWith("..."))&&t(s[3])){if(!(i===this.indentNext-1&&1===this.flowLevel&&("]"===s[0]||"}"===s[0])))return this.flowLevel=0,yield e.FLOW_END,yield*this.parseLineStart()}let a=0;for(;","===s[a];)a+=(yield*this.pushCount(1)),a+=(yield*this.pushSpaces(!0)),this.flowKey=!1;switch(a+=(yield*this.pushIndicators()),s[a]){
1537
- case void 0:return"flow";case"#":return yield*this.pushCount(s.length-a),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(o),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{const e=this.charAt(1);if(this.flowKey||t(e)||","===e)return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){const e=this.charAt(0);let t=this.buffer.indexOf(e,this.pos+1);if("'"===e)for(;-1!==t&&"'"===this.buffer[t+1];)t=this.buffer.indexOf("'",t+2);else for(;-1!==t;){let e=0;for(;"\\"===this.buffer[t-1-e];)e+=1;if(e%2==0)break;t=this.buffer.indexOf('"',t+1)}const r=this.buffer.substring(0,t);let n=r.indexOf("\n",this.pos);if(-1!==n){for(;-1!==n;){const e=this.continueScalar(n+1)
1538
- ;if(-1===e)break;n=r.indexOf("\n",e)}-1!==n&&(t=n-("\r"===r[n-1]?2:1))}if(-1===t){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){const t=this.buffer[++e];if("+"===t)this.blockScalarKeep=!0;else if(t>"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if("-"!==t)break}return yield*this.pushUntil(e=>t(e)||"#"===e)}*parseBlockScalar(){let t,r=this.pos-1,n=0;e:for(let e=this.pos;t=this.buffer[e];++e)switch(t){case" ":n+=1;break;case"\n":r=e,n=0;break;case"\r":{const t=this.buffer[e+1];if(!t&&!this.atEnd)return this.setNext("block-scalar");if("\n"===t)break}default:break e}if(!t&&!this.atEnd)return this.setNext("block-scalar");if(n>=this.indentNext){-1===this.blockScalarIndent?this.indentNext=n:this.indentNext=this.blockScalarIndent+(0===this.indentNext?1:this.indentNext);do{
1539
- const e=this.continueScalar(r+1);if(-1===e)break;r=this.buffer.indexOf("\n",e)}while(-1!==r);if(-1===r){if(!this.atEnd)return this.setNext("block-scalar");r=this.buffer.length}}let i=r+1;for(t=this.buffer[i];" "===t;)t=this.buffer[++i];if("\t"===t){for(;"\t"===t||" "===t||"\r"===t||"\n"===t;)t=this.buffer[++i];r=i-1}else if(!this.blockScalarKeep)for(;;){let e=r-1,t=this.buffer[e];"\r"===t&&(t=this.buffer[--e]);const i=e;for(;" "===t;)t=this.buffer[--e];if(!("\n"===t&&e>=this.pos&&e+1+n>i))break;r=e}return yield e.SCALAR,yield*this.pushToIndex(r+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){const r=this.flowLevel>0;let n,s=this.pos-1,o=this.pos-1;for(;n=this.buffer[++o];)if(":"===n){const e=this.buffer[o+1];if(t(e)||r&&i.has(e))break;s=o}else if(t(n)){let e=this.buffer[o+1];if("\r"===n&&("\n"===e?(o+=1,n="\n",e=this.buffer[o+1]):s=o),"#"===e||r&&i.has(e))break;if("\n"===n){const e=this.continueScalar(o+1);if(-1===e)break;o=Math.max(o,e-2)}}else{if(r&&i.has(n))break;s=o}
1540
- return n||this.atEnd?(yield e.SCALAR,yield*this.pushToIndex(s+1,!0),r?"flow":"doc"):this.setNext("plain-scalar")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){const r=this.buffer.slice(this.pos,e);return r?(yield r,this.pos+=r.length,r.length):(t&&(yield""),0)}*pushIndicators(){switch(this.charAt(0)){case"!":return(yield*this.pushTag())+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"&":return(yield*this.pushUntil(o))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,r=this.charAt(1);if(t(r)||e&&i.has(r))return e?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,(yield*this.pushCount(1))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators())}}return 0}*pushTag(){if("<"===this.charAt(1)){let e=this.pos+2,r=this.buffer[e];for(;!t(r)&&">"!==r;)r=this.buffer[++e];return yield*this.pushToIndex(">"===r?e+1:e,!1)}{let e=this.pos+1,t=this.buffer[e]
1541
- ;for(;t;)if(n.has(t))t=this.buffer[++e];else{if("%"!==t||!r.has(this.buffer[e+1])||!r.has(this.buffer[e+2]))break;t=this.buffer[e+=3]}return yield*this.pushToIndex(e,!1)}}*pushNewline(){const e=this.buffer[this.pos];return"\n"===e?yield*this.pushCount(1):"\r"===e&&"\n"===this.charAt(1)?yield*this.pushCount(2):0}*pushSpaces(e){let t,r=this.pos-1;do{t=this.buffer[++r]}while(" "===t||e&&"\t"===t);const n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(e){let t=this.pos,r=this.buffer[t];for(;!e(r);)r=this.buffer[++t];return yield*this.pushToIndex(t,!1)}},lexer}var lineCounter={},hasRequiredLineCounter;function requireLineCounter(){if(hasRequiredLineCounter)return lineCounter;hasRequiredLineCounter=1;return lineCounter.LineCounter=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,r=this.lineStarts.length;for(;t<r;){const n=t+r>>1;this.lineStarts[n]<e?t=n+1:r=n}if(this.lineStarts[t]===e)return{
1542
- line:t+1,col:1};if(0===t)return{line:0,col:e};return{line:t,col:e-this.lineStarts[t-1]+1}}}},lineCounter}var parser$1={},hasRequiredParser$2;function requireParser$2(){if(hasRequiredParser$2)return parser$1;hasRequiredParser$2=1;var e=process__default,t=requireCst(),r=requireLexer();function n(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function i(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function s(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function o(e){switch(e.type){case"document":return e.start;case"block-map":{const t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function a(e){if(0===e.length)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":
1543
- case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;"space"===e[++t]?.type;);return e.splice(t,e.length)}function c(e){if("flow-seq-start"===e.start.type)for(const t of e.items)!t.sep||t.value||n(t.start,"explicit-key-ind")||n(t.sep,"map-value-ind")||(t.key&&(t.value=t.key),delete t.key,s(t.value)?t.value.end?Array.prototype.push.apply(t.value.end,t.sep):t.value.end=t.sep:Array.prototype.push.apply(t.start,t.sep),delete t.sep)}return parser$1.Parser=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new r.Lexer,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&0===this.offset&&this.onNewLine(0);for(const r of this.lexer.lex(e,t))yield*this.next(r);t||(yield*this.end())}*next(r){if(this.source=r,e.env.LOG_TOKENS&&console.log("|",t.prettyToken(r)),this.atScalar)return this.atScalar=!1,yield*this.step(),void(this.offset+=r.length);const n=t.tokenType(r)
1544
- ;if(n)if("scalar"===n)this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=n,yield*this.step(),n){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+r.length);break;case"space":this.atNewLine&&" "===r[0]&&(this.indent+=r.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=r.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=r.length}else{const e=`Not a YAML token: ${r}`;yield*this.pop({type:"error",offset:this.offset,message:e,source:r}),this.offset+=r.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){const e=this.peek(1);if("doc-end"!==this.type||e&&"doc-end"===e.type){if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":
1545
- case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}else{for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source})}}peek(e){return this.stack[this.stack.length-e]}*pop(e){const t=e??this.stack.pop();if(t)if(0===this.stack.length)yield t;else{const e=this.peek(1);switch("block-scalar"===t.type?t.indent="indent"in e?e.indent:0:"flow-collection"===t.type&&"document"===e.type&&(t.indent=0),"flow-collection"===t.type&&c(t),e.type){case"document":e.value=t;break;case"block-scalar":e.props.push(t);break;case"block-map":{const r=e.items[e.items.length-1];if(r.value)return e.items.push({start:[],key:t,sep:[]}),void(this.onKeyLine=!0);if(!r.sep)return Object.assign(r,{
1546
- key:t,sep:[]}),void(this.onKeyLine=!r.explicitKey);r.value=t;break}case"block-seq":{const r=e.items[e.items.length-1];r.value?e.items.push({start:[],value:t}):r.value=t;break}case"flow-collection":{const r=e.items[e.items.length-1];return void(!r||r.value?e.items.push({start:[],key:t,sep:[]}):r.sep?r.value=t:Object.assign(r,{key:t,sep:[]}))}default:yield*this.pop(),yield*this.pop(t)}if(!("document"!==e.type&&"block-map"!==e.type&&"block-seq"!==e.type||"block-map"!==t.type&&"block-seq"!==t.type)){const r=t.items[t.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&-1===i(r.start)&&(0===t.indent||r.start.every(e=>"comment"!==e.type||e.indent<t.indent))&&("document"===e.type?e.end=r.start:e.items.push({start:r.start}),t.items.splice(-1,1))}}else{const e="Tried to pop an empty stack";yield{type:"error",offset:this.offset,source:"",message:e}}}*stream(){switch(this.type){case"directive-line":return void(yield{type:"directive",offset:this.offset,source:this.source})
1547
- ;case"byte-order-mark":case"space":case"comment":case"newline":return void(yield this.sourceToken);case"doc-mode":case"doc-start":{const e={type:"document",offset:this.offset,start:[]};return"doc-start"===this.type&&e.start.push(this.sourceToken),void this.stack.push(e)}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":return void(-1!==i(e.start)?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken));case"anchor":case"tag":case"space":case"comment":case"newline":return void e.start.push(this.sourceToken)}const t=this.startBlockValue(e);t?this.stack.push(t):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if("map-value-ind"===this.type){const t=a(o(this.peek(2)));let r;e.end?(r=e.end,r.push(this.sourceToken),delete e.end):r=[this.sourceToken]
1548
- ;const n={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:t,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=n}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":return void e.props.push(this.sourceToken);case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let e=this.source.indexOf("\n")+1;for(;0!==e;)this.onNewLine(this.offset+e),e=this.source.indexOf("\n",e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){const r="end"in t.value?t.value.end:void 0,n=Array.isArray(r)?r[r.length-1]:void 0;"comment"===n?.type?r?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]
1549
- });else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){const r=e.items[e.items.length-2],n=r?.value?.end;if(Array.isArray(n))return Array.prototype.push.apply(n,t.start),n.push(this.sourceToken),void e.items.pop()}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){const r=!this.onKeyLine&&this.indent===e.indent,i=r&&(t.sep||t.explicitKey)&&"seq-item-ind"!==this.type;let o=[];if(i&&t.sep&&!t.value){const r=[];for(let n=0;n<t.sep.length;++n){const i=t.sep[n];switch(i.type){case"newline":r.push(n);break;case"space":break;case"comment":i.indent>e.indent&&(r.length=0);break;default:r.length=0}}r.length>=2&&(o=t.sep.splice(r[1]))}switch(this.type){case"anchor":case"tag":return void(i||t.value?(o.push(this.sourceToken),e.items.push({start:o}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken));case"explicit-key-ind":return t.sep||t.explicitKey?i||t.value?(o.push(this.sourceToken),e.items.push({start:o,
1550
- explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}):(t.start.push(this.sourceToken),t.explicitKey=!0),void(this.onKeyLine=!0);case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(n(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]});else if(s(t.key)&&!n(t.sep,"newline")){const e=a(t.start),r=t.key,n=t.sep;n.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:e,key:r,sep:n}]})}else o.length>0?t.sep=t.sep.concat(o,this.sourceToken):t.sep.push(this.sourceToken);else if(n(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const e=a(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:e,
1551
- key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||i?e.items.push({start:o,key:null,sep:[this.sourceToken]}):n(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return void(this.onKeyLine=!0);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const r=this.flowScalar(this.type);return void(i||t.value?(e.items.push({start:o,key:r,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(r):(Object.assign(t,{key:r,sep:[]}),this.onKeyLine=!0))}default:{const i=this.startBlockValue(e);if(i){if("block-seq"===i.type){if(!t.explicitKey&&t.sep&&!n(t.sep,"newline"))return void(yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source}))}else r&&e.items.push({start:o});return void this.stack.push(i)}}}}yield*this.pop(),
1552
- yield*this.step()}*blockSequence(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){const r="end"in t.value?t.value.end:void 0,n=Array.isArray(r)?r[r.length-1]:void 0;"comment"===n?.type?r?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){const r=e.items[e.items.length-2],n=r?.value?.end;if(Array.isArray(n))return Array.prototype.push.apply(n,t.start),n.push(this.sourceToken),void e.items.pop()}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;return void t.start.push(this.sourceToken);case"seq-item-ind":if(this.indent!==e.indent)break;return void(t.value||n(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken))}if(this.indent>e.indent){const t=this.startBlockValue(e)
1553
- ;if(t)return void this.stack.push(t)}yield*this.pop(),yield*this.step()}*flowCollection(e){const t=e.items[e.items.length-1];if("flow-error-end"===this.type){let e;do{yield*this.pop(),e=this.peek(1)}while(e&&"flow-collection"===e.type)}else if(0===e.end.length){switch(this.type){case"comma":case"explicit-key-ind":return void(!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken));case"map-value-ind":return void(!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]}));case"space":case"comment":case"newline":case"anchor":case"tag":return void(!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken));case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const r=this.flowScalar(this.type);return void(!t||t.value?e.items.push({start:[],key:r,sep:[]
1554
- }):t.sep?this.stack.push(r):Object.assign(t,{key:r,sep:[]}))}case"flow-map-end":case"flow-seq-end":return void e.end.push(this.sourceToken)}const r=this.startBlockValue(e);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{const t=this.peek(2);if("block-map"===t.type&&("map-value-ind"===this.type&&t.indent===e.indent||"newline"===this.type&&!t.items[t.items.length-1].sep))yield*this.pop(),yield*this.step();else if("map-value-ind"===this.type&&"flow-collection"!==t.type){const r=a(o(t));c(e);const n=e.end.splice(1,e.end.length);n.push(this.sourceToken);const i={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:r,key:e,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf("\n")+1;for(;0!==e;)this.onNewLine(this.offset+e),e=this.source.indexOf("\n",e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){
1555
- case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;const t=a(o(e));return t.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;const t=a(o(e));return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return"comment"===this.type&&(!(this.indent<=t)&&e.every(e=>"newline"===e.type||"space"===e.type))}
1556
- *documentEnd(e){"doc-mode"!==this.type&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],"newline"===this.type&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],"newline"===this.type&&(yield*this.pop())}}},parser$1}var publicApi={},hasRequiredPublicApi,hasRequiredDist$1;function requirePublicApi(){if(hasRequiredPublicApi)return publicApi;hasRequiredPublicApi=1;var e=requireComposer(),t=requireDocument(),r=requireErrors$4(),n=requireLog(),i=requireIdentity$1(),s=requireLineCounter(),o=requireParser$2();function a(e){const t=!1!==e.prettyErrors;return{lineCounter:e.lineCounter||t&&new s.LineCounter||null,prettyErrors:t}}function c(t,n={}){const{lineCounter:i,prettyErrors:s}=a(n),c=new o.Parser(i?.addNewLine),u=new e.Composer(n);let l=null
1557
- ;for(const e of u.compose(c.parse(t),!0,t.length))if(l){if("silent"!==l.options.logLevel){l.errors.push(new r.YAMLParseError(e.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}}else l=e;return s&&i&&(l.errors.forEach(r.prettifyError(t,i)),l.warnings.forEach(r.prettifyError(t,i))),l}return publicApi.parse=function(e,t,r){let i;"function"==typeof t?i=t:void 0===r&&t&&"object"==typeof t&&(r=t);const s=c(e,r);if(!s)return null;if(s.warnings.forEach(e=>n.warn(s.options.logLevel,e)),s.errors.length>0){if("silent"!==s.options.logLevel)throw s.errors[0];s.errors=[]}return s.toJS(Object.assign({reviver:i},r))},publicApi.parseAllDocuments=function(t,n={}){const{lineCounter:i,prettyErrors:s}=a(n),c=new o.Parser(i?.addNewLine),u=new e.Composer(n),l=Array.from(u.compose(c.parse(t)));if(s&&i)for(const e of l)e.errors.forEach(r.prettifyError(t,i)),e.warnings.forEach(r.prettifyError(t,i));return l.length>0?l:Object.assign([],{empty:!0
1558
- },u.streamInfo())},publicApi.parseDocument=c,publicApi.stringify=function(e,r,n){let s=null;if("function"==typeof r||Array.isArray(r)?s=r:void 0===n&&r&&(n=r),"string"==typeof n&&(n=n.length),"number"==typeof n){const e=Math.round(n);n=e<1?void 0:e>8?{indent:8}:{indent:e}}if(void 0===e){const{keepUndefined:e}=n??r??{};if(!e)return}return i.isDocument(e)&&!s?e.toString(n):new t.Document(e,s,n).toString(n)},publicApi}function requireDist$1(){if(hasRequiredDist$1)return dist$1;hasRequiredDist$1=1;var e=requireComposer(),t=requireDocument(),r=requireSchema(),n=requireErrors$4(),i=requireAlias(),s=requireIdentity$1(),o=requirePair(),a=requireScalar(),c=requireYAMLMap(),u=requireYAMLSeq(),l=requireCst(),d=requireLexer(),p=requireLineCounter(),h=requireParser$2(),A=requirePublicApi(),f=requireVisit();return dist$1.Composer=e.Composer,dist$1.Document=t.Document,dist$1.Schema=r.Schema,dist$1.YAMLError=n.YAMLError,dist$1.YAMLParseError=n.YAMLParseError,dist$1.YAMLWarning=n.YAMLWarning,
1559
- dist$1.Alias=i.Alias,dist$1.isAlias=s.isAlias,dist$1.isCollection=s.isCollection,dist$1.isDocument=s.isDocument,dist$1.isMap=s.isMap,dist$1.isNode=s.isNode,dist$1.isPair=s.isPair,dist$1.isScalar=s.isScalar,dist$1.isSeq=s.isSeq,dist$1.Pair=o.Pair,dist$1.Scalar=a.Scalar,dist$1.YAMLMap=c.YAMLMap,dist$1.YAMLSeq=u.YAMLSeq,dist$1.CST=l,dist$1.Lexer=d.Lexer,dist$1.LineCounter=p.LineCounter,dist$1.Parser=h.Parser,dist$1.parse=A.parse,dist$1.parseAllDocuments=A.parseAllDocuments,dist$1.parseDocument=A.parseDocument,dist$1.stringify=A.stringify,dist$1.visit=f.visit,dist$1.visitAsync=f.visitAsync,dist$1}var distExports=requireDist$1();class UnknownToolError extends Error{constructor(e){super(`Unknown tool: '${e}'`),this.toolName=e}}const easyModelAliases={"o3-mini-2025-01-31":"openai-maybe-stream","o4-mini-2025-04-16":"openai-maybe-stream","gpt-4o-2024-08-06":"openai-maybe-stream","gpt-4.1-2025-04-14":"openai-maybe-stream","claude-3-7-sonnet-20250219":"anthropic",
1560
- "claude-sonnet-4-20250514":"anthropic","claude-opus-4-20250514":"anthropic","us.anthropic.claude-sonnet-4-20250514-v1:0":"bedrock","us.anthropic.claude-opus-4-20250514-v1:0":"bedrock","us.anthropic.claude-3-7-sonnet-20250219-v1:0":"bedrock","accounts/fireworks/models/deepseek-r1":"deepseek","accounts/fireworks/models/llama-v3p1-405b-instruct":"llama","gemini-2.0-pro-exp-02-05":"google-no-stream"};function isEasyModelAlias(e){return e in easyModelAliases}const complicatedModelAliases={"gpt-4o":e=>{e.modelClient="openai",e.modelParams??={},e.modelParams.model="gpt-4o-2024-08-06"},"cerebras-llama-4-scout-17b-16e-instruct":e=>{e.modelClient="cerebras",e.modelParams??={temperature:.6},e.modelParams.model="llama-4-scout-17b-16e-instruct"}};function isComplicatedModelAlias(e){return e in complicatedModelAliases}var toml={},parse$4={exports:{}},tomlParser={exports:{}
1419
+ ;for(const n of i)try{if((await specLinkedPaths(t,n,r,e.projectDir)).includes(s))return n}catch(t){e.reporter.alert("error",`Failed to check spec file ${n}: ${t instanceof Error?t.message:String(t)}`);continue}}const returnSchema={name:"testOutput",schema:objectType$1({numPassingTests:numberType$1(),numFailingTests:numberType$1(),numErrorTests:numberType$1(),numTotalTests:numberType$1(),testLineCoveragePercentage:numberType$1(),testBranchCoveragePercentage:numberType$1(),testFunctionCoveragePercentage:numberType$1(),testStatementCoveragePercentage:numberType$1()})};async function analyseResults(e,t){const r=formatRunTestCommandUserPrompt(e);return{...await t(RUN_TEST_COMMAND_SYSTEM_TEMPLATE).user(r).object(returnSchema),fullResponse:e}}
1420
+ const RUN_TEST_COMMAND_SYSTEM_TEMPLATE="You are a test output parser. Populate the fields based on the test output. If test output contains test coverage related metrics populate them as well, otherwise populate them with -1. If test suites cannot run, report them as errors.",RUN_TEST_COMMAND_USER_TEMPLATE="{testOutput}";function formatRunTestCommandUserPrompt(e){return RUN_TEST_COMMAND_USER_TEMPLATE.replace("{testOutput}",e)}async function runTests(e,t,r,n,i,s){if(!isLocalFsd(r))throw new Error("runTests only works with local FSDs");let o=e;if(o.includes("{files}"))o=o.replace("{files}",t.join(" "));else if(o.includes("{maven-classes}")||o.includes("{gradle-classes}")){const e=t.map(e=>convertFilenameToJavaClass(e,n));if(e.length>0){if(o.includes("{maven-classes}")){const t=formatClassesForTestRunner("maven",e);o=o.replace("{maven-classes}",t)}if(o.includes("{gradle-classes}")){const t=formatClassesForTestRunner("gradle",e);o=o.replace("{gradle-classes}",t)}
1421
+ }else o=o.replace(" {maven-classes}",""),o=o.replace(" {gradle-classes}","")}return await n.exec({cmd:o,cwd:r.root,timeoutSecs:i,mergeStdStreams:!0,inactivityTimeoutSecs:s})}function formatClassesForTestRunner(e,t){return"gradle"===e?t.map(e=>`--tests "${e}"`).join(" "):`-Dtest=${t.join(",")}`}function convertFilenameToJavaClass(e,t){const r=e.replace(/\\/g,"/"),n=r.indexOf("/src/test/java/");if(-1===n){const n=r.match(/.*src\/test\/java\/(.+)\.java$/);if(n&&n[1])return n[1].replace(/\//g,".");t.logger.warn({filePath:e},"Could not determine fully qualified class name from path, using simple class name");return(r.split("/").pop()||"").replace(/\.java$/,"")}return r.substring(n+15).replace(/\.java$/,"").replace(/\//g,".")}const testResultFileName="test-results.json",getFullTestResultsPath=e=>`${DEFAULT_TESSL_DIRS.testResultsDirectory}/${e}/${testResultFileName}`,testOutputSchema=returnSchema.schema.extend({fullResponse:stringType$1()}),validateTestOutput=e=>{
1422
+ const t=testOutputSchema.safeParse(e);if(!t.success)throw new Error(`Invalid test output format: ${t.error.errors.map(e=>`${e.path.join(".")}: ${e.message}`).join(", ")}`);return t.data},readTestResults=async(e,t)=>{const r=await t.readText(getFullTestResultsPath(e));if(!r)throw new Error(`No test results found in session data at: ${getFullTestResultsPath(e)}`);const n=JSON.parse(r);return validateTestOutput(n)},saveTestResults=async(e,t,r)=>(await r.writeText(getFullTestResultsPath(e),JSON.stringify(t,null,2)),getFullTestResultsPath(e));function _nullishCoalesce$L(e,t){return null!=e?e:t()}function _optionalChain$S(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}
1423
+ const testCommandDescription=enableTestRunners()?'Command override to use for running tests in fix loop (e.g. "npm test -- {files}", "mvn test {maven-classes}") - if not provided an appropriate runner will be generated. Supports placeholders: {files} for test file paths, {maven-classes} for Maven test classes, {gradle-classes} for Gradle test classes':'Command to use for running tests (e.g. "npm test -- {files}", "mvn test {maven-classes}", "gradle test {gradle-classes}"). Supports placeholders: {files} for test file paths, {maven-classes} for Maven test classes, {gradle-classes} for Gradle test classes',testParamsSchema=objectType$1({spec:stringType$1().describe("Path to the spec to test, relative to the project root. Must be a .spec.md file.").transform(stripSurroundingQuotes).refine(e=>e.endsWith(SPEC_FILE_EXTENSION),{message:`Spec files must end with ${SPEC_FILE_EXTENSION}`}),timeoutSecs:numberType$1().describe("Override test execution timeout, specified in seconds").default(300),
1424
+ ...enableTestRunners()&&{regenerateTestRunner:booleanType$1().describe("Force regeneration of the test runner (defaults to using an existing one if available)").optional()},inactivityTimeoutSecs:numberType$1().describe("Override test *inactivity* timeout, specified in seconds. This will cause the test to timeout if nothing is written to stdout or stderr for x seconds").default(10),testCommand:enableTestRunners()?stringType$1().describe(testCommandDescription).optional():stringType$1().describe(testCommandDescription),lockTests:booleanType$1().describe("Lock tests if all tests are passing").optional().default(!1)}),testTool={name:"test",type:"fsd",impl:test,paramsSchema:testParamsSchema,description:"Run tests for the provided spec",visibility:"public",denyRunIn:["cloud"],positionalParam:"spec"};async function test({fsd:e,params:t,rc:r,utils:n}){const{spec:i,testCommand:s,timeoutSecs:o,inactivityTimeoutSecs:a}=t,{reporter:c}=r;if(c.hideOverview(),
1425
+ !isLocalFsd(e))throw new Error("test tool only works with local FSDs");const u=await e.readText(i);if(!u)throw new Error(`Failed to find spec: ${i}`);const l=await specLinkedPaths(e,i,[findTestPaths],e.root);if(0===l.length)return c.success([`No test links found in spec: ${i}, nothing to run`]);const d=[];if(await Promise.all(l.map(async t=>{await e.readText(t)&&d.push(t)})),0===d.length)return await saveTestResults(i,{numPassingTests:0,numFailingTests:0,numErrorTests:0,numTotalTests:0,testLineCoveragePercentage:0,testBranchCoveragePercentage:0,testFunctionCoveragePercentage:0,testStatementCoveragePercentage:0,fullResponse:"Skipped running tests: No generated test files found."},e),c.success(["No generated test files found."]);let p;if(c.heading(`Running tests for ${i}`),s){const t=await specLinkedPaths(e,i,[findTestPaths],e.root);p=await runTests(s,t,e,r,o,a)}else{const i=await ensureTestRunner({fsd:e,params:t,rc:r,utils:n});if(r.reporter.message("Executing test runner"),
1426
+ p=await r.exec({cmd:`sh ${i}`,cwd:e.root,timeoutSecs:o,inactivityTimeoutSecs:a,mergeStdStreams:!0}),p.code===SUCCESS?"SIGTERM"===p.signal?r.logger.debug({testResults:p,timeoutType:p.timeoutType},"Test script timed out"):r.logger.debug({testResults:p},"Test script ran successfully"):r.logger.error({testResults:p},"Test script encountered an error"),126===p.code||_optionalChain$S([p,"access",e=>e.stdout,"optionalAccess",e=>e.includes,"call",e=>e("Permission denied")]))return r.reporter.failure("Failed to run test file: Permission denied",{testRunnerPath:i})}let h=_nullishCoalesce$L(p.stdout,()=>"");if("inactivity"===_optionalChain$S([p,"optionalAccess",e=>e.timeoutType]))h+=`Timed out as nothing was output for ${t.inactivityTimeoutSecs} seconds`;else if("process"===_optionalChain$S([p,"optionalAccess",e=>e.timeoutType]))h+=`Timed out after ${t.timeoutSecs} seconds`;else if(p.error){let e="Unexpected error"
1427
+ ;p.error&&p.error instanceof Error?e=p.error.message:"string"==typeof p.error&&(e=p.error),h+=`Unexpected error running test process. Process exited with error: "${e}", code: ${p.code}, and signal: ${p.signal}`}const A=await analyseResults(h,n.script),f=await saveTestResults(i,A,e),g=0===A.numFailingTests&&0===A.numErrorTests;if(c.alert(g?"success":"error",`${A.numErrorTests} test suite errors, ${A.numPassingTests}/${A.numTotalTests} tests passed.`),g&&t.lockTests){const t=findTests(specFromMarkdown(u)).filter(e=>"draft"===e.kind),r=[...new Set(t.map(e=>e.path))],n=(await Promise.all(r.map(async t=>await e.readText(t)?t:null))).filter(e=>null!==e),s=r.reduce((e,t)=>{if(!n.includes(t))return e;const r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`\\[@test\\]\\(${r}\\)`,"g");return e.replace(i,"$& { .locked }")},u);c.message(`Converted ${n.length} draft ${pluralize$1("test",n.length)} to locked.`),await e.writeText(i,s)}
1428
+ return"inactivity"===_optionalChain$S([p,"optionalAccess",e=>e.timeoutType])?r.reporter.summary([`Tests timed out as nothing was output for ${t.inactivityTimeoutSecs} seconds. Consider re-running with a higher value for the --inactivity-timeout-secs param`]):"process"===_optionalChain$S([p,"optionalAccess",e=>e.timeoutType])&&r.reporter.summary([`Tests timed out after ${t.timeoutSecs} seconds. Consider re-running with a higher value for the --timeout-secs parameter`]),r.reporter.summary([`${i}: Saved test results to session data at ${f}`,`${A.numErrorTests} suite errors, ${A.numFailingTests} failures and ${A.numPassingTests}/${A.numTotalTests} passing`]),r.logger.info({result:h},`Test results: ${A.numErrorTests} test suite errors, ${A.numPassingTests} out of ${A.numTotalTests} tests passed.`),g?SUCCESS:FAILURE}const ensureTestRunner=async({params:e,fsd:t,rc:r,utils:n})=>{let i=getTestRunnerPath(e.spec)
1429
+ ;return enableTestRunners()&&"regenerateTestRunner"in e&&e.regenerateTestRunner||!await t.exists(i)?(r.logger.debug({testRunnerPath:i,spec:e.spec},"Generating new test runner"),i=await generateTestRunner({spec:e.spec,fsd:t,projectDir:r.projectDir,script:n.script,systemMessage:await getSystemPrompt(r.projectDir)})):r.logger.debug({testRunnerPath:i,spec:e.spec},"Using existing test runner"),i};class ResponseValidationError extends Error{constructor(e,t){super(e),this.attempts=t}}var dist$1={},composer={},directives={},identity$3={},hasRequiredIdentity$1;function requireIdentity$1(){if(hasRequiredIdentity$1)return identity$3;hasRequiredIdentity$1=1;const e=Symbol.for("yaml.alias"),t=Symbol.for("yaml.document"),r=Symbol.for("yaml.map"),n=Symbol.for("yaml.pair"),i=Symbol.for("yaml.scalar"),s=Symbol.for("yaml.seq"),o=Symbol.for("yaml.node.type"),a=e=>!!e&&"object"==typeof e&&e[o]===i;function c(e){if(e&&"object"==typeof e)switch(e[o]){case r:case s:return!0}return!1}
1430
+ return identity$3.ALIAS=e,identity$3.DOC=t,identity$3.MAP=r,identity$3.NODE_TYPE=o,identity$3.PAIR=n,identity$3.SCALAR=i,identity$3.SEQ=s,identity$3.hasAnchor=e=>(a(e)||c(e))&&!!e.anchor,identity$3.isAlias=t=>!!t&&"object"==typeof t&&t[o]===e,identity$3.isCollection=c,identity$3.isDocument=e=>!!e&&"object"==typeof e&&e[o]===t,identity$3.isMap=e=>!!e&&"object"==typeof e&&e[o]===r,identity$3.isNode=function(t){if(t&&"object"==typeof t)switch(t[o]){case e:case r:case i:case s:return!0}return!1},identity$3.isPair=e=>!!e&&"object"==typeof e&&e[o]===n,identity$3.isScalar=a,identity$3.isSeq=e=>!!e&&"object"==typeof e&&e[o]===s,identity$3}var visit={},hasRequiredVisit,hasRequiredDirectives;function requireVisit(){if(hasRequiredVisit)return visit;hasRequiredVisit=1;var e=requireIdentity$1();const t=Symbol("break visit"),r=Symbol("skip children"),n=Symbol("remove node");function i(t,r){const i=c(r);if(e.isDocument(t)){s(null,t.contents,i,Object.freeze([t]))===n&&(t.contents=null)
1431
+ }else s(null,t,i,Object.freeze([]))}function s(r,i,o,a){const c=u(r,i,o,a);if(e.isNode(c)||e.isPair(c))return l(r,a,c),s(r,c,o,a);if("symbol"!=typeof c)if(e.isCollection(i)){a=Object.freeze(a.concat(i));for(let e=0;e<i.items.length;++e){const r=s(e,i.items[e],o,a);if("number"==typeof r)e=r-1;else{if(r===t)return t;r===n&&(i.items.splice(e,1),e-=1)}}}else if(e.isPair(i)){a=Object.freeze(a.concat(i));const e=s("key",i.key,o,a);if(e===t)return t;e===n&&(i.key=null);const r=s("value",i.value,o,a);if(r===t)return t;r===n&&(i.value=null)}return c}async function o(t,r){const i=c(r);if(e.isDocument(t)){await a(null,t.contents,i,Object.freeze([t]))===n&&(t.contents=null)}else await a(null,t,i,Object.freeze([]))}async function a(r,i,s,o){const c=await u(r,i,s,o);if(e.isNode(c)||e.isPair(c))return l(r,o,c),a(r,c,s,o);if("symbol"!=typeof c)if(e.isCollection(i)){o=Object.freeze(o.concat(i));for(let e=0;e<i.items.length;++e){const r=await a(e,i.items[e],s,o);if("number"==typeof r)e=r-1;else{
1432
+ if(r===t)return t;r===n&&(i.items.splice(e,1),e-=1)}}}else if(e.isPair(i)){o=Object.freeze(o.concat(i));const e=await a("key",i.key,s,o);if(e===t)return t;e===n&&(i.key=null);const r=await a("value",i.value,s,o);if(r===t)return t;r===n&&(i.value=null)}return c}function c(e){return"object"==typeof e&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function u(t,r,n,i){return"function"==typeof n?n(t,r,i):e.isMap(r)?n.Map?.(t,r,i):e.isSeq(r)?n.Seq?.(t,r,i):e.isPair(r)?n.Pair?.(t,r,i):e.isScalar(r)?n.Scalar?.(t,r,i):e.isAlias(r)?n.Alias?.(t,r,i):void 0}function l(t,r,n){const i=r[r.length-1];if(e.isCollection(i))i.items[t]=n;else if(e.isPair(i))"key"===t?i.key=n:i.value=n;else{if(!e.isDocument(i)){const t=e.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${t} parent`)}i.contents=n}}return i.BREAK=t,i.SKIP=r,
1433
+ i.REMOVE=n,o.BREAK=t,o.SKIP=r,o.REMOVE=n,visit.visit=i,visit.visitAsync=o,visit}function requireDirectives(){if(hasRequiredDirectives)return directives;hasRequiredDirectives=1;var e=requireIdentity$1(),t=requireVisit();const r={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},n=e=>e.replace(/[!,[\]{}]/g,e=>r[e]);class i{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},i.defaultYaml,e),this.tags=Object.assign({},i.defaultTags,t)}clone(){const e=new i(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new i(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:i.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},i.defaultTags)}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:i.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},i.defaultTags),this.atNextDocument=!1)
1434
+ ;const r=e.trim().split(/[ \t]+/),n=r.shift();switch(n){case"%TAG":{if(2!==r.length&&(t(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;const[e,n]=r;return this.tags[e]=n,!0}case"%YAML":{if(this.yaml.explicit=!0,1!==r.length)return t(0,"%YAML directive should contain exactly one part"),!1;const[e]=r;if("1.1"===e||"1.2"===e)return this.yaml.version=e,!0;return t(6,`Unsupported YAML version ${e}`,/^\d+\.\d+$/.test(e)),!1}default:return t(0,`Unknown directive ${n}`,!0),!1}}tagName(e,t){if("!"===e)return"!";if("!"!==e[0])return t(`Not a valid tag: ${e}`),null;if("<"===e[1]){const r=e.slice(2,-1);return"!"===r||"!!"===r?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(">"!==e[e.length-1]&&t("Verbatim tags must end with a >"),r)}const[,r,n]=e.match(/^(.*!)([^!]*)$/s);n||t(`The ${e} tag has no suffix`);const i=this.tags[r];if(i)try{return i+decodeURIComponent(n)}catch(e){return t(String(e)),null}return"!"===r?e:(t(`Could not resolve tag: ${e}`),null)}
1435
+ tagString(e){for(const[t,r]of Object.entries(this.tags))if(e.startsWith(r))return t+n(e.substring(r.length));return"!"===e[0]?e:`!<${e}>`}toString(r){const n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags);let s;if(r&&i.length>0&&e.isNode(r.contents)){const n={};t.visit(r.contents,(t,r)=>{e.isNode(r)&&r.tag&&(n[r.tag]=!0)}),s=Object.keys(n)}else s=[];for(const[e,t]of i)"!!"===e&&"tag:yaml.org,2002:"===t||r&&!s.some(e=>e.startsWith(t))||n.push(`%TAG ${e} ${t}`);return n.join("\n")}}return i.defaultYaml={explicit:!1,version:"1.2"},i.defaultTags={"!!":"tag:yaml.org,2002:"},directives.Directives=i,directives}var Document={},Alias={},anchors={},hasRequiredAnchors;function requireAnchors(){if(hasRequiredAnchors)return anchors;hasRequiredAnchors=1;var e=requireIdentity$1(),t=requireVisit();function r(e){const r=new Set;return t.visit(e,{Value(e,t){t.anchor&&r.add(t.anchor)}}),r}function n(e,t){for(let r=1;;++r){const n=`${e}${r}`;if(!t.has(n))return n}}
1436
+ return anchors.anchorIsValid=function(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){const t=JSON.stringify(e);throw new Error(`Anchor must not contain whitespace or control characters: ${t}`)}return!0},anchors.anchorNames=r,anchors.createNodeAnchors=function(t,i){const s=[],o=new Map;let a=null;return{onAnchor:e=>{s.push(e),a??(a=r(t));const o=n(i,a);return a.add(o),o},setAnchors:()=>{for(const t of s){const r=o.get(t);if("object"!=typeof r||!r.anchor||!e.isScalar(r.node)&&!e.isCollection(r.node)){const e=new Error("Failed to resolve repeated object (this should not happen)");throw e.source=t,e}r.node.anchor=r.anchor}},sourceObjects:o}},anchors.findNewAnchor=n,anchors}var Node={},applyReviver={},hasRequiredApplyReviver;function requireApplyReviver(){if(hasRequiredApplyReviver)return applyReviver;return hasRequiredApplyReviver=1,applyReviver.applyReviver=function e(t,r,n,i){if(i&&"object"==typeof i)if(Array.isArray(i))for(let r=0,n=i.length;r<n;++r){const n=i[r],s=e(t,i,String(r),n)
1437
+ ;void 0===s?delete i[r]:s!==n&&(i[r]=s)}else if(i instanceof Map)for(const r of Array.from(i.keys())){const n=i.get(r),s=e(t,i,r,n);void 0===s?i.delete(r):s!==n&&i.set(r,s)}else if(i instanceof Set)for(const r of Array.from(i)){const n=e(t,i,r,r);void 0===n?i.delete(r):n!==r&&(i.delete(r),i.add(n))}else for(const[r,n]of Object.entries(i)){const s=e(t,i,r,n);void 0===s?delete i[r]:s!==n&&(i[r]=s)}return t.call(r,n,i)},applyReviver}var toJS={},hasRequiredToJS,hasRequiredNode$1,hasRequiredAlias;function requireToJS(){if(hasRequiredToJS)return toJS;hasRequiredToJS=1;var e=requireIdentity$1();return toJS.toJS=function t(r,n,i){if(Array.isArray(r))return r.map((e,r)=>t(e,String(r),i));if(r&&"function"==typeof r.toJSON){if(!i||!e.hasAnchor(r))return r.toJSON(n,i);const t={aliasCount:0,count:1,res:void 0};i.anchors.set(r,t),i.onCreate=e=>{t.res=e,delete i.onCreate};const s=r.toJSON(n,i);return i.onCreate&&i.onCreate(s),s}return"bigint"!=typeof r||i?.keep?r:Number(r)},toJS}
1438
+ function requireNode$1(){if(hasRequiredNode$1)return Node;hasRequiredNode$1=1;var e=requireApplyReviver(),t=requireIdentity$1(),r=requireToJS();return Node.NodeBase=class{constructor(e){Object.defineProperty(this,t.NODE_TYPE,{value:e})}clone(){const e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(n,{mapAsMap:i,maxAliasCount:s,onAnchor:o,reviver:a}={}){if(!t.isDocument(n))throw new TypeError("A document argument is required");const c={anchors:new Map,doc:n,keep:!0,mapAsMap:!0===i,mapKeyWarned:!1,maxAliasCount:"number"==typeof s?s:100},u=r.toJS(this,"",c);if("function"==typeof o)for(const{count:e,res:t}of c.anchors.values())o(t,e);return"function"==typeof a?e.applyReviver(a,{"":u},"",u):u}},Node}function requireAlias(){if(hasRequiredAlias)return Alias;hasRequiredAlias=1;var e=requireAnchors(),t=requireVisit(),r=requireIdentity$1(),n=requireNode$1(),i=requireToJS();let s=class extends n.NodeBase{
1439
+ constructor(e){super(r.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,n){let i,s;n?.aliasResolveCache?i=n.aliasResolveCache:(i=[],t.visit(e,{Node:(e,t)=>{(r.isAlias(t)||r.hasAnchor(t))&&i.push(t)}}),n&&(n.aliasResolveCache=i));for(const e of i){if(e===this)break;e.anchor===this.source&&(s=e)}return s}toJSON(e,t){if(!t)return{source:this.source};const{anchors:r,doc:n,maxAliasCount:s}=t,a=this.resolve(n,t);if(!a){const e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(e)}let c=r.get(a);if(c||(i.toJS(a,null,t),c=r.get(a)),!c||void 0===c.res){throw new ReferenceError("This should not happen: Alias anchor was not resolved?")}if(s>=0&&(c.count+=1,0===c.aliasCount&&(c.aliasCount=o(n,a,r)),c.count*c.aliasCount>s)){throw new ReferenceError("Excessive alias count indicates a resource exhaustion attack")}return c.res}toString(t,r,n){const i=`*${this.source}`;if(t){
1440
+ if(e.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){const e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(e)}if(t.implicitKey)return`${i} `}return i}};function o(e,t,n){if(r.isAlias(t)){const r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(r.isCollection(t)){let r=0;for(const i of t.items){const t=o(e,i,n);t>r&&(r=t)}return r}if(r.isPair(t)){const r=o(e,t.key,n),i=o(e,t.value,n);return Math.max(r,i)}return 1}return Alias.Alias=s,Alias}var Collection={},createNode={},Scalar={},hasRequiredScalar,hasRequiredCreateNode,hasRequiredCollection;function requireScalar(){if(hasRequiredScalar)return Scalar;hasRequiredScalar=1;var e=requireIdentity$1(),t=requireNode$1(),r=requireToJS();let n=class extends t.NodeBase{constructor(t){super(e.SCALAR),this.value=t}toJSON(e,t){return t?.keep?this.value:r.toJS(this.value,e,t)}toString(){return String(this.value)}};return n.BLOCK_FOLDED="BLOCK_FOLDED",
1441
+ n.BLOCK_LITERAL="BLOCK_LITERAL",n.PLAIN="PLAIN",n.QUOTE_DOUBLE="QUOTE_DOUBLE",n.QUOTE_SINGLE="QUOTE_SINGLE",Scalar.Scalar=n,Scalar.isScalarValue=e=>!e||"function"!=typeof e&&"object"!=typeof e,Scalar}function requireCreateNode(){if(hasRequiredCreateNode)return createNode;hasRequiredCreateNode=1;var e=requireAlias(),t=requireIdentity$1(),r=requireScalar();return createNode.createNode=function(n,i,s){if(t.isDocument(n)&&(n=n.contents),t.isNode(n))return n;if(t.isPair(n)){const e=s.schema[t.MAP].createNode?.(s.schema,null,s);return e.items.push(n),e}(n instanceof String||n instanceof Number||n instanceof Boolean||"undefined"!=typeof BigInt&&n instanceof BigInt)&&(n=n.valueOf());const{aliasDuplicateObjects:o,onAnchor:a,onTagObj:c,schema:u,sourceObjects:l}=s;let d;if(o&&n&&"object"==typeof n){if(d=l.get(n),d)return d.anchor??(d.anchor=a(n)),new e.Alias(d.anchor);d={anchor:null,node:null},l.set(n,d)}i?.startsWith("!!")&&(i="tag:yaml.org,2002:"+i.slice(2));let p=function(e,t,r){if(t){
1442
+ const e=r.filter(e=>e.tag===t),n=e.find(e=>!e.format)??e[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return r.find(t=>t.identify?.(e)&&!t.format)}(n,i,u.tags);if(!p){if(n&&"function"==typeof n.toJSON&&(n=n.toJSON()),!n||"object"!=typeof n){const e=new r.Scalar(n);return d&&(d.node=e),e}p=n instanceof Map?u[t.MAP]:Symbol.iterator in Object(n)?u[t.SEQ]:u[t.MAP]}c&&(c(p),delete s.onTagObj);const h=p?.createNode?p.createNode(s.schema,n,s):"function"==typeof p?.nodeClass?.from?p.nodeClass.from(s.schema,n,s):new r.Scalar(n);return i?h.tag=i:p.default||(h.tag=p.tag),d&&(d.node=h),h},createNode}function requireCollection(){if(hasRequiredCollection)return Collection;hasRequiredCollection=1;var e=requireCreateNode(),t=requireIdentity$1(),r=requireNode$1();function n(t,r,n){let i=n;for(let e=r.length-1;e>=0;--e){const t=r[e];if("number"==typeof t&&Number.isInteger(t)&&t>=0){const e=[];e[t]=i,i=e}else i=new Map([[t,i]])}return e.createNode(i,void 0,{aliasDuplicateObjects:!1,
1443
+ keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}const i=e=>null==e||"object"==typeof e&&!!e[Symbol.iterator]().next().done;let s=class extends r.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){const r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(r.schema=e),r.items=r.items.map(r=>t.isNode(r)||t.isPair(r)?r.clone(e):r),this.range&&(r.range=this.range.slice()),r}addIn(e,r){if(i(e))this.add(r);else{const[i,...s]=e,o=this.get(i,!0);if(t.isCollection(o))o.addIn(s,r);else{if(void 0!==o||!this.schema)throw new Error(`Expected YAML collection at ${i}. Remaining path: ${s}`);this.set(i,n(this.schema,s,r))}}}deleteIn(e){const[r,...n]=e;if(0===n.length)return this.delete(r);const i=this.get(r,!0);if(t.isCollection(i))return i.deleteIn(n)
1444
+ ;throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}getIn(e,r){const[n,...i]=e,s=this.get(n,!0);return 0===i.length?!r&&t.isScalar(s)?s.value:s:t.isCollection(s)?s.getIn(i,r):void 0}hasAllNullValues(e){return this.items.every(r=>{if(!t.isPair(r))return!1;const n=r.value;return null==n||e&&t.isScalar(n)&&null==n.value&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){const[r,...n]=e;if(0===n.length)return this.has(r);const i=this.get(r,!0);return!!t.isCollection(i)&&i.hasIn(n)}setIn(e,r){const[i,...s]=e;if(0===s.length)this.set(i,r);else{const e=this.get(i,!0);if(t.isCollection(e))e.setIn(s,r);else{if(void 0!==e||!this.schema)throw new Error(`Expected YAML collection at ${i}. Remaining path: ${s}`);this.set(i,n(this.schema,s,r))}}}};return Collection.Collection=s,Collection.collectionFromPath=n,Collection.isEmptyPath=i,Collection}var Pair={},stringifyPair={},stringify$5={},stringifyComment={},hasRequiredStringifyComment;function requireStringifyComment(){
1445
+ if(hasRequiredStringifyComment)return stringifyComment;hasRequiredStringifyComment=1;function e(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}return stringifyComment.indentComment=e,stringifyComment.lineComment=(t,r,n)=>t.endsWith("\n")?e(n,r):n.includes("\n")?"\n"+e(n,r):(t.endsWith(" ")?"":" ")+n,stringifyComment.stringifyComment=e=>e.replace(/^(?!$)(?: $)?/gm,"#"),stringifyComment}var stringifyString={},foldFlowLines={},hasRequiredFoldFlowLines,hasRequiredStringifyString,hasRequiredStringify$4,hasRequiredStringifyPair;function requireFoldFlowLines(){if(hasRequiredFoldFlowLines)return foldFlowLines;hasRequiredFoldFlowLines=1;const e="block",t="quoted";function r(e,t,r){let n=t,i=t+1,s=e[i];for(;" "===s||"\t"===s;)if(t<i+r)s=e[++t];else{do{s=e[++t]}while(s&&"\n"!==s);n=t,i=t+1,s=e[i]}return n}return foldFlowLines.FOLD_BLOCK=e,foldFlowLines.FOLD_FLOW="flow",foldFlowLines.FOLD_QUOTED=t,
1446
+ foldFlowLines.foldFlowLines=function(n,i,s="flow",{indentAtStart:o,lineWidth:a=80,minContentWidth:c=20,onFold:u,onOverflow:l}={}){if(!a||a<0)return n;a<c&&(c=0);const d=Math.max(1+c,1+a-i.length);if(n.length<=d)return n;const p=[],h={};let A,f,g=a-i.length;"number"==typeof o&&(o>a-Math.max(2,c)?p.push(0):g=a-o);let m=!1,y=-1,E=-1,b=-1;s===e&&(y=r(n,y,i.length),-1!==y&&(g=y+d));for(let o;o=n[y+=1];){if(s===t&&"\\"===o){switch(E=y,n[y+1]){case"x":y+=3;break;case"u":y+=5;break;case"U":y+=9;break;default:y+=1}b=y}if("\n"===o)s===e&&(y=r(n,y,i.length)),g=y+i.length+d,A=void 0;else{if(" "===o&&f&&" "!==f&&"\n"!==f&&"\t"!==f){const e=n[y+1];e&&" "!==e&&"\n"!==e&&"\t"!==e&&(A=y)}if(y>=g)if(A)p.push(A),g=A+d,A=void 0;else if(s===t){for(;" "===f||"\t"===f;)f=o,o=n[y+=1],m=!0;const e=y>b+1?y-2:E-1;if(h[e])return n;p.push(e),h[e]=!0,g=e+d,A=void 0}else m=!0}f=o}if(m&&l&&l(),0===p.length)return n;u&&u();let C=n.slice(0,p[0]);for(let e=0;e<p.length;++e){const r=p[e],o=p[e+1]||n.length
1447
+ ;0===r?C=`\n${i}${n.slice(0,o)}`:(s===t&&h[r]&&(C+=`${n[r]}\\`),C+=`\n${i}${n.slice(r+1,o)}`)}return C},foldFlowLines}function requireStringifyString(){if(hasRequiredStringifyString)return stringifyString;hasRequiredStringifyString=1;var e=requireScalar(),t=requireFoldFlowLines();const r=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),n=e=>/^(%|---|\.\.\.)/m.test(e);function i(e,i){const s=JSON.stringify(e);if(i.options.doubleQuotedAsJSON)return s;const{implicitKey:o}=i,a=i.options.doubleQuotedMinMultiLineLength,c=i.indent||(n(e)?" ":"");let u="",l=0;for(let e=0,t=s[e];t;t=s[++e])if(" "===t&&"\\"===s[e+1]&&"n"===s[e+2]&&(u+=s.slice(l,e)+"\\ ",e+=1,l=e,t="\\"),"\\"===t)switch(s[e+1]){case"u":{u+=s.slice(l,e);const t=s.substr(e+2,4);switch(t){case"0000":u+="\\0";break;case"0007":u+="\\a";break;case"000b":u+="\\v";break;case"001b":u+="\\e";break;case"0085":u+="\\N";break;case"00a0":u+="\\_";break
1448
+ ;case"2028":u+="\\L";break;case"2029":u+="\\P";break;default:"00"===t.substr(0,2)?u+="\\x"+t.substr(2):u+=s.substr(e,6)}e+=5,l=e+1}break;case"n":if(o||'"'===s[e+2]||s.length<a)e+=1;else{for(u+=s.slice(l,e)+"\n\n";"\\"===s[e+2]&&"n"===s[e+3]&&'"'!==s[e+4];)u+="\n",e+=2;u+=c," "===s[e+2]&&(u+="\\"),e+=1,l=e+1}break;default:e+=1}return u=l?u+s.slice(l):s,o?u:t.foldFlowLines(u,c,t.FOLD_QUOTED,r(i,!1))}function s(e,s){if(!1===s.options.singleQuote||s.implicitKey&&e.includes("\n")||/[ \t]\n|\n[ \t]/.test(e))return i(e,s);const o=s.indent||(n(e)?" ":""),a="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&\n${o}`)+"'";return s.implicitKey?a:t.foldFlowLines(a,o,t.FOLD_FLOW,r(s,!1))}function o(e,t){const{singleQuote:r}=t.options;let n;if(!1===r)n=i;else{const t=e.includes('"'),o=e.includes("'");n=t&&!o?s:o&&!t?i:r?s:i}return n(e,t)}let a;try{a=new RegExp("(^|(?<!\n))\n+(?!\n|$)","g")}catch{a=/\n+(?!\n|$)/g}function c({comment:i,type:s,value:c},u,l,d){
1449
+ const{blockQuote:p,commentString:h,lineWidth:A}=u.options;if(!p||/\n[\t ]+$/.test(c)||/^\s*$/.test(c))return o(c,u);const f=u.indent||(u.forceBlockIndent||n(c)?" ":""),g="literal"===p||"folded"!==p&&s!==e.Scalar.BLOCK_FOLDED&&(s===e.Scalar.BLOCK_LITERAL||!function(e,t,r){if(!t||t<0)return!1;const n=t-r,i=e.length;if(i<=n)return!1;for(let t=0,r=0;t<i;++t)if("\n"===e[t]){if(t-r>n)return!0;if(r=t+1,i-r<=n)return!1}return!0}(c,A,f.length));if(!c)return g?"|\n":">\n";let m,y;for(y=c.length;y>0;--y){const e=c[y-1];if("\n"!==e&&"\t"!==e&&" "!==e)break}let E=c.substring(y);const b=E.indexOf("\n");-1===b?m="-":c===E||b!==E.length-1?(m="+",d&&d()):m="",E&&(c=c.slice(0,-E.length),"\n"===E[E.length-1]&&(E=E.slice(0,-1)),E=E.replace(a,`$&${f}`));let C,v=!1,I=-1;for(C=0;C<c.length;++C){const e=c[C];if(" "===e)v=!0;else{if("\n"!==e)break;I=C}}let _=c.substring(0,I<C?I+1:C);_&&(c=c.substring(_.length),_=_.replace(/\n+/g,`$&${f}`));let S=(v?f?"2":"1":"")+m;if(i&&(S+=" "+h(i.replace(/ ?[\r\n]+/g," ")),
1450
+ l&&l()),!g){const n=c.replace(/\n+/g,"\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${f}`);let i=!1;const o=r(u,!0);"folded"!==p&&s!==e.Scalar.BLOCK_FOLDED&&(o.onOverflow=()=>{i=!0});const a=t.foldFlowLines(`${_}${n}${E}`,f,t.FOLD_BLOCK,o);if(!i)return`>${S}\n${f}${a}`}return`|${S}\n${f}${_}${c=c.replace(/\n+/g,`$&${f}`)}${E}`}return stringifyString.stringifyString=function(a,u,l,d){const{implicitKey:p,inFlow:h}=u,A="string"==typeof a.value?a:Object.assign({},a,{value:String(a.value)});let{type:f}=a;f!==e.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(A.value)&&(f=e.Scalar.QUOTE_DOUBLE);const g=a=>{switch(a){case e.Scalar.BLOCK_FOLDED:case e.Scalar.BLOCK_LITERAL:return p||h?o(A.value,u):c(A,u,l,d);case e.Scalar.QUOTE_DOUBLE:return i(A.value,u);case e.Scalar.QUOTE_SINGLE:return s(A.value,u);case e.Scalar.PLAIN:return function(i,s,a,u){
1451
+ const{type:l,value:d}=i,{actualString:p,implicitKey:h,indent:A,indentStep:f,inFlow:g}=s;if(h&&d.includes("\n")||g&&/[[\]{},]/.test(d))return o(d,s);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(d))return h||g||!d.includes("\n")?o(d,s):c(i,s,a,u);if(!h&&!g&&l!==e.Scalar.PLAIN&&d.includes("\n"))return c(i,s,a,u);if(n(d)){if(""===A)return s.forceBlockIndent=!0,c(i,s,a,u);if(h&&A===f)return o(d,s)}const m=d.replace(/\n+/g,`$&\n${A}`);if(p){const e=e=>e.default&&"tag:yaml.org,2002:str"!==e.tag&&e.test?.test(m),{compat:t,tags:r}=s.doc.schema;if(r.some(e)||t?.some(e))return o(d,s)}return h?m:t.foldFlowLines(m,A,t.FOLD_FLOW,r(s,!1))}(A,u,l,d);default:return null}};let m=g(f);if(null===m){const{defaultKeyType:e,defaultStringType:t}=u.options,r=p&&e||t;if(m=g(r),null===m)throw new Error(`Unsupported default string type ${r}`)}return m},stringifyString}function requireStringify$4(){if(hasRequiredStringify$4)return stringify$5;hasRequiredStringify$4=1
1452
+ ;var e=requireAnchors(),t=requireIdentity$1(),r=requireStringifyComment(),n=requireStringifyString();return stringify$5.createStringifyContext=function(e,t){const n=Object.assign({blockQuote:!0,commentString:r.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t);let i;switch(n.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:"number"==typeof n.indent?" ".repeat(n.indent):" ",inFlow:i,options:n}},stringify$5.stringify=function(r,i,s,o){if(t.isPair(r))return r.toString(i,s,o);if(t.isAlias(r)){if(i.doc.directives)return r.toString(i)
1453
+ ;if(i.resolvedAliases?.has(r))throw new TypeError("Cannot stringify circular structure without alias nodes");i.resolvedAliases?i.resolvedAliases.add(r):i.resolvedAliases=new Set([r]),r=r.resolve(i.doc)}let a;const c=t.isNode(r)?r:i.doc.createNode(r,{onTagObj:e=>a=e});a??(a=function(e,r){if(r.tag){const t=e.filter(e=>e.tag===r.tag);if(t.length>0)return t.find(e=>e.format===r.format)??t[0]}let n,i;if(t.isScalar(r)){i=r.value;let t=e.filter(e=>e.identify?.(i));if(t.length>1){const e=t.filter(e=>e.test);e.length>0&&(t=e)}n=t.find(e=>e.format===r.format)??t.find(e=>!e.format)}else i=r,n=e.find(e=>e.nodeClass&&i instanceof e.nodeClass);if(!n)throw new Error(`Tag not resolved for ${i?.constructor?.name??(null===i?"null":typeof i)} value`);return n}(i.doc.schema.tags,c));const u=function(r,n,{anchors:i,doc:s}){if(!s.directives)return"";const o=[],a=(t.isScalar(r)||t.isCollection(r))&&r.anchor;a&&e.anchorIsValid(a)&&(i.add(a),o.push(`&${a}`));const c=r.tag??(n.default?null:n.tag)
1454
+ ;return c&&o.push(s.directives.tagString(c)),o.join(" ")}(c,a,i);u.length>0&&(i.indentAtStart=(i.indentAtStart??0)+u.length+1);const l="function"==typeof a.stringify?a.stringify(c,i,s,o):t.isScalar(c)?n.stringifyString(c,i,s,o):c.toString(i,s,o);return u?t.isScalar(c)||"{"===l[0]||"["===l[0]?`${u} ${l}`:`${u}\n${i.indent}${l}`:l},stringify$5}function requireStringifyPair(){if(hasRequiredStringifyPair)return stringifyPair;hasRequiredStringifyPair=1;var e=requireIdentity$1(),t=requireScalar(),r=requireStringify$4(),n=requireStringifyComment();return stringifyPair.stringifyPair=function({key:i,value:s},o,a,c){const{allNullValues:u,doc:l,indent:d,indentStep:p,options:{commentString:h,indentSeq:A,simpleKeys:f}}=o;let g=e.isNode(i)&&i.comment||null;if(f){if(g)throw new Error("With simple keys, key nodes cannot have comments");if(e.isCollection(i)||!e.isNode(i)&&"object"==typeof i){throw new Error("With simple keys, collection cannot be used as a key value")}}
1455
+ let m=!f&&(!i||g&&null==s&&!o.inFlow||e.isCollection(i)||(e.isScalar(i)?i.type===t.Scalar.BLOCK_FOLDED||i.type===t.Scalar.BLOCK_LITERAL:"object"==typeof i));o=Object.assign({},o,{allNullValues:!1,implicitKey:!m&&(f||!u),indent:d+p});let y,E,b,C=!1,v=!1,I=r.stringify(i,o,()=>C=!0,()=>v=!0);if(!m&&!o.inFlow&&I.length>1024){if(f)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");m=!0}if(o.inFlow){if(u||null==s)return C&&a&&a(),""===I?"?":m?`? ${I}`:I}else if(u&&!f||null==s&&m)return I=`? ${I}`,g&&!C?I+=n.lineComment(I,o.indent,h(g)):v&&c&&c(),I;C&&(g=null),m?(g&&(I+=n.lineComment(I,o.indent,h(g))),I=`? ${I}\n${d}:`):(I=`${I}:`,g&&(I+=n.lineComment(I,o.indent,h(g)))),e.isNode(s)?(y=!!s.spaceBefore,E=s.commentBefore,b=s.comment):(y=!1,E=null,b=null,s&&"object"==typeof s&&(s=l.createNode(s))),o.implicitKey=!1,m||g||!e.isScalar(s)||(o.indentAtStart=I.length+1),v=!1,
1456
+ A||!(p.length>=2)||o.inFlow||m||!e.isSeq(s)||s.flow||s.tag||s.anchor||(o.indent=o.indent.substring(2));let _=!1;const S=r.stringify(s,o,()=>_=!0,()=>v=!0);let D=" ";if(g||y||E){if(D=y?"\n":"",E){const e=h(E);D+=`\n${n.indentComment(e,o.indent)}`}""!==S||o.inFlow?D+=`\n${o.indent}`:"\n"===D&&(D="\n\n")}else if(!m&&e.isCollection(s)){const e=S[0],t=S.indexOf("\n"),r=-1!==t,n=o.inFlow??s.flow??0===s.items.length;if(r||!n){let n=!1;if(r&&("&"===e||"!"===e)){let r=S.indexOf(" ");"&"===e&&-1!==r&&r<t&&"!"===S[r+1]&&(r=S.indexOf(" ",r+1)),(-1===r||t<r)&&(n=!0)}n||(D=`\n${o.indent}`)}}else""!==S&&"\n"!==S[0]||(D="");return I+=D+S,o.inFlow?_&&a&&a():b&&!_?I+=n.lineComment(I,o.indent,h(b)):v&&c&&c(),I},stringifyPair}var addPairToJSMap={},log$1={},hasRequiredLog;function requireLog(){if(hasRequiredLog)return log$1;hasRequiredLog=1;var e=process__default;return log$1.debug=function(e,...t){"debug"===e&&console.log(...t)},log$1.warn=function(t,r){
1457
+ "debug"!==t&&"warn"!==t||("function"==typeof e.emitWarning?e.emitWarning(r):console.warn(r))},log$1}var merge$4={},hasRequiredMerge$3,hasRequiredAddPairToJSMap,hasRequiredPair;function requireMerge$3(){if(hasRequiredMerge$3)return merge$4;hasRequiredMerge$3=1;var e=requireIdentity$1(),t=requireScalar();const r="<<",n={identify:e=>e===r||"symbol"==typeof e&&e.description===r,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new t.Scalar(Symbol(r)),{addToJSMap:i}),stringify:()=>r};function i(t,r,n){if(n=t&&e.isAlias(n)?n.resolve(t.doc):n,e.isSeq(n))for(const e of n.items)s(t,r,e);else if(Array.isArray(n))for(const e of n)s(t,r,e);else s(t,r,n)}function s(t,r,n){const i=t&&e.isAlias(n)?n.resolve(t.doc):n;if(!e.isMap(i))throw new Error("Merge sources must be maps or map aliases");const s=i.toJSON(null,t,Map)
1458
+ ;for(const[e,t]of s)r instanceof Map?r.has(e)||r.set(e,t):r instanceof Set?r.add(e):Object.prototype.hasOwnProperty.call(r,e)||Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0});return r}return merge$4.addMergeToJSMap=i,merge$4.isMergeKey=(r,i)=>(n.identify(i)||e.isScalar(i)&&(!i.type||i.type===t.Scalar.PLAIN)&&n.identify(i.value))&&r?.doc.schema.tags.some(e=>e.tag===n.tag&&e.default),merge$4.merge=n,merge$4}function requireAddPairToJSMap(){if(hasRequiredAddPairToJSMap)return addPairToJSMap;hasRequiredAddPairToJSMap=1;var e=requireLog(),t=requireMerge$3(),r=requireStringify$4(),n=requireIdentity$1(),i=requireToJS();return addPairToJSMap.addPairToJSMap=function(s,o,{key:a,value:c}){if(n.isNode(a)&&a.addToJSMap)a.addToJSMap(s,o,c);else if(t.isMergeKey(s,a))t.addMergeToJSMap(s,o,c);else{const t=i.toJS(a,"",s);if(o instanceof Map)o.set(t,i.toJS(c,t,s));else if(o instanceof Set)o.add(t);else{const u=function(t,i,s){if(null===i)return""
1459
+ ;if("object"!=typeof i)return String(i);if(n.isNode(t)&&s?.doc){const n=r.createStringifyContext(s.doc,{});n.anchors=new Set;for(const e of s.anchors.keys())n.anchors.add(e.anchor);n.inFlow=!0,n.inStringifyKey=!0;const i=t.toString(n);if(!s.mapKeyWarned){let t=JSON.stringify(i);t.length>40&&(t=t.substring(0,36)+'..."'),e.warn(s.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${t}. Set mapAsMap: true to use object keys.`),s.mapKeyWarned=!0}return i}return JSON.stringify(i)}(a,t,s),l=i.toJS(c,u,s);u in o?Object.defineProperty(o,u,{value:l,writable:!0,enumerable:!0,configurable:!0}):o[u]=l}}return o},addPairToJSMap}function requirePair(){if(hasRequiredPair)return Pair;hasRequiredPair=1;var e=requireCreateNode(),t=requireStringifyPair(),r=requireAddPairToJSMap(),n=requireIdentity$1();let i=class e{constructor(e,t=null){Object.defineProperty(this,n.NODE_TYPE,{value:n.PAIR}),this.key=e,this.value=t}clone(t){let{key:r,value:i}=this
1460
+ ;return n.isNode(r)&&(r=r.clone(t)),n.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(e,t){const n=t?.mapAsMap?new Map:{};return r.addPairToJSMap(t,n,this)}toString(e,r,n){return e?.doc?t.stringifyPair(this,e,r,n):JSON.stringify(this)}};return Pair.Pair=i,Pair.createPair=function(t,r,n){const s=e.createNode(t,void 0,n),o=e.createNode(r,void 0,n);return new i(s,o)},Pair}var Schema={},map$1={},YAMLMap={},stringifyCollection={},hasRequiredStringifyCollection,hasRequiredYAMLMap,hasRequiredMap$1;function requireStringifyCollection(){if(hasRequiredStringifyCollection)return stringifyCollection;hasRequiredStringifyCollection=1;var e=requireIdentity$1(),t=requireStringify$4(),r=requireStringifyComment();function n({comment:n,items:i},o,{blockItemPrefix:a,flowChars:c,itemIndent:u,onChompKeep:l,onComment:d}){const{indent:p,options:{commentString:h}}=o,A=Object.assign({},o,{indent:u,type:null});let f=!1;const g=[];for(let n=0;n<i.length;++n){const c=i[n];let l=null
1461
+ ;if(e.isNode(c))!f&&c.spaceBefore&&g.push(""),s(o,g,c.commentBefore,f),c.comment&&(l=c.comment);else if(e.isPair(c)){const t=e.isNode(c.key)?c.key:null;t&&(!f&&t.spaceBefore&&g.push(""),s(o,g,t.commentBefore,f))}f=!1;let d=t.stringify(c,A,()=>l=null,()=>f=!0);l&&(d+=r.lineComment(d,u,h(l))),f&&l&&(f=!1),g.push(a+d)}let m;if(0===g.length)m=c.start+c.end;else{m=g[0];for(let e=1;e<g.length;++e){const t=g[e];m+=t?`\n${p}${t}`:"\n"}}return n?(m+="\n"+r.indentComment(h(n),p),d&&d()):f&&l&&l(),m}function i({items:n},i,{flowChars:o,itemIndent:a}){const{indent:c,indentStep:u,flowCollectionPadding:l,options:{commentString:d}}=i;a+=u;const p=Object.assign({},i,{indent:a,inFlow:!0,type:null});let h=!1,A=0;const f=[];for(let o=0;o<n.length;++o){const c=n[o];let u=null;if(e.isNode(c))c.spaceBefore&&f.push(""),s(i,f,c.commentBefore,!1),c.comment&&(u=c.comment);else if(e.isPair(c)){const t=e.isNode(c.key)?c.key:null;t&&(t.spaceBefore&&f.push(""),s(i,f,t.commentBefore,!1),t.comment&&(h=!0))
1462
+ ;const r=e.isNode(c.value)?c.value:null;r?(r.comment&&(u=r.comment),r.commentBefore&&(h=!0)):null==c.value&&t?.comment&&(u=t.comment)}u&&(h=!0);let l=t.stringify(c,p,()=>u=null);o<n.length-1&&(l+=","),u&&(l+=r.lineComment(l,a,d(u))),!h&&(f.length>A||l.includes("\n"))&&(h=!0),f.push(l),A=f.length}const{start:g,end:m}=o;if(0===f.length)return g+m;if(!h){const e=f.reduce((e,t)=>e+t.length+2,2);h=i.options.lineWidth>0&&e>i.options.lineWidth}if(h){let e=g;for(const t of f)e+=t?`\n${u}${c}${t}`:"\n";return`${e}\n${c}${m}`}return`${g}${l}${f.join(" ")}${l}${m}`}function s({indent:e,options:{commentString:t}},n,i,s){if(i&&s&&(i=i.replace(/^\n+/,"")),i){const s=r.indentComment(t(i),e);n.push(s.trimStart())}}return stringifyCollection.stringifyCollection=function(e,t,r){return(t.inFlow??e.flow?i:n)(e,t,r)},stringifyCollection}function requireYAMLMap(){if(hasRequiredYAMLMap)return YAMLMap;hasRequiredYAMLMap=1
1463
+ ;var e=requireStringifyCollection(),t=requireAddPairToJSMap(),r=requireCollection(),n=requireIdentity$1(),i=requirePair(),s=requireScalar();function o(e,t){const r=n.isScalar(t)?t.value:t;for(const i of e)if(n.isPair(i)){if(i.key===t||i.key===r)return i;if(n.isScalar(i.key)&&i.key.value===r)return i}}let a=class extends r.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(n.MAP,e),this.items=[]}static from(e,t,r){const{keepUndefined:n,replacer:s}=r,o=new this(e),a=(e,a)=>{if("function"==typeof s)a=s.call(t,e,a);else if(Array.isArray(s)&&!s.includes(e))return;(void 0!==a||n)&&o.items.push(i.createPair(e,a,r))};if(t instanceof Map)for(const[e,r]of t)a(e,r);else if(t&&"object"==typeof t)for(const e of Object.keys(t))a(e,t[e]);return"function"==typeof e.sortMapEntries&&o.items.sort(e.sortMapEntries),o}add(e,t){let r;r=n.isPair(e)?e:e&&"object"==typeof e&&"key"in e?new i.Pair(e.key,e.value):new i.Pair(e,e?.value)
1464
+ ;const a=o(this.items,r.key),c=this.schema?.sortMapEntries;if(a){if(!t)throw new Error(`Key ${r.key} already set`);n.isScalar(a.value)&&s.isScalarValue(r.value)?a.value.value=r.value:a.value=r.value}else if(c){const e=this.items.findIndex(e=>c(r,e)<0);-1===e?this.items.push(r):this.items.splice(e,0,r)}else this.items.push(r)}delete(e){const t=o(this.items,e);if(!t)return!1;return this.items.splice(this.items.indexOf(t),1).length>0}get(e,t){const r=o(this.items,e),i=r?.value;return(!t&&n.isScalar(i)?i.value:i)??void 0}has(e){return!!o(this.items,e)}set(e,t){this.add(new i.Pair(e,t),!0)}toJSON(e,r,n){const i=n?new n:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(i);for(const e of this.items)t.addPairToJSMap(r,i,e);return i}toString(t,r,i){if(!t)return JSON.stringify(this);for(const e of this.items)if(!n.isPair(e))throw new Error(`Map items must all be pairs; found ${JSON.stringify(e)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),
1465
+ e.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};return YAMLMap.YAMLMap=a,YAMLMap.findPair=o,YAMLMap}function requireMap$1(){if(hasRequiredMap$1)return map$1;hasRequiredMap$1=1;var e=requireIdentity$1(),t=requireYAMLMap();const r={collection:"map",default:!0,nodeClass:t.YAMLMap,tag:"tag:yaml.org,2002:map",resolve:(t,r)=>(e.isMap(t)||r("Expected a mapping for this tag"),t),createNode:(e,r,n)=>t.YAMLMap.from(e,r,n)};return map$1.map=r,map$1}var seq={},YAMLSeq={},hasRequiredYAMLSeq,hasRequiredSeq;function requireYAMLSeq(){if(hasRequiredYAMLSeq)return YAMLSeq;hasRequiredYAMLSeq=1;var e=requireCreateNode(),t=requireStringifyCollection(),r=requireCollection(),n=requireIdentity$1(),i=requireScalar(),s=requireToJS();let o=class extends r.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(n.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=a(e)
1466
+ ;if("number"!=typeof t)return!1;return this.items.splice(t,1).length>0}get(e,t){const r=a(e);if("number"!=typeof r)return;const i=this.items[r];return!t&&n.isScalar(i)?i.value:i}has(e){const t=a(e);return"number"==typeof t&&t<this.items.length}set(e,t){const r=a(e);if("number"!=typeof r)throw new Error(`Expected a valid index, not ${e}.`);const s=this.items[r];n.isScalar(s)&&i.isScalarValue(t)?s.value=t:this.items[r]=t}toJSON(e,t){const r=[];t?.onCreate&&t.onCreate(r);let n=0;for(const e of this.items)r.push(s.toJS(e,String(n++),t));return r}toString(e,r,n){return e?t.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:n,onComment:r}):JSON.stringify(this)}static from(t,r,n){const{replacer:i}=n,s=new this(t);if(r&&Symbol.iterator in Object(r)){let t=0;for(let o of r){if("function"==typeof i){const e=r instanceof Set?o:String(t++);o=i.call(r,e,o)}s.items.push(e.createNode(o,void 0,n))}}return s}};function a(e){
1467
+ let t=n.isScalar(e)?e.value:e;return t&&"string"==typeof t&&(t=Number(t)),"number"==typeof t&&Number.isInteger(t)&&t>=0?t:null}return YAMLSeq.YAMLSeq=o,YAMLSeq}function requireSeq(){if(hasRequiredSeq)return seq;hasRequiredSeq=1;var e=requireIdentity$1(),t=requireYAMLSeq();const r={collection:"seq",default:!0,nodeClass:t.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve:(t,r)=>(e.isSeq(t)||r("Expected a sequence for this tag"),t),createNode:(e,r,n)=>t.YAMLSeq.from(e,r,n)};return seq.seq=r,seq}var string$4={},hasRequiredString$2;function requireString$2(){if(hasRequiredString$2)return string$4;hasRequiredString$2=1;var e=requireStringifyString();const t={identify:e=>"string"==typeof e,default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:(t,r,n,i)=>(r=Object.assign({actualString:!0},r),e.stringifyString(t,r,n,i))};return string$4.string=t,string$4}var tags={},_null={},hasRequired_null;function require_null(){if(hasRequired_null)return _null;hasRequired_null=1;var e=requireScalar()
1468
+ ;const t={identify:e=>null==e,createNode:()=>new e.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new e.Scalar(null),stringify:({source:e},r)=>"string"==typeof e&&t.test.test(e)?e:r.options.nullStr};return _null.nullTag=t,_null}var bool$1={},hasRequiredBool$1;function requireBool$1(){if(hasRequiredBool$1)return bool$1;hasRequiredBool$1=1;var e=requireScalar();const t={identify:e=>"boolean"==typeof e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new e.Scalar("t"===t[0]||"T"===t[0]),stringify({source:e,value:r},n){if(e&&t.test.test(e)){if(r===("t"===e[0]||"T"===e[0]))return e}return r?n.options.trueStr:n.options.falseStr}};return bool$1.boolTag=t,bool$1}var float$1={},stringifyNumber={},hasRequiredStringifyNumber,hasRequiredFloat$1;function requireStringifyNumber(){if(hasRequiredStringifyNumber)return stringifyNumber;return hasRequiredStringifyNumber=1,
1469
+ stringifyNumber.stringifyNumber=function({format:e,minFractionDigits:t,tag:r,value:n}){if("bigint"==typeof n)return String(n);const i="number"==typeof n?n:Number(n);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let s=JSON.stringify(n);if(!e&&t&&(!r||"tag:yaml.org,2002:float"===r)&&/^\d/.test(s)){let e=s.indexOf(".");e<0&&(e=s.length,s+=".");let r=t-(s.length-e-1);for(;r-- >0;)s+="0"}return s},stringifyNumber}function requireFloat$1(){if(hasRequiredFloat$1)return float$1;hasRequiredFloat$1=1;var e=requireScalar(),t=requireStringifyNumber();const r={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>"nan"===e.slice(-3).toLowerCase()?NaN:"-"===e[0]?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:t.stringifyNumber},n={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,
1470
+ resolve:e=>parseFloat(e),stringify(e){const r=Number(e.value);return isFinite(r)?r.toExponential():t.stringifyNumber(e)}},i={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){const r=new e.Scalar(parseFloat(t)),n=t.indexOf(".");return-1!==n&&"0"===t[t.length-1]&&(r.minFractionDigits=t.length-n-1),r},stringify:t.stringifyNumber};return float$1.float=i,float$1.floatExp=n,float$1.floatNaN=r,float$1}var int$1={},hasRequiredInt$1;function requireInt$1(){if(hasRequiredInt$1)return int$1;hasRequiredInt$1=1;var e=requireStringifyNumber();const t=e=>"bigint"==typeof e||Number.isInteger(e),r=(e,t,r,{intAsBigInt:n})=>n?BigInt(e):parseInt(e.substring(t),r);function n(r,n,i){const{value:s}=r;return t(s)&&s>=0?i+s.toString(n):e.stringifyNumber(r)}const i={identify:e=>t(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>r(e,2,8,n),stringify:e=>n(e,8,"0o")},s={identify:t,default:!0,
1471
+ tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>r(e,0,10,n),stringify:e.stringifyNumber},o={identify:e=>t(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>r(e,2,16,n),stringify:e=>n(e,16,"0x")};return int$1.int=s,int$1.intHex=o,int$1.intOct=i,int$1}var schema$2={},hasRequiredSchema$3;function requireSchema$3(){if(hasRequiredSchema$3)return schema$2;hasRequiredSchema$3=1;var e=requireMap$1(),t=require_null(),r=requireSeq(),n=requireString$2(),i=requireBool$1(),s=requireFloat$1(),o=requireInt$1();const a=[e.map,r.seq,n.string,t.nullTag,i.boolTag,o.intOct,o.int,o.intHex,s.floatNaN,s.floatExp,s.float];return schema$2.schema=a,schema$2}var schema$1={},hasRequiredSchema$2;function requireSchema$2(){if(hasRequiredSchema$2)return schema$1;hasRequiredSchema$2=1;var e=requireScalar(),t=requireMap$1(),r=requireSeq();function n(e){return"bigint"==typeof e||Number.isInteger(e)}const i=({value:e})=>JSON.stringify(e),s=[{
1472
+ identify:e=>"string"==typeof e,default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:i},{identify:e=>null==e,createNode:()=>new e.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:i},{identify:e=>"boolean"==typeof e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>"true"===e,stringify:i},{identify:n,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:r})=>r?BigInt(e):parseInt(e,10),stringify:({value:e})=>n(e)?e.toString():JSON.stringify(e)},{identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:i}],o={default:!0,tag:"",test:/^/,resolve:(e,t)=>(t(`Unresolved plain scalar ${JSON.stringify(e)}`),e)},a=[t.map,r.seq].concat(s,o);return schema$1.schema=a,schema$1}var binary$3={},hasRequiredBinary$1;function requireBinary$1(){if(hasRequiredBinary$1)return binary$3
1473
+ ;hasRequiredBinary$1=1;var e=require$$0$g,t=requireScalar(),r=requireStringifyString();const n={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,r){if("function"==typeof e.Buffer)return e.Buffer.from(t,"base64");if("function"==typeof atob){const e=atob(t.replace(/[\n\r]/g,"")),r=new Uint8Array(e.length);for(let t=0;t<e.length;++t)r[t]=e.charCodeAt(t);return r}return r("This environment does not support reading binary tags; either Buffer or atob is required"),t},stringify({comment:n,type:i,value:s},o,a,c){if(!s)return"";const u=s;let l;if("function"==typeof e.Buffer)l=u instanceof e.Buffer?u.toString("base64"):e.Buffer.from(u.buffer).toString("base64");else{if("function"!=typeof btoa)throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");{let e="";for(let t=0;t<u.length;++t)e+=String.fromCharCode(u[t]);l=btoa(e)}}if(i??(i=t.Scalar.BLOCK_LITERAL),i!==t.Scalar.QUOTE_DOUBLE){
1474
+ const e=Math.max(o.options.lineWidth-o.indent.length,o.options.minContentWidth),r=Math.ceil(l.length/e),n=new Array(r);for(let t=0,i=0;t<r;++t,i+=e)n[t]=l.substr(i,e);l=n.join(i===t.Scalar.BLOCK_LITERAL?"\n":" ")}return r.stringifyString({comment:n,type:i,value:l},o,a,c)}};return binary$3.binary=n,binary$3}var omap={},pairs$1={},hasRequiredPairs$1,hasRequiredOmap;function requirePairs$1(){if(hasRequiredPairs$1)return pairs$1;hasRequiredPairs$1=1;var e=requireIdentity$1(),t=requirePair(),r=requireScalar(),n=requireYAMLSeq();function i(n,i){if(e.isSeq(n))for(let s=0;s<n.items.length;++s){let o=n.items[s];if(!e.isPair(o)){if(e.isMap(o)){o.items.length>1&&i("Each pair must have its own sequence indicator");const e=o.items[0]||new t.Pair(new r.Scalar(null));if(o.commentBefore&&(e.key.commentBefore=e.key.commentBefore?`${o.commentBefore}\n${e.key.commentBefore}`:o.commentBefore),o.comment){const t=e.value??e.key;t.comment=t.comment?`${o.comment}\n${t.comment}`:o.comment}o=e}
1475
+ n.items[s]=e.isPair(o)?o:new t.Pair(o)}}else i("Expected a sequence for this tag");return n}function s(e,r,i){const{replacer:s}=i,o=new n.YAMLSeq(e);o.tag="tag:yaml.org,2002:pairs";let a=0;if(r&&Symbol.iterator in Object(r))for(let e of r){let n,c;if("function"==typeof s&&(e=s.call(r,String(a++),e)),Array.isArray(e)){if(2!==e.length)throw new TypeError(`Expected [key, value] tuple: ${e}`);n=e[0],c=e[1]}else if(e&&e instanceof Object){const t=Object.keys(e);if(1!==t.length)throw new TypeError(`Expected tuple with one key, not ${t.length} keys`);n=t[0],c=e[n]}else n=e;o.items.push(t.createPair(n,c,i))}return o}const o={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:i,createNode:s};return pairs$1.createPairs=s,pairs$1.pairs=o,pairs$1.resolvePairs=i,pairs$1}function requireOmap(){if(hasRequiredOmap)return omap;hasRequiredOmap=1;var e=requireIdentity$1(),t=requireToJS(),r=requireYAMLMap(),n=requireYAMLSeq(),i=requirePairs$1();class s extends n.YAMLSeq{constructor(){
1476
+ super(),this.add=r.YAMLMap.prototype.add.bind(this),this.delete=r.YAMLMap.prototype.delete.bind(this),this.get=r.YAMLMap.prototype.get.bind(this),this.has=r.YAMLMap.prototype.has.bind(this),this.set=r.YAMLMap.prototype.set.bind(this),this.tag=s.tag}toJSON(r,n){if(!n)return super.toJSON(r);const i=new Map;n?.onCreate&&n.onCreate(i);for(const r of this.items){let s,o;if(e.isPair(r)?(s=t.toJS(r.key,"",n),o=t.toJS(r.value,s,n)):s=t.toJS(r,"",n),i.has(s))throw new Error("Ordered maps must not include duplicate keys");i.set(s,o)}return i}static from(e,t,r){const n=i.createPairs(e,t,r),s=new this;return s.items=n.items,s}}s.tag="tag:yaml.org,2002:omap";const o={collection:"seq",identify:e=>e instanceof Map,nodeClass:s,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,r){const n=i.resolvePairs(t,r),o=[];for(const{key:t}of n.items)e.isScalar(t)&&(o.includes(t.value)?r(`Ordered maps must not include duplicate keys: ${t.value}`):o.push(t.value));return Object.assign(new s,n)},
1477
+ createNode:(e,t,r)=>s.from(e,t,r)};return omap.YAMLOMap=s,omap.omap=o,omap}var schema={},bool={},hasRequiredBool;function requireBool(){if(hasRequiredBool)return bool;hasRequiredBool=1;var e=requireScalar();function t({value:e,source:t},i){return t&&(e?r:n).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}const r={identify:e=>!0===e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new e.Scalar(!0),stringify:t},n={identify:e=>!1===e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new e.Scalar(!1),stringify:t};return bool.falseTag=n,bool.trueTag=r,bool}var float={},hasRequiredFloat;function requireFloat(){if(hasRequiredFloat)return float;hasRequiredFloat=1;var e=requireScalar(),t=requireStringifyNumber();const r={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
1478
+ resolve:e=>"nan"===e.slice(-3).toLowerCase()?NaN:"-"===e[0]?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:t.stringifyNumber},n={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){const r=Number(e.value);return isFinite(r)?r.toExponential():t.stringifyNumber(e)}},i={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){const r=new e.Scalar(parseFloat(t.replace(/_/g,""))),n=t.indexOf(".");if(-1!==n){const e=t.substring(n+1).replace(/_/g,"");"0"===e[e.length-1]&&(r.minFractionDigits=e.length)}return r},stringify:t.stringifyNumber};return float.float=i,float.floatExp=n,float.floatNaN=r,float}var int={},hasRequiredInt;function requireInt(){if(hasRequiredInt)return int;hasRequiredInt=1;var e=requireStringifyNumber()
1479
+ ;const t=e=>"bigint"==typeof e||Number.isInteger(e);function r(e,t,r,{intAsBigInt:n}){const i=e[0];if("-"!==i&&"+"!==i||(t+=1),e=e.substring(t).replace(/_/g,""),n){switch(r){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`}const t=BigInt(e);return"-"===i?BigInt(-1)*t:t}const s=parseInt(e,r);return"-"===i?-1*s:s}function n(r,n,i){const{value:s}=r;if(t(s)){const e=s.toString(n);return s<0?"-"+i+e.substr(1):i+e}return e.stringifyNumber(r)}const i={identify:t,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>r(e,2,2,n),stringify:e=>n(e,2,"0b")},s={identify:t,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>r(e,1,8,n),stringify:e=>n(e,8,"0")},o={identify:t,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>r(e,0,10,n),stringify:e.stringifyNumber},a={identify:t,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,
1480
+ resolve:(e,t,n)=>r(e,2,16,n),stringify:e=>n(e,16,"0x")};return int.int=o,int.intBin=i,int.intHex=a,int.intOct=s,int}var set={},hasRequiredSet;function requireSet(){if(hasRequiredSet)return set;hasRequiredSet=1;var e=requireIdentity$1(),t=requirePair(),r=requireYAMLMap();class n extends r.YAMLMap{constructor(e){super(e),this.tag=n.tag}add(n){let i;i=e.isPair(n)?n:n&&"object"==typeof n&&"key"in n&&"value"in n&&null===n.value?new t.Pair(n.key,null):new t.Pair(n,null);r.findPair(this.items,i.key)||this.items.push(i)}get(t,n){const i=r.findPair(this.items,t);return!n&&e.isPair(i)?e.isScalar(i.key)?i.key.value:i.key:i}set(e,n){if("boolean"!=typeof n)throw new Error("Expected boolean value for set(key, value) in a YAML set, not "+typeof n);const i=r.findPair(this.items,e);i&&!n?this.items.splice(this.items.indexOf(i),1):!i&&n&&this.items.push(new t.Pair(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,r){if(!e)return JSON.stringify(this)
1481
+ ;if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,r);throw new Error("Set items must all have null values")}static from(e,r,n){const{replacer:i}=n,s=new this(e);if(r&&Symbol.iterator in Object(r))for(let e of r)"function"==typeof i&&(e=i.call(r,e,e)),s.items.push(t.createPair(e,null,n));return s}}n.tag="tag:yaml.org,2002:set";const i={collection:"map",identify:e=>e instanceof Set,nodeClass:n,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>n.from(e,t,r),resolve(t,r){if(e.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new n,t);r("Set items must all have null values")}else r("Expected a mapping for this tag");return t}};return set.YAMLSet=n,set.set=i,set}var timestamp$1={},hasRequiredTimestamp$1,hasRequiredSchema$1,hasRequiredTags,hasRequiredSchema;function requireTimestamp$1(){if(hasRequiredTimestamp$1)return timestamp$1;hasRequiredTimestamp$1=1;var e=requireStringifyNumber();function t(e,t){
1482
+ const r=e[0],n="-"===r||"+"===r?e.substring(1):e,i=e=>t?BigInt(e):Number(e),s=n.replace(/_/g,"").split(":").reduce((e,t)=>e*i(60)+i(t),i(0));return"-"===r?i(-1)*s:s}function r(t){let{value:r}=t,n=e=>e;if("bigint"==typeof r)n=e=>BigInt(e);else if(isNaN(r)||!isFinite(r))return e.stringifyNumber(t);let i="";r<0&&(i="-",r*=n(-1));const s=n(60),o=[r%s];return r<60?o.unshift(0):(r=(r-o[0])/s,o.unshift(r%s),r>=60&&(r=(r-o[0])/s,o.unshift(r))),i+o.map(e=>String(e).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}const n={identify:e=>"bigint"==typeof e||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,r,{intAsBigInt:n})=>t(e,n),stringify:r},i={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>t(e,!1),stringify:r},s={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",
1483
+ test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){const r=e.match(s.test);if(!r)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");const[,n,i,o,a,c,u]=r.map(Number),l=r[7]?Number((r[7]+"00").substr(1,3)):0;let d=Date.UTC(n,i-1,o,a||0,c||0,u||0,l);const p=r[8];if(p&&"Z"!==p){let e=t(p,!1);Math.abs(e)<30&&(e*=60),d-=6e4*e}return new Date(d)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};return timestamp$1.floatTime=i,timestamp$1.intTime=n,timestamp$1.timestamp=s,timestamp$1}function requireSchema$1(){if(hasRequiredSchema$1)return schema;hasRequiredSchema$1=1;var e=requireMap$1(),t=require_null(),r=requireSeq(),n=requireString$2(),i=requireBinary$1(),s=requireBool(),o=requireFloat(),a=requireInt(),c=requireMerge$3(),u=requireOmap(),l=requirePairs$1(),d=requireSet(),p=requireTimestamp$1()
1484
+ ;const h=[e.map,r.seq,n.string,t.nullTag,s.trueTag,s.falseTag,a.intBin,a.intOct,a.int,a.intHex,o.floatNaN,o.floatExp,o.float,i.binary,c.merge,u.omap,l.pairs,d.set,p.intTime,p.floatTime,p.timestamp];return schema.schema=h,schema}function requireTags(){if(hasRequiredTags)return tags;hasRequiredTags=1;var e=requireMap$1(),t=require_null(),r=requireSeq(),n=requireString$2(),i=requireBool$1(),s=requireFloat$1(),o=requireInt$1(),a=requireSchema$3(),c=requireSchema$2(),u=requireBinary$1(),l=requireMerge$3(),d=requireOmap(),p=requirePairs$1(),h=requireSchema$1(),A=requireSet(),f=requireTimestamp$1();const g=new Map([["core",a.schema],["failsafe",[e.map,r.seq,n.string]],["json",c.schema],["yaml11",h.schema],["yaml-1.1",h.schema]]),m={binary:u.binary,bool:i.boolTag,float:s.float,floatExp:s.floatExp,floatNaN:s.floatNaN,floatTime:f.floatTime,int:o.int,intHex:o.intHex,intOct:o.intOct,intTime:f.intTime,map:e.map,merge:l.merge,null:t.nullTag,omap:d.omap,pairs:p.pairs,seq:r.seq,set:A.set,
1485
+ timestamp:f.timestamp},y={"tag:yaml.org,2002:binary":u.binary,"tag:yaml.org,2002:merge":l.merge,"tag:yaml.org,2002:omap":d.omap,"tag:yaml.org,2002:pairs":p.pairs,"tag:yaml.org,2002:set":A.set,"tag:yaml.org,2002:timestamp":f.timestamp};return tags.coreKnownTags=y,tags.getTags=function(e,t,r){const n=g.get(t);if(n&&!e)return r&&!n.includes(l.merge)?n.concat(l.merge):n.slice();let i=n;if(!i){if(!Array.isArray(e)){const e=Array.from(g.keys()).filter(e=>"yaml11"!==e).map(e=>JSON.stringify(e)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${e} or define customTags array`)}i=[]}if(Array.isArray(e))for(const t of e)i=i.concat(t);else"function"==typeof e&&(i=e(i.slice()));return r&&(i=i.concat(l.merge)),i.reduce((e,t)=>{const r="string"==typeof t?m[t]:t;if(!r){const e=JSON.stringify(t),r=Object.keys(m).map(e=>JSON.stringify(e)).join(", ");throw new Error(`Unknown custom tag ${e}; use one of ${r}`)}return e.includes(r)||e.push(r),e},[])},tags}function requireSchema(){
1486
+ if(hasRequiredSchema)return Schema;hasRequiredSchema=1;var e=requireIdentity$1(),t=requireMap$1(),r=requireSeq(),n=requireString$2(),i=requireTags();const s=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0;return Schema.Schema=class o{constructor({compat:o,customTags:a,merge:c,resolveKnownTags:u,schema:l,sortMapEntries:d,toStringDefaults:p}){this.compat=Array.isArray(o)?i.getTags(o,"compat"):o?i.getTags(null,o):null,this.name="string"==typeof l&&l||"core",this.knownTags=u?i.coreKnownTags:{},this.tags=i.getTags(a,this.name,c),this.toStringOptions=p??null,Object.defineProperty(this,e.MAP,{value:t.map}),Object.defineProperty(this,e.SCALAR,{value:n.string}),Object.defineProperty(this,e.SEQ,{value:r.seq}),this.sortMapEntries="function"==typeof d?d:!0===d?s:null}clone(){const e=Object.create(o.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}},Schema}var stringifyDocument={},hasRequiredStringifyDocument,hasRequiredDocument;function requireStringifyDocument(){
1487
+ if(hasRequiredStringifyDocument)return stringifyDocument;hasRequiredStringifyDocument=1;var e=requireIdentity$1(),t=requireStringify$4(),r=requireStringifyComment();return stringifyDocument.stringifyDocument=function(n,i){const s=[];let o=!0===i.directives;if(!1!==i.directives&&n.directives){const e=n.directives.toString(n);e?(s.push(e),o=!0):n.directives.docStart&&(o=!0)}o&&s.push("---");const a=t.createStringifyContext(n,i),{commentString:c}=a.options;if(n.commentBefore){1!==s.length&&s.unshift("");const e=c(n.commentBefore);s.unshift(r.indentComment(e,""))}let u=!1,l=null;if(n.contents){if(e.isNode(n.contents)){if(n.contents.spaceBefore&&o&&s.push(""),n.contents.commentBefore){const e=c(n.contents.commentBefore);s.push(r.indentComment(e,""))}a.forceBlockIndent=!!n.comment,l=n.contents.comment}const i=l?void 0:()=>u=!0;let d=t.stringify(n.contents,a,()=>l=null,i);l&&(d+=r.lineComment(d,"",c(l))),"|"!==d[0]&&">"!==d[0]||"---"!==s[s.length-1]?s.push(d):s[s.length-1]=`--- ${d}`
1488
+ }else s.push(t.stringify(n.contents,a));if(n.directives?.docEnd)if(n.comment){const e=c(n.comment);e.includes("\n")?(s.push("..."),s.push(r.indentComment(e,""))):s.push(`... ${e}`)}else s.push("...");else{let e=n.comment;e&&u&&(e=e.replace(/^\n+/,"")),e&&(u&&!l||""===s[s.length-1]||s.push(""),s.push(r.indentComment(c(e),"")))}return s.join("\n")+"\n"},stringifyDocument}function requireDocument(){if(hasRequiredDocument)return Document;hasRequiredDocument=1;var e=requireAlias(),t=requireCollection(),r=requireIdentity$1(),n=requirePair(),i=requireToJS(),s=requireSchema(),o=requireStringifyDocument(),a=requireAnchors(),c=requireApplyReviver(),u=requireCreateNode(),l=requireDirectives();function d(e){if(r.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}return Document.Document=class p{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,r.NODE_TYPE,{value:r.DOC});let i=null
1489
+ ;"function"==typeof t||Array.isArray(t)?i=t:void 0===n&&t&&(n=t,t=void 0);const s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=s;let{version:o}=s;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new l.Directives({version:o}),this.setSchema(o,n),this.contents=void 0===e?null:this.createNode(e,i,n)}clone(){const e=Object.create(p.prototype,{[r.NODE_TYPE]:{value:r.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=r.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){d(this.contents)&&this.contents.add(e)}addIn(e,t){
1490
+ d(this.contents)&&this.contents.addIn(e,t)}createAlias(t,r){if(!t.anchor){const e=a.anchorNames(this);t.anchor=!r||e.has(r)?a.findNewAnchor(r||"a",e):r}return new e.Alias(t.anchor)}createNode(e,t,n){let i;if("function"==typeof t)e=t.call({"":e},"",e),i=t;else if(Array.isArray(t)){const e=e=>"number"==typeof e||e instanceof String||e instanceof Number,r=t.filter(e).map(String);r.length>0&&(t=t.concat(r)),i=t}else void 0===n&&t&&(n=t,t=void 0);const{aliasDuplicateObjects:s,anchorPrefix:o,flow:c,keepUndefined:l,onTagObj:d,tag:p}=n??{},{onAnchor:h,setAnchors:A,sourceObjects:f}=a.createNodeAnchors(this,o||"a"),g={aliasDuplicateObjects:s??!0,keepUndefined:l??!1,onAnchor:h,onTagObj:d,replacer:i,schema:this.schema,sourceObjects:f},m=u.createNode(e,p,g);return c&&r.isCollection(m)&&(m.flow=!0),A(),m}createPair(e,t,r={}){const i=this.createNode(e,null,r),s=this.createNode(t,null,r);return new n.Pair(i,s)}delete(e){return!!d(this.contents)&&this.contents.delete(e)}deleteIn(e){
1491
+ return t.isEmptyPath(e)?null!=this.contents&&(this.contents=null,!0):!!d(this.contents)&&this.contents.deleteIn(e)}get(e,t){return r.isCollection(this.contents)?this.contents.get(e,t):void 0}getIn(e,n){return t.isEmptyPath(e)?!n&&r.isScalar(this.contents)?this.contents.value:this.contents:r.isCollection(this.contents)?this.contents.getIn(e,n):void 0}has(e){return!!r.isCollection(this.contents)&&this.contents.has(e)}hasIn(e){return t.isEmptyPath(e)?void 0!==this.contents:!!r.isCollection(this.contents)&&this.contents.hasIn(e)}set(e,r){null==this.contents?this.contents=t.collectionFromPath(this.schema,[e],r):d(this.contents)&&this.contents.set(e,r)}setIn(e,r){t.isEmptyPath(e)?this.contents=r:null==this.contents?this.contents=t.collectionFromPath(this.schema,Array.from(e),r):d(this.contents)&&this.contents.setIn(e,r)}setSchema(e,t={}){let r;switch("number"==typeof e&&(e=String(e)),e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new l.Directives({
1492
+ version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new l.Directives({version:e}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{const t=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${t}`)}}if(t.schema instanceof Object)this.schema=t.schema;else{if(!r)throw new Error("With a null YAML version, the { schema: Schema } option is required");this.schema=new s.Schema(Object.assign(r,t))}}toJS({json:e,jsonArg:t,mapAsMap:r,maxAliasCount:n,onAnchor:s,reviver:o}={}){const a={anchors:new Map,doc:this,keep:!e,mapAsMap:!0===r,mapKeyWarned:!1,maxAliasCount:"number"==typeof n?n:100},u=i.toJS(this.contents,t??"",a);if("function"==typeof s)for(const{count:e,res:t}of a.anchors.values())s(t,e);return"function"==typeof o?c.applyReviver(o,{"":u},"",u):u}toJSON(e,t){return this.toJS({json:!0,
1493
+ jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){const t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return o.stringifyDocument(this,e)}},Document}var errors$4={},hasRequiredErrors$4;function requireErrors$4(){if(hasRequiredErrors$4)return errors$4;hasRequiredErrors$4=1;class e extends Error{constructor(e,t,r,n){super(),this.name=e,this.code=r,this.message=n,this.pos=t}}return errors$4.YAMLError=e,errors$4.YAMLParseError=class extends e{constructor(e,t,r){super("YAMLParseError",e,t,r)}},errors$4.YAMLWarning=class extends e{constructor(e,t,r){super("YAMLWarning",e,t,r)}},errors$4.prettifyError=(e,t)=>r=>{if(-1===r.pos[0])return;r.linePos=r.pos.map(e=>t.linePos(e));const{line:n,col:i}=r.linePos[0];r.message+=` at line ${n}, column ${i}`
1494
+ ;let s=i-1,o=e.substring(t.lineStarts[n-1],t.lineStarts[n]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){const e=Math.min(s-39,o.length-79);o="…"+o.substring(e),s-=e-1}if(o.length>80&&(o=o.substring(0,79)+"…"),n>1&&/^ *$/.test(o.substring(0,s))){let r=e.substring(t.lineStarts[n-2],t.lineStarts[n-1]);r.length>80&&(r=r.substring(0,79)+"…\n"),o=r+o}if(/[^ ]/.test(o)){let e=1;const t=r.linePos[1];t&&t.line===n&&t.col>i&&(e=Math.max(1,Math.min(t.col-i,80-s)));const a=" ".repeat(s)+"^".repeat(e);r.message+=`:\n\n${o}\n${a}\n`}},errors$4}var composeDoc={},composeNode={},composeCollection={},resolveBlockMap={},resolveProps={},hasRequiredResolveProps;function requireResolveProps(){if(hasRequiredResolveProps)return resolveProps;return hasRequiredResolveProps=1,resolveProps.resolveProps=function(e,{flow:t,indicator:r,next:n,offset:i,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,u=a,l=a,d="",p="",h=!1,A=!1,f=null,g=null,m=null,y=null,E=null,b=null,C=null
1495
+ ;for(const i of e)switch(A&&("space"!==i.type&&"newline"!==i.type&&"comma"!==i.type&&s(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),A=!1),f&&(u&&"comment"!==i.type&&"newline"!==i.type&&s(f,"TAB_AS_INDENT","Tabs are not allowed as indentation"),f=null),i.type){case"space":t||"doc-start"===r&&"flow-collection"===n?.type||!i.source.includes("\t")||(f=i),l=!0;break;case"comment":{l||s(i,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const e=i.source.substring(1)||" ";d?d+=p+e:d=e,p="",u=!1;break}case"newline":u?d?d+=i.source:b&&"seq-item-ind"===r||(c=!0):p+=i.source,u=!0,h=!0,(g||m)&&(y=i),l=!0;break;case"anchor":g&&s(i,"MULTIPLE_ANCHORS","A node can have at most one anchor"),i.source.endsWith(":")&&s(i.offset+i.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),g=i,C??(C=i.offset),u=!1,l=!1,A=!0;break;case"tag":m&&s(i,"MULTIPLE_TAGS","A node can have at most one tag"),m=i,
1496
+ C??(C=i.offset),u=!1,l=!1,A=!0;break;case r:(g||m)&&s(i,"BAD_PROP_ORDER",`Anchors and tags must be after the ${i.source} indicator`),b&&s(i,"UNEXPECTED_TOKEN",`Unexpected ${i.source} in ${t??"collection"}`),b=i,u="seq-item-ind"===r||"explicit-key-ind"===r,l=!1;break;case"comma":if(t){E&&s(i,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),E=i,u=!1,l=!1;break}default:s(i,"UNEXPECTED_TOKEN",`Unexpected ${i.type} token`),u=!1,l=!1}const v=e[e.length-1],I=v?v.offset+v.source.length:i;return A&&n&&"space"!==n.type&&"newline"!==n.type&&"comma"!==n.type&&("scalar"!==n.type||""!==n.source)&&s(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),f&&(u&&f.indent<=o||"block-map"===n?.type||"block-seq"===n?.type)&&s(f,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:E,found:b,spaceBefore:c,comment:d,hasNewline:h,anchor:g,tag:m,newlineAfterProp:y,end:I,start:C??I}},resolveProps}var utilContainsNewline={},hasRequiredUtilContainsNewline
1497
+ ;function requireUtilContainsNewline(){if(hasRequiredUtilContainsNewline)return utilContainsNewline;return hasRequiredUtilContainsNewline=1,utilContainsNewline.containsNewline=function e(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes("\n"))return!0;if(t.end)for(const e of t.end)if("newline"===e.type)return!0;return!1;case"flow-collection":for(const r of t.items){for(const e of r.start)if("newline"===e.type)return!0;if(r.sep)for(const e of r.sep)if("newline"===e.type)return!0;if(e(r.key)||e(r.value))return!0}return!1;default:return!0}},utilContainsNewline}var utilFlowIndentCheck={},hasRequiredUtilFlowIndentCheck;function requireUtilFlowIndentCheck(){if(hasRequiredUtilFlowIndentCheck)return utilFlowIndentCheck;hasRequiredUtilFlowIndentCheck=1;var e=requireUtilContainsNewline();return utilFlowIndentCheck.flowIndentCheck=function(t,r,n){if("flow-collection"===r?.type){const i=r.end[0]
1498
+ ;if(i.indent===t&&("]"===i.source||"}"===i.source)&&e.containsNewline(r)){n(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}},utilFlowIndentCheck}var utilMapIncludes={},hasRequiredUtilMapIncludes,hasRequiredResolveBlockMap;function requireUtilMapIncludes(){if(hasRequiredUtilMapIncludes)return utilMapIncludes;hasRequiredUtilMapIncludes=1;var e=requireIdentity$1();return utilMapIncludes.mapIncludes=function(t,r,n){const{uniqueKeys:i}=t.options;if(!1===i)return!1;const s="function"==typeof i?i:(t,r)=>t===r||e.isScalar(t)&&e.isScalar(r)&&t.value===r.value;return r.some(e=>s(e.key,n))},utilMapIncludes}function requireResolveBlockMap(){if(hasRequiredResolveBlockMap)return resolveBlockMap;hasRequiredResolveBlockMap=1;var e=requirePair(),t=requireYAMLMap(),r=requireResolveProps(),n=requireUtilContainsNewline(),i=requireUtilFlowIndentCheck(),s=requireUtilMapIncludes();const o="All mapping items must start at the same column"
1499
+ ;return resolveBlockMap.resolveBlockMap=function({composeNode:a,composeEmptyNode:c},u,l,d,p){const h=new(p?.nodeClass??t.YAMLMap)(u.schema);u.atRoot&&(u.atRoot=!1);let A=l.offset,f=null;for(const t of l.items){const{start:p,key:g,sep:m,value:y}=t,E=r.resolveProps(p,{indicator:"explicit-key-ind",next:g??m?.[0],offset:A,onError:d,parentIndent:l.indent,startOnNewline:!0}),b=!E.found;if(b){if(g&&("block-seq"===g.type?d(A,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in g&&g.indent!==l.indent&&d(A,"BAD_INDENT",o)),!E.anchor&&!E.tag&&!m){f=E.end,E.comment&&(h.comment?h.comment+="\n"+E.comment:h.comment=E.comment);continue}(E.newlineAfterProp||n.containsNewline(g))&&d(g??p[p.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else E.found?.indent!==l.indent&&d(A,"BAD_INDENT",o);u.atKey=!0;const C=E.end,v=g?a(u,g,E,d):c(u,C,p,null,E,d);u.schema.compat&&i.flowIndentCheck(l.indent,g,d),u.atKey=!1,
1500
+ s.mapIncludes(u,h.items,v)&&d(C,"DUPLICATE_KEY","Map keys must be unique");const I=r.resolveProps(m??[],{indicator:"map-value-ind",next:y,offset:v.range[2],onError:d,parentIndent:l.indent,startOnNewline:!g||"block-scalar"===g.type});if(A=I.end,I.found){b&&("block-map"!==y?.type||I.hasNewline||d(A,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),u.options.strict&&E.start<I.found.offset-1024&&d(v.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));const r=y?a(u,y,I,d):c(u,A,m,null,I,d);u.schema.compat&&i.flowIndentCheck(l.indent,y,d),A=r.range[2];const n=new e.Pair(v,r);u.options.keepSourceTokens&&(n.srcToken=t),h.items.push(n)}else{b&&d(v.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),I.comment&&(v.comment?v.comment+="\n"+I.comment:v.comment=I.comment);const r=new e.Pair(v);u.options.keepSourceTokens&&(r.srcToken=t),h.items.push(r)}}
1501
+ return f&&f<A&&d(f,"IMPOSSIBLE","Map comment with trailing content"),h.range=[l.offset,A,f??A],h},resolveBlockMap}var resolveBlockSeq={},hasRequiredResolveBlockSeq;function requireResolveBlockSeq(){if(hasRequiredResolveBlockSeq)return resolveBlockSeq;hasRequiredResolveBlockSeq=1;var e=requireYAMLSeq(),t=requireResolveProps(),r=requireUtilFlowIndentCheck();return resolveBlockSeq.resolveBlockSeq=function({composeNode:n,composeEmptyNode:i},s,o,a,c){const u=new(c?.nodeClass??e.YAMLSeq)(s.schema);s.atRoot&&(s.atRoot=!1),s.atKey&&(s.atKey=!1);let l=o.offset,d=null;for(const{start:e,value:c}of o.items){const p=t.resolveProps(e,{indicator:"seq-item-ind",next:c,offset:l,onError:a,parentIndent:o.indent,startOnNewline:!0});if(!p.found){if(!(p.anchor||p.tag||c)){d=p.end,p.comment&&(u.comment=p.comment);continue}c&&"block-seq"===c.type?a(p.end,"BAD_INDENT","All sequence items must start at the same column"):a(l,"MISSING_CHAR","Sequence item without - indicator")}
1502
+ const h=c?n(s,c,p,a):i(s,p.end,e,null,p,a);s.schema.compat&&r.flowIndentCheck(o.indent,c,a),l=h.range[2],u.items.push(h)}return u.range=[o.offset,l,d??l],u},resolveBlockSeq}var resolveFlowCollection={},resolveEnd={},hasRequiredResolveEnd,hasRequiredResolveFlowCollection,hasRequiredComposeCollection;function requireResolveEnd(){if(hasRequiredResolveEnd)return resolveEnd;return hasRequiredResolveEnd=1,resolveEnd.resolveEnd=function(e,t,r,n){let i="";if(e){let s=!1,o="";for(const a of e){const{source:e,type:c}=a;switch(c){case"space":s=!0;break;case"comment":{r&&!s&&n(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const t=e.substring(1)||" ";i?i+=o+t:i=t,o="";break}case"newline":i&&(o+=e),s=!0;break;default:n(a,"UNEXPECTED_TOKEN",`Unexpected ${c} at node end`)}t+=e.length}}return{comment:i,offset:t}},resolveEnd}function requireResolveFlowCollection(){if(hasRequiredResolveFlowCollection)return resolveFlowCollection
1503
+ ;hasRequiredResolveFlowCollection=1;var e=requireIdentity$1(),t=requirePair(),r=requireYAMLMap(),n=requireYAMLSeq(),i=requireResolveEnd(),s=requireResolveProps(),o=requireUtilContainsNewline(),a=requireUtilMapIncludes();const c="Block collections are not allowed within flow collections",u=e=>e&&("block-map"===e.type||"block-seq"===e.type);return resolveFlowCollection.resolveFlowCollection=function({composeNode:l,composeEmptyNode:d},p,h,A,f){const g="{"===h.start.source,m=g?"flow map":"flow sequence",y=new(f?.nodeClass??(g?r.YAMLMap:n.YAMLSeq))(p.schema);y.flow=!0;const E=p.atRoot;E&&(p.atRoot=!1),p.atKey&&(p.atKey=!1);let b=h.offset+h.start.source.length;for(let n=0;n<h.items.length;++n){const i=h.items[n],{start:f,key:E,sep:C,value:v}=i,I=s.resolveProps(f,{flow:m,indicator:"explicit-key-ind",next:E??C?.[0],offset:b,onError:A,parentIndent:h.indent,startOnNewline:!1});if(!I.found){if(!(I.anchor||I.tag||C||v)){
1504
+ 0===n&&I.comma?A(I.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${m}`):n<h.items.length-1&&A(I.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${m}`),I.comment&&(y.comment?y.comment+="\n"+I.comment:y.comment=I.comment),b=I.end;continue}!g&&p.options.strict&&o.containsNewline(E)&&A(E,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(0===n)I.comma&&A(I.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${m}`);else if(I.comma||A(I.start,"MISSING_CHAR",`Missing , between ${m} items`),I.comment){let t="";e:for(const e of f)switch(e.type){case"comma":case"space":break;case"comment":t=e.source.substring(1);break e;default:break e}if(t){let r=y.items[y.items.length-1];e.isPair(r)&&(r=r.value??r.key),r.comment?r.comment+="\n"+t:r.comment=t,I.comment=I.comment.substring(t.length+1)}}if(g||C||I.found){p.atKey=!0;const e=I.end,n=E?l(p,E,I,A):d(p,e,f,null,I,A);u(E)&&A(n.range,"BLOCK_IN_FLOW",c),p.atKey=!1;const o=s.resolveProps(C??[],{flow:m,
1505
+ indicator:"map-value-ind",next:v,offset:n.range[2],onError:A,parentIndent:h.indent,startOnNewline:!1});if(o.found){if(!g&&!I.found&&p.options.strict){if(C)for(const e of C){if(e===o.found)break;if("newline"===e.type){A(e,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}I.start<o.found.offset-1024&&A(o.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else v&&("source"in v&&v.source&&":"===v.source[0]?A(v,"MISSING_CHAR",`Missing space after : in ${m}`):A(o.start,"MISSING_CHAR",`Missing , or : between ${m} items`));const _=v?l(p,v,o,A):o.found?d(p,o.end,C,null,o,A):null;_?u(v)&&A(_.range,"BLOCK_IN_FLOW",c):o.comment&&(n.comment?n.comment+="\n"+o.comment:n.comment=o.comment);const S=new t.Pair(n,_);if(p.options.keepSourceTokens&&(S.srcToken=i),g){const t=y;a.mapIncludes(p,t.items,n)&&A(e,"DUPLICATE_KEY","Map keys must be unique"),t.items.push(S)}else{
1506
+ const e=new r.YAMLMap(p.schema);e.flow=!0,e.items.push(S);const t=(_??n).range;e.range=[n.range[0],t[1],t[2]],y.items.push(e)}b=_?_.range[2]:o.end}else{const e=v?l(p,v,I,A):d(p,I.end,C,null,I,A);y.items.push(e),b=e.range[2],u(v)&&A(e.range,"BLOCK_IN_FLOW",c)}}const C=g?"}":"]",[v,...I]=h.end;let _=b;if(v&&v.source===C)_=v.offset+v.source.length;else{const e=m[0].toUpperCase()+m.substring(1);A(b,E?"MISSING_CHAR":"BAD_INDENT",E?`${e} must end with a ${C}`:`${e} in block collection must be sufficiently indented and end with a ${C}`),v&&1!==v.source.length&&I.unshift(v)}if(I.length>0){const e=i.resolveEnd(I,_,p.options.strict,A);e.comment&&(y.comment?y.comment+="\n"+e.comment:y.comment=e.comment),y.range=[h.offset,_,e.offset]}else y.range=[h.offset,_,_];return y},resolveFlowCollection}function requireComposeCollection(){if(hasRequiredComposeCollection)return composeCollection;hasRequiredComposeCollection=1
1507
+ ;var e=requireIdentity$1(),t=requireScalar(),r=requireYAMLMap(),n=requireYAMLSeq(),i=requireResolveBlockMap(),s=requireResolveBlockSeq(),o=requireResolveFlowCollection();function a(e,t,r,n,a,c){const u="block-map"===r.type?i.resolveBlockMap(e,t,r,n,c):"block-seq"===r.type?s.resolveBlockSeq(e,t,r,n,c):o.resolveFlowCollection(e,t,r,n,c),l=u.constructor;return"!"===a||a===l.tagName?(u.tag=l.tagName,u):(a&&(u.tag=a),u)}return composeCollection.composeCollection=function(i,s,o,c,u){const l=c.tag,d=l?s.directives.tagName(l.source,e=>u(l,"TAG_RESOLVE_FAILED",e)):null;if("block-seq"===o.type){const{anchor:e,newlineAfterProp:t}=c,r=e&&l?e.offset>l.offset?e:l:e??l;if(r&&(!t||t.offset<r.offset)){u(r,"MISSING_CHAR","Missing newline after block sequence props")}}const p="block-map"===o.type?"map":"block-seq"===o.type?"seq":"{"===o.start.source?"map":"seq";if(!l||!d||"!"===d||d===r.YAMLMap.tagName&&"map"===p||d===n.YAMLSeq.tagName&&"seq"===p)return a(i,s,o,u,d)
1508
+ ;let h=s.schema.tags.find(e=>e.tag===d&&e.collection===p);if(!h){const e=s.schema.knownTags[d];if(!e||e.collection!==p)return e?u(l,"BAD_COLLECTION_TYPE",`${e.tag} used for ${p} collection, but expects ${e.collection??"scalar"}`,!0):u(l,"TAG_RESOLVE_FAILED",`Unresolved tag: ${d}`,!0),a(i,s,o,u,d);s.schema.tags.push(Object.assign({},e,{default:!1})),h=e}const A=a(i,s,o,u,d,h),f=h.resolve?.(A,e=>u(l,"TAG_RESOLVE_FAILED",e),s.options)??A,g=e.isNode(f)?f:new t.Scalar(f);return g.range=A.range,g.tag=d,h?.format&&(g.format=h.format),g},composeCollection}var composeScalar={},resolveBlockScalar={},hasRequiredResolveBlockScalar;function requireResolveBlockScalar(){if(hasRequiredResolveBlockScalar)return resolveBlockScalar;hasRequiredResolveBlockScalar=1;var e=requireScalar();return resolveBlockScalar.resolveBlockScalar=function(t,r,n){const i=r.offset,s=function({offset:e,props:t},r,n){if("block-scalar-header"!==t[0].type)return n(t[0],"IMPOSSIBLE","Block scalar header not found"),null
1509
+ ;const{source:i}=t[0],s=i[0];let o=0,a="",c=-1;for(let t=1;t<i.length;++t){const r=i[t];if(a||"-"!==r&&"+"!==r){const n=Number(r);!o&&n?o=n:-1===c&&(c=e+t)}else a=r}-1!==c&&n(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let u=!1,l="",d=i.length;for(let e=1;e<t.length;++e){const i=t[e];switch(i.type){case"space":u=!0;case"newline":d+=i.source.length;break;case"comment":if(r&&!u){n(i,"MISSING_CHAR","Comments must be separated from other tokens by white space characters")}d+=i.source.length,l=i.source.substring(1);break;case"error":n(i,"UNEXPECTED_TOKEN",i.message),d+=i.source.length;break;default:{n(i,"UNEXPECTED_TOKEN",`Unexpected token in block scalar header: ${i.type}`);const e=i.source;e&&"string"==typeof e&&(d+=e.length)}}}return{mode:s,indent:o,chomp:a,comment:l,length:d}}(r,t.options.strict,n);if(!s)return{value:"",type:null,comment:"",range:[i,i,i]};const o=">"===s.mode?e.Scalar.BLOCK_FOLDED:e.Scalar.BLOCK_LITERAL,a=r.source?function(e){
1510
+ const t=e.split(/\n( *)/),r=t[0],n=r.match(/^( *)/),i=n?.[1]?[n[1],r.slice(n[1].length)]:["",r],s=[i];for(let e=1;e<t.length;e+=2)s.push([t[e],t[e+1]]);return s}(r.source):[];let c=a.length;for(let e=a.length-1;e>=0;--e){const t=a[e][1];if(""!==t&&"\r"!==t)break;c=e}if(0===c){const e="+"===s.chomp&&a.length>0?"\n".repeat(Math.max(1,a.length-1)):"";let t=i+s.length;return r.source&&(t+=r.source.length),{value:e,type:o,comment:s.comment,range:[i,t,t]}}let u=r.indent+s.indent,l=r.offset+s.length,d=0;for(let e=0;e<c;++e){const[r,i]=a[e];if(""!==i&&"\r"!==i){if(r.length<u){const e="Block scalars with more-indented leading empty lines must use an explicit indentation indicator";n(l+r.length,"MISSING_CHAR",e)}if(0===s.indent&&(u=r.length),d=e,0===u&&!t.atRoot){n(l,"BAD_INDENT","Block scalar values in collections must be indented")}break}0===s.indent&&r.length>u&&(u=r.length),l+=r.length+i.length+1}for(let e=a.length-1;e>=c;--e)a[e][0].length>u&&(c=e+1);let p="",h="",A=!1
1511
+ ;for(let e=0;e<d;++e)p+=a[e][0].slice(u)+"\n";for(let t=d;t<c;++t){let[r,i]=a[t];l+=r.length+i.length+1;const c="\r"===i[i.length-1];if(c&&(i=i.slice(0,-1)),i&&r.length<u){const e=`Block scalar lines must not be less indented than their ${s.indent?"explicit indentation indicator":"first line"}`;n(l-i.length-(c?2:1),"BAD_INDENT",e),r=""}o===e.Scalar.BLOCK_LITERAL?(p+=h+r.slice(u)+i,h="\n"):r.length>u||"\t"===i[0]?(" "===h?h="\n":A||"\n"!==h||(h="\n\n"),p+=h+r.slice(u)+i,h="\n",A=!0):""===i?"\n"===h?p+="\n":h="\n":(p+=h+i,h=" ",A=!1)}switch(s.chomp){case"-":break;case"+":for(let e=c;e<a.length;++e)p+="\n"+a[e][0].slice(u);"\n"!==p[p.length-1]&&(p+="\n");break;default:p+="\n"}const f=i+s.length+r.source.length;return{value:p,type:o,comment:s.comment,range:[i,f,f]}},resolveBlockScalar}var resolveFlowScalar={},hasRequiredResolveFlowScalar,hasRequiredComposeScalar;function requireResolveFlowScalar(){if(hasRequiredResolveFlowScalar)return resolveFlowScalar;hasRequiredResolveFlowScalar=1
1512
+ ;var e=requireScalar(),t=requireResolveEnd();function r(e){let t,r;try{t=new RegExp("(.*?)(?<![ \t])[ \t]*\r?\n","sy"),r=new RegExp("[ \t]*(.*?)(?:(?<![ \t])[ \t]*)?\r?\n","sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,r=/[ \t]*(.*?)[ \t]*\r?\n/sy}let n=t.exec(e);if(!n)return e;let i=n[1],s=" ",o=t.lastIndex;for(r.lastIndex=o;n=r.exec(e);)""===n[1]?"\n"===s?i+=s:s="\n":(i+=s+n[1],s=" "),o=r.lastIndex;const a=/[ \t]*(.*)/sy;return a.lastIndex=o,n=a.exec(e),i+s+(n?.[1]??"")}function n(e,t){let r="",n=e[t+1];for(;!(" "!==n&&"\t"!==n&&"\n"!==n&&"\r"!==n||"\r"===n&&"\n"!==e[t+2]);)"\n"===n&&(r+="\n"),n=e[(t+=1)+1];return r||(r=" "),{fold:r,offset:t}}const i={0:"\0",a:"",b:"\b",e:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function s(e,t,r,n){const i=e.substr(t,r),s=i.length===r&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;if(isNaN(s)){const i=e.substr(t-2,r+2);return n(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${i}`),i}
1513
+ return String.fromCodePoint(s)}return resolveFlowScalar.resolveFlowScalar=function(o,a,c){const{offset:u,type:l,source:d,end:p}=o;let h,A;const f=(e,t,r)=>c(u+e,t,r);switch(l){case"scalar":h=e.Scalar.PLAIN,A=function(e,t){let n="";switch(e[0]){case"\t":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":n=`block scalar indicator ${e[0]}`;break;case"@":case"`":n=`reserved character ${e[0]}`}n&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`);return r(e)}(d,f);break;case"single-quoted-scalar":h=e.Scalar.QUOTE_SINGLE,A=function(e,t){"'"===e[e.length-1]&&1!==e.length||t(e.length,"MISSING_CHAR","Missing closing 'quote");return r(e.slice(1,-1)).replace(/''/g,"'")}(d,f);break;case"double-quoted-scalar":h=e.Scalar.QUOTE_DOUBLE,A=function(e,t){let r="";for(let o=1;o<e.length-1;++o){const a=e[o];if("\r"!==a||"\n"!==e[o+1])if("\n"===a){const{fold:t,offset:i}=n(e,o);r+=t,o=i}else if("\\"===a){
1514
+ let n=e[++o];const a=i[n];if(a)r+=a;else if("\n"===n)for(n=e[o+1];" "===n||"\t"===n;)n=e[1+ ++o];else if("\r"===n&&"\n"===e[o+1])for(n=e[1+ ++o];" "===n||"\t"===n;)n=e[1+ ++o];else if("x"===n||"u"===n||"U"===n){const i={x:2,u:4,U:8}[n];r+=s(e,o+1,i,t),o+=i}else{const n=e.substr(o-1,2);t(o-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${n}`),r+=n}}else if(" "===a||"\t"===a){const t=o;let n=e[o+1];for(;" "===n||"\t"===n;)n=e[1+ ++o];"\n"===n||"\r"===n&&"\n"===e[o+2]||(r+=o>t?e.slice(t,o+1):a)}else r+=a}'"'===e[e.length-1]&&1!==e.length||t(e.length,"MISSING_CHAR",'Missing closing "quote');return r}(d,f);break;default:return c(o,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${l}`),{value:"",type:null,comment:"",range:[u,u+d.length,u+d.length]}}const g=u+d.length,m=t.resolveEnd(p,g,a,c);return{value:A,type:h,comment:m.comment,range:[u,g,m.offset]}},resolveFlowScalar}function requireComposeScalar(){if(hasRequiredComposeScalar)return composeScalar;hasRequiredComposeScalar=1
1515
+ ;var e=requireIdentity$1(),t=requireScalar(),r=requireResolveBlockScalar(),n=requireResolveFlowScalar();return composeScalar.composeScalar=function(i,s,o,a){const{value:c,type:u,comment:l,range:d}="block-scalar"===s.type?r.resolveBlockScalar(i,s,a):n.resolveFlowScalar(s,i.options.strict,a),p=o?i.directives.tagName(o.source,e=>a(o,"TAG_RESOLVE_FAILED",e)):null;let h,A;h=i.options.stringKeys&&i.atKey?i.schema[e.SCALAR]:p?function(t,r,n,i,s){if("!"===n)return t[e.SCALAR];const o=[];for(const e of t.tags)if(!e.collection&&e.tag===n){if(!e.default||!e.test)return e;o.push(e)}for(const e of o)if(e.test?.test(r))return e;const a=t.knownTags[n];if(a&&!a.collection)return t.tags.push(Object.assign({},a,{default:!1,test:void 0})),a;return s(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,"tag:yaml.org,2002:str"!==n),t[e.SCALAR]}(i.schema,c,p,o,a):"scalar"===s.type?function({atKey:t,directives:r,schema:n},i,s,o){
1516
+ const a=n.tags.find(e=>(!0===e.default||t&&"key"===e.default)&&e.test?.test(i))||n[e.SCALAR];if(n.compat){const t=n.compat.find(e=>e.default&&e.test?.test(i))??n[e.SCALAR];if(a.tag!==t.tag){o(s,"TAG_RESOLVE_FAILED",`Value may be parsed as either ${r.tagString(a.tag)} or ${r.tagString(t.tag)}`,!0)}}return a}(i,c,s,a):i.schema[e.SCALAR];try{const r=h.resolve(c,e=>a(o??s,"TAG_RESOLVE_FAILED",e),i.options);A=e.isScalar(r)?r:new t.Scalar(r)}catch(e){const r=e instanceof Error?e.message:String(e);a(o??s,"TAG_RESOLVE_FAILED",r),A=new t.Scalar(c)}return A.range=d,A.source=c,u&&(A.type=u),p&&(A.tag=p),h.format&&(A.format=h.format),l&&(A.comment=l),A},composeScalar}var utilEmptyScalarPosition={},hasRequiredUtilEmptyScalarPosition,hasRequiredComposeNode,hasRequiredComposeDoc,hasRequiredComposer;function requireUtilEmptyScalarPosition(){if(hasRequiredUtilEmptyScalarPosition)return utilEmptyScalarPosition;return hasRequiredUtilEmptyScalarPosition=1,
1517
+ utilEmptyScalarPosition.emptyScalarPosition=function(e,t,r){if(t){r??(r=t.length);for(let n=r-1;n>=0;--n){let r=t[n];switch(r.type){case"space":case"comment":case"newline":e-=r.source.length;continue}for(r=t[++n];"space"===r?.type;)e+=r.source.length,r=t[++n];break}}return e},utilEmptyScalarPosition}function requireComposeNode(){if(hasRequiredComposeNode)return composeNode;hasRequiredComposeNode=1;var e=requireAlias(),t=requireIdentity$1(),r=requireComposeCollection(),n=requireComposeScalar(),i=requireResolveEnd(),s=requireUtilEmptyScalarPosition();const o={composeNode:a,composeEmptyNode:c};function a(s,a,u,l){const d=s.atKey,{spaceBefore:p,comment:h,anchor:A,tag:f}=u;let g,m=!0;switch(a.type){case"alias":g=function({options:t},{offset:r,source:n,end:s},o){const a=new e.Alias(n.substring(1));""===a.source&&o(r,"BAD_ALIAS","Alias cannot be an empty string");a.source.endsWith(":")&&o(r+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0)
1518
+ ;const c=r+n.length,u=i.resolveEnd(s,c,t.strict,o);a.range=[r,c,u.offset],u.comment&&(a.comment=u.comment);return a}(s,a,l),(A||f)&&l(a,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":g=n.composeScalar(s,a,f,l),A&&(g.anchor=A.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":g=r.composeCollection(o,s,a,u,l),A&&(g.anchor=A.source.substring(1));break;default:l(a,"UNEXPECTED_TOKEN","error"===a.type?a.message:`Unsupported token (type: ${a.type})`),g=c(s,a.offset,void 0,null,u,l),m=!1}if(A&&""===g.anchor&&l(A,"BAD_ALIAS","Anchor cannot be an empty string"),d&&s.options.stringKeys&&(!t.isScalar(g)||"string"!=typeof g.value||g.tag&&"tag:yaml.org,2002:str"!==g.tag)){l(f??a,"NON_STRING_KEY","With stringKeys, all keys must be strings")}return p&&(g.spaceBefore=!0),h&&("scalar"===a.type&&""===a.source?g.comment=h:g.commentBefore=h),
1519
+ s.options.keepSourceTokens&&m&&(g.srcToken=a),g}function c(e,t,r,i,{spaceBefore:o,comment:a,anchor:c,tag:u,end:l},d){const p={type:"scalar",offset:s.emptyScalarPosition(t,r,i),indent:-1,source:""},h=n.composeScalar(e,p,u,d);return c&&(h.anchor=c.source.substring(1),""===h.anchor&&d(c,"BAD_ALIAS","Anchor cannot be an empty string")),o&&(h.spaceBefore=!0),a&&(h.comment=a,h.range[2]=l),h}return composeNode.composeEmptyNode=c,composeNode.composeNode=a,composeNode}function requireComposeDoc(){if(hasRequiredComposeDoc)return composeDoc;hasRequiredComposeDoc=1;var e=requireDocument(),t=requireComposeNode(),r=requireResolveEnd(),n=requireResolveProps();return composeDoc.composeDoc=function(i,s,{offset:o,start:a,value:c,end:u},l){const d=Object.assign({_directives:s},i),p=new e.Document(void 0,d),h={atKey:!1,atRoot:!0,directives:p.directives,options:p.options,schema:p.schema},A=n.resolveProps(a,{indicator:"doc-start",next:c??u?.[0],offset:o,onError:l,parentIndent:0,startOnNewline:!0})
1520
+ ;A.found&&(p.directives.docStart=!0,!c||"block-map"!==c.type&&"block-seq"!==c.type||A.hasNewline||l(A.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),p.contents=c?t.composeNode(h,c,A,l):t.composeEmptyNode(h,A.end,a,null,A,l);const f=p.contents.range[2],g=r.resolveEnd(u,f,!1,l);return g.comment&&(p.comment=g.comment),p.range=[o,f,g.offset],p},composeDoc}function requireComposer(){if(hasRequiredComposer)return composer;hasRequiredComposer=1;var e=process__default,t=requireDirectives(),r=requireDocument(),n=requireErrors$4(),i=requireIdentity$1(),s=requireComposeDoc(),o=requireResolveEnd();function a(e){if("number"==typeof e)return[e,e+1];if(Array.isArray(e))return 2===e.length?e:[e[0],e[1]];const{offset:t,source:r}=e;return[t,t+("string"==typeof r?r.length:1)]}function c(e){let t="",r=!1,n=!1;for(let i=0;i<e.length;++i){const s=e[i];switch(s[0]){case"#":t+=(""===t?"":n?"\n\n":"\n")+(s.substring(1)||" "),r=!0,n=!1;break;case"%":
1521
+ "#"!==e[i+1]?.[0]&&(i+=1),r=!1;break;default:r||(n=!0),r=!1}}return{comment:t,afterEmptyLine:n}}return composer.Composer=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,r,i)=>{const s=a(e);i?this.warnings.push(new n.YAMLWarning(s,t,r)):this.errors.push(new n.YAMLParseError(s,t,r))},this.directives=new t.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:r,afterEmptyLine:n}=c(this.prelude);if(r){const s=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${r}`:r;else if(n||e.directives.docStart||!s)e.commentBefore=r;else if(i.isCollection(s)&&!s.flow&&s.items.length>0){let e=s.items[0];i.isPair(e)&&(e=e.key);const t=e.commentBefore;e.commentBefore=t?`${r}\n${t}`:r}else{const e=s.commentBefore;s.commentBefore=e?`${r}\n${e}`:r}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),
1522
+ this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:c(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,r=-1){for(const t of e)yield*this.next(t);yield*this.end(t,r)}*next(t){switch(e.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(e,r,n)=>{const i=a(t);i[0]+=e,this.onError(i,"BAD_DIRECTIVE",r,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{const e=s.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!e.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(e,!1),this.doc&&(yield this.doc),this.doc=e,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{
1523
+ const e=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,r=new n.YAMLParseError(a(t),"UNEXPECTED_TOKEN",e);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){const e="Unexpected doc-end without preceding document";this.errors.push(new n.YAMLParseError(a(t),"UNEXPECTED_TOKEN",e));break}this.doc.directives.docEnd=!0;const e=o.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),e.comment){const t=this.doc.comment;this.doc.comment=t?`${t}\n${e.comment}`:e.comment}this.doc.range[2]=e.offset;break}default:this.errors.push(new n.YAMLParseError(a(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){const e=Object.assign({_directives:this.directives},this.options),n=new r.Document(void 0,e)
1524
+ ;this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,t,t],this.decorate(n,!1),yield n}}},composer}var cst={},cstScalar={},hasRequiredCstScalar;function requireCstScalar(){if(hasRequiredCstScalar)return cstScalar;hasRequiredCstScalar=1;var e=requireResolveBlockScalar(),t=requireResolveFlowScalar(),r=requireErrors$4(),n=requireStringifyString();function i(e,t){if(t)for(const r of t)switch(r.type){case"space":case"comment":e.push(r);break;case"newline":return e.push(r),!0}return!1}function s(e,t,r){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=r,e.source=t;break;case"block-scalar":{const n=e.props.slice(1);let i=t.length;"block-scalar-header"===e.props[0].type&&(i-=e.props[0].source.length);for(const e of n)e.offset+=i;delete e.props,Object.assign(e,{type:r,source:t,end:n});break}case"block-map":case"block-seq":{const n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:"\n"}
1525
+ ;delete e.items,Object.assign(e,{type:r,source:t,end:[n]});break}default:{const n="indent"in e?e.indent:-1,i="end"in e&&Array.isArray(e.end)?e.end.filter(e=>"space"===e.type||"comment"===e.type||"newline"===e.type):[];for(const t of Object.keys(e))"type"!==t&&"offset"!==t&&delete e[t];Object.assign(e,{type:r,indent:n,source:t,end:i})}}}return cstScalar.createScalarToken=function(e,t){const{implicitKey:r=!1,indent:s,inFlow:o=!1,offset:a=-1,type:c="PLAIN"}=t,u=n.stringifyString({type:c,value:e},{implicitKey:r,indent:s>0?" ".repeat(s):"",inFlow:o,options:{blockQuote:!0,lineWidth:-1}}),l=t.end??[{type:"newline",offset:-1,indent:s,source:"\n"}];switch(u[0]){case"|":case">":{const e=u.indexOf("\n"),t=u.substring(0,e),r=u.substring(e+1)+"\n",n=[{type:"block-scalar-header",offset:a,indent:s,source:t}];return i(n,l)||n.push({type:"newline",offset:-1,indent:s,source:"\n"}),{type:"block-scalar",offset:a,indent:s,props:n,source:r}}case'"':return{type:"double-quoted-scalar",offset:a,indent:s,
1526
+ source:u,end:l};case"'":return{type:"single-quoted-scalar",offset:a,indent:s,source:u,end:l};default:return{type:"scalar",offset:a,indent:s,source:u,end:l}}},cstScalar.resolveAsScalar=function(n,i=!0,s){if(n){const o=(e,t,n)=>{const i="number"==typeof e?e:Array.isArray(e)?e[0]:e.offset;if(!s)throw new r.YAMLParseError([i,i+1],t,n);s(i,t,n)};switch(n.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return t.resolveFlowScalar(n,i,o);case"block-scalar":return e.resolveBlockScalar({options:{strict:i}},n,o)}}return null},cstScalar.setScalarValue=function(e,t,r={}){let{afterKey:o=!1,implicitKey:a=!1,inFlow:c=!1,type:u}=r,l="indent"in e?e.indent:null;if(o&&"number"==typeof l&&(l+=2),!u)switch(e.type){case"single-quoted-scalar":u="QUOTE_SINGLE";break;case"double-quoted-scalar":u="QUOTE_DOUBLE";break;case"block-scalar":{const t=e.props[0];if("block-scalar-header"!==t.type)throw new Error("Invalid block scalar header");u=">"===t.source[0]?"BLOCK_FOLDED":"BLOCK_LITERAL"
1527
+ ;break}default:u="PLAIN"}const d=n.stringifyString({type:u,value:t},{implicitKey:a||null===l,indent:null!==l&&l>0?" ".repeat(l):"",inFlow:c,options:{blockQuote:!0,lineWidth:-1}});switch(d[0]){case"|":case">":!function(e,t){const r=t.indexOf("\n"),n=t.substring(0,r),s=t.substring(r+1)+"\n";if("block-scalar"===e.type){const t=e.props[0];if("block-scalar-header"!==t.type)throw new Error("Invalid block scalar header");t.source=n,e.source=s}else{const{offset:t}=e,r="indent"in e?e.indent:-1,o=[{type:"block-scalar-header",offset:t,indent:r,source:n}];i(o,"end"in e?e.end:void 0)||o.push({type:"newline",offset:-1,indent:r,source:"\n"});for(const t of Object.keys(e))"type"!==t&&"offset"!==t&&delete e[t];Object.assign(e,{type:"block-scalar",indent:r,props:o,source:s})}}(e,d);break;case'"':s(e,d,"double-quoted-scalar");break;case"'":s(e,d,"single-quoted-scalar");break;default:s(e,d,"scalar")}},cstScalar}var cstStringify={},hasRequiredCstStringify;function requireCstStringify(){
1528
+ if(hasRequiredCstStringify)return cstStringify;hasRequiredCstStringify=1;function e(r){switch(r.type){case"block-scalar":{let t="";for(const n of r.props)t+=e(n);return t+r.source}case"block-map":case"block-seq":{let e="";for(const n of r.items)e+=t(n);return e}case"flow-collection":{let e=r.start.source;for(const n of r.items)e+=t(n);for(const t of r.end)e+=t.source;return e}case"document":{let e=t(r);if(r.end)for(const t of r.end)e+=t.source;return e}default:{let e=r.source;if("end"in r&&r.end)for(const t of r.end)e+=t.source;return e}}}function t({start:t,key:r,sep:n,value:i}){let s="";for(const e of t)s+=e.source;if(r&&(s+=e(r)),n)for(const e of n)s+=e.source;return i&&(s+=e(i)),s}return cstStringify.stringify=r=>"type"in r?e(r):t(r),cstStringify}var cstVisit={},hasRequiredCstVisit,hasRequiredCst;function requireCstVisit(){if(hasRequiredCstVisit)return cstVisit;hasRequiredCstVisit=1;const e=Symbol("break visit"),t=Symbol("skip children"),r=Symbol("remove item");function n(e,t){
1529
+ "type"in e&&"document"===e.type&&(e={start:e.start,value:e.value}),i(Object.freeze([]),e,t)}function i(t,n,s){let o=s(n,t);if("symbol"==typeof o)return o;for(const a of["key","value"]){const c=n[a];if(c&&"items"in c){for(let n=0;n<c.items.length;++n){const o=i(Object.freeze(t.concat([[a,n]])),c.items[n],s);if("number"==typeof o)n=o-1;else{if(o===e)return e;o===r&&(c.items.splice(n,1),n-=1)}}"function"==typeof o&&"key"===a&&(o=o(n,t))}}return"function"==typeof o?o(n,t):o}return n.BREAK=e,n.SKIP=t,n.REMOVE=r,n.itemAtPath=(e,t)=>{let r=e;for(const[e,n]of t){const t=r?.[e];if(!t||!("items"in t))return;r=t.items[n]}return r},n.parentCollection=(e,t)=>{const r=n.itemAtPath(e,t.slice(0,-1)),i=t[t.length-1][0],s=r?.[i];if(s&&"items"in s)return s;throw new Error("Parent collection not found")},cstVisit.visit=n,cstVisit}function requireCst(){if(hasRequiredCst)return cst;hasRequiredCst=1;var e=requireCstScalar(),t=requireCstStringify(),r=requireCstVisit()
1530
+ ;return cst.createScalarToken=e.createScalarToken,cst.resolveAsScalar=e.resolveAsScalar,cst.setScalarValue=e.setScalarValue,cst.stringify=t.stringify,cst.visit=r.visit,cst.BOM="\ufeff",cst.DOCUMENT="",cst.FLOW_END="",cst.SCALAR="",cst.isCollection=e=>!!e&&"items"in e,cst.isScalar=e=>!!e&&("scalar"===e.type||"single-quoted-scalar"===e.type||"double-quoted-scalar"===e.type||"block-scalar"===e.type),cst.prettyToken=function(e){switch(e){case"\ufeff":return"<BOM>";case"":return"<DOC>";case"":return"<FLOW_END>";case"":return"<SCALAR>";default:return JSON.stringify(e)}},cst.tokenType=function(e){switch(e){case"\ufeff":return"byte-order-mark";case"":return"doc-mode";case"":return"flow-error-end";case"":return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case"\n":case"\r\n":return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":
1531
+ return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case"\t":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null},cst}var lexer={},hasRequiredLexer;function requireLexer(){if(hasRequiredLexer)return lexer;hasRequiredLexer=1;var e=requireCst();function t(e){switch(e){case void 0:case" ":case"\n":case"\r":case"\t":return!0;default:return!1}}const r=new Set("0123456789ABCDEFabcdef"),n=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),i=new Set(",[]{}"),s=new Set(" ,[]{}\n\r\t"),o=e=>!e||s.has(e);return lexer.Lexer=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,
1532
+ this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if("string"!=typeof e)throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let r=this.next??"stream";for(;r&&(t||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;" "===t||"\t"===t;)t=this.buffer[++e];return!t||"#"===t||"\n"===t||"\r"===t&&"\n"===this.buffer[e+1]}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let r=this.buffer[e];if(this.indentNext>0){let t=0;for(;" "===r;)r=this.buffer[++t+e];if("\r"===r){const r=this.buffer[t+e+1];if("\n"===r||!r&&!this.atEnd)return e+t+1}return"\n"===r||t>=this.indentNext||!r&&!this.atEnd?e+t:-1}if("-"===r||"."===r){const r=this.buffer.substr(e,3);if(("---"===r||"..."===r)&&t(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return("number"!=typeof e||-1!==e&&e<this.pos)&&(e=this.buffer.indexOf("\n",this.pos),this.lineEndPos=e),
1533
+ -1===e?this.atEnd?this.buffer.substring(this.pos):null:("\r"===this.buffer[e-1]&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(null===t)return this.setNext("stream");if(t[0]===e.BOM&&(yield*this.pushCount(1),t=t.substring(1)),"%"===t[0]){let e=t.length,r=t.indexOf("#");for(;-1!==r;){const n=t[r-1]
1534
+ ;if(" "===n||"\t"===n){e=r-1;break}r=t.indexOf("#",r+1)}for(;;){const r=t[e-1];if(" "!==r&&"\t"!==r)break;e-=1}const n=(yield*this.pushCount(e))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){const e=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-e),yield*this.pushNewline(),"stream"}return yield e.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){const e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if("-"===e||"."===e){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");const e=this.peek(3);if(("---"===e||"..."===e)&&t(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,"---"===e?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!t(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){const[e,r]=this.peek(2)
1535
+ ;if(!r&&!this.atEnd)return this.setNext("block-start");if(("-"===e||"?"===e||":"===e)&&t(r)){const e=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=e,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);const e=this.getLine();if(null===e)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(o),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=(yield*this.parseBlockScalarHeader()),t+=(yield*this.pushSpaces(!0)),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}
1536
+ *parseFlowCollection(){let r,n,i=-1;do{r=yield*this.pushNewline(),r>0?(n=yield*this.pushSpaces(!1),this.indentValue=i=n):n=0,n+=(yield*this.pushSpaces(!0))}while(r+n>0);const s=this.getLine();if(null===s)return this.setNext("flow");if(-1!==i&&i<this.indentNext&&"#"!==s[0]||0===i&&(s.startsWith("---")||s.startsWith("..."))&&t(s[3])){if(!(i===this.indentNext-1&&1===this.flowLevel&&("]"===s[0]||"}"===s[0])))return this.flowLevel=0,yield e.FLOW_END,yield*this.parseLineStart()}let a=0;for(;","===s[a];)a+=(yield*this.pushCount(1)),a+=(yield*this.pushSpaces(!0)),this.flowKey=!1;switch(a+=(yield*this.pushIndicators()),s[a]){case void 0:return"flow";case"#":return yield*this.pushCount(s.length-a),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(o),"flow";case'"':case"'":return this.flowKey=!0,
1537
+ yield*this.parseQuotedScalar();case":":{const e=this.charAt(1);if(this.flowKey||t(e)||","===e)return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){const e=this.charAt(0);let t=this.buffer.indexOf(e,this.pos+1);if("'"===e)for(;-1!==t&&"'"===this.buffer[t+1];)t=this.buffer.indexOf("'",t+2);else for(;-1!==t;){let e=0;for(;"\\"===this.buffer[t-1-e];)e+=1;if(e%2==0)break;t=this.buffer.indexOf('"',t+1)}const r=this.buffer.substring(0,t);let n=r.indexOf("\n",this.pos);if(-1!==n){for(;-1!==n;){const e=this.continueScalar(n+1);if(-1===e)break;n=r.indexOf("\n",e)}-1!==n&&(t=n-("\r"===r[n-1]?2:1))}if(-1===t){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){const t=this.buffer[++e]
1538
+ ;if("+"===t)this.blockScalarKeep=!0;else if(t>"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if("-"!==t)break}return yield*this.pushUntil(e=>t(e)||"#"===e)}*parseBlockScalar(){let t,r=this.pos-1,n=0;e:for(let e=this.pos;t=this.buffer[e];++e)switch(t){case" ":n+=1;break;case"\n":r=e,n=0;break;case"\r":{const t=this.buffer[e+1];if(!t&&!this.atEnd)return this.setNext("block-scalar");if("\n"===t)break}default:break e}if(!t&&!this.atEnd)return this.setNext("block-scalar");if(n>=this.indentNext){-1===this.blockScalarIndent?this.indentNext=n:this.indentNext=this.blockScalarIndent+(0===this.indentNext?1:this.indentNext);do{const e=this.continueScalar(r+1);if(-1===e)break;r=this.buffer.indexOf("\n",e)}while(-1!==r);if(-1===r){if(!this.atEnd)return this.setNext("block-scalar");r=this.buffer.length}}let i=r+1;for(t=this.buffer[i];" "===t;)t=this.buffer[++i];if("\t"===t){for(;"\t"===t||" "===t||"\r"===t||"\n"===t;)t=this.buffer[++i];r=i-1}else if(!this.blockScalarKeep)for(;;){
1539
+ let e=r-1,t=this.buffer[e];"\r"===t&&(t=this.buffer[--e]);const i=e;for(;" "===t;)t=this.buffer[--e];if(!("\n"===t&&e>=this.pos&&e+1+n>i))break;r=e}return yield e.SCALAR,yield*this.pushToIndex(r+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){const r=this.flowLevel>0;let n,s=this.pos-1,o=this.pos-1;for(;n=this.buffer[++o];)if(":"===n){const e=this.buffer[o+1];if(t(e)||r&&i.has(e))break;s=o}else if(t(n)){let e=this.buffer[o+1];if("\r"===n&&("\n"===e?(o+=1,n="\n",e=this.buffer[o+1]):s=o),"#"===e||r&&i.has(e))break;if("\n"===n){const e=this.continueScalar(o+1);if(-1===e)break;o=Math.max(o,e-2)}}else{if(r&&i.has(n))break;s=o}return n||this.atEnd?(yield e.SCALAR,yield*this.pushToIndex(s+1,!0),r?"flow":"doc"):this.setNext("plain-scalar")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){const r=this.buffer.slice(this.pos,e);return r?(yield r,this.pos+=r.length,r.length):(t&&(yield""),0)}*pushIndicators(){switch(this.charAt(0)){case"!":
1540
+ return(yield*this.pushTag())+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"&":return(yield*this.pushUntil(o))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,r=this.charAt(1);if(t(r)||e&&i.has(r))return e?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,(yield*this.pushCount(1))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators())}}return 0}*pushTag(){if("<"===this.charAt(1)){let e=this.pos+2,r=this.buffer[e];for(;!t(r)&&">"!==r;)r=this.buffer[++e];return yield*this.pushToIndex(">"===r?e+1:e,!1)}{let e=this.pos+1,t=this.buffer[e];for(;t;)if(n.has(t))t=this.buffer[++e];else{if("%"!==t||!r.has(this.buffer[e+1])||!r.has(this.buffer[e+2]))break;t=this.buffer[e+=3]}return yield*this.pushToIndex(e,!1)}}*pushNewline(){const e=this.buffer[this.pos];return"\n"===e?yield*this.pushCount(1):"\r"===e&&"\n"===this.charAt(1)?yield*this.pushCount(2):0}*pushSpaces(e){let t,r=this.pos-1;do{
1541
+ t=this.buffer[++r]}while(" "===t||e&&"\t"===t);const n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(e){let t=this.pos,r=this.buffer[t];for(;!e(r);)r=this.buffer[++t];return yield*this.pushToIndex(t,!1)}},lexer}var lineCounter={},hasRequiredLineCounter;function requireLineCounter(){if(hasRequiredLineCounter)return lineCounter;hasRequiredLineCounter=1;return lineCounter.LineCounter=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,r=this.lineStarts.length;for(;t<r;){const n=t+r>>1;this.lineStarts[n]<e?t=n+1:r=n}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(0===t)return{line:0,col:e};return{line:t,col:e-this.lineStarts[t-1]+1}}}},lineCounter}var parser$1={},hasRequiredParser$2;function requireParser$2(){if(hasRequiredParser$2)return parser$1;hasRequiredParser$2=1;var e=process__default,t=requireCst(),r=requireLexer();function n(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0
1542
+ ;return!1}function i(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function s(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function o(e){switch(e.type){case"document":return e.start;case"block-map":{const t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function a(e){if(0===e.length)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;"space"===e[++t]?.type;);return e.splice(t,e.length)}function c(e){if("flow-seq-start"===e.start.type)for(const t of e.items)!t.sep||t.value||n(t.start,"explicit-key-ind")||n(t.sep,"map-value-ind")||(t.key&&(t.value=t.key),delete t.key,
1543
+ s(t.value)?t.value.end?Array.prototype.push.apply(t.value.end,t.sep):t.value.end=t.sep:Array.prototype.push.apply(t.start,t.sep),delete t.sep)}return parser$1.Parser=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new r.Lexer,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&0===this.offset&&this.onNewLine(0);for(const r of this.lexer.lex(e,t))yield*this.next(r);t||(yield*this.end())}*next(r){if(this.source=r,e.env.LOG_TOKENS&&console.log("|",t.prettyToken(r)),this.atScalar)return this.atScalar=!1,yield*this.step(),void(this.offset+=r.length);const n=t.tokenType(r);if(n)if("scalar"===n)this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=n,yield*this.step(),n){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+r.length);break;case"space":this.atNewLine&&" "===r[0]&&(this.indent+=r.length);break;case"explicit-key-ind":
1544
+ case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=r.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=r.length}else{const e=`Not a YAML token: ${r}`;yield*this.pop({type:"error",offset:this.offset,message:e,source:r}),this.offset+=r.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){const e=this.peek(1);if("doc-end"!==this.type||e&&"doc-end"===e.type){if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}
1545
+ yield*this.pop()}else{for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source})}}peek(e){return this.stack[this.stack.length-e]}*pop(e){const t=e??this.stack.pop();if(t)if(0===this.stack.length)yield t;else{const e=this.peek(1);switch("block-scalar"===t.type?t.indent="indent"in e?e.indent:0:"flow-collection"===t.type&&"document"===e.type&&(t.indent=0),"flow-collection"===t.type&&c(t),e.type){case"document":e.value=t;break;case"block-scalar":e.props.push(t);break;case"block-map":{const r=e.items[e.items.length-1];if(r.value)return e.items.push({start:[],key:t,sep:[]}),void(this.onKeyLine=!0);if(!r.sep)return Object.assign(r,{key:t,sep:[]}),void(this.onKeyLine=!r.explicitKey);r.value=t;break}case"block-seq":{const r=e.items[e.items.length-1];r.value?e.items.push({start:[],value:t}):r.value=t;break}case"flow-collection":{const r=e.items[e.items.length-1];return void(!r||r.value?e.items.push({start:[],key:t,sep:[]
1546
+ }):r.sep?r.value=t:Object.assign(r,{key:t,sep:[]}))}default:yield*this.pop(),yield*this.pop(t)}if(!("document"!==e.type&&"block-map"!==e.type&&"block-seq"!==e.type||"block-map"!==t.type&&"block-seq"!==t.type)){const r=t.items[t.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&-1===i(r.start)&&(0===t.indent||r.start.every(e=>"comment"!==e.type||e.indent<t.indent))&&("document"===e.type?e.end=r.start:e.items.push({start:r.start}),t.items.splice(-1,1))}}else{const e="Tried to pop an empty stack";yield{type:"error",offset:this.offset,source:"",message:e}}}*stream(){switch(this.type){case"directive-line":return void(yield{type:"directive",offset:this.offset,source:this.source});case"byte-order-mark":case"space":case"comment":case"newline":return void(yield this.sourceToken);case"doc-mode":case"doc-start":{const e={type:"document",offset:this.offset,start:[]};return"doc-start"===this.type&&e.start.push(this.sourceToken),void this.stack.push(e)}}yield{type:"error",offset:this.offset,
1547
+ message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":return void(-1!==i(e.start)?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken));case"anchor":case"tag":case"space":case"comment":case"newline":return void e.start.push(this.sourceToken)}const t=this.startBlockValue(e);t?this.stack.push(t):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if("map-value-ind"===this.type){const t=a(o(this.peek(2)));let r;e.end?(r=e.end,r.push(this.sourceToken),delete e.end):r=[this.sourceToken];const n={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:t,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=n}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":return void e.props.push(this.sourceToken);case"scalar":
1548
+ if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let e=this.source.indexOf("\n")+1;for(;0!==e;)this.onNewLine(this.offset+e),e=this.source.indexOf("\n",e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){const r="end"in t.value?t.value.end:void 0,n=Array.isArray(r)?r[r.length-1]:void 0;"comment"===n?.type?r?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){const r=e.items[e.items.length-2],n=r?.value?.end;if(Array.isArray(n))return Array.prototype.push.apply(n,t.start),n.push(this.sourceToken),void e.items.pop()}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){
1549
+ const r=!this.onKeyLine&&this.indent===e.indent,i=r&&(t.sep||t.explicitKey)&&"seq-item-ind"!==this.type;let o=[];if(i&&t.sep&&!t.value){const r=[];for(let n=0;n<t.sep.length;++n){const i=t.sep[n];switch(i.type){case"newline":r.push(n);break;case"space":break;case"comment":i.indent>e.indent&&(r.length=0);break;default:r.length=0}}r.length>=2&&(o=t.sep.splice(r[1]))}switch(this.type){case"anchor":case"tag":return void(i||t.value?(o.push(this.sourceToken),e.items.push({start:o}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken));case"explicit-key-ind":return t.sep||t.explicitKey?i||t.value?(o.push(this.sourceToken),e.items.push({start:o,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}):(t.start.push(this.sourceToken),t.explicitKey=!0),void(this.onKeyLine=!0);case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,
1550
+ sep:[this.sourceToken]});else if(n(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]});else if(s(t.key)&&!n(t.sep,"newline")){const e=a(t.start),r=t.key,n=t.sep;n.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:e,key:r,sep:n}]})}else o.length>0?t.sep=t.sep.concat(o,this.sourceToken):t.sep.push(this.sourceToken);else if(n(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const e=a(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||i?e.items.push({start:o,key:null,sep:[this.sourceToken]}):n(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{
1551
+ key:null,sep:[this.sourceToken]});return void(this.onKeyLine=!0);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const r=this.flowScalar(this.type);return void(i||t.value?(e.items.push({start:o,key:r,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(r):(Object.assign(t,{key:r,sep:[]}),this.onKeyLine=!0))}default:{const i=this.startBlockValue(e);if(i){if("block-seq"===i.type){if(!t.explicitKey&&t.sep&&!n(t.sep,"newline"))return void(yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source}))}else r&&e.items.push({start:o});return void this.stack.push(i)}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){const r="end"in t.value?t.value.end:void 0,n=Array.isArray(r)?r[r.length-1]:void 0;"comment"===n?.type?r?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken)
1552
+ ;return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){const r=e.items[e.items.length-2],n=r?.value?.end;if(Array.isArray(n))return Array.prototype.push.apply(n,t.start),n.push(this.sourceToken),void e.items.pop()}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;return void t.start.push(this.sourceToken);case"seq-item-ind":if(this.indent!==e.indent)break;return void(t.value||n(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken))}if(this.indent>e.indent){const t=this.startBlockValue(e);if(t)return void this.stack.push(t)}yield*this.pop(),yield*this.step()}*flowCollection(e){const t=e.items[e.items.length-1];if("flow-error-end"===this.type){let e;do{yield*this.pop(),e=this.peek(1)}while(e&&"flow-collection"===e.type)}else if(0===e.end.length){switch(this.type){case"comma":case"explicit-key-ind":
1553
+ return void(!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken));case"map-value-ind":return void(!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]}));case"space":case"comment":case"newline":case"anchor":case"tag":return void(!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken));case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const r=this.flowScalar(this.type);return void(!t||t.value?e.items.push({start:[],key:r,sep:[]}):t.sep?this.stack.push(r):Object.assign(t,{key:r,sep:[]}))}case"flow-map-end":case"flow-seq-end":return void e.end.push(this.sourceToken)}const r=this.startBlockValue(e);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{const t=this.peek(2)
1554
+ ;if("block-map"===t.type&&("map-value-ind"===this.type&&t.indent===e.indent||"newline"===this.type&&!t.items[t.items.length-1].sep))yield*this.pop(),yield*this.step();else if("map-value-ind"===this.type&&"flow-collection"!==t.type){const r=a(o(t));c(e);const n=e.end.splice(1,e.end.length);n.push(this.sourceToken);const i={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:r,key:e,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf("\n")+1;for(;0!==e;)this.onNewLine(this.offset+e),e=this.source.indexOf("\n",e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":
1555
+ case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;const t=a(o(e));return t.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;const t=a(o(e));return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return"comment"===this.type&&(!(this.indent<=t)&&e.every(e=>"newline"===e.type||"space"===e.type))}*documentEnd(e){"doc-mode"!==this.type&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],"newline"===this.type&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":
1556
+ case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],"newline"===this.type&&(yield*this.pop())}}},parser$1}var publicApi={},hasRequiredPublicApi,hasRequiredDist$1;function requirePublicApi(){if(hasRequiredPublicApi)return publicApi;hasRequiredPublicApi=1;var e=requireComposer(),t=requireDocument(),r=requireErrors$4(),n=requireLog(),i=requireIdentity$1(),s=requireLineCounter(),o=requireParser$2();function a(e){const t=!1!==e.prettyErrors;return{lineCounter:e.lineCounter||t&&new s.LineCounter||null,prettyErrors:t}}function c(t,n={}){const{lineCounter:i,prettyErrors:s}=a(n),c=new o.Parser(i?.addNewLine),u=new e.Composer(n);let l=null;for(const e of u.compose(c.parse(t),!0,t.length))if(l){if("silent"!==l.options.logLevel){l.errors.push(new r.YAMLParseError(e.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}}else l=e
1557
+ ;return s&&i&&(l.errors.forEach(r.prettifyError(t,i)),l.warnings.forEach(r.prettifyError(t,i))),l}return publicApi.parse=function(e,t,r){let i;"function"==typeof t?i=t:void 0===r&&t&&"object"==typeof t&&(r=t);const s=c(e,r);if(!s)return null;if(s.warnings.forEach(e=>n.warn(s.options.logLevel,e)),s.errors.length>0){if("silent"!==s.options.logLevel)throw s.errors[0];s.errors=[]}return s.toJS(Object.assign({reviver:i},r))},publicApi.parseAllDocuments=function(t,n={}){const{lineCounter:i,prettyErrors:s}=a(n),c=new o.Parser(i?.addNewLine),u=new e.Composer(n),l=Array.from(u.compose(c.parse(t)));if(s&&i)for(const e of l)e.errors.forEach(r.prettifyError(t,i)),e.warnings.forEach(r.prettifyError(t,i));return l.length>0?l:Object.assign([],{empty:!0},u.streamInfo())},publicApi.parseDocument=c,publicApi.stringify=function(e,r,n){let s=null;if("function"==typeof r||Array.isArray(r)?s=r:void 0===n&&r&&(n=r),"string"==typeof n&&(n=n.length),"number"==typeof n){const e=Math.round(n);n=e<1?void 0:e>8?{
1558
+ indent:8}:{indent:e}}if(void 0===e){const{keepUndefined:e}=n??r??{};if(!e)return}return i.isDocument(e)&&!s?e.toString(n):new t.Document(e,s,n).toString(n)},publicApi}function requireDist$1(){if(hasRequiredDist$1)return dist$1;hasRequiredDist$1=1;var e=requireComposer(),t=requireDocument(),r=requireSchema(),n=requireErrors$4(),i=requireAlias(),s=requireIdentity$1(),o=requirePair(),a=requireScalar(),c=requireYAMLMap(),u=requireYAMLSeq(),l=requireCst(),d=requireLexer(),p=requireLineCounter(),h=requireParser$2(),A=requirePublicApi(),f=requireVisit();return dist$1.Composer=e.Composer,dist$1.Document=t.Document,dist$1.Schema=r.Schema,dist$1.YAMLError=n.YAMLError,dist$1.YAMLParseError=n.YAMLParseError,dist$1.YAMLWarning=n.YAMLWarning,dist$1.Alias=i.Alias,dist$1.isAlias=s.isAlias,dist$1.isCollection=s.isCollection,dist$1.isDocument=s.isDocument,dist$1.isMap=s.isMap,dist$1.isNode=s.isNode,dist$1.isPair=s.isPair,dist$1.isScalar=s.isScalar,dist$1.isSeq=s.isSeq,dist$1.Pair=o.Pair,
1559
+ dist$1.Scalar=a.Scalar,dist$1.YAMLMap=c.YAMLMap,dist$1.YAMLSeq=u.YAMLSeq,dist$1.CST=l,dist$1.Lexer=d.Lexer,dist$1.LineCounter=p.LineCounter,dist$1.Parser=h.Parser,dist$1.parse=A.parse,dist$1.parseAllDocuments=A.parseAllDocuments,dist$1.parseDocument=A.parseDocument,dist$1.stringify=A.stringify,dist$1.visit=f.visit,dist$1.visitAsync=f.visitAsync,dist$1}var distExports=requireDist$1();class UnknownToolError extends Error{constructor(e){super(`Unknown tool: '${e}'`),this.toolName=e}}const easyModelAliases={"o3-mini-2025-01-31":"openai-maybe-stream","o4-mini-2025-04-16":"openai-maybe-stream","gpt-4o-2024-08-06":"openai-maybe-stream","gpt-4.1-2025-04-14":"openai-maybe-stream","claude-3-7-sonnet-20250219":"anthropic","claude-sonnet-4-20250514":"anthropic","claude-opus-4-20250514":"anthropic","us.anthropic.claude-sonnet-4-20250514-v1:0":"bedrock","us.anthropic.claude-opus-4-20250514-v1:0":"bedrock","us.anthropic.claude-3-7-sonnet-20250219-v1:0":"bedrock",
1560
+ "accounts/fireworks/models/deepseek-r1":"deepseek","accounts/fireworks/models/llama-v3p1-405b-instruct":"llama","gemini-2.0-pro-exp-02-05":"google-no-stream"};function isEasyModelAlias(e){return e in easyModelAliases}const complicatedModelAliases={"gpt-4o":e=>{e.modelClient="openai",e.modelParams??={},e.modelParams.model="gpt-4o-2024-08-06"},"cerebras-llama-4-scout-17b-16e-instruct":e=>{e.modelClient="cerebras",e.modelParams??={temperature:.6},e.modelParams.model="llama-4-scout-17b-16e-instruct"}};function isComplicatedModelAlias(e){return e in complicatedModelAliases}var toml={},parse$4={exports:{}},tomlParser={exports:{}
1561
1561
  },parser,hasRequiredParser$1,createDatetime,hasRequiredCreateDatetime,formatNum,hasRequiredFormatNum,createDatetimeFloat,hasRequiredCreateDatetimeFloat,createDate,hasRequiredCreateDate,createTime,hasRequiredCreateTime,hasRequiredTomlParser,parsePrettyError,hasRequiredParsePrettyError,parseString_1,hasRequiredParseString,parseAsync_1,hasRequiredParseAsync,parseStream_1,hasRequiredParseStream,hasRequiredParse$5;function requireParser$1(){if(hasRequiredParser$1)return parser;hasRequiredParser$1=1;const e=1114112;class t extends Error{constructor(e,r,n){super("[ParserError] "+e,r,n),this.name="ParserError",this.code="ParserError",Error.captureStackTrace&&Error.captureStackTrace(this,t)}}class r{constructor(e){this.parser=e,this.buf="",this.returned=null,this.result=null,this.resultTable=null,this.resultArr=null}}class n{constructor(){this.pos=0,this.col=0,this.line=0,this.obj={},this.ctx=this.obj,this.stack=[],this._buf="",this.char=null,this.ii=0,this.state=new r(this.parseStart)}
1562
1562
  parse(e){if(0===e.length||null==e.length)return;let t;for(this._buf=String(e),this.ii=-1,this.char=-1;!1===t||this.nextChar();)t=this.runOne();this._buf=null}nextChar(){return 10===this.char&&(++this.line,this.col=-1),++this.ii,this.char=this._buf.codePointAt(this.ii),++this.pos,++this.col,this.haveBuffer()}haveBuffer(){return this.ii<this._buf.length}runOne(){return this.state.parser.call(this,this.state.returned)}finish(){let t;this.char=e;do{t=this.state.parser,this.runOne()}while(this.state.parser!==t);return this.ctx=null,this.state=null,this._buf=null,this.obj}next(e){if("function"!=typeof e)throw new t("Tried to set state to non-existent state: "+JSON.stringify(e));this.state.parser=e}goto(e){return this.next(e),this.runOne()}call(e,t){t&&this.next(t),this.stack.push(this.state),this.state=new r(e)}callNow(e,t){return this.call(e,t),this.runOne()}return(e){if(0===this.stack.length)throw this.error(new t("Stack underflow"));void 0===e&&(e=this.state.buf),
1563
1563
  this.state=this.stack.pop(),this.state.returned=e}returnNow(e){return this.return(e),this.runOne()}consume(){if(this.char===e)throw this.error(new t("Unexpected end-of-buffer"));this.state.buf+=this._buf[this.ii]}error(e){return e.line=this.line,e.col=this.col,e.pos=this.pos,e}parseStart(){throw new t("Must declare a parseStart method")}}return n.END=e,n.Error=t,parser=n}function requireCreateDatetime(){return hasRequiredCreateDatetime||(hasRequiredCreateDatetime=1,createDatetime=e=>{const t=new Date(e);if(isNaN(t))throw new TypeError("Invalid Datetime");return t}),createDatetime}function requireFormatNum(){return hasRequiredFormatNum?formatNum:(hasRequiredFormatNum=1,formatNum=(e,t)=>{for(t=String(t);t.length<e;)t="0"+t;return t})}function requireCreateDatetimeFloat(){if(hasRequiredCreateDatetimeFloat)return createDatetimeFloat;hasRequiredCreateDatetimeFloat=1;const e=requireFormatNum();class t extends Date{constructor(e){super(e+"Z"),this.isFloating=!0}toISOString(){
@@ -1748,7 +1748,7 @@ return!(!e||"object"!=typeof e)&&(isShouldRetryFlag(e)?structuredClone(e[SCRIPT_
1748
1748
  ;e.startsWith("```json")&&e.endsWith("```")&&(i=e.substring(7,e.length-3).trim())}try{n=JSON.parse(i)}catch(e){throw allowRetries(new AggregateError([e],"asObject: error parsing json: "+i),{withDelay:!1})}try{return[e.parse(n),i]}catch(e){throw allowRetries(new AggregateError([e],"asObject: error validating json: "+JSON.stringify(n)),{withDelay:!1})}}async function sleepInterruptable(e,t){return new Promise((r,n)=>{const i=setTimeout$1(()=>{o(),r()},e);function s(){clearTimeout(i),o(),n(new Error("aborted during nap"))}function o(){t.removeEventListener("abort",s)}t.addEventListener("abort",s),t.aborted&&s()})}async function sleepUntil(e,t){const r=Date.now();if(e<=r)return;const n=e-r;await sleepInterruptable(n,t)}function _optionalChain$R(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}
1749
1749
  return r}async function streamFakeTypingEvents(e,t,r,n=Date.now(),i="yes"===process.env.SLOWMO){for(const[s,o]of t)i&&await sleepUntil(n+1e3*s,r),await _optionalChain$R([e,"optionalAccess",e=>e.chunk,"call",e=>e(o)]),throwWhenAborted(r)}function capturingTyper(e,t){const r=clock$2(),n=[];return{events:n,async start(){throwWhenAborted(e),await _optionalChain$R([t,"optionalAccess",e=>e.start,"call",e=>e()])},async chunk(i){throwWhenAborted(e),n.push([Number(clock$2()-r)/1e9,i]),await _optionalChain$R([t,"optionalAccess",e=>e.chunk,"call",e=>e(i)])},async countTokens(r){throwWhenAborted(e),await _optionalChain$R([t,"optionalAccess",e=>e.countTokens,"call",e=>e(r)])},async done(){throwWhenAborted(e),await _optionalChain$R([t,"optionalAccess",e=>e.done,"call",e=>e()])}}}function _nullishCoalesce$K(e,t){return null!=e?e:t()}function _optionalChain$Q(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return
1750
1750
  ;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}class LLMCacheMissError extends Error{constructor(e){super(`Expected an LLM cache hit but no matching entry was found for key ${e}`)}}function serializeInput(e,t){const{indent:r}=_nullishCoalesce$K(t,()=>({})),{args:n,...i}=e;return JSON.stringify({args:sortKeys(n,{deep:!0}),...i},void 0,r)}function cacheKey(e){const t=serializeInput(e);return base32.encode(createHash$1("sha512-256").update(t).digest()).replace(/=/g,"").toLowerCase()}function cacheWrapper(e,t,r){return{cacheKey:e.cacheKey,async streamFromMessages(n,i){const s=_optionalChain$Q([i,"optionalAccess",e=>e.respondObject,"optionalAccess",e=>e.schema]);return chatStreamBuilder(s,async o=>{let a=!1;const{string:c,events:u}=await r({method:"streamFromMessages",args:{messages:n},modelInfo:e.cacheKey,retryIdx:_optionalChain$Q([i,"optionalAccess",e=>e.retryIdx])},async()=>{a=!0
1751
- ;const r=capturingTyper(t,o),c=await e.streamFromMessages(n,i),u=await c.asString(r);return s&&await asObject(s,()=>u),{string:u,events:JSON.stringify(r.events)}});return a||await streamFakeTypingEvents(o,JSON.parse(u),t),c})}}}async function considerFsCaching(){if(!process.env.LLM_CACHE_DIR)return;const e=resolve$2(process.env.LLM_CACHE_DIR);return await fsp.mkdir(e,{recursive:!0}),e}async function fsCache(e,t,r){const n=cacheKey(t),i=resolve$2(e,`${n}.toml`),s=await readTextIfExists(i);if(s){return tomlExports.parse(s).output}if("mock"===process.env.LLM_MODE){const r=serializeInput(t,{indent:2});throw await writeText(resolve$2(e,`${n}.input.json`),r),new LLMCacheMissError(n)}if("record"===process.env.LLM_MODE||"real"===process.env.LLM_MODE){const e=process.env.TESSL_LLM_API_KEY;if("dummy-key-replace-me"===e||"a"===e)throw new Error("LLM key is set to dummy value. Please read the integration test documentation and set TESSL_LLM_API_KEY to a real key when recording LLM snapshots.")}
1751
+ ;const r=capturingTyper(t,o),c=await e.streamFromMessages(n,i),u=await c.asString(r);return s&&await asObject(s,()=>u),{string:u,events:JSON.stringify(r.events)}});return a||await streamFakeTypingEvents(o,JSON.parse(u),t),c})}}}async function considerFsCaching(){if(!process.env.LLM_CACHE_DIR)return;const e=resolve$2(process.env.LLM_CACHE_DIR);return await fsp.mkdir(e,{recursive:!0}),e}async function fsCache(e,t,r){const n=cacheKey(t),i=resolve$2(e,`${n}.toml`),s=await readTextIfExists(i);if(s){return tomlExports.parse(s).output}if("mock"===process.env.LLM_MODE){const r=serializeInput(t,{indent:2});throw await writeText(resolve$2(e,`${n}.input.json`),r),new LLMCacheMissError(n)}if("record"===process.env.LLM_MODE||"real"===process.env.LLM_MODE){const e=process.env.TESSL_LLM_API_KEY;if("dummy-key-replace-me"===e||"a"===e)throw new Error("LLM key is set to dummy value. Please read the e2e test documentation and set TESSL_LLM_API_KEY to a real key when recording LLM snapshots.")}
1752
1752
  const o=await r(),a={input:t,output:o};return await writeText(i,tomlExports.stringify(a)),o}async function redisCache(e,t,r){const n="cache:1:"+cacheKey(t);_optionalChain$Q([trace$1,"access",e=>e.getActiveSpan,"call",e=>e(),"optionalAccess",e=>e.setAttribute,"call",e=>e("cache.key",n)]);const i=await e.get(n);if(i)return _optionalChain$Q([trace$1,"access",e=>e.getActiveSpan,"call",e=>e(),"optionalAccess",e=>e.setAttribute,"call",e=>e("cache.hit",!0)]),JSON.parse(i);_optionalChain$Q([trace$1,"access",e=>e.getActiveSpan,"call",e=>e(),"optionalAccess",e=>e.setAttribute,"call",e=>e("cache.hit",!1)]);const s=await r();return await e.set(n,JSON.stringify(s),"EX",2764800),s}function __classPrivateFieldSet(e,t,r,n,i){if("function"==typeof t||!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,r),r}function __classPrivateFieldGet(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter")
1753
1753
  ;if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)}let uuid4=function(){const{crypto:e}=globalThis;if(e?.randomUUID)return uuid4=e.randomUUID.bind(e),e.randomUUID();const t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>255*Math.random()&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(+e^r()&15>>+e/4).toString(16))};function isAbortError$1(e){return"object"==typeof e&&null!==e&&("name"in e&&"AbortError"===e.name||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}const castToError=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e){try{if("[object Error]"===Object.prototype.toString.call(e)){const t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{
1754
1754
  return new Error(JSON.stringify(e))}catch{}}return new Error(e)};class AnthropicError extends Error{}class APIError extends AnthropicError{constructor(e,t,r,n){super(`${APIError.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.requestID=n?.get("request-id"),this.error=t}static makeMessage(e,t,r){const n=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e||!n)return new APIConnectionError({message:r,cause:castToError(t)});const i=t;return 400===e?new BadRequestError(e,i,r,n):401===e?new AuthenticationError(e,i,r,n):403===e?new PermissionDeniedError(e,i,r,n):404===e?new NotFoundError$1(e,i,r,n):409===e?new ConflictError(e,i,r,n):422===e?new UnprocessableEntityError(e,i,r,n):429===e?new RateLimitError(e,i,r,n):e>=500?new InternalServerError(e,i,r,n):new APIError(e,i,r,n)}}class APIUserAbortError extends APIError{
@@ -1828,8 +1828,8 @@ const i=e?"error; no more retries left":"error; not retryable";loggerFor(this).i
1828
1828
  calculateNonstreamingTimeout(e,t){const r=6e5;if(36e5*e/128e3>r||null!=t&&e>t)throw new AnthropicError("Streaming is strongly recommended for operations that may token longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return r}buildRequest(e,{retryCount:t=0}={}){const r={...e},{method:n,path:i,query:s,defaultBaseURL:o}=r,a=this.buildURL(i,s,o);"timeout"in r&&validatePositiveInteger("timeout",r.timeout),r.timeout=r.timeout??this.timeout;const{bodyHeaders:c,body:u}=this.buildBody({options:r});return{req:{method:n,headers:this.buildHeaders({options:e,method:n,bodyHeaders:c,retryCount:t}),...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...r.fetchOptions??{}},url:a,timeout:r.timeout}}buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:n}){let i={}
1829
1829
  ;this.idempotencyHeader&&"get"!==t&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);const s=buildHeaders([i,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...getPlatformHeaders(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(s),s.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const r=buildHeaders([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||"string"==typeof e&&r.values.has("content-type")||e instanceof Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{
1830
1830
  bodyHeaders:void 0,body:e}:"object"==typeof e&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&"function"==typeof e.next)?{bodyHeaders:void 0,body:ReadableStreamFrom(e)}:__classPrivateFieldGet(this,_BaseAnthropic_encoder,"f").call(this,{body:e,headers:r})}}_a=BaseAnthropic,_BaseAnthropic_encoder=new WeakMap,_BaseAnthropic_instances=new WeakSet,_BaseAnthropic_baseURLOverridden=function(){return"https://api.anthropic.com"!==this.baseURL},BaseAnthropic.Anthropic=_a,BaseAnthropic.HUMAN_PROMPT="\n\nHuman:",BaseAnthropic.AI_PROMPT="\n\nAssistant:",BaseAnthropic.DEFAULT_TIMEOUT=6e5,BaseAnthropic.AnthropicError=AnthropicError,BaseAnthropic.APIError=APIError,BaseAnthropic.APIConnectionError=APIConnectionError,BaseAnthropic.APIConnectionTimeoutError=APIConnectionTimeoutError,BaseAnthropic.APIUserAbortError=APIUserAbortError,BaseAnthropic.NotFoundError=NotFoundError$1,BaseAnthropic.ConflictError=ConflictError,BaseAnthropic.RateLimitError=RateLimitError,
1831
- BaseAnthropic.BadRequestError=BadRequestError,BaseAnthropic.AuthenticationError=AuthenticationError,BaseAnthropic.InternalServerError=InternalServerError,BaseAnthropic.PermissionDeniedError=PermissionDeniedError,BaseAnthropic.UnprocessableEntityError=UnprocessableEntityError,BaseAnthropic.toFile=toFile;class Anthropic extends BaseAnthropic{constructor(){super(...arguments),this.completions=new Completions(this),this.messages=new Messages(this),this.models=new Models(this),this.beta=new Beta(this)}}Anthropic.Completions=Completions,Anthropic.Messages=Messages,Anthropic.Models=Models,Anthropic.Beta=Beta;const{HUMAN_PROMPT,AI_PROMPT}=Anthropic,ignoreOverride$1=Symbol("Let zodToJsonSchema decide on which parser to use"),defaultOptions$1={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,
1832
- definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},getDefaultOptions$1=e=>"string"==typeof e?{...defaultOptions$1,name:e}:{...defaultOptions$1,...e},getRefs$1=e=>{const t=getDefaultOptions$1(e),r=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,r])=>[r._def,{def:r._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function addErrorMessage$1(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function setResponseValueAndErrors$1(e,t,r,n,i){e[t]=r,addErrorMessage$1(e,t,n,i)}const getRelativePath$1=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);
1831
+ BaseAnthropic.BadRequestError=BadRequestError,BaseAnthropic.AuthenticationError=AuthenticationError,BaseAnthropic.InternalServerError=InternalServerError,BaseAnthropic.PermissionDeniedError=PermissionDeniedError,BaseAnthropic.UnprocessableEntityError=UnprocessableEntityError,BaseAnthropic.toFile=toFile;class Anthropic extends BaseAnthropic{constructor(){super(...arguments),this.completions=new Completions(this),this.messages=new Messages(this),this.models=new Models(this),this.beta=new Beta(this)}}Anthropic.Completions=Completions,Anthropic.Messages=Messages,Anthropic.Models=Models,Anthropic.Beta=Beta;const{HUMAN_PROMPT,AI_PROMPT}=Anthropic,ignoreOverride$1=Symbol("Let zodToJsonSchema decide on which parser to use"),defaultOptions$3={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,
1832
+ definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},getDefaultOptions$1=e=>"string"==typeof e?{...defaultOptions$3,name:e}:{...defaultOptions$3,...e},getRefs$1=e=>{const t=getDefaultOptions$1(e),r=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,r])=>[r._def,{def:r._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function addErrorMessage$1(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function setResponseValueAndErrors$1(e,t,r,n,i){e[t]=r,addErrorMessage$1(e,t,n,i)}const getRelativePath$1=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);
1833
1833
  return[(e.length-r).toString(),...t.slice(r)].join("/")};function parseAnyDef$1(e){if("openAi"!==e.target)return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===e.$refStrategy?getRelativePath$1(t,e.currentPath):t.join("/")}}function parseArrayDef$1(e,t){const r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==ZodFirstPartyTypeKind$1.ZodAny&&(r.items=parseDef$1(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&setResponseValueAndErrors$1(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&setResponseValueAndErrors$1(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(setResponseValueAndErrors$1(r,"minItems",e.exactLength.value,e.exactLength.message,t),setResponseValueAndErrors$1(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}function parseBigintDef$1(e,t){const r={type:"integer",format:"int64"};if(!e.checks)return r
1834
1834
  ;for(const n of e.checks)switch(n.kind){case"min":"jsonSchema7"===t.target?n.inclusive?setResponseValueAndErrors$1(r,"minimum",n.value,n.message,t):setResponseValueAndErrors$1(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),setResponseValueAndErrors$1(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?n.inclusive?setResponseValueAndErrors$1(r,"maximum",n.value,n.message,t):setResponseValueAndErrors$1(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),setResponseValueAndErrors$1(r,"maximum",n.value,n.message,t));break;case"multipleOf":setResponseValueAndErrors$1(r,"multipleOf",n.value,n.message,t)}return r}function parseBooleanDef$1(){return{type:"boolean"}}function parseBrandedDef$1(e,t){return parseDef$1(e.type._def,t)}const parseCatchDef$1=(e,t)=>parseDef$1(e.innerType._def,t);function parseDateDef$1(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((r,n)=>parseDateDef$1(e,t,r))
1835
1835
  };switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return integerDateParser$1(e,t)}}const integerDateParser$1=(e,t)=>{const r={type:"integer",format:"unix-time"};if("openApi3"===t.target)return r;for(const n of e.checks)switch(n.kind){case"min":setResponseValueAndErrors$1(r,"minimum",n.value,n.message,t);break;case"max":setResponseValueAndErrors$1(r,"maximum",n.value,n.message,t)}return r};function parseDefaultDef$1(e,t){return{...parseDef$1(e.innerType._def,t),default:e.defaultValue()}}function parseEffectsDef$1(e,t){return"input"===t.effectStrategy?parseDef$1(e.schema._def,t):parseAnyDef$1(t)}function parseEnumDef$1(e){return{type:"string",enum:Array.from(e.values)}}const isJsonSchema7AllOfType$1=e=>(!("type"in e)||"string"!==e.type)&&"allOf"in e;function parseIntersectionDef$1(e,t){const r=[parseDef$1(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]
@@ -1854,57 +1854,52 @@ const parseReadonlyDef$1=(e,t)=>parseDef$1(e.innerType._def,t),selectParser$1=(e
1854
1854
  ;case ZodFirstPartyTypeKind$1.ZodDefault:return parseDefaultDef$1(e,r);case ZodFirstPartyTypeKind$1.ZodBranded:return parseBrandedDef$1(e,r);case ZodFirstPartyTypeKind$1.ZodReadonly:return parseReadonlyDef$1(e,r);case ZodFirstPartyTypeKind$1.ZodCatch:return parseCatchDef$1(e,r);case ZodFirstPartyTypeKind$1.ZodPipeline:return parsePipelineDef$1(e,r);case ZodFirstPartyTypeKind$1.ZodFunction:case ZodFirstPartyTypeKind$1.ZodVoid:case ZodFirstPartyTypeKind$1.ZodSymbol:default:return}};function parseDef$1(e,t,r=!1){const n=t.seen.get(e);if(t.override){const i=t.override?.(e,t,n,r);if(i!==ignoreOverride$1)return i}if(n&&!r){const e=get$ref$1(n,t);if(void 0!==e)return e}const i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);const s=selectParser$1(e,e.typeName,t),o="function"==typeof s?parseDef$1(s(),t):s;if(o&&addMeta$1(e,t,o),t.postProcess){const r=t.postProcess(o,e,t);return i.jsonSchema=o,r}return i.jsonSchema=o,o}const get$ref$1=(e,t)=>{switch(t.$refStrategy){case"root":
1855
1855
  return{$ref:e.path.join("/")};case"relative":return{$ref:getRelativePath$1(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((e,r)=>t.currentPath[r]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),parseAnyDef$1(t)):"seen"===t.$refStrategy?parseAnyDef$1(t):void 0}},addMeta$1=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),zodToJsonSchema$2=(e,t)=>{const r=getRefs$1(t);let n="object"==typeof t&&t.definitions?Object.entries(t.definitions).reduce((e,[t,n])=>({...e,[t]:parseDef$1(n._def,{...r,currentPath:[...r.basePath,r.definitionPath,t]},!0)??parseAnyDef$1(r)}),{}):void 0;const i="string"==typeof t?t:"title"===t?.nameStrategy?void 0:t?.name,s=parseDef$1(e._def,void 0===i?r:{...r,currentPath:[...r.basePath,r.definitionPath,i]
1856
1856
  },!1)??parseAnyDef$1(r),o="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==o&&(s.title=o),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:"relative"===r.$refStrategy?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const a=void 0===i?n?{...s,[r.definitionPath]:n}:s:{$ref:[..."relative"===r.$refStrategy?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...n,[i]:s}};return"jsonSchema7"===r.target?a.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"!==r.target&&"openAi"!==r.target||(a.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===r.target&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};var index$1=Object.freeze({
1857
- __proto__:null,addErrorMessage:addErrorMessage$1,defaultOptions:defaultOptions$1,getDefaultOptions:getDefaultOptions$1,getRefs:getRefs$1,getRelativePath:getRelativePath$1,ignoreOverride:ignoreOverride$1,parseAnyDef:parseAnyDef$1,parseArrayDef:parseArrayDef$1,parseBigintDef:parseBigintDef$1,parseBooleanDef:parseBooleanDef$1,parseBrandedDef:parseBrandedDef$1,parseCatchDef:parseCatchDef$1,parseDateDef:parseDateDef$1,parseDef:parseDef$1,parseDefaultDef:parseDefaultDef$1,parseEffectsDef:parseEffectsDef$1,parseEnumDef:parseEnumDef$1,parseIntersectionDef:parseIntersectionDef$1,parseLiteralDef:parseLiteralDef$1,parseMapDef:parseMapDef$1,parseNativeEnumDef:parseNativeEnumDef$1,parseNeverDef:parseNeverDef$1,parseNullDef:parseNullDef$1,parseNullableDef:parseNullableDef$1,parseNumberDef:parseNumberDef$1,parseObjectDef:parseObjectDef$1,parseOptionalDef:parseOptionalDef$1,parsePipelineDef:parsePipelineDef$1,parsePromiseDef:parsePromiseDef$1,parseReadonlyDef:parseReadonlyDef$1,
1857
+ __proto__:null,addErrorMessage:addErrorMessage$1,defaultOptions:defaultOptions$3,getDefaultOptions:getDefaultOptions$1,getRefs:getRefs$1,getRelativePath:getRelativePath$1,ignoreOverride:ignoreOverride$1,parseAnyDef:parseAnyDef$1,parseArrayDef:parseArrayDef$1,parseBigintDef:parseBigintDef$1,parseBooleanDef:parseBooleanDef$1,parseBrandedDef:parseBrandedDef$1,parseCatchDef:parseCatchDef$1,parseDateDef:parseDateDef$1,parseDef:parseDef$1,parseDefaultDef:parseDefaultDef$1,parseEffectsDef:parseEffectsDef$1,parseEnumDef:parseEnumDef$1,parseIntersectionDef:parseIntersectionDef$1,parseLiteralDef:parseLiteralDef$1,parseMapDef:parseMapDef$1,parseNativeEnumDef:parseNativeEnumDef$1,parseNeverDef:parseNeverDef$1,parseNullDef:parseNullDef$1,parseNullableDef:parseNullableDef$1,parseNumberDef:parseNumberDef$1,parseObjectDef:parseObjectDef$1,parseOptionalDef:parseOptionalDef$1,parsePipelineDef:parsePipelineDef$1,parsePromiseDef:parsePromiseDef$1,parseReadonlyDef:parseReadonlyDef$1,
1858
1858
  parseRecordDef:parseRecordDef$1,parseSetDef:parseSetDef$1,parseStringDef:parseStringDef$1,parseTupleDef:parseTupleDef$1,parseUndefinedDef:parseUndefinedDef$1,parseUnionDef:parseUnionDef$1,parseUnknownDef:parseUnknownDef$1,primitiveMappings:primitiveMappings$1,selectParser:selectParser$1,setResponseValueAndErrors:setResponseValueAndErrors$1,zodPatterns:zodPatterns$1,zodToJsonSchema:zodToJsonSchema$2});function _optionalChain$P(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function removeThinking(e){const t=/(?<=<\/think>)([\s\S]*)/;return _optionalChain$P([e,"optionalAccess",e=>e.match,"call",e=>e(t),"optionalAccess",e=>e[0]])||""}function injectMinificationToMessages(e){
1859
1859
  return"system"===_optionalChain$P([e,"access",e=>e[0],"optionalAccess",e=>e.role])&&(e[0].content=e[0].content+"\nEmit a minified JSON in your response, no whitespace, newlines or tabs."),e}function translateMessagesToArray(e){let t;const r=[],n=[],i=()=>{r.length&&(n.push({role:t,content:r.map(e=>({text:e,type:"text"}))}),r.length=0)};for(const n of e){const e="system"===n.role?"user":n.role;t!==e&&(i(),t=e),r.push(n.content)}return i(),n}function appendSchema(e,t){const r=zodToJsonSchema$2(t);delete r.$schema,delete r.additionalProperties,e[e.length-1].content.push({text:"Return a JSON object matching this exact schema. Your response will be serialized as JSON, so make sure all newlines are properly escaped. Do not include any other text or commentary: "+JSON.stringify(r),type:"text"})}function nonStreamedAsString(e){return async t=>(await _optionalChain$P([t,"optionalAccess",e=>e.start,"call",e=>e()]),await _optionalChain$P([t,"optionalAccess",e=>e.chunk,"call",t=>t(e)]),
1860
1860
  await _optionalChain$P([t,"optionalAccess",e=>e.done,"call",e=>e()]),e)}function _nullishCoalesce$J(e,t){return null!=e?e:t()}function _optionalChain$O(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function handleConfig$2(e){return{max_tokens:4096,temperature:_nullishCoalesce$J(e.modelTemperature,()=>1),model:e.modelName,...e.modelParams}}function anthropicImpl(e,t){const r=new Anthropic({}),n=handleConfig$2(t);return{cacheKey:[n.model,String(n.temperature)],streamFromMessages:async(e,t)=>withSpan("anthropicClient.streamFromMessages",async i=>{const s=translateMessagesToArray(structuredClone(e)),o=_optionalChain$O([t,"optionalAccess",e=>e.respondObject,"optionalAccess",e=>e.schema]);o&&appendSchema(s,o);const a={...n};delete a.model
1861
- ;const c=_optionalChain$O([t,"optionalAccess",e=>e.traceInfo,"optionalAccess",e=>e.parent,"optionalAccess",e=>e.generation,"call",e=>e({name:_optionalChain$O([t,"optionalAccess",e=>e.traceInfo,"optionalAccess",e=>e.generationName]),model:n.model,modelParameters:a,input:s})]),u={};propagation.inject(context.active(),u);const l=await r.messages.create({messages:s,...n},{headers:u});return _optionalChain$O([c,"optionalAccess",e=>e.end,"call",e=>e({output:l.content,usage:{input:_optionalChain$O([l,"access",e=>e.usage,"optionalAccess",e=>e.input_tokens]),output:_optionalChain$O([l,"access",e=>e.usage,"optionalAccess",e=>e.output_tokens])}})]),chatStreamBuilder(_optionalChain$O([t,"optionalAccess",e=>e.respondObject,"optionalAccess",e=>e.schema]),nonStreamedAsString(_optionalChain$O([l,"access",e=>e.content,"access",e=>e.map,"call",e=>e(e=>"text"===e.type?e.text:""),"optionalAccess",e=>e.join,"call",e=>e("\n")])))})}}var validator$1={},util$a={},hasRequiredUtil$9,hasRequiredValidator$1
1862
- ;function requireUtil$9(){return hasRequiredUtil$9||(hasRequiredUtil$9=1,function(e){const t=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",r="["+t+"]["+(t+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040")+"]*",n=new RegExp("^"+r+"$");e.isExist=function(e){return void 0!==e},e.isEmptyObject=function(e){return 0===Object.keys(e).length},e.merge=function(e,t,r){if(t){const n=Object.keys(t),i=n.length;for(let s=0;s<i;s++)e[n[s]]="strict"===r?[t[n[s]]]:t[n[s]]}},e.getValue=function(t){return e.isExist(t)?t:""},e.isName=function(e){const t=n.exec(e);return!(null==t)},e.getAllMatches=function(e,t){const r=[];let n=t.exec(e);for(;n;){const i=[];i.startIndex=t.lastIndex-n[0].length;const s=n.length;for(let e=0;e<s;e++)i.push(n[e]);r.push(i),n=t.exec(e)}return r},e.nameRegexp=r}(util$a)),util$a}function requireValidator$1(){if(hasRequiredValidator$1)return validator$1
1863
- ;hasRequiredValidator$1=1;const e=requireUtil$9(),t={allowBooleanAttributes:!1,unpairedTags:[]};function r(e){return" "===e||"\t"===e||"\n"===e||"\r"===e}function n(e,t){const r=t;for(;t<e.length;t++)if("?"==e[t]||" "==e[t]){const n=e.substr(r,t-r);if(t>5&&"xml"===n)return d("InvalidXml","XML declaration allowed only at the start of the document.",A(e,t));if("?"==e[t]&&">"==e[t+1]){t++;break}continue}return t}function i(e,t){if(e.length>t+5&&"-"===e[t+1]&&"-"===e[t+2]){for(t+=3;t<e.length;t++)if("-"===e[t]&&"-"===e[t+1]&&">"===e[t+2]){t+=2;break}}else if(e.length>t+8&&"D"===e[t+1]&&"O"===e[t+2]&&"C"===e[t+3]&&"T"===e[t+4]&&"Y"===e[t+5]&&"P"===e[t+6]&&"E"===e[t+7]){let r=1;for(t+=8;t<e.length;t++)if("<"===e[t])r++;else if(">"===e[t]&&(r--,0===r))break}else if(e.length>t+9&&"["===e[t+1]&&"C"===e[t+2]&&"D"===e[t+3]&&"A"===e[t+4]&&"T"===e[t+5]&&"A"===e[t+6]&&"["===e[t+7])for(t+=8;t<e.length;t++)if("]"===e[t]&&"]"===e[t+1]&&">"===e[t+2]){t+=2;break}return t}
1864
- validator$1.validate=function(e,s){s=Object.assign({},t,s);const o=[];let c=!1,p=!1;"\ufeff"===e[0]&&(e=e.substr(1));for(let t=0;t<e.length;t++)if("<"===e[t]&&"?"===e[t+1]){if(t+=2,t=n(e,t),t.err)return t}else{if("<"!==e[t]){if(r(e[t]))continue;return d("InvalidChar","char '"+e[t]+"' is not expected.",A(e,t))}{let f=t;if(t++,"!"===e[t]){t=i(e,t);continue}{let g=!1;"/"===e[t]&&(g=!0,t++);let m="";for(;t<e.length&&">"!==e[t]&&" "!==e[t]&&"\t"!==e[t]&&"\n"!==e[t]&&"\r"!==e[t];t++)m+=e[t];if(m=m.trim(),"/"===m[m.length-1]&&(m=m.substring(0,m.length-1),t--),!h(m)){let r;return r=0===m.trim().length?"Invalid space after '<'.":"Tag '"+m+"' is an invalid name.",d("InvalidTag",r,A(e,t))}const y=a(e,t);if(!1===y)return d("InvalidAttr","Attributes for '"+m+"' have open quote.",A(e,t));let E=y.value;if(t=y.index,"/"===E[E.length-1]){const r=t-E.length;E=E.substring(0,E.length-1);const n=u(E,s);if(!0!==n)return d(n.err.code,n.err.msg,A(e,r+n.err.line));c=!0}else if(g){
1865
- if(!y.tagClosed)return d("InvalidTag","Closing tag '"+m+"' doesn't have proper closing.",A(e,t));if(E.trim().length>0)return d("InvalidTag","Closing tag '"+m+"' can't have attributes or invalid starting.",A(e,f));if(0===o.length)return d("InvalidTag","Closing tag '"+m+"' has not been opened.",A(e,f));{const t=o.pop();if(m!==t.tagName){let r=A(e,t.tagStartPos);return d("InvalidTag","Expected closing tag '"+t.tagName+"' (opened in line "+r.line+", col "+r.col+") instead of closing tag '"+m+"'.",A(e,f))}0==o.length&&(p=!0)}}else{const r=u(E,s);if(!0!==r)return d(r.err.code,r.err.msg,A(e,t-E.length+r.err.line));if(!0===p)return d("InvalidXml","Multiple possible root nodes found.",A(e,t));-1!==s.unpairedTags.indexOf(m)||o.push({tagName:m,tagStartPos:f}),c=!0}for(t++;t<e.length;t++)if("<"===e[t]){if("!"===e[t+1]){t++,t=i(e,t);continue}if("?"!==e[t+1])break;if(t=n(e,++t),t.err)return t}else if("&"===e[t]){const r=l(e,t);if(-1==r)return d("InvalidChar","char '&' is not expected.",A(e,t));t=r
1866
- }else if(!0===p&&!r(e[t]))return d("InvalidXml","Extra text at the end",A(e,t));"<"===e[t]&&t--}}}return c?1==o.length?d("InvalidTag","Unclosed tag '"+o[0].tagName+"'.",A(e,o[0].tagStartPos)):!(o.length>0)||d("InvalidXml","Invalid '"+JSON.stringify(o.map(e=>e.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):d("InvalidXml","Start tag expected.",1)};const s='"',o="'";function a(e,t){let r="",n="",i=!1;for(;t<e.length;t++){if(e[t]===s||e[t]===o)""===n?n=e[t]:n!==e[t]||(n="");else if(">"===e[t]&&""===n){i=!0;break}r+=e[t]}return""===n&&{value:r,index:t,tagClosed:i}}const c=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function u(t,r){const n=e.getAllMatches(t,c),i={};for(let e=0;e<n.length;e++){if(0===n[e][1].length)return d("InvalidAttr","Attribute '"+n[e][2]+"' has no space in starting.",f(n[e]));if(void 0!==n[e][3]&&void 0===n[e][4])return d("InvalidAttr","Attribute '"+n[e][2]+"' is without value.",f(n[e]))
1867
- ;if(void 0===n[e][3]&&!r.allowBooleanAttributes)return d("InvalidAttr","boolean attribute '"+n[e][2]+"' is not allowed.",f(n[e]));const t=n[e][2];if(!p(t))return d("InvalidAttr","Attribute '"+t+"' is an invalid name.",f(n[e]));if(i.hasOwnProperty(t))return d("InvalidAttr","Attribute '"+t+"' is repeated.",f(n[e]));i[t]=1}return!0}function l(e,t){if(";"===e[++t])return-1;if("#"===e[t])return function(e,t){let r=/\d/;for("x"===e[t]&&(t++,r=/[\da-fA-F]/);t<e.length;t++){if(";"===e[t])return t;if(!e[t].match(r))break}return-1}(e,++t);let r=0;for(;t<e.length;t++,r++)if(!(e[t].match(/\w/)&&r<20)){if(";"===e[t])break;return-1}return t}function d(e,t,r){return{err:{code:e,msg:t,line:r.line||r,col:r.col}}}function p(t){return e.isName(t)}function h(t){return e.isName(t)}function A(e,t){const r=e.substring(0,t).split(/\r?\n/);return{line:r.length,col:r[r.length-1].length+1}}function f(e){return e.startIndex+e[1].length}return validator$1}
1868
- var OptionsBuilder={},hasRequiredOptionsBuilder,xmlNode,hasRequiredXmlNode,DocTypeReader,hasRequiredDocTypeReader,strnum,hasRequiredStrnum,OrderedObjParser_1,hasRequiredOrderedObjParser;function requireOptionsBuilder(){if(hasRequiredOptionsBuilder)return OptionsBuilder;hasRequiredOptionsBuilder=1;const e={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(e,t,r){return e}};return OptionsBuilder.buildOptions=function(t){return Object.assign({},e,t)},
1869
- OptionsBuilder.defaultOptions=e,OptionsBuilder}function requireXmlNode(){if(hasRequiredXmlNode)return xmlNode;hasRequiredXmlNode=1;return xmlNode=class{constructor(e){this.tagname=e,this.child=[],this[":@"]={}}add(e,t){"__proto__"===e&&(e="#__proto__"),this.child.push({[e]:t})}addChild(e){"__proto__"===e.tagname&&(e.tagname="#__proto__"),e[":@"]&&Object.keys(e[":@"]).length>0?this.child.push({[e.tagname]:e.child,":@":e[":@"]}):this.child.push({[e.tagname]:e.child})}},xmlNode}function requireDocTypeReader(){if(hasRequiredDocTypeReader)return DocTypeReader;hasRequiredDocTypeReader=1;const e=requireUtil$9();function t(e,t){let r="";for(;t<e.length&&"'"!==e[t]&&'"'!==e[t];t++)r+=e[t];if(r=r.trim(),-1!==r.indexOf(" "))throw new Error("External entites are not supported");const n=e[t++];let i="";for(;t<e.length&&e[t]!==n;t++)i+=e[t];return[r,i,t]}function r(e,t){return"!"===e[t+1]&&"-"===e[t+2]&&"-"===e[t+3]}function n(e,t){
1870
- return"!"===e[t+1]&&"E"===e[t+2]&&"N"===e[t+3]&&"T"===e[t+4]&&"I"===e[t+5]&&"T"===e[t+6]&&"Y"===e[t+7]}function i(e,t){return"!"===e[t+1]&&"E"===e[t+2]&&"L"===e[t+3]&&"E"===e[t+4]&&"M"===e[t+5]&&"E"===e[t+6]&&"N"===e[t+7]&&"T"===e[t+8]}function s(e,t){return"!"===e[t+1]&&"A"===e[t+2]&&"T"===e[t+3]&&"T"===e[t+4]&&"L"===e[t+5]&&"I"===e[t+6]&&"S"===e[t+7]&&"T"===e[t+8]}function o(e,t){return"!"===e[t+1]&&"N"===e[t+2]&&"O"===e[t+3]&&"T"===e[t+4]&&"A"===e[t+5]&&"T"===e[t+6]&&"I"===e[t+7]&&"O"===e[t+8]&&"N"===e[t+9]}function a(t){if(e.isName(t))return t;throw new Error(`Invalid entity name ${t}`)}return DocTypeReader=function(e,c){const u={};if("O"!==e[c+3]||"C"!==e[c+4]||"T"!==e[c+5]||"Y"!==e[c+6]||"P"!==e[c+7]||"E"!==e[c+8])throw new Error("Invalid Tag instead of DOCTYPE");{c+=9;let l=1,d=!1,p=!1,h="";for(;c<e.length;c++)if("<"!==e[c]||p)if(">"===e[c]){if(p?"-"===e[c-1]&&"-"===e[c-2]&&(p=!1,l--):l--,0===l)break}else"["===e[c]?d=!0:h+=e[c];else{if(d&&n(e,c))c+=7,[entityName,val,c]=t(e,c+1),
1871
- -1===val.indexOf("&")&&(u[a(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(d&&i(e,c))c+=8;else if(d&&s(e,c))c+=8;else if(d&&o(e,c))c+=9;else{if(!r)throw new Error("Invalid DOCTYPE");p=!0}l++,h=""}if(0!==l)throw new Error("Unclosed DOCTYPE")}return{entities:u,i:c}},DocTypeReader}function requireStrnum(){if(hasRequiredStrnum)return strnum;hasRequiredStrnum=1;const e=/^[-+]?0x[a-fA-F0-9]+$/,t=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,r={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};return strnum=function(n,i={}){if(i=Object.assign({},r,i),!n||"string"!=typeof n)return n;let s=n.trim();if(void 0!==i.skipLike&&i.skipLike.test(s))return n;if("0"===n)return 0;if(i.hex&&e.test(s))return function(e,t){if(parseInt)return parseInt(e,t);if(Number.parseInt)return Number.parseInt(e,t);if(window&&window.parseInt)return window.parseInt(e,t);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}(s,16);if(-1!==s.search(/[eE]/)){
1872
- const e=s.match(/^([-\+])?(0*)([0-9]*(\.[0-9]*)?[eE][-\+]?[0-9]+)$/);if(e){if(i.leadingZeros)s=(e[1]||"")+e[3];else if("0"!==e[2]||"."!==e[3][0])return n;return i.eNotation?Number(s):n}return n}{const e=t.exec(s);if(e){const t=e[1],r=e[2];let o=function(e){if(e&&-1!==e.indexOf("."))return"."===(e=e.replace(/0+$/,""))?e="0":"."===e[0]?e="0"+e:"."===e[e.length-1]&&(e=e.substr(0,e.length-1)),e;return e}(e[3]);if(!i.leadingZeros&&r.length>0&&t&&"."!==s[2])return n;if(!i.leadingZeros&&r.length>0&&!t&&"."!==s[1])return n;if(i.leadingZeros&&r===n)return 0;{const e=Number(s),a=""+e;return-1!==a.search(/[eE]/)?i.eNotation?e:n:-1!==s.indexOf(".")?"0"===a&&""===o||a===o||t&&a==="-"+o?e:n:r?o===a||t+o===a?e:n:s===a||s===t+a?e:n}}return n}},strnum}function requireOrderedObjParser(){if(hasRequiredOrderedObjParser)return OrderedObjParser_1;hasRequiredOrderedObjParser=1;const e=requireUtil$9(),t=requireXmlNode(),r=requireDocTypeReader(),n=requireStrnum();function i(e){const t=Object.keys(e)
1873
- ;for(let r=0;r<t.length;r++){const n=t[r];this.lastEntities[n]={regex:new RegExp("&"+n+";","g"),val:e[n]}}}function s(e,t,r,n,i,s,o){if(void 0!==e&&(this.options.trimValues&&!n&&(e=e.trim()),e.length>0)){o||(e=this.replaceEntitiesValue(e));const n=this.options.tagValueProcessor(t,e,r,i,s);if(null==n)return e;if(typeof n!=typeof e||n!==e)return n;if(this.options.trimValues)return m(e,this.options.parseTagValue,this.options.numberParseOptions);return e.trim()===e?m(e,this.options.parseTagValue,this.options.numberParseOptions):e}}function o(e){if(this.options.removeNSPrefix){const t=e.split(":"),r="/"===e.charAt(0)?"/":"";if("xmlns"===t[0])return"";2===t.length&&(e=r+t[1])}return e}const a=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function c(t,r,n){if(!this.options.ignoreAttributes&&"string"==typeof t){const n=e.getAllMatches(t,a),i=n.length,s={};for(let e=0;e<i;e++){const t=this.resolveNameSpace(n[e][1]);let i=n[e][4],o=this.options.attributeNamePrefix+t
1874
- ;if(t.length)if(this.options.transformAttributeName&&(o=this.options.transformAttributeName(o)),"__proto__"===o&&(o="#__proto__"),void 0!==i){this.options.trimValues&&(i=i.trim()),i=this.replaceEntitiesValue(i);const e=this.options.attributeValueProcessor(t,i,r);s[o]=null==e?i:typeof e!=typeof i||e!==i?e:m(i,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(s[o]=!0)}if(!Object.keys(s).length)return;if(this.options.attributesGroupName){const e={};return e[this.options.attributesGroupName]=s,e}return s}}const u=function(e){e=e.replace(/\r\n?/g,"\n");const n=new t("!xml");let i=n,s="",o="";for(let a=0;a<e.length;a++){if("<"===e[a])if("/"===e[a+1]){const t=A(e,">",a,"Closing Tag is not closed.");let r=e.substring(a+2,t).trim();if(this.options.removeNSPrefix){const e=r.indexOf(":");-1!==e&&(r=r.substr(e+1))}this.options.transformTagName&&(r=this.options.transformTagName(r)),i&&(s=this.saveTextToParentTag(s,i,o))
1875
- ;const n=o.substring(o.lastIndexOf(".")+1);if(r&&-1!==this.options.unpairedTags.indexOf(r))throw new Error(`Unpaired tag can not be used as closing tag: </${r}>`);let c=0;n&&-1!==this.options.unpairedTags.indexOf(n)?(c=o.lastIndexOf(".",o.lastIndexOf(".")-1),this.tagsNodeStack.pop()):c=o.lastIndexOf("."),o=o.substring(0,c),i=this.tagsNodeStack.pop(),s="",a=t}else if("?"===e[a+1]){let r=f(e,a,!1,"?>");if(!r)throw new Error("Pi Tag is not closed.");if(s=this.saveTextToParentTag(s,i,o),this.options.ignoreDeclaration&&"?xml"===r.tagName||this.options.ignorePiTags);else{const e=new t(r.tagName);e.add(this.options.textNodeName,""),r.tagName!==r.tagExp&&r.attrExpPresent&&(e[":@"]=this.buildAttributesMap(r.tagExp,o,r.tagName)),this.addChild(i,e,o)}a=r.closeIndex+1}else if("!--"===e.substr(a+1,3)){const t=A(e,"--\x3e",a+4,"Comment is not closed.");if(this.options.commentPropName){const r=e.substring(a+4,t-2);s=this.saveTextToParentTag(s,i,o),i.add(this.options.commentPropName,[{
1876
- [this.options.textNodeName]:r}])}a=t}else if("!D"===e.substr(a+1,2)){const t=r(e,a);this.docTypeEntities=t.entities,a=t.i}else if("!["===e.substr(a+1,2)){const t=A(e,"]]>",a,"CDATA is not closed.")-2,r=e.substring(a+9,t);s=this.saveTextToParentTag(s,i,o);let n=this.parseTextData(r,i.tagname,o,!0,!1,!0,!0);null==n&&(n=""),this.options.cdataPropName?i.add(this.options.cdataPropName,[{[this.options.textNodeName]:r}]):i.add(this.options.textNodeName,n),a=t+2}else{let r=f(e,a,this.options.removeNSPrefix),c=r.tagName;const u=r.rawTagName;let l=r.tagExp,d=r.attrExpPresent,p=r.closeIndex;this.options.transformTagName&&(c=this.options.transformTagName(c)),i&&s&&"!xml"!==i.tagname&&(s=this.saveTextToParentTag(s,i,o,!1));const h=i;if(h&&-1!==this.options.unpairedTags.indexOf(h.tagname)&&(i=this.tagsNodeStack.pop(),o=o.substring(0,o.lastIndexOf("."))),c!==n.tagname&&(o+=o?"."+c:c),this.isItStopNode(this.options.stopNodes,o,c)){let n=""
1877
- ;if(l.length>0&&l.lastIndexOf("/")===l.length-1)"/"===c[c.length-1]?(c=c.substr(0,c.length-1),o=o.substr(0,o.length-1),l=c):l=l.substr(0,l.length-1),a=r.closeIndex;else if(-1!==this.options.unpairedTags.indexOf(c))a=r.closeIndex;else{const t=this.readStopNodeData(e,u,p+1);if(!t)throw new Error(`Unexpected end of ${u}`);a=t.i,n=t.tagContent}const s=new t(c);c!==l&&d&&(s[":@"]=this.buildAttributesMap(l,o,c)),n&&(n=this.parseTextData(n,c,o,!0,d,!0,!0)),o=o.substr(0,o.lastIndexOf(".")),s.add(this.options.textNodeName,n),this.addChild(i,s,o)}else{if(l.length>0&&l.lastIndexOf("/")===l.length-1){"/"===c[c.length-1]?(c=c.substr(0,c.length-1),o=o.substr(0,o.length-1),l=c):l=l.substr(0,l.length-1),this.options.transformTagName&&(c=this.options.transformTagName(c));const e=new t(c);c!==l&&d&&(e[":@"]=this.buildAttributesMap(l,o,c)),this.addChild(i,e,o),o=o.substr(0,o.lastIndexOf("."))}else{const e=new t(c);this.tagsNodeStack.push(i),c!==l&&d&&(e[":@"]=this.buildAttributesMap(l,o,c)),
1878
- this.addChild(i,e,o),i=e}s="",a=p}}else s+=e[a]}return n.child};function l(e,t,r){const n=this.options.updateTag(t.tagname,r,t[":@"]);!1===n||("string"==typeof n?(t.tagname=n,e.addChild(t)):e.addChild(t))}const d=function(e){if(this.options.processEntities){for(let t in this.docTypeEntities){const r=this.docTypeEntities[t];e=e.replace(r.regx,r.val)}for(let t in this.lastEntities){const r=this.lastEntities[t];e=e.replace(r.regex,r.val)}if(this.options.htmlEntities)for(let t in this.htmlEntities){const r=this.htmlEntities[t];e=e.replace(r.regex,r.val)}e=e.replace(this.ampEntity.regex,this.ampEntity.val)}return e};function p(e,t,r,n){return e&&(void 0===n&&(n=0===Object.keys(t.child).length),void 0!==(e=this.parseTextData(e,t.tagname,r,!1,!!t[":@"]&&0!==Object.keys(t[":@"]).length,n))&&""!==e&&t.add(this.options.textNodeName,e),e=""),e}function h(e,t,r){const n="*."+r;for(const r in e){const i=e[r];if(n===i||t===i)return!0}return!1}function A(e,t,r,n){const i=e.indexOf(t,r)
1879
- ;if(-1===i)throw new Error(n);return i+t.length-1}function f(e,t,r,n=">"){const i=function(e,t,r=">"){let n,i="";for(let s=t;s<e.length;s++){let t=e[s];if(n)t===n&&(n="");else if('"'===t||"'"===t)n=t;else if(t===r[0]){if(!r[1])return{data:i,index:s};if(e[s+1]===r[1])return{data:i,index:s}}else"\t"===t&&(t=" ");i+=t}}(e,t+1,n);if(!i)return;let s=i.data;const o=i.index,a=s.search(/\s/);let c=s,u=!0;-1!==a&&(c=s.substring(0,a),s=s.substring(a+1).trimStart());const l=c;if(r){const e=c.indexOf(":");-1!==e&&(c=c.substr(e+1),u=c!==i.data.substr(e+1))}return{tagName:c,tagExp:s,closeIndex:o,attrExpPresent:u,rawTagName:l}}function g(e,t,r){const n=r;let i=1;for(;r<e.length;r++)if("<"===e[r])if("/"===e[r+1]){const s=A(e,">",r,`${t} is not closed`);if(e.substring(r+2,s).trim()===t&&(i--,0===i))return{tagContent:e.substring(n,r),i:s};r=s}else if("?"===e[r+1]){r=A(e,"?>",r+1,"StopNode is not closed.")}else if("!--"===e.substr(r+1,3)){r=A(e,"--\x3e",r+3,"StopNode is not closed.")
1880
- }else if("!["===e.substr(r+1,2)){r=A(e,"]]>",r,"StopNode is not closed.")-2}else{const n=f(e,r,">");if(n){(n&&n.tagName)===t&&"/"!==n.tagExp[n.tagExp.length-1]&&i++,r=n.closeIndex}}}function m(t,r,i){if(r&&"string"==typeof t){const e=t.trim();return"true"===e||"false"!==e&&n(t,i)}return e.isExist(t)?t:""}return OrderedObjParser_1=class{constructor(e){this.options=e,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},
1881
- num_dec:{regex:/&#([0-9]{1,7});/g,val:(e,t)=>String.fromCharCode(Number.parseInt(t,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(e,t)=>String.fromCharCode(Number.parseInt(t,16))}},this.addExternalEntities=i,this.parseXml=u,this.parseTextData=s,this.resolveNameSpace=o,this.buildAttributesMap=c,this.isItStopNode=h,this.replaceEntitiesValue=d,this.readStopNodeData=g,this.saveTextToParentTag=p,this.addChild=l}},OrderedObjParser_1}var node2json={},hasRequiredNode2json,XMLParser_1,hasRequiredXMLParser,orderedJs2Xml,hasRequiredOrderedJs2Xml,json2xml,hasRequiredJson2xml,fxp,hasRequiredFxp;function requireNode2json(){if(hasRequiredNode2json)return node2json;function e(i,s,o){let a;const c={};for(let u=0;u<i.length;u++){const l=i[u],d=t(l);let p="";if(p=void 0===o?d:o+"."+d,d===s.textNodeName)void 0===a?a=l[d]:a+=""+l[d];else{if(void 0===d)continue;if(l[d]){let t=e(l[d],s,p);const i=n(t,s)
1882
- ;l[":@"]?r(t,l[":@"],p,s):1!==Object.keys(t).length||void 0===t[s.textNodeName]||s.alwaysCreateTextNode?0===Object.keys(t).length&&(s.alwaysCreateTextNode?t[s.textNodeName]="":t=""):t=t[s.textNodeName],void 0!==c[d]&&c.hasOwnProperty(d)?(Array.isArray(c[d])||(c[d]=[c[d]]),c[d].push(t)):s.isArray(d,p,i)?c[d]=[t]:c[d]=t}}}return"string"==typeof a?a.length>0&&(c[s.textNodeName]=a):void 0!==a&&(c[s.textNodeName]=a),c}function t(e){const t=Object.keys(e);for(let e=0;e<t.length;e++){const r=t[e];if(":@"!==r)return r}}function r(e,t,r,n){if(t){const i=Object.keys(t),s=i.length;for(let o=0;o<s;o++){const s=i[o];n.isArray(s,r+"."+s,!0,!0)?e[s]=[t[s]]:e[s]=t[s]}}}function n(e,t){const{textNodeName:r}=t,n=Object.keys(e).length;return 0===n||!(1!==n||!e[r]&&"boolean"!=typeof e[r]&&0!==e[r])}return hasRequiredNode2json=1,node2json.prettify=function(t,r){return e(t,r)},node2json}function requireXMLParser(){if(hasRequiredXMLParser)return XMLParser_1;hasRequiredXMLParser=1
1883
- ;const{buildOptions:e}=requireOptionsBuilder(),t=requireOrderedObjParser(),{prettify:r}=requireNode2json(),n=requireValidator$1();return XMLParser_1=class{constructor(t){this.externalEntities={},this.options=e(t)}parse(e,i){if("string"==typeof e);else{if(!e.toString)throw new Error("XML data is accepted in String or Bytes[] form.");e=e.toString()}if(i){!0===i&&(i={});const t=n.validate(e,i);if(!0!==t)throw Error(`${t.err.msg}:${t.err.line}:${t.err.col}`)}const s=new t(this.options);s.addExternalEntities(this.externalEntities);const o=s.parseXml(e);return this.options.preserveOrder||void 0===o?o:r(o,this.options)}addEntity(e,t){if(-1!==t.indexOf("&"))throw new Error("Entity value can't have '&'");if(-1!==e.indexOf("&")||-1!==e.indexOf(";"))throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if("&"===t)throw new Error("An entity with value '&' is not permitted");this.externalEntities[e]=t}}}function requireOrderedJs2Xml(){
1884
- if(hasRequiredOrderedJs2Xml)return orderedJs2Xml;hasRequiredOrderedJs2Xml=1;function e(s,o,a,c){let u="",l=!1;for(let d=0;d<s.length;d++){const p=s[d],h=t(p);if(void 0===h)continue;let A="";if(A=0===a.length?h:`${a}.${h}`,h===o.textNodeName){let e=p[h];n(A,o)||(e=o.tagValueProcessor(h,e),e=i(e,o)),l&&(u+=c),u+=e,l=!1;continue}if(h===o.cdataPropName){l&&(u+=c),u+=`<![CDATA[${p[h][0][o.textNodeName]}]]>`,l=!1;continue}if(h===o.commentPropName){u+=c+`\x3c!--${p[h][0][o.textNodeName]}--\x3e`,l=!0;continue}if("?"===h[0]){const e=r(p[":@"],o),t="?xml"===h?"":c;let n=p[h][0][o.textNodeName];n=0!==n.length?" "+n:"",u+=t+`<${h}${n}${e}?>`,l=!0;continue}let f=c;""!==f&&(f+=o.indentBy);const g=c+`<${h}${r(p[":@"],o)}`,m=e(p[h],o,A,f);-1!==o.unpairedTags.indexOf(h)?o.suppressUnpairedNode?u+=g+">":u+=g+"/>":m&&0!==m.length||!o.suppressEmptyNode?m&&m.endsWith(">")?u+=g+`>${m}${c}</${h}>`:(u+=g+">",m&&""!==c&&(m.includes("/>")||m.includes("</"))?u+=c+o.indentBy+m+c:u+=m,u+=`</${h}>`):u+=g+"/>",l=!0}
1885
- return u}function t(e){const t=Object.keys(e);for(let r=0;r<t.length;r++){const n=t[r];if(e.hasOwnProperty(n)&&":@"!==n)return n}}function r(e,t){let r="";if(e&&!t.ignoreAttributes)for(let n in e){if(!e.hasOwnProperty(n))continue;let s=t.attributeValueProcessor(n,e[n]);s=i(s,t),!0===s&&t.suppressBooleanAttributes?r+=` ${n.substr(t.attributeNamePrefix.length)}`:r+=` ${n.substr(t.attributeNamePrefix.length)}="${s}"`}return r}function n(e,t){let r=(e=e.substr(0,e.length-t.textNodeName.length-1)).substr(e.lastIndexOf(".")+1);for(let n in t.stopNodes)if(t.stopNodes[n]===e||t.stopNodes[n]==="*."+r)return!0;return!1}function i(e,t){if(e&&e.length>0&&t.processEntities)for(let r=0;r<t.entities.length;r++){const n=t.entities[r];e=e.replace(n.regex,n.val)}return e}return orderedJs2Xml=function(t,r){let n="";return r.format&&r.indentBy.length>0&&(n="\n"),e(t,r,"",n)}}function requireJson2xml(){if(hasRequiredJson2xml)return json2xml;hasRequiredJson2xml=1;const e=requireOrderedJs2Xml(),t={
1886
- attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],processEntities:!0,stopNodes:[],oneListGroup:!1};function r(e){this.options=Object.assign({},t,e),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=s),this.processTextOrObjNode=n,this.options.format?(this.indentate=i,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},
1887
- this.tagEndChar=">",this.newLine="")}function n(e,t,r){const n=this.j2x(e,r+1);return void 0!==e[this.options.textNodeName]&&1===Object.keys(e).length?this.buildTextValNode(e[this.options.textNodeName],t,n.attrStr,r):this.buildObjectNode(n.val,t,n.attrStr,r)}function i(e){return this.options.indentBy.repeat(e)}function s(e){return!(!e.startsWith(this.options.attributeNamePrefix)||e===this.options.textNodeName)&&e.substr(this.attrPrefixLen)}return r.prototype.build=function(t){return this.options.preserveOrder?e(t,this.options):(Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t}),this.j2x(t,0).val)},r.prototype.j2x=function(e,t){let r="",n=""
1888
- ;for(let i in e)if(Object.prototype.hasOwnProperty.call(e,i))if(void 0===e[i])this.isAttribute(i)&&(n+="");else if(null===e[i])this.isAttribute(i)?n+="":"?"===i[0]?n+=this.indentate(t)+"<"+i+"?"+this.tagEndChar:n+=this.indentate(t)+"<"+i+"/"+this.tagEndChar;else if(e[i]instanceof Date)n+=this.buildTextValNode(e[i],i,"",t);else if("object"!=typeof e[i]){const s=this.isAttribute(i);if(s)r+=this.buildAttrPairStr(s,""+e[i]);else if(i===this.options.textNodeName){let t=this.options.tagValueProcessor(i,""+e[i]);n+=this.replaceEntitiesValue(t)}else n+=this.buildTextValNode(e[i],i,"",t)}else if(Array.isArray(e[i])){const r=e[i].length;let s="",o="";for(let a=0;a<r;a++){const r=e[i][a];if(void 0===r);else if(null===r)"?"===i[0]?n+=this.indentate(t)+"<"+i+"?"+this.tagEndChar:n+=this.indentate(t)+"<"+i+"/"+this.tagEndChar;else if("object"==typeof r)if(this.options.oneListGroup){const e=this.j2x(r,t+1);s+=e.val,
1889
- this.options.attributesGroupName&&r.hasOwnProperty(this.options.attributesGroupName)&&(o+=e.attrStr)}else s+=this.processTextOrObjNode(r,i,t);else if(this.options.oneListGroup){let e=this.options.tagValueProcessor(i,r);e=this.replaceEntitiesValue(e),s+=e}else s+=this.buildTextValNode(r,i,"",t)}this.options.oneListGroup&&(s=this.buildObjectNode(s,i,o,t)),n+=s}else if(this.options.attributesGroupName&&i===this.options.attributesGroupName){const t=Object.keys(e[i]),n=t.length;for(let s=0;s<n;s++)r+=this.buildAttrPairStr(t[s],""+e[i][t[s]])}else n+=this.processTextOrObjNode(e[i],i,t);return{attrStr:r,val:n}},r.prototype.buildAttrPairStr=function(e,t){return t=this.options.attributeValueProcessor(e,""+t),t=this.replaceEntitiesValue(t),this.options.suppressBooleanAttributes&&"true"===t?" "+e:" "+e+'="'+t+'"'},r.prototype.buildObjectNode=function(e,t,r,n){if(""===e)return"?"===t[0]?this.indentate(n)+"<"+t+r+"?"+this.tagEndChar:this.indentate(n)+"<"+t+r+this.closeTag(t)+this.tagEndChar;{
1890
- let i="</"+t+this.tagEndChar,s="";return"?"===t[0]&&(s="?",i=""),!r&&""!==r||-1!==e.indexOf("<")?!1!==this.options.commentPropName&&t===this.options.commentPropName&&0===s.length?this.indentate(n)+`\x3c!--${e}--\x3e`+this.newLine:this.indentate(n)+"<"+t+r+s+this.tagEndChar+e+this.indentate(n)+i:this.indentate(n)+"<"+t+r+s+">"+e+i}},r.prototype.closeTag=function(e){let t="";return-1!==this.options.unpairedTags.indexOf(e)?this.options.suppressUnpairedNode||(t="/"):t=this.options.suppressEmptyNode?"/":`></${e}`,t},r.prototype.buildTextValNode=function(e,t,r,n){if(!1!==this.options.cdataPropName&&t===this.options.cdataPropName)return this.indentate(n)+`<![CDATA[${e}]]>`+this.newLine;if(!1!==this.options.commentPropName&&t===this.options.commentPropName)return this.indentate(n)+`\x3c!--${e}--\x3e`+this.newLine;if("?"===t[0])return this.indentate(n)+"<"+t+r+"?"+this.tagEndChar;{let i=this.options.tagValueProcessor(t,e);return i=this.replaceEntitiesValue(i),
1891
- ""===i?this.indentate(n)+"<"+t+r+this.closeTag(t)+this.tagEndChar:this.indentate(n)+"<"+t+r+">"+i+"</"+t+this.tagEndChar}},r.prototype.replaceEntitiesValue=function(e){if(e&&e.length>0&&this.options.processEntities)for(let t=0;t<this.options.entities.length;t++){const r=this.options.entities[t];e=e.replace(r.regex,r.val)}return e},json2xml=r}function requireFxp(){if(hasRequiredFxp)return fxp;hasRequiredFxp=1;const e=requireValidator$1(),t=requireXMLParser(),r=requireJson2xml();return fxp={XMLParser:t,XMLValidator:e,XMLBuilder:r}}var fxpExports=requireFxp(),objectToString$2=Object.prototype.toString,isArray$1=Array.isArray||function(e){return"[object Array]"===objectToString$2.call(e)};function isFunction$1(e){return"function"==typeof e}function typeStr(e){return isArray$1(e)?"array":typeof e}function escapeRegExp(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function hasProperty(e,t){return null!=e&&"object"==typeof e&&t in e}function primitiveHasOwnProperty(e,t){
1892
- return null!=e&&"object"!=typeof e&&e.hasOwnProperty&&e.hasOwnProperty(t)}var regExpTest=RegExp.prototype.test;function testRegExp(e,t){return regExpTest.call(e,t)}var nonSpaceRe=/\S/;function isWhitespace(e){return!testRegExp(nonSpaceRe,e)}var entityMap={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function escapeHtml$1(e){return String(e).replace(/[&<>"'`=\/]/g,function(e){return entityMap[e]})}var whiteRe=/\s*/,spaceRe=/\s+/,equalsRe=/\s*=/,curlyRe=/\s*\}/,tagRe=/#|\^|\/|>|\{|&|=|!/;function parseTemplate$1(e,t){if(!e)return[];var r,n,i,s=!1,o=[],a=[],c=[],u=!1,l=!1,d="",p=0;function h(){if(u&&!l)for(;c.length;)delete a[c.pop()];else c=[];u=!1,l=!1}function A(e){if("string"==typeof e&&(e=e.split(spaceRe,2)),!isArray$1(e)||2!==e.length)throw new Error("Invalid tags: "+e);r=new RegExp(escapeRegExp(e[0])+"\\s*"),n=new RegExp("\\s*"+escapeRegExp(e[1])),i=new RegExp("\\s*"+escapeRegExp("}"+e[1]))}A(t||mustache.tags)
1893
- ;for(var f,g,m,y,E,b,C=new Scanner(e);!C.eos();){if(f=C.pos,m=C.scanUntil(r))for(var v=0,I=m.length;v<I;++v)isWhitespace(y=m.charAt(v))?(c.push(a.length),d+=y):(l=!0,s=!0,d+=" "),a.push(["text",y,f,f+1]),f+=1,"\n"===y&&(h(),d="",p=0,s=!1);if(!C.scan(r))break;if(u=!0,g=C.scan(tagRe)||"name",C.scan(whiteRe),"="===g?(m=C.scanUntil(equalsRe),C.scan(equalsRe),C.scanUntil(n)):"{"===g?(m=C.scanUntil(i),C.scan(curlyRe),C.scanUntil(n),g="&"):m=C.scanUntil(n),!C.scan(n))throw new Error("Unclosed tag at "+C.pos);if(E=">"==g?[g,m,f,C.pos,d,p,s]:[g,m,f,C.pos],p++,a.push(E),"#"===g||"^"===g)o.push(E);else if("/"===g){if(!(b=o.pop()))throw new Error('Unopened section "'+m+'" at '+f);if(b[1]!==m)throw new Error('Unclosed section "'+b[1]+'" at '+f)}else"name"===g||"{"===g||"&"===g?l=!0:"="===g&&A(m)}if(h(),b=o.pop())throw new Error('Unclosed section "'+b[1]+'" at '+C.pos);return nestTokens(squashTokens(a))}function squashTokens(e){
1894
- for(var t,r,n=[],i=0,s=e.length;i<s;++i)(t=e[i])&&("text"===t[0]&&r&&"text"===r[0]?(r[1]+=t[1],r[3]=t[3]):(n.push(t),r=t));return n}function nestTokens(e){for(var t,r=[],n=r,i=[],s=0,o=e.length;s<o;++s)switch((t=e[s])[0]){case"#":case"^":n.push(t),i.push(t),n=t[4]=[];break;case"/":i.pop()[5]=t[2],n=i.length>0?i[i.length-1][4]:r;break;default:n.push(t)}return r}function Scanner(e){this.string=e,this.tail=e,this.pos=0}function Context(e,t){this.view=e,this.cache={".":this.view},this.parent=t}function Writer(){this.templateCache={_cache:{},set:function(e,t){this._cache[e]=t},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}Scanner.prototype.eos=function(){return""===this.tail},Scanner.prototype.scan=function(e){var t=this.tail.match(e);if(!t||0!==t.index)return"";var r=t[0];return this.tail=this.tail.substring(r.length),this.pos+=r.length,r},Scanner.prototype.scanUntil=function(e){var t,r=this.tail.search(e);switch(r){case-1:t=this.tail,this.tail="";break;case 0:
1895
- t="";break;default:t=this.tail.substring(0,r),this.tail=this.tail.substring(r)}return this.pos+=t.length,t},Context.prototype.push=function(e){return new Context(e,this)},Context.prototype.lookup=function(e){var t,r=this.cache;if(r.hasOwnProperty(e))t=r[e];else{for(var n,i,s,o=this,a=!1;o;){if(e.indexOf(".")>0)for(n=o.view,i=e.split("."),s=0;null!=n&&s<i.length;)s===i.length-1&&(a=hasProperty(n,i[s])||primitiveHasOwnProperty(n,i[s])),n=n[i[s++]];else n=o.view[e],a=hasProperty(o.view,e);if(a){t=n;break}o=o.parent}r[e]=t}return isFunction$1(t)&&(t=t.call(this.view)),t},Writer.prototype.clearCache=function(){void 0!==this.templateCache&&this.templateCache.clear()},Writer.prototype.parse=function(e,t){var r=this.templateCache,n=e+":"+(t||mustache.tags).join(":"),i=void 0!==r,s=i?r.get(n):void 0;return null==s&&(s=parseTemplate$1(e,t),i&&r.set(n,s)),s},Writer.prototype.render=function(e,t,r,n){var i=this.getConfigTags(n),s=this.parse(e,i),o=t instanceof Context?t:new Context(t,void 0)
1896
- ;return this.renderTokens(s,o,r,e,n)},Writer.prototype.renderTokens=function(e,t,r,n,i){for(var s,o,a,c="",u=0,l=e.length;u<l;++u)a=void 0,"#"===(o=(s=e[u])[0])?a=this.renderSection(s,t,r,n,i):"^"===o?a=this.renderInverted(s,t,r,n,i):">"===o?a=this.renderPartial(s,t,r,i):"&"===o?a=this.unescapedValue(s,t):"name"===o?a=this.escapedValue(s,t,i):"text"===o&&(a=this.rawValue(s)),void 0!==a&&(c+=a);return c},Writer.prototype.renderSection=function(e,t,r,n,i){var s=this,o="",a=t.lookup(e[1]);if(a){if(isArray$1(a))for(var c=0,u=a.length;c<u;++c)o+=this.renderTokens(e[4],t.push(a[c]),r,n,i);else if("object"==typeof a||"string"==typeof a||"number"==typeof a)o+=this.renderTokens(e[4],t.push(a),r,n,i);else if(isFunction$1(a)){if("string"!=typeof n)throw new Error("Cannot use higher-order sections without the original template");a=a.call(t.view,n.slice(e[3],e[5]),function(e){return s.render(e,t,r,i)}),null!=a&&(o+=a)}else o+=this.renderTokens(e[4],t,r,n,i);return o}},
1897
- Writer.prototype.renderInverted=function(e,t,r,n,i){var s=t.lookup(e[1]);if(!s||isArray$1(s)&&0===s.length)return this.renderTokens(e[4],t,r,n,i)},Writer.prototype.indentPartial=function(e,t,r){for(var n=t.replace(/[^ \t]/g,""),i=e.split("\n"),s=0;s<i.length;s++)i[s].length&&(s>0||!r)&&(i[s]=n+i[s]);return i.join("\n")},Writer.prototype.renderPartial=function(e,t,r,n){if(r){var i=this.getConfigTags(n),s=isFunction$1(r)?r(e[1]):r[e[1]];if(null!=s){var o=e[6],a=e[5],c=e[4],u=s;0==a&&c&&(u=this.indentPartial(s,c,o));var l=this.parse(u,i);return this.renderTokens(l,t,r,u,n)}}},Writer.prototype.unescapedValue=function(e,t){var r=t.lookup(e[1]);if(null!=r)return r},Writer.prototype.escapedValue=function(e,t,r){var n=this.getConfigEscape(r)||mustache.escape,i=t.lookup(e[1]);if(null!=i)return"number"==typeof i&&n===mustache.escape?String(i):n(i)},Writer.prototype.rawValue=function(e){return e[1]},Writer.prototype.getConfigTags=function(e){
1898
- return isArray$1(e)?e:e&&"object"==typeof e?e.tags:void 0},Writer.prototype.getConfigEscape=function(e){return e&&"object"==typeof e&&!isArray$1(e)?e.escape:void 0};var mustache={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(e){defaultWriter.templateCache=e},get templateCache(){return defaultWriter.templateCache}},defaultWriter=new Writer;mustache.clearCache=function(){return defaultWriter.clearCache()},mustache.parse=function(e,t){return defaultWriter.parse(e,t)},mustache.render=function(e,t,r,n){if("string"!=typeof e)throw new TypeError('Invalid template! Template should be a "string" but "'+typeStr(e)+'" was given as the first argument for mustache#render(template, view, partials)');return defaultWriter.render(e,t,r,n)},mustache.escape=escapeHtml$1,mustache.Scanner=Scanner,mustache.Context=Context,mustache.Writer=Writer;let SimpleEventEmitter$1=class{
1899
- constructor(){this.events={},this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.events[e]=this.events[e].filter(e=>e!==t)}}emit(e,t){for(const r of this.events[e]||[])r(t);for(const r of this.events["*"]||[])r(e,t)}};const DEFAULT_PROMPT_CACHE_TTL_SECONDS=60;class LangfusePromptCacheItem{constructor(e,t){this.value=e,this._expiry=Date.now()+1e3*t}get isExpired(){return Date.now()>this._expiry}}class LangfusePromptCache{constructor(){this._cache=new Map,this._defaultTtlSeconds=DEFAULT_PROMPT_CACHE_TTL_SECONDS,this._refreshingKeys=new Map}getIncludingExpired(e){return this._cache.get(e)??null}set(e,t,r){const n=r??this._defaultTtlSeconds;this._cache.set(e,new LangfusePromptCacheItem(t,n))}addRefreshingPromise(e,t){this._refreshingKeys.set(e,t),t.then(()=>{this._refreshingKeys.delete(e)}).catch(()=>{this._refreshingKeys.delete(e)})}isRefreshing(e){return this._refreshingKeys.has(e)}invalidate(e){
1900
- console.log("invalidating",e,this._cache.keys());for(const t of this._cache.keys())t.startsWith(e)&&this._cache.delete(t)}}var LangfusePersistedProperty,ChatMessageType;!function(e){e.Props="props",e.Queue="queue",e.OptedOut="opted_out"}(LangfusePersistedProperty||(LangfusePersistedProperty={})),function(e){e.ChatMessage="chatmessage",e.Placeholder="placeholder"}(ChatMessageType||(ChatMessageType={})),mustache.escape=function(e){return e};class BasePromptClient{constructor(e,t=!1,r){this.name=e.name,this.version=e.version,this.config=e.config,this.labels=e.labels,this.tags=e.tags,this.isFallback=t,this.type=r,this.commitMessage=e.commitMessage}_transformToLangchainVariables(e){return this.escapeJsonForLangchain(e).replace(/\{\{(\w+)\}\}/g,"{$1}")}escapeJsonForLangchain(e){const t=[],r=[];let n=0;const i=e.length;for(;n<i;){const s=e[n];if("{"===s){if(n+1<i&&"{"===e[n+1]){t.push("{{"),n+=2;continue}let s=n+1;for(;s<i&&/\s/.test(e[s]);)s++;const o=s<i&&("'"===e[s]||'"'===e[s])
1901
- ;t.push(o?"{{":"{"),r.push(o),n+=1;continue}if("}"===s){if(n+1<i&&"}"===e[n+1]){t.push("}}"),n+=2;continue}const s=r.pop()??!1;t.push(s?"}}":"}"),n+=1;continue}t.push(s),n+=1}return t.join("")}}class TextPromptClient extends BasePromptClient{constructor(e,t=!1){super(e,t,"text"),this.promptResponse=e,this.prompt=e.prompt}compile(e,t){return mustache.render(this.promptResponse.prompt,e??{})}getLangchainPrompt(e){return this._transformToLangchainVariables(this.prompt)}toJSON(){return JSON.stringify({name:this.name,prompt:this.prompt,version:this.version,isFallback:this.isFallback,tags:this.tags,labels:this.labels,type:this.type,config:this.config})}}class ChatPromptClient extends BasePromptClient{constructor(e,t=!1){const r=ChatPromptClient.normalizePrompt(e.prompt),n={...e,prompt:r};super(n,t,"chat"),this.promptResponse=n,this.prompt=r}static normalizePrompt(e){return e.map(e=>"type"in e?e:{type:ChatMessageType.ChatMessage,...e})}compile(e,t){const r=[],n=t??{}
1902
- ;for(const e of this.prompt)if("type"in e&&e.type===ChatMessageType.Placeholder){const t=n[e.name];Array.isArray(t)&&t.length>0&&t.every(e=>"object"==typeof e&&"role"in e&&"content"in e)?r.push(...t):Array.isArray(t)&&0===t.length||(void 0!==t?r.push(JSON.stringify(t)):r.push(e))}else"role"in e&&"content"in e&&e.type===ChatMessageType.ChatMessage&&r.push({role:e.role,content:e.content});return r.map(t=>"object"==typeof t&&null!==t&&"role"in t&&"content"in t?{...t,content:mustache.render(t.content,e??{})}:t)}getLangchainPrompt(e){const t=[],r=e?.placeholders??{};for(const e of this.prompt)if("type"in e&&e.type===ChatMessageType.Placeholder){const n=r[e.name];Array.isArray(n)&&n.length>0&&n.every(e=>"object"==typeof e&&"role"in e&&"content"in e)?t.push(...n.map(e=>({role:e.role,content:this._transformToLangchainVariables(e.content)}))):Array.isArray(n)&&0===n.length||(void 0!==n?t.push(JSON.stringify(n)):t.push({variableName:e.name,optional:!1}))
1903
- }else"role"in e&&"content"in e&&e.type===ChatMessageType.ChatMessage&&t.push({role:e.role,content:this._transformToLangchainVariables(e.content)});return t}toJSON(){return JSON.stringify({name:this.name,prompt:this.promptResponse.prompt.map(e=>{if("type"in e&&e.type===ChatMessageType.ChatMessage){const{type:t,...r}=e;return r}return e}),version:this.version,isFallback:this.isFallback,tags:this.tags,labels:this.labels,type:this.type,config:this.config})}}function assert$3(e,t){if(!e)throw new Error(t)}function removeTrailingSlash$2(e){return e?.replace(/\/+$/,"")}async function retriable$1(e,t={},r){const{retryCount:n=3,retryDelay:i=5e3,retryCheck:s=()=>!0}=t;let o=null;for(let t=0;t<n+1;t++){t>0&&(await new Promise(e=>setTimeout(e,i)),r(`Retrying ${t+1} of ${n+1}`));try{return await e()}catch(e){if(o=e,!s(e))throw e;r(`Retriable error: ${JSON.stringify(e)}`)}}throw o}function generateUUID(e){let t=(new Date).getTime(),r=e&&e.performance&&e.performance.now&&1e3*e.performance.now()||0
1904
- ;return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){let n=16*Math.random();return t>0?(n=(t+n)%16|0,t=Math.floor(t/16)):(n=(r+n)%16|0,r=Math.floor(r/16)),("x"===e?n:3&n|8).toString(16)})}function currentTimestamp(){return(new Date).getTime()}function currentISOTime$1(){return(new Date).toISOString()}function safeSetTimeout$1(e,t){const r=setTimeout(e,t);return r?.unref&&r?.unref(),r}function getEnv$1(e){return"undefined"!=typeof process&&process.env[e]?process.env[e]:"undefined"!=typeof globalThis?globalThis[e]:void 0}function configLangfuseSDK(e,t=!0){const{publicKey:r,secretKey:n,...i}=e??{},s=r??getEnv$1("LANGFUSE_PUBLIC_KEY"),o=t?n??getEnv$1("LANGFUSE_SECRET_KEY"):void 0,a=i.baseUrl??getEnv$1("LANGFUSE_BASEURL");return{publicKey:s,...t?{secretKey:o}:void 0,...{...i,baseUrl:a}}}const encodeQueryParams=e=>{const t=new URLSearchParams;return Object.entries(e??{}).forEach(([e,r])=>{null!=r&&(r instanceof Date?t.append(e,r.toISOString()):t.append(e,r.toString()))
1905
- }),t.toString()};var utils$7=Object.freeze({__proto__:null,assert:assert$3,configLangfuseSDK,currentISOTime:currentISOTime$1,currentTimestamp,encodeQueryParams,generateUUID,getEnv:getEnv$1,removeTrailingSlash:removeTrailingSlash$2,retriable:retriable$1,safeSetTimeout:safeSetTimeout$1});const common_release_envs=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","TRIGGER_DEPLOYMENT_ID"];function getCommonReleaseEnvs(){for(const e of common_release_envs){const t=getEnv$1(e);if(t)return t}}let fs$4=null,cryptoModule=null;const dynamicImport=e=>import(e);void 0!==globalThis.Deno?Promise.all([dynamicImport("node:fs"),dynamicImport("node:crypto")]).then(([e,t])=>{fs$4=e,cryptoModule=t}).catch():"undefined"!=typeof process&&process.versions?.node?Promise.all([dynamicImport("fs"),dynamicImport("crypto")]).then(([e,t])=>{fs$4=e,cryptoModule=t
1906
- }).catch():"undefined"!=typeof crypto&&(cryptoModule=crypto);class LangfuseMedia{constructor(e){const{obj:t,base64DataUri:r,contentType:n,contentBytes:i,filePath:s}=e;if(this.obj=t,this._mediaId=void 0,r){const[e,t]=this.parseBase64DataUri(r);this._contentBytes=e,this._contentType=t,this._source="base64_data_uri"}else if(i&&n)this._contentBytes=i,this._contentType=n,this._source="bytes";else if(s&&n){if(!fs$4)throw new Error("File system support is not available in this environment");if(!fs$4.existsSync(s))throw new Error(`File at path ${s} does not exist`);this._contentBytes=this.readFile(s),this._contentType=this._contentBytes?n:void 0,this._source=this._contentBytes?"file":void 0}else console.error("base64DataUri, or contentBytes and contentType, or filePath must be provided to LangfuseMedia")}readFile(e){try{if(!fs$4)throw new Error("File system support is not available in this environment");return fs$4.readFileSync(e)}catch(t){
1907
- return void console.error(`Error reading file at path ${e}`,t)}}parseBase64DataUri(e){try{if(!e||"string"!=typeof e)throw new Error("Data URI is not a string");if(!e.startsWith("data:"))throw new Error("Data URI does not start with 'data:'");const[t,r]=e.slice(5).split(",",2);if(!t||!r)throw new Error("Invalid URI");const n=t.split(";");if(!n.includes("base64"))throw new Error("Data is not base64 encoded");const i=n[0];if(!i)throw new Error("Content type is empty");return[Buffer.from(r,"base64"),i]}catch(e){return console.error("Error parsing base64 data URI",e),[void 0,void 0]}}get contentLength(){return this._contentBytes?.length}get contentSha256Hash(){if(!this._contentBytes)return;if(!cryptoModule)return void console.error("Crypto support is not available in this environment");return cryptoModule.createHash("sha256").update(this._contentBytes).digest("base64")}toJSON(){
1861
+ ;const c=_optionalChain$O([t,"optionalAccess",e=>e.traceInfo,"optionalAccess",e=>e.parent,"optionalAccess",e=>e.generation,"call",e=>e({name:_optionalChain$O([t,"optionalAccess",e=>e.traceInfo,"optionalAccess",e=>e.generationName]),model:n.model,modelParameters:a,input:s})]),u={};propagation.inject(context.active(),u);const l=await r.messages.create({messages:s,...n},{headers:u});return _optionalChain$O([c,"optionalAccess",e=>e.end,"call",e=>e({output:l.content,usage:{input:_optionalChain$O([l,"access",e=>e.usage,"optionalAccess",e=>e.input_tokens]),output:_optionalChain$O([l,"access",e=>e.usage,"optionalAccess",e=>e.output_tokens])}})]),chatStreamBuilder(_optionalChain$O([t,"optionalAccess",e=>e.respondObject,"optionalAccess",e=>e.schema]),nonStreamedAsString(_optionalChain$O([l,"access",e=>e.content,"access",e=>e.map,"call",e=>e(e=>"text"===e.type?e.text:""),"optionalAccess",e=>e.join,"call",e=>e("\n")])))})}}
1862
+ const nameStartChar=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",nameChar=nameStartChar+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",nameRegexp="["+nameStartChar+"]["+nameChar+"]*",regexName=new RegExp("^"+nameRegexp+"$");function getAllMatches(e,t){const r=[];let n=t.exec(e);for(;n;){const i=[];i.startIndex=t.lastIndex-n[0].length;const s=n.length;for(let e=0;e<s;e++)i.push(n[e]);r.push(i),n=t.exec(e)}return r}const isName=function(e){const t=regexName.exec(e);return!(null==t)};function isExist(e){return void 0!==e}const defaultOptions$2={allowBooleanAttributes:!1,unpairedTags:[]};function validate$2(e,t){t=Object.assign({},defaultOptions$2,t);const r=[];let n=!1,i=!1;"\ufeff"===e[0]&&(e=e.substr(1));for(let s=0;s<e.length;s++)if("<"===e[s]&&"?"===e[s+1]){if(s+=2,s=readPI(e,s),s.err)return s}else{if("<"!==e[s]){if(isWhiteSpace(e[s]))continue
1863
+ ;return getErrorObject("InvalidChar","char '"+e[s]+"' is not expected.",getLineNumberForPosition(e,s))}{let o=s;if(s++,"!"===e[s]){s=readCommentAndCDATA(e,s);continue}{let a=!1;"/"===e[s]&&(a=!0,s++);let c="";for(;s<e.length&&">"!==e[s]&&" "!==e[s]&&"\t"!==e[s]&&"\n"!==e[s]&&"\r"!==e[s];s++)c+=e[s];if(c=c.trim(),"/"===c[c.length-1]&&(c=c.substring(0,c.length-1),s--),!validateTagName(c)){let t;return t=0===c.trim().length?"Invalid space after '<'.":"Tag '"+c+"' is an invalid name.",getErrorObject("InvalidTag",t,getLineNumberForPosition(e,s))}const u=readAttributeStr(e,s);if(!1===u)return getErrorObject("InvalidAttr","Attributes for '"+c+"' have open quote.",getLineNumberForPosition(e,s));let l=u.value;if(s=u.index,"/"===l[l.length-1]){const r=s-l.length;l=l.substring(0,l.length-1);const i=validateAttributeString(l,t);if(!0!==i)return getErrorObject(i.err.code,i.err.msg,getLineNumberForPosition(e,r+i.err.line));n=!0}else if(a){
1864
+ if(!u.tagClosed)return getErrorObject("InvalidTag","Closing tag '"+c+"' doesn't have proper closing.",getLineNumberForPosition(e,s));if(l.trim().length>0)return getErrorObject("InvalidTag","Closing tag '"+c+"' can't have attributes or invalid starting.",getLineNumberForPosition(e,o));if(0===r.length)return getErrorObject("InvalidTag","Closing tag '"+c+"' has not been opened.",getLineNumberForPosition(e,o));{const t=r.pop();if(c!==t.tagName){let r=getLineNumberForPosition(e,t.tagStartPos);return getErrorObject("InvalidTag","Expected closing tag '"+t.tagName+"' (opened in line "+r.line+", col "+r.col+") instead of closing tag '"+c+"'.",getLineNumberForPosition(e,o))}0==r.length&&(i=!0)}}else{const a=validateAttributeString(l,t);if(!0!==a)return getErrorObject(a.err.code,a.err.msg,getLineNumberForPosition(e,s-l.length+a.err.line));if(!0===i)return getErrorObject("InvalidXml","Multiple possible root nodes found.",getLineNumberForPosition(e,s));-1!==t.unpairedTags.indexOf(c)||r.push({
1865
+ tagName:c,tagStartPos:o}),n=!0}for(s++;s<e.length;s++)if("<"===e[s]){if("!"===e[s+1]){s++,s=readCommentAndCDATA(e,s);continue}if("?"!==e[s+1])break;if(s=readPI(e,++s),s.err)return s}else if("&"===e[s]){const t=validateAmpersand(e,s);if(-1==t)return getErrorObject("InvalidChar","char '&' is not expected.",getLineNumberForPosition(e,s));s=t}else if(!0===i&&!isWhiteSpace(e[s]))return getErrorObject("InvalidXml","Extra text at the end",getLineNumberForPosition(e,s));"<"===e[s]&&s--}}}return n?1==r.length?getErrorObject("InvalidTag","Unclosed tag '"+r[0].tagName+"'.",getLineNumberForPosition(e,r[0].tagStartPos)):!(r.length>0)||getErrorObject("InvalidXml","Invalid '"+JSON.stringify(r.map(e=>e.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):getErrorObject("InvalidXml","Start tag expected.",1)}function isWhiteSpace(e){return" "===e||"\t"===e||"\n"===e||"\r"===e}function readPI(e,t){const r=t;for(;t<e.length;t++)if("?"==e[t]||" "==e[t]){const n=e.substr(r,t-r)
1866
+ ;if(t>5&&"xml"===n)return getErrorObject("InvalidXml","XML declaration allowed only at the start of the document.",getLineNumberForPosition(e,t));if("?"==e[t]&&">"==e[t+1]){t++;break}continue}return t}function readCommentAndCDATA(e,t){if(e.length>t+5&&"-"===e[t+1]&&"-"===e[t+2]){for(t+=3;t<e.length;t++)if("-"===e[t]&&"-"===e[t+1]&&">"===e[t+2]){t+=2;break}}else if(e.length>t+8&&"D"===e[t+1]&&"O"===e[t+2]&&"C"===e[t+3]&&"T"===e[t+4]&&"Y"===e[t+5]&&"P"===e[t+6]&&"E"===e[t+7]){let r=1;for(t+=8;t<e.length;t++)if("<"===e[t])r++;else if(">"===e[t]&&(r--,0===r))break}else if(e.length>t+9&&"["===e[t+1]&&"C"===e[t+2]&&"D"===e[t+3]&&"A"===e[t+4]&&"T"===e[t+5]&&"A"===e[t+6]&&"["===e[t+7])for(t+=8;t<e.length;t++)if("]"===e[t]&&"]"===e[t+1]&&">"===e[t+2]){t+=2;break}return t}const doubleQuote='"',singleQuote="'";function readAttributeStr(e,t){let r="",n="",i=!1;for(;t<e.length;t++){if(e[t]===doubleQuote||e[t]===singleQuote)""===n?n=e[t]:n!==e[t]||(n="");else if(">"===e[t]&&""===n){i=!0;break}
1867
+ r+=e[t]}return""===n&&{value:r,index:t,tagClosed:i}}const validAttrStrRegxp=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function validateAttributeString(e,t){const r=getAllMatches(e,validAttrStrRegxp),n={};for(let e=0;e<r.length;e++){if(0===r[e][1].length)return getErrorObject("InvalidAttr","Attribute '"+r[e][2]+"' has no space in starting.",getPositionFromMatch(r[e]));if(void 0!==r[e][3]&&void 0===r[e][4])return getErrorObject("InvalidAttr","Attribute '"+r[e][2]+"' is without value.",getPositionFromMatch(r[e]));if(void 0===r[e][3]&&!t.allowBooleanAttributes)return getErrorObject("InvalidAttr","boolean attribute '"+r[e][2]+"' is not allowed.",getPositionFromMatch(r[e]));const i=r[e][2];if(!validateAttrName(i))return getErrorObject("InvalidAttr","Attribute '"+i+"' is an invalid name.",getPositionFromMatch(r[e]));if(n.hasOwnProperty(i))return getErrorObject("InvalidAttr","Attribute '"+i+"' is repeated.",getPositionFromMatch(r[e]));n[i]=1}return!0}
1868
+ function validateNumberAmpersand(e,t){let r=/\d/;for("x"===e[t]&&(t++,r=/[\da-fA-F]/);t<e.length;t++){if(";"===e[t])return t;if(!e[t].match(r))break}return-1}function validateAmpersand(e,t){if(";"===e[++t])return-1;if("#"===e[t])return validateNumberAmpersand(e,++t);let r=0;for(;t<e.length;t++,r++)if(!(e[t].match(/\w/)&&r<20)){if(";"===e[t])break;return-1}return t}function getErrorObject(e,t,r){return{err:{code:e,msg:t,line:r.line||r,col:r.col}}}function validateAttrName(e){return isName(e)}function validateTagName(e){return isName(e)}function getLineNumberForPosition(e,t){const r=e.substring(0,t).split(/\r?\n/);return{line:r.length,col:r[r.length-1].length+1}}function getPositionFromMatch(e){return e.startIndex+e[1].length}const defaultOptions$1={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{
1869
+ hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(e,t,r){return e},captureMetaData:!1},buildOptions=function(e){return Object.assign({},defaultOptions$1,e)};let METADATA_SYMBOL$1;METADATA_SYMBOL$1="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class XmlNode{constructor(e){this.tagname=e,this.child=[],this[":@"]={}}add(e,t){"__proto__"===e&&(e="#__proto__"),this.child.push({[e]:t})}addChild(e,t){"__proto__"===e.tagname&&(e.tagname="#__proto__"),e[":@"]&&Object.keys(e[":@"]).length>0?this.child.push({[e.tagname]:e.child,":@":e[":@"]}):this.child.push({[e.tagname]:e.child}),void 0!==t&&(this.child[this.child.length-1][METADATA_SYMBOL$1]={startIndex:t})}
1870
+ static getMetaDataSymbol(){return METADATA_SYMBOL$1}}function readDocType(e,t){const r={};if("O"!==e[t+3]||"C"!==e[t+4]||"T"!==e[t+5]||"Y"!==e[t+6]||"P"!==e[t+7]||"E"!==e[t+8])throw new Error("Invalid Tag instead of DOCTYPE");{t+=9;let n=1,i=!1,s=!1,o="";for(;t<e.length;t++)if("<"!==e[t]||s)if(">"===e[t]){if(s?"-"===e[t-1]&&"-"===e[t-2]&&(s=!1,n--):n--,0===n)break}else"["===e[t]?i=!0:o+=e[t];else{if(i&&hasSeq(e,"!ENTITY",t)){let n,i;t+=7,[n,i,t]=readEntityExp(e,t+1),-1===i.indexOf("&")&&(r[n]={regx:RegExp(`&${n};`,"g"),val:i})}else if(i&&hasSeq(e,"!ELEMENT",t)){t+=8;const{index:r}=readElementExp(e,t+1);t=r}else if(i&&hasSeq(e,"!ATTLIST",t))t+=8;else if(i&&hasSeq(e,"!NOTATION",t)){t+=9;const{index:r}=readNotationExp(e,t+1);t=r}else{if(!hasSeq(e,"!--",t))throw new Error("Invalid DOCTYPE");s=!0}n++,o=""}if(0!==n)throw new Error("Unclosed DOCTYPE")}return{entities:r,i:t}}const skipWhitespace=(e,t)=>{for(;t<e.length&&/\s/.test(e[t]);)t++;return t};function readEntityExp(e,t){
1871
+ t=skipWhitespace(e,t);let r="";for(;t<e.length&&!/\s/.test(e[t])&&'"'!==e[t]&&"'"!==e[t];)r+=e[t],t++;if(validateEntityName(r),t=skipWhitespace(e,t),"SYSTEM"===e.substring(t,t+6).toUpperCase())throw new Error("External entities are not supported");if("%"===e[t])throw new Error("Parameter entities are not supported");let n="";return[t,n]=readIdentifierVal(e,t,"entity"),[r,n,--t]}function readNotationExp(e,t){t=skipWhitespace(e,t);let r="";for(;t<e.length&&!/\s/.test(e[t]);)r+=e[t],t++;validateEntityName(r),t=skipWhitespace(e,t);const n=e.substring(t,t+6).toUpperCase();if("SYSTEM"!==n&&"PUBLIC"!==n)throw new Error(`Expected SYSTEM or PUBLIC, found "${n}"`);t+=n.length,t=skipWhitespace(e,t);let i=null,s=null;if("PUBLIC"===n)[t,i]=readIdentifierVal(e,t,"publicIdentifier"),'"'!==e[t=skipWhitespace(e,t)]&&"'"!==e[t]||([t,s]=readIdentifierVal(e,t,"systemIdentifier"));else if("SYSTEM"===n&&([t,s]=readIdentifierVal(e,t,"systemIdentifier"),
1872
+ !s))throw new Error("Missing mandatory system identifier for SYSTEM notation");return{notationName:r,publicIdentifier:i,systemIdentifier:s,index:--t}}function readIdentifierVal(e,t,r){let n="";const i=e[t];if('"'!==i&&"'"!==i)throw new Error(`Expected quoted string, found "${i}"`);for(t++;t<e.length&&e[t]!==i;)n+=e[t],t++;if(e[t]!==i)throw new Error(`Unterminated ${r} value`);return[++t,n]}function readElementExp(e,t){t=skipWhitespace(e,t);let r="";for(;t<e.length&&!/\s/.test(e[t]);)r+=e[t],t++;if(!validateEntityName(r))throw new Error(`Invalid element name: "${r}"`);let n="";if("E"===e[t=skipWhitespace(e,t)]&&hasSeq(e,"MPTY",t))t+=4;else if("A"===e[t]&&hasSeq(e,"NY",t))t+=2;else{if("("!==e[t])throw new Error(`Invalid Element Expression, found "${e[t]}"`);for(t++;t<e.length&&")"!==e[t];)n+=e[t],t++;if(")"!==e[t])throw new Error("Unterminated content model")}return{elementName:r,contentModel:n.trim(),index:t}}function hasSeq(e,t,r){for(let n=0;n<t.length;n++)if(t[n]!==e[r+n+1])return!1
1873
+ ;return!0}function validateEntityName(e){if(isName(e))return e;throw new Error(`Invalid entity name ${e}`)}const hexRegex=/^[-+]?0x[a-fA-F0-9]+$/,numRegex=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,consider={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function toNumber(e,t={}){if(t=Object.assign({},consider,t),!e||"string"!=typeof e)return e;let r=e.trim();if(void 0!==t.skipLike&&t.skipLike.test(r))return e;if("0"===e)return 0;if(t.hex&&hexRegex.test(r))return parse_int(r,16);if(-1!==r.search(/.+[eE].+/))return resolveEnotation(e,r,t);{const n=numRegex.exec(r);if(n){const i=n[1]||"",s=n[2];let o=trimZeros(n[3]);const a=i?"."===e[s.length+1]:"."===e[s.length];if(!t.leadingZeros&&(s.length>1||1===s.length&&!a))return e;{const n=Number(r),a=String(n);if(0===n)return n;if(-1!==a.search(/[eE]/))return t.eNotation?n:e;if(-1!==r.indexOf("."))return"0"===a||a===o||a===`${i}${o}`?n:e;let c=s?o:r;return s?c===a||i+c===a?n:e:c===a||c===i+a?n:e}}return e}}
1874
+ const eNotationRegx=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function resolveEnotation(e,t,r){if(!r.eNotation)return e;const n=t.match(eNotationRegx);if(n){let i=n[1]||"";const s=-1===n[3].indexOf("e")?"E":"e",o=n[2],a=i?e[o.length+1]===s:e[o.length]===s;return o.length>1&&a?e:1!==o.length||!n[3].startsWith(`.${s}`)&&n[3][0]!==s?r.leadingZeros&&!a?(t=(n[1]||"")+n[3],Number(t)):e:Number(t)}return e}function trimZeros(e){return e&&-1!==e.indexOf(".")?("."===(e=e.replace(/0+$/,""))?e="0":"."===e[0]?e="0"+e:"."===e[e.length-1]&&(e=e.substring(0,e.length-1)),e):e}function parse_int(e,t){if(parseInt)return parseInt(e,t);if(Number.parseInt)return Number.parseInt(e,t);if(window&&window.parseInt)return window.parseInt(e,t);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}function getIgnoreAttributesFn(e){return"function"==typeof e?e:Array.isArray(e)?t=>{for(const r of e){if("string"==typeof r&&t===r)return!0;if(r instanceof RegExp&&r.test(t))return!0}}:()=>!1}
1875
+ class OrderedObjParser{constructor(e){this.options=e,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(e,t)=>String.fromCodePoint(Number.parseInt(t,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(e,t)=>String.fromCodePoint(Number.parseInt(t,16))}},this.addExternalEntities=addExternalEntities,this.parseXml=parseXml,this.parseTextData=parseTextData,
1876
+ this.resolveNameSpace=resolveNameSpace,this.buildAttributesMap=buildAttributesMap,this.isItStopNode=isItStopNode,this.replaceEntitiesValue=replaceEntitiesValue,this.readStopNodeData=readStopNodeData,this.saveTextToParentTag=saveTextToParentTag,this.addChild=addChild,this.ignoreAttributesFn=getIgnoreAttributesFn(this.options.ignoreAttributes)}}function addExternalEntities(e){const t=Object.keys(e);for(let r=0;r<t.length;r++){const n=t[r];this.lastEntities[n]={regex:new RegExp("&"+n+";","g"),val:e[n]}}}function parseTextData(e,t,r,n,i,s,o){if(void 0!==e&&(this.options.trimValues&&!n&&(e=e.trim()),e.length>0)){o||(e=this.replaceEntitiesValue(e));const n=this.options.tagValueProcessor(t,e,r,i,s);if(null==n)return e;if(typeof n!=typeof e||n!==e)return n;if(this.options.trimValues)return parseValue$1(e,this.options.parseTagValue,this.options.numberParseOptions);return e.trim()===e?parseValue$1(e,this.options.parseTagValue,this.options.numberParseOptions):e}}function resolveNameSpace(e){
1877
+ if(this.options.removeNSPrefix){const t=e.split(":"),r="/"===e.charAt(0)?"/":"";if("xmlns"===t[0])return"";2===t.length&&(e=r+t[1])}return e}const attrsRegx=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function buildAttributesMap(e,t,r){if(!0!==this.options.ignoreAttributes&&"string"==typeof e){const r=getAllMatches(e,attrsRegx),n=r.length,i={};for(let e=0;e<n;e++){const n=this.resolveNameSpace(r[e][1]);if(this.ignoreAttributesFn(n,t))continue;let s=r[e][4],o=this.options.attributeNamePrefix+n;if(n.length)if(this.options.transformAttributeName&&(o=this.options.transformAttributeName(o)),"__proto__"===o&&(o="#__proto__"),void 0!==s){this.options.trimValues&&(s=s.trim()),s=this.replaceEntitiesValue(s);const e=this.options.attributeValueProcessor(n,s,t);i[o]=null==e?s:typeof e!=typeof s||e!==s?e:parseValue$1(s,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(i[o]=!0)}if(!Object.keys(i).length)return
1878
+ ;if(this.options.attributesGroupName){const e={};return e[this.options.attributesGroupName]=i,e}return i}}const parseXml=function(e){e=e.replace(/\r\n?/g,"\n");const t=new XmlNode("!xml");let r=t,n="",i="";for(let s=0;s<e.length;s++){if("<"===e[s])if("/"===e[s+1]){const t=findClosingIndex(e,">",s,"Closing Tag is not closed.");let o=e.substring(s+2,t).trim();if(this.options.removeNSPrefix){const e=o.indexOf(":");-1!==e&&(o=o.substr(e+1))}this.options.transformTagName&&(o=this.options.transformTagName(o)),r&&(n=this.saveTextToParentTag(n,r,i));const a=i.substring(i.lastIndexOf(".")+1);if(o&&-1!==this.options.unpairedTags.indexOf(o))throw new Error(`Unpaired tag can not be used as closing tag: </${o}>`);let c=0;a&&-1!==this.options.unpairedTags.indexOf(a)?(c=i.lastIndexOf(".",i.lastIndexOf(".")-1),this.tagsNodeStack.pop()):c=i.lastIndexOf("."),i=i.substring(0,c),r=this.tagsNodeStack.pop(),n="",s=t}else if("?"===e[s+1]){let t=readTagExp(e,s,!1,"?>")
1879
+ ;if(!t)throw new Error("Pi Tag is not closed.");if(n=this.saveTextToParentTag(n,r,i),this.options.ignoreDeclaration&&"?xml"===t.tagName||this.options.ignorePiTags);else{const e=new XmlNode(t.tagName);e.add(this.options.textNodeName,""),t.tagName!==t.tagExp&&t.attrExpPresent&&(e[":@"]=this.buildAttributesMap(t.tagExp,i,t.tagName)),this.addChild(r,e,i,s)}s=t.closeIndex+1}else if("!--"===e.substr(s+1,3)){const t=findClosingIndex(e,"--\x3e",s+4,"Comment is not closed.");if(this.options.commentPropName){const o=e.substring(s+4,t-2);n=this.saveTextToParentTag(n,r,i),r.add(this.options.commentPropName,[{[this.options.textNodeName]:o}])}s=t}else if("!D"===e.substr(s+1,2)){const t=readDocType(e,s);this.docTypeEntities=t.entities,s=t.i}else if("!["===e.substr(s+1,2)){const t=findClosingIndex(e,"]]>",s,"CDATA is not closed.")-2,o=e.substring(s+9,t);n=this.saveTextToParentTag(n,r,i);let a=this.parseTextData(o,r.tagname,i,!0,!1,!0,!0);null==a&&(a=""),
1880
+ this.options.cdataPropName?r.add(this.options.cdataPropName,[{[this.options.textNodeName]:o}]):r.add(this.options.textNodeName,a),s=t+2}else{let o=readTagExp(e,s,this.options.removeNSPrefix),a=o.tagName;const c=o.rawTagName;let u=o.tagExp,l=o.attrExpPresent,d=o.closeIndex;this.options.transformTagName&&(a=this.options.transformTagName(a)),r&&n&&"!xml"!==r.tagname&&(n=this.saveTextToParentTag(n,r,i,!1));const p=r;p&&-1!==this.options.unpairedTags.indexOf(p.tagname)&&(r=this.tagsNodeStack.pop(),i=i.substring(0,i.lastIndexOf("."))),a!==t.tagname&&(i+=i?"."+a:a);const h=s;if(this.isItStopNode(this.options.stopNodes,i,a)){let t="";if(u.length>0&&u.lastIndexOf("/")===u.length-1)"/"===a[a.length-1]?(a=a.substr(0,a.length-1),i=i.substr(0,i.length-1),u=a):u=u.substr(0,u.length-1),s=o.closeIndex;else if(-1!==this.options.unpairedTags.indexOf(a))s=o.closeIndex;else{const r=this.readStopNodeData(e,c,d+1);if(!r)throw new Error(`Unexpected end of ${c}`);s=r.i,t=r.tagContent}const n=new XmlNode(a)
1881
+ ;a!==u&&l&&(n[":@"]=this.buildAttributesMap(u,i,a)),t&&(t=this.parseTextData(t,a,i,!0,l,!0,!0)),i=i.substr(0,i.lastIndexOf(".")),n.add(this.options.textNodeName,t),this.addChild(r,n,i,h)}else{if(u.length>0&&u.lastIndexOf("/")===u.length-1){"/"===a[a.length-1]?(a=a.substr(0,a.length-1),i=i.substr(0,i.length-1),u=a):u=u.substr(0,u.length-1),this.options.transformTagName&&(a=this.options.transformTagName(a));const e=new XmlNode(a);a!==u&&l&&(e[":@"]=this.buildAttributesMap(u,i,a)),this.addChild(r,e,i,h),i=i.substr(0,i.lastIndexOf("."))}else{const e=new XmlNode(a);this.tagsNodeStack.push(r),a!==u&&l&&(e[":@"]=this.buildAttributesMap(u,i,a)),this.addChild(r,e,i,h),r=e}n="",s=d}}else n+=e[s]}return t.child};function addChild(e,t,r,n){this.options.captureMetaData||(n=void 0);const i=this.options.updateTag(t.tagname,r,t[":@"]);!1===i||("string"==typeof i?(t.tagname=i,e.addChild(t,n)):e.addChild(t,n))}const replaceEntitiesValue=function(e){if(this.options.processEntities){
1882
+ for(let t in this.docTypeEntities){const r=this.docTypeEntities[t];e=e.replace(r.regx,r.val)}for(let t in this.lastEntities){const r=this.lastEntities[t];e=e.replace(r.regex,r.val)}if(this.options.htmlEntities)for(let t in this.htmlEntities){const r=this.htmlEntities[t];e=e.replace(r.regex,r.val)}e=e.replace(this.ampEntity.regex,this.ampEntity.val)}return e};function saveTextToParentTag(e,t,r,n){return e&&(void 0===n&&(n=0===t.child.length),void 0!==(e=this.parseTextData(e,t.tagname,r,!1,!!t[":@"]&&0!==Object.keys(t[":@"]).length,n))&&""!==e&&t.add(this.options.textNodeName,e),e=""),e}function isItStopNode(e,t,r){const n="*."+r;for(const r in e){const i=e[r];if(n===i||t===i)return!0}return!1}function tagExpWithClosingIndex(e,t,r=">"){let n,i="";for(let s=t;s<e.length;s++){let t=e[s];if(n)t===n&&(n="");else if('"'===t||"'"===t)n=t;else if(t===r[0]){if(!r[1])return{data:i,index:s};if(e[s+1]===r[1])return{data:i,index:s}}else"\t"===t&&(t=" ");i+=t}}function findClosingIndex(e,t,r,n){
1883
+ const i=e.indexOf(t,r);if(-1===i)throw new Error(n);return i+t.length-1}function readTagExp(e,t,r,n=">"){const i=tagExpWithClosingIndex(e,t+1,n);if(!i)return;let s=i.data;const o=i.index,a=s.search(/\s/);let c=s,u=!0;-1!==a&&(c=s.substring(0,a),s=s.substring(a+1).trimStart());const l=c;if(r){const e=c.indexOf(":");-1!==e&&(c=c.substr(e+1),u=c!==i.data.substr(e+1))}return{tagName:c,tagExp:s,closeIndex:o,attrExpPresent:u,rawTagName:l}}function readStopNodeData(e,t,r){const n=r;let i=1;for(;r<e.length;r++)if("<"===e[r])if("/"===e[r+1]){const s=findClosingIndex(e,">",r,`${t} is not closed`);if(e.substring(r+2,s).trim()===t&&(i--,0===i))return{tagContent:e.substring(n,r),i:s};r=s}else if("?"===e[r+1]){r=findClosingIndex(e,"?>",r+1,"StopNode is not closed.")}else if("!--"===e.substr(r+1,3)){r=findClosingIndex(e,"--\x3e",r+3,"StopNode is not closed.")}else if("!["===e.substr(r+1,2)){r=findClosingIndex(e,"]]>",r,"StopNode is not closed.")-2}else{const n=readTagExp(e,r,">");if(n){
1884
+ (n&&n.tagName)===t&&"/"!==n.tagExp[n.tagExp.length-1]&&i++,r=n.closeIndex}}}function parseValue$1(e,t,r){if(t&&"string"==typeof e){const t=e.trim();return"true"===t||"false"!==t&&toNumber(e,r)}return isExist(e)?e:""}const METADATA_SYMBOL=XmlNode.getMetaDataSymbol();function prettify(e,t){return compress(e,t)}function compress(e,t,r){let n;const i={};for(let s=0;s<e.length;s++){const o=e[s],a=propName(o);let c="";if(c=void 0===r?a:r+"."+a,a===t.textNodeName)void 0===n?n=o[a]:n+=""+o[a];else{if(void 0===a)continue;if(o[a]){let e=compress(o[a],t,c);const r=isLeafTag(e,t);void 0!==o[METADATA_SYMBOL]&&(e[METADATA_SYMBOL]=o[METADATA_SYMBOL]),o[":@"]?assignAttributes(e,o[":@"],c,t):1!==Object.keys(e).length||void 0===e[t.textNodeName]||t.alwaysCreateTextNode?0===Object.keys(e).length&&(t.alwaysCreateTextNode?e[t.textNodeName]="":e=""):e=e[t.textNodeName],void 0!==i[a]&&i.hasOwnProperty(a)?(Array.isArray(i[a])||(i[a]=[i[a]]),i[a].push(e)):t.isArray(a,c,r)?i[a]=[e]:i[a]=e}}}
1885
+ return"string"==typeof n?n.length>0&&(i[t.textNodeName]=n):void 0!==n&&(i[t.textNodeName]=n),i}function propName(e){const t=Object.keys(e);for(let e=0;e<t.length;e++){const r=t[e];if(":@"!==r)return r}}function assignAttributes(e,t,r,n){if(t){const i=Object.keys(t),s=i.length;for(let o=0;o<s;o++){const s=i[o];n.isArray(s,r+"."+s,!0,!0)?e[s]=[t[s]]:e[s]=t[s]}}}function isLeafTag(e,t){const{textNodeName:r}=t,n=Object.keys(e).length;return 0===n||!(1!==n||!e[r]&&"boolean"!=typeof e[r]&&0!==e[r])}class XMLParser{constructor(e){this.externalEntities={},this.options=buildOptions(e)}parse(e,t){if("string"==typeof e);else{if(!e.toString)throw new Error("XML data is accepted in String or Bytes[] form.");e=e.toString()}if(t){!0===t&&(t={});const r=validate$2(e,t);if(!0!==r)throw Error(`${r.err.msg}:${r.err.line}:${r.err.col}`)}const r=new OrderedObjParser(this.options);r.addExternalEntities(this.externalEntities);const n=r.parseXml(e)
1886
+ ;return this.options.preserveOrder||void 0===n?n:prettify(n,this.options)}addEntity(e,t){if(-1!==t.indexOf("&"))throw new Error("Entity value can't have '&'");if(-1!==e.indexOf("&")||-1!==e.indexOf(";"))throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if("&"===t)throw new Error("An entity with value '&' is not permitted");this.externalEntities[e]=t}static getMetaDataSymbol(){return XmlNode.getMetaDataSymbol()}}var objectToString$2=Object.prototype.toString,isArray$1=Array.isArray||function(e){return"[object Array]"===objectToString$2.call(e)};function isFunction$1(e){return"function"==typeof e}function typeStr(e){return isArray$1(e)?"array":typeof e}function escapeRegExp(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function hasProperty(e,t){return null!=e&&"object"==typeof e&&t in e}function primitiveHasOwnProperty(e,t){return null!=e&&"object"!=typeof e&&e.hasOwnProperty&&e.hasOwnProperty(t)}var regExpTest=RegExp.prototype.test
1887
+ ;function testRegExp(e,t){return regExpTest.call(e,t)}var nonSpaceRe=/\S/;function isWhitespace(e){return!testRegExp(nonSpaceRe,e)}var entityMap={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function escapeHtml$1(e){return String(e).replace(/[&<>"'`=\/]/g,function(e){return entityMap[e]})}var whiteRe=/\s*/,spaceRe=/\s+/,equalsRe=/\s*=/,curlyRe=/\s*\}/,tagRe=/#|\^|\/|>|\{|&|=|!/;function parseTemplate$1(e,t){if(!e)return[];var r,n,i,s=!1,o=[],a=[],c=[],u=!1,l=!1,d="",p=0;function h(){if(u&&!l)for(;c.length;)delete a[c.pop()];else c=[];u=!1,l=!1}function A(e){if("string"==typeof e&&(e=e.split(spaceRe,2)),!isArray$1(e)||2!==e.length)throw new Error("Invalid tags: "+e);r=new RegExp(escapeRegExp(e[0])+"\\s*"),n=new RegExp("\\s*"+escapeRegExp(e[1])),i=new RegExp("\\s*"+escapeRegExp("}"+e[1]))}A(t||mustache.tags);for(var f,g,m,y,E,b,C=new Scanner(e);!C.eos();){if(f=C.pos,
1888
+ m=C.scanUntil(r))for(var v=0,I=m.length;v<I;++v)isWhitespace(y=m.charAt(v))?(c.push(a.length),d+=y):(l=!0,s=!0,d+=" "),a.push(["text",y,f,f+1]),f+=1,"\n"===y&&(h(),d="",p=0,s=!1);if(!C.scan(r))break;if(u=!0,g=C.scan(tagRe)||"name",C.scan(whiteRe),"="===g?(m=C.scanUntil(equalsRe),C.scan(equalsRe),C.scanUntil(n)):"{"===g?(m=C.scanUntil(i),C.scan(curlyRe),C.scanUntil(n),g="&"):m=C.scanUntil(n),!C.scan(n))throw new Error("Unclosed tag at "+C.pos);if(E=">"==g?[g,m,f,C.pos,d,p,s]:[g,m,f,C.pos],p++,a.push(E),"#"===g||"^"===g)o.push(E);else if("/"===g){if(!(b=o.pop()))throw new Error('Unopened section "'+m+'" at '+f);if(b[1]!==m)throw new Error('Unclosed section "'+b[1]+'" at '+f)}else"name"===g||"{"===g||"&"===g?l=!0:"="===g&&A(m)}if(h(),b=o.pop())throw new Error('Unclosed section "'+b[1]+'" at '+C.pos);return nestTokens(squashTokens(a))}function squashTokens(e){for(var t,r,n=[],i=0,s=e.length;i<s;++i)(t=e[i])&&("text"===t[0]&&r&&"text"===r[0]?(r[1]+=t[1],r[3]=t[3]):(n.push(t),r=t));return n}
1889
+ function nestTokens(e){for(var t,r=[],n=r,i=[],s=0,o=e.length;s<o;++s)switch((t=e[s])[0]){case"#":case"^":n.push(t),i.push(t),n=t[4]=[];break;case"/":i.pop()[5]=t[2],n=i.length>0?i[i.length-1][4]:r;break;default:n.push(t)}return r}function Scanner(e){this.string=e,this.tail=e,this.pos=0}function Context(e,t){this.view=e,this.cache={".":this.view},this.parent=t}function Writer(){this.templateCache={_cache:{},set:function(e,t){this._cache[e]=t},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}Scanner.prototype.eos=function(){return""===this.tail},Scanner.prototype.scan=function(e){var t=this.tail.match(e);if(!t||0!==t.index)return"";var r=t[0];return this.tail=this.tail.substring(r.length),this.pos+=r.length,r},Scanner.prototype.scanUntil=function(e){var t,r=this.tail.search(e);switch(r){case-1:t=this.tail,this.tail="";break;case 0:t="";break;default:t=this.tail.substring(0,r),this.tail=this.tail.substring(r)}return this.pos+=t.length,t},
1890
+ Context.prototype.push=function(e){return new Context(e,this)},Context.prototype.lookup=function(e){var t,r=this.cache;if(r.hasOwnProperty(e))t=r[e];else{for(var n,i,s,o=this,a=!1;o;){if(e.indexOf(".")>0)for(n=o.view,i=e.split("."),s=0;null!=n&&s<i.length;)s===i.length-1&&(a=hasProperty(n,i[s])||primitiveHasOwnProperty(n,i[s])),n=n[i[s++]];else n=o.view[e],a=hasProperty(o.view,e);if(a){t=n;break}o=o.parent}r[e]=t}return isFunction$1(t)&&(t=t.call(this.view)),t},Writer.prototype.clearCache=function(){void 0!==this.templateCache&&this.templateCache.clear()},Writer.prototype.parse=function(e,t){var r=this.templateCache,n=e+":"+(t||mustache.tags).join(":"),i=void 0!==r,s=i?r.get(n):void 0;return null==s&&(s=parseTemplate$1(e,t),i&&r.set(n,s)),s},Writer.prototype.render=function(e,t,r,n){var i=this.getConfigTags(n),s=this.parse(e,i),o=t instanceof Context?t:new Context(t,void 0);return this.renderTokens(s,o,r,e,n)},Writer.prototype.renderTokens=function(e,t,r,n,i){
1891
+ for(var s,o,a,c="",u=0,l=e.length;u<l;++u)a=void 0,"#"===(o=(s=e[u])[0])?a=this.renderSection(s,t,r,n,i):"^"===o?a=this.renderInverted(s,t,r,n,i):">"===o?a=this.renderPartial(s,t,r,i):"&"===o?a=this.unescapedValue(s,t):"name"===o?a=this.escapedValue(s,t,i):"text"===o&&(a=this.rawValue(s)),void 0!==a&&(c+=a);return c},Writer.prototype.renderSection=function(e,t,r,n,i){var s=this,o="",a=t.lookup(e[1]);if(a){if(isArray$1(a))for(var c=0,u=a.length;c<u;++c)o+=this.renderTokens(e[4],t.push(a[c]),r,n,i);else if("object"==typeof a||"string"==typeof a||"number"==typeof a)o+=this.renderTokens(e[4],t.push(a),r,n,i);else if(isFunction$1(a)){if("string"!=typeof n)throw new Error("Cannot use higher-order sections without the original template");a=a.call(t.view,n.slice(e[3],e[5]),function(e){return s.render(e,t,r,i)}),null!=a&&(o+=a)}else o+=this.renderTokens(e[4],t,r,n,i);return o}},Writer.prototype.renderInverted=function(e,t,r,n,i){var s=t.lookup(e[1])
1892
+ ;if(!s||isArray$1(s)&&0===s.length)return this.renderTokens(e[4],t,r,n,i)},Writer.prototype.indentPartial=function(e,t,r){for(var n=t.replace(/[^ \t]/g,""),i=e.split("\n"),s=0;s<i.length;s++)i[s].length&&(s>0||!r)&&(i[s]=n+i[s]);return i.join("\n")},Writer.prototype.renderPartial=function(e,t,r,n){if(r){var i=this.getConfigTags(n),s=isFunction$1(r)?r(e[1]):r[e[1]];if(null!=s){var o=e[6],a=e[5],c=e[4],u=s;0==a&&c&&(u=this.indentPartial(s,c,o));var l=this.parse(u,i);return this.renderTokens(l,t,r,u,n)}}},Writer.prototype.unescapedValue=function(e,t){var r=t.lookup(e[1]);if(null!=r)return r},Writer.prototype.escapedValue=function(e,t,r){var n=this.getConfigEscape(r)||mustache.escape,i=t.lookup(e[1]);if(null!=i)return"number"==typeof i&&n===mustache.escape?String(i):n(i)},Writer.prototype.rawValue=function(e){return e[1]},Writer.prototype.getConfigTags=function(e){return isArray$1(e)?e:e&&"object"==typeof e?e.tags:void 0},Writer.prototype.getConfigEscape=function(e){
1893
+ return e&&"object"==typeof e&&!isArray$1(e)?e.escape:void 0};var mustache={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(e){defaultWriter.templateCache=e},get templateCache(){return defaultWriter.templateCache}},defaultWriter=new Writer;mustache.clearCache=function(){return defaultWriter.clearCache()},mustache.parse=function(e,t){return defaultWriter.parse(e,t)},mustache.render=function(e,t,r,n){if("string"!=typeof e)throw new TypeError('Invalid template! Template should be a "string" but "'+typeStr(e)+'" was given as the first argument for mustache#render(template, view, partials)');return defaultWriter.render(e,t,r,n)},mustache.escape=escapeHtml$1,mustache.Scanner=Scanner,mustache.Context=Context,mustache.Writer=Writer;let SimpleEventEmitter$1=class{constructor(){this.events={},this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),
1894
+ this.events[e].push(t),()=>{this.events[e]=this.events[e].filter(e=>e!==t)}}emit(e,t){for(const r of this.events[e]||[])r(t);for(const r of this.events["*"]||[])r(e,t)}};const DEFAULT_PROMPT_CACHE_TTL_SECONDS=60;class LangfusePromptCacheItem{constructor(e,t){this.value=e,this._expiry=Date.now()+1e3*t}get isExpired(){return Date.now()>this._expiry}}class LangfusePromptCache{constructor(){this._cache=new Map,this._defaultTtlSeconds=DEFAULT_PROMPT_CACHE_TTL_SECONDS,this._refreshingKeys=new Map}getIncludingExpired(e){return this._cache.get(e)??null}set(e,t,r){const n=r??this._defaultTtlSeconds;this._cache.set(e,new LangfusePromptCacheItem(t,n))}addRefreshingPromise(e,t){this._refreshingKeys.set(e,t),t.then(()=>{this._refreshingKeys.delete(e)}).catch(()=>{this._refreshingKeys.delete(e)})}isRefreshing(e){return this._refreshingKeys.has(e)}invalidate(e){console.log("invalidating",e,this._cache.keys());for(const t of this._cache.keys())t.startsWith(e)&&this._cache.delete(t)}}
1895
+ var LangfusePersistedProperty,ChatMessageType;!function(e){e.Props="props",e.Queue="queue",e.OptedOut="opted_out"}(LangfusePersistedProperty||(LangfusePersistedProperty={})),function(e){e.ChatMessage="chatmessage",e.Placeholder="placeholder"}(ChatMessageType||(ChatMessageType={})),mustache.escape=function(e){return e};class BasePromptClient{constructor(e,t=!1,r){this.name=e.name,this.version=e.version,this.config=e.config,this.labels=e.labels,this.tags=e.tags,this.isFallback=t,this.type=r,this.commitMessage=e.commitMessage}_transformToLangchainVariables(e){return this.escapeJsonForLangchain(e).replace(/\{\{(\w+)\}\}/g,"{$1}")}escapeJsonForLangchain(e){const t=[],r=[];let n=0;const i=e.length;for(;n<i;){const s=e[n];if("{"===s){if(n+1<i&&"{"===e[n+1]){t.push("{{"),n+=2;continue}let s=n+1;for(;s<i&&/\s/.test(e[s]);)s++;const o=s<i&&("'"===e[s]||'"'===e[s]);t.push(o?"{{":"{"),r.push(o),n+=1;continue}if("}"===s){if(n+1<i&&"}"===e[n+1]){t.push("}}"),n+=2;continue}const s=r.pop()??!1
1896
+ ;t.push(s?"}}":"}"),n+=1;continue}t.push(s),n+=1}return t.join("")}}class TextPromptClient extends BasePromptClient{constructor(e,t=!1){super(e,t,"text"),this.promptResponse=e,this.prompt=e.prompt}compile(e,t){return mustache.render(this.promptResponse.prompt,e??{})}getLangchainPrompt(e){return this._transformToLangchainVariables(this.prompt)}toJSON(){return JSON.stringify({name:this.name,prompt:this.prompt,version:this.version,isFallback:this.isFallback,tags:this.tags,labels:this.labels,type:this.type,config:this.config})}}class ChatPromptClient extends BasePromptClient{constructor(e,t=!1){const r=ChatPromptClient.normalizePrompt(e.prompt),n={...e,prompt:r};super(n,t,"chat"),this.promptResponse=n,this.prompt=r}static normalizePrompt(e){return e.map(e=>"type"in e?e:{type:ChatMessageType.ChatMessage,...e})}compile(e,t){const r=[],n=t??{};for(const e of this.prompt)if("type"in e&&e.type===ChatMessageType.Placeholder){const t=n[e.name]
1897
+ ;Array.isArray(t)&&t.length>0&&t.every(e=>"object"==typeof e&&"role"in e&&"content"in e)?r.push(...t):Array.isArray(t)&&0===t.length||(void 0!==t?r.push(JSON.stringify(t)):r.push(e))}else"role"in e&&"content"in e&&e.type===ChatMessageType.ChatMessage&&r.push({role:e.role,content:e.content});return r.map(t=>"object"==typeof t&&null!==t&&"role"in t&&"content"in t?{...t,content:mustache.render(t.content,e??{})}:t)}getLangchainPrompt(e){const t=[],r=e?.placeholders??{};for(const e of this.prompt)if("type"in e&&e.type===ChatMessageType.Placeholder){const n=r[e.name];Array.isArray(n)&&n.length>0&&n.every(e=>"object"==typeof e&&"role"in e&&"content"in e)?t.push(...n.map(e=>({role:e.role,content:this._transformToLangchainVariables(e.content)}))):Array.isArray(n)&&0===n.length||(void 0!==n?t.push(JSON.stringify(n)):t.push({variableName:e.name,optional:!1}))}else"role"in e&&"content"in e&&e.type===ChatMessageType.ChatMessage&&t.push({role:e.role,
1898
+ content:this._transformToLangchainVariables(e.content)});return t}toJSON(){return JSON.stringify({name:this.name,prompt:this.promptResponse.prompt.map(e=>{if("type"in e&&e.type===ChatMessageType.ChatMessage){const{type:t,...r}=e;return r}return e}),version:this.version,isFallback:this.isFallback,tags:this.tags,labels:this.labels,type:this.type,config:this.config})}}function assert$3(e,t){if(!e)throw new Error(t)}function removeTrailingSlash$2(e){return e?.replace(/\/+$/,"")}async function retriable$1(e,t={},r){const{retryCount:n=3,retryDelay:i=5e3,retryCheck:s=()=>!0}=t;let o=null;for(let t=0;t<n+1;t++){t>0&&(await new Promise(e=>setTimeout(e,i)),r(`Retrying ${t+1} of ${n+1}`));try{return await e()}catch(e){if(o=e,!s(e))throw e;r(`Retriable error: ${JSON.stringify(e)}`)}}throw o}function generateUUID(e){let t=(new Date).getTime(),r=e&&e.performance&&e.performance.now&&1e3*e.performance.now()||0;return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){
1899
+ let n=16*Math.random();return t>0?(n=(t+n)%16|0,t=Math.floor(t/16)):(n=(r+n)%16|0,r=Math.floor(r/16)),("x"===e?n:3&n|8).toString(16)})}function currentTimestamp(){return(new Date).getTime()}function currentISOTime$1(){return(new Date).toISOString()}function safeSetTimeout$1(e,t){const r=setTimeout(e,t);return r?.unref&&r?.unref(),r}function getEnv$1(e){return"undefined"!=typeof process&&process.env[e]?process.env[e]:"undefined"!=typeof globalThis?globalThis[e]:void 0}function configLangfuseSDK(e,t=!0){const{publicKey:r,secretKey:n,...i}=e??{},s=r??getEnv$1("LANGFUSE_PUBLIC_KEY"),o=t?n??getEnv$1("LANGFUSE_SECRET_KEY"):void 0,a=i.baseUrl??getEnv$1("LANGFUSE_BASEURL");return{publicKey:s,...t?{secretKey:o}:void 0,...{...i,baseUrl:a}}}const encodeQueryParams=e=>{const t=new URLSearchParams;return Object.entries(e??{}).forEach(([e,r])=>{null!=r&&(r instanceof Date?t.append(e,r.toISOString()):t.append(e,r.toString()))}),t.toString()};var utils$7=Object.freeze({__proto__:null,assert:assert$3,
1900
+ configLangfuseSDK,currentISOTime:currentISOTime$1,currentTimestamp,encodeQueryParams,generateUUID,getEnv:getEnv$1,removeTrailingSlash:removeTrailingSlash$2,retriable:retriable$1,safeSetTimeout:safeSetTimeout$1});const common_release_envs=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","TRIGGER_DEPLOYMENT_ID"];function getCommonReleaseEnvs(){for(const e of common_release_envs){const t=getEnv$1(e);if(t)return t}}let fs$4=null,cryptoModule=null;const dynamicImport=e=>import(e);void 0!==globalThis.Deno?Promise.all([dynamicImport("node:fs"),dynamicImport("node:crypto")]).then(([e,t])=>{fs$4=e,cryptoModule=t}).catch():"undefined"!=typeof process&&process.versions?.node?Promise.all([dynamicImport("fs"),dynamicImport("crypto")]).then(([e,t])=>{fs$4=e,cryptoModule=t}).catch():"undefined"!=typeof crypto&&(cryptoModule=crypto);class LangfuseMedia{constructor(e){
1901
+ const{obj:t,base64DataUri:r,contentType:n,contentBytes:i,filePath:s}=e;if(this.obj=t,this._mediaId=void 0,r){const[e,t]=this.parseBase64DataUri(r);this._contentBytes=e,this._contentType=t,this._source="base64_data_uri"}else if(i&&n)this._contentBytes=i,this._contentType=n,this._source="bytes";else if(s&&n){if(!fs$4)throw new Error("File system support is not available in this environment");if(!fs$4.existsSync(s))throw new Error(`File at path ${s} does not exist`);this._contentBytes=this.readFile(s),this._contentType=this._contentBytes?n:void 0,this._source=this._contentBytes?"file":void 0}else console.error("base64DataUri, or contentBytes and contentType, or filePath must be provided to LangfuseMedia")}readFile(e){try{if(!fs$4)throw new Error("File system support is not available in this environment");return fs$4.readFileSync(e)}catch(t){return void console.error(`Error reading file at path ${e}`,t)}}parseBase64DataUri(e){try{
1902
+ if(!e||"string"!=typeof e)throw new Error("Data URI is not a string");if(!e.startsWith("data:"))throw new Error("Data URI does not start with 'data:'");const[t,r]=e.slice(5).split(",",2);if(!t||!r)throw new Error("Invalid URI");const n=t.split(";");if(!n.includes("base64"))throw new Error("Data is not base64 encoded");const i=n[0];if(!i)throw new Error("Content type is empty");return[Buffer.from(r,"base64"),i]}catch(e){return console.error("Error parsing base64 data URI",e),[void 0,void 0]}}get contentLength(){return this._contentBytes?.length}get contentSha256Hash(){if(!this._contentBytes)return;if(!cryptoModule)return void console.error("Crypto support is not available in this environment");return cryptoModule.createHash("sha256").update(this._contentBytes).digest("base64")}toJSON(){
1908
1903
  return this._contentType&&this._source&&this._mediaId?`@@@langfuseMedia:type=${this._contentType}|id=${this._mediaId}|source=${this._source}@@@`:`<Upload handling failed for LangfuseMedia of type ${this._contentType}>`}static parseReferenceString(e){const t="@@@langfuseMedia:";if(!e.startsWith(t))throw new Error("Reference string does not start with '@@@langfuseMedia:type='");if(!e.endsWith("@@@"))throw new Error("Reference string does not end with '@@@'");const r=e.slice(17,-3).split("|"),n={};for(const e of r){const[t,r]=e.split("=",2);n[t]=r}if(!("type"in n&&"id"in n&&"source"in n))throw new Error("Missing required fields in reference string");return{mediaId:n.id,source:n.source,contentType:n.type}}static async resolveMediaReferences(e){const{obj:t,langfuseClient:r,maxDepth:n=10}=e;return async function e(t,i){if(i>n)return t;if("string"==typeof t){const e=/@@@langfuseMedia:.+?@@@/g,n=t.match(e);if(!n)return t;let i=t;const s=new Map;await Promise.all(n.map(async e=>{try{
1909
1904
  const t=LangfuseMedia.parseReferenceString(e),n=await r.fetchMedia(t.mediaId),i=await r.fetch(n.url,{method:"GET",headers:{}});if(200!==i.status)throw new Error("Failed to fetch media content");const o=Buffer.from(await i.arrayBuffer()).toString("base64"),a=`data:${n.contentType};base64,${o}`;s.set(e,a)}catch(t){console.warn("Error fetching media content for reference string",e,t)}}));for(const[e,t]of s.entries())i=i.replaceAll(e,t);return i}return Array.isArray(t)?Promise.all(t.map(async t=>await e(t,i+1))):"object"==typeof t&&null!==t?Object.fromEntries(await Promise.all(Object.entries(t).map(async([t,r])=>[t,await e(r,i+1)]))):t}(t,0)}}function isInSample(e,t){return void 0===t||0!==t&&(t<0||t>1||isNaN(t)?(console.warn("Sample rate must be between 0 and 1. Ignoring setting."),!0):simpleHash(e)<t)}function simpleHash(e){let t=0;for(let r=0;r<e.length;r++)t=31*t+e.charCodeAt(r)>>>0;return t=73244475*(t>>>16^t),t=73244475*(t>>>16^t),t^=t>>>16,Math.abs(t)/2147483647}
1910
1905
  const MAX_EVENT_SIZE_BYTES=getEnv$1("LANGFUSE_MAX_EVENT_SIZE_BYTES")?Number(getEnv$1("LANGFUSE_MAX_EVENT_SIZE_BYTES")):1e6,MAX_BATCH_SIZE_BYTES=getEnv$1("LANGFUSE_MAX_BATCH_SIZE_BYTES")?Number(getEnv$1("LANGFUSE_MAX_BATCH_SIZE_BYTES")):25e5,ENVIRONMENT_PATTERN=/^(?!langfuse)[a-z0-9_-]+$/,WHITELISTED_LANGFUSE_INTERNAL_ENVIRONMENTS=["langfuse-prompt-experiment"];class LangfuseFetchHttpError extends Error{constructor(e,t){super("HTTP error while fetching Langfuse: "+e.status+" and body: "+t),this.response=e,this.name="LangfuseFetchHttpError"}}class LangfuseFetchNetworkError extends Error{constructor(e){super("Network error while fetching Langfuse",e instanceof Error?{cause:e}:{}),this.error=e,this.name="LangfuseFetchNetworkError"}}function isLangfuseFetchHttpError(e){return"object"==typeof e&&"LangfuseFetchHttpError"===e.name}function isLangfuseFetchNetworkError(e){return"object"==typeof e&&"LangfuseFetchNetworkError"===e.name}function isLangfuseFetchError(e){
@@ -2072,14 +2067,14 @@ t.respondObject&&(a=zodResponseFormat(t.respondObject.schema,t.respondObject.nam
2072
2067
  r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}requireDist();const CLIENTS=["anthropic","bedrock","cerebras","deepseek","google-no-stream","llama","openai","openai-no-stream"],clientMap={anthropic:anthropicImpl,bedrock:throwUnavailableInThisVersion,cerebras:cerebrasNoStreamImpl,deepseek:deepseekImpl,"google-no-stream":throwUnavailableInThisVersion,llama:llama3_1__405bImpl,openai:openAiImpl,"openai-no-stream":openAiNoStreamImpl};function createLlmClient(e,t){const{abortSignal:r}=e;if(!t.modelClient&&t.modelName&&isEasyModelAlias(t.modelName)){const e=easyModelAliases[t.modelName];t.modelClient="openai-maybe-stream"===e?t.skipStreaming?"openai-no-stream":"openai":e,t.modelParams??={},t.modelParams.model=t.modelName}if(!t.modelClient&&t.modelName&&isComplicatedModelAlias(t.modelName)){_optionalChain$I([complicatedModelAliases[t.modelName],"optionalCall",e=>e(t)])}t.modelClient||(t.modelClient=t.skipStreaming?"openai-no-stream":"openai",
2073
2068
  t.modelParams??={},t.modelParams.model=t.modelName);let n=(0,clientMap[t.modelClient])(e,t);n=withTextValidation(n);const i=_optionalChain$I([e,"access",e=>e.cacheWith,"optionalAccess",e=>e.fs]);i&&(n=cacheWrapper(n,r,async(e,t)=>fsCache(i,e,t)));const s=_optionalChain$I([e,"access",e=>e.cacheWith,"optionalAccess",e=>e.redis]);return s&&(n=cacheWrapper(n,r,async(e,t)=>redisCache(s,e,t))),n}function withTextValidation(e){return{async streamFromMessages(t,r){for(const e of t)try{assertSafeText(e.content)}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`Refusing to send data with unsafe characters to LLM: ${t}`)}return e.streamFromMessages(t,r)},cacheKey:e.cacheKey}}function withDefaultTraceInfo(e,t){return{streamFromMessages:async(r,n)=>e.streamFromMessages(r,{...n,traceInfo:{parent:t,..._optionalChain$I([n,"optionalAccess",e=>e.traceInfo])}}),cacheKey:e.cacheKey}}function zodLiteralUnion(e){const t=e.map(e=>literalType$1(e));return unionType$1(t,{
2074
2069
  errorMap:(e,t)=>"invalid_union"===e.code?{message:`Invalid value provided for ${e.path.join(".")}`}:{message:""}})}function _nullishCoalesce$D(e,t){return null!=e?e:t()}function _optionalChain$H(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}const defaultDefaults={modelName:getDefaultModel(),modelTemperature:1,skipStreaming:!1},ModelParamSchema=Type.Object({modelName:Type.Optional(Type.String()),modelClient:Type.Optional(Type.Union([Type.Literal("anthropic"),Type.Literal("bedrock"),Type.Literal("cerebras"),Type.Literal("deepseek"),Type.Literal("google-no-stream"),Type.Literal("llama"),Type.Literal("openai"),Type.Literal("openai-no-stream")])),modelParams:Type.Optional(Type.Record(Type.String(),Type.Unknown())),modelTemperature:Type.Optional(Type.Number()),
2075
- modelReasoningEffort:Type.Optional(Type.String()),skipStreaming:Type.Optional(Type.Boolean())}),cmdParamSchema=objectType$1({cloud:booleanType$1().optional().default(!1).describe("Enables cloud execution of tool; defaults to false")}),getModelNameSchema=()=>{const e=getModelAliases(),t=getDefaultModel(),r=getModelPrefix();return zodLiteralUnion(e).default(t).describe(`The model to use (one of: ${r}auto, ${r}anthropic-reasoning, ${r}openai-reasoning)`)},modelParamSchema=objectType$1({modelName:getModelNameSchema(),modelClient:zodLiteralUnion(CLIENTS).optional().describe("The name of the LLM provider - use for access models not available via modelName"),modelParams:recordType$1(stringType$1(),unknownType$1()).optional().describe("The parameters that should be passed to the model"),modelTemperature:numberType$1().optional().default(1).describe("Controls randomness in output; higher means more creative"),
2076
- modelReasoningEffort:zodLiteralUnion(["low","medium","high"]).optional().describe("Determines how much computation the model devotes to analyzing the prompt before responding"),skipStreaming:booleanType$1().optional().default(!1).describe("If enabled, disables streaming and returns full output at once")}),getCliModelParamSchema=()=>objectType$1({modelName:getModelNameSchema()}).strict(),Defaults=ModelParamSchema,reqSchema=objectType$1({defaults:modelParamSchema.optional().default({}),steps:arrayType$1(objectType$1({name:stringType$1(),params:recordType$1(stringType$1(),unknownType$1()).optional()}))}),Req=Type.Object({defaults:Type.Optional(Defaults),steps:Type.Array(Type.Object({name:Type.String(),params:Type.Optional(Type.Record(Type.String(),Type.Unknown()))}))});function loadReq(e){const t=distExports.parse(e);strictCheck(Req,t),t.defaults=_nullishCoalesce$D(t.defaults,()=>structuredClone(defaultDefaults));const r=t
2077
- ;for(const[e,t]of entriesOf(defaultDefaults))e in r.defaults||(r.defaults[e]=structuredClone(t));return r}async function bindTools(e,t){const r=[];for(const{name:n,params:i}of t.steps){const s=await e(n);if(!s)throw new UnknownToolError(n);const o=setupToolParams(s,i,t.defaults);r.push({tool:s,params:o})}return r}function setupToolParams(e,t,r){return validateToolParams$1(e,{...structuredClone(r),...t})}function checkToolCanRun(e,t=isCliBuild()){if(t){if(_optionalChain$H([e,"optionalAccess",e=>e.denyRunIn,"optionalAccess",e=>e.includes,"call",e=>e("cli")]))throw new Error("Tool not available in CLI mode")}else if(_optionalChain$H([e,"optionalAccess",e=>e.denyRunIn,"optionalAccess",e=>e.includes,"call",e=>e("cloud")]))throw new Error("Tool not available in cloud mode")}function filterFalsyParams(e){if(!e)return e;const t={};for(const[r,n]of Object.entries(e))if(!1===n||0===n)t[r]=n;else{if(Array.isArray(n)&&0===n.length)continue;if("string"==typeof n&&""===n)continue;null!=n&&(t[r]=n)}
2078
- return t}function validateToolParams$1(e,t){const r=filterFalsyParams(t),n=modelParamSchema.merge(e.paramsSchema).safeParse(r);if(!n.success){const t=n.error.errors[0],r=t.path.map(e=>"number"==typeof e?`[${e}]`:e.toString()).join(".");throw new ExpectedError(`Error in ${e.name} param ${r}: ${t.message}`)}return n.data}Set$1("uuid",e=>"string"==typeof e&&!!e.match(UUID_REGEX));var REGEX$1=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function validate$1(e){return"string"==typeof e&&REGEX$1.test(e)}const byteToHex=[];for(let e=0;e<256;++e)byteToHex.push((e+256).toString(16).slice(1));function unsafeStringify(e,t=0){
2070
+ modelReasoningEffort:Type.Optional(Type.String()),skipStreaming:Type.Optional(Type.Boolean())}),cmdParamSchema=objectType$1({cloud:booleanType$1().optional().default(!1).describe("Enables cloud execution of tool; defaults to false")}),getModelNameSchema=()=>{const e=getDefaultModel();return stringType$1().default(e).describe("The model to use (one of: auto, anthropic-reasoning, openai-reasoning)")},modelParamSchema=objectType$1({modelName:getModelNameSchema(),modelClient:zodLiteralUnion(CLIENTS).optional().describe("The name of the LLM provider - use for access models not available via modelName"),modelParams:recordType$1(stringType$1(),unknownType$1()).optional().describe("The parameters that should be passed to the model"),modelTemperature:numberType$1().optional().default(1).describe("Controls randomness in output; higher means more creative"),
2071
+ modelReasoningEffort:zodLiteralUnion(["low","medium","high"]).optional().describe("Determines how much computation the model devotes to analyzing the prompt before responding"),skipStreaming:booleanType$1().optional().default(!1).describe("If enabled, disables streaming and returns full output at once")}),getCliModelParamSchema=()=>objectType$1({modelName:getModelNameSchema(),modelParams:recordType$1(stringType$1(),unknownType$1()).optional().describe("The parameters that should be passed to the model")}).strict(),Defaults=ModelParamSchema,reqSchema=objectType$1({defaults:modelParamSchema.optional().default({}),steps:arrayType$1(objectType$1({name:stringType$1(),params:recordType$1(stringType$1(),unknownType$1()).optional()}))}),Req=Type.Object({defaults:Type.Optional(Defaults),steps:Type.Array(Type.Object({name:Type.String(),params:Type.Optional(Type.Record(Type.String(),Type.Unknown()))}))});function loadReq(e){const t=distExports.parse(e);strictCheck(Req,t),
2072
+ t.defaults=_nullishCoalesce$D(t.defaults,()=>structuredClone(defaultDefaults));const r=t;for(const[e,t]of entriesOf(defaultDefaults))e in r.defaults||(r.defaults[e]=structuredClone(t));return r}async function bindTools(e,t){const r=[];for(const{name:n,params:i}of t.steps){const s=await e(n);if(!s)throw new UnknownToolError(n);const o=setupToolParams(s,i,t.defaults);r.push({tool:s,params:o})}return r}function setupToolParams(e,t,r){return validateToolParams$1(e,{...structuredClone(r),...t})}function checkToolCanRun(e,t=isCliBuild()){if(t){if(_optionalChain$H([e,"optionalAccess",e=>e.denyRunIn,"optionalAccess",e=>e.includes,"call",e=>e("cli")]))throw new Error("Tool not available in CLI mode")}else if(_optionalChain$H([e,"optionalAccess",e=>e.denyRunIn,"optionalAccess",e=>e.includes,"call",e=>e("cloud")]))throw new Error("Tool not available in cloud mode")}function filterFalsyParams(e){if(!e)return e;const t={};for(const[r,n]of Object.entries(e))if(!1===n||0===n)t[r]=n;else{
2073
+ if(Array.isArray(n)&&0===n.length)continue;if("string"==typeof n&&""===n)continue;null!=n&&(t[r]=n)}return t}function validateToolParams$1(e,t){const r=filterFalsyParams(t),n=modelParamSchema.merge(e.paramsSchema).safeParse(r);if(!n.success){const t=n.error.errors[0],r=t.path.map(e=>"number"==typeof e?`[${e}]`:e.toString()).join(".");throw new ExpectedError(`Error in ${e.name} param ${r}: ${t.message}`)}return n.data}Set$1("uuid",e=>"string"==typeof e&&!!e.match(UUID_REGEX));var REGEX$1=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function validate$1(e){return"string"==typeof e&&REGEX$1.test(e)}const byteToHex=[];for(let e=0;e<256;++e)byteToHex.push((e+256).toString(16).slice(1));function unsafeStringify(e,t=0){
2079
2074
  return(byteToHex[e[t+0]]+byteToHex[e[t+1]]+byteToHex[e[t+2]]+byteToHex[e[t+3]]+"-"+byteToHex[e[t+4]]+byteToHex[e[t+5]]+"-"+byteToHex[e[t+6]]+byteToHex[e[t+7]]+"-"+byteToHex[e[t+8]]+byteToHex[e[t+9]]+"-"+byteToHex[e[t+10]]+byteToHex[e[t+11]]+byteToHex[e[t+12]]+byteToHex[e[t+13]]+byteToHex[e[t+14]]+byteToHex[e[t+15]]).toLowerCase()}const rnds8Pool=new Uint8Array(256);let poolPtr=rnds8Pool.length;function rng(){return poolPtr>rnds8Pool.length-16&&(randomFillSync(rnds8Pool),poolPtr=0),rnds8Pool.slice(poolPtr,poolPtr+=16)}var native={randomUUID};function v4(e,t,r){if(native.randomUUID&&!e)return native.randomUUID();const n=(e=e||{}).random??e.rng?.()??rng();if(n.length<16)throw new Error("Random bytes length must be >= 16");return n[6]=15&n[6]|64,n[8]=63&n[8]|128,unsafeStringify(n)}const _state={};function v7(e,t,r){let n;{const e=Date.now(),i=rng();updateV7State(_state,e,i),n=v7Bytes(i,_state.msecs,_state.seq,t,r)}return unsafeStringify(n)}function updateV7State(e,t,r){
2080
2075
  return e.msecs??=-1/0,e.seq??=0,t>e.msecs?(e.seq=r[6]<<23|r[7]<<16|r[8]<<8|r[9],e.msecs=t):(e.seq=e.seq+1|0,0===e.seq&&e.msecs++),e}function v7Bytes(e,t,r,n,i=0){if(e.length<16)throw new Error("Random bytes length must be >= 16");if(n){if(i<0||i+16>n.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`)}else n=new Uint8Array(16),i=0;return t??=Date.now(),r??=127*e[6]<<24|e[7]<<16|e[8]<<8|e[9],n[i++]=t/1099511627776&255,n[i++]=t/4294967296&255,n[i++]=t/16777216&255,n[i++]=t/65536&255,n[i++]=t/256&255,n[i++]=255&t,n[i++]=112|r>>>28&15,n[i++]=r>>>20&255,n[i++]=128|r>>>14&63,n[i++]=r>>>6&255,n[i++]=r<<2&255|3&e[10],n[i++]=e[11],n[i++]=e[12],n[i++]=e[13],n[i++]=e[14],n[i++]=e[15],n}function _nullishCoalesce$C(e,t){return null!=e?e:t()}function _optionalChain$G(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,
2081
2076
  r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}async function fetchFromLocal(e,t){const r={};for(const n of _nullishCoalesce$C(t,()=>[])){const t=resolve$2(e,n);if(!t.startsWith(e))throw new Error(`bad path outside wd ${t} (${n} not in ${e})`);try{r[n]=await fsp.readFile(t,"utf8")}catch(e){}}return r}function safeEnv(){return _pick(process.env,["PATH","HOME","TMPDIR","USER"])}async function exec(e,t){const{cmd:r,argv:n,cwd:i,timeoutSecs:s=10,inactivityTimeoutSecs:o=10,fetchFiles:a=[],mergeStdStreams:c=!1,env:u=safeEnv(),signal:l}=e;if(!r&&!n)throw new Error("Must provide either cmd or argv");if(r&&n)throw new Error("Cannot provide both cmd and argv");const d=resolve$2(i);try{await fsp.access(d)}catch(e){throw new Error(`Working directory does not exist: ${d}`)}const p={cwd:d,stdio:["pipe","pipe","pipe"],env:u,detached:!0};let h,A,f,g="",m="";function y(){try{A.pid&&process.kill(-A.pid,"SIGTERM")}catch(e){if(!isErrnoException(e))throw e
2082
- ;if("ESRCH"!==e.code&&"EPERM"!==e.code)throw e}}_optionalChain$G([l,"optionalAccess",e=>e.throwIfAborted,"call",e=>e()]),h=r?["/bin/sh","-c",r]:n;const E=(e,r,n)=>{n&&clearTimeout(n);const i=setTimeout(()=>{try{y(),f=r}catch(e){_optionalChain$G([t,"optionalAccess",e=>e.warn,"call",t=>t({err:e},"unexpected error attempting to clear process group")])}},1e3*e);return i.unref(),i};let b;o&&(b=E(o,"inactivity"));const C=E(s,"process");let v;try{v=await new Promise(e=>{if(A=cp.spawn(h[0],h.slice(1),p),_optionalChain$G([A,"access",e=>e.stdin,"optionalAccess",e=>e.end,"call",e=>e()]),A.on("error",t=>e({error:t})),A.on("exit",(t,r)=>e({code:t,signal:r})),_optionalChain$G([A,"access",e=>e.stdout,"optionalAccess",e=>e.setEncoding,"call",e=>e("utf8")]),_optionalChain$G([A,"access",e=>e.stdout,"optionalAccess",e=>e.on,"call",e=>e("data",e=>{g+=e})]),_optionalChain$G([A,"access",e=>e.stderr,"optionalAccess",e=>e.setEncoding,"call",e=>e("utf8")]),
2077
+ ;if("ESRCH"!==e.code&&"EPERM"!==e.code)throw e}}_optionalChain$G([l,"optionalAccess",e=>e.throwIfAborted,"call",e=>e()]),h=r?["/bin/sh","-c",r]:n;const E=(e,r,n)=>{n&&clearTimeout(n);const i=setTimeout(()=>{try{y(),f=r}catch(e){_optionalChain$G([t,"optionalAccess",e=>e.warn,"call",t=>t({err:e},"unexpected error attempting to clear process group")])}},1e3*e);return i.unref(),i};let b;o&&(b=E(o,"inactivity"));const C=E(s,"process");let v;try{v=await new Promise(e=>{if(A=cp.spawn(h[0],h.slice(1),p),_optionalChain$G([A,"access",e=>e.stdin,"optionalAccess",e=>e.end,"call",e=>e()]),A.on("error",t=>e({error:t})),A.on("close",(t,r)=>e({code:t,signal:r})),_optionalChain$G([A,"access",e=>e.stdout,"optionalAccess",e=>e.setEncoding,"call",e=>e("utf8")]),_optionalChain$G([A,"access",e=>e.stdout,"optionalAccess",e=>e.on,"call",e=>e("data",e=>{g+=e})]),_optionalChain$G([A,"access",e=>e.stderr,"optionalAccess",e=>e.setEncoding,"call",e=>e("utf8")]),
2083
2078
  _optionalChain$G([A,"access",e=>e.stderr,"optionalAccess",e=>e.on,"call",e=>e("data",e=>{m+=e})]),c&&_optionalChain$G([A,"access",e=>e.stderr,"optionalAccess",e=>e.on,"call",e=>e("data",e=>{g+=e})]),o){const e=()=>{b=E(o,"inactivity",b)};_optionalChain$G([A,"access",e=>e.stdout,"optionalAccess",e=>e.on,"call",t=>t("data",e)]),_optionalChain$G([A,"access",e=>e.stderr,"optionalAccess",e=>e.on,"call",t=>t("data",e)])}})}finally{y(),clearTimeout(C),b&&clearTimeout(b)}const I=await fetchFromLocal(d,a);return{stdout:g,stderr:c?"":m,code:_nullishCoalesce$C(v.code,()=>{}),signal:_nullishCoalesce$C(v.signal,()=>{}),fetchedFiles:I,error:v.error,timeoutType:f}}var create$1,hasRequiredCreate,src$1,hasRequiredSrc$1;function requireCreate(){if(hasRequiredCreate)return create$1;hasRequiredCreate=1;class e{constructor(e){this.data=e}}class t{enqueue(t){if(this.head){let r=this.head;for(;r.next;)r=r.next;r.next=new e(t)}else this.head=new e(t)}dequeue(){if(!this.head)return;const e=this.head.data
2084
2079
  ;return this.head=this.head.next,e}size(){let e=0,t=this.head;for(;t;)e++,t=t.next;return e}}return create$1=(e=1)=>{const r=new t,n=()=>{++e;const t=r.dequeue();void 0!==t&&t()},i=t=>{--e,t(n)},s=()=>new Promise(e=>s.isLocked()?r.enqueue(()=>i(e)):i(e));return s.isLocked=()=>0===e,s.awaiting=()=>r.size(),s},create$1}function requireSrc$1(){if(hasRequiredSrc$1)return src$1;hasRequiredSrc$1=1;const e=requireCreate();return src$1={withLock:t=>{const r=e(t),n=async e=>{const t=await r();try{return await e()}finally{t()}};return n.isLocked=r.isLocked,n.awaiting=r.awaiting,n},createLock:e},src$1}var srcExports$1=requireSrc$1(),Utf8Stream_1,hasRequiredUtf8Stream,Parser_1,hasRequiredParser;function stripMarkdown(e){if(0===e.trim().length)return"";if(!/^```/gm.test(e))return e.trimEnd()+"\n";const t=[...e.matchAll(/```\w*\n(.*?)\n```/gs)];if(0===t.length)throw Error("Unable to extract code block. This may indicate a truncated model response.",{cause:{text:e}})
2085
2080
  ;if(t.length>1)throw Error("Unexpected model response: multiple code blocks found.",{cause:{text:e}});let r=t[0][1];return r.endsWith("\n")||(r+="\n"),r}function requireUtf8Stream(){if(hasRequiredUtf8Stream)return Utf8Stream_1;hasRequiredUtf8Stream=1;const{Transform:e}=require$$0$e,{StringDecoder:t}=require$$1$c;return Utf8Stream_1=class extends e{constructor(e){super(Object.assign({},e,{writableObjectMode:!1})),this._buffer=""}_transform(e,r,n){"string"==typeof e?this._transform=this._transformString:(this._stringDecoder=new t,this._transform=this._transformBuffer),this._transform(e,r,n)}_transformBuffer(e,t,r){this._buffer+=this._stringDecoder.write(e),this._processBuffer(r)}_transformString(e,t,r){this._buffer+=e.toString(),this._processBuffer(r)}_processBuffer(e){this._buffer&&(this.push(this._buffer,"utf8"),this._buffer=""),e(null)}_flushInput(){this._stringDecoder&&(this._buffer+=this._stringDecoder.end())}_flush(e){this._flushInput(),this._processBuffer(e)}}}
@@ -2123,7 +2118,7 @@ async function generateTestContent(e){const{testFilePath:t,specPath:r,codePaths:
2123
2118
  `;d+=await constructGeneralUserPrompt(o,r,s,i?void 0:t,u);const p=a(c).user(d);return addOrReplaceGeneratedCodeComment(await p.text(!0),relative(dirname(t),r),_nullishCoalesce$z(await o.readText(r),()=>{}),t)}const constructGeneralUserPrompt=async function(e,t,r,n,i){let s="";r&&r.trim().length>0&&(s+=`\n The user's instruction is:\n ${r}\n `);const o=n?await e.readText(n):void 0;return o&&o.trim().length>0&&n&&(s+=`\n The current version of the file is:\n ${wrapWithFileTag(n,o)}\n `),i[t]=await _asyncNullishCoalesce$4(await e.readText(t),async()=>""),s+=`\n ${formatFileContextMessage(i)}`,s};function _nullishCoalesce$y(e,t){return null!=e?e:t()}function _optionalChain$C(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}
2124
2119
  const generateTestsParamsSchema=objectType$1({spec:stringType$1().describe("Path to the spec to generate tests from, relative to the project root").transform(stripSurroundingQuotes),prompt:stringType$1().describe("Additional context to steer the LLM when generating tests").optional(),context:arrayType$1(stringType$1()).describe("Paths of any additional files that should be considered as context during generation").optional(),reference:enumType$1(["none","current"]).describe('Whether to reference existing content: "none" to regenerate from scratch, "current" to edit existing content').default("current"),testPaths:arrayType$1(stringType$1()).describe("Paths of the test files to filter on for generation (if omitted, will generate all test paths found in spec)").optional(),generateTests:common$4.generate()}),generateTestsTool={name:"generate-tests",type:"fsd",impl:generateTests,paramsSchema:generateTestsParamsSchema,description:"Generate tests for a spec",
2125
2120
  help:"Generates tests for any [@test] links in the spec.",visibility:"private",positionalParam:"spec"};async function generateTests({utils:e,fsd:t,params:r,rc:n}){const{spec:i,prompt:s,context:o,reference:a="current",testPaths:c}=r,{reporter:u}=n,l=await validateContextFiles(o,t);if(l)return n.reporter.failure(l);if(!i)return u.failure("No spec path provided. Please provide a spec path in the params",{specPath:i});const d=await getSystemPrompt(n.projectDir),p=[i],h=await Promise.all(p.map(async l=>{const{specContent:p,fileContext:h,exitCode:A}=await getStandardSpecFileContext({specPath:l,extraFiles:_nullishCoalesce$y(o,()=>[]),fsd:t,rc:n,allowEmptySpec:!1,includeLinkedContent:!0});if(A!==SUCCESS)return A;if(!p)return u.alert("error",`No spec content found for ${l}`),FAILURE;let f=specLinkedPathsFromContents(p,l,[findTestsConsidering(r)],n.projectDir);if(0===f.length)return u.alert("error",`No tests found for ${l}`),FAILURE
2126
- ;if(_optionalChain$C([c,"optionalAccess",e=>e.length])&&(f=f.filter(e=>c.includes(e.path)),0===f.length))return u.alert("info",`No matching tests to generate for ${l}`),FAILURE;const g=specLinkedPathsFromContents(p,l,[findGeneratePaths,findDescribePaths],n.projectDir);if(0===g.length)return u.alert("error",`No code path found for ${l}: did you include a @generate or @describe link?`),FAILURE;const m=calculateSpecHash(p),y=[],E=[];for(const e of f){let n;switch(e.kind){case"draft":case"impl":n=r.generateTests;break;case"locked":n=[GenerateOption.never],E.push(e)}await checkShouldUpdate({fsd:t,specPath:l,specHash:m,generate:n,generatedFilePath:e.path})&&y.push(e)}return E.length>0&&u.alert("info",`Skipped ${E.length} locked test${1===E.length?"":"s"} (always protected): ${E.map(e=>e.path).join(", ")}`),0===y.length?(u.alert("info",`No test files to generate for ${l}. ${f.length} skipped`),SUCCESS):(y.push("test-runner"),await u.cMap(y,async(r,o)=>{
2121
+ ;if(_optionalChain$C([c,"optionalAccess",e=>e.length])&&(f=f.filter(e=>c.includes(e.path)),0===f.length))return u.alert("info",`No matching tests to generate for ${l}`),FAILURE;const g=specLinkedPathsFromContents(p,l,[findGeneratePaths,findDescribePaths],n.projectDir);if(0===g.length)return u.alert("error",`No code path found for ${l}: did you include a @generate or @describe link?`),FAILURE;const m=calculateSpecHash(p),y=[],E=[];for(const e of f){let n;switch(e.kind){case"draft":n=r.generateTests;break;case"locked":n=[GenerateOption.never],E.push(e)}await checkShouldUpdate({fsd:t,specPath:l,specHash:m,generate:n,generatedFilePath:e.path})&&y.push(e)}return E.length>0&&u.alert("info",`Skipped ${E.length} locked test${1===E.length?"":"s"} (always protected): ${E.map(e=>e.path).join(", ")}`),0===y.length?(u.alert("info",`No test files to generate for ${l}. ${f.length} skipped`),SUCCESS):(y.push("test-runner"),await u.cMap(y,async(r,o)=>{
2127
2122
  if("test-runner"===r)return o(`${l} (test-runner)`),void await generateTestRunner({spec:i,fsd:t,script:e.script,systemMessage:d,projectDir:n.projectDir});const c=r.path;o(c);const u=await generateTestContent({testFilePath:c,specPath:l,codePaths:g,ignoreCurrent:"none"===a,prompt:_nullishCoalesce$y(s,()=>""),fsd:t,script:e.script,systemMessage:d,fileContext:h});await t.writeText(c,u)},{message:`Generated {progress}/{total} test files for ${l}`,publishResults:!1}),SUCCESS)}));return h.filter(e=>e===SUCCESS).length===h.length?SUCCESS:FAILURE}async function generateNewSpec(e,t,r,n,i,s){const o=formatFileContextMessage(i),a=formatUserMessage(e,t,r);return await s.script(n).user(o).user(a).text()}function formatUserMessage(e,t,r){const n=["Update the content for the following spec file so that it matches the user's goal. If adding links, note the file path that has been provided, and make sure that links are relative to its actual location."]
2128
2123
  ;return t?n.push(wrapWithFileTag(e,t)):n.push(createFileTag(e)),n.push(`GOAL: ${r}`),n.push(stripIndent`REQUIREMENTS:
2129
2124
  - Return only the updated spec file content, no other text, wrapper tags, or comments.
@@ -2142,21 +2137,21 @@ const n=e.length>0?e.map(e=>`- ${e}`).join("\n"):"No dependencies declared in th
2142
2137
  if(!e.content)throw new Error(`Action ${this.name} failed to retrieve generated code – consider halting the fix loop.`);t.add(e.content,`Result of running action ${this.name} on ${e.path}`)})}catch(t){return e.rc.logger.error({},`Memory loading failed for action "${this.name}": ${t instanceof Error?t.message:String(t)}`),n}return n}};async function getCodeContents(e,t){const r=await e.readText(t);if(!r)return[];const n=findGeneratePaths(specFromMarkdown(r));return 0===n.length?[]:await Promise.all(n.map(async r=>{const n=resolveRelativeToRoot(t,r);return{path:n,content:await e.readText(n)}}))}const codeContentsMemoryLoader=async(e,t)=>getCodeContents(e,t.spec),actionStepsConfig=[new Action$2("generate-code",[{name:generateCodeTool.name}],"Generate code from the spec based on the existing implementation",(e,t)=>({...e,generateCode:t.generateCode,codePaths:t.targetCodeFiles}),codeContentsMemoryLoader),new Action$2("generate-code-from-scratch",[{name:generateCodeTool.name
2143
2138
  }],"Generate code from the spec from scratch. Ignore the existing implementation. May be useful if you cant fix the issue after several attempts.",(e,t)=>({...e,generateCode:t.generateCode,codePaths:t.targetCodeFiles,reference:"none"}),codeContentsMemoryLoader),new Action$2("generate-tests",[{name:generateTestsTool.name}],"Generate tests from the spec",(e,t)=>({...e,generateTests:t.generateTests,testPaths:e.tests instanceof Array&&e.tests.every(e=>"string"==typeof e)?[...e.tests,...t.targetTestFiles]:t.targetTestFiles})),new Action$2("edit-spec",[{name:primitiveEditSpecTool.name},{name:generateTestsTool.name}],"Edit the spec file, then triggers tests re-generation for consistency")];actionStepsConfig.map(e=>e.name);class ActionExecutor{constructor(e=[],t,r){if(this.memory=t,this.availableActions=actionStepsConfig.filter(t=>t.tools.every(t=>e.includes(t.name))),0===this.availableActions.length)throw new Error("No available actions found based on allowed tools");this.planContext=r}
2144
2139
  getAvailableActions(){return this.availableActions.map(e=>e.name)}getAvailableActionsWithDescriptions(){return this.availableActions.map((e,t)=>`${t+1}. ${e.name}: ${e.description}`)}async run(e,t){const r=this.availableActions.find(t=>t.name===e);if(!r)throw new Error(`Action ${e} is not available but has to be`);const n=await r.run(t,this.memory,this.planContext);return n!==SUCCESS&&t.rc.logger.error({},`Action "${e}" failed with exit code ${n}. Halting execution of this action.`),n}}class Memory{__init(){this.history=[]}constructor(e=7){Memory.prototype.__init.call(this),this.maxSize=e}add(e,t){this.history.push({message:e,description:t}),this.history.length>this.maxSize&&this.history.shift()}formatToString(e=!0){const t=e?this.history:this.history.slice(0,-1);return 0===t.length?"No history available.":t.map((e,t)=>{let r=`\n --- Message ${t+1} ---\n`;return e.description&&(r+=`\nDescription: ${e.description}`),r+=`\n${e.message}`,r}).join("\n\n")}getHistory(){
2145
- return[...this.history]}}var ObservationStatus;!function(e){e.OK="OK";e.FAILED="FAILED"}(ObservationStatus||(ObservationStatus={}));class Observer{constructor(e,t){this.name=e,this.description=t||"No description available."}async run(e,t,r){const n=await e.rc.lookupTool(this.name);if(!n)throw new Error(`Tool '${this.name}' not found via lookup`);await runTool({tool:n,params:{...e.params,testCommand:r.testCommand}},{rc:e.rc,fsd:e.fsd});return await this.parseResult(e,t)}}class RunTestsObserver extends Observer{async parseResult(e,t){const{spec:r}=e.params;let n;try{n=await readTestResults(r,e.fsd)}catch(t){throw e.rc.logger.error({error:t},"Fix loop run tests observer failed to read valid test results"),new Error(`Fix loop run tests observer failed to read valid test results: ${t instanceof Error?t.message:String(t)}`)}const i=0===n.numFailingTests&&0===n.numErrorTests?ObservationStatus.OK:ObservationStatus.FAILED,s={regularFailingTests:n.numFailingTests-(n.numFailingImplTests||0),
2146
- regularErrorTests:n.numErrorTests-(n.numErrorImplTests||0),implFailingTests:n.numFailingImplTests||0,implErrorTests:n.numErrorImplTests||0},o=i===ObservationStatus.FAILED&&0===s.regularFailingTests&&0===s.regularErrorTests&&(s.implFailingTests>0||s.implErrorTests>0);return t.add(JSON.stringify(n),`Result of running observer named ${this.name}`),{name:this.name,status:i,observation:n,onlyImplTestsFailing:o,testFailureCounts:s}}}const observationStepsConfig=[new RunTestsObserver("test","Run tests for the spec")];observationStepsConfig.map(e=>e.name);class ObservationsExecutor{constructor(e=[],t,r){this.memory=t,this.availableObservations=observationStepsConfig.filter(t=>!e.includes(t.name)),this.planContext=r}getAvailableObservations(){return this.availableObservations.map(e=>e.name)}async runObservation(e,t){const r=this.availableObservations.find(t=>t.name===e);if(!r)throw new Error(`Observation ${e} is not available but has to be`);return r.run(t,this.memory,this.planContext)}}
2147
- async function _asyncNullishCoalesce$3(e,t){return null!=e?e:await t()}const planStepSchema=objectType$1({action:stringType$1().describe("The name of the action to execute."),reasoning:stringType$1().describe("The reasoning for choosing this action and its parameters"),instruction:stringType$1().describe("The instruction for the action to execute")}),planSchema={name:"plan",schema:objectType$1({plan:arrayType$1(planStepSchema).describe("The sequence of actions to execute to fix the issue")})};class PlanGenerator{constructor(e,t,r,n,i=1,s=""){this.rc=e,this.fsd=t,this.memory=r,this.utils=n,this.planLength=i,this.goal=s}async generatePlan(e,t,r,n){if(!this.rc.projectConfig)throw new Error("No config found. Run `tessl init` to create one.");const i=await this.fsd.readText(e);if(!i)throw new Error(`Spec file not found: ${e}`)
2148
- ;const s=r.observationPath?await _asyncNullishCoalesce$3(await this.fsd.readText(r.observationPath),async()=>""):JSON.stringify(r.observation,null,2),o=this.createSystemMessage(),a=this.createUserMessage(i,t,s,n,this.goal,r),c=await this.utils.script(o).user(a).object(planSchema);this.rc.logger.info({},"Generated plan:");const u=JSON.stringify(c,null,2);return this.rc.logger.info({},u),this.memory.add(u,"Generated plan"),c}createUserMessage(e,t,r,n,i,s){const o=n.join("\n"),a=this.memory.formatToString(!1);let c="";if(s.testFailureCounts&&void 0!==s.onlyImplTestsFailing){const e=s.testFailureCounts;c=`\n\nImplementation Test Status:\n- Regular spec tests: ${e.regularFailingTests+e.regularErrorTests>0?"FAILING":"PASSING"}\n- Implementation tests: ${e.implFailingTests+e.implErrorTests>0?"FAILING":"PASSING"}\n${s.onlyImplTestsFailing?"- Only implementation tests are failing":""}`}
2149
- return`\n<spec>\n${e}\n</spec>\n\n\n\n<memory>\n${a}\n</memory>\n\n\n\n<observer-response>\n${r}${c}\n</observer-response>\n\n\n\n<tools>\n${o}\n\n\n\nYou also have access to an additional tool named **"terminate"**.\nUse this when either:\n0. You observe that errors are related to missing dependencies—for example, when a package is not installed or when imports come from the path you can't make imports from. \n - If that's the case, output in your reasoning only what dependencies are missing, do not suggest how to install them.\n1. You believe the issue cannot be resolved using the provided tools\n2. Only implementation tests are failing - suggest updating implementation details or removing outdated impl tests\n3. The failures originate from a fundamental contradiction between spec requirements and implementation details\n\nIf you choose **"terminate"**, you **must not** include any other actions in the plan.\nBe sure to provide a clear and concise reasoning for selecting it.\n</tools>\n\n\n\n<test-files>\n${t.map(e=>`- ${e}`).join("\n")}\n</test-files>\n\n\n\n<goal>\n${i}\n</goal>\n\n\n\nPlease generate a plan to address the issue using the format specified in the system prompt.\n`
2140
+ return[...this.history]}}var ObservationStatus;!function(e){e.OK="OK";e.FAILED="FAILED"}(ObservationStatus||(ObservationStatus={}));class Observer{constructor(e,t){this.name=e,this.description=t||"No description available."}async run(e,t,r){const n=await e.rc.lookupTool(this.name);if(!n)throw new Error(`Tool '${this.name}' not found via lookup`);await runTool({tool:n,params:{...e.params,testCommand:r.testCommand}},{rc:e.rc,fsd:e.fsd});return await this.parseResult(e,t)}}class RunTestsObserver extends Observer{async parseResult(e,t){const{spec:r}=e.params;let n;try{n=await readTestResults(r,e.fsd)}catch(t){throw e.rc.logger.error({error:t},"Fix loop run tests observer failed to read valid test results"),new Error(`Fix loop run tests observer failed to read valid test results: ${t instanceof Error?t.message:String(t)}`)}const i=0===n.numFailingTests&&0===n.numErrorTests?ObservationStatus.OK:ObservationStatus.FAILED,s={failingTests:n.numFailingTests||0,errorTests:n.numErrorTests||0}
2141
+ ;return t.add(JSON.stringify(n),`Result of running observer named ${this.name}`),{name:this.name,status:i,observation:n,testFailureCounts:s}}}const observationStepsConfig=[new RunTestsObserver("test","Run tests for the spec")];observationStepsConfig.map(e=>e.name);class ObservationsExecutor{constructor(e=[],t,r){this.memory=t,this.availableObservations=observationStepsConfig.filter(t=>!e.includes(t.name)),this.planContext=r}getAvailableObservations(){return this.availableObservations.map(e=>e.name)}async runObservation(e,t){const r=this.availableObservations.find(t=>t.name===e);if(!r)throw new Error(`Observation ${e} is not available but has to be`);return r.run(t,this.memory,this.planContext)}}async function _asyncNullishCoalesce$3(e,t){return null!=e?e:await t()}const planStepSchema=objectType$1({action:stringType$1().describe("The name of the action to execute."),reasoning:stringType$1().describe("The reasoning for choosing this action and its parameters"),
2142
+ instruction:stringType$1().describe("The instruction for the action to execute")}),planSchema={name:"plan",schema:objectType$1({plan:arrayType$1(planStepSchema).describe("The sequence of actions to execute to fix the issue")})};class PlanGenerator{constructor(e,t,r,n,i=1,s=""){this.rc=e,this.fsd=t,this.memory=r,this.utils=n,this.planLength=i,this.goal=s}async generatePlan(e,t,r,n){if(!this.rc.projectConfig)throw new Error("No config found. Run `tessl init` to create one.");const i=await this.fsd.readText(e);if(!i)throw new Error(`Spec file not found: ${e}`);const s=r.observationPath?await _asyncNullishCoalesce$3(await this.fsd.readText(r.observationPath),async()=>""):JSON.stringify(r.observation,null,2),o=this.createSystemMessage(),a=this.createUserMessage(i,t,s,n,this.goal),c=await this.utils.script(o).user(a).object(planSchema);this.rc.logger.info({},"Generated plan:");const u=JSON.stringify(c,null,2);return this.rc.logger.info({},u),this.memory.add(u,"Generated plan"),c}
2143
+ createUserMessage(e,t,r,n,i){const s=n.join("\n")
2144
+ ;return`\n<spec>\n${e}\n</spec>\n\n\n\n<memory>\n${this.memory.formatToString(!1)}\n</memory>\n\n\n\n<observer-response>\n${r}\n</observer-response>\n\n\n\n<tools>\n${s}\n\n\n\nYou also have access to an additional tool named **"terminate"**.\nUse this when either:\n0. You observe that errors are related to missing dependencies—for example, when a package is not installed or when imports come from the path you can't make imports from. \n - If that's the case, output in your reasoning only what dependencies are missing, do not suggest how to install them.\n1. You believe the issue cannot be resolved using the provided tools\n2. Only implementation tests are failing - suggest updating implementation details or removing outdated impl tests\n3. The failures originate from a fundamental contradiction between spec requirements and implementation details\n\nIf you choose **"terminate"**, you **must not** include any other actions in the plan.\nBe sure to provide a clear and concise reasoning for selecting it.\n</tools>\n\n\n\n<test-files>\n${t.map(e=>`- ${e}`).join("\n")}\n</test-files>\n\n\n\n<goal>\n${i}\n</goal>\n\n\n\nPlease generate a plan to address the issue using the format specified in the system prompt.\n`
2150
2145
  }createSystemMessage(){
2151
2146
  return`\nYou are a software fix planner.\n\nYou will receive:\n- A content of the spec file wrapped in <spec></spec> tags. Spec defines the API of the component, explains nature of tests and provides context for the component. Spec is the source of truth.\n- A memory of the conversation, wrapped in <memory></memory> tags so that you could see what happened. Memory can include generated code from previous fix iterations so you can see and understand context of the current fix iteration.\n- An <observer-response></observer-response> section, which contains the actual issue or failure observed in the current solution. This is the latest feedback from the system\n- A list of available tools, wrapped in <tools></tools> tags.\n- An optional list of test files <test-files></test-files>, listing the subset of test files that we are going to be regenerating if we are going to limit them.\n- An optional user goal <goal></goal>, describing the intended outcome or the problem.\n\nYour task is to analyze the spec, analyze the observer response, analyze the available tools, and propose a step-by-step **plan to fix the issue** using the provided tools.\n\nFor each step in the plan:\n- Select a relevant tool.\n- Provide a **short, clear reasoning** for choosing this tool.\n- Write a concise **instruction** that tells the executor exactly what to do when running this tool.\n\nEach plan step must follow this format:\n{\n"tool": "<tool name>",\n"reasoning": "<why this tool is needed>",\n"instruction": "<clear, relevant instruction>"\n}\n**Instruction Examples:**\n- For "generate-code", if unit tests are failing, the instruction could be: "Update the code to pass the tests."\n\n**Output Requirements:**\n- Return the plan as a **JSON array** of tools in the format above.\n- You may include up to ${this.planLength} tools in the plan.\n\n**Important:**\n- Your plan must satisfy the spec first.\n- Code or tests can easily contradict spec (due to a bug in code/tests) that's why you can use the toolings to decide how to fix the issue.\n if you observe feedback from failed tests it can be not due to a bug in the code but rather a problem with tests not following spec properly. **Your plan must satisfy the spec first.**\n- If you already tried to generate code multiple times (based on your memory), it might be a good idea to change the strategy and re-generate tests or edit the spec. Don't be afraid to change the strategy.\n- if toolset allows to edit spec, then you can edit spec in case there are clear contradictions inside the spec that prevent from generating a valid solution.\n- Use memory to see what actions were taken in the past and result they produced in order to outline your plan\n\n**Implementation Test Handling:**\n- Implementation tests have "_impl" suffix in their file names and test implementation details marked with { .impl } tags in the spec\n- If ONLY implementation tests are failing (regular spec tests pass), this indicates:\n 1. The core functionality works correctly per the spec\n 2. Implementation details have changed or are inconsistent with current behavior\n- In this scenario, prefer the "terminate" action with reasoning that suggests:\n - Using \`tessl document --include-impl-details {spec-path}\` to update implementation details\n - Or deleting the failing implementation tests if they're no longer relevant\n - Implementation details should follow the actual working code, not drive it\n`
2152
2147
  }}function _optionalChain$B(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}const primitiveToolNames=[primitiveEditSpecTool.name,generateCodeTool.name,generateTestsTool.name],defaultTools=["generate-code"],fixLoopParamsSchema=objectType$1({spec:stringType$1().describe("Path to the spec, relative to the project root").transform(stripSurroundingQuotes),goal:stringType$1().describe("A string describing the goal that user wants to achieve through the fix loop").optional(),tests:arrayType$1(stringType$1()).describe("List of test files that should be worked on during the fix loop. Others are ignored").optional(),code:arrayType$1(stringType$1()).describe("List of code files that should be worked on during the fix loop. Others are ignored").optional(),
2153
2148
  tools:arrayType$1(stringType$1().refine(e=>primitiveToolNames.includes(e),e=>({message:`Invalid tool: ${e}. Must be one of: ${primitiveToolNames.join(", ")}`}))).describe("A list of primitive tools available for the fix loop").default(defaultTools),maxPlanLength:numberType$1().describe("The maximum number of tools in a plan").optional(),iterations:numberType$1().describe("The number of iterations to run the fix loop").default(3),testCommand:stringType$1().optional().describe(testCommandDescription),context:arrayType$1(stringType$1()).describe("Paths of any additional files that should be considered as context during generation").optional(),generateTests:common$4.generate(),generateCode:common$4.generate()}),fixTool={name:"fix",type:"fsd",impl:fixLoop,paramsSchema:fixLoopParamsSchema,description:"Fix failing tests for a single spec by updating the code",visibility:"private"};async function fixLoop({fsd:e,rc:t,utils:r,params:n}){
2154
2149
  const{spec:i,goal:s,iterations:o,maxPlanLength:a,tools:c,testCommand:u,context:l}=n,d=await validateContextFiles(l,e);if(d)return t.reporter.failure(d);let p,h;try{p=await resolveTargetedFiles(t,e,i,[findTestsConsidering(n)],n.tests)}catch(e){return t.reporter.failure(`${e instanceof Error?e.message:`Unknown error resolving ${i} tests`}`,{specPath:i,tests:n.tests})}try{h=await resolveTargetedFiles(t,e,i,[findGeneratePaths],n.code)}catch(e){return t.reporter.failure(e instanceof Error?e.message:`Unknown error resolving ${i} generated files`,{specPath:i,code:n.code})}t.reporter.message(`Defined ${o} agentic loop iterations`);const A=new Memory(7);(await getCodeContents(e,i)).forEach(e=>{e.content&&A.add(e.content,`Current source code in ${e.path}`)});const f=new ActionExecutor(c,A,{generateTests:n.generateTests,generateCode:n.generateCode,targetTestFiles:p,targetCodeFiles:h,testCommand:u});t.reporter.message(`Available actions: ${f.getAvailableActions().join(", ")}`)
2155
2150
  ;const g=new ObservationsExecutor([],A,{testCommand:u}),m=new PlanGenerator(t,e,A,r,a,s);for(let s=0;s<o+1;s++){t.reporter.message(`Running iteration ${s+1} of the fix loop`),t.reporter.message("First, run tests and inspect the results.");const a=await g.runObservation("test",{fsd:e,rc:t,utils:r,params:n});if(a.status===ObservationStatus.OK)return t.reporter.success(["All tests are passing"]);if(s===o)return t.reporter.failure(`Reached maximum iterations (${o}) without fixing the issue`);t.reporter.message("test tool observation failed indicating some issues likely with failed tests. Trying to generate a plan to address the problem.");const c=await m.generatePlan(i,p,a,f.getAvailableActionsWithDescriptions());if(0===c.plan.length)throw new Error("Something went wrong: No plan was generated, process should have terminated.");t.reporter.message(`Executing plan with ${c.plan.length} actions`);let u=0;for(const s of c.plan){if(u++,
2156
- "terminate"===_optionalChain$B([s,"optionalAccess",e=>e.action]))return a.onlyImplTestsFailing?t.reporter.failure(["Fix loop terminated: Only implementation tests are failing.",`Reasoning: ${s.reasoning}`,"","Suggested actions:",`- Use 'tessl document --include-impl-details -s ${i}' to update implementation details in the spec`,"- Or delete the failing implementation tests if they're no longer relevant"].join("\n")):t.reporter.failure(`Something went wrong. Reasoning: ${s.reasoning}`);const o=getFullTestResultsPath(i);if(await t.reporter.wait(`Executing action ${u}/${c.plan.length}: ${s.action}`,async()=>f.run(s.action,{fsd:e,rc:t,utils:r,params:{...n,goal:s.instruction,context:[...n.context||[],o]}}))!==SUCCESS)return t.reporter.failure("Fix loop interrupted: executed action returned unexpected failure")}}return t.reporter.success(["Fix loop completed successfully"])}async function resolveTargetedFiles(e,t,r,n,i){const{projectDir:s}=e,o=getPaths(await specLinkedPaths(t,r,n,s))
2157
- ;if(void 0===i)return o;const a=[];for(const e of i)o.some(t=>t===e)||a.push(e);if(a.length>0)throw new Error(`spec ${r} does not contain links for the following files: ${a.join(" ")}`);return i}const createParamsSchema=objectType$1({spec:stringType$1().describe(`Path to the spec to be created. You should choose a path that is relative to the project root. Must be a ${SPEC_FILE_EXTENSION} file. If none is provided, one will be inferred from the prompt.`).transform(stripSurroundingQuotes).refine(e=>e.endsWith(SPEC_FILE_EXTENSION),{message:`Spec file must end with ${SPEC_FILE_EXTENSION} extension`}).optional(),prompt:stringType$1().describe("A short description of what you want to build").transform(stripSurroundingQuotes),context:arrayType$1(stringType$1()).describe("Paths of any additional files that should be considered as context during generation").optional(),force:booleanType$1().describe("Whether to overwrite the spec if it already exists").optional()}),createTool={name:"create",
2158
- type:"fsd",impl:create,paramsSchema:createParamsSchema,description:"Create a new spec from a natural language prompt",visibility:"public"};async function create({fsd:e,params:t,rc:r,utils:{script:n}}){const{context:i,prompt:s,force:o}=t,{reporter:a,lfTrace:c}=r;if(!await hasBootstrapRun(e))return a.alert("error",BOOTSTRAP_NOT_RUN_ERROR),c.event({name:"bootstrapNotRun",input:{prompt:s}}),FAILURE;const u=await validateContextFiles(i,e);if(u)return r.reporter.failure(u);a.heading("Creating a new spec");let l=t.spec;if(l)a.alert("info",`Using provided spec path: ${l}`);else try{l=await inferSpecPath({rc:r,specPrompt:s,fsd:e,script:n}),r.reporter.alert("info",`Inferred spec path as: ${l}`)}catch(e){return r.logger.error({err:e},"Failed to infer spec path"),r.reporter.failure(`Failed to infer spec path: ${getMessageFromMaybeError(e)}`)}if(await e.readText(l)&&!o)return r.reporter.failure(`Spec ${l} already exists. Use --force to overwrite.`,{specPath:l});const d=await runTool({
2159
- tool:primitiveEditSpecTool,params:{...t,spec:l,goal:s,reference:"none",context:i,init:!0}},{rc:r,fsd:e});return d===SUCCESS?r.reporter.success([`Spec created at ${l}`,"Next: Run `tessl build` to generate code and tests"]):d}async function inferSpecPath({rc:e,specPrompt:t,fsd:r,script:n}){const i={name:"inferSpecSchema",schema:objectType$1({specPath:stringType$1().transform(stripSurroundingQuotes).refine(e=>e.endsWith(SPEC_FILE_EXTENSION),{message:`Spec file must end with ${SPEC_FILE_EXTENSION} extension`}).refine(e=>!path__default.isAbsolute(e),{message:"Spec path must be relative"})})};return e.reporter.wait("Inferring spec path",async()=>(await n(await getSystemPrompt(e.projectDir,r)).user(TASK_CONTEXT).user(await projectFilesContext(r)).user(inferSpecUserPrompt(t)).object(i)).specPath)}const TASK_CONTEXT=stripIndent`
2151
+ "terminate"===_optionalChain$B([s,"optionalAccess",e=>e.action]))return t.reporter.failure(`Something went wrong. Reasoning: ${s.reasoning}`);const o=getFullTestResultsPath(i);if(await t.reporter.wait(`Executing action ${u}/${c.plan.length}: ${s.action}`,async()=>f.run(s.action,{fsd:e,rc:t,utils:r,params:{...n,goal:s.instruction,context:[...n.context||[],o]}}))!==SUCCESS)return t.reporter.failure("Fix loop interrupted: executed action returned unexpected failure")}}return t.reporter.success(["Fix loop completed successfully"])}async function resolveTargetedFiles(e,t,r,n,i){const{projectDir:s}=e,o=getPaths(await specLinkedPaths(t,r,n,s));if(void 0===i)return o;const a=[];for(const e of i)o.some(t=>t===e)||a.push(e);if(a.length>0)throw new Error(`spec ${r} does not contain links for the following files: ${a.join(" ")}`);return i}const createParamsSchema=objectType$1({
2152
+ spec:stringType$1().describe(`Path to the spec to be created. You should choose a path that is relative to the project root. Must be a ${SPEC_FILE_EXTENSION} file. If none is provided, one will be inferred from the prompt.`).transform(stripSurroundingQuotes).refine(e=>e.endsWith(SPEC_FILE_EXTENSION),{message:`Spec file must end with ${SPEC_FILE_EXTENSION} extension`}).optional(),prompt:stringType$1().describe("A short description of what you want to build").transform(stripSurroundingQuotes),context:arrayType$1(stringType$1()).describe("Paths of any additional files that should be considered as context during generation").optional(),force:booleanType$1().describe("Whether to overwrite the spec if it already exists").optional()}),createTool={name:"create",type:"fsd",impl:create,paramsSchema:createParamsSchema,description:"Create a new spec from a natural language prompt",visibility:"public"};async function create({fsd:e,params:t,rc:r,utils:{script:n}}){
2153
+ const{context:i,prompt:s,force:o}=t,{reporter:a,lfTrace:c}=r;if(!await hasBootstrapRun(e))return a.alert("error",BOOTSTRAP_NOT_RUN_ERROR),c.event({name:"bootstrapNotRun",input:{prompt:s}}),FAILURE;const u=await validateContextFiles(i,e);if(u)return r.reporter.failure(u);a.heading("Creating a new spec");let l=t.spec;if(l)a.alert("info",`Using provided spec path: ${l}`);else try{l=await inferSpecPath({rc:r,specPrompt:s,fsd:e,script:n}),r.reporter.alert("info",`Inferred spec path as: ${l}`)}catch(e){return r.logger.error({err:e},"Failed to infer spec path"),r.reporter.failure(`Failed to infer spec path: ${getMessageFromMaybeError(e)}`)}if(await e.readText(l)&&!o)return r.reporter.failure(`Spec ${l} already exists. Use --force to overwrite.`,{specPath:l});const d=await runTool({tool:primitiveEditSpecTool,params:{...t,spec:l,goal:s,reference:"none",context:i,init:!0}},{rc:r,fsd:e})
2154
+ ;return d===SUCCESS?r.reporter.success([`Spec created at ${l}`,"Next: Run `tessl build` to generate code and tests"]):d}async function inferSpecPath({rc:e,specPrompt:t,fsd:r,script:n}){const i={name:"inferSpecSchema",schema:objectType$1({specPath:stringType$1().transform(stripSurroundingQuotes).refine(e=>e.endsWith(SPEC_FILE_EXTENSION),{message:`Spec file must end with ${SPEC_FILE_EXTENSION} extension`}).refine(e=>!path__default.isAbsolute(e),{message:"Spec path must be relative"})})};return e.reporter.wait("Inferring spec path",async()=>(await n(await getSystemPrompt(e.projectDir,r)).user(TASK_CONTEXT).user(await projectFilesContext(r)).user(inferSpecUserPrompt(t)).object(i)).specPath)}const TASK_CONTEXT=stripIndent`
2160
2155
  Your goal is to come up with the spec path for a new specification markdown file based on the prompt that we are going to use to create the spec.
2161
2156
 
2162
2157
  You must follow the following rules:
@@ -2195,7 +2190,7 @@ codeDiff:s.diff(),testsDiff:i.diff(),params:r,err:t},"Error thrown during the fi
2195
2190
  context:arrayType$1(stringType$1()).describe("Paths of any additional files that should be considered as context during generation").optional(),specifyMissingDependencies:booleanType$1().optional().default(!1).describe("If true, automatically add missing dependencies to the spec when verify-deps finds violations")}).merge(testParamsSchema.pick({timeoutSecs:!0,inactivityTimeoutSecs:!0})),buildTool={name:"build",type:"fsd",impl:build,paramsSchema:buildParamsSchema,description:"Generate or refresh code for each [@generate] link in the spec and runs any existing tests. If no spec is provided, all project specs will be built.",visibility:"public",positionalParam:"spec"};async function build({fsd:e,params:t,rc:r}){const{spec:n}=t,{reporter:i,lfTrace:s}=r;if(!await hasBootstrapRun(e))return i.alert("error",BOOTSTRAP_NOT_RUN_ERROR),s.event({name:"bootstrapNotRun",input:{spec:_nullishCoalesce$w(n,()=>"")}}),FAILURE;if(n&&n.length>0){const t=await getSpecsMissingGenerateLinks(n,e,i)
2196
2191
  ;if(t.length>0)return i.alert("error","Invalid spec input"),i.list(`The following ${pluralize$1("spec",t.length)} ${pluralize$1("has",t.length)} no @generate links and cannot be built:`,t),FAILURE}let o=n||[];if(0===o.length&&(i.alert("info","No specs provided, looking for specs that need to be rebuilt"),o=await findSpecsToBuild(r,e,[findGeneratePaths],async(r,n,i)=>checkShouldUpdate({specPath:r,specHash:n,generatedFilePath:i,generate:t.generateCode,fsd:e}))),!o.length)return i.success(["All specs are up to date"]);i.alert("info",`Building ${o.length} ${pluralize$1("spec",o.length)}`);const a=[],c=[];await i.cMap(o,async(n,s)=>{s(`Building ${n}...`);try{const s={...t,generateTests:[GenerateOption.never]};await buildSpec(n,{fsd:e,params:s,rc:r})!==SUCCESS?(c.push(n),i.alert("error",`Failed to build spec ${n}`)):a.push(n)}catch(e){c.push(n);const t=e instanceof Error?e.message:cerealiseError(e);i.alert("error",`Failed to build spec ${n}: ${t}`)}},{
2197
2192
  message:"Processing {progress}/{total} specs",publishResults:!1});const u=[];return a.length>0?u.push(`Successfully built ${a.length} ${pluralize$1("spec",a.length)}:`,...a.map(e=>` - ${e}`)):i.hideOverview(),0===c.length?i.success([...u,"All [@generate] links have been processed"]):(i.summary([...u,`Failed to build ${c.length} ${pluralize$1("spec",c.length)}:`,...c.map(e=>` - ${e}`)]),FAILURE)}function _nullishCoalesce$v(e,t){return null!=e?e:t()}const buildTestsParamsSchema=objectType$1({spec:arrayType$1(stringType$1().transform(stripSurroundingQuotes).refine(e=>e.endsWith(SPEC_FILE_EXTENSION),{message:`Spec files must end with ${SPEC_FILE_EXTENSION}`})).describe("Path to the spec file to build tests for. If omitted, all project specs will be processed.").optional(),maxIterations:numberType$1().describe("Max improvement passes to attempt to fix generated tests").default(0),testCommand:stringType$1().describe(testCommandDescription).optional(),
2198
- generateTests:common$4.generate().default([GenerateOption.missing,GenerateOption.outdated,GenerateOption.dirty]),context:arrayType$1(stringType$1()).describe("Paths of any additional files that should be considered as context during generation").optional()}).merge(testParamsSchema.pick({timeoutSecs:!0,inactivityTimeoutSecs:!0})),buildTestsTool={name:"build-tests",type:"fsd",impl:buildTests,paramsSchema:buildTestsParamsSchema,description:"Generate tests for [@test] links in the spec without generating code. Focuses specifically on test generation and running existing tests. If no spec is provided, all project specs will be processed.",visibility:"public",positionalParam:"spec"};function getGenerateOptionsForTestKind(e,t){switch(e){case"draft":case"impl":return t.generateTests;case"locked":return[GenerateOption.never];default:assertUnreachable(e)}}async function buildTests({fsd:e,params:t,rc:r}){const{spec:n,context:i}=t,{reporter:s,lfTrace:o}=r
2193
+ generateTests:common$4.generate().default([GenerateOption.missing,GenerateOption.outdated,GenerateOption.dirty]),context:arrayType$1(stringType$1()).describe("Paths of any additional files that should be considered as context during generation").optional()}).merge(testParamsSchema.pick({timeoutSecs:!0,inactivityTimeoutSecs:!0})),buildTestsTool={name:"build-tests",type:"fsd",impl:buildTests,paramsSchema:buildTestsParamsSchema,description:"Generate tests for [@test] links in the spec without generating code. Focuses specifically on test generation and running existing tests. If no spec is provided, all project specs will be processed.",visibility:"public",positionalParam:"spec"};function getGenerateOptionsForTestKind(e,t){switch(e){case"draft":return t.generateTests;case"locked":return[GenerateOption.never];default:assertUnreachable(e)}}async function buildTests({fsd:e,params:t,rc:r}){const{spec:n,context:i}=t,{reporter:s,lfTrace:o}=r
2199
2194
  ;if(!await hasBootstrapRun(e))return s.alert("error",BOOTSTRAP_NOT_RUN_ERROR),o.event({name:"bootstrapNotRun",input:{spec:_nullishCoalesce$v(n,()=>"")}}),FAILURE;const a=await validateContextFiles(i,e);if(a)return r.reporter.failure(a);let c=n||[];if(0===c.length&&(s.alert("info","No specs provided, looking for specs that need to be rebuilt"),c=await findSpecsToBuild(r,e,[findTests],async(r,n,i)=>await checkShouldUpdate({specPath:r,specHash:n,generatedFilePath:i.path,generate:getGenerateOptionsForTestKind(i.kind,t),fsd:e}))),!c.length)return s.success(["All specs are up to date"]);s.alert("info",`Building tests for ${c.length} ${pluralize$1("spec",c.length)}`);const u=[],l=[];await s.cMap(c,async(n,i)=>{i(`Building tests for ${n}...`);try{const i={...t,generateCode:[GenerateOption.never],specifyMissingDependencies:!1};await buildSpec(n,{fsd:e,params:i,rc:r})!==SUCCESS?(l.push(n),s.alert("error",`Failed to build tests for spec ${n}`)):u.push(n)}catch(e){l.push(n)
2200
2195
  ;const t=e instanceof Error?e.message:cerealiseError(e);s.alert("error",`Failed to build tests for spec ${n}: ${t}`)}},{message:"Processing {progress}/{total} specs",publishResults:!1});const d=[];return u.length>0?d.push(`Successfully built tests for ${u.length} ${pluralize$1("spec",u.length)}:`,...u.map(e=>` - ${e}`)):s.hideOverview(),0===l.length?s.success([...d,"All [@test] links have been processed"]):(s.summary([...d,`Failed to build tests for ${l.length} ${pluralize$1("spec",l.length)}:`,...l.map(e=>` - ${e}`)]),FAILURE)}const createSpecParamsSchema=objectType$1({spec:stringType$1().describe(`Path to the spec to be created. You should choose a path that is relative to the project root and consistent with the layout specified in ${AGENTS_MD_FILENAME}. Must be a ${SPEC_FILE_EXTENSION} file.`).transform(stripSurroundingQuotes).refine(e=>e.endsWith(SPEC_FILE_EXTENSION),{message:`Spec file must end with ${SPEC_FILE_EXTENSION} extension`}),
2201
2196
  goal:stringType$1().describe("A short description of what you want to build"),context:arrayType$1(stringType$1()).describe("Paths of any additional files that should be considered as context during generation").optional(),force:booleanType$1().describe("Whether to overwrite the spec if it already exists").optional(),language:stringType$1().describe("The language that this spec should target.").optional()}),createSpecTool={name:"create-spec",type:"fsd",impl:createSpec$1,paramsSchema:createSpecParamsSchema,description:"Create a single spec based on an initial prompt",visibility:"private"};async function createSpec$1({fsd:e,params:t,rc:r}){const{spec:n,goal:i,force:s,context:o,language:a}=t,c=await validateContextFiles(o,e);if(c)return r.reporter.failure(c);r.reporter.message(`Creating spec at ${n}`);if(await e.readText(n)&&!s)return r.reporter.failure(`Spec ${n} already exists. Use --force to overwrite.`,{specPath:n});let u=stripIndent`
@@ -2422,10 +2417,10 @@ this.#or=createLocalJWKSet(this.#ar.jwks)))}pendingFetch(){return!!this.#nr}cool
2422
2417
  get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>r.pendingFetch(),enumerable:!0,configurable:!1},jwks:{value:()=>r.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}async function initialiseDeviceAuthFlow(e){const t=await fetch("https://api.workos.com/user_management/authorize/device",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e})}),r=await t.json();return{deviceCode:r.device_code,userCode:r.user_code,verificationUri:r.verification_uri,verificationUriComplete:r.verification_uri_complete,expiresIn:r.expires_in,interval:r.interval}}async function pollForTokens({authClientId:e,deviceCode:t,expiresIn:r,interval:n,signal:i}){const s=AbortSignal.timeout(r);for(;;){i&&throwWhenAborted(i);const r=await _fetchTokens({authClientId:e,deviceCode:t,timeoutSignal:s});if("access_token"in r)return{accessToken:r.access_token,
2423
2418
  refreshToken:r.refresh_token};if(!("error"in r))return{error:"Authorization failed"};switch(r.error){case"authorization_pending":await sleepWithAbort(n,i);break;case"slow_down":n+=1e3,await sleepWithAbort(n,i);break;case"access_denied":return{error:"Access denied"};case"expired_token":return{error:"Expired token"};default:return{error:"Authorization failed"}}}}async function _fetchTokens(e){try{const t=await fetch("https://api.workos.com/user_management/authenticate",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:e.deviceCode,client_id:e.authClientId}),signal:e.timeoutSignal});return await t.json()}catch(e){if(e instanceof Error&&"TimeoutError"===e.name)return{error:"Authorization timed out"};throw e}}async function authenticateWithRefreshToken(e,t){const r=await fetch("https://api.workos.com/user_management/authenticate",{method:"POST",headers:{
2424
2419
  "Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",client_id:e,refresh_token:t,user_agent:"tessl.cli"})}),n=await r.json();if(r.ok){const e=n;return{user:{id:e.user.id,email:e.user.email,firstName:e.user.first_name,lastName:e.user.last_name},accessToken:e.access_token,refreshToken:e.refresh_token}}return{error:getErrorFromResponseBody(n)||"Failed to authenticate with refresh token"}}function getAuthClientId(){const e="client_01HXSHDD9KV92A4892CWHZZDDR";if(!e.startsWith("client_"))throw new Error("Auth client id not set to appropriate value - please check `WORKOS_CLIENT_ID` env var");return e}function getErrorFromResponseBody(e){if("object"==typeof e&&e){if("error_description"in e&&"string"==typeof e.error_description)return e.error_description;if("error"in e&&"string"==typeof e.error)return e.error}}async function validateAccessTokenWithJWKS(e,t){const r=createRemoteJWKSet(new URL(`https://api.workos.com/sso/jwks/${t}`)),{payload:n}=await jwtVerify(e,r,{
2425
- issuer:"https://api.workos.com"});return n}function _optionalChain$w(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}async function createDotenvFile(e,t,r,n){e.debug({},"provisioning dotenv file");const i=getTesslClient(t,n),s=await i.GET("/experimental/cli-env");if("error"in s)throw e.error({err:s.error},"Failed to fetch dotenv data"),new Error("Failed to setup environment file: please try again");const o=_optionalChain$w([s,"access",e=>e.data,"optionalAccess",e=>e.data,"optionalAccess",e=>e.attributes,"optionalAccess",e=>e.envVars]);if(!o||"object"!=typeof o)throw e.warn({},"No environment variables received from API"),new Error("Failed to setup environment file: please try again")
2426
- ;const a=`# Generated on ${(new Date).toISOString()} from ${t.TESSL_BASE_API_URL}`,c=Object.entries(o).map(([e,t])=>`${e}="${t}"`).join("\n"),u=c?`${a}\n${c}`:a,l=join(r,"dotenv");await mkdir(dirname$1(l),{recursive:!0}),await writeFile(l,u,"utf-8"),await chmod(l,384),e.debug({path:l},"Created dotenv file")}const DEFAULT_TESSL_PATHS={globalConfigDir:getDefaultGlobalConfigDir(),projDir:process.cwd()},CredsSchema=Type.Object({accessToken:Type.String(),refreshToken:Type.String(),user:Type.Object({id:Type.String(),email:Type.String(),firstName:Type.Optional(Type.String()),lastName:Type.Optional(Type.String()),username:Type.Optional(Type.String())})}),AUTH_FILENAME="api-credentials.json",AUTH_PERMISSIONS=384,readAuth=async(e=DEFAULT_TESSL_PATHS.globalConfigDir)=>{const t=resolve$3(e,AUTH_FILENAME),r=await readFile$2(t),n=JSON.parse(r.toString());return strictCheck(CredsSchema,n),n},writeAuth=async(e,t,r=DEFAULT_TESSL_PATHS.globalConfigDir)=>{const n=resolve$3(r,AUTH_FILENAME)
2427
- ;return t.debug({path:n},"writing auth"),await writeText(n,JSON.stringify(e),AUTH_PERMISSIONS),e},updateAuth=async(e,t,r=DEFAULT_TESSL_PATHS.globalConfigDir)=>{const n=resolve$3(r,AUTH_FILENAME),i={...await readAuth(r),...e};return t.debug({path:n},"updating auth"),await writeText(n,JSON.stringify(i),AUTH_PERMISSIONS),i},getCreds=async(e,t,r=DEFAULT_TESSL_PATHS.globalConfigDir)=>{if(process.env.TESSL_SIMULATE_LOGOUT)return null;if(process.env.TESSL_TOKEN)return{accessToken:process.env.TESSL_TOKEN,refreshToken:"",user:{id:"token-user",email:"token@example.com"}};try{const n=await readAuth(r);return await refreshSessionIfNeeded(e,t,n,r)}catch(t){e.error({err:t},"error getting credentials");try{await clearAuth(e,r)}catch(t){e.debug({err:t},"failed to clear auth file")}return null}},isAuthed=async(e,t,r)=>null!==await getCreds(e,t,r),clearAuth=async(e,t=DEFAULT_TESSL_PATHS.globalConfigDir)=>{const r=resolve$3(t,AUTH_FILENAME);e.debug({path:r},"clearing auth"),
2428
- existsSync$1(r)?await unlink(r):e.debug({path:r},"auth file does not exist, nothing to clear")};async function refreshSessionIfNeeded(e,t,r,n=DEFAULT_TESSL_PATHS.globalConfigDir){const{accessToken:i,refreshToken:s}=r,o=t.WORKOS_CLIENT_ID;if(!o)throw new Error("no auth client id configured");try{e.debug({},"Validating access token with JWKS");const t=(await validateAccessTokenWithJWKS(i,o)).exp;if(t){if(!(Math.floor(Date.now()/1e3)>=t-5))return e.debug({},"Access token valid, not expired"),r;e.debug({},"Access token expired, will refresh")}else e.debug({},"No expiry claim in token payload, will refresh")}catch(t){e.debug({err:t},"JWKS validation failed, will refresh token")}const a=await authenticateWithRefreshToken(o,s);if("error"in a)throw e.error({response:a},"error authenticating with refresh token"),new Error("error while authenticating with refresh token");const{accessToken:c,refreshToken:u}=a,l=await updateAuth({accessToken:c,refreshToken:u},e,n)
2420
+ issuer:"https://api.workos.com"});return n}function _optionalChain$w(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}async function createDotenvFile(e,t,r,n){e.debug({},"provisioning dotenv file");const i=getTesslClient(t,n),s=await i.GET("/experimental/cli-env");if("error"in s)throw e.error({err:s.error},"Failed to fetch dotenv data"),new Error("Failed to setup environment file: please try again");const o=_optionalChain$w([s,"access",e=>e.data,"optionalAccess",e=>e.data,"optionalAccess",e=>e.attributes,"optionalAccess",e=>e.envVars]);if(!o||"object"!=typeof o)throw e.warn({},"No environment variables received from API"),new Error("Failed to setup environment file: please try again");const a=`# Generated on ${(new Date).toISOString()} from ${t.TESSL_BASE_API_URL}`;let c=o
2421
+ ;"development"===t.NODE_ENV&&(c=Object.fromEntries(Object.entries(c).filter(([e])=>"LANGFUSE_PROXY_TOKEN"!==e)));const u=Object.entries(c).map(([e,t])=>`${e}="${t}"`).join("\n"),l=u?`${a}\n${u}`:a,d=join(r,"dotenv");await mkdir(dirname$1(d),{recursive:!0}),await writeFile(d,l,"utf-8"),await chmod(d,384),e.debug({path:d},"Created dotenv file")}const DEFAULT_TESSL_PATHS={globalConfigDir:getDefaultGlobalConfigDir(),projDir:process.cwd()},CredsSchema=Type.Object({accessToken:Type.String(),refreshToken:Type.String(),user:Type.Object({id:Type.String(),email:Type.String(),firstName:Type.Optional(Type.String()),lastName:Type.Optional(Type.String()),username:Type.Optional(Type.String())})}),AUTH_FILENAME="api-credentials.json",AUTH_PERMISSIONS=384,readAuth=async(e=DEFAULT_TESSL_PATHS.globalConfigDir)=>{const t=resolve$3(e,AUTH_FILENAME),r=await readFile$2(t),n=JSON.parse(r.toString());return strictCheck(CredsSchema,n),n},writeAuth=async(e,t,r=DEFAULT_TESSL_PATHS.globalConfigDir)=>{
2422
+ const n=resolve$3(r,AUTH_FILENAME);return t.debug({path:n},"writing auth"),await writeText(n,JSON.stringify(e),AUTH_PERMISSIONS),e},updateAuth=async(e,t,r=DEFAULT_TESSL_PATHS.globalConfigDir)=>{const n=resolve$3(r,AUTH_FILENAME),i={...await readAuth(r),...e};return t.debug({path:n},"updating auth"),await writeText(n,JSON.stringify(i),AUTH_PERMISSIONS),i},getCreds=async(e,t,r=DEFAULT_TESSL_PATHS.globalConfigDir)=>{if(process.env.TESSL_SIMULATE_LOGOUT)return null;if(process.env.TESSL_TOKEN)return{accessToken:process.env.TESSL_TOKEN,refreshToken:"",user:{id:"token-user",email:"token@example.com"}};try{const n=await readAuth(r);return await refreshSessionIfNeeded(e,t,n,r)}catch(t){e.error({err:t},"error getting credentials");try{await clearAuth(e,r)}catch(t){e.debug({err:t},"failed to clear auth file")}return null}},isAuthed=async(e,t,r)=>null!==await getCreds(e,t,r),clearAuth=async(e,t=DEFAULT_TESSL_PATHS.globalConfigDir)=>{const r=resolve$3(t,AUTH_FILENAME);e.debug({path:r
2423
+ },"clearing auth"),existsSync$1(r)?await unlink(r):e.debug({path:r},"auth file does not exist, nothing to clear")};async function refreshSessionIfNeeded(e,t,r,n=DEFAULT_TESSL_PATHS.globalConfigDir){const{accessToken:i,refreshToken:s}=r,o=t.WORKOS_CLIENT_ID;if(!o)throw new Error("no auth client id configured");try{e.debug({},"Validating access token with JWKS");const t=(await validateAccessTokenWithJWKS(i,o)).exp;if(t){if(!(Math.floor(Date.now()/1e3)>=t-5))return e.debug({},"Access token valid, not expired"),r;e.debug({},"Access token expired, will refresh")}else e.debug({},"No expiry claim in token payload, will refresh")}catch(t){e.debug({err:t},"JWKS validation failed, will refresh token")}const a=await authenticateWithRefreshToken(o,s);if("error"in a)throw e.error({response:a},"error authenticating with refresh token"),new Error("error while authenticating with refresh token");const{accessToken:c,refreshToken:u}=a,l=await updateAuth({accessToken:c,refreshToken:u},e,n)
2429
2424
  ;return await createDotenvFile(e,t,n||DEFAULT_TESSL_PATHS.globalConfigDir,c),e.debug({},"Token refreshed successfully"),l}function _nullishCoalesce$p(e,t){return null!=e?e:t()}function _optionalChain$v(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}const SPINNER_OPTIONS={hideCursor:!1,discardStdin:!1},loginCommand=new Command$1({name:"login",summary:"Login to Tessl; requires a Tessl account. See https://www.tessl.io/ to request access.",flags:{},requiresConfig:!1,handler:async({monitoring:{logger:e},env:t,tesslClient:r})=>{const n=arg(flagToSpec(GlobalFlags),{permissive:!0})["--global-config-dir"]||DEFAULT_TESSL_PATHS.globalConfigDir;if(await handleTokenLogin(e,t,n))return SUCCESS;return await login({logger:e,env:t,globalConfigDir:n,tesslClient:r})}})
2430
2425
  ;async function login({logger:e,env:t,globalConfigDir:r=DEFAULT_TESSL_PATHS.globalConfigDir,tesslClient:n}){const i=ora({text:"Initializing login flow",...SPINNER_OPTIONS}).start(),s=getAuthClientId();let o;try{o=await initialiseDeviceAuthFlow(s)}catch(t){return e.error({err:t},"Failed to initialize device auth flow"),i.fail("Failed to initialize device auth flow"),FAILURE}i.stop();let a=!1;try{await open(o.verificationUriComplete),a=!0}catch(e){}const c=stripIndent`
2431
2426
  If you have access to the full Tessl framework, you can log in at the following URL. (To request access, go to https://www.tessl.io/)
@@ -2439,14 +2434,14 @@ existsSync$1(r)?await unlink(r):e.debug({path:r},"auth file does not exist, noth
2439
2434
  ${cyan$1(o.userCode)}
2440
2435
  `;process.stdout.write(c+"\n\n"),i.start(),i.text=`Waiting for ${a?"confirmation":"code"}…`;const u=new AbortController,l=()=>{u.abort()};let d,p,h;process.on("SIGINT",l);try{const t=await pollForTokens({authClientId:s,deviceCode:o.deviceCode,expiresIn:1e3*o.expiresIn,interval:Math.min(1e3*o.interval,5e3),signal:u.signal});if("error"in t)return e.error({err:t.error},"Login failed while polling for tokens"),i.fail(t.error),FAILURE;({accessToken:d,refreshToken:p}=t)}catch(t){return t instanceof Error&&"aborted"===t.message?(i.fail("Login cancelled"),FAILURE):(e.error({err:t},"Login failed while polling for tokens"),i.fail("Login failed"),FAILURE)}finally{process.off("SIGINT",l)}try{n.setAccessToken(d);const t=await n.GET("/v1/users/me");if(t.error)return e.error({errMsg:_nullishCoalesce$p(_optionalChain$v([t,"access",e=>e.error,"access",e=>e.errors,"access",e=>e[0],"optionalAccess",e=>e.detail]),()=>"Unknown error")},"Failed to get user"),i.fail("Failed to get user"),FAILURE
2441
2436
  ;h=t.data.data}catch(t){return e.error({err:t},"Failed to get user"),i.fail("Failed to get user"),FAILURE}i.text="Storing credentials";try{await writeAuth({user:{id:h.id,email:h.attributes.email,firstName:_nullishCoalesce$p(h.attributes.firstName,()=>{}),lastName:_nullishCoalesce$p(h.attributes.lastName,()=>{}),username:_nullishCoalesce$p(h.attributes.username,()=>{})},accessToken:d,refreshToken:p},e,r)}catch(t){return e.error({err:t},"Failed to store credentials"),i.fail("Failed to store credentials"),FAILURE}i.text="Setting up";try{await createDotenvFile(e,{WORKOS_CLIENT_ID:s,TESSL_BASE_API_URL:t.TESSL_BASE_API_URL,NODE_ENV:t.NODE_ENV},r,d)}catch(t){return e.error({err:t},"Failed to provision environment"),i.fail("Failed to provision environment"),FAILURE}return i.succeed("Login successful"),SUCCESS}async function handleTokenLogin(e,t,r){const n=t.TESSL_TOKEN;if(!n)return!1;e.debug({},"TESSL_TOKEN found, creating dotenv file directly");const i=ora({text:"Setting up with TESSL_TOKEN",
2442
- ...SPINNER_OPTIONS}).start();try{return await createDotenvFile(e,t,r,n),i.succeed("Login successful with TESSL_TOKEN"),!0}catch(t){return e.error({err:t},"Failed to create dotenv file with TESSL_TOKEN"),i.fail("Login failed"),!0}}const logoutCommand=new Command$1({name:"logout",summary:"Logout from Tessl",flags:{},requiresConfig:!1,handler:async({monitoring:{logger:e},globalConfigDir:t})=>(await render(jsxRuntimeExports.jsx(LogoutFlow,{logger:e,globalConfigDir:t})).waitUntilExit(),SUCCESS)}),LogoutFlow=({logger:e,globalConfigDir:t})=>{const[r,n]=reactExports.useState("loading");return reactExports.useEffect(()=>{(async()=>{await clearAuth(e,t),n("success")})()},[e,t]),"loading"===r?jsxRuntimeExports.jsx(Text,{children:"Logging out..."}):jsxRuntimeExports.jsx(Text,{color:"green",children:"✅ Logout successful"})},tokenCommand=new Command$1({name:"token",summary:"Generate a new API key",flags:{},requiresConfig:!1,
2443
- handler:async({monitoring:{logger:e},tesslClient:t,isAuthenticated:r})=>(await render(jsxRuntimeExports.jsx(TokenFlow,{logger:e,tesslClient:t,isAuthenticated:r})).waitUntilExit(),SUCCESS)}),TokenFlow=({logger:e,tesslClient:t,isAuthenticated:r})=>{const[n,i]=reactExports.useState("loading"),[s,o]=reactExports.useState(null),[a,c]=reactExports.useState(null);return reactExports.useEffect(()=>{(async()=>{if(r)try{i("generating");const r=new Date;r.setDate(r.getDate()+29);const n=await t.POST("/v1/users/keys",{body:{expiryDate:r.toISOString()}});if("error"in n)return e.error({err:n.error},"Failed to create API key"),c("Failed to create API key"),void i("error");o(n.data.data.attributes.apiKey),i("success")}catch(t){e.debug({err:t},"failed to generate API key"),t instanceof Error&&t.message.includes("No access token found")?i("not-authenticated"):(c(t instanceof Error?t.message:"Unknown error"),i("error"))}else i("not-authenticated")})()},[e,t,r]),"loading"===n?jsxRuntimeExports.jsx(Text,{
2444
- children:"Checking authentication..."}):"generating"===n?jsxRuntimeExports.jsx(Text,{children:"Generating API key..."}):"success"===n&&s?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Text,{color:"green",children:"✅ API key generated successfully!"}),jsxRuntimeExports.jsx(Text,{children:s}),jsxRuntimeExports.jsx(Text,{color:"gray",children:"This key expires in 30 days. Store it securely!"})]}):"error"===n?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Text,{color:"red",children:"❌ Failed to generate API key"}),a&&jsxRuntimeExports.jsx(Text,{color:"red",children:a})]}):"not-authenticated"===n?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Text,{color:"yellow",children:"❌ You are not logged in"}),jsxRuntimeExports.jsx(Text,{color:"gray",children:"Run 'tessl login' to log in"})]}):jsxRuntimeExports.jsx(Text,{children:"Unknown status"})};function CommandText({children:e}){
2445
- return jsxRuntimeExports.jsx(Text,{color:"blue",children:e})}const whoamiCommand=new Command$1({name:"whoami",summary:"Show Tessl authentication status",flags:{},requiresConfig:!1,handler:async({user:e,isAuthenticated:t})=>(await render(jsxRuntimeExports.jsx(WhoAmIFlow,{user:e,isAuthenticated:t})).waitUntilExit(),SUCCESS)}),WhoAmIFlow=({user:e,isAuthenticated:t})=>{if(t&&e){const t=e.firstName||e.lastName?`${e.firstName} ${e.lastName}`.trim():"";return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Text,{color:"green",children:"✅ You are logged in to Tessl"}),e.username&&jsxRuntimeExports.jsxs(Text,{children:["Username: ",e.username]}),jsxRuntimeExports.jsxs(Text,{children:["Email: ",e.email]}),jsxRuntimeExports.jsxs(Text,{children:["User ID: ",e.id]}),t&&jsxRuntimeExports.jsxs(Text,{children:["Name: ",t]}),!1,jsxRuntimeExports.jsxs(Text,{color:"gray",children:["Run ",jsxRuntimeExports.jsx(CommandText,{children:"tessl logout"})," to log out"]})]})}
2446
- return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Text,{color:"yellow",children:"❌ You are not logged in"}),!1,jsxRuntimeExports.jsxs(Text,{color:"gray",children:["Run ",jsxRuntimeExports.jsx(CommandText,{children:"tessl login"})," to log in"]})]})};function _nullishCoalesce$o(e,t){return null!=e?e:t()}const STOCK_PHRASES=["Cluck!","Have you tried turning it off and on again?","Anyone for Honest Burgers?","Rules make us a civilization, Rob.","Time to tile that bathroom!","....doughnuts?","These models may be 'large' but they still can't understand why I crossed the road","Kevin broke it","I'm available for weddings, bar mitzvahs, birthdays....","The OG eggen","As a large language model I can't help you with this request","Fiat clux!"],getRandomStockPhrase=()=>STOCK_PHRASES[Math.floor(Math.random()*STOCK_PHRASES.length)],cluckCommand=new Command$1({name:"cluck",summary:"Cluck!",requiresConfig:!1,flags:{message:{type:String,short:"m",
2447
- description:"💬"}},handler:async({args:{message:e}})=>(render(jsxRuntimeExports.jsx(()=>jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text,{color:"yellow",children:" xx\n / .|_\n /(_)_&lt;\n / (\n ((____.-' )\n \\\\ /\n \\'-.-.-'`/\n _ \\______/\n(_) _|_\\_\n''''''''''''''''"}),jsxRuntimeExports.jsx(Box,{paddingTop:2,paddingLeft:5,children:jsxRuntimeExports.jsx(Text,{color:"green",children:_nullishCoalesce$o(e,()=>getRandomStockPhrase())})})]}),{})),Promise.resolve(SUCCESS))});function _optionalChain$u(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}const SUPPORTED_SHELLS=["bash","zsh"];function detectShell(){
2448
- const e=_optionalChain$u([process,"access",e=>e.env,"access",e=>e.SHELL,"optionalAccess",e=>e.split,"call",e=>e("/"),"access",e=>e.pop,"call",e=>e()])||"bash";return SUPPORTED_SHELLS.includes(e)?e:"bash"}function getCommandData(){const e={};for(const[t,r]of Object.entries(standaloneGeneralCommands))e[t]=r.summary;for(const[t,r]of Object.entries(standaloneToolCommands))e[t]=r.summary;const t=Object.keys(e),r=Object.keys(structuredCommands),n={};for(const[e,t]of Object.entries(structuredCommands)){n[e]={};for(const[r,i]of Object.entries(t))n[e][r]=i.summary}const i={},s=builtInTools(),o=Object.values(s).filter(e=>"public"===e.visibility);for(const{name:e,description:t}of o)i[e]=t||`Run the ${e} tool`;const a=o.map(({name:e})=>e);return{allCommands:[...t,...r,...a].sort(),standaloneCommandsWithDesc:e,structuredActions:r,structuredResources:n,toolAliasesWithDesc:i}}function generateBashCompletionScript(){
2449
- const{allCommands:e,structuredActions:t,structuredResources:r}=getCommandData(),n="tessl"
2437
+ ...SPINNER_OPTIONS}).start();try{return await createDotenvFile(e,t,r,n),i.succeed("Login successful with TESSL_TOKEN"),!0}catch(t){return e.error({err:t},"Failed to create dotenv file with TESSL_TOKEN"),i.fail("Login failed"),!0}}const logoutCommand=new Command$1({name:"logout",summary:"Logout from Tessl",flags:{},requiresConfig:!1,handler:async({monitoring:{logger:e},globalConfigDir:t})=>{try{await clearAuth(e,t),render(jsxRuntimeExports.jsx(Text,{color:"green",children:"✅ Logout successful"}))}catch(t){return e.error({err:t},"Failed to logout"),render(jsxRuntimeExports.jsx(Text,{color:"red",children:"❌ Logout failed. See the logs for more details."})),FAILURE}return SUCCESS}});async function renderUntilExit(e){const t=render(e);let r=!1;const n=()=>{r=!0,t.unmount(),process.off("SIGINT",n),process.off("SIGTERM",n)};process.on("SIGINT",n),process.on("SIGTERM",n);try{if(await t.waitUntilExit(),r)return FAILURE}finally{n()}return SUCCESS}const tokenCommand=new Command$1({name:"token",
2438
+ summary:"Generate a new API key",flags:{},requiresConfig:!1,handler:async({monitoring:{logger:e},tesslClient:t,isAuthenticated:r})=>await renderUntilExit(jsxRuntimeExports.jsx(TokenFlow,{logger:e,tesslClient:t,isAuthenticated:r}))}),TokenFlow=({logger:e,tesslClient:t,isAuthenticated:r})=>{const[n,i]=reactExports.useState("loading"),[s,o]=reactExports.useState(null),[a,c]=reactExports.useState(null),{exit:u}=useApp();return reactExports.useEffect(()=>{(async()=>{if(r)try{i("generating");const r=new Date;r.setDate(r.getDate()+29);const n=await t.POST("/v1/users/keys",{body:{expiryDate:r.toISOString()}});if("error"in n)return e.error({err:n.error},"Failed to create API key"),c("Failed to create API key"),void i("error");o(n.data.data.attributes.apiKey),i("success")}catch(t){e.debug({err:t},"failed to generate API key"),t instanceof Error&&t.message.includes("No access token found")?i("not-authenticated"):(c(t instanceof Error?t.message:"Unknown error"),i("error"))
2439
+ }else i("not-authenticated")})()},[e,t,r]),reactExports.useEffect(()=>{"error"===n&&u(new Error("Failed to generate API key")),"not-authenticated"===n&&u(new Error("You are not logged in")),"success"===n&&u()},[n,u]),"loading"===n?jsxRuntimeExports.jsx(Text,{children:"Checking authentication..."}):"generating"===n?jsxRuntimeExports.jsx(Text,{children:"Generating API key..."}):"success"===n&&s?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Text,{color:"green",children:"✅ API key generated successfully!"}),jsxRuntimeExports.jsx(Text,{children:s}),jsxRuntimeExports.jsx(Text,{color:"gray",children:"This key expires in 30 days. Store it securely!"})]}):"error"===n?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Text,{color:"red",children:"❌ Failed to generate API key"}),a&&jsxRuntimeExports.jsx(Text,{color:"red",children:a})]}):"not-authenticated"===n?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{
2440
+ children:[jsxRuntimeExports.jsx(Text,{color:"yellow",children:"❌ You are not logged in"}),jsxRuntimeExports.jsx(Text,{color:"gray",children:"Run 'tessl login' to log in"})]}):jsxRuntimeExports.jsx(Text,{children:"Unknown status"})};function CommandText({children:e}){return jsxRuntimeExports.jsx(Text,{color:"blue",children:e})}const whoamiCommand=new Command$1({name:"whoami",summary:"Show Tessl authentication status",flags:{},requiresConfig:!1,handler:async({user:e,isAuthenticated:t})=>(render(jsxRuntimeExports.jsx(WhoAmIFlow,{user:e,isAuthenticated:t})),Promise.resolve(SUCCESS))}),WhoAmIFlow=({user:e,isAuthenticated:t})=>{if(t&&e){const t=e.firstName||e.lastName?`${e.firstName} ${e.lastName}`.trim():"";return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Text,{color:"green",children:"✅ You are logged in to Tessl"}),e.username&&jsxRuntimeExports.jsxs(Text,{children:["Username: ",e.username]}),jsxRuntimeExports.jsxs(Text,{children:["Email: ",e.email]
2441
+ }),jsxRuntimeExports.jsxs(Text,{children:["User ID: ",e.id]}),t&&jsxRuntimeExports.jsxs(Text,{children:["Name: ",t]}),!1,jsxRuntimeExports.jsxs(Text,{color:"gray",children:["Run ",jsxRuntimeExports.jsx(CommandText,{children:"tessl logout"})," to log out"]})]})}return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Text,{color:"yellow",children:"❌ You are not logged in"}),!1,jsxRuntimeExports.jsxs(Text,{color:"gray",children:["Run ",jsxRuntimeExports.jsx(CommandText,{children:"tessl login"})," to log in"]})]})};function _nullishCoalesce$o(e,t){return null!=e?e:t()}
2442
+ const STOCK_PHRASES=["Cluck!","Have you tried turning it off and on again?","Anyone for Honest Burgers?","Rules make us a civilization, Rob.","Time to tile that bathroom!","....doughnuts?","These models may be 'large' but they still can't understand why I crossed the road","Kevin broke it","I'm available for weddings, bar mitzvahs, birthdays....","The OG eggen","As a large language model I can't help you with this request","Fiat clux!"],getRandomStockPhrase=()=>STOCK_PHRASES[Math.floor(Math.random()*STOCK_PHRASES.length)],cluckCommand=new Command$1({name:"cluck",summary:"Cluck!",requiresConfig:!1,flags:{message:{type:String,short:"m",description:"💬"}},handler:async({args:{message:e}})=>(render(jsxRuntimeExports.jsx(()=>jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text,{color:"yellow",children:" xx\n / .|_\n /(_)_&lt;\n / (\n ((____.-' )\n \\\\ /\n \\'-.-.-'`/\n _ \\______/\n(_) _|_\\_\n''''''''''''''''"
2443
+ }),jsxRuntimeExports.jsx(Box,{paddingTop:2,paddingLeft:5,children:jsxRuntimeExports.jsx(Text,{color:"green",children:_nullishCoalesce$o(e,()=>getRandomStockPhrase())})})]}),{})),Promise.resolve(SUCCESS))});function _optionalChain$u(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}const SUPPORTED_SHELLS=["bash","zsh"];function detectShell(){const e=_optionalChain$u([process,"access",e=>e.env,"access",e=>e.SHELL,"optionalAccess",e=>e.split,"call",e=>e("/"),"access",e=>e.pop,"call",e=>e()])||"bash";return SUPPORTED_SHELLS.includes(e)?e:"bash"}function getCommandData(){const e={};for(const[t,r]of Object.entries(standaloneGeneralCommands))e[t]=r.summary;for(const[t,r]of Object.entries(standaloneToolCommands))e[t]=r.summary;const t=Object.keys(e),r=Object.keys(structuredCommands),n={}
2444
+ ;for(const[e,t]of Object.entries(structuredCommands)){n[e]={};for(const[r,i]of Object.entries(t))n[e][r]=i.summary}const i={},s=builtInTools(),o=Object.values(s).filter(e=>"public"===e.visibility);for(const{name:e,description:t}of o)i[e]=t||`Run the ${e} tool`;const a=o.map(({name:e})=>e);return{allCommands:[...t,...r,...a].sort(),standaloneCommandsWithDesc:e,structuredActions:r,structuredResources:n,toolAliasesWithDesc:i}}function generateBashCompletionScript(){const{allCommands:e,structuredActions:t,structuredResources:r}=getCommandData(),n="tessl"
2450
2445
  ;return`# Bash completion script for ${n}\n# Generated for command: ${n}\n#\n# To enable completion, choose one of these methods:\n#\n# Method 1 (eval pattern):\n# eval "$(${n} completion --shell=bash)"\n#\n# Method 2 (static file):\n# ${n} completion --shell=bash > ~/.${n}-completion.bash\n# echo 'source ~/.${n}-completion.bash' >> ~/.bashrc\n# source ~/.bashrc\n\n\n_${n}_completion() {\n local cur prev words cword\n _init_completion || return\n\n # Available commands\n local commands="${e.join(" ")}"\n\n # Structured command resources\n ${Object.entries(r).map(([e,t])=>`local ${e}_resources="${Object.keys(t).join(" ")}"`).join("\n ")}\n\n case \${cword} in\n 1)\n # First argument - complete with all available commands\n COMPREPLY=($(compgen -W "\\$commands" -- "\\$cur"))\n ;;\n 2)\n # Second argument - complete based on first argument\n case "\\$prev" in\n ${t.map(e=>`${e})\n COMPREPLY=($(compgen -W "\\$${e}_resources" -- "\\$cur"))\n ;;`).join("\n ")}\n *)\n # For standalone commands, no second argument completion\n ;;\n esac\n ;;\n *)\n # For 3+ arguments, provide basic file completion\n _filedir\n ;;\n esac\n}\n\n# Register the completion function for the current command name\ncomplete -F _${n}_completion ${n}\n`
2451
2446
  }function generateZshCompletionScript(){const{standaloneCommandsWithDesc:e,structuredActions:t,structuredResources:r,toolAliasesWithDesc:n}=getCommandData(),i="tessl",s={...e,...n};for(const r of t)e[r]?s[r]=e[r]:s[r]="add"===r?"Add components (has subcommands)":"config"===r?"Configuration commands (has subcommands)":`${r} command`
2452
2447
  ;return`# Zsh completion script for ${i} CLI\n# Generated for command: ${i}\n#\n# To enable completion, choose one of these methods:\n#\n# Method 1 (eval pattern):\n# eval "$(${i} completion --shell=zsh)"\n#\n# Method 2 (static file):\n# ${i} completion --shell=zsh > ~/.${i}-completion.zsh\n# echo 'source ~/.${i}-completion.zsh' >> ~/.zshrc\n# source ~/.zshrc\n\n# This script is designed to be safely used with eval\n# Define the completion function - not immediately executed\n_${i}() {\n local context state line\n typeset -A opt_args\n\n local commands=(\n ${Object.entries(s).map(([e,t])=>`'${e}:${t.replace(/'/g,"'\\''")}'`).join("\n ")}\n )\n\n _arguments -C \\\n '1: :->command' \\\n '*: :->args' && return 0\n\n case $state in\n command)\n _describe '${i} commands' commands\n ;;\n args)\n case $words[2] in\n ${t.map(e=>`${e})\n local ${e}_resources=(\n ${Object.entries(r[e]||{}).map(([e,t])=>`'${e}:${t.replace(/'/g,"'\\''")}'`).join("\n ")||""}\n )\n _describe '${e} resources' ${e}_resources\n ;;`).join("\n ")}\n *)\n _files\n ;;\n esac\n ;;\n esac\n}\n\n# Register the completion function without immediately executing _arguments\ncompdef _${i} ${i}\n`
@@ -2459,7 +2454,7 @@ if(void 0===e)throw new ExpectedError("The key argument is required.");const s=t
2459
2454
  if(r.upArrow||r.downArrow||r.ctrl&&"c"===t||r.tab||r.shift&&r.tab)return;if(r.return)return void(a&&a(e));let n=l,i=e,c=0;r.leftArrow?s&&n--:r.rightArrow?s&&n++:r.backspace||r.delete?l>0&&(i=e.slice(0,l-1)+e.slice(l,e.length),n--):(i=e.slice(0,l)+t+e.slice(l,e.length),n+=t.length,t.length>1&&(c=t.length)),l<0&&(n=0),l>e.length&&(n=e.length),u({cursorOffset:n,cursorWidth:c}),i!==e&&o(i)},{isActive:r}),React.createElement(Text,null,t?h.length>0?A:f:A)}function Thanks(){return jsxRuntimeExports.jsx(Box,{marginBottom:1,children:jsxRuntimeExports.jsx(Text,{children:"Thanks for your feedback!"})})}function Feedback({initialMessage:e,onSubmit:t}){const[r,n]=reactExports.useState(e||"");return e?jsxRuntimeExports.jsx(Thanks,{}):jsxRuntimeExports.jsxs(Box,{flexDirection:"column",children:[jsxRuntimeExports.jsx(Text,{children:"What do you want to tell us?"}),jsxRuntimeExports.jsx(TextInput,{value:r,onChange:n,onSubmit:t,placeholder:"Type your feedback here and press Enter to submit"})]})}
2460
2455
  const feedbackCommand=new Command$1({name:"feedback",summary:"Send feedback to the Tessl team",requiresConfig:!1,requiresLogin:!0,positionals:[{name:"message",description:"The user's feedback message. Requested interactively if not provided"}],handler:async({monitoring:e,positionals:t,isInteractive:r})=>{const n=t.message,i=t=>{e.posthogCapture({event:"survey sent",properties:{sessionId:e.analytics.getSessionId(),projectId:e.analytics.getProjectId(),$survey_id:"0197d0d3-6704-0000-e36e-569911acb8ee",$survey_questions:[{id:"e34e48fc-938a-4af1-b255-3c55d6bdcbc7",question:"Feedback message"}],"$survey_response_e34e48fc-938a-4af1-b255-3c55d6bdcbc7":t}},{bypassOptOut:!0})};if(n)return i(n),render(jsxRuntimeExports.jsx(Feedback,{initialMessage:n,onSubmit:()=>{}})),Promise.resolve(SUCCESS);if(!r)throw new ExpectedError("In non-interactive mode, you must provide a feedback message as an argument");return new Promise(e=>{render(jsxRuntimeExports.jsx(Feedback,{onSubmit:t=>{t.trim()?(i(t.trim()),
2461
2456
  render(jsxRuntimeExports.jsx(Thanks,{})),e(SUCCESS)):(render(jsxRuntimeExports.jsx(Text,{color:"yellow",children:"Feedback submission cancelled - message was empty."})),e(FAILURE))}}))})}
2462
- }),content$6="\n# Tessl\n\nTessl is a [spec driven development](./docs/spec-driven-development.md) framework and toolkit: @docs/spec-driven-development.md\n\n## Spec Driven Software Development Lifecycle\n\n### User Engagement\n\nUsers should be encouraged to engage directly with specs, so that they understand what is being asked for (or documented), and can steer the software development processes.\n\nIn order to do this, agents should:\n\n1. Interview the user to get details before creating or updating specs (but ask one or two questions at a time, so as not to overwhelm them).\n2. Ask for feedback on specs before building them. This should include pointing out key implementation choices, and highlighting any gaps in the spec.\n3. Include interview/feedback points as separate tasks in plans, so these steps are not skipped.\n\n### Primary Workflow: Spec to code\n\nSoftware is developed by creating or editing a spec and then `building` that spec to generate or update the implementation and then `fixing` to refine the spec and implementation until it works as intended.\n\n1. Create/edit the spec to reflect the desired functionality/changes requested, using the appropriate Tessl tool and providing it with relevant context (see the \"Using Tessl Tools\" instructions below)\n2. Install any new required dependencies from the spec\n3. Build the spec to generate the implementation code from the updated spec and fix\n4. When/if the user asks for tests, add them to the spec and generate them and fix.\n\n### Alternative Workflow: Code to spec\n\nSometimes the user may decide to change the code directly, or they may have legacy code they want to document. In such cases:\n\n1. Document the code changes into the spec + fix spec/tests to match observed code behaviors\n2. If the spec is changed, flag any capabilities that are lost or changed.\n\n### Using Tessl Tools\n\nTessl tools allow targeted changes to spec, code and test files ensuring that the methodology is followed, and that the correct context is provided at each step.\n\nBefore using any Tessl tool (`create`, `edit`, `build`, `document` etc) you must:\n\n1. **First: Check Knowledge Index:**\n\n - Read `./KNOWLEDGE.md` (the Knowledge Index)\n - Consider the Tessl tool call you're about to make, including any parameters\n - Decide if any entries in the Knowledge Index seem directly relevant to the current task\n - If so, spawn a research sub-agent to dig deeper into the chosen documents\n - If not, skip research and just call the tool\n\n2. **Research context** - Spawn a research sub-agent with details about:\n\n - The Knowledge Index candidates to explore\n - The specific Tessl tool you're about to call\n - The inputs to that tool call (what you're building, which files, etc.)\n\n3. **Research sub-agent identifies relevant context file paths:**\n\n - Explore the provided Knowledge Index entries\n - **Return**: Only relevant file paths (relative to the project root)\n\n4. **Then: Call the Tessl tool** - Use the file paths returned by the research sub-agent (relative to project root) in the `--context` parameter.\n\nRemember the research output and re-use it for similar tool calls (where the tool and inputs are the same).\n\nUse Tessl tools to:\n\n- Capture requirements for new code files in specs using the `create` tool\n- Edit specs / code / tests whenever the user wants to introduce or change behavior in existing specs / code / tests with the `edit` tool\n- Build code and tests from specs using the `build` and `build-tests` tools\n- Document code into specs using the `document` tool\n- Run tests using the `test` tool\n- Add extra functionality to code, by editing the spec and rebuilding\n- Check project and spec status using the `status` tool\n\nTessl also provides the capability to run its tools in parallel. Use this when you have multiple tasks to do that are independent of each other - e.g. rebuilding multiple specs at once.\n\n### Detailed Expectations Around Fixing Code and Tests:\n\nA key concept in spec-driven development is that built code and tests should be run to verify conformity to the spec. Often, however, working code and useful tests are not made on the first attempt. \n\nTessl tools will attempt to 'fix' before finishing build, but agents may need to continue or debug this process. \n\nBy default, the spec will have few if any test cases to start with, focus on getting the functionality working and then if the user asks for more tests, add them to the spec and generate them.\n\nTests should be prioritised in the following order:\n- Locked tests. Make sure the code is able to pass these tests, they are core functional requirements that have been confirmed by the user.\n- Draft tests. If draft tests have been generated, try to make the code pass. These tests have not been fully validated, so their definition or implementation may need to be refined until useful or removed altogether.\n- Impl tests. If generated, then try to make the code pass. These tests were created to capture details in an implementation that may not be important, so they may be deleted if they are no longer valid.\n\nFixes should be applied in this preference order:\n1. (Preferred fix): Install dependencies explicitly listed in the spec if needed.\n2. (Preferred fix): Iteratively run tests and update code to address errors, until the code passes the tests.\n3. (Cautious fix): Iteratively fix implementation errors in tests (e.g. syntax errors) and check they are still faithful to the spec.\n4. (Last resort): Identify if the spec contains errors, ambiguities or hard to implement definitions. Ask the user for how to proceed.\n\n**Never** simply remove requirements from the spec.\n**Never** add new capabilities to the code without updating the spec to capture how it will be verified.\n\n**Setup/Configuration errors**\nIt's possible the error stems from the overall project set up, in this case:\n\n- Ask the user to add dependencies to the spec if they are implied or necessary for the capabilities required.\n- Help the user configure their project further and make sure that their development environment is working.\n- Make sure that project details like the language(s), test runner(s) and ecosystem(s), and any testing or implementation guidelines are added to AGENTS.md to help guide the Tessl tools to produce consistent implementations that adhere to them.\n\n### Software Decomposition\n\nSpecs should map 1:1 with code files, with the structure of the specs and the links between them matching the intended decomposition of the software.\n\nIf the user asks for new functionality that would be challenging to fit into a single spec and code file, then you should first suggest decomposition approaches with them, and then make a plan to iteratively build up the software spec by spec.\n\nMake sure that specs link to each other as needed, and that there is a clear entry-point.\n\n**Pointers:**\n\n- Prefer to work in an incremental way, building up the software one piece at a time, improving the software with each iteration. Suggest a simple starting point, and include tasks in your plan to add additional features one by one later.\n- Check generated specs to make sure that they link to one another via \"dependencies\" links, and if not, call edit spec and ask for the dependency to be added.\n- Add more details on project expectations to AGENTS.md if you need more consistency in the project across specs - for example, on choices on key external dependencies, or testing guidelines.\n- Make sure the user provides explicit feedback and approval before deciding on a decomposition and beginning to create multiple specs and building them all.\n\n## The Knowledge Index\n\nThe Knowledge Index is a centralized reference for documentation about dependencies and processes used in the project.\n\nIt's stored in `./KNOWLEDGE.md` and contains links to versioned documentation files.\n\nThe Knowledge Index helps ensure consistency when selecting dependency versions and provides quick access to relevant documentation during development.\n\n## Important\n\nAlways modify code, tests or specs using Tessl tools. The only exceptions are when the user approves this behavior interactively. In either case **specs and generated code and tests must be always in sync**\n",content$5='\n# Project Information Bootstrapping\n\nBefore you can use any Tessl tools, you need to write information about the project into the AGENTS.md file\n\nFollow these steps:\n\n## 1. Interview\n\nWork out the following information, either by:\na. working out what setup already exists in the directory and confirming it with the user, or \nb. by interviewing the user interactively to work out what they\'d like to use:\n\nCover:\n- What stack to use (e.g. Node, TypeScript/ESM, Python, Java/Maven)\n- What testing framework to use (you can provide suggestions like `vitest`)\n- Where to put specs, code files and test files (e.g. `./specs`, `./src`, `./tests`)\n- How to set up the development environment (e.g. environment management and build tools)\n\nAsk these questions one at a time, and ask follow up questions when answers are unclear.\n\n## 2. Setup\n\nUsing the supplied information, perform any necessary steps to get the project set up as needed. This might involve creating directories, or installing a minimal set of core dependencies. Consider the local Knowledge Index when selecting dependency versions, if it exists.\n\n## 3. Update Project Configuration\n\nRecord the project configuration information in `./AGENTS.md` and remove the "Project Bootstrapping" section from the file. Make sure to include the test command(s).\n\nWhen writing up the test command(s), beware of "watch mode" that might interfere with agentic testing feedback loops. For example: the `vitest` command will run in watch mode by default, which will appear to hang as it will not exit - instead the `vitest run` command should be used.\n\n## 4. Interview the user about their task\n\nBefore making a spec or making code changes, you should again interview the user about their task. This time, ask clarifying questions about the details of what they want to build, and the plan to build it. \n\nUsers are generally more successful if:\na. they approach the task in an agile way, building the software in small increments, focussing on one or two files at the most each time. See if there\'s a way to start simply and add details about extra features to the plan to be added later, after you get the first slice working.\nb. you get feedback from them about the spec before starting to build it. For example, ask if the test definitions are precise enough, and whether key capabilities are reflected in the spec.\n\nInclude steps in your plan for when you need to get feedback from the user.\n\n',content$4="\n# Spec Driven Development (SDD)\n\nSpec driven development places specs at the center of the software development lifecycle. Specs are considered the canonical source of truth when they are verifiable. Code is considered disposable when it can be reliably regenerated from a spec.\n\nSpecs capture _intent_, and may contain or link to files containing the API and test cases. Over time specs are updated to add new features or requirements, and code is regenerated to align with the specs.\n\nEach spec usually maps 1:1 to a code file. Larger units are composed of multiple linked specs (via dependencies), mirroring decomposition. A linked set of specs with their code and tests is a **tile** or **Tessl tile**. Projects may contain multiple tiles.\n\n## Specs\n\n- Follow the [Spec Format](./spec-format.md)\n- Used to capture all user intent\n- MUST NOT be modified without explicit user instruction or review\n- Together reflect the expected software decomposition with local spec dependencies mirroring targeted local code files, and with links to external dependencies\n\n## Code\n\n- Follow language and ecosystem requirements specified in AGENTS.md, and APIs and requirements in spec\n- Can be edited or rebuilt by tools or agents\n- Makes good use of dependencies explicitly linked in spec - following dependency APIs if provided and without reimplementing functionality\n- Doesn't use dependencies not explicitly listed in the spec\n\n## Tests\n\n- Follow the test runner requirements specified in AGENTS.md\n- Can be edited or rebuilt by tools or agents\n- Each test implements exactly one test definition from the spec, and only verifies that exact case\n- Assumes code complies exactly with the defined APIs\n- Can be tagged to indicate prioritization: draft (default), locked, impl\n",content$3='\n# Spec Format\n\nSpecs are markdown files with some annotations for parsing. Typically one spec is written for each module.\n\nThey can contain the following sections, empty sections can be omitted:\n\n- Name.\n - Short overview to explain overall purpose.\n- Target.\n - Relative link to the code file this spec targets.\n- Capabilities.\n - Headings for each capability with an optional description.\n - List of test definitions for each capability, with relative links to the test files where they will be implemented.\n- API.\n - Description of the module\'s API that code and tests will be written to conform to.\n- Dependencies.\n - List of dependencies the spec has on other modules and external libraries.\n\nA further explanation of each is provided below.\n\n## Target\n\nShould contain a relative link to the code file that will contain the code this spec targets. This can be one of two flavors:\n\n- [@generate](./relative/path/to/code/file) or\n- [@describe](./relative/path/to/code/file)\n\n@generate is used where the spec is the primary artifact and the linked code will be generated (and regenerated) from the spec. This is the default.\n@describe is used to provide a wrapper to an existing code file, where the code is the primary artifact. This is provided to allow the spec to act as a reference material. The spec will be updated to match code changes.\n\nA spec may contain multiple links if multiple code files are generated from or described by the spec, but it is best practice to have one spec for one code file.\n\n## Capabilities\n\nList of capabilities of the module.\n\nEach capability:\n\n- Should be precise and concise.\n- Should explicitly describe the _intent_ of the capability, rather than describing the approach.\n- Can optionally have a short description under the title to explain the capability in more detail.\n\nEach capability should be followed by a list of requirements.\n\nEach requirement:\n\n- Should be concise, precise and opinionated on specific behaviors.\n- Can cover internal logic or external behavior.\n- Requirements can be converted into test cases by adding a corresponding [@test](./relative/path/to/test/file) annotation. Test cases must have clearly defined inputs and outputs, as well as setup/mocking notes if needed.\n\nExample:\n\n```markdown\nReverses any string. Preserves capitalization and whitespaces during reversal.\n\n- "hello" becomes "olleh" [@test](./relative/path/to/test/file)\n- "Hello, world!" becomes "!dlrow ,olleH" [@test](./relative/path/to/test/file_impl) { .impl }\n```\n\n## API\n\n- Describe the external interface for the module, including function signatures and parameters with types.\n- Must be wrapped in code block with a language identifier, with an { .api } tag on the block.\n- Should be an appropriate format for the language, and should be consistent with any project configuration provided.\n\n## Dependencies\n\nList of dependencies on other specs, files or external libraries that the module is expected to have. No other dependencies should be assumed, unless explicitly specified in the project configuration or in a user goal. Links can either be to the spec for the module if available, or directly to the code itself if the spec is not available.\n\n- Each lists what is expected from the dependency and has a link to the dependency.\n- New dependencies should only be added when explicitly requested by the user.\n\n- The whole section can be skipped if there are no requirements.\n- Each requirement should have a @use link.\n- For local dependencies, the link will be a relative path, for example [@use](./relative/path/to/dependency-spec)\n- For external dependencies a package name will be used, for example [@use](package-name)\n- For code dependencies, the link will be a relative path, for example [@use](./relative/path/to/code-file).\n\nExample dependencies:\n\n```markdown\n# Dependencies\n\n## Code Dependency Example\n\nDescription of the requirements for the module.\n[@use](./relative/path/to/code-file)\n\n## Spec Dependency Example\n\nDescription of the requirements for the module.\n[@use](./relative/path/to/dependency-spec)\n\n## External Dependency Example\n\nDescription of the requirements for the module.\n[@use](package-name)\n```\n\n## Content tags\n\nSections of the spec can be annotated with tags to explain the prioritization and level of editing that is appropriate. They are most often used for annotating specific tests.\n\nRules for applying tags:\n- By default, do not add tags.\n- Tags applied to a section will apply to all tests in the section.\n- Tests must not have more than one kind. e.g: you should not have a test marked as `impl` and `locked`, or a section marked with both `impl` and a test marked with `locked`.\n- Tests files must not mix test kinds. e.g: you should not have untagged and `locked` tests in the same test file.\n- Locked content must never be edited unless instructed to do so by the user.\n- Content must never be tagged as locked unless explicitly requested by the user.\n\n### Untagged (default)\n\nUntagged content is the standard and is considered draft.\n\nUntagged test cases \n- **Purpose**: Regular test cases that can be modified during development as necessary.\n- **Annotation**: No special class required (default behavior)\n- **Priority**: Medium priority, they can be changed during the development flow as the spec is refined\n\nExample:\n```markdown\n- "hello" becomes "olleh" [@test](./relative/path/to/test/file)\n```\n\n\n### Locked { .locked }\n\nLocked tags capture core functional requirements that should remain stable over time. They represent critical test cases that define the essential behavior of the module that have been confirmed by the user.\n\n- **Purpose**: Capture core functional requirements that should remain stable over time\n- **Annotation**: `{ .locked }` class on individual tests or section headers\n- **Priority**: High priority, they are applied deliberately by the user after reviews have been completed.\n\nExamples:\n```markdown\n- "hello" becomes "olleh" [@test](./relative/path/to/test/file) { .locked }\n\n### Core functionality { .locked }\n- "test1" becomes "1tset" [@test](./relative/path/to/test/file1)\n- "test2" becomes "2tset" [@test](./relative/path/to/test/file2)\n```\n\n### Implementation { .impl }\n\nImplementation tags are used to mark incidental implementation by-products rather than user-specified capabilities. They have lower priority and can be changed more freely.\n\n- **Purpose**: Cover implementation details that were not explicitly specified by the user.\n- **Annotation**: `{ .impl }` class on individual tests or section headers\n- **Priority**: Lower priority, they should be more freely changed if user requirements change.\n\nExamples:\n```markdown\n- "Hello" becomes "olleH" [@test](./relative/path/to/test/file) { .impl }\n\n### Implementation details { .impl }\n- Edge case behavior [@test](./relative/path/to/test/file1)\n- Performance characteristics [@test](./relative/path/to/test/file2)\n```\n\n\n## Example spec (with placeholders for the api details)\n\n````markdown\n# String Reverser\n\nString reverser. Switches the order of characters in a string.\n\n## Target\n\n[@generate](./relative/path/to/code/file)\n\n## Capabilities\n\n### Reverses a string.\n\n- "hello" becomes "olleh" [@test](./relative/path/to/test/file1)\n- "iPhone 5 Samsung" becomes "gnusmaS 5 enohPi" [@test](./relative/path/to/test/file2)\n\n### Reverses within a delimiter.\n\nDelimiter is optional, but if provided, reversing only happens between each delimited block, with block order preserved.\n\n- ("hello friend", " ") becomes "olleh dneirf" [@test](./relative/path/to/test/file4)\n\n### Efficient implementation\n\n- Uses a single pass buffer approach.\n- Doesn\'t modify the original string.\n\n\n## API\n\n```{{LANGUAGE}} { .api }\n\n{{API_CODE}}\n\n```\n\n````\n\n\n',content$2='# Plan Files\n\n**CRITICAL: Create a plan file EVERY TIME you make a plan:**\n\n1. Create a new plan file in the `plans/` directory at the root of the project.\n2. Plan filename format: `YYYY-MM-DD_HH-mm-ss_descriptive-name.plan.md`\n - Example: `2025-08-25_14-37-12_user-authentication.plan.md`\n3. Keep the plan file in sync with your own native task tracking tool.\n4. Update the plan file IMMEDIATELY after completing EACH task. Do NOT batch updates.\n\n## Plan File Structure\n\n### Format\nA plan file is a markdown document (`.plan.md`) that records tasks to achieve a goal, and acts as an audit trail of the plan.\n\n### Components\n1. **Header**: Overall goal and any relevant background context\n2. **Task List**: Markdown checkboxes for each task\n - `- [ ]` for pending tasks\n - `- [x]` for completed tasks\n3. **Task Outputs**: Document results as blockquotes after each task\n\n## Rules for Executing Plans with Plan Files\n\n### 1. Task Documentation\nAfter completing each task, document comprehensively:\n\n- **Update status**: Change checkbox from `[ ]` to `[x]`\n- **Add output**: Create detailed blockquote on new line after task\n- **Document tool calls**: For EVERY tool call (MCP, Bash, Edit, etc.), include:\n - Tool name\n - COMPLETE, VERBATIM parameters (do not summarize), EXCEPTION: do summarize parameters containing file contents\n - Use markdown code blocks for multi-line string parameters (e.g. prompts)\n - Summary of tool output\n- **Include every step in the task**: Document every tool call needed to complete the task\n- **Use separators**: Add `---` and a newline between multiple tool calls in same task\n- **Include full journey**: Document the complete process, including diagnostics and debugging:\n - ALL problems encountered with specific details\n - Each fix attempt and rationale\n - Every diagnostic tool used (exact tool name, summary of parameters and output)\n - Summary of outcome, including initial state (e.g., "7 tests failed out of 12") and final state (e.g., "All 11 tests passing")\n- **Always link to project files**: Include markdown links to any created/read/update/deleted project files:\n - link text: file path relative to the project root\n - link href: file path relative to the plan file\n\n### 2. Plan Updates\n- Modify the plan and plan file as needed when requirements change\n- Add new tasks or remove irrelevant ones\n- Document reasons for significant changes\n\n## Best Practices\nTasks should be:\n- **Specific**: Clear, actionable completion criteria\n- **Atomic**: One logical unit of work per task\n- **Logically Ordered**: Arrange in execution sequence\n- **Well Sized**: Break down complex goals into incremental atomic tasks\n\n## Example\n\n````markdown\n# Plan: Implement User Authentication\n\nAdd secure user authentication with email/password login.\n\n## Tasks\n\n- [x] Create user model spec with email, password hash, and timestamps\n > **MCP** `tessl - create`\n > - spec: specs/models/user.spec.md\n > - prompt:\n > ```\n > Create a User model with the following fields:\n > - id: string (UUID)\n > - email: string (unique, required)\n > - passwordHash: string (required)\n > - createdAt: Date\n > - updatedAt: Date\n >\n > Include methods for:\n > - Password hashing and verification using bcrypt\n > - Email validation\n > - Safe JSON serialization (excludes passwordHash)\n > ```\n >\n > Created [specs/models/user.spec.md](../specs/models/user.spec.md)\n > Model spec created successfully with all required fields and methods.\n\n- [x] Build user model from spec\n > **MCP** `tessl - build`\n > - spec: ["specs/models/user.spec.md"]\n >\n > Generated:\n > - [src/models/user.ts](../src/models/user.ts)\n >\n > Build completed successfully, no errors.\n > ---\n >\n > **Bash** `npm run build`\n > Build failed with TypeScript errors: missing import extensions\n > ---\n >\n > **Edit** `src/models/user.ts`\n > - old_string: import { SomeType } from \'./types\'\n > - new_string: import { SomeType } from \'./types.js\'\n >\n > Updated [src/models/user.ts](../src/models/user.ts).\n > Fixed import to include .js extension for ESM compatibility.\n > ---\n >\n > **MCP** `tessl - document`\n > - spec: specs/models/user.spec.md\n > - includeImplDetails: true\n >\n > Synced [code](../src/models/user.ts) behavior to [spec](../specs/models/user.spec.md)\n\n- [ ] Add database migration for users table\n- [ ] Create authentication service spec\n- [ ] Implement login endpoint\n- [ ] Add session management\n- [ ] Test authentication flow end-to-end\n- [ ] Ask user to manually review and confirm authentication flow is working as expected\n````\n',content$1="\n# Tessl\n\nTessl is a spec driven development framework and toolkit.\n\nAlways use [Spec Driven Development](./docs/spec-driven-development.md) when executing tasks.\n",content="\n# Using the Knowledge Index\n\nRequired dependencies for this projects are documented in the Knowledge Index: `./KNOWLEDGE.md`\n\nBefore starting any work, review the contents of `./KNOWLEDGE.md` to discover the expectations on what dependencies (and which versions) and processes you must follow.\n\nBecause the index can link to a large amount of content, use this workflow to read relevant content:\n\n1. Review `./KNOWLEDGE.md` and check if there any relevant files.\n2. If so, spawn a research subagent with information about your task and a pointer to the files, and ask it to return a relevant summary of context for you to use (but not to do the task). This will prevent you from getting overwhelmed by too much information.\n3. Use the information in your task!\n\nClarify by interviewing the user if the content is not what you expect:\n\n- There's documentation for a dependency you could use, but it isn't the obvious choice. Check if you are expected to use it for the task you are doing.\n- If you are not sure whether to use the version of the dependency from the docs, for example, if you discover that there's a more up to date version of the package.\n- If there's documentation that appears to be missing that would help.\n\nREPEAT this workflow for every new task. The Knowledge Index is updated frequently, so make sure to review it for changes.\n\n# Using the Tessl Spec Registry\n\nDocumentation can be added to the Knowledge Index using the Tessl `registry` tools:\n\n- Search Tessl's Spec Registry for dependency documentation using `search`\n- Install relevant docs into the Knowledge Index using `install`\n\nConsult the Spec Registry when deciding which dependencies to install into a project. Likewise, install the documentation for a given dependency after installing it.\n",FRAMEWORK_FILES={
2457
+ }),content$6="\n# Tessl\n\nTessl is a [spec driven development](./docs/spec-driven-development.md) framework and toolkit: @docs/spec-driven-development.md\n\n## Spec Driven Software Development Lifecycle\n\n### User Engagement\n\nUsers should be encouraged to engage directly with specs, so that they understand what is being asked for (or documented), and can steer the software development processes.\n\nIn order to do this, agents should:\n\n1. Interview the user to get details before creating or updating specs (but ask one or two questions at a time, so as not to overwhelm them).\n2. Ask for feedback on specs before building them. This should include pointing out key implementation choices, and highlighting any gaps in the spec.\n3. Include interview/feedback points as separate tasks in plans, so these steps are not skipped.\n\n### Primary Workflow: Spec to code\n\nSoftware is developed by creating or editing a spec and then `building` that spec to generate or update the implementation and then `fixing` to refine the spec and implementation until it works as intended.\n\n1. Create/edit the spec to reflect the desired functionality/changes requested, using the appropriate Tessl tool and providing it with relevant context (see the \"Using Tessl Tools\" instructions below)\n2. Install any new required dependencies from the spec\n3. Build the spec to generate the implementation code from the updated spec and fix\n4. When/if the user asks for tests, add them to the spec and generate them and fix.\n\n### Alternative Workflow: Code to spec\n\nSometimes the user may decide to change the code directly, or they may have legacy code they want to document. In such cases:\n\n1. Document the code changes into the spec + fix spec/tests to match observed code behaviors\n2. If the spec is changed, flag any capabilities that are lost or changed.\n\n### Using Tessl Tools\n\nTessl tools allow targeted changes to spec, code and test files ensuring that the methodology is followed, and that the correct context is provided at each step.\n\nBefore using any Tessl tool (`create`, `edit`, `build`, `document` etc) you must:\n\n1. **First: Check Knowledge Index:**\n\n - Read `./KNOWLEDGE.md` (the Knowledge Index)\n - Consider the Tessl tool call you're about to make, including any parameters\n - Decide if any entries in the Knowledge Index seem directly relevant to the current task\n - If so, spawn a research sub-agent to dig deeper into the chosen documents\n - If not, skip research and just call the tool\n\n2. **Research context** - Spawn a research sub-agent with details about:\n\n - The Knowledge Index candidates to explore\n - The specific Tessl tool you're about to call\n - The inputs to that tool call (what you're building, which files, etc.)\n\n3. **Research sub-agent identifies relevant context file paths:**\n\n - Explore the provided Knowledge Index entries\n - **Return**: Only relevant file paths (relative to the project root)\n\n4. **Then: Call the Tessl tool** - Use the file paths returned by the research sub-agent (relative to project root) in the `--context` parameter.\n\nRemember the research output and re-use it for similar tool calls (where the tool and inputs are the same).\n\nUse Tessl tools to:\n\n- Capture requirements for new code files in specs using the `create` tool\n- Edit specs / code / tests whenever the user wants to introduce or change behavior in existing specs / code / tests with the `edit` tool\n- Build code and tests from specs using the `build` and `build-tests` tools\n- Document code into specs using the `document` tool\n- Run tests using the `test` tool\n- Add extra functionality to code, by editing the spec and rebuilding\n- Check project and spec status using the `status` tool\n\nTessl also provides the capability to run its tools in parallel. Use this when you have multiple tasks to do that are independent of each other - e.g. rebuilding multiple specs at once.\n\n### Detailed Expectations Around Fixing Code and Tests:\n\nA key concept in spec-driven development is that built code and tests should be run to verify conformity to the spec. Often, however, working code and useful tests are not made on the first attempt. \n\nTessl tools will attempt to 'fix' before finishing build, but agents may need to continue or debug this process. \n\nBy default, the spec will have few if any test cases to start with, focus on getting the functionality working and then if the user asks for more tests, add them to the spec and generate them.\n\nTests should be prioritised in the following order:\n- Locked tests. Make sure the code is able to pass these tests, they are core functional requirements that have been confirmed by the user.\n- Draft tests. If draft tests have been generated, try to make the code pass. These tests have not been fully validated, so their definition or implementation may need to be refined until useful or removed altogether.\n\nFixes should be applied in this preference order:\n1. (Preferred fix): Install dependencies explicitly listed in the spec if needed.\n2. (Preferred fix): Iteratively run tests and update code to address errors, until the code passes the tests.\n3. (Cautious fix): Iteratively fix implementation errors in tests (e.g. syntax errors) and check they are still faithful to the spec.\n4. (Last resort): Identify if the spec contains errors, ambiguities or hard to implement definitions. Ask the user for how to proceed.\n\n**Never** simply remove requirements from the spec.\n**Never** add new capabilities to the code without updating the spec to capture how it will be verified.\n\n**Setup/Configuration errors**\nIt's possible the error stems from the overall project set up, in this case:\n\n- Ask the user to add dependencies to the spec if they are implied or necessary for the capabilities required.\n- Help the user configure their project further and make sure that their development environment is working.\n- Make sure that project details like the language(s), test runner(s) and ecosystem(s), and any testing or implementation guidelines are added to AGENTS.md to help guide the Tessl tools to produce consistent implementations that adhere to them.\n\n### Software Decomposition\n\nSpecs should map 1:1 with code files, with the structure of the specs and the links between them matching the intended decomposition of the software.\n\nIf the user asks for new functionality that would be challenging to fit into a single spec and code file, then you should first suggest decomposition approaches with them, and then make a plan to iteratively build up the software spec by spec.\n\nMake sure that specs link to each other as needed, and that there is a clear entry-point.\n\n**Pointers:**\n\n- Prefer to work in an incremental way, building up the software one piece at a time, improving the software with each iteration. Suggest a simple starting point, and include tasks in your plan to add additional features one by one later.\n- Check generated specs to make sure that they link to one another via \"dependencies\" links, and if not, call edit spec and ask for the dependency to be added.\n- Add more details on project expectations to AGENTS.md if you need more consistency in the project across specs - for example, on choices on key external dependencies, or testing guidelines.\n- Make sure the user provides explicit feedback and approval before deciding on a decomposition and beginning to create multiple specs and building them all.\n\n## The Knowledge Index\n\nThe Knowledge Index is a centralized reference for documentation about dependencies and processes used in the project.\n\nIt's stored in `./KNOWLEDGE.md` and contains links to versioned documentation files.\n\nThe Knowledge Index helps ensure consistency when selecting dependency versions and provides quick access to relevant documentation during development.\n\n## Important\n\nAlways modify code, tests or specs using Tessl tools. The only exceptions are when the user approves this behavior interactively. In either case **specs and generated code and tests must be always in sync**\n",content$5='\n# Project Information Bootstrapping\n\nBefore you can use any Tessl tools, you need to write information about the project into the AGENTS.md file\n\nFollow these steps:\n\n## 1. Interview\n\nWork out the following information, either by:\na. working out what setup already exists in the directory and confirming it with the user, or \nb. by interviewing the user interactively to work out what they\'d like to use:\n\nCover:\n- What stack to use (e.g. Node, TypeScript/ESM, Python, Java/Maven)\n- What testing framework to use (you can provide suggestions like `vitest`)\n- Where to put specs, code files and test files (e.g. `./specs`, `./src`, `./tests`)\n- How to set up the development environment (e.g. environment management and build tools)\n\nAsk these questions one at a time, and ask follow up questions when answers are unclear.\n\n## 2. Setup\n\nUsing the supplied information, perform any necessary steps to get the project set up as needed. This might involve creating directories, or installing a minimal set of core dependencies. Consider the local Knowledge Index when selecting dependency versions, if it exists.\n\n## 3. Update Project Configuration\n\nRecord the project configuration information in `./AGENTS.md` and remove the "Project Bootstrapping" section from the file. Make sure to include the test command(s).\n\nWhen writing up the test command(s), beware of "watch mode" that might interfere with agentic testing feedback loops. For example: the `vitest` command will run in watch mode by default, which will appear to hang as it will not exit - instead the `vitest run` command should be used.\n\n## 4. Interview the user about their task\n\nBefore making a spec or making code changes, you should again interview the user about their task. This time, ask clarifying questions about the details of what they want to build, and the plan to build it. \n\nUsers are generally more successful if:\na. they approach the task in an agile way, building the software in small increments, focussing on one or two files at the most each time. See if there\'s a way to start simply and add details about extra features to the plan to be added later, after you get the first slice working.\nb. you get feedback from them about the spec before starting to build it. For example, ask if the test definitions are precise enough, and whether key capabilities are reflected in the spec.\n\nInclude steps in your plan for when you need to get feedback from the user.\n\n',content$4="\n# Spec Driven Development (SDD)\n\nSpec driven development places specs at the center of the software development lifecycle. Specs are considered the canonical source of truth when they are verifiable. Code is considered disposable when it can be reliably regenerated from a spec.\n\nSpecs capture _intent_, and may contain or link to files containing the API and test cases. Over time specs are updated to add new features or requirements, and code is regenerated to align with the specs.\n\nEach spec usually maps 1:1 to a code file. Larger units are composed of multiple linked specs (via dependencies), mirroring decomposition. A linked set of specs with their code and tests is a **tile** or **Tessl tile**. Projects may contain multiple tiles.\n\n## Specs\n\n- Follow the [Spec Format](./spec-format.md)\n- Used to capture all user intent\n- MUST NOT be modified without explicit user instruction or review\n- Together reflect the expected software decomposition with local spec dependencies mirroring targeted local code files, and with links to external dependencies\n\n## Code\n\n- Follow language and ecosystem requirements specified in AGENTS.md, and APIs and requirements in spec\n- Can be edited or rebuilt by tools or agents\n- Makes good use of dependencies explicitly linked in spec - following dependency APIs if provided and without reimplementing functionality\n- Doesn't use dependencies not explicitly listed in the spec\n\n## Tests\n\n- Follow the test runner requirements specified in AGENTS.md\n- Can be edited or rebuilt by tools or agents\n- Each test implements exactly one test definition from the spec, and only verifies that exact case\n- Assumes code complies exactly with the defined APIs\n- Can be tagged to indicate prioritization: draft (default), locked\n",content$3='\n# Spec Format\n\nSpecs are markdown files with some annotations for parsing. Typically one spec is written for each module.\n\nThey can contain the following sections, empty sections can be omitted:\n\n- Name.\n - Short overview to explain overall purpose.\n- Target.\n - Relative link to the code file this spec targets.\n- Capabilities.\n - Headings for each capability with an optional description.\n - List of test definitions for each capability, with relative links to the test files where they will be implemented.\n- API.\n - Description of the module\'s API that code and tests will be written to conform to.\n- Dependencies.\n - List of dependencies the spec has on other modules and external libraries.\n\nA further explanation of each is provided below.\n\n## Target\n\nShould contain a relative link to the code file that will contain the code this spec targets. This can be one of two flavors:\n\n- [@generate](./relative/path/to/code/file) or\n- [@describe](./relative/path/to/code/file)\n\n@generate is used where the spec is the primary artifact and the linked code will be generated (and regenerated) from the spec. This is the default.\n@describe is used to provide a wrapper to an existing code file, where the code is the primary artifact. This is provided to allow the spec to act as a reference material. The spec will be updated to match code changes.\n\nA spec may contain multiple links if multiple code files are generated from or described by the spec, but it is best practice to have one spec for one code file.\n\n## Capabilities\n\nList of capabilities of the module.\n\nEach capability:\n\n- Should be precise and concise.\n- Should explicitly describe the _intent_ of the capability, rather than describing the approach.\n- Can optionally have a short description under the title to explain the capability in more detail.\n\nEach capability should be followed by a list of requirements.\n\nEach requirement:\n\n- Should be concise, precise and opinionated on specific behaviors.\n- Can cover internal logic or external behavior.\n- Requirements can be converted into test cases by adding a corresponding [@test](./relative/path/to/test/file) annotation. Test cases must have clearly defined inputs and outputs, as well as setup/mocking notes if needed.\n\nExample:\n\n```markdown\nReverses any string. Preserves capitalization and whitespaces during reversal.\n\n- "hello" becomes "olleh" [@test](./relative/path/to/test/file)\n- "Hello, world!" becomes "!dlrow ,olleH" [@test](./relative/path/to/test/file_impl) { .impl }\n```\n\n## API\n\n- Describe the external interface for the module, including function signatures and parameters with types.\n- Must be wrapped in code block with a language identifier, with an { .api } tag on the block.\n- Should be an appropriate format for the language, and should be consistent with any project configuration provided.\n\n## Dependencies\n\nList of dependencies on other specs, files or external libraries that the module is expected to have. No other dependencies should be assumed, unless explicitly specified in the project configuration or in a user goal. Links can either be to the spec for the module if available, or directly to the code itself if the spec is not available.\n\n- Each lists what is expected from the dependency and has a link to the dependency.\n- New dependencies should only be added when explicitly requested by the user.\n\n- The whole section can be skipped if there are no requirements.\n- Each requirement should have a @use link.\n- For local dependencies, the link will be a relative path, for example [@use](./relative/path/to/dependency-spec)\n- For external dependencies a package name will be used, for example [@use](package-name)\n- For code dependencies, the link will be a relative path, for example [@use](./relative/path/to/code-file).\n\nExample dependencies:\n\n```markdown\n# Dependencies\n\n## Code Dependency Example\n\nDescription of the requirements for the module.\n[@use](./relative/path/to/code-file)\n\n## Spec Dependency Example\n\nDescription of the requirements for the module.\n[@use](./relative/path/to/dependency-spec)\n\n## External Dependency Example\n\nDescription of the requirements for the module.\n[@use](package-name)\n```\n\n## Content tags\n\nSections of the spec can be annotated with tags to explain the prioritization and level of editing that is appropriate. They are most often used for annotating specific tests.\n\nRules for applying tags:\n- By default, do not add tags.\n- Tags applied to a section will apply to all tests in the section.\n- Tests must not have more than one kind. e.g: you should not have a test marked as `impl` and `locked`, or a section marked with both `impl` and a test marked with `locked`.\n- Tests files must not mix test kinds. e.g: you should not have untagged and `locked` tests in the same test file.\n- Locked content must never be edited unless instructed to do so by the user.\n- Content must never be tagged as locked unless explicitly requested by the user.\n\n### Untagged (default)\n\nUntagged content is the standard and is considered draft.\n\nUntagged test cases \n- **Purpose**: Regular test cases that can be modified during development as necessary.\n- **Annotation**: No special class required (default behavior)\n- **Priority**: Medium priority, they can be changed during the development flow as the spec is refined\n\nExample:\n```markdown\n- "hello" becomes "olleh" [@test](./relative/path/to/test/file)\n```\n\n\n### Locked { .locked }\n\nLocked tags capture core functional requirements that should remain stable over time. They represent critical test cases that define the essential behavior of the module that have been confirmed by the user.\n\n- **Purpose**: Capture core functional requirements that should remain stable over time\n- **Annotation**: `{ .locked }` class on individual tests or section headers\n- **Priority**: High priority, they are applied deliberately by the user after reviews have been completed.\n\nExamples:\n```markdown\n- "hello" becomes "olleh" [@test](./relative/path/to/test/file) { .locked }\n\n### Core functionality { .locked }\n- "test1" becomes "1tset" [@test](./relative/path/to/test/file1)\n- "test2" becomes "2tset" [@test](./relative/path/to/test/file2)\n```\n\n### Implementation { .impl }\n\nImplementation tags are used to mark incidental implementation by-products rather than user-specified capabilities. They have lower priority and can be changed more freely.\n\n- **Purpose**: Cover implementation details that were not explicitly specified by the user.\n- **Annotation**: `{ .impl }` class on individual tests or section headers\n- **Priority**: Lower priority, they should be more freely changed if user requirements change.\n\nExamples:\n```markdown\n- "Hello" becomes "olleH" [@test](./relative/path/to/test/file) { .impl }\n\n### Implementation details { .impl }\n- Edge case behavior [@test](./relative/path/to/test/file1)\n- Performance characteristics [@test](./relative/path/to/test/file2)\n```\n\n\n## Example spec (with placeholders for the api details)\n\n````markdown\n# String Reverser\n\nString reverser. Switches the order of characters in a string.\n\n## Target\n\n[@generate](./relative/path/to/code/file)\n\n## Capabilities\n\n### Reverses a string.\n\n- "hello" becomes "olleh" [@test](./relative/path/to/test/file1)\n- "iPhone 5 Samsung" becomes "gnusmaS 5 enohPi" [@test](./relative/path/to/test/file2)\n\n### Reverses within a delimiter.\n\nDelimiter is optional, but if provided, reversing only happens between each delimited block, with block order preserved.\n\n- ("hello friend", " ") becomes "olleh dneirf" [@test](./relative/path/to/test/file4)\n\n### Efficient implementation\n\n- Uses a single pass buffer approach.\n- Doesn\'t modify the original string.\n\n\n## API\n\n```{{LANGUAGE}} { .api }\n\n{{API_CODE}}\n\n```\n\n````\n\n\n',content$2='# Plan Files\n\n**CRITICAL: Create a plan file EVERY TIME you make a plan:**\n\n1. Create a new plan file in the `plans/` directory at the root of the project.\n2. Plan filename format: `YYYY-MM-DD_HH-mm-ss_descriptive-name.plan.md`\n - Example: `2025-08-25_14-37-12_user-authentication.plan.md`\n3. Keep the plan file in sync with your own native task tracking tool.\n4. Update the plan file IMMEDIATELY after completing EACH task. Do NOT batch updates.\n\n## Plan File Structure\n\n### Format\nA plan file is a markdown document (`.plan.md`) that records tasks to achieve a goal, and acts as an audit trail of the plan.\n\n### Components\n1. **Header**: Overall goal and any relevant background context\n2. **Task List**: Markdown checkboxes for each task\n - `- [ ]` for pending tasks\n - `- [x]` for completed tasks\n3. **Task Outputs**: Document results as blockquotes after each task\n\n## Rules for Executing Plans with Plan Files\n\n### 1. Task Documentation\nAfter completing each task, document comprehensively:\n\n- **Update status**: Change checkbox from `[ ]` to `[x]`\n- **Add output**: Create detailed blockquote on new line after task\n- **Document tool calls**: For EVERY tool call (MCP, Bash, Edit, etc.), include:\n - Tool name\n - COMPLETE, VERBATIM parameters (do not summarize), EXCEPTION: do summarize parameters containing file contents\n - Use markdown code blocks for multi-line string parameters (e.g. prompts)\n - Summary of tool output\n- **Include every step in the task**: Document every tool call needed to complete the task\n- **Use separators**: Add `---` and a newline between multiple tool calls in same task\n- **Include full journey**: Document the complete process, including diagnostics and debugging:\n - ALL problems encountered with specific details\n - Each fix attempt and rationale\n - Every diagnostic tool used (exact tool name, summary of parameters and output)\n - Summary of outcome, including initial state (e.g., "7 tests failed out of 12") and final state (e.g., "All 11 tests passing")\n- **Always link to project files**: Include markdown links to any created/read/update/deleted project files:\n - link text: file path relative to the project root\n - link href: file path relative to the plan file\n\n### 2. Plan Updates\n- Modify the plan and plan file as needed when requirements change\n- Add new tasks or remove irrelevant ones\n- Document reasons for significant changes\n\n## Best Practices\nTasks should be:\n- **Specific**: Clear, actionable completion criteria\n- **Atomic**: One logical unit of work per task\n- **Logically Ordered**: Arrange in execution sequence\n- **Well Sized**: Break down complex goals into incremental atomic tasks\n\n## Example\n\n````markdown\n# Plan: Implement User Authentication\n\nAdd secure user authentication with email/password login.\n\n## Tasks\n\n- [x] Create user model spec with email, password hash, and timestamps\n > **MCP** `tessl - create`\n > - spec: specs/models/user.spec.md\n > - prompt:\n > ```\n > Create a User model with the following fields:\n > - id: string (UUID)\n > - email: string (unique, required)\n > - passwordHash: string (required)\n > - createdAt: Date\n > - updatedAt: Date\n >\n > Include methods for:\n > - Password hashing and verification using bcrypt\n > - Email validation\n > - Safe JSON serialization (excludes passwordHash)\n > ```\n >\n > Created [specs/models/user.spec.md](../specs/models/user.spec.md)\n > Model spec created successfully with all required fields and methods.\n\n- [x] Build user model from spec\n > **MCP** `tessl - build`\n > - spec: ["specs/models/user.spec.md"]\n >\n > Generated:\n > - [src/models/user.ts](../src/models/user.ts)\n >\n > Build completed successfully, no errors.\n > ---\n >\n > **Bash** `npm run build`\n > Build failed with TypeScript errors: missing import extensions\n > ---\n >\n > **Edit** `src/models/user.ts`\n > - old_string: import { SomeType } from \'./types\'\n > - new_string: import { SomeType } from \'./types.js\'\n >\n > Updated [src/models/user.ts](../src/models/user.ts).\n > Fixed import to include .js extension for ESM compatibility.\n > ---\n >\n > **MCP** `tessl - document`\n > - spec: specs/models/user.spec.md\n > - includeImplDetails: true\n >\n > Synced [code](../src/models/user.ts) behavior to [spec](../specs/models/user.spec.md)\n\n- [ ] Add database migration for users table\n- [ ] Create authentication service spec\n- [ ] Implement login endpoint\n- [ ] Add session management\n- [ ] Test authentication flow end-to-end\n- [ ] Ask user to manually review and confirm authentication flow is working as expected\n````\n',content$1="\n# Tessl\n\nTessl is a spec driven development framework and toolkit.\n\nAlways use [Spec Driven Development](./docs/spec-driven-development.md) when executing tasks.\n",content="\n# Using the Knowledge Index\n\nRequired dependencies for this projects are documented in the Knowledge Index: `./KNOWLEDGE.md`\n\nBefore starting any work, review the contents of `./KNOWLEDGE.md` to discover the expectations on what dependencies (and which versions) and processes you must follow.\n\nBecause the index can link to a large amount of content, use this workflow to read relevant content:\n\n1. Review `./KNOWLEDGE.md` and check if there any relevant files.\n2. If so, spawn a research subagent with information about your task and a pointer to the files, and ask it to return a relevant summary of context for you to use (but not to do the task). This will prevent you from getting overwhelmed by too much information.\n3. Use the information in your task!\n\nClarify by interviewing the user if the content is not what you expect:\n\n- There's documentation for a dependency you could use, but it isn't the obvious choice. Check if you are expected to use it for the task you are doing.\n- If you are not sure whether to use the version of the dependency from the docs, for example, if you discover that there's a more up to date version of the package.\n- If there's documentation that appears to be missing that would help.\n\nREPEAT this workflow for every new task. The Knowledge Index is updated frequently, so make sure to review it for changes.\n\n# Using the Tessl Spec Registry\n\nDocumentation can be added to the Knowledge Index using the Tessl `registry` tools:\n\n- Search Tessl's Spec Registry for dependency documentation using `search`\n- Install relevant docs into the Knowledge Index using `install`\n\nConsult the Spec Registry when deciding which dependencies to install into a project. Likewise, install the documentation for a given dependency after installing it.\n",FRAMEWORK_FILES={
2463
2458
  "agents.md":content$6,"bootstrap.md":content$5,"plan-files.md":content$2,"tessl-system-prompt.md":content$1,"docs/spec-driven-development.md":content$4,"docs/spec-format.md":content$3},KNOWLEDGE_ONLY_FILES={"usage-specs.md":content};function installFullFrameworkFiles(e){return installFrameworkFiles(e,FRAMEWORK_FILES)}function installKnowledgeFrameworkFiles(e){return installFrameworkFiles(e,KNOWLEDGE_ONLY_FILES)}function installFrameworkFiles(e,t){const r=path__default.resolve(e,DEFAULT_TESSL_DIRS.frameworkDirectory);fs$8.existsSync(r)&&fs$8.rmSync(r,{recursive:!0});const n=[];for(const[i,s]of Object.entries(t)){const t=path__default.join(r,i);fs$8.existsSync(path__default.dirname(t))||fs$8.mkdirSync(path__default.dirname(t),{recursive:!0}),fs$8.writeFileSync(t,s.trim());const o=path__default.relative(e,t);n.push(o)}return n}function setupFramework(e,t){const r=[];if("full"===e){removeHooks(t,KNOWLEDGE_ONLY_HOOKS);const e=installFullFrameworkFiles(t);r.push(...e)
2464
2459
  ;const n=addAgentsMdHooks(t,ALL_TESSL_FRAMEWORK_HOOKS);r.push(...n)}else{removeHooks(t,ALL_TESSL_FRAMEWORK_HOOKS);const e=installKnowledgeFrameworkFiles(t);r.push(...e);const n=addAgentsMdHooks(t,KNOWLEDGE_ONLY_HOOKS);r.push(...n)}return r}function getExistingFrameworkType(e){return hasHooks(e,REQUIRED_TESSL_FRAMEWORK_HOOKS)?"full":hasHooks(e,KNOWLEDGE_ONLY_HOOKS)?"spec-registry":void 0}var ansiEscapes$3={exports:{}},hasRequiredAnsiEscapes$1;function requireAnsiEscapes$1(){return hasRequiredAnsiEscapes$1||(hasRequiredAnsiEscapes$1=1,function(e){const t=e.exports;e.exports.default=t;const r="[",n="]",i="",s=";",o="Apple_Terminal"===process.env.TERM_PROGRAM;t.cursorTo=(e,t)=>{if("number"!=typeof e)throw new TypeError("The `x` argument is required");return"number"!=typeof t?r+(e+1)+"G":r+(t+1)+";"+(e+1)+"H"},t.cursorMove=(e,t)=>{if("number"!=typeof e)throw new TypeError("The `x` argument is required");let n="";return e<0?n+=r+-e+"D":e>0&&(n+=r+e+"C"),t<0?n+=r+-t+"A":t>0&&(n+=r+t+"B"),n
2465
2460
  },t.cursorUp=(e=1)=>r+e+"A",t.cursorDown=(e=1)=>r+e+"B",t.cursorForward=(e=1)=>r+e+"C",t.cursorBackward=(e=1)=>r+e+"D",t.cursorLeft="",t.cursorSavePosition=o?"7":"",t.cursorRestorePosition=o?"8":"",t.cursorGetPosition="",t.cursorNextLine="",t.cursorPrevLine="",t.cursorHide="[?25l",t.cursorShow="[?25h",t.eraseLines=e=>{let r="";for(let n=0;n<e;n++)r+=t.eraseLine+(n<e-1?t.cursorUp():"");return e&&(r+=t.cursorLeft),r},t.eraseEndLine="",t.eraseStartLine="",t.eraseLine="",t.eraseDown="",t.eraseUp="",t.eraseScreen="",t.scrollUp="",t.scrollDown="",t.clearScreen="c",t.clearTerminal="win32"===process.platform?`${t.eraseScreen}${r}0f`:`${t.eraseScreen}${r}3J${r}H`,t.beep=i,t.link=(e,t)=>[n,"8",s,s,t,i,e,n,"8",s,s,i].join(""),t.image=(e,t={})=>{let r=`${n}1337;File=inline=1`;return t.width&&(r+=`;width=${t.width}`),t.height&&(r+=`;height=${t.height}`),!1===t.preserveAspectRatio&&(r+=";preserveAspectRatio=0"),r+":"+e.toString("base64")+i},
@@ -2475,9 +2470,11 @@ ansiEscapes$1.exports}var ansiEscapesExports=requireAnsiEscapes(),ansiEscapes=ge
2475
2470
  ;if(-1===e)throw new ValidationError$1("[select prompt] No selectable choices. All choices are disabled.");return{first:e,last:t}},[l]),p=useMemo(()=>"default"in e?l.findIndex(t=>isSelectable(t)&&t.value===e.default):-1,[e.default,l]),[h,A]=useState(-1===p?d.first:p),f=l[h];useKeypress((e,n)=>{if(clearTimeout(u.current),isEnterKey(e))a("done"),t(f.value);else if(isUpKey(e)||isDownKey(e)){if(n.clearLine(0),r||isUpKey(e)&&h!==d.first||isDownKey(e)&&h!==d.last){const t=isUpKey(e)?-1:1;let r=h;do{r=(r+t+l.length)%l.length}while(!isSelectable(l[r]));A(r)}}else if(isNumberKey(e)&&!Number.isNaN(Number(n.line))){const e=Number(n.line)-1;let t=-1;const r=l.findIndex(r=>!Separator.isSeparator(r)&&(t++,t===e)),i=l[r];null!=i&&isSelectable(i)&&A(r),u.current=setTimeout(()=>{n.clearLine(0)},700)}else if(isBackspaceKey(e))n.clearLine(0);else{const e=n.line.toLowerCase(),t=l.findIndex(t=>!(Separator.isSeparator(t)||!isSelectable(t))&&t.name.toLowerCase().startsWith(e));-1!==t&&A(t),
2476
2471
  u.current=setTimeout(()=>{n.clearLine(0)},700)}}),useEffect(()=>()=>{clearTimeout(u.current)},[]);const g=s.style.message(e.message,o);let m="",y="";("always"===s.helpMode||"auto"===s.helpMode&&i.current)&&(i.current=!1,l.length>n?y=`\n${s.style.help(`(${e.instructions?.pager??"Use arrow keys to reveal more choices"})`)}`:m=s.style.help(`(${e.instructions?.navigation??"Use arrow keys"})`));const E=usePagination({items:l,active:h,renderItem({item:e,isActive:t,index:r}){if(Separator.isSeparator(e))return` ${e.separator}`;const n="number"===s.indexMode?`${r+1}. `:"";if(e.disabled){const t="string"==typeof e.disabled?e.disabled:"(disabled)";return s.style.disabled(`${n}${e.name} ${t}`)}return(t?s.style.highlight:e=>e)(`${t?s.icon.cursor:" "} ${n}${e.name}`)},pageSize:n,loop:r});if("done"===o)return`${c} ${g} ${s.style.answer(f.short)}`;const b=f.description?`\n${s.style.description(f.description)}`:"";return`${[c,g,m].filter(Boolean).join(" ")}\n${E}${y}${b}${ansiEscapes.cursorHide}`})
2477
2472
  ;function getMCPConfig(e){return{mcpServers:{tessl:{type:"stdio",command:"tessl",args:["mcp",...e?["--config-dir","."]:[]]}}}}function createOrAppendMcpConfig(e){mkdirSync$1(dirname$1(e),{recursive:!0});if(!existsSync(e))return writeFileSync$1(e,JSON.stringify(getMCPConfig(e.includes("cursor")),null,2)),relative$1(process.cwd(),e);const t=readFileSync$1(e,"utf-8"),r=JSON.parse(t);if(!("mcpServers"in r)){const t={...r,...getMCPConfig(e.includes("cursor"))};return writeFileSync$1(e,JSON.stringify(t,null,2)+"\n"),relative$1(process.cwd(),e)}if("object"!=typeof r.mcpServers||null===r.mcpServers)throw new Error(`Expected "mcpServers" to be an object in ${e}`);if("tessl"in r.mcpServers)return;const n={...r,mcpServers:{...r.mcpServers,...getMCPConfig(e.includes("cursor")).mcpServers}};return writeFileSync$1(e,JSON.stringify(n,null,2)+"\n"),relative$1(process.cwd(),e)}function addCursorMcpConfig(e=process.cwd()){return createOrAppendMcpConfig(join(e,".cursor","mcp.json"))}
2478
- function addGeminiMcpConfig(e=process.cwd()){return createOrAppendMcpConfig(join(e,".gemini","settings.json"))}function addCodexMcpConfig(){const e=join(homedir$1(),".codex","config.toml");mkdirSync$1(dirname$1(e),{recursive:!0});const t={tessl:{command:"tessl",args:["mcp"]}};if(!existsSync(e)){const r={mcp_servers:t};return writeFileSync$1(e,tomlExports.stringify(r)),relative$1(process.cwd(),e)}const r=readFileSync$1(e,"utf-8"),n=tomlExports.parse(r);if(!("mcp_servers"in n)){const r={...n,mcp_servers:t};return writeFileSync$1(e,tomlExports.stringify(r)),relative$1(process.cwd(),e)}if("object"!=typeof n.mcp_servers||null===n.mcp_servers)throw new Error(`Expected "mcp_servers" to be an object in ${e}`);if("tessl"in n.mcp_servers)return;const i={...n,mcp_servers:{...n.mcp_servers,...t}};return writeFileSync$1(e,tomlExports.stringify(i)),relative$1(process.cwd(),e)}function addClaudeMcpConfig(e=process.cwd()){return createOrAppendMcpConfig(join(e,".mcp.json"))}const AGENT_INFO={amp:{
2479
- label:"Amp",configFile:"AGENTS.md",addMcpConfig:void 0,level:"experimental"},"claude-code":{label:"Claude Code",configFile:"CLAUDE.md",addMcpConfig:addClaudeMcpConfig,level:"core"},cline:{label:"Cline",configFile:"AGENTS.md",addMcpConfig:void 0,level:"experimental"},codex:{label:"Codex",configFile:"AGENTS.md",addMcpConfig:addCodexMcpConfig,level:"alpha"},cursor:{label:"Cursor",configFile:"AGENTS.md",addMcpConfig:addCursorMcpConfig,level:"alpha"},"gemini-cli":{label:"Gemini CLI",configFile:"GEMINI.md",addMcpConfig:addGeminiMcpConfig,level:"alpha"},"github-copilot":{label:"GitHub Copilot",configFile:"AGENTS.md",addMcpConfig:void 0,level:"experimental"},goose:{label:"Goose",configFile:"AGENTS.md",addMcpConfig:void 0,level:"experimental"},opencode:{label:"opencode",configFile:"AGENTS.md",addMcpConfig:void 0,level:"experimental"},windsurf:{label:"Windsurf",configFile:"AGENTS.md",addMcpConfig:void 0,level:"experimental"},zed:{label:"Zed",configFile:"AGENTS.md",addMcpConfig:void 0,
2480
- level:"experimental"}},RECOGNIZED_AGENTS=Object.keys(AGENT_INFO);function ensureAgentFiles(e,t){if(0===e.length)return[];const r=[],n=path__default.join(t,AGENTS_MD_FILENAME);if(!fs$8.existsSync(n))throw new RequiresInitError;const i=path__default.join(t,"TESSL.md");for(const s of e){const e=AGENT_INFO[s].configFile,o=path__default.join(t,e);if(fs$8.existsSync(o)){if(o===n)continue;try{if(fs$8.lstatSync(o).isSymbolicLink()){const e=fs$8.readlinkSync(o);if(path__default.resolve(e)===path__default.resolve(n))continue;path__default.resolve(e)===path__default.resolve(i)&&fs$8.unlinkSync(o)}}catch(t){throw new AggregateError([t],`Failed to process existing file ${e}`)}}fs$8.existsSync(o)||(fs$8.writeFileSync(o,""),r.push({path:e,type:"file",description:"Created agent file"}));const a=`@${AGENTS_MD_FILENAME}`;fs$8.readFileSync(o,"utf-8").includes(a)||fs$8.appendFileSync(o,`\n${a}\n`)}return r}const AGENT_CHOICES=(()=>{
2473
+ function addGeminiMcpConfig(e=process.cwd()){return createOrAppendMcpConfig(join(e,".gemini","settings.json"))}function addCodexMcpConfig(){const e=join(homedir$1(),".codex","config.toml");mkdirSync$1(dirname$1(e),{recursive:!0});const t={tessl:{command:"tessl",args:["mcp"]}};if(!existsSync(e)){const r={mcp_servers:t};return writeFileSync$1(e,tomlExports.stringify(r)),relative$1(process.cwd(),e)}const r=readFileSync$1(e,"utf-8"),n=tomlExports.parse(r);if(!("mcp_servers"in n)){const r={...n,mcp_servers:t};return writeFileSync$1(e,tomlExports.stringify(r)),relative$1(process.cwd(),e)}if("object"!=typeof n.mcp_servers||null===n.mcp_servers)throw new Error(`Expected "mcp_servers" to be an object in ${e}`);if("tessl"in n.mcp_servers)return;const i={...n,mcp_servers:{...n.mcp_servers,...t}};return writeFileSync$1(e,tomlExports.stringify(i)),relative$1(process.cwd(),e)}function addClaudeMcpConfig(e=process.cwd()){return createOrAppendMcpConfig(join(e,".mcp.json"))}
2474
+ const TESSL_RULES_DIR=".cursor/rules/tessl/framework",FRAMEWORK_RULES={"agents.mdc":{content:FRAMEWORK_FILES["agents.md"],description:"Tessl framework",alwaysApply:!0},"bootstrap.mdc":{content:FRAMEWORK_FILES["bootstrap.md"],description:"Configuring a project"},"plan-files.mdc":{content:FRAMEWORK_FILES["plan-files.md"],description:"Planning"},"docs/spec-driven-development.mdc":{content:FRAMEWORK_FILES["docs/spec-driven-development.md"],description:"Spec driven development",alwaysApply:!0},"docs/spec-format.mdc":{content:FRAMEWORK_FILES["docs/spec-format.md"],description:"Spec format"}},KNOWLEDGE_ONLY_RULES={"usage-specs.mdc":{content:KNOWLEDGE_ONLY_FILES["usage-specs.md"],description:"Working with external dependencies",alwaysApply:!0}};function installCursorFiles(e){const t=[],r=path__default.join(e,TESSL_RULES_DIR);if(fs$8.existsSync(r)&&fs$8.rmSync(r,{recursive:!0}),fs$8.mkdirSync(r,{recursive:!0}),
2475
+ "full"===getExistingFrameworkType(e))for(const[n,i]of Object.entries(FRAMEWORK_RULES)){const s=writeMdcContent(r,n,i);t.push(path__default.relative(e,s))}else for(const[n,i]of Object.entries(KNOWLEDGE_ONLY_RULES)){const s=writeMdcContent(r,n,i);t.push(path__default.relative(e,s))}return t}function writeMdcContent(e,t,r){const n=toMdcContent(r),i=path__default.join(e,t);return fs$8.existsSync(path__default.dirname(i))||fs$8.mkdirSync(path__default.dirname(i),{recursive:!0}),fs$8.writeFileSync(i,n),i}function toMdcContent(e){return`---\n${[`description: ${e.description}`,"alwaysApply"in e?`alwaysApply: ${e.alwaysApply}`:"","globs"in e?`globs: ${e.globs}`:""].filter(Boolean).join("\n")}\n---\n${e.content.replaceAll(/((?:\[[^\]]*\]\([^)]*?)|@docs\/[^\s)]+)\.md\b/g,"$1.mdc")}`}const AGENT_INFO={amp:{label:"Amp",configFile:"AGENTS.md",addMcpConfig:void 0,level:"experimental"},"claude-code":{label:"Claude Code",configFile:"CLAUDE.md",addMcpConfig:addClaudeMcpConfig,level:"core"},cline:{
2476
+ label:"Cline",configFile:"AGENTS.md",addMcpConfig:void 0,level:"experimental"},codex:{label:"Codex",configFile:"AGENTS.md",addMcpConfig:addCodexMcpConfig,level:"alpha"},cursor:{label:"Cursor",configFile:"AGENTS.md",addMcpConfig:addCursorMcpConfig,installCustomFiles:installCursorFiles,level:"alpha"},"gemini-cli":{label:"Gemini CLI",configFile:"GEMINI.md",addMcpConfig:addGeminiMcpConfig,level:"alpha"},"github-copilot":{label:"GitHub Copilot",configFile:"AGENTS.md",addMcpConfig:void 0,level:"experimental"},goose:{label:"Goose",configFile:"AGENTS.md",addMcpConfig:void 0,level:"experimental"},opencode:{label:"opencode",configFile:"AGENTS.md",addMcpConfig:void 0,level:"experimental"},windsurf:{label:"Windsurf",configFile:"AGENTS.md",addMcpConfig:void 0,level:"experimental"},zed:{label:"Zed",configFile:"AGENTS.md",addMcpConfig:void 0,level:"experimental"}},RECOGNIZED_AGENTS=Object.keys(AGENT_INFO);function ensureAgentFiles(e,t){if(0===e.length)return[]
2477
+ ;const r=[],n=path__default.join(t,AGENTS_MD_FILENAME);if(!fs$8.existsSync(n))throw new RequiresInitError;const i=path__default.join(t,"TESSL.md");for(const s of e){const e=AGENT_INFO[s].configFile,o=path__default.join(t,e);if(fs$8.existsSync(o)){if(o===n)continue;try{if(fs$8.lstatSync(o).isSymbolicLink()){const e=fs$8.readlinkSync(o);if(path__default.resolve(e)===path__default.resolve(n))continue;path__default.resolve(e)===path__default.resolve(i)&&fs$8.unlinkSync(o)}}catch(t){throw new AggregateError([t],`Failed to process existing file ${e}`)}}fs$8.existsSync(o)||(fs$8.writeFileSync(o,""),r.push({path:e,type:"file",description:"Created agent file"}));const a=`@${AGENTS_MD_FILENAME}`;fs$8.readFileSync(o,"utf-8").includes(a)||fs$8.appendFileSync(o,`\n${a}\n`)}for(const n of e){const e=AGENT_INFO[n];if("installCustomFiles"in e){const n=e.installCustomFiles(t);r.push(...n.map(e=>({path:e,type:"file",description:"Created custom agent file"})))}}return r}const AGENT_CHOICES=(()=>{
2481
2478
  const e=Object.entries(AGENT_INFO).filter(([,e])=>"experimental"!==e.level).map(([e,{label:t,level:r}])=>({name:"core"===r?t:`${t} (Alpha)`,value:e})),t=Object.entries(AGENT_INFO).filter(([,e])=>"experimental"===e.level).map(([e,{label:t}])=>({name:chalk.dim(t),value:e}));return[...e,new Separator("-- Experimental support --"),...t]})();async function promptForAgentSelection(e){if(e&&!RECOGNIZED_AGENTS.includes(e))throw new ExpectedError(`Unsupported agent: ${e}`);let t=e;return t||(t=await select({message:"Which agent would you like to set up?",choices:AGENT_CHOICES,loop:!1})),t}async function promptForMcpSetup(e,t,r){const{addMcpConfig:n,label:i}=AGENT_INFO[e];let s=!1;if(void 0!==n&&!r)try{s=t||await confirm({message:`Would you like to auto-configure Tessl's MCP integration for ${i}?`,default:!0})}catch(e){if(!(e instanceof Error&&"ExitPromptError"===e.name))throw e}return s}async function promptForAgentSetup(e,t,r){try{const n=await promptForAgentSelection(e);return{
2482
2479
  selectedAgent:n,shouldSetupMcp:await promptForMcpSetup(n,t,r),agentLevel:AGENT_INFO[n].level}}catch(e){if(!(e instanceof Error&&"ExitPromptError"===e.name))throw e;return}}function performAgentSetup(e,t,r){const{selectedAgent:n,shouldSetupMcp:i}=e,{addMcpConfig:s}=AGENT_INFO[n],o=ensureAgentFiles([n],t),a=[];let c=!1;if(i&&s){const e=s(t);e&&a.push(e),c=!0}return r.agentSetup({agent:n}),c&&r.mcpSetup({client:n}),{agentFiles:o,mcpFiles:a,didSetupMcp:c}}const DEFAULT_KNOWLEDGE_MD_CONTENT="# Knowledge Index\n\n";function ensureKnowledgeMd(e){const t=path__default.resolve(e,KNOWLEDGE_MD_FILENAME$1);if(!fs$8.existsSync(t)){fs$8.writeFileSync(t,DEFAULT_KNOWLEDGE_MD_CONTENT);return[path__default.relative(e,t)]}return[]}class Initializer{#cr;constructor(e){this.#cr=e}addTesslFiles(e){const t=[],r=process.cwd(),n=ensureTesslJsonSync(r,{name:path__default.basename(r)});n&&t.push(n);const i=path__default.resolve(r,CONFIG_DIR_NAME);fs__default.mkdirSync(i,{recursive:!0})
2483
2480
  ;const s=path__default.resolve(i,".gitignore"),o=path__default.relative(i,DEFAULT_TESSL_DIRS.tmpDirectory);fs__default.writeFileSync(s,`${o}/${EOL}${USAGE_SPEC_DIR_NAME}/${EOL}`),t.push(`${CONFIG_DIR_NAME}/.gitignore`);const a=ensureAgentsMd(r);t.push(...a);const c=setupFramework(e,r);t.push(...c);const u=ensureKnowledgeMd(r);return t.push(...u),[...new Set(t)]}initializeProject(e,t,r){let n=!0;try{return{filesCreated:this.addTesslFiles(t)}}catch(e){throw n=!1,e}finally{this.#cr.init({success:n,isReinitializing:e,type:t,...r?{previousType:r}:{}})}}}function FilesCreated({base:e,filepaths:t}){return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:t.map(t=>jsxRuntimeExports.jsxs(Text,{children:[jsxRuntimeExports.jsx(Text,{color:"green",children:"+"})," ",e&&jsxRuntimeExports.jsxs(Text,{dimColor:!0,children:["/"!==e?e:"","/"]}),t]},t))})}function BigTessl(){return jsxRuntimeExports.jsx(Text,{
@@ -2502,7 +2499,7 @@ message:"\n {bold Continuing will downgrade this project by removing Tessl
2502
2499
  ;return render(jsxRuntimeExports.jsx(Complete$1,{agent:o,createdFiles:a,createdMcpFiles:c,didSetupMcp:u})),SUCCESS}catch(e){if(!(e instanceof Error&&"ExitPromptError"===e.name))throw e;return SUCCESS}}});function Complete$1({agent:e,createdFiles:t,didSetupMcp:r,createdMcpFiles:n}){const i=t.filter(e=>"symlink"===e.type),s=t.filter(e=>"file"===e.type),o=t.filter(e=>"subagent"===e.type),a=AGENT_INFO[e],{label:c}=a;return jsxRuntimeExports.jsx(Box,{gap:1,flexDirection:"column",children:jsxRuntimeExports.jsxs(Box,{flexDirection:"column",marginY:1,children:[jsxRuntimeExports.jsxs(Text,{color:"green",children:[c," configured successfully!"]}),jsxRuntimeExports.jsxs(Text,{children:[c," is now auto-configured to work with Tessl."]}),i.length+s.length+o.length>0&&jsxRuntimeExports.jsxs(Box,{flexDirection:"column",marginTop:1,children:[i.map(e=>jsxRuntimeExports.jsxs(Text,{children:[jsxRuntimeExports.jsx(Text,{color:"green",children:"+"})," ",e.path," ",jsxRuntimeExports.jsxs(Text,{dimColor:!0,
2503
2500
  children:["→ ",e.target]})]},e.path)),s.map(e=>jsxRuntimeExports.jsxs(Text,{children:[jsxRuntimeExports.jsx(Text,{color:"green",children:"+"})," ",e.path," ",e.description&&jsxRuntimeExports.jsxs(Text,{dimColor:!0,children:["(",e.description,")"]})]},e.path)),o.length>0&&o.map(e=>jsxRuntimeExports.jsxs(Box,{flexDirection:"column",children:[jsxRuntimeExports.jsxs(Text,{children:[jsxRuntimeExports.jsx(Text,{color:"green",children:"+"})," ",e.path," ",jsxRuntimeExports.jsx(Text,{dimColor:!0,children:"(Tessl subagent)"})]}),e.description&&jsxRuntimeExports.jsx(Box,{marginLeft:2,children:jsxRuntimeExports.jsx(Text,{dimColor:!0,children:e.description})})]},e.path))]}),r&&jsxRuntimeExports.jsxs(Box,{flexDirection:"column",marginTop:1,children:[jsxRuntimeExports.jsxs(Text,{children:["MCP has been auto-configured for ",c,"."]}),n.map(e=>jsxRuntimeExports.jsxs(Text,{children:[jsxRuntimeExports.jsx(Text,{color:"green",children:"+"})," ",e," "]},e))]}),jsxRuntimeExports.jsx(AgentWarnings,{
2504
2501
  agentLevel:a.level})]})})}function AgentWarnings({agentLevel:e}){return e&&"core"!==e?jsxRuntimeExports.jsxs(Box,{flexDirection:"column",borderStyle:"single",padding:1,children:[jsxRuntimeExports.jsx(Warning,{children:`There are known issues with ${e} agents.`}),jsxRuntimeExports.jsxs(Text,{dimColor:!0,children:["Please refer to"," ",jsxRuntimeExports.jsx(Link,{url:`https://docs.tessl.io/reference/supported-platforms#${e}`,children:`https://docs.tessl.io/reference/supported-platforms#${e}`})," ","for more information."]})]}):null}function _optionalChain$t(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}const initCommand=new Command$1({name:"init",summary:"Initialize Tessl in the current directory. Sets up Tessl context and provides a default AI agent integration via AGENTS.md.",
2505
- requiresConfig:!1,requiresLogin:!1,flags:{force:{type:Boolean,short:"f",description:"Automatically accept the reinitialization prompt"},agent:{type:String,description:"The AI agent that should be configured to work with Tessl"},mcp:{type:Boolean,description:"Automatically configure Tessl MCP for the selected agent (if available)"},"no-mcp":{type:Boolean,description:"Skip configuring Tessl MCP without prompting"}},handler:async e=>await doInit({...e,targetDir:process.cwd()})});async function doInit(e){return e.isAuthenticated?await fullInit(e):await knowledgeOnlyInit(e)}async function ensureInit(e,t){if(await hasTesslJson(e.targetDir))return{isInitialized:!0};return await confirm({message:t,default:!0})?(await doInit(e),await hasTesslJson(e.targetDir)?{isInitialized:!0}:{isInitialized:!1}):{isInitialized:!1}}async function fullInit(e){
2502
+ requiresConfig:!1,requiresLogin:!1,flags:{force:{type:Boolean,short:"f",description:"Automatically accept the reinitialization prompt"},agent:{type:String,description:"The AI agent that should be configured to work with Tessl",availableValues:RECOGNIZED_AGENTS},mcp:{type:Boolean,description:"Automatically configure Tessl MCP for the selected agent (if available)"},"no-mcp":{type:Boolean,description:"Skip configuring Tessl MCP without prompting"}},handler:async e=>await doInit({...e,targetDir:process.cwd()})});async function doInit(e){return e.isAuthenticated?await fullInit(e):await knowledgeOnlyInit(e)}async function ensureInit(e,t){if(await hasTesslJson(e.targetDir))return{isInitialized:!0};return await confirm({message:t,default:!0})?(await doInit(e),await hasTesslJson(e.targetDir)?{isInitialized:!0}:{isInitialized:!1}):{isInitialized:!1}}async function fullInit(e){
2506
2503
  const{targetDir:t,isInteractive:r,monitoring:n,args:{force:i,agent:s,mcp:o,"no-mcp":a}={}}=e,c=await hasTesslJson(t),u=path__default.join(DEFAULT_TESSL_DIRS.frameworkDirectory,"usage-specs.md"),l=fs$8.existsSync(u);if(c&&!i){let e=!1;if(!r)throw new ExpectedError("Tessl is already initialized in this directory. Re-run with --force if you want to initialize anyway in non-interactive mode.");try{if(e=l?await upgradeToFullFrameworkPrompt():await reinitPrompt(),!e)throw new ExpectedError("Initialization cancelled.")}catch(e){if(e instanceof ExitPromptError)return SUCCESS;throw e}}let d;try{(!!s||!c&&r&&await confirm({message:"Would you like to configure an AI agent now?",default:!0}))&&(d=await promptForAgentSetup(s,o,a))}catch(e){if(e instanceof Error&&"ExitPromptError"===e.name)return SUCCESS;n.logger.error({err:e},"Prompting for agent and/or mcp setup failed while initializing Tessl")}const p=new Initializer(n.analytics);return await render(jsxRuntimeExports.jsx(Init,{logger:n.logger,
2507
2504
  initializer:p,isReinitializing:c,framework:"full",existingFramework:getExistingFrameworkType(t),nextSteps:jsxRuntimeExports.jsx(NextSteps,{}),postInitialize:()=>{if(!d)return[];try{const{agentFiles:e,mcpFiles:r}=performAgentSetup(d,t,n.analytics);return[...e.map(e=>e.path),...r]}catch(e){return n.logger.error({err:e},"Setting up agent and/or mcp failed while initializing Tessl"),[]}},targetDir:t,agentLevel:_optionalChain$t([d,"optionalAccess",e=>e.agentLevel])})).waitUntilExit(),SUCCESS}async function knowledgeOnlyInit(e){const{targetDir:t,isInteractive:r,monitoring:n,args:{force:i,agent:s,mcp:o,"no-mcp":a}={}}=e,c=await hasTesslJson(t),u=path__default.join(DEFAULT_TESSL_DIRS.frameworkDirectory,"agents.md"),l=fs$8.existsSync(u);if(c&&!i){let e=!1;if(!r)throw new ExpectedError("Tessl is already initialized in this directory. Re-run with --force if you want to initialize anyway in non-interactive mode.");try{if(e=l?await downgradeToSpecRegistryFrameworkPrompt():await reinitPrompt(),
2508
2505
  !e)throw new ExpectedError("Initialization cancelled.")}catch(e){if(e instanceof Error&&"ExitPromptError"===e.name)return SUCCESS;throw e}}let d;try{(!!s||!c&&r&&await confirm({message:"Would you like to configure an AI agent now?",default:!0}))&&(d=await promptForAgentSetup(s,o,a))}catch(e){if(e instanceof Error&&"ExitPromptError"===e.name)return SUCCESS;n.logger.error({err:e},"Prompting for agent and/or mcp setup failed while initializing Tessl")}const p=new Initializer(n.analytics);return await render(jsxRuntimeExports.jsx(Init,{logger:n.logger,initializer:p,isReinitializing:c,framework:"spec-registry",existingFramework:getExistingFrameworkType(t),nextSteps:jsxRuntimeExports.jsx(KnowledgeOnlyNextSteps,{}),targetDir:t,postInitialize:()=>{if(!d)return[];try{const{agentFiles:e,mcpFiles:r}=performAgentSetup(d,t,n.analytics);return[...e.map(e=>e.path),...r]}catch(e){return n.logger.error({err:e},"Setting up agent and/or mcp failed while initializing Tessl"),[]}},
@@ -3257,8 +3254,8 @@ const r=Math.floor(Math.random()*t.length),n=t[r];return e[n]}}),cliSpinners=e}v
3257
3254
  children:[jsxRuntimeExports.jsx(Dimdent,{}),r,jsxRuntimeExports.jsx(Text,{color:"green",children:t.message.replace("{progress}",_nullishCoalesce$l(_optionalChain$p([t,"access",e=>e.progress,"optionalAccess",e=>e.toString,"call",e=>e()]),()=>"")).replace("{total}",_nullishCoalesce$l(_optionalChain$p([t,"access",e=>e.total,"optionalAccess",e=>e.toString,"call",e=>e()]),()=>""))})]})}function _nullishCoalesce$k(e,t){return null!=e?e:t()}function _optionalChain$o(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function ActivityItem({activity:e}){return e.end?null:void 0===e.total?jsxRuntimeExports.jsx(Box,{children:jsxRuntimeExports.jsxs(Text,{color:"yellow",children:[jsxRuntimeExports.jsx(NonBlockingSpinner,{})," ",e.message]})
3258
3255
  }):e.children?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[e.children.map(e=>jsxRuntimeExports.jsx(Box,{children:jsxRuntimeExports.jsx(Action,{message:{content:{result:"running",message:e.message}}})},e.id)),jsxRuntimeExports.jsx(Box,{children:jsxRuntimeExports.jsx(ProgressBar,{message:{content:{message:e.message,progress:e.progress,total:e.total}}})})]}):null}const TypingIndicator=React.memo(function({totalTokens:e}){return void 0===e?null:jsxRuntimeExports.jsx(Box,{children:jsxRuntimeExports.jsxs(Text,{color:"cyan",children:[jsxRuntimeExports.jsx(NonBlockingSpinner,{})," Generating…",e>0&&` (${e} tokens)`]})})}),Activities=React.memo(function({activities:e,activeTypers:t}){const r=reactExports.useMemo(()=>{if(t&&0!==t.size)return Math.ceil(Array.from(t.values()).map(e=>e.characterCount).reduce((e,t)=>e+t,0)/4)},[t]),n=(()=>{const t=new Map,r=[],n=e.filter(e=>!e.end);return n.forEach(e=>{t.set(e.id,{...e,children:[]})}),n.forEach(e=>{const n=t.get(e.id);if(e.parentId){
3259
3256
  const i=t.get(e.parentId);i?i.children.push(n):r.push(n)}else r.push(n)}),r})();return 0===n.length&&0===_nullishCoalesce$k(_optionalChain$o([t,"optionalAccess",e=>e.size]),()=>0)?null:jsxRuntimeExports.jsxs(Box,{flexDirection:"column",marginBottom:1,children:[n.map(e=>jsxRuntimeExports.jsx(ActivityItem,{activity:e},e.id)),0===n.length&&jsxRuntimeExports.jsx(TypingIndicator,{totalTokens:r})]})});function Alert$1({message:e}){const t={info:void 0,warning:"yellow",error:"red",success:"green"}[e.content.severity];return jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Dimdent,{}),jsxRuntimeExports.jsxs(Text,{color:t,children:[e.content.message," "]})]})}function Heading$1({message:e}){return jsxRuntimeExports.jsxs(Box,{marginTop:1,gap:1,children:[jsxRuntimeExports.jsx(Text,{dimColor:!0,children:figures.lozenge}),jsxRuntimeExports.jsx(Text,{bold:!0,children:e.content})]})}function _nullishCoalesce$j(e,t){return null!=e?e:t()}function List({message:e}){
3260
- return jsxRuntimeExports.jsxs(Text,{children:[e.content.title&&`${e.content.title}: \n`,e.content.items.map(t=>`${_nullishCoalesce$j(e.content.bullet,()=>"-")} ${t}`).join("\n")]})}var cjs,hasRequiredCjs;function requireCjs(){if(hasRequiredCjs)return cjs;hasRequiredCjs=1;var e=function(e){return function(e){return!!e&&"object"==typeof e}(e)&&!function(e){var r=Object.prototype.toString.call(e);return"[object RegExp]"===r||"[object Date]"===r||function(e){return e.$$typeof===t}(e)}(e)};var t="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function r(e,t){return!1!==t.clone&&t.isMergeableObject(e)?a(function(e){return Array.isArray(e)?[]:{}}(e),e,t):e}function n(e,t,n){return e.concat(t).map(function(e){return r(e,n)})}function i(e){return Object.keys(e).concat(function(e){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e).filter(function(t){return Object.propertyIsEnumerable.call(e,t)}):[]}(e))}function s(e,t){try{return t in e}catch(e){return!1}
3261
- }function o(e,t,n){var o={};return n.isMergeableObject(e)&&i(e).forEach(function(t){o[t]=r(e[t],n)}),i(t).forEach(function(i){(function(e,t){return s(e,t)&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))})(e,i)||(s(e,i)&&n.isMergeableObject(t[i])?o[i]=function(e,t){if(!t.customMerge)return a;var r=t.customMerge(e);return"function"==typeof r?r:a}(i,n)(e[i],t[i],n):o[i]=r(t[i],n))}),o}function a(t,i,s){(s=s||{}).arrayMerge=s.arrayMerge||n,s.isMergeableObject=s.isMergeableObject||e,s.cloneUnlessOtherwiseSpecified=r;var a=Array.isArray(i);return a===Array.isArray(t)?a?s.arrayMerge(t,i,s):o(t,i,s):r(i,s)}return a.all=function(e,t){if(!Array.isArray(e))throw new Error("first argument should be an array");return e.reduce(function(e,r){return a(e,r,t)},{})},cjs=a}requireCjs();const colorByVariant$1={info:"blue",success:"green",error:"red",warning:"yellow"},theme$c={styles:{container:({variant:e})=>({flexGrow:1,borderStyle:"round",borderColor:colorByVariant$1[e],gap:1,
3257
+ return jsxRuntimeExports.jsxs(Text,{children:[e.content.title&&`${e.content.title}: \n`,e.content.items.map(t=>`${_nullishCoalesce$j(e.content.bullet,()=>"-")} ${t}`).join("\n")]})}var cjs,hasRequiredCjs;function requireCjs(){if(hasRequiredCjs)return cjs;hasRequiredCjs=1;var e=function(e){return function(e){return!!e&&"object"==typeof e}(e)&&!function(e){var r=Object.prototype.toString.call(e);return"[object RegExp]"===r||"[object Date]"===r||function(e){return e.$$typeof===t}(e)}(e)};var t="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function r(e,t){return!1!==t.clone&&t.isMergeableObject(e)?a((r=e,Array.isArray(r)?[]:{}),e,t):e;var r}function n(e,t,n){return e.concat(t).map(function(e){return r(e,n)})}function i(e){return Object.keys(e).concat(function(e){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e).filter(function(t){return Object.propertyIsEnumerable.call(e,t)}):[]}(e))}function s(e,t){try{return t in e}catch(e){return!1}}
3258
+ function o(e,t,n){var o={};return n.isMergeableObject(e)&&i(e).forEach(function(t){o[t]=r(e[t],n)}),i(t).forEach(function(i){(function(e,t){return s(e,t)&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))})(e,i)||(s(e,i)&&n.isMergeableObject(t[i])?o[i]=function(e,t){if(!t.customMerge)return a;var r=t.customMerge(e);return"function"==typeof r?r:a}(i,n)(e[i],t[i],n):o[i]=r(t[i],n))}),o}function a(t,i,s){(s=s||{}).arrayMerge=s.arrayMerge||n,s.isMergeableObject=s.isMergeableObject||e,s.cloneUnlessOtherwiseSpecified=r;var a=Array.isArray(i);return a===Array.isArray(t)?a?s.arrayMerge(t,i,s):o(t,i,s):r(i,s)}return a.all=function(e,t){if(!Array.isArray(e))throw new Error("first argument should be an array");return e.reduce(function(e,r){return a(e,r,t)},{})},cjs=a}requireCjs();const colorByVariant$1={info:"blue",success:"green",error:"red",warning:"yellow"},theme$c={styles:{container:({variant:e})=>({flexGrow:1,borderStyle:"round",borderColor:colorByVariant$1[e],gap:1,
3262
3259
  paddingX:1}),iconContainer:()=>({flexShrink:0}),icon:({variant:e})=>({color:colorByVariant$1[e]}),content:()=>({flexShrink:1,flexGrow:1,minWidth:0,flexDirection:"column",gap:1}),title:()=>({bold:!0}),message:()=>({})},config({variant:e}){let t;return"info"===e&&(t=figures.info),"success"===e&&(t=figures.tick),"error"===e&&(t=figures.cross),"warning"===e&&(t=figures.warning),{icon:t}}},theme$b={styles:{container:({color:e})=>({backgroundColor:e}),label:()=>({color:"black"})}},theme$a={styles:{input:({isFocused:e})=>({dimColor:!e})}},theme$9={styles:{container:()=>({flexDirection:"column"}),option:({isFocused:e})=>({gap:1,paddingLeft:e?0:2}),selectedIndicator:()=>({color:"green"}),focusIndicator:()=>({color:"blue"}),label({isFocused:e,isSelected:t}){let r;return t&&(r="green"),e&&(r="blue"),{color:r}},highlightedText:()=>({bold:!0})}},theme$8={styles:{list:()=>({flexDirection:"column"}),listItem:()=>({gap:1}),marker:()=>({dimColor:!0}),content:()=>({flexDirection:"column"})}},theme$7={
3263
3260
  styles:{container:()=>({flexGrow:1,minWidth:0}),completed:()=>({color:"magenta"}),remaining:()=>({dimColor:!0})},config:()=>({completedCharacter:figures.square,remainingCharacter:figures.squareLightShade})},theme$6={styles:{container:()=>({flexDirection:"column"}),option:({isFocused:e})=>({gap:1,paddingLeft:e?0:2}),selectedIndicator:()=>({color:"green"}),focusIndicator:()=>({color:"blue"}),label({isFocused:e,isSelected:t}){let r;return t&&(r="green"),e&&(r="blue"),{color:r}},highlightedText:()=>({bold:!0})}},theme$5={styles:{container:()=>({gap:1}),frame:()=>({color:"blue"}),label:()=>({})}},colorByVariant={success:"green",error:"red",warning:"yellow",info:"blue"},iconByVariant={success:figures.tick,error:figures.cross,warning:figures.warning,info:figures.info},theme$4={styles:{container:()=>({gap:1}),iconContainer:()=>({flexShrink:0}),icon:({variant:e})=>({color:colorByVariant[e]}),message:()=>({})},config:({variant:e})=>({icon:iconByVariant[e]})},theme$3={styles:{list:()=>({
3264
3261
  flexDirection:"column"}),listItem:()=>({gap:1}),marker:()=>({dimColor:!0}),content:()=>({flexDirection:"column"})},config:()=>({marker:figures.line})},theme$2={styles:{value:()=>({})}},theme$1={styles:{value:()=>({})}},theme={styles:{value:()=>({})}},defaultTheme={components:{Alert:theme$c,Badge:theme$b,ConfirmInput:theme$a,MultiSelect:theme$9,OrderedList:theme$8,ProgressBar:theme$7,Select:theme$6,Spinner:theme$5,StatusMessage:theme$4,UnorderedList:theme$3,TextInput:theme$2,EmailInput:theme$1,PasswordInput:theme}},ThemeContext=reactExports.createContext(defaultTheme),useComponentTheme=e=>reactExports.useContext(ThemeContext).components[e],defaultMarker=figures.line;function Alert({children:e,variant:t,title:r}){const{styles:n,config:i}=useComponentTheme("Alert");return React.createElement(Box,{...n.container({variant:t})},React.createElement(Box,{...n.iconContainer()},React.createElement(Text,{...n.icon({variant:t})},i({variant:t}).icon)),React.createElement(Box,{...n.content()
@@ -3270,10 +3267,10 @@ function Summary({messages:e}){const t=e.filter(e=>"report"===e.id&&"message"===
3270
3267
  children:[u,jsxRuntimeExports.jsx(Activities,{activities:r,activeTypers:i}),hasEnded(s)&&jsxRuntimeExports.jsxs(Box,{flexDirection:"column",children:[!c&&jsxRuntimeExports.jsx(Overview,{getTotalTokenCount:n,executionTree:s,fileDiff:isFsDiff(o)?o.diff():void 0}),jsxRuntimeExports.jsx(Summary,{messages:t})]})]})}function Sidecar({tailer:e}){const[t,r]=reactExports.useState(null),{messages:n,activities:i,hideOverview:s,handleManagementEvent:o,executionTree:a}=useReporterState(),c=reactExports.useRef(!1);return reactExports.useEffect(()=>{if(c.current)return;c.current=!0;(async()=>{try{await e.start({onEvent:e=>{o(e).catch(e=>{r(`Error handling event: ${String(e)}`)})},onError:e=>{r(`Error while tailing events: ${String(e)}`)},onShutdown:()=>{}})}catch(e){r(`Failed to start event observation: ${String(e)}`)}})().catch(e=>{r(`Failed to start tailing: ${String(e)}`)})},[e,o]),t?jsxRuntimeExports.jsx(Text,{children:t}):jsxRuntimeExports.jsx(ToolResults,{mode:"observe",messages:n,activities:i,
3271
3268
  getTotalTokenCount:()=>0,activeTypers:new Map,executionTree:a,fsd:null,staticMessages:!0,hideOverview:s})}reactExports.createContext({marker:defaultMarker}),reactExports.createContext({depth:0}),chalk.inverse(" "),reactExports.createContext({marker:figures.line}),reactExports.createContext({marker:""}),chalk.inverse(" "),chalk.inverse(" ");const observeCommand=new Command$1({name:"observe",summary:"[Experimental] Provides a real-time view of Tessl activity for the current project. Run in a directory initialized with Tessl. Best used in a separate window.",requiresConfig:!1,flags:{},handler:async()=>{const e=getSessionDataPath(),t=path__default$1.join(e,"events.jsonl"),r=new EventTailer(t),n=render(jsxRuntimeExports.jsx(Sidecar,{tailer:r})),i=()=>{r.stop(),n.unmount()};process.on("SIGINT",i),process.on("SIGTERM",i);try{await n.waitUntilExit()}finally{process.removeListener("SIGINT",i),process.removeListener("SIGTERM",i)}return SUCCESS}});function createSpinner(e){return ora({
3272
3269
  hideCursor:!1,discardStdin:!1}).start(e)}const registryArchiveCommand=new Command$1({name:"registry-archive",summary:"Archive specs in the Tessl registry",allowArbitraryFlags:!1,flags:{spec:{type:String,description:"The full name of the spec to archive"},reason:{type:String,description:"The reason for archiving the specs"}},requiresLogin:!0,requiresConfig:!1,handler:async({monitoring:{logger:e},args:t,tesslClient:r})=>{const{spec:n,reason:i}=t;if(!n)throw new ExpectedError('A --spec argument is required, in the format "workspace/spec@version"');if(!i)throw new ExpectedError("A --reason argument is required");const[s,o]=n.split("@");if(!s||!o)throw new ExpectedError('The spec must be in the format "workspace/spec@version"');const[a,c]=s.split("/");if(!a||!c)throw new ExpectedError('The spec must be in the format "workspace/tile"');const u=createSpinner("Archiving"),l=await r.POST("/v1/tiles/{workspaceName}/{tileName}/versions/{version}",{params:{path:{workspaceName:a,tileName:c,
3273
- version:o}},body:{archived:!0,archivedReason:i}});return l.error?(e.error({err:l.error},"Failed to archive spec"),u.fail(apiErrToString(l.error)),FAILURE):(u.succeed(`Archived ${a}/${c}@${o}`),SUCCESS)}});function _nullishCoalesce$i(e,t){return null!=e?e:t()}const installCommand=new Command$1({name:"registry-install",summary:"Install usage specs into your project",positionals:[{name:"name",description:"The name of the usage spec to install"}],allowArbitraryFlags:!1,requiresLogin:!1,requiresConfig:!1,handler:async({positionals:{name:e},monitoring:{analytics:t,logger:r},projectDir:n,isInteractive:i,tesslClient:s,isAuthenticated:o,monitoring:a})=>{if(!i)throw new ExpectedError('"install" does not support non-interactive mode');const{isInitialized:c}=await ensureInit({targetDir:n,isAuthenticated:o,isInteractive:i,monitoring:a,args:{"no-mcp":!0}},"Usage specs require Tessl to be initialized. Would you like to initialize Tessl now?");if(!c)return SUCCESS;const u=openFsd(n);if(!e){
3274
- const e=ora({hideCursor:!1,discardStdin:!1}).start("Installing usage specs"),t=await syncUsageSpecs(n,u,s);return t.success?(e.succeed("Installed usage specs"),SUCCESS):(r.error({err:t.error},"Failed to sync usage specs"),e.fail(t.error),FAILURE)}const l=ora({hideCursor:!1,discardStdin:!1}).start("Retrieving spec data"),d=e.split("@"),p=d[0];let h=d[1];const[A,f]=_nullishCoalesce$i(p,()=>"").split("/");if(!A||!f)return r.error({name:e},'The name argument must be in the format "workspace/tile" (or "workspace/tile@version")'),l.fail('The name argument must be in the format "workspace/tile" (or "workspace/tile@version")'),FAILURE;const g=await s.GET("/v1/tiles/{workspaceName}/{tileName}",{params:{path:{workspaceName:A,tileName:f}}});if(g.error)return r.error({name:e,err:g.error},"Failed to get tile"),l.fail(apiErrToString(g.error)),FAILURE;const m=g.data.data;if(!h){const e=m.attributes.latestVersion;if(!e)return r.error({fullName:p
3275
- },"The tile does not have a latest version. Please specify a version"),l.fail("The tile does not have a latest version. Please specify a version"),FAILURE;h=e}const y=await s.GET("/v1/tiles/{workspaceName}/{tileName}/versions/{version}",{params:{path:{workspaceName:A,tileName:f,version:h}}});if(y.error)return r.error({fullName:p,version:h,err:y.error},"Failed to get tile version"),l.fail(apiErrToString(y.error)),FAILURE;const E=y.data.data;if(!E.attributes.describes)return r.error({name:e,version:h},"Invalid usage spec; does not describe a package"),l.fail("Invalid usage spec; does not describe a package"),FAILURE;l.text=`Installing ${m.attributes.fullName}@${h}`;const b={workspaceName:A,tileName:f,version:E.attributes.version},C=await downloadTile(n,s,b);if(!C.success)return r.error({name:e,version:h,err:C.error},"Failed to download usage spec"),l.fail(C.error),FAILURE;const v=await updateTesslJsonDependencies(u,{add:[{workspaceName:A,tileName:f,newVersion:E.attributes.version}]})
3276
- ;if(!v.success)return r.error({name:e,version:h,err:v.error},"Failed to update Tessl JSON dependencies"),l.fail(v.error),FAILURE;const I=await syncUsageSpecs(n,u,s);return I.success?(r.info({name:e,version:h},"Usage spec installed"),l.succeed(`Installed ${m.attributes.fullName}@${h}`),t.tileInstall(b),SUCCESS):(r.error({name:e,err:I.error},"Failed to sync usage specs"),l.fail(stripIndents`${I.error}
3270
+ version:o}},body:{archived:!0,archivedReason:i}});return l.error?(e.error({err:l.error},"Failed to archive spec"),u.fail(apiErrToString(l.error)),FAILURE):(u.succeed(`Archived ${a}/${c}@${o}`),SUCCESS)}});function _nullishCoalesce$i(e,t){return null!=e?e:t()}const installCommand=new Command$1({name:"registry-install",summary:"Install usage specs into your project",positionals:[{name:"name",description:"The name of the usage spec to install"}],allowArbitraryFlags:!1,requiresLogin:!1,requiresConfig:!1,handler:async({positionals:{name:e},monitoring:{analytics:t,logger:r},projectDir:n,isInteractive:i,tesslClient:s,isAuthenticated:o,monitoring:a})=>{const{isInitialized:c}=await ensureInit({targetDir:n,isAuthenticated:o,isInteractive:i,monitoring:a,args:{"no-mcp":!0}},"Usage specs require Tessl to be initialized. Would you like to initialize Tessl now?");if(!c)return SUCCESS;const u=openFsd(n);if(!e){const e=createSpinner("Installing usage specs"),t=await syncUsageSpecs(n,u,s)
3271
+ ;return t.success?(e.succeed("Installed usage specs"),SUCCESS):(r.error({err:t.error},"Failed to sync usage specs"),e.fail(t.error),FAILURE)}const l=createSpinner("Retrieving spec data"),d=e.split("@"),p=d[0];let h=d[1];const[A,f]=_nullishCoalesce$i(p,()=>"").split("/");if(!A||!f)return r.error({name:e},'The name argument must be in the format "workspace/tile" (or "workspace/tile@version")'),l.fail('The name argument must be in the format "workspace/tile" (or "workspace/tile@version")'),FAILURE;const g=await s.GET("/v1/tiles/{workspaceName}/{tileName}",{params:{path:{workspaceName:A,tileName:f}}});if(g.error)return r.error({name:e,err:g.error},"Failed to get tile"),l.fail(apiErrToString(g.error)),FAILURE;const m=g.data.data;if(!h){const e=m.attributes.latestVersion;if(!e)return r.error({fullName:p},"The tile does not have a latest version. Please specify a version"),l.fail("The tile does not have a latest version. Please specify a version"),FAILURE;h=e}
3272
+ const y=await s.GET("/v1/tiles/{workspaceName}/{tileName}/versions/{version}",{params:{path:{workspaceName:A,tileName:f,version:h}}});if(y.error)return r.error({fullName:p,version:h,err:y.error},"Failed to get tile version"),l.fail(apiErrToString(y.error)),FAILURE;const E=y.data.data;if(!E.attributes.describes)return r.error({name:e,version:h},"Invalid usage spec; does not describe a package"),l.fail("Invalid usage spec; does not describe a package"),FAILURE;l.text=`Installing ${m.attributes.fullName}@${h}`;const b={workspaceName:A,tileName:f,version:E.attributes.version},C=await downloadTile(n,s,b);if(!C.success)return r.error({name:e,version:h,err:C.error},"Failed to download usage spec"),l.fail(C.error),FAILURE;const v=await updateTesslJsonDependencies(u,{add:[{workspaceName:A,tileName:f,newVersion:E.attributes.version}]});if(!v.success)return r.error({name:e,version:h,err:v.error},"Failed to update Tessl JSON dependencies"),l.fail(v.error),FAILURE
3273
+ ;const I=await syncUsageSpecs(n,u,s);return I.success?(r.info({name:e,version:h},"Usage spec installed"),l.succeed(`Installed ${m.attributes.fullName}@${h}`),t.tileInstall(b),SUCCESS):(r.error({name:e,err:I.error},"Failed to sync usage specs"),l.fail(stripIndents`${I.error}
3277
3274
 
3278
3275
  ${m.attributes.fullName}@${h} added to tessl.json, but dependency sync failed.
3279
3276
  Your agent won't have access to the newly installed usage spec until this is fixed.
@@ -3398,8 +3395,8 @@ Y("braces");const e={type:"brace",value:q,output:"(",outputIndex:P.output.length
3398
3395
  value:q,output:""});continue}const s=P.braces>0&&("comma"===t.type||"brace"===t.type),o=O.length&&("pipe"===t.type||"paren"===t.type);if(!n&&"paren"!==t.type&&!s&&!o){K({type:"star",value:q,output:""});continue}for(;"/**"===e.slice(0,3);){const t=l[P.index+4];if(t&&"/"!==t)break;e=e.slice(3),W("/**",3)}if("bos"===t.type&&j()){U.type="globstar",U.value+=q,U.output=F(p),P.output=U.output,P.globstar=!0,W(q);continue}if("slash"===t.type&&"bos"!==t.prev.type&&!i&&j()){P.output=P.output.slice(0,-(t.output+U.output).length),t.output=`(?:${t.output}`,U.type="globstar",U.output=F(p)+(p.strictSlashes?")":"|$)"),U.value+=q,P.globstar=!0,P.output+=t.output+U.output,W(q);continue}if("slash"===t.type&&"bos"!==t.prev.type&&"/"===e[0]){const r=void 0!==e[1]?"|$":"";P.output=P.output.slice(0,-(t.output+U.output).length),t.output=`(?:${t.output}`,U.type="globstar",U.output=`${F(p)}${I}|${I}${r})`,U.value+=q,P.output+=t.output+U.output,P.globstar=!0,W(q+H()),K({type:"slash",value:"/",output:""});continue
3399
3396
  }if("bos"===t.type&&"/"===e[0]){U.type="globstar",U.value+=q,U.output=`(?:^|${I}|${F(p)}${I})`,P.output=U.output,P.globstar=!0,W(q+H()),K({type:"slash",value:"/",output:""});continue}P.output=P.output.slice(0,-U.output.length),U.type="globstar",U.output=F(p),U.value+=q,P.output+=U.output,P.globstar=!0,W(q);continue}const r={type:"star",value:q,output:N};!0!==p.bash?!U||"bracket"!==U.type&&"paren"!==U.type||!0!==p.regex?(P.index!==P.start&&"slash"!==U.type&&"dot"!==U.type||("dot"===U.type?(P.output+=w,U.output+=w):!0===p.dot?(P.output+=R,U.output+=R):(P.output+=k,U.output+=k),"*"!==G()&&(P.output+=_,U.output+=_)),K(r)):(r.output=q,K(r)):(r.output=".*?","bos"!==U.type&&"slash"!==U.type||(r.output=k+r.output),K(r))}for(;P.brackets>0;){if(!0===p.strictBrackets)throw new SyntaxError(c("closing","]"));P.output=t.escapeLast(P.output,"["),J("brackets")}for(;P.parens>0;){if(!0===p.strictBrackets)throw new SyntaxError(c("closing",")"));P.output=t.escapeLast(P.output,"("),J("parens")}
3400
3397
  for(;P.braces>0;){if(!0===p.strictBrackets)throw new SyntaxError(c("closing","}"));P.output=t.escapeLast(P.output,"{"),J("braces")}if(!0===p.strictSlashes||"star"!==U.type&&"bracket"!==U.type||K({type:"maybe_slash",value:"",output:`${I}?`}),!0===P.backtrack){P.output="";for(const e of P.tokens)P.output+=null!=e.output?e.output:e.value,e.suffix&&(P.output+=e.suffix)}return P};return u.fastpaths=(n,i)=>{const s={...i},a="number"==typeof s.maxLength?Math.min(r,s.maxLength):r,c=n.length;if(c>a)throw new SyntaxError(`Input length: ${c}, exceeds maximum allowed length: ${a}`);n=o[n]||n;const u=t.isWindows(i),{DOT_LITERAL:l,SLASH_LITERAL:d,ONE_CHAR:p,DOTS_SLASH:h,NO_DOT:A,NO_DOTS:f,NO_DOTS_SLASH:g,STAR:m,START_ANCHOR:y}=e.globChars(u),E=s.dot?f:A,b=s.dot?g:A,C=s.capture?"":"?:";let v=!0===s.bash?".*?":m;s.capture&&(v=`(${v})`);const I=e=>!0===e.noglobstar?v:`(${C}(?:(?!${y}${e.dot?h:l}).)*?)`,_=e=>{switch(e){case"*":return`${E}${p}${v}`;case".*":return`${l}${p}${v}`;case"*.*":
3401
- return`${E}${v}${l}${p}${v}`;case"*/*":return`${E}${v}${d}${p}${b}${v}`;case"**":return E+I(s);case"**/*":return`(?:${E}${I(s)}${d})?${b}${p}${v}`;case"**/*.*":return`(?:${E}${I(s)}${d})?${b}${v}${l}${p}${v}`;case"**/.*":return`(?:${E}${I(s)}${d})?${l}${p}${v}`;default:{const t=/^(.*?)\.(\w+)$/.exec(e);if(!t)return;const r=_(t[1]);if(!r)return;return r+l+t[2]}}},S=t.removePrefix(n,{negated:!1,prefix:""});let D=_(S);return D&&!0!==s.strictSlashes&&(D+=`${d}?`),D},parse_1$2=u}function requirePicomatch$1(){if(hasRequiredPicomatch$1)return picomatch_1;hasRequiredPicomatch$1=1;const e=path__default,t=requireScan(),r=requireParse$3(),n=requireUtils$3(),i=requireConstants$7(),s=(e,t,r=!1)=>{if(Array.isArray(e)){const n=e.map(e=>s(e,t,r)),i=e=>{for(const t of n){const r=t(e);if(r)return r}return!1};return i}const i=(e=>e&&"object"==typeof e&&!Array.isArray(e))(e)&&e.tokens&&e.input;if(""===e||"string"!=typeof e&&!i)throw new TypeError("Expected pattern to be a non-empty string")
3402
- ;const o=t||{},a=n.isWindows(t),c=i?s.compileRe(e,t):s.makeRe(e,t,!1,!0),u=c.state;delete c.state;let l=()=>!1;if(o.ignore){const e={...t,ignore:null,onMatch:null,onResult:null};l=s(o.ignore,e,r)}const d=(r,n=!1)=>{const{isMatch:i,match:d,output:p}=s.test(r,c,t,{glob:e,posix:a}),h={glob:e,state:u,regex:c,posix:a,input:r,output:p,match:d,isMatch:i};return"function"==typeof o.onResult&&o.onResult(h),!1===i?(h.isMatch=!1,!!n&&h):l(r)?("function"==typeof o.onIgnore&&o.onIgnore(h),h.isMatch=!1,!!n&&h):("function"==typeof o.onMatch&&o.onMatch(h),!n||h)};return r&&(d.state=u),d};return s.test=(e,t,r,{glob:i,posix:o}={})=>{if("string"!=typeof e)throw new TypeError("Expected input to be a string");if(""===e)return{isMatch:!1,output:""};const a=r||{},c=a.format||(o?n.toPosixSlashes:null);let u=e===i,l=u&&c?c(e):e;return!1===u&&(l=c?c(e):e,u=l===i),!1!==u&&!0!==a.capture||(u=!0===a.matchBase||!0===a.basename?s.matchBase(e,t,r,o):t.exec(l)),{isMatch:Boolean(u),match:u,output:l}},
3398
+ return`${E}${v}${l}${p}${v}`;case"*/*":return`${E}${v}${d}${p}${b}${v}`;case"**":return E+I(s);case"**/*":return`(?:${E}${I(s)}${d})?${b}${p}${v}`;case"**/*.*":return`(?:${E}${I(s)}${d})?${b}${v}${l}${p}${v}`;case"**/.*":return`(?:${E}${I(s)}${d})?${l}${p}${v}`;default:{const t=/^(.*?)\.(\w+)$/.exec(e);if(!t)return;const r=_(t[1]);if(!r)return;return r+l+t[2]}}},S=t.removePrefix(n,{negated:!1,prefix:""});let D=_(S);return D&&!0!==s.strictSlashes&&(D+=`${d}?`),D},parse_1$2=u}function requirePicomatch$1(){if(hasRequiredPicomatch$1)return picomatch_1;hasRequiredPicomatch$1=1;const e=path__default,t=requireScan(),r=requireParse$3(),n=requireUtils$3(),i=requireConstants$7(),s=(e,t,r=!1)=>{if(Array.isArray(e)){const n=e.map(e=>s(e,t,r)),i=e=>{for(const t of n){const r=t(e);if(r)return r}return!1};return i}const i=(o=e)&&"object"==typeof o&&!Array.isArray(o)&&e.tokens&&e.input;var o;if(""===e||"string"!=typeof e&&!i)throw new TypeError("Expected pattern to be a non-empty string")
3399
+ ;const a=t||{},c=n.isWindows(t),u=i?s.compileRe(e,t):s.makeRe(e,t,!1,!0),l=u.state;delete u.state;let d=()=>!1;if(a.ignore){const e={...t,ignore:null,onMatch:null,onResult:null};d=s(a.ignore,e,r)}const p=(r,n=!1)=>{const{isMatch:i,match:o,output:p}=s.test(r,u,t,{glob:e,posix:c}),h={glob:e,state:l,regex:u,posix:c,input:r,output:p,match:o,isMatch:i};return"function"==typeof a.onResult&&a.onResult(h),!1===i?(h.isMatch=!1,!!n&&h):d(r)?("function"==typeof a.onIgnore&&a.onIgnore(h),h.isMatch=!1,!!n&&h):("function"==typeof a.onMatch&&a.onMatch(h),!n||h)};return r&&(p.state=l),p};return s.test=(e,t,r,{glob:i,posix:o}={})=>{if("string"!=typeof e)throw new TypeError("Expected input to be a string");if(""===e)return{isMatch:!1,output:""};const a=r||{},c=a.format||(o?n.toPosixSlashes:null);let u=e===i,l=u&&c?c(e):e;return!1===u&&(l=c?c(e):e,u=l===i),!1!==u&&!0!==a.capture||(u=!0===a.matchBase||!0===a.basename?s.matchBase(e,t,r,o):t.exec(l)),{isMatch:Boolean(u),match:u,output:l}},
3403
3400
  s.matchBase=(t,r,i,o=n.isWindows(i))=>(r instanceof RegExp?r:s.makeRe(r,i)).test(e.basename(t)),s.isMatch=(e,t,r)=>s(t,r)(e),s.parse=(e,t)=>Array.isArray(e)?e.map(e=>s.parse(e,t)):r(e,{...t,fastpaths:!1}),s.scan=(e,r)=>t(e,r),s.compileRe=(e,t,r=!1,n=!1)=>{if(!0===r)return e.output;const i=t||{},o=i.contains?"":"^",a=i.contains?"":"$";let c=`${o}(?:${e.output})${a}`;e&&!0===e.negated&&(c=`^(?!${c}).*$`);const u=s.toRegex(c,t);return!0===n&&(u.state=e),u},s.makeRe=(e,t={},n=!1,i=!1)=>{if(!e||"string"!=typeof e)throw new TypeError("Expected a non-empty string");let o={negated:!1,fastpaths:!0};return!1===t.fastpaths||"."!==e[0]&&"*"!==e[0]||(o.output=r.fastpaths(e,t)),o.output||(o=r(e,t)),s.compileRe(o,t,n,i)},s.toRegex=(e,t)=>{try{const r=t||{};return new RegExp(e,r.flags||(r.nocase?"i":""))}catch(e){if(t&&!0===t.debug)throw e;return/$^/}},s.constants=i,picomatch_1=s}function requirePicomatch(){return hasRequiredPicomatch?picomatch:(hasRequiredPicomatch=1,picomatch=requirePicomatch$1())}
3404
3401
  function requireMicromatch(){if(hasRequiredMicromatch)return micromatch_1;hasRequiredMicromatch=1;const e=require$$1__default,t=requireBraces(),r=requirePicomatch(),n=requireUtils$3(),i=e=>""===e||"./"===e,s=e=>{const t=e.indexOf("{");return t>-1&&e.indexOf("}",t)>-1},o=(e,t,n)=>{t=[].concat(t),e=[].concat(e);let i=new Set,s=new Set,o=new Set,a=0,c=e=>{o.add(e.output),n&&n.onResult&&n.onResult(e)};for(let o=0;o<t.length;o++){let u=r(String(t[o]),{...n,onResult:c},!0),l=u.state.negated||u.state.negatedExtglob;l&&a++;for(let t of e){let e=u(t,!0);(l?!e.isMatch:e.isMatch)&&(l?i.add(e.output):(i.delete(e.output),s.add(e.output)))}}let u=(a===t.length?[...o]:[...s]).filter(e=>!i.has(e));if(n&&0===u.length){if(!0===n.failglob)throw new Error(`No matches found for "${t.join(", ")}"`);if(!0===n.nonull||!0===n.nullglob)return n.unescape?t.map(e=>e.replace(/\\/g,"")):t}return u};return o.match=o,o.matcher=(e,t)=>r(e,t),o.isMatch=(e,t,n)=>r(t,n)(e),o.any=o.isMatch,o.not=(e,t,r={})=>{
3405
3402
  t=[].concat(t).map(String);let n=new Set,i=[],s=new Set(o(e,t,{...r,onResult:e=>{r.onResult&&r.onResult(e),i.push(e.output)}}));for(let e of i)s.has(e)||n.add(e);return[...n]},o.contains=(t,r,n)=>{if("string"!=typeof t)throw new TypeError(`Expected a string: "${e.inspect(t)}"`);if(Array.isArray(r))return r.some(e=>o.contains(t,e,n));if("string"==typeof r){if(i(t)||i(r))return!1;if(t.includes(r)||t.startsWith("./")&&t.slice(2).includes(r))return!0}return o.isMatch(t,r,{...n,contains:!0})},o.matchKeys=(e,t,r)=>{if(!n.isObject(e))throw new TypeError("Expected the first argument to be an object");let i=o(Object.keys(e),t,r),s={};for(let t of i)s[t]=e[t];return s},o.some=(e,t,n)=>{let i=[].concat(e);for(let e of[].concat(t)){let t=r(String(e),n);if(i.some(e=>t(e)))return!0}return!1},o.every=(e,t,n)=>{let i=[].concat(e);for(let e of[].concat(t)){let t=r(String(e),n);if(!i.every(e=>t(e)))return!1}return!0},o.all=(t,n,i)=>{
@@ -3519,17 +3516,17 @@ await this.fsd.exists("poetry.lock")&&(a.lockfilePath="poetry.lock")}}catch(t){e
3519
3516
  cmd:"poetry show --format=json",cwd:this.fsd.root,timeoutSecs:30});if(0===e.code&&e.stdout.trim())try{return JSON.parse(e.stdout).map(e=>({displayName:`${e.name}@${e.version}`,name:e.name,version:e.version,packageType:"pypi"}))}catch(e){return[]}}catch(e){}return this.parsePoetryFile()}async parsePipFiles(){const e=[],t=await this.fsd.readText("requirements.txt");if(t)try{e.push(...this.parseRequirementsTxt(t))}catch(e){}const r=await this.fsd.readText("setup.py");if(r)try{e.push(...this.parseSetupPy(r))}catch(e){}return e}parseRequirementsTxt(e){if(!e.trim()||"invalid-format"===e.trim())return[];const t=e.split("\n").filter(e=>e.trim()&&!e.trim().startsWith("#")),r=[];for(const e of t){const t=e.trim();if("invalid-format"===t||!t.match(/^[a-zA-Z0-9_-]/))continue;const n=t.match(/^([a-zA-Z0-9_-]+)([><=~!]+.*)?$/);if(n){const e=n[1],t=(n[2]||"").match(/[><=~!]*([0-9.]+)/),i=t?t[1]:"unknown";e&&r.push({displayName:`${e}@${i}`,name:e,version:i,packageType:"pypi"})}}return r}
3520
3517
  parseSetupPy(e){if(!e.trim()||e.includes("invalid-format"))return[];const t=e.match(/install_requires\s*=\s*\[(.*?)\]/s);if(!t)return[];const r=t[1].split(",").map(e=>e.trim().replace(/['"]/g,"")).filter(e=>e),n=[];for(const e of r){if("invalid-format"===e||!e.match(/^[a-zA-Z0-9_-]/))continue;const t=e.match(/^([a-zA-Z0-9_-]+)([><=~!]+.*)?$/);if(t){const e=t[1],r=(t[2]||"").match(/[><=~!]*([0-9.]+)/),i=r?r[1]:"unknown";e&&n.push({displayName:`${e}@${i}`,name:e,version:i,packageType:"pypi"})}}return n}async parsePoetryFile(){const e=await this.fsd.readText("pyproject.toml");if(!e)return[];let t;try{t=parse$2(e)}catch(e){return[]}const r=_optionalChain$m([t,"access",e=>e.tool,"optionalAccess",e=>e.poetry,"optionalAccess",e=>e.dependencies]);if(!r||"object"!=typeof r)return[];const n=[];for(const[e,t]of Object.entries(r)){if("python"===e||"invalid-format"===e||!e.match(/^[a-zA-Z0-9_-]/))continue;const r="string"==typeof t?this.extractVersionFromSpec(t):"unknown";n.push({
3521
3518
  displayName:`${e}@${r}`,name:e,version:r,packageType:"pypi"})}return n}extractVersionFromSpec(e){const t=e.match(/[><=~^]*([0-9.]+)/);return t?t[1]:e}}async function _asyncNullishCoalesce$2(e,t){return null!=e?e:await t()}function _optionalChain$l(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}class JavaDetector{constructor(e,t){this.fsd=e,this.logger=t}async detect(){try{_optionalChain$l([this,"access",e=>e.logger,"optionalAccess",e=>e.debug,"call",e=>e({},"Checking for Java package manager files")]);const e=await this.fsd.exists("pom.xml"),t=await this.fsd.exists("build.gradle"),r=await this.fsd.exists("build.gradle.kts");return e||t||r}catch(e){throw new AggregateError([e],"Failed to detect Java package managers")}}async getDependencies(){const e=[],t=[];try{
3522
- if(await this.fsd.exists("pom.xml")){const e=await this.getMavenDependencies();t.push({packageManager:"maven",manifestPath:"pom.xml",detected:!0,dependencies:e})}else t.push({packageManager:"maven",manifestPath:"pom.xml",detected:!1,dependencies:[]})}catch(t){e.push(t)}try{const e=await this.fsd.exists("build.gradle"),r=await this.fsd.exists("build.gradle.kts"),n=e?"build.gradle":r?"build.gradle.kts":"build.gradle";if(e||r){const e=await this.getGradleDependencies();t.push({packageManager:"gradle",manifestPath:n,detected:!0,dependencies:e})}else t.push({packageManager:"gradle",manifestPath:n,detected:!1,dependencies:[]})}catch(t){e.push(t)}if(e.length>0)throw new AggregateError(e,"Failed to extract Java dependencies");return t}async getMavenDependencies(){try{const{stdout:e,error:t,code:r}=await exec({cmd:"mvn dependency:list -DoutputType=json",cwd:this.fsd.root,timeoutSecs:30});if(t||0!==r)throw t||new Error(`mvn exited with code ${r}`);return this.parseMavenCommandOutput(e)}catch(e){
3523
- return this.parsePomXml()}}async getGradleDependencies(){try{const{stdout:e,error:t,code:r}=await exec({cmd:"gradle dependencies --configuration=runtimeClasspath --quiet",cwd:this.fsd.root,timeoutSecs:30});if(t||0!==r)throw t||new Error(`gradle exited with code ${r}`);return this.parseGradleCommandOutput(e)}catch(e){return this.parseGradleFiles()}}parseMavenCommandOutput(e){try{const t=JSON.parse(e),r=[];if(Array.isArray(t.dependencies))for(const e of t.dependencies)r.push({displayName:`${e.groupId}:${e.artifactId}@${e.version}`,namespace:e.groupId,name:e.artifactId,version:e.version,packageType:"maven"});return r}catch(e){return[]}}parseGradleCommandOutput(e){const t=[];for(const r of e.split("\n")){const e=r.match(/^\+---\s+([^:]+):([^:]+):([^\s]+)/);e&&t.push({displayName:`${e[1]}:${e[2]}@${e[3]}`,namespace:e[1],name:e[2],version:e[3],packageType:"maven"})}return t}async parsePomXml(){try{const e=await this.fsd.readText("pom.xml");if(!e)return[]
3524
- ;const t=(new fxpExports.XMLParser).parse(e),r=[],n=_optionalChain$l([t,"access",e=>e.project,"optionalAccess",e=>e.dependencies,"optionalAccess",e=>e.dependency]);if(n){const e=Array.isArray(n)?n:[n];for(const t of e)t.groupId&&t.artifactId&&t.version&&r.push({displayName:`${t.groupId}:${t.artifactId}@${t.version}`,namespace:t.groupId,name:t.artifactId,version:t.version,packageType:"maven"})}return r}catch(e){return[]}}async parseGradleFiles(){try{let e=await _asyncNullishCoalesce$2(await this.fsd.readText("build.gradle"),async()=>await this.fsd.readText("build.gradle.kts"));if(!e)return[];const t=[],r=/(?:implementation|compile|api|runtimeOnly)\s+['"]([^:]+):([^:]+):([^'"]+)['"]/g;let n;for(;n=r.exec(e);)t.push({displayName:`${n[1]}:${n[2]}@${n[3]}`,namespace:n[1],name:n[2],version:n[3],packageType:"maven"});return t}catch(e){return[]}}}class DepList{constructor(e,t){this.detectors=[new NpmDetector(e,t),new PythonDetector(e,t),new JavaDetector(e,t)]}async scan(){const e=[],t=[]
3525
- ;for(const r of this.detectors)try{const t=await r.getDependencies();e.push(...t)}catch(e){t.push(e instanceof Error?e:new Error(String(e)))}if(t.length>0)throw new AggregateError(t,"Failed to scan for dependencies");return{results:e}}getSupportedPackageManagers(){return["npm","yarn","pnpm","pip","poetry","maven","gradle"]}}const cyan=e=>styleText("cyan",e.toString()),syncCommand=new Command$1({name:"registry-sync",summary:"Check for newer versions of tiles and install them into your project",allowArbitraryFlags:!1,requiresLogin:!1,requiresConfig:!1,flags:{yes:{type:Boolean,description:"Automatically accept all installations and updates",short:"y"}},handler:async({monitoring:e,projectDir:t,isInteractive:r,tesslClient:n,isAuthenticated:i,args:s})=>{if(!r)throw new ExpectedError('"sync" does not support non-interactive mode');const{logger:o,analytics:a}=e,c={scanned:[],dependenciesWithoutTiles:[],tilesInstalled:[]
3526
- },u=createSpinner("Scanning project dependencies..."),l=openFsd(t),d=await gatherDependencies({fsd:l,logger:o,analytics:a,trackingData:c});if(0===d.results.flatMap(e=>e.dependencies).length)return u.succeed('No dependencies found. Use "tessl registry search" to find and install usage specs.'),a.registrySync(c),SUCCESS;u.start("Finding candidates...");const p=await findCandidates({scanResult:d,tesslClient:n});u.stop();const h=p.some(e=>e.dependenciesWithCandidates.some(e=>null!==e.candidate));if(!h)return u.succeed("No suitable tiles found"),c.dependenciesWithoutTiles=d.results.flatMap(e=>e.dependencies.map(e=>({displayName:e.displayName,packageType:e.packageType}))),a.registrySync(c),SUCCESS;const{isInitialized:A}=await ensureInit({targetDir:t,isAuthenticated:i,isInteractive:r,monitoring:e,args:{"no-mcp":!0}},"Tiles require Tessl to be initialized. Would you like to initialize Tessl now?");if(!A)return c.refusedInit=!0,a.registrySync(c),SUCCESS;const f=await loadTesslManifest(l)
3527
- ;for(const e of p){const t=analyzeDependencyGroup(e,f.dependencies||{});if(c.dependenciesWithoutTiles.push(...t.dependenciesWithoutTiles.map(e=>({displayName:e.displayName,packageType:e.packageType}))),0===t.tilesToInstall.length&&0===t.tilesToUpdate.length){u.succeed(`All tiles are up to date for ${cyan(t.packageManager)} manifest ${cyan(t.manifestPath)}`);continue}const r=await selectTiles({analysis:t,args:s,spinner:u,logger:o});if("cancelled"in r)return c.cancelled=!0,a.registrySync(c),SUCCESS;if(!(await installTiles({chosen:r.chosen,analysis:t,fsd:l,tesslClient:n,spinner:u,analytics:a,logger:o})).success)return a.registrySync(c),FAILURE;c.tilesInstalled.push(...r.chosen)}return a.registrySync(c),SUCCESS}});async function gatherDependencies({fsd:e,logger:t,analytics:r,trackingData:n}){try{const r=new DepList(e,t),i=await r.scan();return n.scanned=i.results.map(({packageManager:e,manifestPath:t,lockfilePath:r,detected:n})=>({packageManager:e,manifestPath:t,lockfilePath:r,detected:n
3528
- })),i}catch(e){return t.error({err:e},"Failed to gather dependencies"),r.cliError({command:"registry-sync",message:getMessageFromMaybeError(e),stack:getStackFromMaybeError(e)||"Unknown stack",expected:!1}),{results:[]}}}async function loadTesslManifest(e){const t=await readTesslJson(e);if(!t.success)throw new ExpectedError(`Failed to read tessl.json: ${t.error}`);return t.data}async function findCandidates({scanResult:e,tesslClient:t}){const r=[];for(const{packageManager:n,manifestPath:i,dependencies:s,detected:o}of e.results){if(!o)continue;const e=await cMap(s,async e=>({dependency:e,candidate:await findBestTile(t,e)}));r.push({packageManager:n,manifestPath:i,dependenciesWithCandidates:e})}return r}async function findBestTile(e,t){const r=new packageurlJsExports.PackageURL(t.packageType,t.namespace,t.name).toString(),n=await e.GET("/v1/tiles",{params:{query:{"filter[describes]":r,"page[size]":1}}});if(n.error)return null;const i=n.data.data;if(0===i.length)return null
3529
- ;const s=i[0],[o,a]=s.attributes.fullName.split("/"),c=r+`@${t.version.split(".")[0]}`,u=await e.GET("/v1/tiles/{workspaceName}/{tileName}/versions",{params:{path:{workspaceName:o,tileName:a},query:{"filter[describes][like]":c,"page[size]":1}}});if(u.error)return null;const l=u.data.data[0];return l?{workspaceName:o,tileName:a,version:l.attributes.version}:null}function analyzeDependencyGroup(e,t){const r=[],n=[],i=[];for(const{candidate:s,dependency:o}of e.dependenciesWithCandidates){if(!s){i.push(o);continue}const e=t[`${s.workspaceName}/${s.tileName}`];e?semverExports.gt(s.version,e.version)&&n.push({candidate:s,dependency:o,currentVersion:e.version}):r.push({candidate:s,dependency:o})}return{packageManager:e.packageManager,manifestPath:e.manifestPath,tilesToInstall:r,tilesToUpdate:n,dependenciesWithoutTiles:i}}function calculateDisplayPadding(e){const t={name:0,currentVersion:0,candidateVersion:0};for(const{candidate:r}of[...e.tilesToInstall,...e.tilesToUpdate]){
3530
- const e=`${r.workspaceName}/${r.tileName}`;t.name=Math.max(t.name,e.length),t.candidateVersion=Math.max(t.candidateVersion,r.version.length)}for(const{currentVersion:r}of e.tilesToUpdate)t.currentVersion=Math.max(t.currentVersion,r.length);return t}function buildTileChoices(e,t){const r=[];return e.tilesToUpdate.length>0&&(r.push(new Separator("-- Select tiles to update --")),r.push(...e.tilesToUpdate.map(({candidate:e,dependency:r,currentVersion:n})=>({name:`${`${e.workspaceName}/${e.tileName}`.padEnd(t.name)} ${n.padEnd(t.currentVersion)} -> ${e.version.padEnd(t.candidateVersion)} (${r.displayName})`,value:{...e,isUpdate:!0}})))),e.tilesToInstall.length>0&&(r.push(new Separator("-- Select new tiles to install --")),r.push(...e.tilesToInstall.map(({candidate:e,dependency:r})=>({name:`${`${e.workspaceName}/${e.tileName}`.padEnd(t.name)} ${e.version.padEnd(t.candidateVersion)} (${r.displayName})`,value:{...e,isUpdate:!1}})))),r}
3531
- async function selectTiles({analysis:e,args:t,spinner:r,logger:n}){const{packageManager:i,manifestPath:s,tilesToInstall:o,tilesToUpdate:a}=e;r.info(`Found ${cyan(o.length)} tiles to install and ${cyan(a.length)} to update for ${cyan(i)} manifest ${cyan(s)}`);const c=buildTileChoices(e,calculateDisplayPadding(e));let u;if(t.yes)u=c.filter(e=>"value"in e).map(e=>e.value);else try{u=await checkbox({message:"Select tiles to install",choices:c,pageSize:12,loop:!1,theme:{style:{renderSelectedChoices:()=>""}}})}catch(e){if(e instanceof ExitPromptError)return{cancelled:!0};throw n.error({choices:c},"Error while selecting tiles to install"),e}return 0===u.length&&r.info(`0 tiles selected for ${cyan(i)} manifest ${cyan(s)}`),{chosen:u}}async function installTiles({fsd:e,chosen:t,analysis:r,tesslClient:n,spinner:i,analytics:s,logger:o}){const{packageManager:a,manifestPath:c}=r;if(0===t.length)return{success:!0};i.start(`Installing tiles for ${cyan(a)} manifest ${cyan(c)}...`)
3532
- ;const u=await updateTesslJsonDependencies(e,{add:t.map(({workspaceName:e,tileName:t,version:r})=>({workspaceName:e,tileName:t,newVersion:r}))});if(!u.success)return o.error({err:u.error},"Failed to update Tessl JSON dependencies"),i.fail(u.error),{success:!1,error:u.error};const l=await syncUsageSpecs(e.root,e,n);if(!l.success)return o.error({err:l.error},"Failed to sync usage specs"),i.fail(stripIndents`${l.error}
3519
+ if(await this.fsd.exists("pom.xml")){const e=await this.getMavenDependencies();t.push({packageManager:"maven",manifestPath:"pom.xml",detected:!0,dependencies:e})}else t.push({packageManager:"maven",manifestPath:"pom.xml",detected:!1,dependencies:[]})}catch(t){e.push(t)}try{const e=await this.fsd.exists("build.gradle"),r=await this.fsd.exists("build.gradle.kts"),n=e?"build.gradle":r?"build.gradle.kts":"build.gradle";if(e||r){const e=await this.getGradleDependencies();t.push({packageManager:"gradle",manifestPath:n,detected:!0,dependencies:e})}else t.push({packageManager:"gradle",manifestPath:n,detected:!1,dependencies:[]})}catch(t){e.push(t)}if(e.length>0)throw new AggregateError(e,"Failed to extract Java dependencies");return t}async getMavenDependencies(){try{const e=await this.fsd.exists("./mvnw")?"./mvnw":"mvn",{stdout:t,error:r,code:n}=await exec({cmd:`${e} dependency:list -DexcludeTransitive=true`,cwd:this.fsd.root,timeoutSecs:30})
3520
+ ;if(r||0!==n)throw r||new Error(`mvn exited with code ${n}`);return this.parseMavenCommandOutput(t)}catch(e){return this.parsePomXml()}}async getGradleDependencies(){try{const{stdout:e,error:t,code:r}=await exec({cmd:"gradle dependencies --configuration=runtimeClasspath --quiet",cwd:this.fsd.root,timeoutSecs:30});if(t||0!==r)throw t||new Error(`gradle exited with code ${r}`);return this.parseGradleCommandOutput(e)}catch(e){return this.parseGradleFiles()}}parseMavenCommandOutput(e){const t=/^\[INFO\]\s+(?<namespace>[^:\s]+):(?<name>[^:\s]+):(?<type>[^:\s]+):(?:(?<classifier>[^:\s]+):)?(?<version>[^:\s]+):/,r=[],n=new Set;for(const i of e.split(/\r?\n/)){const e=t.exec(i);if(!e||!e.groups)continue;const{namespace:s,name:o,version:a}=e.groups,c=`${s}:${o}:${a}`;n.has(c)||(n.add(c),r.push({displayName:`${s}:${o}@${a}`,namespace:s,name:o,version:a,packageType:"maven"}))}return r}parseGradleCommandOutput(e){const t=[];for(const r of e.split("\n")){
3521
+ const e=r.match(/^\+---\s+([^:]+):([^:]+):([^\s]+)/);e&&t.push({displayName:`${e[1]}:${e[2]}@${e[3]}`,namespace:e[1],name:e[2],version:e[3],packageType:"maven"})}return t}async parsePomXml(){try{const e=await this.fsd.readText("pom.xml");if(!e)return[];const t=(new XMLParser).parse(e),r=[],n=_optionalChain$l([t,"access",e=>e.project,"optionalAccess",e=>e.dependencies,"optionalAccess",e=>e.dependency]);if(n){const e=Array.isArray(n)?n:[n];for(const t of e)t.groupId&&t.artifactId&&t.version&&r.push({displayName:`${t.groupId}:${t.artifactId}@${t.version}`,namespace:t.groupId,name:t.artifactId,version:t.version,packageType:"maven"})}return r}catch(e){return[]}}async parseGradleFiles(){try{let e=await _asyncNullishCoalesce$2(await this.fsd.readText("build.gradle"),async()=>await this.fsd.readText("build.gradle.kts"));if(!e)return[];const t=[],r=/(?:implementation|compile|api|runtimeOnly)\s+['"]([^:]+):([^:]+):([^'"]+)['"]/g;let n;for(;n=r.exec(e);)t.push({
3522
+ displayName:`${n[1]}:${n[2]}@${n[3]}`,namespace:n[1],name:n[2],version:n[3],packageType:"maven"});return t}catch(e){return[]}}}class DepList{constructor(e,t){this.detectors=[new NpmDetector(e,t),new PythonDetector(e,t),new JavaDetector(e,t)]}async scan(){const e=[],t=[];for(const r of this.detectors)try{const t=await r.getDependencies();e.push(...t)}catch(e){t.push(e instanceof Error?e:new Error(String(e)))}if(t.length>0)throw new AggregateError(t,"Failed to scan for dependencies");return{results:e}}getSupportedPackageManagers(){return["npm","yarn","pnpm","pip","poetry","maven","gradle"]}}const cyan=e=>styleText("cyan",e.toString()),syncCommand=new Command$1({name:"registry-sync",summary:"Check for newer versions of tiles and install them into your project",allowArbitraryFlags:!1,requiresLogin:!1,requiresConfig:!1,flags:{yes:{type:Boolean,description:"Automatically accept all installations and updates",short:"y"}},
3523
+ handler:async({monitoring:e,projectDir:t,isInteractive:r,tesslClient:n,isAuthenticated:i,args:s})=>{if(!r)throw new ExpectedError('"sync" does not support non-interactive mode');const{logger:o,analytics:a}=e,c={scanned:[],dependenciesWithoutTiles:[],tilesInstalled:[]},u=createSpinner("Scanning project dependencies..."),l=openFsd(t),d=await gatherDependencies({fsd:l,logger:o,analytics:a,trackingData:c});if(0===d.results.flatMap(e=>e.dependencies).length)return u.succeed('No dependencies found. Use "tessl registry search" to find and install usage specs.'),a.registrySync(c),SUCCESS;u.start("Finding candidates...");const p=await findCandidates({scanResult:d,tesslClient:n});u.stop();const h=p.some(e=>e.dependenciesWithCandidates.some(e=>null!==e.candidate));if(!h)return u.succeed("No suitable tiles found"),c.dependenciesWithoutTiles=d.results.flatMap(e=>e.dependencies.map(e=>({displayName:e.displayName,packageType:e.packageType}))),a.registrySync(c),SUCCESS
3524
+ ;const{isInitialized:A}=await ensureInit({targetDir:t,isAuthenticated:i,isInteractive:r,monitoring:e,args:{"no-mcp":!0}},"Tiles require Tessl to be initialized. Would you like to initialize Tessl now?");if(!A)return c.refusedInit=!0,a.registrySync(c),SUCCESS;const f=await loadTesslManifest(l);for(const e of p){const t=analyzeDependencyGroup(e,f.dependencies||{});if(c.dependenciesWithoutTiles.push(...t.dependenciesWithoutTiles.map(e=>({displayName:e.displayName,packageType:e.packageType}))),0===t.tilesToInstall.length&&0===t.tilesToUpdate.length){u.succeed(`All tiles are up to date for ${cyan(t.packageManager)} manifest ${cyan(t.manifestPath)}`);continue}const r=await selectTiles({analysis:t,args:s,spinner:u,logger:o});if("cancelled"in r)return c.cancelled=!0,a.registrySync(c),SUCCESS;if(!(await installTiles({chosen:r.chosen,analysis:t,fsd:l,tesslClient:n,spinner:u,analytics:a,logger:o})).success)return a.registrySync(c),FAILURE;c.tilesInstalled.push(...r.chosen)}
3525
+ return a.registrySync(c),SUCCESS}});async function gatherDependencies({fsd:e,logger:t,analytics:r,trackingData:n}){try{const r=new DepList(e,t),i=await r.scan();return n.scanned=i.results.map(({packageManager:e,manifestPath:t,lockfilePath:r,detected:n})=>({packageManager:e,manifestPath:t,lockfilePath:r,detected:n})),i}catch(e){return t.error({err:e},"Failed to gather dependencies"),r.cliError({command:"registry-sync",message:getMessageFromMaybeError(e),stack:getStackFromMaybeError(e)||"Unknown stack",expected:!1}),{results:[]}}}async function loadTesslManifest(e){const t=await readTesslJson(e);if(!t.success)throw new ExpectedError(`Failed to read tessl.json: ${t.error}`);return t.data}async function findCandidates({scanResult:e,tesslClient:t}){const r=[];for(const{packageManager:n,manifestPath:i,dependencies:s,detected:o}of e.results){if(!o)continue;const e=await cMap(s,async e=>({dependency:e,candidate:await findBestTile(t,e)}));r.push({packageManager:n,manifestPath:i,
3526
+ dependenciesWithCandidates:e})}return r}async function findBestTile(e,t){const r=new packageurlJsExports.PackageURL(t.packageType,t.namespace,t.name).toString(),n=await e.GET("/v1/tiles",{params:{query:{"filter[describes]":r,"page[size]":1}}});if(n.error)return null;const i=n.data.data;if(0===i.length)return null;const s=i[0],[o,a]=s.attributes.fullName.split("/"),c=r+`@${t.version.split(".")[0]}`,u=await e.GET("/v1/tiles/{workspaceName}/{tileName}/versions",{params:{path:{workspaceName:o,tileName:a},query:{"filter[describes][like]":c,"page[size]":1}}});if(u.error)return null;const l=u.data.data[0];return l?{workspaceName:o,tileName:a,version:l.attributes.version}:null}function analyzeDependencyGroup(e,t){const r=[],n=[],i=[];for(const{candidate:s,dependency:o}of e.dependenciesWithCandidates){if(!s){i.push(o);continue}const e=t[`${s.workspaceName}/${s.tileName}`];e?semverExports.gt(s.version,e.version)&&n.push({candidate:s,dependency:o,currentVersion:e.version}):r.push({candidate:s,
3527
+ dependency:o})}return{packageManager:e.packageManager,manifestPath:e.manifestPath,tilesToInstall:r,tilesToUpdate:n,dependenciesWithoutTiles:i}}function calculateDisplayPadding(e){const t={name:0,currentVersion:0,candidateVersion:0};for(const{candidate:r}of[...e.tilesToInstall,...e.tilesToUpdate]){const e=`${r.workspaceName}/${r.tileName}`;t.name=Math.max(t.name,e.length),t.candidateVersion=Math.max(t.candidateVersion,r.version.length)}for(const{currentVersion:r}of e.tilesToUpdate)t.currentVersion=Math.max(t.currentVersion,r.length);return t}function buildTileChoices(e,t){const r=[];return e.tilesToUpdate.length>0&&(r.push(new Separator("-- Select tiles to update --")),r.push(...e.tilesToUpdate.map(({candidate:e,dependency:r,currentVersion:n})=>({name:`${`${e.workspaceName}/${e.tileName}`.padEnd(t.name)} ${n.padEnd(t.currentVersion)} -> ${e.version.padEnd(t.candidateVersion)} (${r.displayName})`,value:{...e,isUpdate:!0},checked:!0})))),
3528
+ e.tilesToInstall.length>0&&(r.push(new Separator("-- Select new tiles to install --")),r.push(...e.tilesToInstall.map(({candidate:e,dependency:r})=>({name:`${`${e.workspaceName}/${e.tileName}`.padEnd(t.name)} ${e.version.padEnd(t.candidateVersion)} (${r.displayName})`,value:{...e,isUpdate:!1},checked:!0})))),r}async function selectTiles({analysis:e,args:t,spinner:r,logger:n}){const{packageManager:i,manifestPath:s,tilesToInstall:o,tilesToUpdate:a}=e;r.info(`Found ${cyan(o.length)} tiles to install and ${cyan(a.length)} to update for ${cyan(i)} manifest ${cyan(s)}`);const c=buildTileChoices(e,calculateDisplayPadding(e));let u;if(t.yes)u=c.filter(e=>"value"in e).map(e=>e.value);else try{u=await checkbox({message:"Select tiles to install",choices:c,pageSize:12,loop:!1,theme:{style:{renderSelectedChoices:()=>""},helpMode:"always"}})}catch(e){if(e instanceof ExitPromptError)return{cancelled:!0};throw n.error({choices:c},"Error while selecting tiles to install"),e}
3529
+ return 0===u.length&&r.info(`0 tiles selected for ${cyan(i)} manifest ${cyan(s)}`),{chosen:u}}async function installTiles({fsd:e,chosen:t,analysis:r,tesslClient:n,spinner:i,analytics:s,logger:o}){const{packageManager:a,manifestPath:c}=r;if(0===t.length)return{success:!0};i.start(`Installing tiles for ${cyan(a)} manifest ${cyan(c)}...`);const u=await updateTesslJsonDependencies(e,{add:t.map(({workspaceName:e,tileName:t,version:r})=>({workspaceName:e,tileName:t,newVersion:r}))});if(!u.success)return o.error({err:u.error},"Failed to update Tessl JSON dependencies"),i.fail(u.error),{success:!1,error:u.error};const l=await syncUsageSpecs(e.root,e,n);if(!l.success)return o.error({err:l.error},"Failed to sync usage specs"),i.fail(stripIndents`${l.error}
3533
3530
 
3534
3531
  Tiles added to tessl.json, but dependency sync failed.
3535
3532
  Your agent won't have access to the newly installed usage specs until this is fixed.
@@ -3691,8 +3688,8 @@ children:[jsxRuntimeExports.jsxs(Text,{children:["First, run ",jsxRuntimeExports
3691
3688
  children:"tessl create"})]}),jsxRuntimeExports.jsxs(Text,{children:["2. Generate code from your spec with"," ",jsxRuntimeExports.jsx(CommandText,{children:"tessl build"})]}),jsxRuntimeExports.jsxs(Text,{children:["3. Iterate on your spec with ",jsxRuntimeExports.jsx(CommandText,{children:"tessl edit"}),", and rebuild your code with"," ",jsxRuntimeExports.jsx(CommandText,{children:"tessl build"})]})]}),jsxRuntimeExports.jsxs(Text,{children:["Check out the commands below for more details and inspiration, along with documentation at"," ",jsxRuntimeExports.jsx(Text,{bold:!0,underline:!0,children:"https://docs.tessl.io/"})]})]})}):jsxRuntimeExports.jsx(Section$1,{title:"Quickstart guide",children:jsxRuntimeExports.jsxs(Box,{flexDirection:"column",gap:1,children:[jsxRuntimeExports.jsxs(Text,{children:[jsxRuntimeExports.jsx(Text,{bold:!0,children:"Usage specs"
3692
3689
  })," are downloadable files that provide coding agents with documentation for open-source libraries; see"," ",jsxRuntimeExports.jsx(Text,{bold:!0,underline:!0,children:"https://tessl.io/registry"})," ","to learn more."]}),jsxRuntimeExports.jsxs(Text,{children:["To download usage specs for your project, first run"," ",jsxRuntimeExports.jsx(CommandText,{children:"tessl init"}),", which installs instructions into your project's agent configuration files (i.e. AGENTS.md), and optionally configures your preferred coding agent to use Tessl's MCP server."]}),jsxRuntimeExports.jsxs(Text,{children:["Then, you or your agent can use"," ",jsxRuntimeExports.jsx(CommandText,{children:"tessl registry search"}),","," ",jsxRuntimeExports.jsx(CommandText,{children:"tessl registry install"})," and"," ",jsxRuntimeExports.jsx(CommandText,{children:"tessl registry sync"})," to find, install and upgrade usage specs in your project."]}),jsxRuntimeExports.jsxs(Text,{
3693
3690
  children:["See below for more information on these and other commands, and visit"," ",jsxRuntimeExports.jsx(Text,{bold:!0,underline:!0,children:"https://docs.tessl.io/"})," ","for full documentation."]})]})})}const helpCommand=new Command$1({name:"help",summary:"Print information on how to use this CLI",requiresConfig:!1,handler:async({isAuthenticated:e,projectDir:t})=>{const r=getExistingFrameworkType(t);return render(jsxRuntimeExports.jsx(GlobalHelp,{isLoggedIn:e,frameworkType:r})),Promise.resolve(SUCCESS)}});function _nullishCoalesce$f(e,t){return null!=e?e:t()}const listCommand=new Command$1({name:"list",summary:"List details of the files associated with specs, whether code implementations or tests",positionals:[{name:"spec",description:"The path of the spec we want to list files for. If not provided, lists files for all specs in the project"}],flags:{tests:{type:[String],
3694
- description:'Select which kind of test links to list: "none" shows no test files, "draft" shows only draft test files, "locked" shows only locked test files, "impl" shows only implementation test files, and "all" shows all kinds of test files',hidden:!1,defaultValue:["all"],availableValues:["none","draft","locked","impl","all"]},code:{type:String,description:'Select which kind code link to show: "none" shows no code links, "generate" shows only `@generate` links, "describe" shows only `@describe` links, and "all" shows both kinds of links',hidden:!1,defaultValue:"all",availableValues:["none","generate","describe","all"]},"include-specs":{type:Boolean,description:"Select whether to include spec files themselves. By default, shows spec files only when a specific spec file is not provided",hidden:!1},"include-missing":{type:Boolean,description:"Include files which have not been generated yet",hidden:!1}},allowArbitraryFlags:!0,requiresLogin:!0,
3695
- handler:async({positionals:{spec:e},projectDir:t,args:{tests:r,code:n,"include-specs":i,"include-missing":s},flagConfig:o})=>{const a=await findFiles({projectDir:t,spec:e,tests:_nullishCoalesce$f(r,()=>o.tests.defaultValue),code:_nullishCoalesce$f(n,()=>o.code.defaultValue),includeMissing:s}),c=!!i||!i&&!e;return Object.entries(a).forEach(([e,{tests:t,code:r}])=>{c&&console.log(e),t.forEach(e=>console.log(e)),r.forEach(e=>console.log(e))}),SUCCESS}});function createTestsFilter(e){if(e.includes("none")&&e.length>1)throw new Error('Cannot specify "none" with other test types');if(e.includes("all")&&e.length>1)throw new Error('Cannot specify "all" with other test types');if(0===e.length)throw new Error("At least one test type must be specified");return t=>{if("all"===e[0])return!0;if("none"===e[0])return!1;switch(t.kind){case"draft":return e.includes("draft");case"locked":return e.includes("locked");case"impl":return e.includes("impl");default:return assertUnreachable(t.kind)}}}
3691
+ description:'Select which kind of test links to list: "none" (default) shows no test files, "draft" shows only draft test files, "locked" shows only locked test files, and "all" shows all kinds of test files',hidden:!1,defaultValue:["all"],availableValues:["none","draft","locked","all"]},code:{type:String,description:'Select which kind code link to show: "none" shows no code links, "generate" shows only `@generate` links, "describe" shows only `@describe` links, and "all" shows both kinds of links',hidden:!1,defaultValue:"all",availableValues:["none","generate","describe","all"]},"include-specs":{type:Boolean,description:"Select whether to include spec files themselves. By default, shows spec files only when a specific spec file is not provided",hidden:!1},"include-missing":{type:Boolean,description:"Include files which have not been generated yet",hidden:!1}},allowArbitraryFlags:!0,requiresLogin:!0,
3692
+ handler:async({positionals:{spec:e},projectDir:t,args:{tests:r,code:n,"include-specs":i,"include-missing":s},flagConfig:o})=>{const a=await findFiles({projectDir:t,spec:e,tests:_nullishCoalesce$f(r,()=>o.tests.defaultValue),code:_nullishCoalesce$f(n,()=>o.code.defaultValue),includeMissing:s}),c=!!i||!i&&!e;return Object.entries(a).forEach(([e,{tests:t,code:r}])=>{c&&console.log(e),t.forEach(e=>console.log(e)),r.forEach(e=>console.log(e))}),SUCCESS}});function createTestsFilter(e){if(e.includes("none")&&e.length>1)throw new Error('Cannot specify "none" with other test types');if(e.includes("all")&&e.length>1)throw new Error('Cannot specify "all" with other test types');if(0===e.length)throw new Error("At least one test type must be specified");return t=>{if("all"===e[0])return!0;if("none"===e[0])return!1;switch(t.kind){case"draft":return e.includes("draft");case"locked":return e.includes("locked");default:return assertUnreachable(t.kind)}}}
3696
3693
  const findFiles=async({projectDir:e,spec:t,tests:r,code:n,includeMissing:i})=>{const s=openFsd(e),o=t?[t]:await listSpecs(s),a={},c=createTestsFilter(r),u=i?e=>!0:t=>existsSync$1(join$1(e,t)),l=codeExtractor(n);for(const t of o)a[t]={tests:[],code:[]},a[t].tests=(await specLinkedPaths(s,t,[findTests],e)).filter(c).map(e=>e.path).filter(u),a[t].code=(await specLinkedPaths(s,t,l,e)).filter(u);return a};function codeExtractor(e){switch(e){case"all":return[findGeneratePaths,findDescribePaths];case"generate":return[findGeneratePaths];case"describe":return[findDescribePaths];case"none":return[];default:assertUnreachable(e)}}const LATEST_PROTOCOL_VERSION$1="2025-06-18",SUPPORTED_PROTOCOL_VERSIONS$1=[LATEST_PROTOCOL_VERSION$1,"2025-03-26","2024-11-05","2024-10-07"],JSONRPC_VERSION$1="2.0",ProgressTokenSchema$1=unionType$1([stringType$1(),numberType$1().int()]),CursorSchema$1=stringType$1(),RequestMetaSchema$1=objectType$1({progressToken:optionalType$1(ProgressTokenSchema$1)
3697
3694
  }).passthrough(),BaseRequestParamsSchema$1=objectType$1({_meta:optionalType$1(RequestMetaSchema$1)}).passthrough(),RequestSchema$1=objectType$1({method:stringType$1(),params:optionalType$1(BaseRequestParamsSchema$1)}),BaseNotificationParamsSchema$1=objectType$1({_meta:optionalType$1(objectType$1({}).passthrough())}).passthrough(),NotificationSchema$1=objectType$1({method:stringType$1(),params:optionalType$1(BaseNotificationParamsSchema$1)}),ResultSchema$1=objectType$1({_meta:optionalType$1(objectType$1({}).passthrough())}).passthrough(),RequestIdSchema$1=unionType$1([stringType$1(),numberType$1().int()]),JSONRPCRequestSchema$1=objectType$1({jsonrpc:literalType$1(JSONRPC_VERSION$1),id:RequestIdSchema$1}).merge(RequestSchema$1).strict(),isJSONRPCRequest$1=e=>JSONRPCRequestSchema$1.safeParse(e).success,JSONRPCNotificationSchema$1=objectType$1({jsonrpc:literalType$1(JSONRPC_VERSION$1)
3698
3695
  }).merge(NotificationSchema$1).strict(),isJSONRPCNotification=e=>JSONRPCNotificationSchema$1.safeParse(e).success,JSONRPCResponseSchema$1=objectType$1({jsonrpc:literalType$1(JSONRPC_VERSION$1),id:RequestIdSchema$1,result:ResultSchema$1}).strict(),isJSONRPCResponse$1=e=>JSONRPCResponseSchema$1.safeParse(e).success;var ErrorCode$1;!function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError"}(ErrorCode$1||(ErrorCode$1={}));const JSONRPCErrorSchema$1=objectType$1({jsonrpc:literalType$1(JSONRPC_VERSION$1),id:RequestIdSchema$1,error:objectType$1({code:numberType$1().int(),message:stringType$1(),data:optionalType$1(unknownType$1())})
@@ -4591,7 +4588,7 @@ mimeType:t.mimeType,uri:e};return"text"in s&&(o.text=s.text),"blob"in s&&(o.blob
4591
4588
  this.emit("connect",{session:e})},onUnhandledRequest:async(t,r)=>{await this.#Cs(t,r,!1,e.host)},port:e.port,streamEndpoint:e.endpoint}),this.#ns.info(`[FastMCP info] server is running on HTTP Stream at http://${e.host}:${e.port}${e.endpoint}`),this.#ns.info("[FastMCP info] Transport type: httpStream (Streamable HTTP, not SSE)"))}}}async stop(){this.#fs&&await this.#fs.close()}#bs(e){const t=e?this.#ms.filter(t=>!t.canAccess||t.canAccess(e)):this.#ms;return new FastMCPSession({auth:e,instructions:this.#c.instructions,logger:this.#ns,name:this.#c.name,ping:this.#c.ping,prompts:this.#as,resources:this.#cs,resourcesTemplates:this.#gs,roots:this.#c.roots,tools:t,transportType:"httpStream",utils:this.#c.utils,version:this.#c.version})}#Cs=async(e,t,r=!1,n)=>{const i=this.#c.health??{};if(void 0===i.enabled||i.enabled){const s=i.path??"/health",o=new URL(e.url||"",`http://${n}`);try{if("GET"===e.method&&o.pathname===s)return void t.writeHead(i.status??200,{"Content-Type":"text/plain"
4592
4589
  }).end(i.message??"✓ Ok");if("GET"===e.method&&"/ready"===o.pathname){if(r){const e={mode:"stateless",ready:1,status:"ready",total:1};t.writeHead(200,{"Content-Type":"application/json"}).end(JSON.stringify(e))}else{const e=this.#As.filter(e=>e.isReady).length,r=this.#As.length,n=e===r&&r>0,i={ready:e,status:n?"ready":0===r?"no_sessions":"initializing",total:r};t.writeHead(n?200:503,{"Content-Type":"application/json"}).end(JSON.stringify(i))}return}}catch(e){this.#ns.error("[FastMCP error] health endpoint error",e)}}const s=this.#c.oauth;if(s?.enabled&&"GET"===e.method){const r=new URL(e.url||"",`http://${n}`);if("/.well-known/oauth-authorization-server"===r.pathname&&s.authorizationServer){const e=convertObjectToSnakeCase(s.authorizationServer);return void t.writeHead(200,{"Content-Type":"application/json"}).end(JSON.stringify(e))}if("/.well-known/oauth-protected-resource"===r.pathname&&s.protectedResource){const e=convertObjectToSnakeCase(s.protectedResource)
4593
4590
  ;return void t.writeHead(200,{"Content-Type":"application/json"}).end(JSON.stringify(e))}}t.writeHead(404).end()};#ys(e){const t=process.argv.slice(2),r=e=>{const r=t.findIndex(t=>t===`--${e}`);return-1!==r&&r+1<t.length?t[r+1]:void 0},n=r("transport"),i=r("port"),s=r("endpoint"),o=r("stateless"),a=r("host"),c=process.env.FASTMCP_TRANSPORT,u=process.env.FASTMCP_PORT,l=process.env.FASTMCP_ENDPOINT,d=process.env.FASTMCP_STATELESS,p=process.env.FASTMCP_HOST;if("httpStream"===(e?.transportType||("http-stream"===n?"httpStream":n)||c||"stdio")){const t=parseInt(e?.httpStream?.port?.toString()||i||u||"8080"),r=e?.httpStream?.host||a||p||"localhost",n=e?.httpStream?.endpoint||s||l||"/mcp";return{httpStream:{enableJsonResponse:e?.httpStream?.enableJsonResponse||!1,endpoint:n,host:r,port:t,stateless:e?.httpStream?.stateless||"true"===o||"true"===d||!1},transportType:"httpStream"}}return{transportType:"stdio"}}#Es(e){const t=this.#As.indexOf(e);-1!==t&&(this.#As.splice(t,1),
4594
- this.emit("disconnect",{session:e}))}};const listFilesParams=objectType$1({spec:stringType$1().optional().describe("Only return files related to this spec file"),testTypes:arrayType$1(enumType$1(["none","draft","locked","impl","all"])).describe('Array describing which test files to return based on the kind of tests contained. Example: ["draft", "locked"]').default(["all"]),codeType:enumType$1(["none","generate","describe","all"]).describe('Single code link type, describing which code files to return, Example: "generate"').default("all"),includeSpecs:booleanType$1().describe("Whether to include spec files or not.").default(!1),includeMissing:booleanType$1().describe("Include files which have not been generated yet").default(!1)}),listSpecFilesTool=e=>({name:"list",description:"Lists tests and implementation paths in the project, optionally filtered by spec",parameters:listFilesParams,execute:async(t,r)=>listSpecFilesToolImpl(t,e)})
4591
+ this.emit("disconnect",{session:e}))}};const listFilesParams=objectType$1({spec:stringType$1().optional().describe("Only return files related to this spec file"),testTypes:arrayType$1(enumType$1(["none","draft","locked","all"])).describe('Array describing which test files to return based on the kind of tests contained. Example: ["draft", "locked"]').default(["all"]),codeType:enumType$1(["none","generate","describe","all"]).describe('Single code link type, describing which code files to return, Example: "generate"').default("all"),includeSpecs:booleanType$1().describe("Whether to include spec files or not.").default(!1),includeMissing:booleanType$1().describe("Include files which have not been generated yet").default(!1)}),listSpecFilesTool=e=>({name:"list",description:"Lists tests and implementation paths in the project, optionally filtered by spec",parameters:listFilesParams,execute:async(t,r)=>listSpecFilesToolImpl(t,e)})
4595
4592
  ;async function listSpecFilesToolImpl({spec:e,testTypes:t,codeType:r,includeMissing:n,includeSpecs:i},s){const o=await findFiles({projectDir:s,spec:e,tests:t,code:r,includeMissing:n}),a=!!i||!i&&!e;return Object.entries(o).flatMap(([e,{tests:t,code:r}])=>a?[e,...t,...r]:[...t,...r]).join("\n")}var resolveExports=requireResolve$1(),resolve=getDefaultExportFromCjs(resolveExports);function _optionalChain$k(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}const isPackageLike=e=>!e.startsWith("./"),resolvePackage=async(e,t={})=>new Promise(r=>{resolve(e,t,(e,t)=>{r(!e&&t?t:void 0)})}),baseNodeDir=(e,t)=>{const r=`node_modules/${t}`,n=e.match(r);if(_optionalChain$k([n,"optionalAccess",e=>e.index])){const t=n.index+r.length;return e.substring(0,t)}},nodeImportResolver=e=>({async resolve(t){
4596
4593
  if(!isPackageLike(t))return;const r=await resolvePackage(t,{basedir:e}),n=r&&baseNodeDir(r,t);return{displayName:t,isInstalled:async()=>!!n,openFsd:async()=>{if(!n)throw new Error("fsd not available for this package");return openFsd(n)}}}});var ndjson$1={},through2={exports:{}},readable={exports:{}},stream,hasRequiredStream,buffer_list,hasRequiredBuffer_list,destroy_1,hasRequiredDestroy;function requireStream(){return hasRequiredStream?stream:(hasRequiredStream=1,stream=require$$0$e)}function requireBuffer_list(){if(hasRequiredBuffer_list)return buffer_list;function e(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function t(t){for(var n=1;n<arguments.length;n++){var i=null!=arguments[n]?arguments[n]:{};n%2?e(Object(i),!0).forEach(function(e){r(t,e,i[e])
4597
4594
  }):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):e(Object(i)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))})}return t}function r(e,t,r){return(t=i(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function n(e,t,r){return t&&function(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,i(n.key),n)}}(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function i(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==typeof t?t:String(t)}hasRequiredBuffer_list=1
@@ -4754,81 +4751,81 @@ function Section({title:e,children:t}){return jsxRuntimeExports.jsxs(Box,{flexDi
4754
4751
  }),jsxRuntimeExports.jsx(Text,{children:e.summary}),jsxRuntimeExports.jsx(Section,{title:"Usage",children:jsxRuntimeExports.jsxs(CommandText,{children:["$ tessl ",s," ",o,_optionalChain$3([e,"access",e=>e.flags,"optionalAccess",e=>e.length])?"[flags]":""]})}),e.help!==e.summary&&jsxRuntimeExports.jsx(Section,{title:"Description",children:jsxRuntimeExports.jsx(Text,{children:e.help})}),a&&jsxRuntimeExports.jsx(Section,{title:"Flags",children:jsxRuntimeExports.jsx(CommandFlags,{flags:e.flags})})]})})}function RunHelp({command:e}){const t=getPublicTools(),[r,n]=reactExports.useState(!1),[i,s]=reactExports.useState([]);if(reactExports.useEffect(()=>{!async function(){s(await loadCustomTools([DEFAULT_TESSL_DIRS.customToolDirectory])),n(!0)}()},[]),!r)return null;const o=t.sort((e,t)=>e.name.localeCompare(t.name)),a=i.sort((e,t)=>e.name.localeCompare(t.name));return jsxRuntimeExports.jsx(StaticSingle,{children:jsxRuntimeExports.jsxs(Box,{flexDirection:"column",gap:1,
4755
4752
  children:[jsxRuntimeExports.jsx(Header,{children:"tessl run"}),jsxRuntimeExports.jsx(Section,{title:"Usage",children:jsxRuntimeExports.jsxs(CommandText,{children:["$ ","tessl run <tool>"," [flags]"]})}),jsxRuntimeExports.jsx(Section,{title:"Description",children:jsxRuntimeExports.jsx(Text,{children:e.summary})}),jsxRuntimeExports.jsx(Section,{title:"Available tools",children:jsxRuntimeExports.jsxs(Box,{flexDirection:"column",gap:1,children:[jsxRuntimeExports.jsx(ToolList,{tools:o}),a.length>0&&jsxRuntimeExports.jsx(Section,{title:"Your custom tools",children:jsxRuntimeExports.jsx(ToolList,{tools:a})})]})}),jsxRuntimeExports.jsx(Section,{title:"Flags",children:jsxRuntimeExports.jsx(CommandFlags,{flags:e.flags})})]})})}function ToolList({tools:e}){return jsxRuntimeExports.jsx(Box,{flexDirection:"column",children:e.map(({name:e,description:t})=>jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Box,{width:24,minWidth:24,children:jsxRuntimeExports.jsx(CommandText,{children:e})
4756
4753
  }),jsxRuntimeExports.jsx(WrappedText,{children:t&&formatDescription(t)})]},e))})}function formatDescription(e){return 0===e.length?"":e.at(0).toLocaleUpperCase()+e.slice(1)}function RunToolHelp({asAlias:e=!1,toolName:t,command:r}){const[n,i]=reactExports.useState(!1),[s,o]=reactExports.useState(builtInTools());reactExports.useEffect(()=>{!async function(){const e=await loadCustomTools([DEFAULT_TESSL_DIRS.customToolDirectory]);o(t=>[...t,...e]),i(!0)}()},[]);const a=s.find(e=>t===e.name);if(!a){if(!n)return null;throw new ExpectedError(`No tool found named ${t}`)}const c=`tessl ${e?"":"run "}${t}`;return jsxRuntimeExports.jsx(StaticSingle,{children:jsxRuntimeExports.jsxs(Box,{flexDirection:"column",gap:1,children:[jsxRuntimeExports.jsx(Header,{children:c}),jsxRuntimeExports.jsx(Section,{title:"Usage",children:jsxRuntimeExports.jsxs(CommandText,{children:["$ ",c,a.positionalParam?` <${a.positionalParam}>`:""," [flags]"]})}),jsxRuntimeExports.jsx(Section,{title:"Description",
4757
- children:jsxRuntimeExports.jsx(Text,{children:a.help||a.description})}),jsxRuntimeExports.jsxs(Box,{flexDirection:"column",gap:1,children:[jsxRuntimeExports.jsx(Section,{title:"Tool parameters",children:jsxRuntimeExports.jsx(ToolParamFlags,{tool:a})}),jsxRuntimeExports.jsx(Section,{title:"Flags",children:jsxRuntimeExports.jsx(CommandFlags,{flags:r.flags})})]})]})})}function CommandFlags({flags:e}){return jsxRuntimeExports.jsx(Box,{flexDirection:"column",children:Object.entries(e).filter(([,{hidden:e}])=>!e).map(([e,{short:t,type:r,description:n,defaultValue:i,availableValues:s}])=>jsxRuntimeExports.jsx(FlagRow,{long:e,short:t,type:getTypeString(r),description:n,defaultValue:i,availableValues:s},e))})}function ToolParamFlags({tool:e}){const t=schemaToFlags(e.paramsSchema,e.positionalParam);return jsxRuntimeExports.jsx(Box,{flexDirection:"column",children:t.map(({long:e,short:t,required:r,type:n,description:i,defaultValue:s,availableValues:o})=>jsxRuntimeExports.jsx(FlagRow,{long:e,
4758
- short:t,type:n,required:r,description:i,defaultValue:s,availableValues:o},e))})}function _optionalChain$2(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}async function main(e,t,r,n){const i=performance$2.now(),{analytics:s}=e,o=validateBaseEnv(process.env);try{const a=arg(flagToSpec(GlobalFlags),{permissive:!0});if(a["--print-project-cache"])return process.stdout.write(`${getProjectCacheDir()}\n`),SUCCESS;s.cliStart({command:process.argv.slice(2).join(" "),flags:a,isInteractive:isInteractive$1()});const c=a["--global-config-dir"]||DEFAULT_TESSL_PATHS.globalConfigDir,u=a["--config-dir"]||DEFAULT_TESSL_PATHS.projDir,l=await getCreds(e.logger,o,c),d=null!==l;if(a["--version"]||a["-v"])return s.runVersion({method:"flag"}),await printVersion({logger:e.logger}),s.cliEnd({
4759
- exitCode:SUCCESS,success:!0,durationMs:performance$2.now()-i,command:process.argv.slice(2).join(" ")}),SUCCESS;const p=a["--help"]||a["-h"]||!1;let[h,A,...f]=a._;_optionalChain$2([A,"optionalAccess",e=>e.startsWith,"call",e=>e("-")])&&(f.unshift(A),A=void 0),_optionalChain$2([h,"optionalAccess",e=>e.startsWith,"call",e=>e("-")])&&(f.unshift(h),h=void 0);const g=getExistingFrameworkType(u);if(!h)return render(jsxRuntimeExports.jsx(GlobalHelp,{isLoggedIn:d,frameworkType:g})),SUCCESS;if("update"!==h)try{await checkForUpdates(n)}catch(e){}if(p&&isValidActionName(h)&&!A)return s.runHelp({level:"command",command:h}),render(jsxRuntimeExports.jsx(ActionHelp,{action:h})),s.cliEnd({exitCode:SUCCESS,success:!0,durationMs:performance$2.now()-i,command:process.argv.slice(2).join(" ")}),SUCCESS;const m=getCommand(h,A);if(p){if(isBuiltInToolName(h)||"run"===h&&A&&isBuiltInToolName(A)){if(!d)throw new RequiresLoginError;const e=isBuiltInToolName(h)?h:A;s.runHelp({level:"tool",isAliased:e===h,
4760
- isCustom:!1,toolName:h}),render(jsxRuntimeExports.jsx(RunToolHelp,{asAlias:!0,toolName:e,command:m}))}else if("run"===h){if(!d)throw new RequiresLoginError;render(jsxRuntimeExports.jsx(RunHelp,{command:m}))}else m?(s.runHelp({level:"command",command:h}),render(jsxRuntimeExports.jsx(CommandHelp,{command:m,action:h,resource:A}))):(s.runHelp({level:"global",method:"command"}),render(jsxRuntimeExports.jsx(GlobalHelp,{isLoggedIn:d,frameworkType:g})));return s.cliEnd({exitCode:SUCCESS,success:!0,durationMs:performance$2.now()-i,command:process.argv.slice(2).join(" ")}),SUCCESS}if(!isValidCommandName(h,A))throw new ExpectedError(`Invalid command '${h}${A?" "+A:""}'. Run 'tessl --help' to see available commands.`);if(!m)throw new ExpectedError("Command not found. Run 'tessl --help' to see available commands.");if(isValidStandaloneCommandName(h)&&A&&f.unshift(A),isBuiltInToolName(h)&&(A&&f.unshift(A),f.unshift(h)),m.requiresLogin&&!d)throw new RequiresLoginError
4761
- ;m.requiresConfig&&ensureNoTesslMd(u);const y=new ConfigManager(join(u,TESSL_CONFIG_FILE_NAME),ProjectConfigSchema,e.logger);m.requiresConfig&&await throwIfNotInitialised(u),await y.validate();try{await checkAndUpdateProjectMetadata({monitoring:e,projectCache:n,projectConfig:y,projectDir:u})}catch(t){e.logger.error({err:t},"Encountered an error while trying to track project metadata")}const E=getTesslClient(o,_optionalChain$2([l,"optionalAccess",e=>e.accessToken])),b=await m.handle({args:f,monitoring:e,projectConfig:y,globalConfig:t,projectDir:u,globalConfigDir:c,sessionData:r,env:o,isAuthenticated:d,user:_optionalChain$2([l,"optionalAccess",e=>e.user]),tesslClient:E});return s.cliEnd({exitCode:b,success:b===SUCCESS,durationMs:performance$2.now()-i,command:process.argv.slice(2).join(" ")}),b}catch(t){if(t instanceof ExitPromptError)return SUCCESS;if(t instanceof Error)return e.logger.error({err:t},t.message),isInteractive$1()&&logError$1(t),s.cliError({message:t.message,
4762
- stack:t.stack||"",expected:t instanceof ExpectedError||t instanceof arg.ArgError,command:process.argv.slice(2).join(" ")}),s.cliEnd({exitCode:FAILURE,success:!1,durationMs:performance$2.now()-i,command:process.argv.slice(2).join(" ")}),FAILURE;throw t}}async function checkForUpdates(e){const t="version-notification-last-shown-at",r=await e.readText(t);try{if(!isInteractive$1()||isDevelopmentBuild())return;if(void 0!==r){const e=new Date(r).getTime(),t=(new Date).getTime();if(t-e<36e5)return}const n=getCurrentVersion(),i=await getLatestVersion();n!==i&&(await e.writeText(t,(new Date).toISOString()),printUpdateGuidance({latestVersion:i}))}catch(e){}}const DIGITS="0123456789abcdef";class UUID{constructor(e){this.bytes=e}static ofInner(e){if(16!==e.length)throw new TypeError("not 128-bit length");return new UUID(e)}static fromFieldsV7(e,t,r,n){
4763
- if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(n)||e<0||t<0||r<0||n<0||e>0xffffffffffff||t>4095||r>1073741823||n>4294967295)throw new RangeError("invalid field value");const i=new Uint8Array(16);return i[0]=e/2**40,i[1]=e/2**32,i[2]=e/2**24,i[3]=e/65536,i[4]=e/256,i[5]=e,i[6]=112|t>>>8,i[7]=t,i[8]=128|r>>>24,i[9]=r>>>16,i[10]=r>>>8,i[11]=r,i[12]=n>>>24,i[13]=n>>>16,i[14]=n>>>8,i[15]=n,new UUID(i)}static parse(e){let t;switch(e.length){case 32:t=/^[0-9a-f]{32}$/i.exec(e)?.[0];break;case 36:t=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;case 38:t=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e)?.slice(1,6).join("");break;case 45:t=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("")}if(t){const e=new Uint8Array(16);for(let r=0;r<16;r+=4){const n=parseInt(t.substring(2*r,2*r+8),16)
4764
- ;e[r+0]=n>>>24,e[r+1]=n>>>16,e[r+2]=n>>>8,e[r+3]=n}return new UUID(e)}throw new SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)e+=DIGITS.charAt(this.bytes[t]>>>4),e+=DIGITS.charAt(15&this.bytes[t]),3!==t&&5!==t&&7!==t&&9!==t||(e+="-");return e}toHex(){let e="";for(let t=0;t<this.bytes.length;t++)e+=DIGITS.charAt(this.bytes[t]>>>4),e+=DIGITS.charAt(15&this.bytes[t]);return e}toJSON(){return this.toString()}getVariant(){const e=this.bytes[8]>>>4;if(e<0)throw new Error("unreachable");if(e<=7)return this.bytes.every(e=>0===e)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every(e=>255===e)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return"VAR_10"===this.getVariant()?this.bytes[6]>>>4:void 0}clone(){return new UUID(this.bytes.slice(0))}equals(e){return 0===this.compareTo(e)}compareTo(e){for(let t=0;t<16;t++){const r=this.bytes[t]-e.bytes[t];if(0!==r)return Math.sign(r)}
4765
- return 0}}class V7Generator{constructor(e){this.timestamp=0,this.counter=0,this.random=e??getDefaultRandom()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let r=this.generateOrAbortCore(e,t);return void 0===r&&(this.timestamp=0,r=this.generateOrAbortCore(e,t)),r}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter())}return UUID.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){
4766
- const e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,UUID.ofInner(e)}}const getDefaultRandom=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())});let defaultGenerator;const uuidv7=()=>uuidv7obj().toString(),uuidv7obj=()=>(defaultGenerator||(defaultGenerator=new V7Generator)).generate();function makeUncaughtExceptionHandler(e,t){let r=!1;return Object.assign(n=>{const i=0===global.process.listeners("uncaughtException").filter(e=>"domainUncaughtExceptionClear"!==e.name&&!0!==e._posthogErrorHandler).length;e(n,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&i&&(r=!0,t())},{_posthogErrorHandler:!0})}function addUncaughtExceptionListener(e,t){global.process.on("uncaughtException",makeUncaughtExceptionHandler(e,t))}function addUnhandledRejectionListener(e){global.process.on("unhandledRejection",t=>{e(t,{
4767
- mechanism:{type:"onunhandledrejection",handled:!1}})})}let parsedStackResults,lastKeysCount,cachedFilenameChunkIds;function getFilenameToChunkIdMap(e){const t=globalThis._posthogChunkIds;if(!t)return console.error("No chunk id map found"),{};const r=Object.keys(t);return cachedFilenameChunkIds&&r.length===lastKeysCount||(lastKeysCount=r.length,cachedFilenameChunkIds=r.reduce((r,n)=>{parsedStackResults||(parsedStackResults={});const i=parsedStackResults[n];if(i)r[i[0]]=i[1];else{const i=e(n);for(let e=i.length-1;e>=0;e--){const s=i[e],o=s?.filename,a=t[n];if(o&&a){r[o]=a,parsedStackResults[n]=[o,a];break}}}return r},{})),cachedFilenameChunkIds}function isEvent(e){return"undefined"!=typeof Event&&isInstanceOf(e,Event)}function isPlainObject(e){return isBuiltin(e,"Object")}function isError(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return isInstanceOf(e,Error)}
4768
- }function isInstanceOf(e,t){try{return e instanceof t}catch{return!1}}function isErrorEvent(e){return isBuiltin(e,"ErrorEvent")}function isBuiltin(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}async function propertiesFromUnknownInput(e,t,r,n){const i=n&&n.mechanism||{handled:!0,type:"generic"},s=getErrorList(i,r,n),o=await Promise.all(s.map(async r=>{const n=await exceptionFromError(e,t,r);return n.value=n.value||"",n.type=n.type||"Error",n.mechanism=i,n}));return{$exception_list:o}}function getErrorList(e,t,r){const n=getError(e,t,r);return n.cause?[n,...getErrorList(e,n.cause,r)]:[n]}function getError(e,t,r){if(isError(t))return t;if(e.synthetic=!0,isPlainObject(t)){const e=getErrorPropertyFromObject(t);if(e)return e;const n=getMessageForObject(t),i=r?.syntheticException||new Error(n);return i.message=n,i}const n=r?.syntheticException||new Error(t);return n.message=`${t}`,n}function getErrorPropertyFromObject(e){
4769
- for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)){const r=e[t];if(isError(r))return r}}function getMessageForObject(e){if("name"in e&&"string"==typeof e.name){let t=`'${e.name}' captured as exception`;return"message"in e&&"string"==typeof e.message&&(t+=` with message '${e.message}'`),t}if("message"in e&&"string"==typeof e.message)return e.message;const t=extractExceptionKeysForMessage(e);if(isErrorEvent(e))return`Event \`ErrorEvent\` captured as exception with message \`${e.message}\``;const r=getObjectClassName(e);return`${r&&"Object"!==r?`'${r}'`:"Object"} captured as exception with keys: ${t}`}function getObjectClassName(e){try{const t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(e){}}function extractExceptionKeysForMessage(e,t=40){const r=Object.keys(convertToPlainObject(e));r.sort();const n=r[0];if(!n)return"[object has no keys]";if(n.length>=t)return truncate(n,t);for(let e=r.length;e>0;e--){const n=r.slice(0,e).join(", ")
4770
- ;if(!(n.length>t))return e===r.length?n:truncate(n,t)}return""}function truncate(e,t=0){return"string"!=typeof e||0===t||e.length<=t?e:`${e.slice(0,t)}...`}function convertToPlainObject(e){if(isError(e))return{message:e.message,name:e.name,stack:e.stack,...getOwnProperties(e)};if(isEvent(e)){return{type:e.type,target:serializeEventTarget(e.target),currentTarget:serializeEventTarget(e.currentTarget),...getOwnProperties(e)}}return e}function getOwnProperties(e){if("object"==typeof e&&null!==e){const t={};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t}return{}}function serializeEventTarget(e){try{return Object.prototype.toString.call(e)}catch(e){return"<unknown>"}}async function exceptionFromError(e,t,r){const n={type:r.name||r.constructor.name,value:r.message};let i=parseStackFrames(e,r);for(const e of t)i=await e(i);return i.length&&(n.stacktrace={frames:i,type:"raw"}),n}function parseStackFrames(e,t){return applyChunkIds(e(t.stack||"",1),e)}
4771
- function applyChunkIds(e,t){const r=getFilenameToChunkIdMap(t);return e.forEach(e=>{e.filename&&(e.chunk_id=r[e.filename])}),e}const SHUTDOWN_TIMEOUT=2e3;class ErrorTracking{static async buildEventMessage(e,t,r,n){const i={...n};r||(i.$process_person_profile=!1);const s=await propertiesFromUnknownInput(this.stackParser,this.frameModifiers,e,t);return{event:"$exception",distinctId:r||uuidv7(),properties:{...s,...i}}}constructor(e,t){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this.startAutocaptureIfEnabled()}startAutocaptureIfEnabled(){this.isEnabled()&&(addUncaughtExceptionListener(this.onException.bind(this),this.onFatalError.bind(this)),addUnhandledRejectionListener(this.onException.bind(this)))}onException(e,t){ErrorTracking.buildEventMessage(e,t).then(e=>{this.client.capture(e)})}async onFatalError(){await this.client.shutdown(SHUTDOWN_TIMEOUT)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}}
4772
- function createGetModuleFromFilename(e=(process.argv[1]?dirname(process.argv[1]):process.cwd()),t="\\"===sep$1){const r=t?normalizeWindowsPath(e):e;return e=>{if(!e)return;const n=t?normalizeWindowsPath(e):e;let{dir:i,base:s,ext:o}=posix$1.parse(n);".js"!==o&&".mjs"!==o&&".cjs"!==o||(s=s.slice(0,-1*o.length));const a=decodeURIComponent(s);i||(i=".");const c=i.lastIndexOf("/node_modules");if(c>-1)return`${i.slice(c+14).replace(/\//g,".")}:${a}`;if(i.startsWith(r)){const e=i.slice(r.length+1).replace(/\//g,".");return e?`${e}:${a}`:a}return a}}function normalizeWindowsPath(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}class ReduceableCache{constructor(e){this._maxSize=e,this._cache=new Map}get(e){const t=this._cache.get(e);if(void 0!==t)return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){for(;this._cache.size>=this._maxSize;){const e=this._cache.keys().next().value;e&&this._cache.delete(e)}}}
4773
- const LRU_FILE_CONTENTS_CACHE=new ReduceableCache(25),LRU_FILE_CONTENTS_FS_READ_FAILED=new ReduceableCache(20),DEFAULT_LINES_OF_CONTEXT=7,MAX_CONTEXTLINES_COLNO=1e3,MAX_CONTEXTLINES_LINENO=1e4;async function addSourceContext(e){const t={};for(let r=e.length-1;r>=0;r--){const n=e[r],i=n?.filename;if(!n||"string"!=typeof i||"number"!=typeof n.lineno||shouldSkipContextLinesForFile(i)||shouldSkipContextLinesForFrame(n))continue;t[i]||(t[i]=[]),t[i].push(n.lineno)}const r=Object.keys(t);if(0==r.length)return e;const n=[];for(const e of r){if(LRU_FILE_CONTENTS_FS_READ_FAILED.get(e))continue;const r=t[e];if(!r)continue;r.sort((e,t)=>e-t);const i=makeLineReaderRanges(r);if(i.every(t=>rangeExistsInContentCache(e,t)))continue;const s=emplace(LRU_FILE_CONTENTS_CACHE,e,{});n.push(getContextLinesFromFile(e,i,s))}return await Promise.all(n).catch(()=>{}),e&&e.length>0&&addSourceContextToFrames(e,LRU_FILE_CONTENTS_CACHE),LRU_FILE_CONTENTS_CACHE.reduce(),e}function getContextLinesFromFile(e,t,r){
4774
- return new Promise(n=>{const i=createReadStream(e),s=createInterface$1({input:i});function o(){i.destroy(),n()}let a=0,c=0;const u=t[c];if(void 0===u)return void o();let l=u[0],d=u[1];function p(){LRU_FILE_CONTENTS_FS_READ_FAILED.set(e,1),s.close(),s.removeAllListeners(),o()}i.on("error",p),s.on("error",p),s.on("close",o),s.on("line",e=>{if(a++,!(a<l)&&(r[a]=snipLine(e,0),a>=d)){if(c===t.length-1)return s.close(),void s.removeAllListeners();c++;const e=t[c];if(void 0===e)return s.close(),void s.removeAllListeners();l=e[0],d=e[1]}})})}function addSourceContextToFrames(e,t){for(const r of e)if(r.filename&&void 0===r.context_line&&"number"==typeof r.lineno){const e=t.get(r.filename);if(void 0===e)continue;addContextToFrame(r.lineno,r,e)}}function addContextToFrame(e,t,r){if(void 0===t.lineno||void 0===r)return;t.pre_context=[];for(let n=makeRangeStart(e);n<e;n++){const e=r[n];if(void 0===e)return void clearLineContext(t);t.pre_context.push(e)}
4775
- if(void 0===r[e])return void clearLineContext(t);t.context_line=r[e];const n=makeRangeEnd(e);t.post_context=[];for(let i=e+1;i<=n;i++){const e=r[i];if(void 0===e)break;t.post_context.push(e)}}function clearLineContext(e){delete e.pre_context,delete e.context_line,delete e.post_context}function shouldSkipContextLinesForFile(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function shouldSkipContextLinesForFrame(e){return void 0!==e.lineno&&e.lineno>MAX_CONTEXTLINES_LINENO||void 0!==e.colno&&e.colno>MAX_CONTEXTLINES_COLNO}function rangeExistsInContentCache(e,t){const r=LRU_FILE_CONTENTS_CACHE.get(e);if(void 0===r)return!1;for(let e=t[0];e<=t[1];e++)if(void 0===r[e])return!1;return!0}function makeLineReaderRanges(e){if(!e.length)return[];let t=0;const r=e[0];if("number"!=typeof r)return[];let n=makeContextRange(r);const i=[];for(;;){if(t===e.length-1){i.push(n);break}const r=e[t+1];if("number"!=typeof r)break
4776
- ;r<=n[1]?n[1]=r+DEFAULT_LINES_OF_CONTEXT:(i.push(n),n=makeContextRange(r)),t++}return i}function makeContextRange(e){return[makeRangeStart(e),makeRangeEnd(e)]}function makeRangeStart(e){return Math.max(1,e-DEFAULT_LINES_OF_CONTEXT)}function makeRangeEnd(e){return e+DEFAULT_LINES_OF_CONTEXT}function emplace(e,t,r){const n=e.get(t);return void 0===n?(e.set(t,r),r):n}function snipLine(e,t){let r=e;const n=r.length;if(n<=150)return r;t>n&&(t=n);let i=Math.max(t-60,0);i<5&&(i=0);let s=Math.min(i+140,n);return s>n-5&&(s=n),s===n&&(i=Math.max(s-140,0)),r=r.slice(i,s),i>0&&(r=`...${r}`),s<n&&(r+="..."),r}var version="5.3.1",PostHogPersistedProperty,Compression,SurveyPosition,SurveyWidgetType,SurveyType,SurveyQuestionDescriptionContentType,SurveyRatingDisplay,SurveyQuestionType,SurveyQuestionBranchingType,SurveyMatchType,ActionStepStringMatching;!function(e){e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.FeatureFlagDetails="feature_flag_details",
4777
- e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",e.BootstrapFeatureFlags="bootstrap_feature_flags",e.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionStartTimestamp="session_start_timestamp",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit"}(PostHogPersistedProperty||(PostHogPersistedProperty={})),function(e){e.GZipJS="gzip-js",e.Base64="base64"}(Compression||(Compression={})),function(e){
4778
- e.TopLeft="top_left",e.TopCenter="top_center",e.TopRight="top_right",e.MiddleLeft="middle_left",e.MiddleCenter="middle_center",e.MiddleRight="middle_right",e.Left="left",e.Right="right",e.Center="center"}(SurveyPosition||(SurveyPosition={})),function(e){e.Button="button",e.Tab="tab",e.Selector="selector"}(SurveyWidgetType||(SurveyWidgetType={})),function(e){e.Popover="popover",e.API="api",e.Widget="widget"}(SurveyType||(SurveyType={})),function(e){e.Html="html",e.Text="text"}(SurveyQuestionDescriptionContentType||(SurveyQuestionDescriptionContentType={})),function(e){e.Number="number",e.Emoji="emoji"}(SurveyRatingDisplay||(SurveyRatingDisplay={})),function(e){e.Open="open",e.MultipleChoice="multiple_choice",e.SingleChoice="single_choice",e.Rating="rating",e.Link="link"}(SurveyQuestionType||(SurveyQuestionType={})),function(e){e.NextQuestion="next_question",e.End="end",e.ResponseBased="response_based",e.SpecificQuestion="specific_question"
4779
- }(SurveyQuestionBranchingType||(SurveyQuestionBranchingType={})),function(e){e.Regex="regex",e.NotRegex="not_regex",e.Exact="exact",e.IsNot="is_not",e.Icontains="icontains",e.NotIcontains="not_icontains"}(SurveyMatchType||(SurveyMatchType={})),function(e){e.Contains="contains",e.Exact="exact",e.Regex="regex"}(ActionStepStringMatching||(ActionStepStringMatching={}));const normalizeFlagsResponse=e=>{if("flags"in e){const t=getFlagValuesFromFlags(e.flags),r=getPayloadsFromFlags(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{const t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([e,t])=>[e,parsePayload(t)])),n=Object.fromEntries(Object.entries(t).map(([e,t])=>[e,getFlagDetailFromFlagAndPayload(e,t,r[e])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:n}}};function getFlagDetailFromFlagAndPayload(e,t,r){return{key:e,enabled:"string"==typeof t||t,variant:"string"==typeof t?t:void 0,reason:void 0,metadata:{id:void 0,
4780
- version:void 0,payload:r?JSON.stringify(r):void 0,description:void 0}}}const getFlagValuesFromFlags=e=>Object.fromEntries(Object.entries(e??{}).map(([e,t])=>[e,getFeatureFlagValue(t)]).filter(([,e])=>void 0!==e)),getPayloadsFromFlags=e=>{const t=e??{};return Object.fromEntries(Object.keys(t).filter(e=>{const r=t[e];return r.enabled&&r.metadata&&void 0!==r.metadata.payload}).map(e=>{const r=t[e].metadata?.payload;return[e,r?parsePayload(r):void 0]}))},getFeatureFlagValue=e=>void 0===e?void 0:e.variant??e.enabled,parsePayload=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return e}},STRING_FORMAT="utf8";function assert(e,t){if(!e||"string"!=typeof e||isEmpty(e))throw new Error(t)}function isEmpty(e){return 0===e.trim().length}function removeTrailingSlash(e){return e?.replace(/\/+$/,"")}async function retriable(e,t){let r=null;for(let n=0;n<t.retryCount+1;n++){n>0&&await new Promise(e=>setTimeout(e,t.retryDelay));try{return await e()}catch(e){if(r=e,
4781
- !t.retryCheck(e))throw e}}throw r}function currentISOTime(){return(new Date).toISOString()}function safeSetTimeout(e,t){const r=setTimeout(e,t);return r?.unref&&r?.unref(),r}function allSettled(e){return Promise.all(e.map(e=>(e??Promise.resolve()).then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e}))))}function isGzipSupported(){return"CompressionStream"in globalThis}async function gzipCompress(e,t=!0){try{const t=new Blob([e],{type:"text/plain"}).stream().pipeThrough(new CompressionStream("gzip"));return await new Response(t).blob()}catch(e){return t&&console.error("Failed to gzip compress data",e),null}}class SimpleEventEmitter{constructor(){this.events={},this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.events[e]=this.events[e].filter(e=>e!==t)}}emit(e,t){for(const r of this.events[e]||[])r(t);for(const r of this.events["*"]||[])r(e,t)}}class PostHogFetchHttpError extends Error{constructor(e,t){
4782
- super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+t),this.response=e,this.reqByteLength=t,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}}class PostHogFetchNetworkError extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}async function logFlushError(e){if(e instanceof PostHogFetchHttpError){let t="";try{t=await e.text}catch{}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error("Error while flushing PostHog",e);return Promise.resolve()}function isPostHogFetchError(e){return"object"==typeof e&&(e instanceof PostHogFetchHttpError||e instanceof PostHogFetchNetworkError)}function isPostHogFetchContentTooLargeError(e){return"object"==typeof e&&e instanceof PostHogFetchHttpError&&413===e.status}
4783
- var QuotaLimitedFeature;!function(e){e.FeatureFlags="feature_flags",e.Recordings="recordings"}(QuotaLimitedFeature||(QuotaLimitedFeature={}));class PostHogCoreStateless{constructor(e,t){this.flushPromise=null,this.shutdownPromise=null,this.pendingPromises={},this._events=new SimpleEventEmitter,this._isInitialized=!1,assert(e,"You must pass your PostHog project's api key."),this.apiKey=e,this.host=removeTrailingSlash(t?.host||"https://us.i.posthog.com"),this.flushAt=t?.flushAt?Math.max(t?.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,t?.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,t?.maxQueueSize??1e3),this.flushInterval=t?.flushInterval??1e4,this.preloadFeatureFlags=t?.preloadFeatureFlags??!0,this.defaultOptIn=t?.defaultOptIn??!0,this.disableSurveys=t?.disableSurveys??!1,this._retryOptions={retryCount:t?.fetchRetryCount??3,retryDelay:t?.fetchRetryDelay??3e3,retryCheck:isPostHogFetchError},this.requestTimeout=t?.requestTimeout??1e4,
4784
- this.featureFlagsRequestTimeoutMs=t?.featureFlagsRequestTimeoutMs??3e3,this.remoteConfigRequestTimeoutMs=t?.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=t?.disableGeoip??!0,this.disabled=t?.disabled??!1,this.historicalMigration=t?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.disableCompression=!isGzipSupported()||(t?.disableCompression??!1)}logMsgIfDebug(e){this.isDebug&&e()}wrap(e){if(!this.disabled)return this._isInitialized?e():void this._initPromise.then(()=>e());this.logMsgIfDebug(()=>console.warn("[PostHog] The client is disabled"))}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(PostHogPersistedProperty.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(PostHogPersistedProperty.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(PostHogPersistedProperty.OptedOut,!0)})}on(e,t){
4785
- return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){const e=this.on("*",(e,t)=>console.log("PostHog Debug",e,t));this.removeDebugCallback=()=>{e(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){return{distinct_id:e.distinct_id,event:e.event,properties:{...e.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(e){const t=uuidv7();return this.pendingPromises[t]=e,e.catch(()=>{}).finally(()=>{delete this.pendingPromises[t]}),e}identifyStateless(e,t,r){this.wrap(()=>{const n={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",n,r)})}async identifyStatelessImmediate(e,t,r){const n={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",n,r)}captureStateless(e,t,r,n){this.wrap(()=>{const i=this.buildPayload({distinct_id:e,event:t,properties:r});this.enqueue("capture",i,n)})
4786
- }async captureStatelessImmediate(e,t,r,n){const i=this.buildPayload({distinct_id:e,event:t,properties:r});await this.sendImmediate("capture",i,n)}aliasStateless(e,t,r,n){this.wrap(()=>{const i=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});this.enqueue("alias",i,n)})}async aliasStatelessImmediate(e,t,r,n){const i=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",i,n)}groupIdentifyStateless(e,t,r,n,i,s){this.wrap(()=>{const o=this.buildPayload({distinct_id:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...s||{}}});this.enqueue("capture",o,n)})}async getRemoteConfig(){await this._initPromise;let e=this.host;"https://us.i.posthog.com"===e?e="https://us-assets.i.posthog.com":"https://eu.i.posthog.com"===e&&(e="https://eu-assets.i.posthog.com");const t=`${e}/array/${this.apiKey}/config`,r={method:"GET",
4787
- headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,r,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(e=>e.json()).catch(e=>{this.logMsgIfDebug(()=>console.error("Remote config could not be loaded",e)),this._events.emit("error",e)})}async getFlags(e,t={},r={},n={},i={}){await this._initPromise;const s=`${this.host}/flags/?v=2&config=true`,o={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify({token:this.apiKey,distinct_id:e,groups:t,person_properties:r,group_properties:n,...i})};return this.logMsgIfDebug(()=>console.log("PostHog Debug","Flags URL",s)),this.fetchWithRetry(s,o,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(e=>e.json()).then(e=>normalizeFlagsResponse(e)).catch(e=>{this._events.emit("error",e)})}async getFeatureFlagStateless(e,t,r={},n={},i={},s){await this._initPromise;const o=await this.getFeatureFlagDetailStateless(e,t,r,n,i,s);if(void 0===o)return{
4788
- response:void 0,requestId:void 0};let a=getFeatureFlagValue(o.response);return void 0===a&&(a=!1),{response:a,requestId:o.requestId}}async getFeatureFlagDetailStateless(e,t,r={},n={},i={},s){await this._initPromise;const o=await this.getFeatureFlagDetailsStateless(t,r,n,i,s,[e]);if(void 0===o)return;return{response:o.flags[e],requestId:o.requestId}}async getFeatureFlagPayloadStateless(e,t,r={},n={},i={},s){await this._initPromise;const o=await this.getFeatureFlagPayloadsStateless(t,r,n,i,s,[e]);if(!o)return;const a=o[e];return void 0===a?null:a}async getFeatureFlagPayloadsStateless(e,t={},r={},n={},i,s){await this._initPromise;return(await this.getFeatureFlagsAndPayloadsStateless(e,t,r,n,i,s)).payloads}async getFeatureFlagsStateless(e,t={},r={},n={},i,s){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,r,n,i,s)}async getFeatureFlagsAndPayloadsStateless(e,t={},r={},n={},i,s){await this._initPromise
4789
- ;const o=await this.getFeatureFlagDetailsStateless(e,t,r,n,i,s);return o?{flags:o.featureFlags,payloads:o.featureFlagPayloads,requestId:o.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(e,t={},r={},n={},i,s){await this._initPromise;const o={};(i??this.disableGeoip)&&(o.geoip_disable=!0),s&&(o.flag_keys_to_evaluate=s);const a=await this.getFlags(e,t,r,n,o);if(void 0!==a)return a.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),a.quotaLimited?.includes(QuotaLimitedFeature.FeatureFlags)?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:a?.requestId}):a}async getSurveysStateless(){
4790
- if(await this._initPromise,!0===this.disableSurveys)return this.logMsgIfDebug(()=>console.log("PostHog Debug","Loading surveys is disabled.")),[];const e=`${this.host}/api/surveys/?token=${this.apiKey}`,t={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},r=await this.fetchWithRetry(e,t).then(e=>{if(200!==e.status||!e.json){const t=`Surveys API could not be loaded: ${e.status}`,r=new Error(t);return this.logMsgIfDebug(()=>console.error(r)),void this._events.emit("error",new Error(t))}return e.json()}).catch(e=>{this.logMsgIfDebug(()=>console.error("Surveys API could not be loaded",e)),this._events.emit("error",e)}),n=r?.surveys;return n&&this.logMsgIfDebug(()=>console.log("PostHog Debug","Surveys fetched from API: ",JSON.stringify(n))),n??[]}get props(){return this._props||(this._props=this.getPersistedProperty(PostHogPersistedProperty.Props)),this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},
4791
- this.setPersistedProperty(PostHogPersistedProperty.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(PostHogPersistedProperty.Props,this.props)})}enqueue(e,t,r){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");const n=this.prepareMessage(e,t,r),i=this.getPersistedProperty(PostHogPersistedProperty.Queue)||[];i.length>=this.maxQueueSize&&(i.shift(),this.logMsgIfDebug(()=>console.info("Queue is full, the oldest event is dropped."))),i.push({message:n}),this.setPersistedProperty(PostHogPersistedProperty.Queue,i),this._events.emit(e,n),i.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=safeSetTimeout(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(e,t,r){if(this.disabled)return void this.logMsgIfDebug(()=>console.warn("[PostHog] The client is disabled"))
4792
- ;if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");const n={api_key:this.apiKey,batch:[this.prepareMessage(e,t,r)],sent_at:currentISOTime()};this.historicalMigration&&(n.historical_migration=!0);const i=JSON.stringify(n),s=`${this.host}/batch/`,o=this.disableCompression?null:await gzipCompress(i,this.isDebug),a={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==o&&{"Content-Encoding":"gzip"}},body:o||i};try{await this.fetchWithRetry(s,a)}catch(e){this._events.emit("error",e)}}prepareMessage(e,t,r){const n={...t,type:e,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:r?.timestamp?r?.timestamp:currentISOTime(),uuid:r?.uuid?r.uuid:uuidv7()};return(r?.disableGeoip??this.disableGeoip)&&(n.properties||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,
4793
- delete n.distinctId),n}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.flush().catch(async e=>{await logFlushError(e)})}async flush(){const e=allSettled([this.flushPromise]).then(()=>this._flush());return this.flushPromise=e,this.addPendingPromise(e),allSettled([e]).then(()=>{this.flushPromise===e&&(this.flushPromise=null)}),e}getCustomHeaders(){const e=this.getCustomUserAgent(),t={};return e&&""!==e&&(t["User-Agent"]=e),t}async _flush(){this.clearFlushTimer(),await this._initPromise;let e=this.getPersistedProperty(PostHogPersistedProperty.Queue)||[];if(!e.length)return;const t=[],r=e.length;for(;e.length>0&&t.length<r;){const r=e.slice(0,this.maxBatchSize),n=r.map(e=>e.message),i=()=>{const t=(this.getPersistedProperty(PostHogPersistedProperty.Queue)||[]).slice(r.length);this.setPersistedProperty(PostHogPersistedProperty.Queue,t),e=t},s={api_key:this.apiKey,batch:n,sent_at:currentISOTime()}
4794
- ;this.historicalMigration&&(s.historical_migration=!0);const o=JSON.stringify(s),a=`${this.host}/batch/`,c=this.disableCompression?null:await gzipCompress(o,this.isDebug),u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==c&&{"Content-Encoding":"gzip"}},body:c||o},l={retryCheck:e=>!isPostHogFetchContentTooLargeError(e)&&isPostHogFetchError(e)};try{await this.fetchWithRetry(a,u,l)}catch(e){if(isPostHogFetchContentTooLargeError(e)&&n.length>1){this.maxBatchSize=Math.max(1,Math.floor(n.length/2)),this.logMsgIfDebug(()=>console.warn(`Received 413 when sending batch of size ${n.length}, reducing batch size to ${this.maxBatchSize}`));continue}throw e instanceof PostHogFetchNetworkError||i(),this._events.emit("error",e),e}i(),t.push(...n)}this._events.emit("flush",t)}async fetchWithRetry(e,t,r,n){var i;(i=AbortSignal).timeout??(i.timeout=function(e){const t=new AbortController;return setTimeout(()=>t.abort(),e),t.signal});const s=t.body?t.body:""
4795
- ;let o=-1;try{o=s instanceof Blob?s.size:Buffer.byteLength(s,STRING_FORMAT)}catch{if(s instanceof Blob)o=s.size;else{const e=(new TextEncoder).encode(s);o=e.length}}return await retriable(async()=>{let r=null;try{r=await this.fetch(e,{signal:AbortSignal.timeout(n??this.requestTimeout),...t})}catch(e){throw new PostHogFetchNetworkError(e)}if(!("no-cors"===t.mode)&&(r.status<200||r.status>=400))throw new PostHogFetchHttpError(r,o);return r},{...this._retryOptions,...r})}async _shutdown(e=3e4){await this._initPromise;let t=!1;this.clearFlushTimer();return Promise.race([new Promise((r,n)=>{safeSetTimeout(()=>{this.logMsgIfDebug(()=>console.error("Timed out while shutting down PostHog")),t=!0,n("Timeout while shutting down PostHog. Some events may not have been sent.")},e)}),(async()=>{try{for(await Promise.all(Object.values(this.pendingPromises));;){if(0===(this.getPersistedProperty(PostHogPersistedProperty.Queue)||[]).length)break;if(await this.flush(),t)break}}catch(e){
4796
- if(!isPostHogFetchError(e))throw e;await logFlushError(e)}})()])}async shutdown(e=3e4){return this.shutdownPromise?this.logMsgIfDebug(()=>console.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup")):this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}}class Lazy{constructor(e){this.factory=e}async getValue(){return void 0!==this.value?this.value:(void 0===this.initializationPromise&&(this.initializationPromise=(async()=>{try{const e=await this.factory();return this.value=e,e}finally{this.initializationPromise=void 0}})()),this.initializationPromise)}isInitialized(){return void 0!==this.value}async waitForInitialization(){this.isInitialized()||await this.getValue()}}const nodeCrypto=new Lazy(async()=>{try{return await import("crypto")}catch{return}});async function getNodeCrypto(){return await nodeCrypto.getValue()}
4797
- const webCrypto=new Lazy(async()=>{if(void 0!==globalThis.crypto?.subtle)return globalThis.crypto.subtle;try{const e=await nodeCrypto.getValue();if(e?.webcrypto?.subtle)return e.webcrypto.subtle}catch{}});async function getWebCrypto(){return await webCrypto.getValue()}async function hashSHA1(e){const t=await getNodeCrypto();if(t)return t.createHash("sha1").update(e).digest("hex");const r=await getWebCrypto();if(r){const t=await r.digest("SHA-1",(new TextEncoder).encode(e));return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,"0")).join("")}throw new Error("No crypto implementation available. Tried Node Crypto API and Web SubtleCrypto API")}const SIXTY_SECONDS=6e4,LONG_SCALE=0x1000000000000000,NULL_VALUES_ALLOWED_OPERATORS=["is_not"];class ClientError extends Error{constructor(e){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,ClientError.prototype)}}class InconclusiveMatchError extends Error{
4798
- constructor(e){super(e),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,InconclusiveMatchError.prototype)}}class FeatureFlagsPoller{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:r,timeout:n,host:i,customHeaders:s,...o}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=n,this.projectApiKey=r,this.host=i,this.poller=void 0,this.fetch=o.fetch||fetch,this.onError=o.onError,this.customHeaders=s,this.onLoad=o.onLoad,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){this.debugMode&&e()}async getFeatureFlag(e,t,r={},n={},i={}){let s,o;if(await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return s;for(const t of this.featureFlags)if(e===t.key){o=t;break}if(void 0!==o)try{
4799
- s=await this.computeFlagLocally(o,t,r,n,i),this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${s}`))}catch(t){t instanceof InconclusiveMatchError?this.logMsgIfDebug(()=>console.debug(`InconclusiveMatchError when computing flag locally: ${e}: ${t}`)):t instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${e}: ${t}`))}return s}async computeFeatureFlagPayloadLocally(e,t){let r;if(await this.loadFeatureFlags(),this.loadedSuccessfullyOnce){if("boolean"==typeof t?r=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t.toString()]:"string"==typeof t&&(r=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t]),null==r)return null;try{return JSON.parse(r)}catch{return r}}}async getAllFlagsAndPayloads(e,t={},r={},n={}){await this.loadFeatureFlags();const i={},s={};let o=0==this.featureFlags.length;return await Promise.all(this.featureFlags.map(async a=>{try{const o=await this.computeFlagLocally(a,e,t,r,n);i[a.key]=o
4800
- ;const c=await this.computeFeatureFlagPayloadLocally(a.key,o);c&&(s[a.key]=c)}catch(e){e instanceof InconclusiveMatchError||e instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${a.key}: ${e}`)),o=!0}})),{response:i,payloads:s,fallbackToFlags:o}}async computeFlagLocally(e,t,r={},n={},i={}){if(e.ensure_experience_continuity)throw new InconclusiveMatchError("Flag has experience continuity enabled");if(!e.active)return!1;const s=(e.filters||{}).aggregation_group_type_index;if(null!=s){const t=this.groupTypeMapping[String(s)];if(!t)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${s} for feature flag ${e.key}`)),new InconclusiveMatchError("Flag has unknown group type index");if(!(t in r))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;const n=i[t];return await this.matchFeatureFlagProperties(e,r[t],n)}
4801
- return await this.matchFeatureFlagProperties(e,t,n)}async matchFeatureFlagProperties(e,t,r){const n=e.filters||{};let i,s=!1;const o=[...n.groups||[]].sort((e,t)=>{const r=!!e.variant,n=!!t.variant;return r&&n?0:r?-1:n?1:0});for(const a of o)try{if(await this.isConditionMatch(e,t,a,r)){const r=a.variant,s=n.multivariate?.variants||[];i=r&&s.some(e=>e.key===r)?r:await this.getMatchingVariant(e,t)||!0;break}}catch(e){if(!(e instanceof InconclusiveMatchError))throw e;s=!0}if(void 0!==i)return i;if(s)throw new InconclusiveMatchError("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,t,r,n){const i=r.rollout_percentage,s=e=>{this.logMsgIfDebug(()=>console.warn(e))};if((r.properties||[]).length>0){for(const e of r.properties){let t=!1;if(t="cohort"===e.type?matchCohort(e,n,this.cohorts,this.debugMode):matchProperty(e,n,s),!t)return!1}if(null==i)return!0}return!(null!=i&&await _hash(e.key,t)>i/100)}async getMatchingVariant(e,t){
4802
- const r=await _hash(e.key,t,"variant"),n=this.variantLookupTable(e).find(e=>r>=e.valueMin&&r<e.valueMax);if(n)return n.key}variantLookupTable(e){const t=[];let r=0,n=0;const i=e.filters||{};return(i.multivariate?.variants||[]).forEach(e=>{n=r+e.rollout_percentage/100,t.push({valueMin:r,valueMax:n,key:e.key}),r=n}),t}async loadFeatureFlags(e=!1){this.loadedSuccessfullyOnce&&!e||await this._loadFeatureFlags()}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(SIXTY_SECONDS,this.pollingInterval*2**this.backOffCount):this.pollingInterval}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this._loadFeatureFlags(),this.getPollingInterval());try{const e=await this._requestFeatureFlagDefinitions();if(!e)return;switch(e.status){case 401:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,
4803
- new ClientError(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:return console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},void(this.cohorts={});case 403:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new ClientError(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,
4804
- new ClientError(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{const t=await e.json()??{};if(!("flags"in t))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(t)}`));this.featureFlags=t.flags??[],this.featureFlagsByKey=this.featureFlags.reduce((e,t)=>(e[t.key]=t,e),{}),this.groupTypeMapping=t.group_type_mapping||{},this.cohorts=t.cohorts||{},this.loadedSuccessfullyOnce=!0,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.onLoad?.(this.featureFlags.length);break}default:return}}catch(e){e instanceof ClientError&&this.onError?.(e)}}getPersonalApiKeyRequestOptions(e="GET"){return{method:e,headers:{...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`}}}async _requestFeatureFlagDefinitions(){
4805
- const e=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions();let r=null;if(this.timeout&&"number"==typeof this.timeout){const e=new AbortController;r=safeSetTimeout(()=>{e.abort()},this.timeout),t.signal=e.signal}try{return await this.fetch(e,t)}finally{clearTimeout(r)}}stopPoller(){clearTimeout(this.poller)}}async function _hash(e,t,r=""){const n=await hashSHA1(`${e}.${t}${r}`);return parseInt(n.slice(0,15),16)/LONG_SCALE}function matchProperty(e,t,r){const n=e.key,i=e.value,s=e.operator||"exact";if(!(n in t))throw new InconclusiveMatchError(`Property ${n} not found in propertyValues`);if("is_not_set"===s)throw new InconclusiveMatchError("Operator is_not_set is not supported");const o=t[n];if(null==o&&!NULL_VALUES_ALLOWED_OPERATORS.includes(s))return r&&r(`Property ${n} cannot have a value of null/undefined with the ${s} operator`),!1;function a(e,t){
4806
- return Array.isArray(e)?e.map(e=>String(e).toLowerCase()).includes(String(t).toLowerCase()):String(e).toLowerCase()===String(t).toLowerCase()}function c(e,t,r){if("gt"===r)return e>t;if("gte"===r)return e>=t;if("lt"===r)return e<t;if("lte"===r)return e<=t;throw new Error(`Invalid operator: ${r}`)}switch(s){case"exact":return a(i,o);case"is_not":return!a(i,o);case"is_set":return n in t;case"icontains":return String(o).toLowerCase().includes(String(i).toLowerCase());case"not_icontains":return!String(o).toLowerCase().includes(String(i).toLowerCase());case"regex":return isValidRegex(String(i))&&null!==String(o).match(String(i));case"not_regex":return isValidRegex(String(i))&&null===String(o).match(String(i));case"gt":case"gte":case"lt":case"lte":{let e="number"==typeof i?i:null;if("string"==typeof i)try{e=parseFloat(i)}catch(e){}return null!=e&&null!=o?c(o,"string"==typeof o?String(i):e,s):c(String(o),String(i),s)}case"is_date_after":case"is_date_before":{
4807
- let e=relativeDateParseForFeatureFlagMatching(String(i));if(null==e&&(e=convertToDateTime(i)),null==e)throw new InconclusiveMatchError(`Invalid date: ${i}`);const t=convertToDateTime(o);return["is_date_before"].includes(s)?t<e:t>e}default:throw new InconclusiveMatchError(`Unknown operator: ${s}`)}}function matchCohort(e,t,r,n=!1){const i=String(e.value);if(!(i in r))throw new InconclusiveMatchError("can't match cohort without a given cohort property value");return matchPropertyGroup(r[i],t,r,n)}function matchPropertyGroup(e,t,r,n=!1){if(!e)return!0;const i=e.type,s=e.values;if(!s||0===s.length)return!0;let o=!1;if("values"in s[0]){for(const e of s)try{const s=matchPropertyGroup(e,t,r,n);if("AND"===i){if(!s)return!1}else if(s)return!0}catch(t){if(!(t instanceof InconclusiveMatchError))throw t;n&&console.debug(`Failed to compute property ${e} locally: ${t}`),o=!0}if(o)throw new InconclusiveMatchError("Can't match cohort without a given cohort property value");return"AND"===i}
4808
- for(const e of s)try{let s;s="cohort"===e.type?matchCohort(e,t,r,n):matchProperty(e,t);const o=e.negation||!1;if("AND"===i){if(!s&&!o)return!1;if(s&&o)return!1}else{if(s&&!o)return!0;if(!s&&o)return!0}}catch(t){if(!(t instanceof InconclusiveMatchError))throw t;n&&console.debug(`Failed to compute property ${e} locally: ${t}`),o=!0}if(o)throw new InconclusiveMatchError("can't match cohort without a given cohort property value");return"AND"===i}function isValidRegex(e){try{return new RegExp(e),!0}catch(e){return!1}}function convertToDateTime(e){if(e instanceof Date)return e;if("string"==typeof e||"number"==typeof e){const t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new InconclusiveMatchError(`${e} is in an invalid date format`)}throw new InconclusiveMatchError(`The date provided ${e} must be a string, number, or date object`)}function relativeDateParseForFeatureFlagMatching(e){const t=e.match(/^-?(?<number>[0-9]+)(?<interval>[a-z])$/),r=new Date((new Date).toISOString());if(t){
4809
- if(!t.groups)return null;const e=parseInt(t.groups.number);if(e>=1e4)return null;const n=t.groups.interval;if("h"==n)r.setUTCHours(r.getUTCHours()-e);else if("d"==n)r.setUTCDate(r.getUTCDate()-e);else if("w"==n)r.setUTCDate(r.getUTCDate()-7*e);else if("m"==n)r.setUTCMonth(r.getUTCMonth()-e);else{if("y"!=n)return null;r.setUTCFullYear(r.getUTCFullYear()-e)}return r}return null}class PostHogMemoryStorage{constructor(){this._memoryStorage={}}getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=null!==t?t:void 0}}const MINIMUM_POLLING_INTERVAL=100,THIRTY_SECONDS=3e4,MAX_CACHE_SIZE=5e4;class PostHogBackendClient extends PostHogCoreStateless{constructor(e,t={}){if(super(e,t),this._memoryStorage=new PostHogMemoryStorage,this.options=t,this.options.featureFlagsPollingInterval="number"==typeof t.featureFlagsPollingInterval?Math.max(t.featureFlagsPollingInterval,MINIMUM_POLLING_INTERVAL):THIRTY_SECONDS,t.personalApiKey){
4810
- if(t.personalApiKey.includes("phc_"))throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');!1!==t.enableLocalEvaluation&&(this.featureFlagsPoller=new FeatureFlagsPoller({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:t.personalApiKey,projectApiKey:e,timeout:t.requestTimeout??1e4,host:this.host,fetch:t.fetch,onError:e=>{this._events.emit("error",e)},onLoad:e=>{this._events.emit("localEvaluationFlagsLoaded",e)},customHeaders:this.getCustomHeaders()}))}this.errorTracking=new ErrorTracking(this,t),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=t.maxCacheSize||MAX_CACHE_SIZE}getPersistedProperty(e){return this._memoryStorage.getProperty(e)}setPersistedProperty(e,t){return this._memoryStorage.setProperty(e,t)}fetch(e,t){return this.options.fetch?this.options.fetch(e,t):fetch(e,t)}getLibraryVersion(){return version}getCustomUserAgent(){
4811
- return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}capture(e){"string"==typeof e&&this.logMsgIfDebug(()=>console.warn("Called capture() with a string as the first argument when an object was expected."));const{distinctId:t,event:r,properties:n,groups:i,sendFeatureFlags:s,timestamp:o,disableGeoip:a,uuid:c}=e,u=e=>{super.captureStateless(t,r,e,{timestamp:o,disableGeoip:a,uuid:c})},l=async(e,t,r)=>(await super.getFeatureFlagsStateless(e,t,void 0,void 0,r)).flags,d=Promise.resolve().then(async()=>{if(s)return await l(t,i,a);if("$feature_flag_called"===r)return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){const e={};for(const[t,r]of Object.entries(i||{}))e[t]=String(r);return await this.getAllFlags(t,{groups:e,disableGeoip:a,onlyEvaluateLocally:!0})}return{}}).then(e=>{const t={};if(e)for(const[r,n]of Object.entries(e))t[`$feature/${r}`]=n
4812
- ;const r=Object.keys(e||{}).filter(t=>!1!==e?.[t]).sort();return r.length>0&&(t.$active_feature_flags=r),t}).catch(()=>({})).then(e=>{u({...e,...n,$groups:i})});this.addPendingPromise(d)}async captureImmediate(e){"string"==typeof e&&this.logMsgIfDebug(()=>console.warn("Called capture() with a string as the first argument when an object was expected."));const{distinctId:t,event:r,properties:n,groups:i,sendFeatureFlags:s,timestamp:o,disableGeoip:a,uuid:c}=e,u=e=>super.captureStatelessImmediate(t,r,e,{timestamp:o,disableGeoip:a,uuid:c}),l=async(e,t,r)=>(await super.getFeatureFlagsStateless(e,t,void 0,void 0,r)).flags,d=Promise.resolve().then(async()=>{if(s)return await l(t,i,a);if("$feature_flag_called"===r)return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){const e={};for(const[t,r]of Object.entries(i||{}))e[t]=String(r);return await this.getAllFlags(t,{groups:e,disableGeoip:a,onlyEvaluateLocally:!0})}return{}}).then(e=>{const t={}
4813
- ;if(e)for(const[r,n]of Object.entries(e))t[`$feature/${r}`]=n;const r=Object.keys(e||{}).filter(t=>!1!==e?.[t]).sort();return r.length>0&&(t.$active_feature_flags=r),t}).catch(()=>({})).then(e=>{u({...e,...n,$groups:i})});await d}identify({distinctId:e,properties:t,disableGeoip:r}){const n=t?.$set_once;delete t?.$set_once;const i=t?.$set||t;super.identifyStateless(e,{$set:i,$set_once:n},{disableGeoip:r})}async identifyImmediate({distinctId:e,properties:t,disableGeoip:r}){const n=t?.$set_once;delete t?.$set_once;const i=t?.$set||t;await super.identifyStatelessImmediate(e,{$set:i,$set_once:n},{disableGeoip:r})}alias(e){super.aliasStateless(e.alias,e.distinctId,void 0,{disableGeoip:e.disableGeoip})}async aliasImmediate(e){await super.aliasStatelessImmediate(e.alias,e.distinctId,void 0,{disableGeoip:e.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(e=THIRTY_SECONDS){
4814
- return!!this.isLocalEvaluationReady()||void 0!==this.featureFlagsPoller&&new Promise(t=>{const r=setTimeout(()=>{n(),t(!1)},e),n=this._events.on("localEvaluationFlagsLoaded",e=>{clearTimeout(r),n(),t(e>0)})})}async getFeatureFlag(e,t,r){const{groups:n,disableGeoip:i}=r||{};let{onlyEvaluateLocally:s,sendFeatureFlagEvents:o,personProperties:a,groupProperties:c}=r||{};const u=this.addLocalPersonAndGroupProperties(t,n,a,c);a=u.allPersonProperties,c=u.allGroupProperties,null==s&&(s=!1),null==o&&(o=!0);let l=await(this.featureFlagsPoller?.getFeatureFlag(e,t,n,a,c));const d=void 0!==l;let p,h;if(!d&&!s){const r=await super.getFeatureFlagDetailStateless(e,t,n,a,c,i);if(void 0===r)return;h=r.response,l=getFeatureFlagValue(h),p=r?.requestId}const A=`${e}_${l}`;return!o||t in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[t].includes(A)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),
4815
- Array.isArray(this.distinctIdHasSentFlagCalls[t])?this.distinctIdHasSentFlagCalls[t].push(A):this.distinctIdHasSentFlagCalls[t]=[A],this.capture({distinctId:t,event:"$feature_flag_called",properties:{$feature_flag:e,$feature_flag_response:l,$feature_flag_id:h?.metadata?.id,$feature_flag_version:h?.metadata?.version,$feature_flag_reason:h?.reason?.description??h?.reason?.code,locally_evaluated:d,[`$feature/${e}`]:l,$feature_flag_request_id:p},groups:n,disableGeoip:i})),l}async getFeatureFlagPayload(e,t,r,n){const{groups:i,disableGeoip:s}=n||{};let{onlyEvaluateLocally:o,sendFeatureFlagEvents:a,personProperties:c,groupProperties:u}=n||{};const l=this.addLocalPersonAndGroupProperties(t,i,c,u);let d;c=l.allPersonProperties,u=l.allGroupProperties;void 0!==this.featureFlagsPoller&&(r||(r=await this.getFeatureFlag(e,t,{...n,onlyEvaluateLocally:!0,sendFeatureFlagEvents:!1})),r&&(d=await(this.featureFlagsPoller?.computeFeatureFlagPayloadLocally(e,r)))),null==o&&(o=!1),null==a&&(a=!0),
4816
- null==o&&(o=!1);return void 0!==d||o||(d=await super.getFeatureFlagPayloadStateless(e,t,i,c,u,s)),d}async getRemoteConfigPayload(e){if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");const t=await this._requestRemoteConfigPayload(e);if(!t)return;const r=await t.json();if("string"==typeof r)try{return JSON.parse(r)}catch(e){return r}return r}async isFeatureEnabled(e,t,r){const n=await this.getFeatureFlag(e,t,r);if(void 0!==n)return!!n||!1}async getAllFlags(e,t){return(await this.getAllFlagsAndPayloads(e,t)).featureFlags||{}}async getAllFlagsAndPayloads(e,t){const{groups:r,disableGeoip:n}=t||{};let{onlyEvaluateLocally:i,personProperties:s,groupProperties:o}=t||{};const a=this.addLocalPersonAndGroupProperties(e,r,s,o);s=a.allPersonProperties,o=a.allGroupProperties,null==i&&(i=!1);const c=await(this.featureFlagsPoller?.getAllFlagsAndPayloads(e,r,s,o));let u={},l={},d=!0;if(c&&(u=c.response,l=c.payloads,d=c.fallbackToFlags),
4817
- d&&!i){const t=await super.getFeatureFlagsAndPayloadsStateless(e,r,s,o,n);u={...u,...t.flags||{}},l={...l,...t.payloads||{}}}return{featureFlags:u,featureFlagPayloads:l}}groupIdentify({groupType:e,groupKey:t,properties:r,distinctId:n,disableGeoip:i}){super.groupIdentifyStateless(e,t,r,{disableGeoip:i},n)}async reloadFeatureFlags(){await(this.featureFlagsPoller?.loadFeatureFlags(!0))}async _shutdown(e){return this.featureFlagsPoller?.stopPoller(),super._shutdown(e)}async _requestRemoteConfigPayload(e){if(!this.options.personalApiKey)return;const t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config/`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}};let n=null;if(this.options.requestTimeout&&"number"==typeof this.options.requestTimeout){const e=new AbortController;n=safeSetTimeout(()=>{e.abort()},this.options.requestTimeout),r.signal=e.signal}try{return await this.fetch(t,r)
4818
- }catch(e){return void this._events.emit("error",e)}finally{n&&clearTimeout(n)}}addLocalPersonAndGroupProperties(e,t,r,n){const i={distinct_id:e,...r||{}},s={};if(t)for(const e of Object.keys(t))s[e]={$group_key:t[e],...n?.[e]||{}};return{allPersonProperties:i,allGroupProperties:s}}captureException(e,t,r){const n=new Error("PostHog syntheticException");ErrorTracking.buildEventMessage(e,{syntheticException:n},t,r).then(e=>{this.capture(e)})}async captureExceptionImmediate(e,t,r){const n=new Error("PostHog syntheticException"),i=await ErrorTracking.buildEventMessage(e,{syntheticException:n},t,r);return await this.captureImmediate(i)}}const WEBPACK_ERROR_REGEXP=/\(error: (.*)\)/,STACKTRACE_FRAME_LIMIT=50,UNKNOWN_FUNCTION="?";function node(e){const t=/^\s*[-]{4,}$/,r=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;return n=>{const i=n.match(r);if(i){let t,r,n,s,o;if(i[1]){n=i[1];let e=n.lastIndexOf(".");if("."===n[e-1]&&e--,e>0){t=n.slice(0,e),r=n.slice(e+1)
4819
- ;const i=t.indexOf(".Module");i>0&&(n=n.slice(i+1),t=t.slice(0,i))}s=void 0}r&&(s=t,o=r),"<anonymous>"===r&&(o=void 0,n=void 0),void 0===n&&(o=o||UNKNOWN_FUNCTION,n=s?`${s}.${o}`:o);let a=i[2]?.startsWith("file://")?i[2].slice(7):i[2];const c="native"===i[5];return a?.match(/\/[A-Z]:/)&&(a=a.slice(1)),a||!i[5]||c||(a=i[5]),{filename:a?decodeURI(a):void 0,module:e?e(a):void 0,function:n,lineno:_parseIntOrUndefined(i[3]),colno:_parseIntOrUndefined(i[4]),in_app:filenameIsInApp(a||"",c),platform:"node:javascript"}}if(n.match(t))return{filename:n,platform:"node:javascript"}}}function filenameIsInApp(e,t=!1){return!(t||e&&!e.startsWith("/")&&!e.match(/^[A-Z]:/)&&!e.startsWith(".")&&!e.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&void 0!==e&&!e.includes("node_modules/")}function _parseIntOrUndefined(e){return parseInt(e||"",10)||void 0}function nodeStackLineParser(e){return[90,node(e)]}function createStackParser(e){const t=[nodeStackLineParser(e)].sort((e,t)=>e[0]-t[0]).map(e=>e[1])
4820
- ;return(e,r=0)=>{const n=[],i=e.split("\n");for(let e=r;e<i.length;e++){const r=i[e];if(r.length>1024)continue;const s=WEBPACK_ERROR_REGEXP.test(r)?r.replace(WEBPACK_ERROR_REGEXP,"$1"):r;if(!s.match(/\S*Error: /)){for(const e of t){const t=e(s);if(t){n.push(t);break}}if(n.length>=STACKTRACE_FRAME_LIMIT)break}}return reverseAndStripFrames(n)}}function reverseAndStripFrames(e){if(!e.length)return[];const t=Array.from(e);return t.reverse(),t.slice(0,STACKTRACE_FRAME_LIMIT).map(e=>({...e,filename:e.filename||getLastStackFrame(t).filename,function:e.function||UNKNOWN_FUNCTION}))}function getLastStackFrame(e){return e[e.length-1]||{}}ErrorTracking.stackParser=createStackParser(createGetModuleFromFilename()),ErrorTracking.frameModifiers=[addSourceContext];class PostHog extends PostHogBackendClient{getLibraryId(){return"posthog-node"}}function _nullishCoalesce$1(e,t){return null!=e?e:t()}async function _asyncNullishCoalesce$1(e,t){return null!=e?e:await t()}
4821
- function wrapLoggerWithEmitter(e,t,r){function n(r,n,i){return e.emit("log",{context:n,message:i,level:r}),t[r](n,i)}return{trace:(e,t)=>n("trace",{...r,...e},t),debug:(e,t)=>n("debug",{...r,...e},t),info:(e,t)=>n("info",{...r,...e},t),warn:(e,t)=>n("warn",{...r,...e},t),error:(e,t)=>n("error",{...r,...e},t),child(n){const i=t.child(n);return wrapLoggerWithEmitter(e,i,{...r,...n})},originalLogger:t}}async function constructLogger(e,t){const r=[],n=validateBaseEnv(process.env),i=process.argv.includes("mcp"),s=i?"mcp":"cli";isInteractive$1()||i||r.push({target:"pino/file",options:{destination:1}});const o=new EventEmitter,a=_nullishCoalesce$1(n.TESSL_LOG_LEVEL,()=>"info"),c=Math.min(_nullishCoalesce$1(pino.levels.values[a],()=>30),_nullishCoalesce$1(pino.levels.values.info,()=>30)),u=_nullishCoalesce$1(pino.levels.labels[c],()=>"info");if(a&&"silent"!==a&&""!==n.TESSL_LOG_FILE){const e=n.TESSL_LOG_FILE?path$7.resolve(n.TESSL_LOG_FILE):path$7.join(getProjectCacheDir(),"tessl.log")
4822
- ;r.push({target:"pino/file",level:a,options:{destination:e,mkdir:!0}})}const l=!t||await _asyncNullishCoalesce$1(await t.get("shareUsageData"),async()=>!0);"true"!==process.env.OTEL_SDK_DISABLED&&l&&r.push({target:"pino-opentelemetry-transport",options:{},level:"info"});const d=wrapLoggerWithEmitter(o,pino({name:e,level:u,transport:{targets:r}}),{context:s});return t&&t.setLogger(d),{logBus:o,logger:d}}function _optionalChain$1(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function quietLangfuse(e){const t={...e};_optionalChain$1([e,"optionalAccess",e=>e.secretKey])||void 0!==process.env.LANGFUSE_SECRET_KEY||(t.enabled=!1,t.publicKey="disabled",t.secretKey="disabled");const r=new Langfuse(t);return"yes"===process.env.TESSL_DEBUG_MONITORING&&r.debug(),r}
4823
- function _nullishCoalesce(e,t){return null!=e?e:t()}const CLI_PROJECT_GROUP_TYPE="CLI Project";class PosthogAnalytics{__init(){this.toolSessionMap=new Map}constructor(e,t,r,n){PosthogAnalytics.prototype.__init.call(this),this.posthog=e,this.distinctId=t,this.projectCache=n,this.runId=null,this.sessionId="",this.shareUsageData=r,this.cliVersion="unknown",this.osType="unknown",this.osRelease="unknown",this.nodeVersion="unknown",this.platformInfo=_nullishCoalesce(platform$1(),()=>"unknown"),this.archInfo=_nullishCoalesce(arch(),()=>"unknown"),this.projectId=""}async initialize(){this.projectId=await getCurrentProjectId(this.projectCache,this.distinctId);const e=getSysinfo();this.cliVersion=_nullishCoalesce(e.version,()=>"unknown"),this.osType=_nullishCoalesce(e.osImplementation,()=>"unknown"),this.osRelease=_nullishCoalesce(e.osRelease,()=>"unknown"),this.nodeVersion=_nullishCoalesce(e.nodeVersion,()=>"unknown");const t=await SessionManager.getCliSessionInfo();this.sessionId=t.sessionId}
4824
- static async create(e,t,r,n){const i=new PosthogAnalytics(e,t,r,n);return await i.initialize(),i}captureEvent(e,t){this.runId||(this.runId=v4()),this.captureEventBase(e,{source:"cli",runId:this.runId,sessionId:this.sessionId,...t})}captureEventBase(e,t){if(!this.shareUsageData)return;const r={...t,source:"cli",cliVersion:this.cliVersion,osType:this.osType,osRelease:this.osRelease,nodeVersion:this.nodeVersion,platform:this.platformInfo,arch:this.archInfo,timestamp:(new Date).toISOString()};this.posthog.capture({distinctId:this.distinctId,event:e,properties:r,groups:{[CLI_PROJECT_GROUP_TYPE]:this.projectId}})}capture(e,t){this.captureEvent(e,t)}async refreshCliSession(){const e=await SessionManager.getCliSessionInfo();this.sessionId=e.sessionId}mcpServerStart(){this.captureEvent("cli:mcp:server:start",{})}mcpServerEnd(e){this.captureEvent("cli:mcp:server:end",{...e})}async mcpToolStart(e){const t=await SessionManager.getMcpToolInfo();await this.refreshCliSession();const r={...e,
4825
- runId:t.runId,sessionId:t.sessionId,parentRunId:t.parentRunId};return this.captureEventBase("cli:mcp:tool:start",r),t.runId}mcpToolEnd(e){this.captureEventBase("cli:mcp:tool:end",e)}cliStart(e){this.runId=v4(),this.captureEvent("cli:start",e)}runCommand(e,t){this.captureEvent("cli:run",{commandName:e,...t})}getDistinctId(){return this.distinctId}getRunId(){return this.runId}getSessionId(){return this.sessionId}getProjectId(){return this.projectId}runTool(e,t,r){const n=String(e);this.captureEvent("cli:run",{commandName:"tool",toolName:n,params:t,...r})}toolStart(e){const t=`${e.toolName}:${this.runId}`;this.toolSessionMap.set(t,this.sessionId),this.captureEvent("cli:tool:start",e)}toolEnd(e){const t=`${e.toolName}:${this.runId}`,r=this.toolSessionMap.get(t);if(r){const n={...e,originalSessionId:r};this.captureEventBase("cli:tool:end",{source:"cli",runId:this.runId,sessionId:r,...n,timestamp:(new Date).toISOString()}),this.toolSessionMap.delete(t)
4826
- }else this.captureEvent("cli:tool:end",e)}cliEnd(e){this.captureEvent("cli:end",e),this.runId=null}cliError(e){this.captureEvent("cli:error",e)}runHelp(e){this.captureEvent("cli:run",{commandName:"help",...e})}tileSearch(e){this.captureEvent("cli:tile:search",e)}tileInstall(e){this.captureEvent("cli:tile:install",e)}registrySync(e){this.captureEvent("cli:registry:sync",e)}runVersion(e){this.captureEvent("cli:run",{commandName:"version",...e})}init(e){this.captureEvent("cli:project:init",e)}agentSetup(e){this.captureEvent("cli:agent:setup",e)}frameworkSetup(e){this.captureEvent("cli:framework:setup",e)}mcpSetup(e){this.captureEvent("cli:mcp:setup",e)}trackProjectGroup(e){this.shareUsageData&&this.posthog.groupIdentify({groupType:CLI_PROJECT_GROUP_TYPE,groupKey:e.projectId,properties:{isInitialized:e.isInitialized,$group_set_once:{firstSeenAt:e.firstSeenAt},lastEditedAt:(new Date).toISOString(),nodeVersion:this.nodeVersion,platform:this.platformInfo,arch:this.archInfo,
4827
- cliVersion:this.cliVersion,osType:this.osType,osRelease:this.osRelease}})}projectMetadata(e){this.captureEventBase("cli:project:metadata",e)}trackProject(e){const t={projectId:this.projectId,distinctId:this.distinctId,...e,nodeVersion:this.nodeVersion,platform:this.platformInfo,arch:this.archInfo,cliVersion:this.cliVersion,osType:this.osType,osRelease:this.osRelease,firstSeenAt:(new Date).toISOString(),lastEditedAt:(new Date).toISOString()};this.trackProjectGroup(t),this.projectMetadata(t)}}async function createPosthogAnalytics(e,t,r,n){return PosthogAnalytics.create(e,t,r,n)}async function _asyncNullishCoalesce(e,t){return null!=e?e:await t()}function _optionalChain(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}async function startMonitoring(e){
4828
- const t=getProvisionedEnvPath("production");if(fs__default.existsSync(t))try{validateEnv(cliMonitoringSchema,process.env)}catch(e){e instanceof Error?console.error(formatValidationError(e)):console.error("Failed to validate environment variables: please review the install instructions."),process.exit(FAILURE)}const r=getDefaultGlobalConfigDir(),n=new ConfigManager(join(r,GLOBAL_CONFIG_FILE_NAME),GlobalConfigSchema),{logger:i,logBus:s}=await constructLogger("cli",n),o=await _asyncNullishCoalesce(await n.get("shareUsageData"),async()=>!0);let a,c;try{a=(await readAuth(r)).user}catch(e){i.debug({err:e},"failed to read auth")}if(o&&process.env.LANGFUSE_PROXY_TOKEN){const[e,t]=process.env.LANGFUSE_PROXY_TOKEN.split(":");c=quietLangfuse({publicKey:e,secretKey:t,baseUrl:"https://42957.tessl.io/",flushAt:1,flushInterval:0})}else c=quietLangfuse();const u=new PostHog("phc_S8tHJaPxa5ORnP0RVyyTaJHeCcft6XMqfjx9ZlJWvkO",{host:process.env.POSTHOG_HOST||"https://app.posthog.com"})
4829
- ;"yes"===process.env.TESSL_DEBUG_MONITORING&&u.debug(!0);const l=userIdentifier(a);setOtelUser(a),u.identify({distinctId:l,properties:{...o?getSysinfo():{},email:a?a.email:void 0}}),a&&u.alias({distinctId:a.id,alias:loggedOutUserIdentifier()});const d=await createPosthogAnalytics(u,l,o,e);return{monitoring:{shareUsageData:o,user:a?{id:a.id,email:a.email}:void 0,langfuse:c,logger:i,logBus:s,reporter:new ReportEmitter,posthogCapture:(e,t)=>{(o||_optionalChain([t,"optionalAccess",e=>e.bypassOptOut]))&&u.capture({distinctId:l,event:e.event,properties:e.properties})},analytics:d,shutdown:async()=>{i.debug({},"Shutting down monitoring services");const e=async()=>new Promise((e,t)=>setTimeout(()=>t(new Error("Monitoring shutdown timed out")),2e3));try{await Promise.race([u.flush(),e()])}catch(e){i.error({err:e},"Failed to flush PostHog events")}try{await Promise.race([c.flushAsync(),e()]),i.debug({},"Successfully flushed Langfuse events")}catch(e){i.error({err:e
4830
- },"Failed to flush Langfuse events")}try{await flushLogger(i.originalLogger),i.debug({},"Successfully flushed logger")}catch(e){}}},globalConfig:n}}async function entry(){if(!await checkLegal())return 145;initSysinfo();const e=await checkDeprecationStatusWithCache();if(e)return console.error(e.message),console.error(e.installUrl),DEPRECATED_EXIT_CODE;const t=sessionData(),r=projectCache(),{monitoring:n,globalConfig:i}=await startMonitoring(r);try{return await withSpan("cli.entry",async()=>main(n,i,t,r))}catch(e){return n.logger.error({err:e},"critical error during startup"),n.analytics.cliError({command:process.argv.slice(2).join(" "),message:e instanceof Error?e.message:String(e),stack:e instanceof Error&&e.stack||"",expected:e instanceof ExpectedError}),144}finally{await n.shutdown(),await sdk.shutdown(),showCursor()}}entry().then(e=>{process.exit(e)}).catch(e=>{console.error("Error occurred during exit:",e),process.exit(1)});const execAsync=require$$1$7.promisify(require$$0$8.exec)
4831
- ;async function getMachineId$4(){try{const e=(await execAsync('ioreg -rd1 -c "IOPlatformExpertDevice"')).stdout.split("\n").find(e=>e.includes("IOPlatformUUID"));if(!e)return;const t=e.split('" = "');if(2===t.length)return t[1].slice(0,-1)}catch(e){diag.debug(`error reading machine id: ${e}`)}}var getMachineIdDarwin=Object.freeze({__proto__:null,getMachineId:getMachineId$4});async function getMachineId$3(){const e=["/etc/machine-id","/var/lib/dbus/machine-id"];for(const t of e)try{return(await promises.readFile(t,{encoding:"utf8"})).trim()}catch(e){diag.debug(`error reading machine id: ${e}`)}}var getMachineIdLinux=Object.freeze({__proto__:null,getMachineId:getMachineId$3});async function getMachineId$2(){try{return(await promises.readFile("/etc/hostid",{encoding:"utf8"})).trim()}catch(e){diag.debug(`error reading machine id: ${e}`)}try{return(await execAsync("kenv -q smbios.system.uuid")).stdout.trim()}catch(e){diag.debug(`error reading machine id: ${e}`)}}
4832
- var getMachineIdBsd=Object.freeze({__proto__:null,getMachineId:getMachineId$2});async function getMachineId$1(){let e="%windir%\\System32\\REG.exe";"ia32"===process$4.arch&&"PROCESSOR_ARCHITEW6432"in process$4.env&&(e="%windir%\\sysnative\\cmd.exe /c "+e);try{const t=(await execAsync(`${e} QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid`)).stdout.split("REG_SZ");if(2===t.length)return t[1].trim()}catch(e){diag.debug(`error reading machine id: ${e}`)}}var getMachineIdWin=Object.freeze({__proto__:null,getMachineId:getMachineId$1});async function getMachineId(){diag.debug("could not read machine-id: unsupported platform")}var getMachineIdUnsupported=Object.freeze({__proto__:null,getMachineId});const getToJsonSchemaFn$4=async()=>e=>e.toJsonSchema();var arktypeCGObzDh=Object.freeze({__proto__:null,getToJsonSchemaFn:getToJsonSchemaFn$4});const getToJsonSchemaFn$3=async()=>{const{JSONSchema:e}=await tryImport(import("effect"),"effect");return t=>e.make(t)}
4833
- ;var effect_Zg3C1LQ=Object.freeze({__proto__:null,getToJsonSchemaFn:getToJsonSchemaFn$3});const getToJsonSchemaFn$2=async()=>{const{toJSONSchema:e}=await tryImport(import("sury"),"sury");return t=>e(t)};var suryS6AklOc=Object.freeze({__proto__:null,getToJsonSchemaFn:getToJsonSchemaFn$2});const getToJsonSchemaFn$1=async()=>{const{toJsonSchema:e}=await tryImport(import("@valibot/to-json-schema"),"@valibot/to-json-schema");return t=>e(t)};var valibotDBCeetIe=Object.freeze({__proto__:null,getToJsonSchemaFn:getToJsonSchemaFn$1});const getToJsonSchemaFn=async()=>{let e=e=>{throw new Error(`xsschema: Missing zod v4 dependencies "zod". see ${missingDependenciesUrl}`)},t=e=>{throw new Error(`xsschema: Missing zod v3 dependencies "zod-to-json-schema". see ${missingDependenciesUrl}`)};try{const{toJSONSchema:t}=await Promise.resolve().then(function(){return index});e=t}catch(e){e instanceof Error&&console.error(e.message)}try{const{zodToJsonSchema:e}=await Promise.resolve().then(function(){
4834
- return index$1});t=e}catch(e){e instanceof Error&&console.error(e.message)}return async r=>"_zod"in r?e(r):t(r)};var zodBw_60DVU=Object.freeze({__proto__:null,getToJsonSchemaFn});export{entry};
4754
+ children:jsxRuntimeExports.jsx(Text,{children:a.help||a.description})}),jsxRuntimeExports.jsxs(Box,{flexDirection:"column",gap:1,children:[jsxRuntimeExports.jsx(Section,{title:"Tool parameters",children:jsxRuntimeExports.jsx(ToolParamFlags,{tool:a})}),jsxRuntimeExports.jsx(Section,{title:"Flags",children:jsxRuntimeExports.jsx(CommandFlags,{flags:r.flags})})]})]})})}const hiddenFlags=["model-client","model-params","model-temperature","model-reasoning-effort","skip-streaming"];function CommandFlags({flags:e}){return jsxRuntimeExports.jsx(Box,{flexDirection:"column",children:Object.entries(e).filter(([e,t])=>!hiddenFlags.includes(e)&&!t.hidden).map(([e,{short:t,type:r,description:n,defaultValue:i,availableValues:s}])=>jsxRuntimeExports.jsx(FlagRow,{long:e,short:t,type:getTypeString(r),description:n,defaultValue:i,availableValues:s},e))})}function ToolParamFlags({tool:e}){const t=schemaToFlags(e.paramsSchema,e.positionalParam);return jsxRuntimeExports.jsx(Box,{flexDirection:"column",
4755
+ children:t.map(({long:e,short:t,required:r,type:n,description:i,defaultValue:s,availableValues:o})=>jsxRuntimeExports.jsx(FlagRow,{long:e,short:t,type:n,required:r,description:i,defaultValue:s,availableValues:o},e))})}function _optionalChain$2(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}async function main(e,t,r,n){const i=performance$2.now(),{analytics:s}=e,o=validateBaseEnv(process.env);try{const a=arg(flagToSpec(GlobalFlags),{permissive:!0});if(a["--print-project-cache"])return process.stdout.write(`${getProjectCacheDir()}\n`),SUCCESS;s.cliStart({command:process.argv.slice(2).join(" "),flags:a,isInteractive:isInteractive$1()})
4756
+ ;const c=a["--global-config-dir"]||DEFAULT_TESSL_PATHS.globalConfigDir,u=a["--config-dir"]||DEFAULT_TESSL_PATHS.projDir,l=await getCreds(e.logger,o,c),d=null!==l;if(a["--version"]||a["-v"])return s.runVersion({method:"flag"}),await printVersion({logger:e.logger}),s.cliEnd({exitCode:SUCCESS,success:!0,durationMs:performance$2.now()-i,command:process.argv.slice(2).join(" ")}),SUCCESS;const p=a["--help"]||a["-h"]||!1;let[h,A,...f]=a._;_optionalChain$2([A,"optionalAccess",e=>e.startsWith,"call",e=>e("-")])&&(f.unshift(A),A=void 0),_optionalChain$2([h,"optionalAccess",e=>e.startsWith,"call",e=>e("-")])&&(f.unshift(h),h=void 0);const g=getExistingFrameworkType(u);if(!h)return render(jsxRuntimeExports.jsx(GlobalHelp,{isLoggedIn:d,frameworkType:g})),SUCCESS;if("update"!==h)try{await checkForUpdates(n)}catch(e){}if(p&&isValidActionName(h)&&!A)return s.runHelp({level:"command",command:h}),render(jsxRuntimeExports.jsx(ActionHelp,{action:h})),s.cliEnd({exitCode:SUCCESS,success:!0,
4757
+ durationMs:performance$2.now()-i,command:process.argv.slice(2).join(" ")}),SUCCESS;const m=getCommand(h,A);if(p){if(isBuiltInToolName(h)||"run"===h&&A&&isBuiltInToolName(A)){if(!d)throw new RequiresLoginError;const e=isBuiltInToolName(h)?h:A;s.runHelp({level:"tool",isAliased:e===h,isCustom:!1,toolName:h}),render(jsxRuntimeExports.jsx(RunToolHelp,{asAlias:!0,toolName:e,command:m}))}else if("run"===h){if(!d)throw new RequiresLoginError;render(jsxRuntimeExports.jsx(RunHelp,{command:m}))}else m?(s.runHelp({level:"command",command:h}),render(jsxRuntimeExports.jsx(CommandHelp,{command:m,action:h,resource:A}))):(s.runHelp({level:"global",method:"command"}),render(jsxRuntimeExports.jsx(GlobalHelp,{isLoggedIn:d,frameworkType:g})));return s.cliEnd({exitCode:SUCCESS,success:!0,durationMs:performance$2.now()-i,command:process.argv.slice(2).join(" ")}),SUCCESS}if(!isValidCommandName(h,A))throw new ExpectedError(`Invalid command '${h}${A?" "+A:""}'. Run 'tessl --help' to see available commands.`)
4758
+ ;if(!m)throw new ExpectedError("Command not found. Run 'tessl --help' to see available commands.");if(isValidStandaloneCommandName(h)&&A&&f.unshift(A),isBuiltInToolName(h)&&(A&&f.unshift(A),f.unshift(h)),m.requiresLogin&&!d)throw new RequiresLoginError;m.requiresConfig&&ensureNoTesslMd(u);const y=new ConfigManager(join(u,TESSL_CONFIG_FILE_NAME),ProjectConfigSchema,e.logger);m.requiresConfig&&await throwIfNotInitialised(u),await y.validate();try{await checkAndUpdateProjectMetadata({monitoring:e,projectCache:n,projectConfig:y,projectDir:u})}catch(t){e.logger.error({err:t},"Encountered an error while trying to track project metadata")}const E=getTesslClient(o,_optionalChain$2([l,"optionalAccess",e=>e.accessToken])),b=await m.handle({args:f,monitoring:e,projectConfig:y,globalConfig:t,projectDir:u,globalConfigDir:c,sessionData:r,env:o,isAuthenticated:d,user:_optionalChain$2([l,"optionalAccess",e=>e.user]),tesslClient:E});return s.cliEnd({exitCode:b,success:b===SUCCESS,
4759
+ durationMs:performance$2.now()-i,command:process.argv.slice(2).join(" ")}),b}catch(t){if(t instanceof ExitPromptError)return SUCCESS;if(t instanceof Error)return e.logger.error({err:t},t.message),isInteractive$1()&&logError$1(t),s.cliError({message:t.message,stack:t.stack||"",expected:t instanceof ExpectedError||t instanceof arg.ArgError,command:process.argv.slice(2).join(" ")}),s.cliEnd({exitCode:FAILURE,success:!1,durationMs:performance$2.now()-i,command:process.argv.slice(2).join(" ")}),FAILURE;throw t}}async function checkForUpdates(e){const t="version-notification-last-shown-at",r=await e.readText(t);try{if(!isInteractive$1()||isDevelopmentBuild())return;if(void 0!==r){const e=new Date(r).getTime(),t=(new Date).getTime();if(t-e<36e5)return}const n=getCurrentVersion(),i=await getLatestVersion();n!==i&&(await e.writeText(t,(new Date).toISOString()),printUpdateGuidance({latestVersion:i}))}catch(e){}}const DIGITS="0123456789abcdef";class UUID{constructor(e){this.bytes=e}
4760
+ static ofInner(e){if(16!==e.length)throw new TypeError("not 128-bit length");return new UUID(e)}static fromFieldsV7(e,t,r,n){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(n)||e<0||t<0||r<0||n<0||e>0xffffffffffff||t>4095||r>1073741823||n>4294967295)throw new RangeError("invalid field value");const i=new Uint8Array(16);return i[0]=e/2**40,i[1]=e/2**32,i[2]=e/2**24,i[3]=e/65536,i[4]=e/256,i[5]=e,i[6]=112|t>>>8,i[7]=t,i[8]=128|r>>>24,i[9]=r>>>16,i[10]=r>>>8,i[11]=r,i[12]=n>>>24,i[13]=n>>>16,i[14]=n>>>8,i[15]=n,new UUID(i)}static parse(e){let t;switch(e.length){case 32:t=/^[0-9a-f]{32}$/i.exec(e)?.[0];break;case 36:t=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;case 38:t=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e)?.slice(1,6).join("");break;case 45:
4761
+ t=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("")}if(t){const e=new Uint8Array(16);for(let r=0;r<16;r+=4){const n=parseInt(t.substring(2*r,2*r+8),16);e[r+0]=n>>>24,e[r+1]=n>>>16,e[r+2]=n>>>8,e[r+3]=n}return new UUID(e)}throw new SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)e+=DIGITS.charAt(this.bytes[t]>>>4),e+=DIGITS.charAt(15&this.bytes[t]),3!==t&&5!==t&&7!==t&&9!==t||(e+="-");return e}toHex(){let e="";for(let t=0;t<this.bytes.length;t++)e+=DIGITS.charAt(this.bytes[t]>>>4),e+=DIGITS.charAt(15&this.bytes[t]);return e}toJSON(){return this.toString()}getVariant(){const e=this.bytes[8]>>>4;if(e<0)throw new Error("unreachable");if(e<=7)return this.bytes.every(e=>0===e)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every(e=>255===e)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){
4762
+ return"VAR_10"===this.getVariant()?this.bytes[6]>>>4:void 0}clone(){return new UUID(this.bytes.slice(0))}equals(e){return 0===this.compareTo(e)}compareTo(e){for(let t=0;t<16;t++){const r=this.bytes[t]-e.bytes[t];if(0!==r)return Math.sign(r)}return 0}}class V7Generator{constructor(e){this.timestamp=0,this.counter=0,this.random=e??getDefaultRandom()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let r=this.generateOrAbortCore(e,t);return void 0===r&&(this.timestamp=0,r=this.generateOrAbortCore(e,t)),r}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;this.counter++,this.counter>4398046511103&&(this.timestamp++,
4763
+ this.resetCounter())}return UUID.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){const e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,UUID.ofInner(e)}}const getDefaultRandom=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())});let defaultGenerator;const uuidv7=()=>uuidv7obj().toString(),uuidv7obj=()=>(defaultGenerator||(defaultGenerator=new V7Generator)).generate();function makeUncaughtExceptionHandler(e,t){let r=!1;return Object.assign(n=>{const i=0===global.process.listeners("uncaughtException").filter(e=>"domainUncaughtExceptionClear"!==e.name&&!0!==e._posthogErrorHandler).length;e(n,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&i&&(r=!0,
4764
+ t())},{_posthogErrorHandler:!0})}function addUncaughtExceptionListener(e,t){global.process.on("uncaughtException",makeUncaughtExceptionHandler(e,t))}function addUnhandledRejectionListener(e){global.process.on("unhandledRejection",t=>{e(t,{mechanism:{type:"onunhandledrejection",handled:!1}})})}let parsedStackResults,lastKeysCount,cachedFilenameChunkIds;function getFilenameToChunkIdMap(e){const t=globalThis._posthogChunkIds;if(!t)return console.error("No chunk id map found"),{};const r=Object.keys(t);return cachedFilenameChunkIds&&r.length===lastKeysCount||(lastKeysCount=r.length,cachedFilenameChunkIds=r.reduce((r,n)=>{parsedStackResults||(parsedStackResults={});const i=parsedStackResults[n];if(i)r[i[0]]=i[1];else{const i=e(n);for(let e=i.length-1;e>=0;e--){const s=i[e],o=s?.filename,a=t[n];if(o&&a){r[o]=a,parsedStackResults[n]=[o,a];break}}}return r},{})),cachedFilenameChunkIds}function isEvent(e){return"undefined"!=typeof Event&&isInstanceOf(e,Event)}function isPlainObject(e){
4765
+ return isBuiltin(e,"Object")}function isError(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return isInstanceOf(e,Error)}}function isInstanceOf(e,t){try{return e instanceof t}catch{return!1}}function isErrorEvent(e){return isBuiltin(e,"ErrorEvent")}function isBuiltin(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}async function propertiesFromUnknownInput(e,t,r,n){const i=n&&n.mechanism||{handled:!0,type:"generic"},s=getErrorList(i,r,n),o=await Promise.all(s.map(async r=>{const n=await exceptionFromError(e,t,r);return n.value=n.value||"",n.type=n.type||"Error",n.mechanism=i,n}));return{$exception_list:o}}function getErrorList(e,t,r){const n=getError(e,t,r);return n.cause?[n,...getErrorList(e,n.cause,r)]:[n]}function getError(e,t,r){if(isError(t))return t;if(e.synthetic=!0,isPlainObject(t)){const e=getErrorPropertyFromObject(t);if(e)return e
4766
+ ;const n=getMessageForObject(t),i=r?.syntheticException||new Error(n);return i.message=n,i}const n=r?.syntheticException||new Error(t);return n.message=`${t}`,n}function getErrorPropertyFromObject(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)){const r=e[t];if(isError(r))return r}}function getMessageForObject(e){if("name"in e&&"string"==typeof e.name){let t=`'${e.name}' captured as exception`;return"message"in e&&"string"==typeof e.message&&(t+=` with message '${e.message}'`),t}if("message"in e&&"string"==typeof e.message)return e.message;const t=extractExceptionKeysForMessage(e);if(isErrorEvent(e))return`Event \`ErrorEvent\` captured as exception with message \`${e.message}\``;const r=getObjectClassName(e);return`${r&&"Object"!==r?`'${r}'`:"Object"} captured as exception with keys: ${t}`}function getObjectClassName(e){try{const t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(e){}}function extractExceptionKeysForMessage(e,t=40){
4767
+ const r=Object.keys(convertToPlainObject(e));r.sort();const n=r[0];if(!n)return"[object has no keys]";if(n.length>=t)return truncate(n,t);for(let e=r.length;e>0;e--){const n=r.slice(0,e).join(", ");if(!(n.length>t))return e===r.length?n:truncate(n,t)}return""}function truncate(e,t=0){return"string"!=typeof e||0===t||e.length<=t?e:`${e.slice(0,t)}...`}function convertToPlainObject(e){if(isError(e))return{message:e.message,name:e.name,stack:e.stack,...getOwnProperties(e)};if(isEvent(e)){return{type:e.type,target:serializeEventTarget(e.target),currentTarget:serializeEventTarget(e.currentTarget),...getOwnProperties(e)}}return e}function getOwnProperties(e){if("object"==typeof e&&null!==e){const t={};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t}return{}}function serializeEventTarget(e){try{return Object.prototype.toString.call(e)}catch(e){return"<unknown>"}}async function exceptionFromError(e,t,r){const n={type:r.name||r.constructor.name,value:r.message}
4768
+ ;let i=parseStackFrames(e,r);for(const e of t)i=await e(i);return i.length&&(n.stacktrace={frames:i,type:"raw"}),n}function parseStackFrames(e,t){return applyChunkIds(e(t.stack||"",1),e)}function applyChunkIds(e,t){const r=getFilenameToChunkIdMap(t);return e.forEach(e=>{e.filename&&(e.chunk_id=r[e.filename])}),e}const SHUTDOWN_TIMEOUT=2e3;class ErrorTracking{static async buildEventMessage(e,t,r,n){const i={...n};r||(i.$process_person_profile=!1);const s=await propertiesFromUnknownInput(this.stackParser,this.frameModifiers,e,t);return{event:"$exception",distinctId:r||uuidv7(),properties:{...s,...i}}}constructor(e,t){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this.startAutocaptureIfEnabled()}startAutocaptureIfEnabled(){this.isEnabled()&&(addUncaughtExceptionListener(this.onException.bind(this),this.onFatalError.bind(this)),addUnhandledRejectionListener(this.onException.bind(this)))}onException(e,t){ErrorTracking.buildEventMessage(e,t).then(e=>{
4769
+ this.client.capture(e)})}async onFatalError(){await this.client.shutdown(SHUTDOWN_TIMEOUT)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}}function createGetModuleFromFilename(e=(process.argv[1]?dirname(process.argv[1]):process.cwd()),t="\\"===sep$1){const r=t?normalizeWindowsPath(e):e;return e=>{if(!e)return;const n=t?normalizeWindowsPath(e):e;let{dir:i,base:s,ext:o}=posix$1.parse(n);".js"!==o&&".mjs"!==o&&".cjs"!==o||(s=s.slice(0,-1*o.length));const a=decodeURIComponent(s);i||(i=".");const c=i.lastIndexOf("/node_modules");if(c>-1)return`${i.slice(c+14).replace(/\//g,".")}:${a}`;if(i.startsWith(r)){const e=i.slice(r.length+1).replace(/\//g,".");return e?`${e}:${a}`:a}return a}}function normalizeWindowsPath(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}class ReduceableCache{constructor(e){this._maxSize=e,this._cache=new Map}get(e){const t=this._cache.get(e);if(void 0!==t)return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){
4770
+ this._cache.set(e,t)}reduce(){for(;this._cache.size>=this._maxSize;){const e=this._cache.keys().next().value;e&&this._cache.delete(e)}}}const LRU_FILE_CONTENTS_CACHE=new ReduceableCache(25),LRU_FILE_CONTENTS_FS_READ_FAILED=new ReduceableCache(20),DEFAULT_LINES_OF_CONTEXT=7,MAX_CONTEXTLINES_COLNO=1e3,MAX_CONTEXTLINES_LINENO=1e4;async function addSourceContext(e){const t={};for(let r=e.length-1;r>=0;r--){const n=e[r],i=n?.filename;if(!n||"string"!=typeof i||"number"!=typeof n.lineno||shouldSkipContextLinesForFile(i)||shouldSkipContextLinesForFrame(n))continue;t[i]||(t[i]=[]),t[i].push(n.lineno)}const r=Object.keys(t);if(0==r.length)return e;const n=[];for(const e of r){if(LRU_FILE_CONTENTS_FS_READ_FAILED.get(e))continue;const r=t[e];if(!r)continue;r.sort((e,t)=>e-t);const i=makeLineReaderRanges(r);if(i.every(t=>rangeExistsInContentCache(e,t)))continue;const s=emplace(LRU_FILE_CONTENTS_CACHE,e,{});n.push(getContextLinesFromFile(e,i,s))}return await Promise.all(n).catch(()=>{}),
4771
+ e&&e.length>0&&addSourceContextToFrames(e,LRU_FILE_CONTENTS_CACHE),LRU_FILE_CONTENTS_CACHE.reduce(),e}function getContextLinesFromFile(e,t,r){return new Promise(n=>{const i=createReadStream(e),s=createInterface$1({input:i});function o(){i.destroy(),n()}let a=0,c=0;const u=t[c];if(void 0===u)return void o();let l=u[0],d=u[1];function p(){LRU_FILE_CONTENTS_FS_READ_FAILED.set(e,1),s.close(),s.removeAllListeners(),o()}i.on("error",p),s.on("error",p),s.on("close",o),s.on("line",e=>{if(a++,!(a<l)&&(r[a]=snipLine(e,0),a>=d)){if(c===t.length-1)return s.close(),void s.removeAllListeners();c++;const e=t[c];if(void 0===e)return s.close(),void s.removeAllListeners();l=e[0],d=e[1]}})})}function addSourceContextToFrames(e,t){for(const r of e)if(r.filename&&void 0===r.context_line&&"number"==typeof r.lineno){const e=t.get(r.filename);if(void 0===e)continue;addContextToFrame(r.lineno,r,e)}}function addContextToFrame(e,t,r){if(void 0===t.lineno||void 0===r)return;t.pre_context=[]
4772
+ ;for(let n=makeRangeStart(e);n<e;n++){const e=r[n];if(void 0===e)return void clearLineContext(t);t.pre_context.push(e)}if(void 0===r[e])return void clearLineContext(t);t.context_line=r[e];const n=makeRangeEnd(e);t.post_context=[];for(let i=e+1;i<=n;i++){const e=r[i];if(void 0===e)break;t.post_context.push(e)}}function clearLineContext(e){delete e.pre_context,delete e.context_line,delete e.post_context}function shouldSkipContextLinesForFile(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function shouldSkipContextLinesForFrame(e){return void 0!==e.lineno&&e.lineno>MAX_CONTEXTLINES_LINENO||void 0!==e.colno&&e.colno>MAX_CONTEXTLINES_COLNO}function rangeExistsInContentCache(e,t){const r=LRU_FILE_CONTENTS_CACHE.get(e);if(void 0===r)return!1;for(let e=t[0];e<=t[1];e++)if(void 0===r[e])return!1;return!0}function makeLineReaderRanges(e){if(!e.length)return[];let t=0;const r=e[0];if("number"!=typeof r)return[]
4773
+ ;let n=makeContextRange(r);const i=[];for(;;){if(t===e.length-1){i.push(n);break}const r=e[t+1];if("number"!=typeof r)break;r<=n[1]?n[1]=r+DEFAULT_LINES_OF_CONTEXT:(i.push(n),n=makeContextRange(r)),t++}return i}function makeContextRange(e){return[makeRangeStart(e),makeRangeEnd(e)]}function makeRangeStart(e){return Math.max(1,e-DEFAULT_LINES_OF_CONTEXT)}function makeRangeEnd(e){return e+DEFAULT_LINES_OF_CONTEXT}function emplace(e,t,r){const n=e.get(t);return void 0===n?(e.set(t,r),r):n}function snipLine(e,t){let r=e;const n=r.length;if(n<=150)return r;t>n&&(t=n);let i=Math.max(t-60,0);i<5&&(i=0);let s=Math.min(i+140,n);return s>n-5&&(s=n),s===n&&(i=Math.max(s-140,0)),r=r.slice(i,s),i>0&&(r=`...${r}`),s<n&&(r+="..."),r}var version="5.3.1",PostHogPersistedProperty,Compression,SurveyPosition,SurveyWidgetType,SurveyType,SurveyQuestionDescriptionContentType,SurveyRatingDisplay,SurveyQuestionType,SurveyQuestionBranchingType,SurveyMatchType,ActionStepStringMatching;!function(e){
4774
+ e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.FeatureFlagDetails="feature_flag_details",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",e.BootstrapFeatureFlags="bootstrap_feature_flags",e.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionStartTimestamp="session_start_timestamp",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit"
4775
+ }(PostHogPersistedProperty||(PostHogPersistedProperty={})),function(e){e.GZipJS="gzip-js",e.Base64="base64"}(Compression||(Compression={})),function(e){e.TopLeft="top_left",e.TopCenter="top_center",e.TopRight="top_right",e.MiddleLeft="middle_left",e.MiddleCenter="middle_center",e.MiddleRight="middle_right",e.Left="left",e.Right="right",e.Center="center"}(SurveyPosition||(SurveyPosition={})),function(e){e.Button="button",e.Tab="tab",e.Selector="selector"}(SurveyWidgetType||(SurveyWidgetType={})),function(e){e.Popover="popover",e.API="api",e.Widget="widget"}(SurveyType||(SurveyType={})),function(e){e.Html="html",e.Text="text"}(SurveyQuestionDescriptionContentType||(SurveyQuestionDescriptionContentType={})),function(e){e.Number="number",e.Emoji="emoji"}(SurveyRatingDisplay||(SurveyRatingDisplay={})),function(e){e.Open="open",e.MultipleChoice="multiple_choice",e.SingleChoice="single_choice",e.Rating="rating",e.Link="link"}(SurveyQuestionType||(SurveyQuestionType={})),function(e){
4776
+ e.NextQuestion="next_question",e.End="end",e.ResponseBased="response_based",e.SpecificQuestion="specific_question"}(SurveyQuestionBranchingType||(SurveyQuestionBranchingType={})),function(e){e.Regex="regex",e.NotRegex="not_regex",e.Exact="exact",e.IsNot="is_not",e.Icontains="icontains",e.NotIcontains="not_icontains"}(SurveyMatchType||(SurveyMatchType={})),function(e){e.Contains="contains",e.Exact="exact",e.Regex="regex"}(ActionStepStringMatching||(ActionStepStringMatching={}));const normalizeFlagsResponse=e=>{if("flags"in e){const t=getFlagValuesFromFlags(e.flags),r=getPayloadsFromFlags(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{const t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([e,t])=>[e,parsePayload(t)])),n=Object.fromEntries(Object.entries(t).map(([e,t])=>[e,getFlagDetailFromFlagAndPayload(e,t,r[e])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:n}}};function getFlagDetailFromFlagAndPayload(e,t,r){return{key:e,
4777
+ enabled:"string"==typeof t||t,variant:"string"==typeof t?t:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:r?JSON.stringify(r):void 0,description:void 0}}}const getFlagValuesFromFlags=e=>Object.fromEntries(Object.entries(e??{}).map(([e,t])=>[e,getFeatureFlagValue(t)]).filter(([,e])=>void 0!==e)),getPayloadsFromFlags=e=>{const t=e??{};return Object.fromEntries(Object.keys(t).filter(e=>{const r=t[e];return r.enabled&&r.metadata&&void 0!==r.metadata.payload}).map(e=>{const r=t[e].metadata?.payload;return[e,r?parsePayload(r):void 0]}))},getFeatureFlagValue=e=>void 0===e?void 0:e.variant??e.enabled,parsePayload=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return e}},STRING_FORMAT="utf8";function assert(e,t){if(!e||"string"!=typeof e||isEmpty(e))throw new Error(t)}function isEmpty(e){return 0===e.trim().length}function removeTrailingSlash(e){return e?.replace(/\/+$/,"")}async function retriable(e,t){let r=null;for(let n=0;n<t.retryCount+1;n++){
4778
+ n>0&&await new Promise(e=>setTimeout(e,t.retryDelay));try{return await e()}catch(e){if(r=e,!t.retryCheck(e))throw e}}throw r}function currentISOTime(){return(new Date).toISOString()}function safeSetTimeout(e,t){const r=setTimeout(e,t);return r?.unref&&r?.unref(),r}function allSettled(e){return Promise.all(e.map(e=>(e??Promise.resolve()).then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e}))))}function isGzipSupported(){return"CompressionStream"in globalThis}async function gzipCompress(e,t=!0){try{const t=new Blob([e],{type:"text/plain"}).stream().pipeThrough(new CompressionStream("gzip"));return await new Response(t).blob()}catch(e){return t&&console.error("Failed to gzip compress data",e),null}}class SimpleEventEmitter{constructor(){this.events={},this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.events[e]=this.events[e].filter(e=>e!==t)}}emit(e,t){for(const r of this.events[e]||[])r(t)
4779
+ ;for(const r of this.events["*"]||[])r(e,t)}}class PostHogFetchHttpError extends Error{constructor(e,t){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+t),this.response=e,this.reqByteLength=t,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}}class PostHogFetchNetworkError extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}async function logFlushError(e){if(e instanceof PostHogFetchHttpError){let t="";try{t=await e.text}catch{}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error("Error while flushing PostHog",e);return Promise.resolve()}function isPostHogFetchError(e){return"object"==typeof e&&(e instanceof PostHogFetchHttpError||e instanceof PostHogFetchNetworkError)}
4780
+ function isPostHogFetchContentTooLargeError(e){return"object"==typeof e&&e instanceof PostHogFetchHttpError&&413===e.status}var QuotaLimitedFeature;!function(e){e.FeatureFlags="feature_flags",e.Recordings="recordings"}(QuotaLimitedFeature||(QuotaLimitedFeature={}));class PostHogCoreStateless{constructor(e,t){this.flushPromise=null,this.shutdownPromise=null,this.pendingPromises={},this._events=new SimpleEventEmitter,this._isInitialized=!1,assert(e,"You must pass your PostHog project's api key."),this.apiKey=e,this.host=removeTrailingSlash(t?.host||"https://us.i.posthog.com"),this.flushAt=t?.flushAt?Math.max(t?.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,t?.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,t?.maxQueueSize??1e3),this.flushInterval=t?.flushInterval??1e4,this.preloadFeatureFlags=t?.preloadFeatureFlags??!0,this.defaultOptIn=t?.defaultOptIn??!0,this.disableSurveys=t?.disableSurveys??!1,this._retryOptions={retryCount:t?.fetchRetryCount??3,
4781
+ retryDelay:t?.fetchRetryDelay??3e3,retryCheck:isPostHogFetchError},this.requestTimeout=t?.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t?.featureFlagsRequestTimeoutMs??3e3,this.remoteConfigRequestTimeoutMs=t?.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=t?.disableGeoip??!0,this.disabled=t?.disabled??!1,this.historicalMigration=t?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.disableCompression=!isGzipSupported()||(t?.disableCompression??!1)}logMsgIfDebug(e){this.isDebug&&e()}wrap(e){if(!this.disabled)return this._isInitialized?e():void this._initPromise.then(()=>e());this.logMsgIfDebug(()=>console.warn("[PostHog] The client is disabled"))}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(PostHogPersistedProperty.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(PostHogPersistedProperty.OptedOut,!1)})
4782
+ }async optOut(){this.wrap(()=>{this.setPersistedProperty(PostHogPersistedProperty.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){const e=this.on("*",(e,t)=>console.log("PostHog Debug",e,t));this.removeDebugCallback=()=>{e(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){return{distinct_id:e.distinct_id,event:e.event,properties:{...e.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(e){const t=uuidv7();return this.pendingPromises[t]=e,e.catch(()=>{}).finally(()=>{delete this.pendingPromises[t]}),e}identifyStateless(e,t,r){this.wrap(()=>{const n={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",n,r)})}async identifyStatelessImmediate(e,t,r){const n={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",n,r)}captureStateless(e,t,r,n){
4783
+ this.wrap(()=>{const i=this.buildPayload({distinct_id:e,event:t,properties:r});this.enqueue("capture",i,n)})}async captureStatelessImmediate(e,t,r,n){const i=this.buildPayload({distinct_id:e,event:t,properties:r});await this.sendImmediate("capture",i,n)}aliasStateless(e,t,r,n){this.wrap(()=>{const i=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});this.enqueue("alias",i,n)})}async aliasStatelessImmediate(e,t,r,n){const i=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",i,n)}groupIdentifyStateless(e,t,r,n,i,s){this.wrap(()=>{const o=this.buildPayload({distinct_id:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...s||{}}});this.enqueue("capture",o,n)})}async getRemoteConfig(){await this._initPromise;let e=this.host
4784
+ ;"https://us.i.posthog.com"===e?e="https://us-assets.i.posthog.com":"https://eu.i.posthog.com"===e&&(e="https://eu-assets.i.posthog.com");const t=`${e}/array/${this.apiKey}/config`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,r,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(e=>e.json()).catch(e=>{this.logMsgIfDebug(()=>console.error("Remote config could not be loaded",e)),this._events.emit("error",e)})}async getFlags(e,t={},r={},n={},i={}){await this._initPromise;const s=`${this.host}/flags/?v=2&config=true`,o={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify({token:this.apiKey,distinct_id:e,groups:t,person_properties:r,group_properties:n,...i})};return this.logMsgIfDebug(()=>console.log("PostHog Debug","Flags URL",s)),this.fetchWithRetry(s,o,{retryCount:0
4785
+ },this.featureFlagsRequestTimeoutMs).then(e=>e.json()).then(e=>normalizeFlagsResponse(e)).catch(e=>{this._events.emit("error",e)})}async getFeatureFlagStateless(e,t,r={},n={},i={},s){await this._initPromise;const o=await this.getFeatureFlagDetailStateless(e,t,r,n,i,s);if(void 0===o)return{response:void 0,requestId:void 0};let a=getFeatureFlagValue(o.response);return void 0===a&&(a=!1),{response:a,requestId:o.requestId}}async getFeatureFlagDetailStateless(e,t,r={},n={},i={},s){await this._initPromise;const o=await this.getFeatureFlagDetailsStateless(t,r,n,i,s,[e]);if(void 0===o)return;return{response:o.flags[e],requestId:o.requestId}}async getFeatureFlagPayloadStateless(e,t,r={},n={},i={},s){await this._initPromise;const o=await this.getFeatureFlagPayloadsStateless(t,r,n,i,s,[e]);if(!o)return;const a=o[e];return void 0===a?null:a}async getFeatureFlagPayloadsStateless(e,t={},r={},n={},i,s){await this._initPromise
4786
+ ;return(await this.getFeatureFlagsAndPayloadsStateless(e,t,r,n,i,s)).payloads}async getFeatureFlagsStateless(e,t={},r={},n={},i,s){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,r,n,i,s)}async getFeatureFlagsAndPayloadsStateless(e,t={},r={},n={},i,s){await this._initPromise;const o=await this.getFeatureFlagDetailsStateless(e,t,r,n,i,s);return o?{flags:o.featureFlags,payloads:o.featureFlagPayloads,requestId:o.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(e,t={},r={},n={},i,s){await this._initPromise;const o={};(i??this.disableGeoip)&&(o.geoip_disable=!0),s&&(o.flag_keys_to_evaluate=s);const a=await this.getFlags(e,t,r,n,o);if(void 0!==a)return a.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),
4787
+ a.quotaLimited?.includes(QuotaLimitedFeature.FeatureFlags)?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:a?.requestId}):a}async getSurveysStateless(){if(await this._initPromise,!0===this.disableSurveys)return this.logMsgIfDebug(()=>console.log("PostHog Debug","Loading surveys is disabled.")),[];const e=`${this.host}/api/surveys/?token=${this.apiKey}`,t={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},r=await this.fetchWithRetry(e,t).then(e=>{if(200!==e.status||!e.json){const t=`Surveys API could not be loaded: ${e.status}`,r=new Error(t);return this.logMsgIfDebug(()=>console.error(r)),void this._events.emit("error",new Error(t))}return e.json()}).catch(e=>{this.logMsgIfDebug(()=>console.error("Surveys API could not be loaded",e)),this._events.emit("error",e)
4788
+ }),n=r?.surveys;return n&&this.logMsgIfDebug(()=>console.log("PostHog Debug","Surveys fetched from API: ",JSON.stringify(n))),n??[]}get props(){return this._props||(this._props=this.getPersistedProperty(PostHogPersistedProperty.Props)),this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(PostHogPersistedProperty.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(PostHogPersistedProperty.Props,this.props)})}enqueue(e,t,r){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");const n=this.prepareMessage(e,t,r),i=this.getPersistedProperty(PostHogPersistedProperty.Queue)||[];i.length>=this.maxQueueSize&&(i.shift(),this.logMsgIfDebug(()=>console.info("Queue is full, the oldest event is dropped."))),i.push({message:n}),
4789
+ this.setPersistedProperty(PostHogPersistedProperty.Queue,i),this._events.emit(e,n),i.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=safeSetTimeout(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(e,t,r){if(this.disabled)return void this.logMsgIfDebug(()=>console.warn("[PostHog] The client is disabled"));if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");const n={api_key:this.apiKey,batch:[this.prepareMessage(e,t,r)],sent_at:currentISOTime()};this.historicalMigration&&(n.historical_migration=!0);const i=JSON.stringify(n),s=`${this.host}/batch/`,o=this.disableCompression?null:await gzipCompress(i,this.isDebug),a={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==o&&{"Content-Encoding":"gzip"}},body:o||i};try{await this.fetchWithRetry(s,a)}catch(e){
4790
+ this._events.emit("error",e)}}prepareMessage(e,t,r){const n={...t,type:e,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:r?.timestamp?r?.timestamp:currentISOTime(),uuid:r?.uuid?r.uuid:uuidv7()};return(r?.disableGeoip??this.disableGeoip)&&(n.properties||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId),n}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.flush().catch(async e=>{await logFlushError(e)})}async flush(){const e=allSettled([this.flushPromise]).then(()=>this._flush());return this.flushPromise=e,this.addPendingPromise(e),allSettled([e]).then(()=>{this.flushPromise===e&&(this.flushPromise=null)}),e}getCustomHeaders(){const e=this.getCustomUserAgent(),t={};return e&&""!==e&&(t["User-Agent"]=e),t}async _flush(){this.clearFlushTimer(),await this._initPromise;let e=this.getPersistedProperty(PostHogPersistedProperty.Queue)||[]
4791
+ ;if(!e.length)return;const t=[],r=e.length;for(;e.length>0&&t.length<r;){const r=e.slice(0,this.maxBatchSize),n=r.map(e=>e.message),i=()=>{const t=(this.getPersistedProperty(PostHogPersistedProperty.Queue)||[]).slice(r.length);this.setPersistedProperty(PostHogPersistedProperty.Queue,t),e=t},s={api_key:this.apiKey,batch:n,sent_at:currentISOTime()};this.historicalMigration&&(s.historical_migration=!0);const o=JSON.stringify(s),a=`${this.host}/batch/`,c=this.disableCompression?null:await gzipCompress(o,this.isDebug),u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==c&&{"Content-Encoding":"gzip"}},body:c||o},l={retryCheck:e=>!isPostHogFetchContentTooLargeError(e)&&isPostHogFetchError(e)};try{await this.fetchWithRetry(a,u,l)}catch(e){if(isPostHogFetchContentTooLargeError(e)&&n.length>1){this.maxBatchSize=Math.max(1,Math.floor(n.length/2)),
4792
+ this.logMsgIfDebug(()=>console.warn(`Received 413 when sending batch of size ${n.length}, reducing batch size to ${this.maxBatchSize}`));continue}throw e instanceof PostHogFetchNetworkError||i(),this._events.emit("error",e),e}i(),t.push(...n)}this._events.emit("flush",t)}async fetchWithRetry(e,t,r,n){var i;(i=AbortSignal).timeout??(i.timeout=function(e){const t=new AbortController;return setTimeout(()=>t.abort(),e),t.signal});const s=t.body?t.body:"";let o=-1;try{o=s instanceof Blob?s.size:Buffer.byteLength(s,STRING_FORMAT)}catch{if(s instanceof Blob)o=s.size;else{const e=(new TextEncoder).encode(s);o=e.length}}return await retriable(async()=>{let r=null;try{r=await this.fetch(e,{signal:AbortSignal.timeout(n??this.requestTimeout),...t})}catch(e){throw new PostHogFetchNetworkError(e)}if(!("no-cors"===t.mode)&&(r.status<200||r.status>=400))throw new PostHogFetchHttpError(r,o);return r},{...this._retryOptions,...r})}async _shutdown(e=3e4){await this._initPromise;let t=!1
4793
+ ;this.clearFlushTimer();return Promise.race([new Promise((r,n)=>{safeSetTimeout(()=>{this.logMsgIfDebug(()=>console.error("Timed out while shutting down PostHog")),t=!0,n("Timeout while shutting down PostHog. Some events may not have been sent.")},e)}),(async()=>{try{for(await Promise.all(Object.values(this.pendingPromises));;){if(0===(this.getPersistedProperty(PostHogPersistedProperty.Queue)||[]).length)break;if(await this.flush(),t)break}}catch(e){if(!isPostHogFetchError(e))throw e;await logFlushError(e)}})()])}async shutdown(e=3e4){return this.shutdownPromise?this.logMsgIfDebug(()=>console.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup")):this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}}class Lazy{constructor(e){this.factory=e}async getValue(){
4794
+ return void 0!==this.value?this.value:(void 0===this.initializationPromise&&(this.initializationPromise=(async()=>{try{const e=await this.factory();return this.value=e,e}finally{this.initializationPromise=void 0}})()),this.initializationPromise)}isInitialized(){return void 0!==this.value}async waitForInitialization(){this.isInitialized()||await this.getValue()}}const nodeCrypto=new Lazy(async()=>{try{return await import("crypto")}catch{return}});async function getNodeCrypto(){return await nodeCrypto.getValue()}const webCrypto=new Lazy(async()=>{if(void 0!==globalThis.crypto?.subtle)return globalThis.crypto.subtle;try{const e=await nodeCrypto.getValue();if(e?.webcrypto?.subtle)return e.webcrypto.subtle}catch{}});async function getWebCrypto(){return await webCrypto.getValue()}async function hashSHA1(e){const t=await getNodeCrypto();if(t)return t.createHash("sha1").update(e).digest("hex");const r=await getWebCrypto();if(r){const t=await r.digest("SHA-1",(new TextEncoder).encode(e))
4795
+ ;return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,"0")).join("")}throw new Error("No crypto implementation available. Tried Node Crypto API and Web SubtleCrypto API")}const SIXTY_SECONDS=6e4,LONG_SCALE=0x1000000000000000,NULL_VALUES_ALLOWED_OPERATORS=["is_not"];class ClientError extends Error{constructor(e){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,ClientError.prototype)}}class InconclusiveMatchError extends Error{constructor(e){super(e),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,InconclusiveMatchError.prototype)}}class FeatureFlagsPoller{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:r,timeout:n,host:i,customHeaders:s,...o}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},
4796
+ this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=n,this.projectApiKey=r,this.host=i,this.poller=void 0,this.fetch=o.fetch||fetch,this.onError=o.onError,this.customHeaders=s,this.onLoad=o.onLoad,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){this.debugMode&&e()}async getFeatureFlag(e,t,r={},n={},i={}){let s,o;if(await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return s;for(const t of this.featureFlags)if(e===t.key){o=t;break}if(void 0!==o)try{s=await this.computeFlagLocally(o,t,r,n,i),this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${s}`))}catch(t){t instanceof InconclusiveMatchError?this.logMsgIfDebug(()=>console.debug(`InconclusiveMatchError when computing flag locally: ${e}: ${t}`)):t instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${e}: ${t}`))}return s}async computeFeatureFlagPayloadLocally(e,t){let r;if(await this.loadFeatureFlags(),
4797
+ this.loadedSuccessfullyOnce){if("boolean"==typeof t?r=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t.toString()]:"string"==typeof t&&(r=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t]),null==r)return null;try{return JSON.parse(r)}catch{return r}}}async getAllFlagsAndPayloads(e,t={},r={},n={}){await this.loadFeatureFlags();const i={},s={};let o=0==this.featureFlags.length;return await Promise.all(this.featureFlags.map(async a=>{try{const o=await this.computeFlagLocally(a,e,t,r,n);i[a.key]=o;const c=await this.computeFeatureFlagPayloadLocally(a.key,o);c&&(s[a.key]=c)}catch(e){e instanceof InconclusiveMatchError||e instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${a.key}: ${e}`)),o=!0}})),{response:i,payloads:s,fallbackToFlags:o}}async computeFlagLocally(e,t,r={},n={},i={}){if(e.ensure_experience_continuity)throw new InconclusiveMatchError("Flag has experience continuity enabled");if(!e.active)return!1;const s=(e.filters||{}).aggregation_group_type_index
4798
+ ;if(null!=s){const t=this.groupTypeMapping[String(s)];if(!t)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${s} for feature flag ${e.key}`)),new InconclusiveMatchError("Flag has unknown group type index");if(!(t in r))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;const n=i[t];return await this.matchFeatureFlagProperties(e,r[t],n)}return await this.matchFeatureFlagProperties(e,t,n)}async matchFeatureFlagProperties(e,t,r){const n=e.filters||{};let i,s=!1;const o=[...n.groups||[]].sort((e,t)=>{const r=!!e.variant,n=!!t.variant;return r&&n?0:r?-1:n?1:0});for(const a of o)try{if(await this.isConditionMatch(e,t,a,r)){const r=a.variant,s=n.multivariate?.variants||[];i=r&&s.some(e=>e.key===r)?r:await this.getMatchingVariant(e,t)||!0;break}}catch(e){if(!(e instanceof InconclusiveMatchError))throw e;s=!0}if(void 0!==i)return i
4799
+ ;if(s)throw new InconclusiveMatchError("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,t,r,n){const i=r.rollout_percentage,s=e=>{this.logMsgIfDebug(()=>console.warn(e))};if((r.properties||[]).length>0){for(const e of r.properties){let t=!1;if(t="cohort"===e.type?matchCohort(e,n,this.cohorts,this.debugMode):matchProperty(e,n,s),!t)return!1}if(null==i)return!0}return!(null!=i&&await _hash(e.key,t)>i/100)}async getMatchingVariant(e,t){const r=await _hash(e.key,t,"variant"),n=this.variantLookupTable(e).find(e=>r>=e.valueMin&&r<e.valueMax);if(n)return n.key}variantLookupTable(e){const t=[];let r=0,n=0;const i=e.filters||{};return(i.multivariate?.variants||[]).forEach(e=>{n=r+e.rollout_percentage/100,t.push({valueMin:r,valueMax:n,key:e.key}),r=n}),t}async loadFeatureFlags(e=!1){this.loadedSuccessfullyOnce&&!e||await this._loadFeatureFlags()}isLocalEvaluationReady(){
4800
+ return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(SIXTY_SECONDS,this.pollingInterval*2**this.backOffCount):this.pollingInterval}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this._loadFeatureFlags(),this.getPollingInterval());try{const e=await this._requestFeatureFlagDefinitions();if(!e)return;switch(e.status){case 401:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new ClientError(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:return console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},
4801
+ this.groupTypeMapping={},void(this.cohorts={});case 403:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new ClientError(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,new ClientError(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{const t=await e.json()??{};if(!("flags"in t))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(t)}`));this.featureFlags=t.flags??[],this.featureFlagsByKey=this.featureFlags.reduce((e,t)=>(e[t.key]=t,e),{}),this.groupTypeMapping=t.group_type_mapping||{},
4802
+ this.cohorts=t.cohorts||{},this.loadedSuccessfullyOnce=!0,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.onLoad?.(this.featureFlags.length);break}default:return}}catch(e){e instanceof ClientError&&this.onError?.(e)}}getPersonalApiKeyRequestOptions(e="GET"){return{method:e,headers:{...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`}}}async _requestFeatureFlagDefinitions(){const e=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions();let r=null;if(this.timeout&&"number"==typeof this.timeout){const e=new AbortController;r=safeSetTimeout(()=>{e.abort()},this.timeout),t.signal=e.signal}try{return await this.fetch(e,t)}finally{clearTimeout(r)}}stopPoller(){clearTimeout(this.poller)}}async function _hash(e,t,r=""){const n=await hashSHA1(`${e}.${t}${r}`);return parseInt(n.slice(0,15),16)/LONG_SCALE}function matchProperty(e,t,r){
4803
+ const n=e.key,i=e.value,s=e.operator||"exact";if(!(n in t))throw new InconclusiveMatchError(`Property ${n} not found in propertyValues`);if("is_not_set"===s)throw new InconclusiveMatchError("Operator is_not_set is not supported");const o=t[n];if(null==o&&!NULL_VALUES_ALLOWED_OPERATORS.includes(s))return r&&r(`Property ${n} cannot have a value of null/undefined with the ${s} operator`),!1;function a(e,t){return Array.isArray(e)?e.map(e=>String(e).toLowerCase()).includes(String(t).toLowerCase()):String(e).toLowerCase()===String(t).toLowerCase()}function c(e,t,r){if("gt"===r)return e>t;if("gte"===r)return e>=t;if("lt"===r)return e<t;if("lte"===r)return e<=t;throw new Error(`Invalid operator: ${r}`)}switch(s){case"exact":return a(i,o);case"is_not":return!a(i,o);case"is_set":return n in t;case"icontains":return String(o).toLowerCase().includes(String(i).toLowerCase());case"not_icontains":return!String(o).toLowerCase().includes(String(i).toLowerCase());case"regex":
4804
+ return isValidRegex(String(i))&&null!==String(o).match(String(i));case"not_regex":return isValidRegex(String(i))&&null===String(o).match(String(i));case"gt":case"gte":case"lt":case"lte":{let e="number"==typeof i?i:null;if("string"==typeof i)try{e=parseFloat(i)}catch(e){}return null!=e&&null!=o?c(o,"string"==typeof o?String(i):e,s):c(String(o),String(i),s)}case"is_date_after":case"is_date_before":{let e=relativeDateParseForFeatureFlagMatching(String(i));if(null==e&&(e=convertToDateTime(i)),null==e)throw new InconclusiveMatchError(`Invalid date: ${i}`);const t=convertToDateTime(o);return["is_date_before"].includes(s)?t<e:t>e}default:throw new InconclusiveMatchError(`Unknown operator: ${s}`)}}function matchCohort(e,t,r,n=!1){const i=String(e.value);if(!(i in r))throw new InconclusiveMatchError("can't match cohort without a given cohort property value");return matchPropertyGroup(r[i],t,r,n)}function matchPropertyGroup(e,t,r,n=!1){if(!e)return!0;const i=e.type,s=e.values
4805
+ ;if(!s||0===s.length)return!0;let o=!1;if("values"in s[0]){for(const e of s)try{const s=matchPropertyGroup(e,t,r,n);if("AND"===i){if(!s)return!1}else if(s)return!0}catch(t){if(!(t instanceof InconclusiveMatchError))throw t;n&&console.debug(`Failed to compute property ${e} locally: ${t}`),o=!0}if(o)throw new InconclusiveMatchError("Can't match cohort without a given cohort property value");return"AND"===i}for(const e of s)try{let s;s="cohort"===e.type?matchCohort(e,t,r,n):matchProperty(e,t);const o=e.negation||!1;if("AND"===i){if(!s&&!o)return!1;if(s&&o)return!1}else{if(s&&!o)return!0;if(!s&&o)return!0}}catch(t){if(!(t instanceof InconclusiveMatchError))throw t;n&&console.debug(`Failed to compute property ${e} locally: ${t}`),o=!0}if(o)throw new InconclusiveMatchError("can't match cohort without a given cohort property value");return"AND"===i}function isValidRegex(e){try{return new RegExp(e),!0}catch(e){return!1}}function convertToDateTime(e){if(e instanceof Date)return e
4806
+ ;if("string"==typeof e||"number"==typeof e){const t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new InconclusiveMatchError(`${e} is in an invalid date format`)}throw new InconclusiveMatchError(`The date provided ${e} must be a string, number, or date object`)}function relativeDateParseForFeatureFlagMatching(e){const t=e.match(/^-?(?<number>[0-9]+)(?<interval>[a-z])$/),r=new Date((new Date).toISOString());if(t){if(!t.groups)return null;const e=parseInt(t.groups.number);if(e>=1e4)return null;const n=t.groups.interval;if("h"==n)r.setUTCHours(r.getUTCHours()-e);else if("d"==n)r.setUTCDate(r.getUTCDate()-e);else if("w"==n)r.setUTCDate(r.getUTCDate()-7*e);else if("m"==n)r.setUTCMonth(r.getUTCMonth()-e);else{if("y"!=n)return null;r.setUTCFullYear(r.getUTCFullYear()-e)}return r}return null}class PostHogMemoryStorage{constructor(){this._memoryStorage={}}getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=null!==t?t:void 0}}
4807
+ const MINIMUM_POLLING_INTERVAL=100,THIRTY_SECONDS=3e4,MAX_CACHE_SIZE=5e4;class PostHogBackendClient extends PostHogCoreStateless{constructor(e,t={}){if(super(e,t),this._memoryStorage=new PostHogMemoryStorage,this.options=t,this.options.featureFlagsPollingInterval="number"==typeof t.featureFlagsPollingInterval?Math.max(t.featureFlagsPollingInterval,MINIMUM_POLLING_INTERVAL):THIRTY_SECONDS,t.personalApiKey){if(t.personalApiKey.includes("phc_"))throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');!1!==t.enableLocalEvaluation&&(this.featureFlagsPoller=new FeatureFlagsPoller({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:t.personalApiKey,projectApiKey:e,timeout:t.requestTimeout??1e4,host:this.host,fetch:t.fetch,onError:e=>{this._events.emit("error",e)},onLoad:e=>{this._events.emit("localEvaluationFlagsLoaded",e)},customHeaders:this.getCustomHeaders()}))}
4808
+ this.errorTracking=new ErrorTracking(this,t),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=t.maxCacheSize||MAX_CACHE_SIZE}getPersistedProperty(e){return this._memoryStorage.getProperty(e)}setPersistedProperty(e,t){return this._memoryStorage.setProperty(e,t)}fetch(e,t){return this.options.fetch?this.options.fetch(e,t):fetch(e,t)}getLibraryVersion(){return version}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}capture(e){"string"==typeof e&&this.logMsgIfDebug(()=>console.warn("Called capture() with a string as the first argument when an object was expected."));const{distinctId:t,event:r,properties:n,groups:i,sendFeatureFlags:s,timestamp:o,disableGeoip:a,uuid:c}=e,u=e=>{super.captureStateless(t,r,e,{timestamp:o,disableGeoip:a,uuid:c})
4809
+ },l=async(e,t,r)=>(await super.getFeatureFlagsStateless(e,t,void 0,void 0,r)).flags,d=Promise.resolve().then(async()=>{if(s)return await l(t,i,a);if("$feature_flag_called"===r)return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){const e={};for(const[t,r]of Object.entries(i||{}))e[t]=String(r);return await this.getAllFlags(t,{groups:e,disableGeoip:a,onlyEvaluateLocally:!0})}return{}}).then(e=>{const t={};if(e)for(const[r,n]of Object.entries(e))t[`$feature/${r}`]=n;const r=Object.keys(e||{}).filter(t=>!1!==e?.[t]).sort();return r.length>0&&(t.$active_feature_flags=r),t}).catch(()=>({})).then(e=>{u({...e,...n,$groups:i})});this.addPendingPromise(d)}async captureImmediate(e){"string"==typeof e&&this.logMsgIfDebug(()=>console.warn("Called capture() with a string as the first argument when an object was expected."));const{distinctId:t,event:r,properties:n,groups:i,sendFeatureFlags:s,timestamp:o,disableGeoip:a,uuid:c}=e,u=e=>super.captureStatelessImmediate(t,r,e,{timestamp:o,
4810
+ disableGeoip:a,uuid:c}),l=async(e,t,r)=>(await super.getFeatureFlagsStateless(e,t,void 0,void 0,r)).flags,d=Promise.resolve().then(async()=>{if(s)return await l(t,i,a);if("$feature_flag_called"===r)return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){const e={};for(const[t,r]of Object.entries(i||{}))e[t]=String(r);return await this.getAllFlags(t,{groups:e,disableGeoip:a,onlyEvaluateLocally:!0})}return{}}).then(e=>{const t={};if(e)for(const[r,n]of Object.entries(e))t[`$feature/${r}`]=n;const r=Object.keys(e||{}).filter(t=>!1!==e?.[t]).sort();return r.length>0&&(t.$active_feature_flags=r),t}).catch(()=>({})).then(e=>{u({...e,...n,$groups:i})});await d}identify({distinctId:e,properties:t,disableGeoip:r}){const n=t?.$set_once;delete t?.$set_once;const i=t?.$set||t;super.identifyStateless(e,{$set:i,$set_once:n},{disableGeoip:r})}async identifyImmediate({distinctId:e,properties:t,disableGeoip:r}){const n=t?.$set_once;delete t?.$set_once;const i=t?.$set||t
4811
+ ;await super.identifyStatelessImmediate(e,{$set:i,$set_once:n},{disableGeoip:r})}alias(e){super.aliasStateless(e.alias,e.distinctId,void 0,{disableGeoip:e.disableGeoip})}async aliasImmediate(e){await super.aliasStatelessImmediate(e.alias,e.distinctId,void 0,{disableGeoip:e.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(e=THIRTY_SECONDS){return!!this.isLocalEvaluationReady()||void 0!==this.featureFlagsPoller&&new Promise(t=>{const r=setTimeout(()=>{n(),t(!1)},e),n=this._events.on("localEvaluationFlagsLoaded",e=>{clearTimeout(r),n(),t(e>0)})})}async getFeatureFlag(e,t,r){const{groups:n,disableGeoip:i}=r||{};let{onlyEvaluateLocally:s,sendFeatureFlagEvents:o,personProperties:a,groupProperties:c}=r||{};const u=this.addLocalPersonAndGroupProperties(t,n,a,c);a=u.allPersonProperties,c=u.allGroupProperties,null==s&&(s=!1),null==o&&(o=!0);let l=await(this.featureFlagsPoller?.getFeatureFlag(e,t,n,a,c))
4812
+ ;const d=void 0!==l;let p,h;if(!d&&!s){const r=await super.getFeatureFlagDetailStateless(e,t,n,a,c,i);if(void 0===r)return;h=r.response,l=getFeatureFlagValue(h),p=r?.requestId}const A=`${e}_${l}`;return!o||t in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[t].includes(A)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[t])?this.distinctIdHasSentFlagCalls[t].push(A):this.distinctIdHasSentFlagCalls[t]=[A],this.capture({distinctId:t,event:"$feature_flag_called",properties:{$feature_flag:e,$feature_flag_response:l,$feature_flag_id:h?.metadata?.id,$feature_flag_version:h?.metadata?.version,$feature_flag_reason:h?.reason?.description??h?.reason?.code,locally_evaluated:d,[`$feature/${e}`]:l,$feature_flag_request_id:p},groups:n,disableGeoip:i})),l}async getFeatureFlagPayload(e,t,r,n){const{groups:i,disableGeoip:s}=n||{}
4813
+ ;let{onlyEvaluateLocally:o,sendFeatureFlagEvents:a,personProperties:c,groupProperties:u}=n||{};const l=this.addLocalPersonAndGroupProperties(t,i,c,u);let d;c=l.allPersonProperties,u=l.allGroupProperties;void 0!==this.featureFlagsPoller&&(r||(r=await this.getFeatureFlag(e,t,{...n,onlyEvaluateLocally:!0,sendFeatureFlagEvents:!1})),r&&(d=await(this.featureFlagsPoller?.computeFeatureFlagPayloadLocally(e,r)))),null==o&&(o=!1),null==a&&(a=!0),null==o&&(o=!1);return void 0!==d||o||(d=await super.getFeatureFlagPayloadStateless(e,t,i,c,u,s)),d}async getRemoteConfigPayload(e){if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");const t=await this._requestRemoteConfigPayload(e);if(!t)return;const r=await t.json();if("string"==typeof r)try{return JSON.parse(r)}catch(e){return r}return r}async isFeatureEnabled(e,t,r){const n=await this.getFeatureFlag(e,t,r);if(void 0!==n)return!!n||!1}async getAllFlags(e,t){
4814
+ return(await this.getAllFlagsAndPayloads(e,t)).featureFlags||{}}async getAllFlagsAndPayloads(e,t){const{groups:r,disableGeoip:n}=t||{};let{onlyEvaluateLocally:i,personProperties:s,groupProperties:o}=t||{};const a=this.addLocalPersonAndGroupProperties(e,r,s,o);s=a.allPersonProperties,o=a.allGroupProperties,null==i&&(i=!1);const c=await(this.featureFlagsPoller?.getAllFlagsAndPayloads(e,r,s,o));let u={},l={},d=!0;if(c&&(u=c.response,l=c.payloads,d=c.fallbackToFlags),d&&!i){const t=await super.getFeatureFlagsAndPayloadsStateless(e,r,s,o,n);u={...u,...t.flags||{}},l={...l,...t.payloads||{}}}return{featureFlags:u,featureFlagPayloads:l}}groupIdentify({groupType:e,groupKey:t,properties:r,distinctId:n,disableGeoip:i}){super.groupIdentifyStateless(e,t,r,{disableGeoip:i},n)}async reloadFeatureFlags(){await(this.featureFlagsPoller?.loadFeatureFlags(!0))}async _shutdown(e){return this.featureFlagsPoller?.stopPoller(),super._shutdown(e)}async _requestRemoteConfigPayload(e){
4815
+ if(!this.options.personalApiKey)return;const t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config/`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}};let n=null;if(this.options.requestTimeout&&"number"==typeof this.options.requestTimeout){const e=new AbortController;n=safeSetTimeout(()=>{e.abort()},this.options.requestTimeout),r.signal=e.signal}try{return await this.fetch(t,r)}catch(e){return void this._events.emit("error",e)}finally{n&&clearTimeout(n)}}addLocalPersonAndGroupProperties(e,t,r,n){const i={distinct_id:e,...r||{}},s={};if(t)for(const e of Object.keys(t))s[e]={$group_key:t[e],...n?.[e]||{}};return{allPersonProperties:i,allGroupProperties:s}}captureException(e,t,r){const n=new Error("PostHog syntheticException");ErrorTracking.buildEventMessage(e,{syntheticException:n},t,r).then(e=>{this.capture(e)})}async captureExceptionImmediate(e,t,r){
4816
+ const n=new Error("PostHog syntheticException"),i=await ErrorTracking.buildEventMessage(e,{syntheticException:n},t,r);return await this.captureImmediate(i)}}const WEBPACK_ERROR_REGEXP=/\(error: (.*)\)/,STACKTRACE_FRAME_LIMIT=50,UNKNOWN_FUNCTION="?";function node(e){const t=/^\s*[-]{4,}$/,r=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;return n=>{const i=n.match(r);if(i){let t,r,n,s,o;if(i[1]){n=i[1];let e=n.lastIndexOf(".");if("."===n[e-1]&&e--,e>0){t=n.slice(0,e),r=n.slice(e+1);const i=t.indexOf(".Module");i>0&&(n=n.slice(i+1),t=t.slice(0,i))}s=void 0}r&&(s=t,o=r),"<anonymous>"===r&&(o=void 0,n=void 0),void 0===n&&(o=o||UNKNOWN_FUNCTION,n=s?`${s}.${o}`:o);let a=i[2]?.startsWith("file://")?i[2].slice(7):i[2];const c="native"===i[5];return a?.match(/\/[A-Z]:/)&&(a=a.slice(1)),a||!i[5]||c||(a=i[5]),{filename:a?decodeURI(a):void 0,module:e?e(a):void 0,function:n,lineno:_parseIntOrUndefined(i[3]),colno:_parseIntOrUndefined(i[4]),in_app:filenameIsInApp(a||"",c),
4817
+ platform:"node:javascript"}}if(n.match(t))return{filename:n,platform:"node:javascript"}}}function filenameIsInApp(e,t=!1){return!(t||e&&!e.startsWith("/")&&!e.match(/^[A-Z]:/)&&!e.startsWith(".")&&!e.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&void 0!==e&&!e.includes("node_modules/")}function _parseIntOrUndefined(e){return parseInt(e||"",10)||void 0}function nodeStackLineParser(e){return[90,node(e)]}function createStackParser(e){const t=[nodeStackLineParser(e)].sort((e,t)=>e[0]-t[0]).map(e=>e[1]);return(e,r=0)=>{const n=[],i=e.split("\n");for(let e=r;e<i.length;e++){const r=i[e];if(r.length>1024)continue;const s=WEBPACK_ERROR_REGEXP.test(r)?r.replace(WEBPACK_ERROR_REGEXP,"$1"):r;if(!s.match(/\S*Error: /)){for(const e of t){const t=e(s);if(t){n.push(t);break}}if(n.length>=STACKTRACE_FRAME_LIMIT)break}}return reverseAndStripFrames(n)}}function reverseAndStripFrames(e){if(!e.length)return[];const t=Array.from(e);return t.reverse(),t.slice(0,STACKTRACE_FRAME_LIMIT).map(e=>({...e,
4818
+ filename:e.filename||getLastStackFrame(t).filename,function:e.function||UNKNOWN_FUNCTION}))}function getLastStackFrame(e){return e[e.length-1]||{}}ErrorTracking.stackParser=createStackParser(createGetModuleFromFilename()),ErrorTracking.frameModifiers=[addSourceContext];class PostHog extends PostHogBackendClient{getLibraryId(){return"posthog-node"}}function _nullishCoalesce$1(e,t){return null!=e?e:t()}async function _asyncNullishCoalesce$1(e,t){return null!=e?e:await t()}function wrapLoggerWithEmitter(e,t,r){function n(r,n,i){return e.emit("log",{context:n,message:i,level:r}),t[r](n,i)}return{trace:(e,t)=>n("trace",{...r,...e},t),debug:(e,t)=>n("debug",{...r,...e},t),info:(e,t)=>n("info",{...r,...e},t),warn:(e,t)=>n("warn",{...r,...e},t),error:(e,t)=>n("error",{...r,...e},t),child(n){const i=t.child(n);return wrapLoggerWithEmitter(e,i,{...r,...n})},originalLogger:t}}async function constructLogger(e,t){
4819
+ const r=[],n=validateBaseEnv(process.env),i=process.argv.includes("mcp"),s=i?"mcp":"cli";isInteractive$1()||i||r.push({target:"pino/file",options:{destination:2}});const o=new EventEmitter,a=_nullishCoalesce$1(n.TESSL_LOG_LEVEL,()=>"info"),c=Math.min(_nullishCoalesce$1(levels.values[a],()=>30),_nullishCoalesce$1(levels.values.info,()=>30)),u=_nullishCoalesce$1(levels.labels[c],()=>"info");if(a&&"silent"!==a&&""!==n.TESSL_LOG_FILE){const e=n.TESSL_LOG_FILE?path$7.resolve(n.TESSL_LOG_FILE):path$7.join(getProjectCacheDir(),"tessl.log");r.push({target:"pino/file",level:a,options:{destination:e,mkdir:!0}})}const l=!t||await _asyncNullishCoalesce$1(await t.get("shareUsageData"),async()=>!0);"true"!==process.env.OTEL_SDK_DISABLED&&l&&r.push({target:"pino-opentelemetry-transport",options:{},level:"info"});const d=wrapLoggerWithEmitter(o,pino({name:e,level:u,transport:{targets:r}}),{context:s});return t&&t.setLogger(d),{logBus:o,logger:d}}function _optionalChain$1(e){let t,r=e[0],n=1
4820
+ ;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function quietLangfuse(e){const t={...e};_optionalChain$1([e,"optionalAccess",e=>e.secretKey])||void 0!==process.env.LANGFUSE_SECRET_KEY||(t.enabled=!1,t.publicKey="disabled",t.secretKey="disabled");const r=new Langfuse(t);return"yes"===process.env.TESSL_DEBUG_MONITORING&&r.debug(),r}function _nullishCoalesce(e,t){return null!=e?e:t()}const CLI_PROJECT_GROUP_TYPE="CLI Project";class PosthogAnalytics{__init(){this.toolSessionMap=new Map}constructor(e,t,r,n){PosthogAnalytics.prototype.__init.call(this),this.posthog=e,this.distinctId=t,this.projectCache=n,this.runId=null,this.sessionId="",this.shareUsageData=r,this.cliVersion="unknown",this.osType="unknown",this.osRelease="unknown",this.nodeVersion="unknown",
4821
+ this.platformInfo=_nullishCoalesce(platform$1(),()=>"unknown"),this.archInfo=_nullishCoalesce(arch(),()=>"unknown"),this.projectId=""}async initialize(){this.projectId=await getCurrentProjectId(this.projectCache,this.distinctId);const e=getSysinfo();this.cliVersion=_nullishCoalesce(e.version,()=>"unknown"),this.osType=_nullishCoalesce(e.osImplementation,()=>"unknown"),this.osRelease=_nullishCoalesce(e.osRelease,()=>"unknown"),this.nodeVersion=_nullishCoalesce(e.nodeVersion,()=>"unknown");const t=await SessionManager.getCliSessionInfo();this.sessionId=t.sessionId}static async create(e,t,r,n){const i=new PosthogAnalytics(e,t,r,n);return await i.initialize(),i}captureEvent(e,t){this.runId||(this.runId=v4()),this.captureEventBase(e,{source:"cli",runId:this.runId,sessionId:this.sessionId,...t})}captureEventBase(e,t){if(!this.shareUsageData)return;const r={...t,source:"cli",cliVersion:this.cliVersion,osType:this.osType,osRelease:this.osRelease,nodeVersion:this.nodeVersion,
4822
+ platform:this.platformInfo,arch:this.archInfo,timestamp:(new Date).toISOString()};this.posthog.capture({distinctId:this.distinctId,event:e,properties:r,groups:{[CLI_PROJECT_GROUP_TYPE]:this.projectId}})}capture(e,t){this.captureEvent(e,t)}async refreshCliSession(){const e=await SessionManager.getCliSessionInfo();this.sessionId=e.sessionId}mcpServerStart(){this.captureEvent("cli:mcp:server:start",{})}mcpServerEnd(e){this.captureEvent("cli:mcp:server:end",{...e})}async mcpToolStart(e){const t=await SessionManager.getMcpToolInfo();await this.refreshCliSession();const r={...e,runId:t.runId,sessionId:t.sessionId,parentRunId:t.parentRunId};return this.captureEventBase("cli:mcp:tool:start",r),t.runId}mcpToolEnd(e){this.captureEventBase("cli:mcp:tool:end",e)}cliStart(e){this.runId=v4(),this.captureEvent("cli:start",e)}runCommand(e,t){this.captureEvent("cli:run",{commandName:e,...t})}getDistinctId(){return this.distinctId}getRunId(){return this.runId}getSessionId(){return this.sessionId}
4823
+ getProjectId(){return this.projectId}runTool(e,t,r){const n=String(e);this.captureEvent("cli:run",{commandName:"tool",toolName:n,params:t,...r})}toolStart(e){const t=`${e.toolName}:${this.runId}`;this.toolSessionMap.set(t,this.sessionId),this.captureEvent("cli:tool:start",e)}toolEnd(e){const t=`${e.toolName}:${this.runId}`,r=this.toolSessionMap.get(t);if(r){const n={...e,originalSessionId:r};this.captureEventBase("cli:tool:end",{source:"cli",runId:this.runId,sessionId:r,...n,timestamp:(new Date).toISOString()}),this.toolSessionMap.delete(t)}else this.captureEvent("cli:tool:end",e)}cliEnd(e){this.captureEvent("cli:end",e),this.runId=null}cliError(e){this.captureEvent("cli:error",e)}runHelp(e){this.captureEvent("cli:run",{commandName:"help",...e})}tileSearch(e){this.captureEvent("cli:tile:search",e)}tileInstall(e){this.captureEvent("cli:tile:install",e)}registrySync(e){this.captureEvent("cli:registry:sync",e)}runVersion(e){this.captureEvent("cli:run",{commandName:"version",...e})}
4824
+ init(e){this.captureEvent("cli:project:init",e)}agentSetup(e){this.captureEvent("cli:agent:setup",e)}frameworkSetup(e){this.captureEvent("cli:framework:setup",e)}mcpSetup(e){this.captureEvent("cli:mcp:setup",e)}trackProjectGroup(e){this.shareUsageData&&this.posthog.groupIdentify({groupType:CLI_PROJECT_GROUP_TYPE,groupKey:e.projectId,properties:{isInitialized:e.isInitialized,$group_set_once:{firstSeenAt:e.firstSeenAt},lastEditedAt:(new Date).toISOString(),nodeVersion:this.nodeVersion,platform:this.platformInfo,arch:this.archInfo,cliVersion:this.cliVersion,osType:this.osType,osRelease:this.osRelease}})}projectMetadata(e){this.captureEventBase("cli:project:metadata",e)}trackProject(e){const t={projectId:this.projectId,distinctId:this.distinctId,...e,nodeVersion:this.nodeVersion,platform:this.platformInfo,arch:this.archInfo,cliVersion:this.cliVersion,osType:this.osType,osRelease:this.osRelease,firstSeenAt:(new Date).toISOString(),lastEditedAt:(new Date).toISOString()}
4825
+ ;this.trackProjectGroup(t),this.projectMetadata(t)}}async function createPosthogAnalytics(e,t,r,n){return PosthogAnalytics.create(e,t,r,n)}async function _asyncNullishCoalesce(e,t){return null!=e?e:await t()}function _optionalChain(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}async function startMonitoring(e){const t=getProvisionedEnvPath("production");if(fs__default.existsSync(t))try{validateEnv(cliMonitoringSchema,process.env)}catch(e){e instanceof Error?console.error(formatValidationError(e)):console.error("Failed to validate environment variables: please review the install instructions."),process.exit(FAILURE)}
4826
+ const r=getDefaultGlobalConfigDir(),n=new ConfigManager(join(r,GLOBAL_CONFIG_FILE_NAME),GlobalConfigSchema),{logger:i,logBus:s}=await constructLogger("cli",n),o=await _asyncNullishCoalesce(await n.get("shareUsageData"),async()=>!0);let a,c;try{a=(await readAuth(r)).user}catch(e){i.debug({err:e},"failed to read auth")}if(o&&process.env.LANGFUSE_PROXY_TOKEN){const[e,t]=process.env.LANGFUSE_PROXY_TOKEN.split(":");c=quietLangfuse({publicKey:e,secretKey:t,baseUrl:process.env.LANGFUSE_BASE_URL||"https://42957.tessl.io/",flushAt:1,flushInterval:0})}else c=quietLangfuse();const u=new PostHog("phc_S8tHJaPxa5ORnP0RVyyTaJHeCcft6XMqfjx9ZlJWvkO",{host:process.env.POSTHOG_HOST||"https://app.posthog.com"});"yes"===process.env.TESSL_DEBUG_MONITORING&&u.debug(!0);const l=userIdentifier(a);setOtelUser(a),u.identify({distinctId:l,properties:{...o?getSysinfo():{},email:a?a.email:void 0}}),a&&u.alias({distinctId:a.id,alias:loggedOutUserIdentifier()});const d=await createPosthogAnalytics(u,l,o,e);return{
4827
+ monitoring:{shareUsageData:o,user:a?{id:a.id,email:a.email}:void 0,langfuse:c,logger:i,logBus:s,reporter:new ReportEmitter,posthogCapture:(e,t)=>{(o||_optionalChain([t,"optionalAccess",e=>e.bypassOptOut]))&&u.capture({distinctId:l,event:e.event,properties:e.properties})},analytics:d,shutdown:async()=>{i.debug({},"Shutting down monitoring services");const e=async()=>new Promise((e,t)=>setTimeout(()=>t(new Error("Monitoring shutdown timed out")),2e3));try{await Promise.race([u.flush(),e()])}catch(e){i.error({err:e},"Failed to flush PostHog events")}try{await Promise.race([c.flushAsync(),e()]),i.debug({},"Successfully flushed Langfuse events")}catch(e){i.error({err:e},"Failed to flush Langfuse events")}try{await flushLogger(i.originalLogger),i.debug({},"Successfully flushed logger")}catch(e){}}},globalConfig:n}}async function entry(){if(!await checkLegal())return 145;initSysinfo();const e=await checkDeprecationStatusWithCache();if(e)return console.error(e.message),
4828
+ console.error(e.installUrl),DEPRECATED_EXIT_CODE;const t=sessionData(),r=projectCache(),{monitoring:n,globalConfig:i}=await startMonitoring(r);try{return await withSpan("cli.entry",async()=>main(n,i,t,r))}catch(e){return n.logger.error({err:e},"critical error during startup"),n.analytics.cliError({command:process.argv.slice(2).join(" "),message:e instanceof Error?e.message:String(e),stack:e instanceof Error&&e.stack||"",expected:e instanceof ExpectedError}),144}finally{await n.shutdown(),await sdk.shutdown(),showCursor()}}entry().then(e=>{process.exit(e)}).catch(e=>{console.error("Error occurred during exit:",e),process.exit(1)});const execAsync=require$$1$7.promisify(require$$0$8.exec);async function getMachineId$4(){try{const e=(await execAsync('ioreg -rd1 -c "IOPlatformExpertDevice"')).stdout.split("\n").find(e=>e.includes("IOPlatformUUID"));if(!e)return;const t=e.split('" = "');if(2===t.length)return t[1].slice(0,-1)}catch(e){diag.debug(`error reading machine id: ${e}`)}}
4829
+ var getMachineIdDarwin=Object.freeze({__proto__:null,getMachineId:getMachineId$4});async function getMachineId$3(){const e=["/etc/machine-id","/var/lib/dbus/machine-id"];for(const t of e)try{return(await promises.readFile(t,{encoding:"utf8"})).trim()}catch(e){diag.debug(`error reading machine id: ${e}`)}}var getMachineIdLinux=Object.freeze({__proto__:null,getMachineId:getMachineId$3});async function getMachineId$2(){try{return(await promises.readFile("/etc/hostid",{encoding:"utf8"})).trim()}catch(e){diag.debug(`error reading machine id: ${e}`)}try{return(await execAsync("kenv -q smbios.system.uuid")).stdout.trim()}catch(e){diag.debug(`error reading machine id: ${e}`)}}var getMachineIdBsd=Object.freeze({__proto__:null,getMachineId:getMachineId$2});async function getMachineId$1(){let e="%windir%\\System32\\REG.exe";"ia32"===process$4.arch&&"PROCESSOR_ARCHITEW6432"in process$4.env&&(e="%windir%\\sysnative\\cmd.exe /c "+e);try{
4830
+ const t=(await execAsync(`${e} QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid`)).stdout.split("REG_SZ");if(2===t.length)return t[1].trim()}catch(e){diag.debug(`error reading machine id: ${e}`)}}var getMachineIdWin=Object.freeze({__proto__:null,getMachineId:getMachineId$1});async function getMachineId(){diag.debug("could not read machine-id: unsupported platform")}var getMachineIdUnsupported=Object.freeze({__proto__:null,getMachineId});const getToJsonSchemaFn$4=async()=>e=>e.toJsonSchema();var arktypeCGObzDh=Object.freeze({__proto__:null,getToJsonSchemaFn:getToJsonSchemaFn$4});const getToJsonSchemaFn$3=async()=>{const{JSONSchema:e}=await tryImport(import("effect"),"effect");return t=>e.make(t)};var effect_Zg3C1LQ=Object.freeze({__proto__:null,getToJsonSchemaFn:getToJsonSchemaFn$3});const getToJsonSchemaFn$2=async()=>{const{toJSONSchema:e}=await tryImport(import("sury"),"sury");return t=>e(t)};var suryS6AklOc=Object.freeze({__proto__:null,
4831
+ getToJsonSchemaFn:getToJsonSchemaFn$2});const getToJsonSchemaFn$1=async()=>{const{toJsonSchema:e}=await tryImport(import("@valibot/to-json-schema"),"@valibot/to-json-schema");return t=>e(t)};var valibotDBCeetIe=Object.freeze({__proto__:null,getToJsonSchemaFn:getToJsonSchemaFn$1});const getToJsonSchemaFn=async()=>{let e=e=>{throw new Error(`xsschema: Missing zod v4 dependencies "zod". see ${missingDependenciesUrl}`)},t=e=>{throw new Error(`xsschema: Missing zod v3 dependencies "zod-to-json-schema". see ${missingDependenciesUrl}`)};try{const{toJSONSchema:t}=await Promise.resolve().then(function(){return index});e=t}catch(e){e instanceof Error&&console.error(e.message)}try{const{zodToJsonSchema:e}=await Promise.resolve().then(function(){return index$1});t=e}catch(e){e instanceof Error&&console.error(e.message)}return async r=>"_zod"in r?e(r):t(r)};var zodBw_60DVU=Object.freeze({__proto__:null,getToJsonSchemaFn});export{entry};